forked from mtusi2026/mtusi2026lab7
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия: - внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial; - TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL), Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA; - OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь; - роли БД, S3-политики и права брокера по принципу минимальных прав; - Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS; - hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия; - отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
158 lines
7.0 KiB
Python
158 lines
7.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Argon2id parameters and the login DoS budget, measured on the stand (level 3 + level 4).
|
|
|
|
bench inside api-1 (same CPU limit 0.5 core as production replicas): time and peak RSS of one hash for
|
|
several parameter sets -> justification of m=19 MiB, t=2, p=1
|
|
flood N concurrent attackers send wrong-password logins (distinct usernames, so per-user limits do not
|
|
help; the per-IP limit must be raised for this run to model a distributed attacker) while a probe
|
|
client sends normal requests; reports login throughput, 503 hash_busy share, API CPU/RSS and probe
|
|
latency vs. a baseline without the flood.
|
|
|
|
LOGIN_RATE_LIMIT_PER_IP=1000000 docker compose --env-file .env up -d --no-deps api-1 api-2 # experiment only
|
|
python3 student-tests/login_budget.py --output evidence/login_budget.json
|
|
docker compose --env-file .env up -d --no-deps api-1 api-2 # restore limits
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import http.client
|
|
import json
|
|
import ssl
|
|
import statistics
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
from stand import ROOT, Client, log
|
|
|
|
BENCH = r'''
|
|
import json, resource, time
|
|
from argon2 import PasswordHasher
|
|
out = []
|
|
for m, t, p in ((19456, 2, 1), (12288, 3, 1), (47104, 1, 1), (65536, 3, 1), (65536, 3, 4)):
|
|
h = PasswordHasher(time_cost=t, memory_cost=m, parallelism=p)
|
|
h.hash("warm-up-password")
|
|
times = []
|
|
for _ in range(10):
|
|
t0 = time.perf_counter(); h.hash("benchmark-password-123"); times.append((time.perf_counter() - t0) * 1000)
|
|
times.sort()
|
|
out.append({"m_kib": m, "t": t, "p": p, "p50_ms": round(times[5], 1), "max_ms": round(times[-1], 1),
|
|
"peak_rss_mib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1)})
|
|
print(json.dumps(out))
|
|
'''
|
|
|
|
|
|
def ctx():
|
|
return ssl.create_default_context(cafile=str(ROOT / "secrets/pki/ca.crt"))
|
|
|
|
|
|
def request(conn, method, path, headers, body=None):
|
|
conn.request(method, path, body=body, headers=headers)
|
|
r = conn.getresponse()
|
|
r.read()
|
|
return r.status
|
|
|
|
|
|
def cgroup_cpu():
|
|
"""CPU seconds of api-1 + api-2 from the Docker API (exact over a window)."""
|
|
host = subprocess.run(["docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}"],
|
|
capture_output=True, text=True).stdout.strip().replace("unix://", "")
|
|
total = 0.0
|
|
for name in ("mtusi-lab7-api-1-1", "mtusi-lab7-api-2-1"):
|
|
raw = subprocess.run(["curl", "-s", "--unix-socket", host,
|
|
"http://localhost/containers/%s/stats?stream=false&one-shot=true" % name],
|
|
capture_output=True, text=True).stdout
|
|
total += json.loads(raw)["cpu_stats"]["cpu_usage"]["total_usage"] / 1e9
|
|
return total
|
|
|
|
|
|
def max_rss():
|
|
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
|
|
capture_output=True, text=True).stdout
|
|
return {l.split()[0]: l.split()[1] for l in out.splitlines() if "api-" in l and "lab7" in l}
|
|
|
|
|
|
def probe(actor, chat, stop, lat):
|
|
conn = http.client.HTTPSConnection("localhost", 8443, context=ctx(), timeout=30)
|
|
headers = {"Authorization": "Bearer " + actor["token"], "Content-Type": "application/json"}
|
|
while not stop.is_set():
|
|
t0 = time.perf_counter()
|
|
try:
|
|
h = dict(headers, **{"Idempotency-Key": uuid.uuid4().hex})
|
|
status = request(conn, "POST", "/api/v1/chats/%s/messages" % chat["id"], h, b'{"text":"probe"}')
|
|
lat.append((time.perf_counter() - t0, status))
|
|
except (OSError, http.client.HTTPException):
|
|
conn = http.client.HTTPSConnection("localhost", 8443, context=ctx(), timeout=30)
|
|
time.sleep(0.2)
|
|
|
|
|
|
def attacker(stop, results):
|
|
conn = http.client.HTTPSConnection("localhost", 8443, context=ctx(), timeout=30)
|
|
while not stop.is_set():
|
|
name = "nouser_" + uuid.uuid4().hex[:12]
|
|
auth = base64.b64encode((name + ":wrong-password-123").encode()).decode()
|
|
t0 = time.perf_counter()
|
|
try:
|
|
status = request(conn, "POST", "/api/v1/auth/sessions", {"Authorization": "Basic " + auth})
|
|
except (OSError, http.client.HTTPException):
|
|
conn = http.client.HTTPSConnection("localhost", 8443, context=ctx(), timeout=30)
|
|
status = "conn_error"
|
|
results.append((time.perf_counter() - t0, status))
|
|
|
|
|
|
def phase(actor, chat, attackers, duration):
|
|
stop, lat, logins = threading.Event(), [], []
|
|
threads = [threading.Thread(target=probe, args=(actor, chat, stop, lat))]
|
|
threads += [threading.Thread(target=attacker, args=(stop, logins)) for _ in range(attackers)]
|
|
cpu0, t0 = cgroup_cpu(), time.time()
|
|
for t in threads:
|
|
t.start()
|
|
rss = []
|
|
while time.time() - t0 < duration:
|
|
time.sleep(5)
|
|
rss.append(max_rss())
|
|
stop.set()
|
|
for t in threads:
|
|
t.join(40)
|
|
elapsed = time.time() - t0
|
|
cpu = (cgroup_cpu() - cpu0) / elapsed * 100
|
|
ok = sorted(x for x, s in lat if s == 201)
|
|
codes = {}
|
|
for _, s in logins:
|
|
codes[str(s)] = codes.get(str(s), 0) + 1
|
|
login_lat = sorted(x for x, s in logins if s == 401)
|
|
pct = lambda v, q: round(v[min(len(v) - 1, int(q * len(v)))] * 1000, 1) if v else None # noqa: E731
|
|
return {"attackers": attackers, "seconds": round(elapsed), "login_attempts_per_s": round(len(logins) / elapsed, 1),
|
|
"login_status_counts": codes, "login_401_p50_ms": pct(login_lat, .5), "login_401_p99_ms": pct(login_lat, .99),
|
|
"probe_ok": len(ok), "probe_errors": sum(1 for _, s in lat if s != 201),
|
|
"probe_p50_ms": pct(ok, .5), "probe_p99_ms": pct(ok, .99),
|
|
"api_cpu_pct_of_one_core_both_replicas": round(cpu, 1), "api_rss_samples": rss[-1] if rss else {}}
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser()
|
|
p.add_argument("--duration", type=int, default=30)
|
|
p.add_argument("--attackers", type=int, default=32)
|
|
p.add_argument("--output", default=str(ROOT / "evidence/login_budget.json"))
|
|
a = p.parse_args()
|
|
bench = json.loads(subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "-c", BENCH], cwd=ROOT,
|
|
capture_output=True, text=True, check=True).stdout)
|
|
for row in bench:
|
|
log("argon2id m=%(m_kib)d KiB t=%(t)d p=%(p)d: p50 %(p50_ms)s ms, max %(max_ms)s ms, peak RSS %(peak_rss_mib)s MiB" % row)
|
|
c = Client()
|
|
alice, _bob, _eve, chat = c.bootstrap()
|
|
base = phase(alice, chat, 0, a.duration)
|
|
log("baseline: %s" % base)
|
|
flood = phase(alice, chat, a.attackers, a.duration)
|
|
log("flood: %s" % flood)
|
|
result = {"argon2_bench_api_container_0_5_cpu": bench, "baseline": base, "flood": flood,
|
|
"config": {"PASSWORD_HASH_CONCURRENCY_per_replica": 4, "PASSWORD_HASH_QUEUE_SECONDS": 3,
|
|
"replicas": 2, "api_cpu_limit": 0.5, "api_mem_limit_mib": 512}}
|
|
Path(a.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
|
print(json.dumps(result, ensure_ascii=False, indent=1))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|