Skeleton contracts / contracts (pull_request) Blocked by required conditions
Брокер и Collector принимают только серийный номер текущего leaf. Прогон показывает rehash, 429 до дорогого Argon2, отказ stranger, ротацию пароля worker и сохранность задания.
170 lines
5.2 KiB
Python
170 lines
5.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Rehash and shared login budget. Prints parameters and timings only."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import socket
|
|
import ssl
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
PROBE = Path(__file__).resolve()
|
|
ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent
|
|
|
|
|
|
def https(method: str, path: str, body: bytes | None = None, headers: dict | None = None) -> tuple[int, str]:
|
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
ctx.load_verify_locations("/certs/ca.crt")
|
|
ctx.check_hostname = True
|
|
ctx.verify_mode = ssl.CERT_REQUIRED
|
|
raw = socket.create_connection(("host.docker.internal", 8443), timeout=10)
|
|
tls = ctx.wrap_socket(raw, server_hostname="localhost")
|
|
header_lines = ["%s %s HTTP/1.1" % (method, path), "Host: localhost", "Connection: close"]
|
|
for key, value in (headers or {}).items():
|
|
header_lines.append("%s: %s" % (key, value))
|
|
if body is not None:
|
|
header_lines.append("Content-Type: application/json")
|
|
header_lines.append("Content-Length: %s" % len(body))
|
|
payload = ("\r\n".join(header_lines) + "\r\n\r\n").encode("ascii")
|
|
if body is not None:
|
|
payload += body
|
|
tls.sendall(payload)
|
|
data = b""
|
|
while True:
|
|
chunk = tls.recv(8192)
|
|
if not chunk:
|
|
break
|
|
data += chunk
|
|
tls.close()
|
|
head, _, _rest = data.partition(b"\r\n\r\n")
|
|
text = head.decode("latin1", "replace")
|
|
status = int(text.split(" ", 2)[1])
|
|
return status, text
|
|
|
|
|
|
def internal() -> None:
|
|
import asyncio
|
|
|
|
from argon2 import PasswordHasher
|
|
|
|
from app import bao, db
|
|
|
|
username = "rehash_" + uuid.uuid4().hex[:10]
|
|
password = "synthetic-rehash-password"
|
|
status, _headers = https(
|
|
"POST",
|
|
"/api/v1/users",
|
|
json.dumps(
|
|
{"username": username, "display_name": "rehash probe", "password": password}
|
|
).encode("utf-8"),
|
|
)
|
|
if status != 201:
|
|
raise SystemExit("FAIL register %s" % status)
|
|
bao.apply()
|
|
|
|
async def memory_param() -> str:
|
|
pool = await db.connect()
|
|
try:
|
|
row = await pool.fetchrow(
|
|
"SELECT substring(password_hash from 'm=[0-9]+') AS param FROM users WHERE username = $1",
|
|
username,
|
|
)
|
|
finally:
|
|
await db.close()
|
|
return row["param"]
|
|
|
|
weak = PasswordHasher(memory_cost=8192, time_cost=1, parallelism=1, hash_len=32, salt_len=16).hash(password)
|
|
|
|
async def store_weak() -> None:
|
|
pool = await db.connect()
|
|
try:
|
|
await pool.execute(
|
|
"UPDATE users SET password_hash = $1 WHERE username = $2",
|
|
weak,
|
|
username,
|
|
)
|
|
finally:
|
|
await db.close()
|
|
|
|
asyncio.run(store_weak())
|
|
before = asyncio.run(memory_param())
|
|
print("rehash_before", before)
|
|
basic = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
|
started = time.perf_counter()
|
|
status, headers = https(
|
|
"POST",
|
|
"/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + basic},
|
|
)
|
|
login_ms = (time.perf_counter() - started) * 1000
|
|
if status != 201:
|
|
raise SystemExit("FAIL rehash login %s" % status)
|
|
after = asyncio.run(memory_param())
|
|
print("rehash_after", after, "login_ms=%.1f" % login_ms)
|
|
if before != "m=8192" or after != "m=19456":
|
|
raise SystemExit("FAIL rehash did not move to the floor")
|
|
|
|
wrong = base64.b64encode((username + ":wrong-password").encode("utf-8")).decode("ascii")
|
|
limited_status = None
|
|
for attempt in range(2, 12):
|
|
started = time.perf_counter()
|
|
status, headers = https(
|
|
"POST",
|
|
"/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + wrong},
|
|
)
|
|
elapsed = (time.perf_counter() - started) * 1000
|
|
if status == 429:
|
|
if "retry-after" not in headers.lower():
|
|
raise SystemExit("FAIL 429 without Retry-After")
|
|
print("rate_limit_attempt", attempt, "status", status, "elapsed_ms=%.1f" % elapsed)
|
|
limited_status = status
|
|
break
|
|
if status != 401:
|
|
raise SystemExit("FAIL unexpected login status %s" % status)
|
|
if attempt == 8:
|
|
print("argon2_reject_attempt", attempt, "elapsed_ms=%.1f" % elapsed)
|
|
if limited_status != 429:
|
|
raise SystemExit("FAIL shared rate limit did not return 429")
|
|
print("PASS rehash and shared login limit")
|
|
|
|
|
|
def main() -> None:
|
|
if "--internal" in sys.argv:
|
|
internal()
|
|
return
|
|
completed = subprocess.run(
|
|
[
|
|
"docker",
|
|
"compose",
|
|
"--env-file",
|
|
".env",
|
|
"run",
|
|
"--rm",
|
|
"--no-deps",
|
|
"--entrypoint",
|
|
"python",
|
|
"-e",
|
|
"PYTHONPATH=/app",
|
|
"-v",
|
|
"%s:/probe.py:ro" % PROBE,
|
|
"api",
|
|
"/probe.py",
|
|
"--internal",
|
|
],
|
|
cwd=ROOT,
|
|
check=False,
|
|
)
|
|
if completed.returncode != 0:
|
|
raise SystemExit(completed.returncode)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main() or 0)
|