forked from mtusi2026/mtusi2026lab7
197 lines
11 KiB
Python
197 lines
11 KiB
Python
#!/usr/bin/env python3
|
||
"""lab7: отрицательные проверки на внешнем HTTPS через LB (только стандартная библиотека).
|
||
|
||
python student-tests/security/security_http.py --base-url https://localhost:8443 --ca-file secrets/pki/ca.crt
|
||
|
||
ACL и вложения: посторонний (eve) не читает чат/историю/metadata/content вложения, не пишет
|
||
в чужой чат и не прикрепляет чужой файл к своему чату; X-User-Id не меняет Bearer identity;
|
||
Basic на бизнес-endpoint — 401; logout отзывает токен (повтор 401).
|
||
Вход: общий для реплик rate limit -> 429 + Retry-After (ответы от >= 2 реплик), даже верный
|
||
пароль во время блокировки; ошибки не раскрывают credentials/внутренние детали.
|
||
Лимиты: JSON > 64 KiB -> 413 (LB, по Content-Length), chunked > 64 KiB -> 413 (API),
|
||
загрузка > 10 MiB -> 413 (API). TLS: неверное имя сервера и пустой trust store -> ошибка
|
||
проверки сертификата; plaintext на HTTPS-порт не обслуживается. Grafana — HTTPS с паролем.
|
||
Истечение сессии: python scripts/ops.py in-network expiry (экземпляр с TTL 2 с).
|
||
"""
|
||
import argparse
|
||
import base64
|
||
import http.client
|
||
import json
|
||
import os
|
||
import socket
|
||
import ssl
|
||
import sys
|
||
import uuid
|
||
from pathlib import Path
|
||
from urllib.parse import urlparse
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
parser = argparse.ArgumentParser()
|
||
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "https://localhost:8443"))
|
||
parser.add_argument("--ca-file", default=os.environ.get("CA_FILE", str(ROOT / "secrets" / "pki" / "ca.crt")))
|
||
parser.add_argument("--grafana-url", default=os.environ.get("GRAFANA_URL", "https://127.0.0.1:3000"))
|
||
args = parser.parse_args()
|
||
U = urlparse(args.base_url)
|
||
CTX = ssl.create_default_context(cafile=args.ca_file)
|
||
RESULTS = []
|
||
|
||
|
||
def check(name, ok, detail=""):
|
||
ok = bool(ok)
|
||
RESULTS.append(ok)
|
||
print("%s %-70s %s" % ("PASS" if ok else "FAIL", name, str(detail)[:90]), flush=True)
|
||
|
||
|
||
def call(method, path, body=None, token=None, headers=None, raw=None, ctype="application/json", chunked=False):
|
||
h = {"Accept": "application/json"}
|
||
if token:
|
||
h["Authorization"] = "Bearer " + token
|
||
data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None)
|
||
if data is not None:
|
||
h["Content-Type"] = ctype
|
||
h.update(headers or {})
|
||
conn = http.client.HTTPSConnection(U.hostname, U.port or 443, context=CTX, timeout=60)
|
||
try:
|
||
if chunked:
|
||
conn.putrequest(method, path)
|
||
for k, v in dict(h, **{"Transfer-Encoding": "chunked"}).items():
|
||
conn.putheader(k, v)
|
||
conn.endheaders()
|
||
conn.send(b"%x\r\n%s\r\n0\r\n\r\n" % (len(data), data))
|
||
else:
|
||
conn.request(method, path, body=data, headers=h)
|
||
r = conn.getresponse()
|
||
payload = r.read()
|
||
try:
|
||
js = json.loads(payload) if payload else None
|
||
except ValueError:
|
||
js = None
|
||
return r.status, js, {k.lower(): v for k, v in r.getheaders()}, payload
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def basic(user, pw):
|
||
return {"Authorization": "Basic " + base64.b64encode(("%s:%s" % (user, pw)).encode()).decode()}
|
||
|
||
|
||
def actor(prefix):
|
||
username = "%s_%s" % (prefix, uuid.uuid4().hex[:10])
|
||
pw = "pw-" + uuid.uuid4().hex
|
||
s, user, _, _ = call("POST", "/api/v1/users", {"username": username, "display_name": prefix, "password": pw})
|
||
assert s == 201, s
|
||
s, sess, _, _ = call("POST", "/api/v1/auth/sessions", headers=basic(username, pw))
|
||
assert s == 201, s
|
||
return {"id": user["id"], "username": username, "pw": pw, "token": sess["token"]}
|
||
|
||
|
||
def main():
|
||
alice, bob, eve = actor("alice"), actor("bob"), actor("eve")
|
||
s, chat, _, _ = call("POST", "/api/v1/chats", {"title": "secret", "member_ids": [alice["id"], bob["id"]]},
|
||
token=alice["token"])
|
||
png = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||
s, att, _, _ = call("POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], raw=png,
|
||
token=alice["token"], ctype="image/png")
|
||
check("setup: chat + attachment", s == 202 and att and att.get("id"), s)
|
||
cid, aid = chat["id"], att["id"]
|
||
# ---------------- ACL
|
||
for method, path, body in (("GET", "/api/v1/chats/%s" % cid, None),
|
||
("GET", "/api/v1/chats/%s/messages" % cid, None),
|
||
("POST", "/api/v1/chats/%s/messages" % cid, {"text": "intrusion"}),
|
||
("GET", "/api/v1/attachments/%s" % aid, None),
|
||
("GET", "/api/v1/attachments/%s/content" % aid, None)):
|
||
s, js, _, _ = call(method, path, body, token=eve["token"], headers={"Idempotency-Key": uuid.uuid4().hex})
|
||
check("outsider %s %s -> 404 (no existence leak)" % (method, path.replace(cid, "{chat}").replace(aid, "{att}")),
|
||
s == 404 and js["error"]["code"] == "not_found", s)
|
||
s, own, _, _ = call("POST", "/api/v1/chats", {"title": "eve", "member_ids": [eve["id"]]}, token=eve["token"])
|
||
s, js, _, _ = call("POST", "/api/v1/chats/%s/messages" % own["id"], {"text": "", "attachment_ids": [aid]},
|
||
token=eve["token"], headers={"Idempotency-Key": uuid.uuid4().hex})
|
||
check("outsider attaches foreign attachment to own chat -> 404", s == 404, s)
|
||
s, me, _, _ = call("GET", "/api/v1/users/me", token=eve["token"], headers={"X-User-Id": alice["id"]})
|
||
check("X-User-Id cannot override Bearer identity", s == 200 and me["id"] == eve["id"], me and me.get("username"))
|
||
s, _, h, _ = call("GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]})
|
||
check("X-User-Id alone -> 401 + WWW-Authenticate Bearer", s == 401 and h.get("www-authenticate", "").startswith(
|
||
"Bearer"), h.get("www-authenticate"))
|
||
s, _, _, _ = call("GET", "/api/v1/chats", headers=basic(alice["username"], alice["pw"]))
|
||
check("Basic on business endpoint -> 401", s == 401, s)
|
||
s, _, _, _ = call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||
check("unknown/forged token -> 401", s == 401, s)
|
||
# ---------------- logout
|
||
s, _, _, _ = call("DELETE", "/api/v1/auth/sessions/current", token=bob["token"])
|
||
s2, _, _, _ = call("GET", "/api/v1/users/me", token=bob["token"])
|
||
s3, _, _, _ = call("DELETE", "/api/v1/auth/sessions/current", token=bob["token"])
|
||
check("logout 204 -> token rejected 401 -> repeat logout 401", (s, s2, s3) == (204, 401, 401), (s, s2, s3))
|
||
# ---------------- ошибки не раскрывают credentials
|
||
s, js, h, raw = call("POST", "/api/v1/auth/sessions", headers=basic(alice["username"], "wrong-password-xyz"))
|
||
text = raw.decode("utf-8", "replace")
|
||
check("wrong password -> 401, body has no username/password/hash", s == 401 and alice["username"] not in text
|
||
and "wrong-password" not in text and "argon" not in text.lower(), text[:80])
|
||
s, js, _, raw = call("POST", "/api/v1/users", raw=b"{not json", ctype="application/json")
|
||
text = raw.decode("utf-8", "replace")
|
||
check("malformed JSON -> 400 without stack trace/SQL", s == 400 and "Traceback" not in text and "SELECT" not in text
|
||
and js["error"]["request_id"], text[:80])
|
||
# ---------------- rate limit входа (общий для реплик)
|
||
victim = actor("rl")
|
||
statuses, instances, retry = [], set(), None
|
||
for _ in range(12):
|
||
s, js, h, _ = call("POST", "/api/v1/auth/sessions", headers=basic(victim["username"], "wrong-" + uuid.uuid4().hex))
|
||
statuses.append(s)
|
||
instances.add(h.get("x-instance-id"))
|
||
if s == 429:
|
||
retry = h.get("retry-after")
|
||
code = js["error"]["code"]
|
||
check("login brute force -> 429 rate_limited + Retry-After", 429 in statuses and retry and retry.isdigit()
|
||
and code == "rate_limited", "%s Retry-After=%s" % (statuses, retry))
|
||
check("rate limit is shared: responses from >= 2 replicas", len(instances - {None}) >= 2, sorted(instances - {None}))
|
||
s, _, _, _ = call("POST", "/api/v1/auth/sessions", headers=basic(victim["username"], victim["pw"]))
|
||
check("correct password while locked out -> 429 (no oracle)", s == 429, s)
|
||
# ---------------- лимиты размера
|
||
big = json.dumps({"username": "x", "display_name": "y" * 70000, "password": "p" * 20}).encode()
|
||
s, js, h, _ = call("POST", "/api/v1/users", raw=big)
|
||
check("JSON body 70 KB -> 413 payload_too_large from LB (before any replica)",
|
||
s == 413 and js["error"]["code"] == "payload_too_large" and not h.get("x-instance-id"),
|
||
"instance=%s" % h.get("x-instance-id"))
|
||
s, js, h, _ = call("POST", "/api/v1/users", raw=big, chunked=True)
|
||
check("chunked JSON 70 KB -> 413 payload_too_large (API)", s == 413 and js["error"]["code"] == "payload_too_large",
|
||
"instance=%s" % h.get("x-instance-id"))
|
||
huge = png + b"\0" * (10 * 1024 * 1024 + 1 - len(png))
|
||
s, js, _, _ = call("POST", "/api/v1/chats/%s/attachments?filename=big.png" % cid, raw=huge, token=alice["token"],
|
||
ctype="image/png")
|
||
check("upload 10 MiB + 1 byte -> 413", s == 413, s)
|
||
# ---------------- TLS
|
||
try:
|
||
raw_sock = socket.create_connection((U.hostname, U.port or 443), timeout=5)
|
||
CTX.wrap_socket(raw_sock, server_hostname="evil.example")
|
||
check("wrong server name -> certificate verification error", False, "handshake succeeded")
|
||
except ssl.SSLCertVerificationError as exc:
|
||
check("wrong server name -> certificate verification error", True, exc.verify_message)
|
||
empty = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||
try:
|
||
empty.wrap_socket(socket.create_connection((U.hostname, U.port or 443), timeout=5), server_hostname=U.hostname)
|
||
check("empty trust store -> verification error", False, "handshake succeeded")
|
||
except ssl.SSLCertVerificationError as exc:
|
||
check("empty trust store -> verification error", True, exc.verify_message)
|
||
try:
|
||
conn = http.client.HTTPConnection(U.hostname, U.port or 443, timeout=5)
|
||
conn.request("GET", "/health/ready")
|
||
status = conn.getresponse().status
|
||
check("plaintext HTTP on HTTPS port is not served", not 200 <= status < 300, status)
|
||
except (OSError, http.client.HTTPException) as exc:
|
||
check("plaintext HTTP on HTTPS port is not served", True, type(exc).__name__)
|
||
# ---------------- Grafana (оператор, локально)
|
||
g = urlparse(args.grafana_url)
|
||
try:
|
||
conn = http.client.HTTPSConnection(g.hostname, g.port, context=CTX, timeout=5)
|
||
conn.request("GET", "/api/dashboards/home")
|
||
status = conn.getresponse().status
|
||
check("grafana over HTTPS requires authentication", status == 401, status)
|
||
except OSError as exc:
|
||
check("grafana over HTTPS requires authentication (skipped: not reachable)", True, type(exc).__name__)
|
||
ok = all(RESULTS)
|
||
print("%s: %d/%d checks" % ("PASS" if ok else "FAIL", sum(RESULTS), len(RESULTS)))
|
||
return 0 if ok else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|