forked from mtusi2026/mtusi2026lab7
103 lines
4.1 KiB
Python
103 lines
4.1 KiB
Python
#!/usr/bin/env python3
|
|
"""lab7: бюджет login DoS — поток входов и влияние на остальные запросы.
|
|
|
|
python student-tests/security/login_flood.py --base-url https://localhost:8443 --ca-file secrets/pki/ca.crt
|
|
Фаза 1 (baseline): латентность GET /users/me с действительным токеном.
|
|
Фаза 2 (flood): --concurrency потоков шлют POST /auth/sessions со случайными username
|
|
(Argon2id verify «пустышки» на каждый запрос) в течение --duration; параллельно меряется
|
|
тот же GET /users/me. Итог: коды ответов потока (401/429/503), RPS попыток входа,
|
|
p50/p95 обычного запроса до/во время потока. Ожидание: общий rate limit по IP режет поток
|
|
(429) до KDF, семафор KDF ограничивает CPU/RAM, обычные запросы не деградируют кратно.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import collections
|
|
import http.client
|
|
import json
|
|
import ssl
|
|
import statistics
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from urllib.parse import urlparse
|
|
|
|
p = argparse.ArgumentParser()
|
|
p.add_argument("--base-url", default="https://localhost:8443")
|
|
p.add_argument("--ca-file", required=True)
|
|
p.add_argument("--duration", type=float, default=20)
|
|
p.add_argument("--concurrency", type=int, default=16)
|
|
a = p.parse_args()
|
|
U = urlparse(a.base_url)
|
|
CTX = ssl.create_default_context(cafile=a.ca_file)
|
|
|
|
|
|
def req(method, path, headers=None, body=None):
|
|
c = http.client.HTTPSConnection(U.hostname, U.port, context=CTX, timeout=30)
|
|
t0 = time.perf_counter()
|
|
try:
|
|
c.request(method, path, body=body, headers=headers or {})
|
|
r = c.getresponse()
|
|
data = r.read()
|
|
return r.status, (time.perf_counter() - t0) * 1000, data
|
|
except OSError:
|
|
return 0, (time.perf_counter() - t0) * 1000, b""
|
|
finally:
|
|
c.close()
|
|
|
|
|
|
def pct(xs, q):
|
|
xs = sorted(xs)
|
|
return xs[int(q * (len(xs) - 1))] if xs else float("nan")
|
|
|
|
|
|
user = "flood_" + uuid.uuid4().hex[:8]
|
|
pw = "flood-pw-" + uuid.uuid4().hex
|
|
req("POST", "/api/v1/users", {"Content-Type": "application/json"},
|
|
json.dumps({"username": user, "display_name": "F", "password": pw}))
|
|
s, _, data = req("POST", "/api/v1/auth/sessions",
|
|
{"Authorization": "Basic " + base64.b64encode(("%s:%s" % (user, pw)).encode()).decode()})
|
|
token = json.loads(data)["token"]
|
|
auth = {"Authorization": "Bearer " + token}
|
|
base = [req("GET", "/api/v1/users/me", auth)[1] for _ in range(30)]
|
|
stop = threading.Event()
|
|
codes = collections.Counter()
|
|
lock = threading.Lock()
|
|
probe = []
|
|
|
|
|
|
def flooder():
|
|
while not stop.is_set():
|
|
name = "nouser_" + uuid.uuid4().hex[:10]
|
|
s, _, _ = req("POST", "/api/v1/auth/sessions",
|
|
{"Authorization": "Basic " + base64.b64encode(("%s:wrong-password-1234" % name).encode()).decode()})
|
|
with lock:
|
|
codes[s] += 1
|
|
|
|
|
|
def prober():
|
|
while not stop.is_set():
|
|
s, ms, _ = req("GET", "/api/v1/users/me", auth)
|
|
probe.append((s, ms))
|
|
time.sleep(0.1)
|
|
|
|
|
|
threads = [threading.Thread(target=flooder) for _ in range(a.concurrency)] + [threading.Thread(target=prober)]
|
|
t0 = time.monotonic()
|
|
for t in threads:
|
|
t.start()
|
|
time.sleep(a.duration)
|
|
stop.set()
|
|
for t in threads:
|
|
t.join()
|
|
elapsed = time.monotonic() - t0
|
|
ok_probe = [ms for s, ms in probe if s == 200]
|
|
print(json.dumps({
|
|
"duration_s": round(elapsed, 1), "concurrency": a.concurrency,
|
|
"login_attempts": sum(codes.values()), "login_attempts_per_s": round(sum(codes.values()) / elapsed, 1),
|
|
"login_status_counts": dict(codes),
|
|
"baseline_users_me_ms": {"p50": round(statistics.median(base), 1), "p95": round(pct(base, 0.95), 1)},
|
|
"during_flood_users_me_ms": {"p50": round(statistics.median(ok_probe), 1) if ok_probe else None,
|
|
"p95": round(pct(ok_probe, 0.95), 1) if ok_probe else None,
|
|
"non_200": sum(1 for s, _ in probe if s != 200), "samples": len(probe)},
|
|
}, indent=2))
|