ЛР7: прогон в Docker, исправления по результатам, evidence и отчёт

This commit is contained in:
LOSYASH
2026-12-03 16:54:53 +01:00
parent cbbe525b3e
commit 17baa0dd7e
47 changed files with 1934 additions and 65 deletions
+24 -6
View File
@@ -172,20 +172,38 @@ def raw_http(base: str, method: str, path: str, headers: dict, chunks=(), chunke
раньше (413 до конца тела) — тогда прекращаем отправку и читаем ответ.
Возвращает (status | None, body_bytes)."""
u = urlparse(base)
sock = socket.create_connection((u.hostname, u.port or 80), timeout=timeout)
port = u.port or (443 if u.scheme == "https" else 80)
sock = socket.create_connection((u.hostname, port), timeout=timeout)
if u.scheme == "https": # lab7: тот же TLS с проверкой CA и имени, что у urllib
sock = tls_context().wrap_socket(sock, server_hostname=u.hostname)
try:
lines = [f"{method} {path} HTTP/1.1", f"Host: {u.hostname}:{u.port or 80}", "Connection: close"]
lines = [f"{method} {path} HTTP/1.1", f"Host: {u.hostname}:{port}", "Connection: close"]
lines += [f"{k}: {v}" for k, v in headers.items()]
if chunked:
lines.append("Transfer-Encoding: chunked")
sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("latin-1"))
early = b""
for part in chunks:
ready, _, _ = select.select([sock], [], [], 0)
if ready:
break # сервер уже ответил — дальше не шлём
# По TLS 1.3 сокет «читаем» и без ответа: сервер шлёт после handshake служебные
# записи (NewSessionTicket). Пробуем прочитать неблокирующе: нет данных приложения —
# шлём дальше; есть ответ или закрытие — прекращаем отправку.
sock.setblocking(False)
try:
early = sock.recv(65536)
got_reply = True
except (ssl.SSLWantReadError, BlockingIOError):
got_reply = False
except OSError:
got_reply = True
finally:
sock.settimeout(timeout)
if got_reply:
break # сервер уже ответил — дальше не шлём
try:
sock.sendall(f"{len(part):x}\r\n".encode() + part + b"\r\n" if chunked else part)
except (BrokenPipeError, ConnectionResetError):
except OSError: # сервер закрыл приём (в т.ч. ssl.SSLError, WinError 10053)
break
else:
if chunked and not close_after_send:
@@ -195,14 +213,14 @@ def raw_http(base: str, method: str, path: str, headers: dict, chunks=(), chunke
pass
if close_after_send:
return None, b"" # обрыв загрузки: ответ не ждём
data = b""
data = early
try:
while True:
piece = sock.recv(65536)
if not piece:
break
data += piece
except (ConnectionResetError, socket.timeout):
except OSError: # ConnectionReset, timeout, TLS EOF без close_notify
pass
finally:
sock.close()
+10 -2
View File
@@ -217,8 +217,16 @@ def main():
if not tel.direct:
for uid in ("prom", "loki", "tempo"):
st, h = tel.get(f"{tel.grafana}/api/datasources/uid/{uid}/health")
rep.check(st == 200 and isinstance(h, dict) and h.get("status") == "OK",
f"Grafana datasource {uid}: {h.get('message', h) if isinstance(h, dict) else h}")
msg = h.get("message", h) if isinstance(h, dict) else h
if uid == "tempo" and msg == "Method not implemented":
# Health API у плагина Tempo в Grafana 11 не реализован — проверяем сам путь
# Grafana → Tempo (mTLS сертификатом grafana) запросом через datasource proxy.
st, d = tel.get(f"{tel.grafana}/api/datasources/proxy/uid/tempo/api/search", {"limit": 1})
rep.check(st == 200 and isinstance(d, dict) and "traces" in d,
f"Grafana datasource tempo: health API не реализован плагином; "
f"поиск через datasource (mTLS) → {st}, трасс: {len(d.get('traces', [])) if isinstance(d, dict) else d}")
continue
rep.check(st == 200 and isinstance(h, dict) and h.get("status") == "OK", f"Grafana datasource {uid}: {msg}")
st, dash = tel.get(f"{tel.grafana}/api/dashboards/uid/messenger-lab6")
panels = [p for p in dash.get("dashboard", {}).get("panels", []) if p.get("type") != "row"] if st == 200 else []
rep.check(st == 200 and len(panels) >= 15,
+7 -4
View File
@@ -252,12 +252,15 @@ def section_docker(rep: Report) -> None:
roots = sorted(r["svc"] for r in rows if r["user"] in ("root", "0", "0:0"))
print(f" root (без capabilities, ФС read-only): {', '.join(roots) or 'нет'}")
img = json.loads(sh(["docker", "image", "inspect", "mtusi-messenger:lab7"]))[0]
env = " ".join(img["Config"].get("Env") or [])
rep.check(not re.search(r"PASSWORD|SECRET|TOKEN|KEY=", env, re.I), "в ENV образа нет паролей/ключей/токенов")
# GPG_KEY — отпечаток публичного ключа подписи релизов Python из базового образа, не секрет
names = [e.split("=", 1)[0] for e in img["Config"].get("Env") or []]
bad = [n for n in names if re.search(r"PASSWORD|SECRET|TOKEN|KEY", n, re.I) and n != "GPG_KEY"]
rep.check(not bad, f"в ENV образа нет паролей/ключей/токенов (переменные: {', '.join(names)}; подозрительные: {bad or 'нет'})")
files = sh(["docker", "run", "--rm", "--network", "none", "--entrypoint", "sh", "mtusi-messenger:lab7", "-c",
"find / -xdev \\( -name '*.key' -o -name '*.pem' -o -name '.env' -o -name 'tls.crt' \\) "
"-not -path '/usr/*' -not -path '/proc/*' 2>/dev/null | head -5"], check=False).strip()
rep.check(files == "", f"в образе нет ключей/сертификатов/.env {files[:80]}")
"-not -path '/usr/*' -not -path '/proc/*' -not -path '/etc/ssl/certs/*' 2>/dev/null | head -5"], check=False).strip()
rep.check(files == "", f"в образе нет ключей/сертификатов/.env (публичные корневые CA /etc/ssl/certs не в счёт) "
f"{files[:80]}")
probe = ("import socket,sys\nfor h,p in (('loki',3100),('prometheus',9090),('tempo',3200),('grafana',3000),"
"('openbao',8200),('postgres',5432)):\n try:\n socket.create_connection((h,p),timeout=2).close();print(h,'reachable')\n"
" except Exception as e:print(h,type(e).__name__)")