forked from mtusi2026/mtusi2026lab7
150 lines
7.6 KiB
Python
150 lines
7.6 KiB
Python
"""lab7: измеренный бюджет защиты от дорогостоящего login DoS.
|
||
|
||
python student-tests/login_dos.py [--seconds 20] [--attackers 16]
|
||
|
||
Фаза 1 (baseline): легитимный клиент — GET /users/me и POST message, p50/p95/p99.
|
||
Фаза 2 (атака): attackers потоков без пауз шлют вход с НЕВЕРНЫМ паролем по множеству разных существующих
|
||
username (обход лимита на username), с одного адреса — как ботнет за NAT; плюс тот же легитимный клиент.
|
||
Ожидаем: Argon2id не съедает реплику — одновременно не больше ARGON2_MAX_CONCURRENCY хешей на реплику,
|
||
лишние входы получают 503 + Retry-After сразу (нет очереди), затем общий лимит на IP даёт 429 до хеширования;
|
||
задержка легитимных запросов остаётся ограниченной. Итог — evidence/login-dos.json.
|
||
"""
|
||
import argparse
|
||
import json
|
||
import threading
|
||
import time
|
||
import uuid
|
||
from collections import Counter
|
||
|
||
from common import EVIDENCE, app_python, basic, new_chat, new_key, new_user, try_call
|
||
|
||
# Фаза 3: всплеск с МНОГИХ адресов (ботнет) — общий лимит по IP не помогает, держит бюджет реплики.
|
||
# Внутри одного контейнера api: N одновременных проверок пароля через auth.password_matches (тот же семафор,
|
||
# те же ARGON2_MAX_CONCURRENCY / ARGON2_QUEUE_SECONDS, что у запросов). Считаем, сколько получили 503 сразу,
|
||
# максимум одновременно идущих хешей и рост памяти процесса.
|
||
BURST = r'''
|
||
import json, resource, sys, threading, time
|
||
from concurrent.futures import ThreadPoolExecutor
|
||
import auth, settings
|
||
from errors import ApiError
|
||
n = int(sys.argv[1])
|
||
running = {"now": 0, "max": 0}
|
||
lock = threading.Lock()
|
||
class Counting: # обёртка над PasswordHasher: сколько verify идёт одновременно
|
||
def __init__(self, inner):
|
||
self.inner = inner
|
||
def verify(self, *a, **k):
|
||
with lock:
|
||
running["now"] += 1; running["max"] = max(running["max"], running["now"])
|
||
try:
|
||
return self.inner.verify(*a, **k)
|
||
finally:
|
||
with lock:
|
||
running["now"] -= 1
|
||
auth.hasher = Counting(auth.hasher)
|
||
rss_before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||
def one(_):
|
||
started = time.perf_counter()
|
||
try:
|
||
auth.password_matches(None, "Wrong-password-123")
|
||
return "hashed", time.perf_counter() - started
|
||
except ApiError as exc:
|
||
return f"rejected_{exc.status_code}", time.perf_counter() - started
|
||
t0 = time.perf_counter()
|
||
with ThreadPoolExecutor(max_workers=n) as pool:
|
||
results = list(pool.map(one, range(n)))
|
||
codes = {}
|
||
for code, _ in results:
|
||
codes[code] = codes.get(code, 0) + 1
|
||
slowest_rejection = max((t for c, t in results if c.startswith("rejected")), default=None)
|
||
print(json.dumps({"requests": n, "codes": codes, "max_parallel_hashes": running["max"],
|
||
"limit": settings.ARGON2_MAX_CONCURRENCY, "queue_s": settings.ARGON2_QUEUE_SECONDS,
|
||
"seconds": round(time.perf_counter() - t0, 2),
|
||
"slowest_rejection_s": round(slowest_rejection, 2) if slowest_rejection else None,
|
||
"maxrss_growth_mib": round((resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - rss_before) / 1024, 1)}))
|
||
'''
|
||
|
||
|
||
|
||
def percentile(values, q):
|
||
if not values:
|
||
return None
|
||
values = sorted(values)
|
||
return round(values[min(len(values) - 1, int(q * len(values)))] * 1000, 1)
|
||
|
||
|
||
def legit(user, chat, stop, latencies, codes):
|
||
while not stop.is_set():
|
||
for method, path, body, headers in (
|
||
("GET", "/api/v1/users/me", None, None),
|
||
("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "hi"}, {"Idempotency-Key": new_key()})):
|
||
started = time.perf_counter()
|
||
reply = try_call(method, path, token=user["token"], body=body, headers=headers, timeout=10)
|
||
latencies.append(time.perf_counter() - started)
|
||
codes[reply.status if reply else "conn_error"] += 1
|
||
time.sleep(0.02)
|
||
|
||
|
||
def attacker(usernames, stop, codes, latencies, offset):
|
||
i = offset
|
||
while not stop.is_set():
|
||
name = usernames[i % len(usernames)]
|
||
i += 1
|
||
started = time.perf_counter()
|
||
reply = try_call("POST", "/api/v1/auth/sessions", headers={"Authorization": basic(name, "Wrong-" + uuid.uuid4().hex)},
|
||
timeout=10)
|
||
latencies.append(time.perf_counter() - started)
|
||
codes[reply.status if reply else "conn_error"] += 1
|
||
|
||
|
||
def phase(seconds, user, chat, usernames=None, attackers=0):
|
||
stop = threading.Event()
|
||
legit_lat, legit_codes, attack_lat, attack_codes = [], Counter(), [], Counter()
|
||
threads = [threading.Thread(target=legit, args=(user, chat, stop, legit_lat, legit_codes))]
|
||
threads += [threading.Thread(target=attacker, args=(usernames, stop, attack_codes, attack_lat, n * 7))
|
||
for n in range(attackers)]
|
||
for t in threads:
|
||
t.start()
|
||
time.sleep(seconds)
|
||
stop.set()
|
||
for t in threads:
|
||
t.join()
|
||
return {"legit": {"requests": len(legit_lat), "codes": dict(legit_codes), "p50_ms": percentile(legit_lat, .5),
|
||
"p95_ms": percentile(legit_lat, .95), "p99_ms": percentile(legit_lat, .99)},
|
||
"attack": {"requests": len(attack_lat), "codes": dict(attack_codes),
|
||
"rps": round(len(attack_lat) / seconds, 1), "p50_ms": percentile(attack_lat, .5),
|
||
"p95_ms": percentile(attack_lat, .95)} if attackers else None}
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser()
|
||
parser.add_argument("--seconds", type=int, default=20)
|
||
parser.add_argument("--attackers", type=int, default=16)
|
||
args = parser.parse_args()
|
||
user = new_user("dos_legit")
|
||
chat = new_chat(user)
|
||
# жертвы: существующие username (неизвестный username тоже стоит один verify с DUMMY_HASH)
|
||
usernames = [new_user("dos_victim")["username"] for _ in range(40)]
|
||
print(f"baseline {args.seconds} s ...")
|
||
baseline = phase(args.seconds, user, chat)
|
||
print(json.dumps(baseline))
|
||
print(f"attack: {args.attackers} threads of wrong-password logins over {len(usernames)} usernames ...")
|
||
attack = phase(args.seconds, user, chat, usernames, args.attackers)
|
||
print(json.dumps(attack))
|
||
burst = json.loads(app_python(BURST, 200).splitlines()[-1])
|
||
print(f"burst of 200 simultaneous password checks in one api process: {json.dumps(burst)}")
|
||
data = {"baseline": baseline, "under_attack": attack, "seconds": args.seconds, "attackers": args.attackers,
|
||
"burst_one_replica": burst}
|
||
(EVIDENCE / "login-dos.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||
codes = attack["attack"]["codes"]
|
||
hashed = codes.get(401, 0)
|
||
print(f"attack: {attack['attack']['rps']} login attempts/s; 401 (hash computed) {hashed}, "
|
||
f"503 busy (rejected before hashing) {codes.get(503, 0)}, 429 rate limited {codes.get(429, 0)}")
|
||
print(f"legit p95: {baseline['legit']['p95_ms']} ms -> {attack['legit']['p95_ms']} ms; "
|
||
f"legit errors: { {k: v for k, v in attack['legit']['codes'].items() if k not in (200, 201)} }")
|
||
print("saved evidence/login-dos.json")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|