"""lab7: защита на внешней границе и в API (через HTTPS-ingress, как обычный клиент). python student-tests/test_lab7_security.py [имя_теста ...] Каждый тест — отрицательная проверка конкретной угрозы из security/THREAT_MODEL.md. Пароли/токены тестов синтетические и не печатаются. """ import base64 import hashlib import json import socket import ssl import sys import urllib.parse import uuid import images from common import (BASE_URL, CA_FILE, PASSWORD, app_python, basic, call, check, login, new_chat, new_key, new_user, redis_cli, run_tests, sql_value, tls_socket, upload, PKI_DIR) URL = urllib.parse.urlsplit(BASE_URL) def raw_request(head: bytes, body: bytes = b"", read=4096) -> bytes: with tls_socket(timeout=10) as sock: sock.sendall(head + body) data = b"" try: while len(data) < read: chunk = sock.recv(4096) if not chunk: break data += chunk if b"\r\n\r\n" in data and (b"Content-Length: 0" in data or data.count(b"}") > 0): break except (socket.timeout, ssl.SSLError, ConnectionResetError): pass return data def test_https_only_and_certificate_checks(): # 1) HTTP на старом порту 8080: API там не отвечает (наружу опубликован только 8443) try: with socket.create_connection((URL.hostname, 8080), timeout=2) as sock: sock.sendall(b"GET /health/live HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n") data = sock.recv(400) check(b"x-instance-id" not in data.lower(), "the API answers plain HTTP on 8080") print("port 8080: something else answers locally, not the API") except OSError: print("port 8080: closed") # 2) открытый HTTP на HTTPS-порт — ответа в открытом виде нет with socket.create_connection((URL.hostname, URL.port), timeout=5) as sock: sock.sendall(b"GET /health/live HTTP/1.1\r\nHost: x\r\n\r\n") try: data = sock.recv(200) except OSError: data = b"" check(b'"status"' not in data, f"plaintext HTTP got an application answer: {data[:80]!r}") # 3) чужой CA и 4) неверное имя сервера — ошибка ПРОВЕРКИ сертификата, а не сети for name, context, server_name in ( ("empty trust store", ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), URL.hostname), ("foreign CA", ssl.create_default_context(cafile=str(PKI_DIR / "test" / "rogue-ca" / "ca.crt")), URL.hostname), ("wrong host name", ssl.create_default_context(cafile=CA_FILE), "evil.example")): context.check_hostname = True context.verify_mode = ssl.CERT_REQUIRED try: with socket.create_connection((URL.hostname, URL.port), timeout=5) as raw: context.wrap_socket(raw, server_hostname=server_name).close() check(False, f"{name}: handshake succeeded") except ssl.SSLCertVerificationError as exc: print(f"{name}: rejected by certificate verification ({exc.verify_message})") print("PASS: only HTTPS on 8443; untrusted CA and wrong host name fail certificate verification") def test_security_headers(): reply = call("GET", "/health/live", 200) check("max-age" in reply.headers.get("strict-transport-security", ""), "no HSTS") check(reply.headers.get("x-content-type-options") == "nosniff", "no nosniff") check("server" not in reply.headers, f"Server header reveals {reply.headers.get('server')}") check(len(reply.instance) == 12 and all(c in "0123456789abcdef" for c in reply.instance), "X-Instance-Id is not a random alias") print(f"HSTS, nosniff, no Server header; X-Instance-Id is an opaque alias ({reply.instance})") print("PASS: security headers") def test_outsider_cannot_reach_foreign_chat(): alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve") chat = new_chat(alice, bob) att = upload(alice, chat["id"], images.sample_png()).json eve_chat = new_chat(eve) spoof = {"X-User-Id": alice["id"]} # подделка идентичности заголовком — игнорируется probes = [ ("GET", f"/api/v1/chats/{chat['id']}", None), ("GET", f"/api/v1/chats/{chat['id']}/messages", None), ("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "intrusion"}), ("GET", f"/api/v1/attachments/{att['id']}", None), ("GET", f"/api/v1/attachments/{att['id']}/content", None), ("POST", f"/api/v1/chats/{eve_chat['id']}/messages", {"text": "", "attachment_ids": [att["id"]]}), ] for method, path, body in probes: headers = {**spoof, "Idempotency-Key": new_key()} if method == "POST" else spoof reply = call(method, path, 404, token=eve["token"], body=body, headers=headers) check(alice["id"] not in reply.data.decode(), "response mentions the victim") me = call("GET", "/api/v1/users/me", 200, token=eve["token"], headers=spoof).json check(me["id"] == eve["id"], "X-User-Id changed the identity") print(f"outsider: {len(probes)} attempts on a foreign chat/attachment -> 404 (existence not revealed); " "X-User-Id of the victim is ignored") print("PASS: ACL — outsider reads/writes nothing, cannot attach a foreign file") def test_logout_revokes_token(): user = new_user("logout") call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"]) reply = call("GET", "/api/v1/users/me", 401, token=user["token"]) check("Bearer" in reply.headers.get("www-authenticate", ""), "no Bearer challenge") call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"]) print("PASS: logout -> the same token is 401 on every replica (session deleted in shared Redis)") def test_login_rate_limit_is_shared(): user = new_user("ratelimit") seen, codes, retry_after = set(), [], None for attempt in range(14): reply = call("POST", "/api/v1/auth/sessions", (401, 429), headers={"Authorization": basic(user["username"], "Wrong-password-" + str(attempt))}) codes.append(reply.status) seen.add(reply.instance) if reply.status == 429: retry_after = reply.headers.get("retry-after") check(reply.json["error"]["code"] == "rate_limited", "wrong error code") # в new_user был 1 успешный вход: лимит 10 попыток на username за окно -> 401 x9, затем 429 check(codes[:9] == [401] * 9 and all(code == 429 for code in codes[9:]), f"unexpected codes {codes}") check(retry_after and retry_after.isdigit() and 1 <= int(retry_after) <= 60, f"Retry-After {retry_after}") check(len(seen) >= 2, f"all answers came from one replica {seen}: shared counter not shown") # даже верный пароль до конца окна — 429 (подбор не продолжить, сменив попытку на правильную) call("POST", "/api/v1/auth/sessions", 429, headers={"Authorization": basic(user["username"], PASSWORD)}) print(f"codes {codes}; answered by replicas {sorted(seen)}; Retry-After {retry_after} s") print("PASS: login rate limit is shared by all replicas (Redis), 429 + Retry-After, before Argon2id") def test_request_size_limits(): user = new_user("size") chat = new_chat(user) big = {"text": "x" * 70000} # > MAX_JSON_BYTES (64 KiB); text сам по себе тоже > 4000 символов reply = call("POST", f"/api/v1/chats/{chat['id']}/messages", 413, token=user["token"], body=big, headers={"Idempotency-Key": new_key()}) check(reply.json["error"]["code"] == "payload_too_large", "wrong code") # chunked без Content-Length: лимит считается по фактически полученным байтам body = json.dumps(big).encode() chunked = b"".join(b"%x\r\n%s\r\n" % (len(body[i:i + 8192]), body[i:i + 8192]) for i in range(0, len(body), 8192)) + b"0\r\n\r\n" head = (f"POST /api/v1/chats/{chat['id']}/messages HTTP/1.1\r\nHost: {URL.hostname}\r\n" f"Authorization: Bearer {user['token']}\r\nContent-Type: application/json\r\n" f"Idempotency-Key: {new_key()}\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n").encode() data = raw_request(head, chunked) check(data.startswith(b"HTTP/1.1 413"), f"chunked oversized JSON: {data[:60]!r}") # ingress отвергает заявленное тело больше 11 MiB ещё до API head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=a.png HTTP/1.1\r\nHost: {URL.hostname}\r\n" f"Authorization: Bearer {user['token']}\r\nContent-Type: image/png\r\n" f"Content-Length: 50000000\r\nConnection: close\r\n\r\n").encode() data = raw_request(head, b"") check(data.startswith(b"HTTP/1.1 413"), f"50 MB upload: {data[:60]!r}") print("JSON > 64 KiB -> 413 (with Content-Length and chunked); upload Content-Length 50 MB -> 413 at the LB") print("PASS: request size limits") def argon2_params(user_id): value = sql_value(f"SELECT password_hash FROM users WHERE id = '{user_id}'") parts = value.split("$") params = dict(item.split("=") for item in parts[3].split(",")) salt = base64.b64decode(parts[4] + "=" * (-len(parts[4]) % 4)) return parts[1], {k: int(v) for k, v in params.items()}, len(salt), value def test_password_storage_argon2id(): a = new_user("hash_a") b = new_user("hash_b") # тот же пароль kind_a, params_a, salt_len, hash_a = argon2_params(a["id"]) kind_b, _params_b, _salt_b, hash_b = argon2_params(b["id"]) check(kind_a == kind_b == "argon2id", f"not argon2id: {kind_a}") check(params_a["m"] >= 19456 and params_a["t"] >= 2 and params_a["p"] >= 1, f"weak params {params_a}") check(salt_len >= 16, f"salt {salt_len} bytes") check(hash_a != hash_b, "same password -> same hash (no salt)") check(PASSWORD not in hash_a, "password in the hash string") print(f"stored: $argon2id$v=19$m={params_a['m']},t={params_a['t']},p={params_a['p']}$<{salt_len}-byte salt>$;" " two users with the same password have different hashes") print("PASS: Argon2id with salt and parameters in the stored string") LEGACY_HASH = r''' import json, sys from argon2 import PasswordHasher # параметры lab2-6 этого решения: m=12 MiB, t=3, p=1 (ниже требования lab7 по памяти) print(json.dumps({"hash": PasswordHasher(time_cost=3, memory_cost=12 * 1024, parallelism=1).hash(sys.argv[1])})) ''' def test_rehash_on_login(): user = new_user("rehash") legacy = json.loads(app_python(LEGACY_HASH, user["password"]).splitlines()[-1])["hash"] sql_value(f"UPDATE users SET password_hash = '{legacy}' WHERE id = '{user['id']}' RETURNING 1") _kind, before, _salt, _h = argon2_params(user["id"]) check(before["m"] == 12288 and before["t"] == 3, f"legacy hash not installed: {before}") login(user["username"], user["password"]) _kind, after, _salt, stored = argon2_params(user["id"]) check(after["m"] >= 19456 and after != before, f"not rehashed: {after}") login(user["username"], user["password"]) print(f"legacy hash m={before['m']},t={before['t']} -> after successful login m={after['m']},t={after['t']}," f"p={after['p']}; the new hash still verifies") print("PASS: old password hash is upgraded on successful login") def test_errors_and_storage_do_not_reveal_credentials(): secret = "Leak-check-" + uuid.uuid4().hex username = "leak_" + uuid.uuid4().hex[:10] # неверное тело регистрации: ответ не повторяет пароль reply = call("POST", "/api/v1/users", 400, body={"username": username, "display_name": "x", "password": secret, "extra": 1}) check(secret not in reply.data.decode(), "400 echoes the password") call("POST", "/api/v1/users", 201, body={"username": username, "display_name": "Leak", "password": secret}) reply = call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(username, secret + "x")}) check(secret not in reply.data.decode() and username not in reply.data.decode(), "401 reveals input") token = login(username, secret).json["token"] keys = redis_cli("--scan", "--pattern", "'session:*'").split() check(f"session:{hashlib.sha256(token.encode()).hexdigest()}" in keys, "session key is not SHA-256 of the token") check(not any(token in key for key in keys), "plain token stored in Redis") check(sql_value(f"SELECT count(*) FROM users WHERE password_hash LIKE '%{secret}%'") == "0", "password in DB") print("errors do not echo credentials; Redis stores session: only; DB stores only the hash") print("PASS: credentials and session tokens are not revealed") if __name__ == "__main__": tests = [test_https_only_and_certificate_checks, test_security_headers, test_outsider_cannot_reach_foreign_chat, test_logout_revokes_token, test_login_rate_limit_is_shared, test_request_size_limits, test_password_storage_argon2id, test_rehash_on_login, test_errors_and_storage_do_not_reveal_credentials] selected = [t for t in tests if not sys.argv[1:] or t.__name__ in sys.argv[1:]] run_tests(selected)