#!/usr/bin/env python3 """lab7: проверки ВНЕШНЕЙ границы через HTTPS (с хоста, как клиент): TLS/hostname, ACL постороннего, подмена X-User-Id/X-Forwarded-For, logout/expiry, общий для реплик лимит входа (429 + Retry-After), ограничения размера запроса, Argon2id и rehash legacy hash, отсутствие утечек в ошибках. python3 student-tests/test_security.py # BASE_URL=https://127.0.0.1:8443, CA_FILE=secrets/tls/trust/ca.crt Для части проверок нужен SQL суперпользователя внутри контейнера (PSQL из common.py; только синтетика). """ import base64 import hashlib import http.client import json import os import secrets import socket import ssl import time import urllib.error import urllib.request from urllib.parse import urlsplit from common import (BASE_URL, CA_FILE, ROOT, TTL_BASE_URL, Client, Suite, basic, check, login, new_user, sql, upload, wait_status) c = Client(BASE_URL) s = Suite("lab7 external security (%s)" % BASE_URL) U = urlsplit(BASE_URL) FOREIGN_CA = str(ROOT / "secrets" / "test" / "foreign-ca.crt") def raw(method, path, headers=None, body=None): """Ответ без проверок публичного клиента (ответы самого LB не содержат X-Instance-Id).""" ctxt = ssl.create_default_context(cafile=CA_FILE) conn = http.client.HTTPSConnection(U.hostname, U.port, context=ctxt, timeout=10) try: conn.request(method, path, body=body, headers=headers or {}) r = conn.getresponse() return r.status, dict(r.getheaders()), r.read() finally: conn.close() def tls_connect(context, server_hostname=None, host=None, port=None): raw = socket.create_connection((host or U.hostname, port or U.port), timeout=5) try: return context.wrap_socket(raw, server_hostname=server_hostname or U.hostname) except BaseException: raw.close() raise @s.case("TLS: доверенный CA + hostname → 200; пустой/чужой trust store и чужое имя → ошибка ПРОВЕРКИ сертификата") def _(): c.call("GET", "/health/ready") out = [] for name, ctxf, host in ( ("empty trust store", lambda: ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), None), ("foreign CA", lambda: ssl.create_default_context(cafile=FOREIGN_CA), None), ("system CAs only", lambda: ssl.create_default_context(), None), ("wrong hostname", lambda: ssl.create_default_context(cafile=CA_FILE), "evil.example")): try: tls_connect(ctxf(), host).close() raise AssertionError(name + ": handshake succeeded") except ssl.SSLCertVerificationError as e: out.append("%s → %s" % (name, e.verify_message)) return "; ".join(out) @s.case("TLS: версии < 1.2 отклоняются; согласуется TLS 1.3/1.2; HSTS; plaintext на :8443 не обслуживается") def _(): old = ssl.create_default_context(cafile=CA_FILE) old.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED import warnings warnings.simplefilter("ignore", DeprecationWarning) old.maximum_version = ssl.TLSVersion.TLSv1_1 try: old.set_ciphers("ALL:@SECLEVEL=0") tls_connect(old).close() raise AssertionError("TLS 1.1 accepted") except ssl.SSLError as e: r11 = getattr(e, "reason", None) or type(e).__name__ t12 = ssl.create_default_context(cafile=CA_FILE) t12.maximum_version = ssl.TLSVersion.TLSv1_2 v12 = tls_connect(t12) v12_ver, v12_cipher = v12.version(), v12.cipher()[0] v12.close() v13 = tls_connect(ssl.create_default_context(cafile=CA_FILE)) ver = v13.version() v13.close() r = c.call("GET", "/health/live") hsts = r["headers"].get("Strict-Transport-Security") or r["headers"].get("strict-transport-security") check(hsts and "max-age=" in hsts, "no HSTS") conn = http.client.HTTPConnection(U.hostname, U.port, timeout=5) try: conn.request("GET", "/health/live") plain = conn.getresponse().status check(plain == 400, "plaintext HTTP on TLS port answered %s" % plain) except (http.client.RemoteDisconnected, ConnectionResetError) as e: plain = "closed (%s)" % type(e).__name__ closed = [] for port in (8080, 8081, 9000, 5432, 6379, 4222, 4318): try: socket.create_connection(("127.0.0.1", port), timeout=1).close() raise AssertionError("port %d is published on the host" % port) except OSError: closed.append(port) return "TLS1.1→%s; TLS1.2 ok (%s); default %s; HSTS=%s; plaintext→%s; host ports closed: %s" % ( r11, v12_cipher, ver, hsts, plain, closed) @s.case("ACL: посторонний не видит чат/сообщения/вложение (404); X-User-Id не меняет Bearer identity") def _(): alice, bob, eve = new_user(c, "sa"), new_user(c, "sb"), new_user(c, "se") for u in (alice, bob, eve): login(c, u) chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", body={"title": "sec", "member_ids": [alice["id"], bob["id"]]})["json"] c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=alice, body={"text": "секрет"}, headers={"Idempotency-Key": secrets.token_hex(8)}) att, _ = upload(c, alice, chat) wait_status(c, alice, att["id"], "ready") for path in ("/api/v1/chats/" + chat["id"], "/api/v1/chats/%s/messages" % chat["id"], "/api/v1/attachments/" + att["id"], "/api/v1/attachments/%s/content" % att["id"]): c.call("GET", path, 404, actor=eve) # eve прикрепляет чужой файл к сообщению в СВОЁМ чате → 404 (файл другого чата) own = c.call("POST", "/api/v1/chats", 201, actor=eve, schema="Chat", body={"title": "eve", "member_ids": [eve["id"]]})["json"] c.call("POST", "/api/v1/chats/%s/messages" % own["id"], 404, actor=eve, body={"text": "x", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": secrets.token_hex(8)}) me = c.call("GET", "/api/v1/users/me", 200, actor=eve, schema="User", headers={"X-User-Id": alice["id"]})["json"] check(me["id"] == eve["id"], "X-User-Id changed identity") c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]}) c.call("GET", "/api/v1/chats/" + chat["id"], 200, actor=bob) return "outsider 404 ×4, foreign attachment 404, X-User-Id ignored (me=eve), anonymous+X-User-Id 401" @s.case("logout отзывает сессию; истечение TTL (api-ttl, профиль ttl) → 401") def _(): u = new_user(c, "lo") login(c, u) c.call("GET", "/api/v1/users/me", 200, actor=u) c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=u) c.call("GET", "/api/v1/users/me", 401, actor=u) c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=u) try: t = Client(TTL_BASE_URL) t.call("GET", "/health/ready") except Exception: # noqa: BLE001 return "logout ok; api-ttl не запущен (expiry — student-tests/test_expiry.py с профилем ttl)" v = new_user(t, "ttl") login(t, v) t.call("GET", "/api/v1/users/me", 200, actor=v) time.sleep(3.0) t.call("GET", "/api/v1/users/me", 401, actor=v) return "logout → 401; TTL 2 s → 401 после истечения" def raw_login(username, password, extra_headers=None): h = {"Authorization": basic(username, password)} h.update(extra_headers or {}) r = c.call("POST", "/api/v1/auth/sessions", [201, 401, 429, 503], headers=h) return r["status"], r["headers"] @s.case("лимит входа ОБЩИЙ для реплик: 5 неудач (IP+username) → 429 + Retry-After, даже с верным паролем") def _(): u = new_user(c, "rl") seen, statuses = set(), [] for i in range(5): st, h = raw_login(u["username"], "wrong-password-%d" % i) statuses.append(st) seen.add(h.get("X-Instance-Id")) st, h = raw_login(u["username"], u["password"]) # верный пароль — уже поздно check(statuses == [401] * 5 and st == 429, "statuses %s then %s" % (statuses, st)) ra = int(h.get("Retry-After", "0")) check(1 <= ra <= 300, "Retry-After=%s" % h.get("Retry-After")) # Подмена X-Forwarded-For не обходит лимит (LB перезаписывает заголовок) st2, h2 = raw_login(u["username"], u["password"], {"X-Forwarded-For": "203.0.113.%d" % secrets.randbelow(250)}) check(st2 == 429, "XFF spoof bypassed the limit: %s" % st2) # Другой пользователь с того же IP не заблокирован (лимит по паре IP+username, а не глобальный) other = new_user(c, "rl2") st3, _ = raw_login(other["username"], other["password"]) check(st3 == 201, "other user blocked: %s" % st3) body = c.call("POST", "/api/v1/auth/sessions", 429, headers={"Authorization": basic(u["username"], u["password"])}) err = body["json"]["error"] check(err["code"] == "rate_limited" and u["password"] not in json.dumps(body["json"]), "error body") check(len(seen) >= 2, "401s came from one replica only (%s) — sharing not demonstrated" % seen) return "401×5 от реплик %s → 429 Retry-After=%ss (shared via Redis); XFF spoof → 429; другой user → 201" % ( sorted(x for x in seen if x), ra) @s.case("ограничения размера: JSON > 64 KiB → 413 (API), URI > 4 KiB → 414, > 64 заголовков → 400, заголовок > 16 KiB → 400 (LB)") def _(): u = new_user(c, "sz") login(c, u) auth = {"Authorization": "Bearer " + u["token"]} out = [] big = json.dumps({"title": "x" * 70000, "member_ids": [u["id"]]}).encode() r = c.call("POST", "/api/v1/chats", 413, actor=u, raw=big, headers={"Content-Type": "application/json"}) out.append("json 70 KB→%s %s" % (r["status"], r["json"]["error"]["code"])) st, h, b = raw("GET", "/api/v1/chats?cursor=" + "a" * 5000, auth) check(st == 414, "long URI: %s" % st) out.append("URI 5 KB→%s" % st) st, h, b = raw("GET", "/api/v1/users/me", dict(auth, **{"X-H%d" % i: "v" for i in range(70)})) check(st == 400, "70 headers: %s" % st) out.append("70 headers→%s" % st) try: st, h, b = raw("GET", "/api/v1/users/me", dict(auth, **{"X-Big": "v" * 20000})) check(st in (400, 431), "20 KB header: %s" % st) out.append("20 KB header→%s" % st) except (ConnectionError, http.client.HTTPException) as e: out.append("20 KB header→closed (%s)" % type(e).__name__) st, h, b = raw("POST", "/api/v1/chats/%s/attachments?filename=a.png" % u["id"], dict(auth, **{"Content-Type": "image/png", "Content-Length": str(50 * 2 ** 20)}), b"") check(st == 413, "50 MiB declared: %s" % st) out.append("upload Content-Length 50 MiB→413 (LB, до чтения тела)") return ", ".join(out) def scrypt_hash(password): salt = secrets.token_bytes(16) d = hashlib.scrypt(password.encode(), salt=salt, n=2 ** 15, r=8, p=3, maxmem=128 * 8 * 2 ** 15 * 2 + 3 * 2 ** 20, dklen=32) b = lambda x: base64.b64encode(x).decode().rstrip("=") # noqa: E731 return "$scrypt$ln=15,r=8,p=3$%s$%s" % (b(salt), b(d)) @s.case("Argon2id: соль+параметры в PHC; ≥ 19 MiB/t≥2/p=1; legacy scrypt и слабый Argon2id перехешируются при входе") def _(): u = new_user(c, "ar") h = sql("SELECT password_hash FROM users WHERE id = '%s'" % u["id"])[0] check(h.startswith("$argon2id$v=19$"), "not argon2id: %s" % h[:20]) params = dict(x.split("=") for x in h.split("$")[3].split(",")) m, t, p = int(params["m"]), int(params["t"]), int(params["p"]) check(m >= 19456 and t >= 2 and p == 1, "weak params %s" % params) # legacy: hash lab2–lab6 (scrypt) → вход → hash заменён текущим Argon2id legacy = new_user(c, "lg") sql("UPDATE users SET password_hash = '%s' WHERE id = '%s'" % (scrypt_hash(legacy["password"]), legacy["id"])) login(c, legacy) after = sql("SELECT password_hash FROM users WHERE id = '%s'" % legacy["id"])[0] check(after.startswith("$argon2id$v=19$m=%d,t=%d,p=%d$" % (m, t, p)), "scrypt not rehashed: %s" % after[:30]) out = ["current m=%d t=%d p=%d" % (m, t, p), "scrypt → argon2id ✓"] if t > 2: # слабее текущих (минимум OWASP t=2) → rehash до текущих from_ = h.replace("t=%d," % t, "t=2,") # параметры в строке не совпадают с hash → вход не пройдёт… weak = new_user(c, "wk") # …поэтому слабый hash считаем честно (если на хосте есть cryptography) — иначе пропускаем. try: from cryptography.hazmat.primitives.kdf.argon2 import Argon2id enc = Argon2id(salt=secrets.token_bytes(16), length=32, iterations=2, lanes=1, memory_cost=19456).derive_phc_encoded(weak["password"].encode()) sql("UPDATE users SET password_hash = '%s' WHERE id = '%s'" % (enc, weak["id"])) login(c, weak) w2 = sql("SELECT password_hash FROM users WHERE id = '%s'" % weak["id"])[0] check("t=%d" % t in w2, "weak argon2 not rehashed: %s" % w2[:40]) out.append("argon2id t=2 → t=%d ✓" % t) except ImportError: out.append("argon2id weak→strong: skipped (no cryptography on host)") del from_ return "; ".join(out) @s.case("ошибки не раскрывают credentials: 401 одинаков для неизвестного/неверного; нет Server/версий; пароль не эхо") def _(): u = new_user(c, "er") a = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(u["username"], "Wrong-pass-123")}) b = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("nouser_" + secrets.token_hex(4), "Wrong-pass-123")}) check(a["json"]["error"]["message"] == b["json"]["error"]["message"], "different 401 messages") check("Wrong-pass-123" not in json.dumps(a["json"]) and u["username"] not in json.dumps(a["json"]), "echo") srv = a["headers"].get("Server") or a["headers"].get("server") check(not srv, "Server header: %s" % srv) return "401 identical, no Server header, no credential echo" if __name__ == "__main__": s.run()