1493 lines
58 KiB
Python
1493 lines
58 KiB
Python
#!/usr/bin/env python3
|
||
"""Учения трека 1 «Компрометация worker» (лаба 7): make worker-compromise.
|
||
|
||
python3 infra/track1/track1.py [--rounds N] [--control wide-rights|no-revoke|
|
||
no-republish] [--out FILE] [--dirty]
|
||
|
||
Стенды — изолированные, по очереди, рабочий (`vladimirceva-lab7`) должен быть
|
||
остановлен и не трогается:
|
||
|
||
- «до» — её лаба 6 (`3e8493b`, git archive во временном каталоге) под проектом
|
||
`vladimirceva-lab7-track1-before` с override `before.compose.yml`: таблица
|
||
операций материалами worker (A1 — пробник в его контейнере) и атака на
|
||
задания H5 (перезапись исходника, удаление строки задания, возврат в
|
||
pending; чтение сессий и хэшей, сообщение от чужого имени, чужой объект
|
||
через API);
|
||
- «после» — рабочее дерево под проектом `vladimirceva-lab7-track1` (стенд
|
||
`student-tests/stand.py` + override `stand.compose.yml`; своя PKI и OpenBao
|
||
прогона во временном каталоге 0700, секреты — env-файл прогона 0600 там же):
|
||
та же таблица (H1), затем раунды: атака на задания (worker остановлен SIGSTOP
|
||
— модель «RCE в процессе»), копия материалов A2 в отдельном контейнере сети
|
||
стенда, порядок «Компрометация процесса» командами `infra/rotation/rotation.py`
|
||
(revoke worker → secret postgres/worker → secret s3/worker → пересоздание
|
||
worker → leaf worker) с окнами каждого материала (H2), `make jobs-audit` и
|
||
возврат, replay ложного failed, сохранность принятых (H3), сверка порчи и
|
||
перезаписанного оригинала (H4).
|
||
|
||
Контроли (код 1): `wide-rights` — роль, брокер и S3 worker шире своих (только
|
||
таблица и перезапись исходника); `no-revoke` — порядок без отзыва;
|
||
`no-republish` — relay остановлен. Вердикты — по порогам `hypotheses.json`
|
||
(commit и sha256 файла в паспорте). Без закоммиченного дерева — только
|
||
`--dirty`, и прогон не доказательство.
|
||
|
||
Коды: 0 — все гипотезы подтверждены; 1 — нет; 2 — предусловие (ничего не
|
||
создано). Уборка — при любом исходе и по SIGINT / SIGTERM / SIGHUP: стенды
|
||
`down -v`, контейнер A2, образ «до», каталоги прогона; остаток SIGKILL убирает
|
||
следующий прогон (по именам проектов). Секреты — только env-файл прогона,
|
||
stdin пробника и память; в выводе — имена, исходы, числа. Только stdlib,
|
||
Python 3.9+.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import base64
|
||
import datetime
|
||
import hashlib
|
||
import ipaddress
|
||
import json
|
||
import os
|
||
import random
|
||
import secrets
|
||
import shutil
|
||
import signal
|
||
import ssl
|
||
import struct
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import threading
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
import uuid
|
||
import zlib
|
||
from pathlib import Path
|
||
|
||
TRACK1 = Path(__file__).resolve().parent
|
||
ROOT = TRACK1.parent.parent
|
||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||
sys.path.insert(0, str(TRACK1))
|
||
import operations # noqa: E402
|
||
|
||
import stand as standmod # noqa: E402
|
||
|
||
PROBE = TRACK1 / "probe.py"
|
||
HYPOTHESES = TRACK1 / "hypotheses.json"
|
||
ROTATION = ROOT / "infra" / "rotation" / "rotation.py"
|
||
JOBS = ROOT / "infra" / "incident" / "jobs.sh"
|
||
AFTER_FILES = (
|
||
ROOT / "compose.yaml",
|
||
ROOT / "student-tests" / "stand.compose.yml",
|
||
TRACK1 / "stand.compose.yml",
|
||
)
|
||
BEFORE_IMAGE = "mtusi-messenger-vladimirceva:track1-before"
|
||
AFTER_IMAGE = "mtusi-messenger-vladimirceva:track1"
|
||
SUBNETS = ipaddress.ip_network("10.217.0.0/22")
|
||
MEMORY_MIN = 6 * 1024**3
|
||
CONTROLS = ("wide-rights", "no-revoke", "no-republish")
|
||
# загрузчик пробника: первая строка stdin — JSON с кодом и входом
|
||
BOOT = (
|
||
"import json,sys;d=json.loads(sys.stdin.readline());"
|
||
'exec(compile(d["code"],"probe","exec"),{"__name__":"probe","INPUT":d})'
|
||
)
|
||
API = "/api/v1"
|
||
READY_WAIT = 120.0
|
||
COHORT_B = 14
|
||
|
||
|
||
def say(text: str) -> None:
|
||
print(f"[track1] {text}", flush=True)
|
||
|
||
|
||
class Precondition(Exception):
|
||
"""Код 2: ничего не создано."""
|
||
|
||
|
||
def interrupt(_signum: int, _frame: object) -> None:
|
||
raise KeyboardInterrupt
|
||
|
||
|
||
# --------------------------------------------------------------- чистые функции
|
||
|
||
|
||
def png(seed: int, side: int = 48) -> bytes:
|
||
"""PNG RGB с шумом: у каждой загрузки свой SHA-256."""
|
||
rng = random.Random(seed)
|
||
rows = b"".join(b"\x00" + rng.randbytes(side * 3) for _ in range(side))
|
||
|
||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||
body = kind + data
|
||
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
|
||
|
||
header = struct.pack(">IIBBBBB", side, side, 8, 2, 0, 0, 0)
|
||
return (
|
||
b"\x89PNG\r\n\x1a\n"
|
||
+ chunk(b"IHDR", header)
|
||
+ chunk(b"IDAT", zlib.compress(rows, 1))
|
||
+ chunk(b"IEND", b"")
|
||
)
|
||
|
||
|
||
def table_summary(before: dict, after: dict) -> dict:
|
||
"""Строки таблицы против ожиданий и доли для H1."""
|
||
unexpected_after, unexpected_before, outside = [], [], []
|
||
available_before = closed = 0
|
||
for op in operations.OPERATIONS:
|
||
got_after, got_before = after.get(op.id), before.get(op.id)
|
||
if got_after is not None and got_after != op.after:
|
||
unexpected_after.append((op.id, op.after, got_after))
|
||
if got_before is not None and got_before != op.before:
|
||
unexpected_before.append((op.id, op.before, got_before))
|
||
if op.scope == operations.OUTSIDE and got_after == operations.OK:
|
||
outside.append(op.id)
|
||
if got_before == operations.OK:
|
||
available_before += 1
|
||
if got_after is not None and got_after.startswith("denied:"):
|
||
closed += 1
|
||
return {
|
||
"unexpected_after": unexpected_after,
|
||
"unexpected_before": unexpected_before,
|
||
"outside_available": outside,
|
||
"available_before": available_before,
|
||
"closed": closed,
|
||
"closed_share": closed / available_before if available_before else 0.0,
|
||
}
|
||
|
||
|
||
def windows(events: list, start: str = "start", end: str = "end") -> dict:
|
||
"""Окно материала: последний успех A2 − метка `start` (с); `after_end` —
|
||
успех позже метки `end`. Материал без успехов после начала — 0."""
|
||
marks = {e["mark"]: e["t"] for e in events if "mark" in e}
|
||
done = next((e for e in events if e.get("done")), {})
|
||
result = {}
|
||
for material, last in sorted(done.get("last_ok", {}).items()):
|
||
result[material] = {
|
||
"window": max(0.0, round(last - marks[start], 1)),
|
||
"after_end": last > marks[end],
|
||
}
|
||
return result
|
||
|
||
|
||
def verdicts(thresholds: dict, measured: dict) -> dict:
|
||
"""Гипотеза → (подтверждена, текст с числом и порогом)."""
|
||
out = {}
|
||
h1 = measured.get("H1")
|
||
if h1 is not None:
|
||
t = thresholds["H1"]["thresholds"]
|
||
ok = (
|
||
len(h1["unexpected_after"]) <= t["unexpected_after"]
|
||
and len(h1["unexpected_before"]) <= t["unexpected_before"]
|
||
# контроль без стенда «до»: доли нет, судят строки «после»
|
||
and (
|
||
not h1["available_before"]
|
||
or h1["closed_share"] >= t["closed_share_min"]
|
||
)
|
||
and len(h1["outside_available"]) <= t["outside_available"]
|
||
)
|
||
out["H1"] = (
|
||
ok,
|
||
f"unexpected after {len(h1['unexpected_after'])}, before "
|
||
f"{len(h1['unexpected_before'])}; closed {h1['closed']} of "
|
||
f"{h1['available_before']} = {h1['closed_share']:.2f} (min "
|
||
f"{t['closed_share_min']}); outside available "
|
||
f"{len(h1['outside_available'])}",
|
||
)
|
||
h2 = measured.get("H2")
|
||
if h2 is not None:
|
||
t = thresholds["H2"]["thresholds"]
|
||
bad = []
|
||
for number, round_windows in enumerate(h2["rounds"], 1):
|
||
# материал без единого успеха не измерен: проба сломана, а не отзыв
|
||
for material in sorted(set(t["windows_seconds"]) - set(round_windows)):
|
||
bad.append(f"round {number} {material} not measured")
|
||
for material, item in round_windows.items():
|
||
limit = t["windows_seconds"].get(material)
|
||
if item["after_end"] or (limit is not None and item["window"] > limit):
|
||
bad.append(f"round {number} {material} {item['window']} s")
|
||
ok = not bad and h2["failed_requests"] <= t["failed_requests"]
|
||
worst = {}
|
||
for round_windows in h2["rounds"]:
|
||
for material, item in round_windows.items():
|
||
worst[material] = max(worst.get(material, 0.0), item["window"])
|
||
text = ", ".join(
|
||
f"{m} {w} / {t['windows_seconds'].get(m, '-')}"
|
||
for m, w in sorted(worst.items())
|
||
)
|
||
out["H2"] = (
|
||
ok,
|
||
f"worst windows, s: {text}; failed LB requests {h2['failed_requests']}"
|
||
+ (f"; over: {'; '.join(bad)}" if bad else ""),
|
||
)
|
||
h3 = measured.get("H3")
|
||
if h3 is not None:
|
||
t = thresholds["H3"]["thresholds"]
|
||
ok = (
|
||
h3["lost"] <= t["lost"]
|
||
and h3["duplicated"] <= t["duplicated"]
|
||
and h3["wrong_sha256"] <= t["wrong_sha256"]
|
||
and h3["ready_seconds"] <= t["ready_seconds"]
|
||
)
|
||
out["H3"] = (
|
||
ok,
|
||
f"accepted {h3['accepted']}, lost {h3['lost']}, duplicated "
|
||
f"{h3['duplicated']}, wrong SHA-256 {h3['wrong_sha256']}; all ready "
|
||
f"{h3['ready_seconds']:.0f} s after the identity (limit "
|
||
f"{t['ready_seconds']})",
|
||
)
|
||
h4 = measured.get("H4")
|
||
if h4 is not None:
|
||
t = thresholds["H4"]["thresholds"]
|
||
ok = (
|
||
h4["missed_damage"] <= t["missed_damage"]
|
||
and h4["left_after_repair"] <= t["left_after_repair"]
|
||
and h4["missed_overwrites"] <= t["missed_overwrites"]
|
||
)
|
||
out["H4"] = (
|
||
ok,
|
||
f"damaged {h4['found']} of {h4['damaged']} found, left after repair "
|
||
f"{h4['left_after_repair']}; overwritten originals found "
|
||
f"{h4['overwrites'] - h4['missed_overwrites']} of {h4['overwrites']}",
|
||
)
|
||
h5 = measured.get("H5")
|
||
if h5 is not None:
|
||
t = thresholds["H5"]["thresholds"]
|
||
ok = (
|
||
min(h5["lost"].values()) >= t["lost_each_min"]
|
||
and h5["failed_actions"] <= t["failed_actions"]
|
||
)
|
||
lost = ", ".join(f"{k} {v}" for k, v in sorted(h5["lost"].items()))
|
||
out["H5"] = (ok, f"lost: {lost}; failed actions {h5['failed_actions']}")
|
||
return out
|
||
|
||
|
||
# --------------------------------------------------------------------- API
|
||
|
||
|
||
class Api:
|
||
"""Клиент API через LB стенда (HTTPS с CA прогона «после», HTTP «до»)."""
|
||
|
||
def __init__(self, base: str, ca_file: str | None) -> None:
|
||
self.base = base
|
||
self.context = ssl.create_default_context(cafile=ca_file) if ca_file else None
|
||
|
||
def call(self, method, path, *, body=None, headers=None, token=None, raw=None):
|
||
data = (
|
||
raw
|
||
if raw is not None
|
||
else (None if body is None else json.dumps(body).encode())
|
||
)
|
||
request = urllib.request.Request(self.base + path, data=data, method=method)
|
||
if body is not None:
|
||
request.add_header("Content-Type", "application/json")
|
||
if token:
|
||
request.add_header("Authorization", f"Bearer {token}")
|
||
for key, value in (headers or {}).items():
|
||
request.add_header(key, value)
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=30, context=self.context) as r:
|
||
return r.status, r.read()
|
||
except urllib.error.HTTPError as error:
|
||
return error.code, error.read()
|
||
except (urllib.error.URLError, OSError) as error:
|
||
return 0, str(error).encode()
|
||
|
||
def user(self, label: str) -> dict:
|
||
password = secrets.token_hex(12)
|
||
name = f"{label}_{uuid.uuid4().hex[:10]}"
|
||
status, raw = self.call(
|
||
"POST",
|
||
f"{API}/users",
|
||
body={"username": name, "display_name": label, "password": password},
|
||
)
|
||
if status != 201:
|
||
raise RuntimeError(f"register: {status}")
|
||
user = json.loads(raw)
|
||
basic = "Basic " + base64.b64encode(f"{name}:{password}".encode()).decode()
|
||
status, raw = self.call(
|
||
"POST", f"{API}/auth/sessions", headers={"Authorization": basic}
|
||
)
|
||
if status != 201:
|
||
raise RuntimeError(f"login: {status}")
|
||
return {"id": user["id"], "token": json.loads(raw)["token"]}
|
||
|
||
def chat(self, owner: dict, *others: dict) -> str:
|
||
status, raw = self.call(
|
||
"POST",
|
||
f"{API}/chats",
|
||
token=owner["token"],
|
||
body={
|
||
"title": "track1",
|
||
"member_ids": [owner["id"], *(o["id"] for o in others)],
|
||
},
|
||
)
|
||
if status != 201:
|
||
raise RuntimeError(f"chat: {status}")
|
||
return json.loads(raw)["id"]
|
||
|
||
def upload(self, user: dict, chat: str, data: bytes) -> str | None:
|
||
status, raw = self.call(
|
||
"POST",
|
||
f"{API}/chats/{chat}/attachments?filename=t.png",
|
||
raw=data,
|
||
token=user["token"],
|
||
headers={"Content-Type": "image/png"},
|
||
)
|
||
return json.loads(raw)["id"] if status == 202 else None
|
||
|
||
def status(self, user: dict, attachment: str) -> str:
|
||
status, raw = self.call(
|
||
"GET", f"{API}/attachments/{attachment}", token=user["token"]
|
||
)
|
||
return json.loads(raw)["status"] if status == 200 else f"http {status}"
|
||
|
||
def content(self, user: dict, attachment: str, variant: str = "") -> bytes | None:
|
||
query = f"?variant={variant}" if variant else ""
|
||
status, raw = self.call(
|
||
"GET", f"{API}/attachments/{attachment}/content{query}", token=user["token"]
|
||
)
|
||
return raw if status == 200 else None
|
||
|
||
|
||
# ------------------------------------------------------------------- стенды
|
||
|
||
|
||
def run(args, *, env=None, stdin=None, check=False, quiet=True, timeout=900):
|
||
result = subprocess.run(
|
||
[str(a) for a in args],
|
||
cwd=ROOT,
|
||
env=env,
|
||
input=stdin,
|
||
text=True,
|
||
capture_output=quiet,
|
||
check=False,
|
||
timeout=timeout,
|
||
)
|
||
if check and result.returncode != 0:
|
||
raise RuntimeError(f"{' '.join(map(str, args[:6]))}: exit {result.returncode}")
|
||
return result
|
||
|
||
|
||
def host_env() -> dict:
|
||
return {k: os.environ[k] for k in standmod.HOST_ENV if k in os.environ}
|
||
|
||
|
||
def write_private(path: Path, text: str) -> None:
|
||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||
with os.fdopen(fd, "w") as handle:
|
||
handle.write(text)
|
||
|
||
|
||
class Probing:
|
||
"""Общее у стендов: compose проекта, пробник в контейнере, psql оператора."""
|
||
|
||
project = ""
|
||
|
||
def compose_args(self) -> list:
|
||
raise NotImplementedError
|
||
|
||
def env_for_compose(self) -> dict:
|
||
raise NotImplementedError
|
||
|
||
def dc(self, *args, stdin=None, check=False, quiet=True, timeout=900):
|
||
return run(
|
||
[*self.compose_args(), *args],
|
||
env=self.env_for_compose(),
|
||
stdin=stdin,
|
||
check=check,
|
||
quiet=quiet,
|
||
timeout=timeout,
|
||
)
|
||
|
||
def probe(self, payload: dict, service: str = "worker") -> list:
|
||
data = json.dumps({"code": PROBE.read_text(), **payload}) + "\n"
|
||
result = self.dc("exec", "-T", service, "python", "-I", "-c", BOOT, stdin=data)
|
||
lines = [json.loads(x) for x in result.stdout.splitlines() if x.startswith("{")]
|
||
if result.returncode != 0:
|
||
tail = (result.stderr.strip().splitlines() or ["?"])[-1][:200]
|
||
raise RuntimeError(
|
||
f"probe {payload.get('mode')}: exit {result.returncode}: {tail}"
|
||
)
|
||
return lines
|
||
|
||
def probe_open(self, payload: dict) -> subprocess.Popen:
|
||
process = subprocess.Popen(
|
||
[*self.compose_args(), "exec", "-T", "worker", "python", "-I", "-c", BOOT],
|
||
cwd=ROOT,
|
||
env=self.env_for_compose(),
|
||
stdin=subprocess.PIPE,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
text=True,
|
||
)
|
||
process.stdin.write(json.dumps({"code": PROBE.read_text(), **payload}) + "\n")
|
||
process.stdin.flush()
|
||
return process
|
||
|
||
def sql(self, query: str) -> list:
|
||
result = self.dc(
|
||
"exec",
|
||
"-T",
|
||
"postgres",
|
||
"sh",
|
||
"-c",
|
||
'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq -F "|" '
|
||
"-v ON_ERROR_STOP=1",
|
||
stdin=query,
|
||
)
|
||
if result.returncode != 0:
|
||
raise RuntimeError(f"psql: exit {result.returncode}")
|
||
return [line.split("|") for line in result.stdout.splitlines() if line]
|
||
|
||
def container(self, service: str) -> str:
|
||
out = self.dc("ps", "-q", service).stdout.split()
|
||
return out[0] if out else ""
|
||
|
||
def signal_worker(self, name: str) -> None:
|
||
run(["docker", "kill", "--signal", name, self.container("worker")])
|
||
|
||
def materials(self) -> dict:
|
||
return self.probe({"mode": "materials"})[0]["materials"]
|
||
|
||
def table(self, values: dict) -> dict:
|
||
ops = [op._asdict() for op in operations.OPERATIONS]
|
||
lines = self.probe({"mode": "table", "ops": ops, "values": values})
|
||
return {line["id"]: line["outcome"] for line in lines if "id" in line}
|
||
|
||
def attack(self, actions: list) -> list:
|
||
return [
|
||
x for x in self.probe({"mode": "attack", "actions": actions}) if "do" in x
|
||
]
|
||
|
||
def wait_status(
|
||
self, api: Api, user: dict, ids: list, want: set, timeout: float
|
||
) -> tuple:
|
||
"""Ждать, пока у каждого id статус не из промежуточных; (статусы, с)."""
|
||
started = time.monotonic()
|
||
states = {}
|
||
while time.monotonic() - started < timeout:
|
||
states = {i: api.status(user, i) for i in ids}
|
||
if all(s in want for s in states.values()):
|
||
break
|
||
time.sleep(1)
|
||
return states, time.monotonic() - started
|
||
|
||
|
||
class After(standmod.Stand, Probing):
|
||
"""Стенд «после»: stand.py с override трека, секреты — env-файл прогона."""
|
||
|
||
SECRET_NAMES = (
|
||
"POSTGRES_PASSWORD",
|
||
"VALKEY_PASSWORD",
|
||
"GRAFANA_ADMIN_PASSWORD",
|
||
*standmod.S3_SECRETS,
|
||
*standmod.ROLE_SECRETS,
|
||
)
|
||
|
||
def __init__(self) -> None:
|
||
standmod.COMPOSE_FILES = AFTER_FILES
|
||
super().__init__("track1")
|
||
lines = [
|
||
x
|
||
for x in standmod.ENV_FILE.read_text().splitlines()
|
||
if x and not x.startswith("#")
|
||
]
|
||
# rotation.py меняет значения в этом файле; в окружении их быть не должно
|
||
for name in (*self.SECRET_NAMES, "STAND_LB_PORT", "BAO_HOST_PORT"):
|
||
lines.append(f"{name}={self.env[name]}")
|
||
for name in self.SECRET_NAMES:
|
||
self.env.pop(name)
|
||
self.env_file = self.pki / "run.env"
|
||
write_private(self.env_file, "\n".join(lines) + "\n")
|
||
standmod.ENV_FILE = self.env_file
|
||
self.base_url = f"https://localhost:{self.env['STAND_LB_PORT']}"
|
||
|
||
def compose_args(self) -> list:
|
||
files = [a for f in AFTER_FILES for a in ("-f", str(f))]
|
||
return [
|
||
"docker",
|
||
"compose",
|
||
"-p",
|
||
self.project,
|
||
"--env-file",
|
||
str(self.env_file),
|
||
*files,
|
||
]
|
||
|
||
def env_for_compose(self) -> dict:
|
||
return dict(self.env)
|
||
|
||
def operator_env(self) -> dict:
|
||
"""Окружение команд оператора прогона (rotation.py, jobs.sh)."""
|
||
return {
|
||
**host_env(),
|
||
"COMPOSE_PROJECT_NAME": self.project,
|
||
"COMPOSE_FILE": os.pathsep.join(str(f) for f in AFTER_FILES),
|
||
"COMPOSE_ENV_FILES": str(self.env_file),
|
||
"PKI_STAND_DIR": str(self.stand_dir),
|
||
"PKI_OPERATOR_DIR": str(self.pki / "operator"),
|
||
"BAO_HOST_PORT": self.env["BAO_HOST_PORT"],
|
||
}
|
||
|
||
def up(self) -> None:
|
||
self.prepare()
|
||
self.start_lb()
|
||
self.compose(
|
||
"up",
|
||
"-d",
|
||
"--no-deps",
|
||
"--no-build",
|
||
"cleaner",
|
||
"otel-gateway",
|
||
"otel-collector",
|
||
quiet=True,
|
||
)
|
||
|
||
def rotation(self, *args: str) -> tuple:
|
||
started = time.monotonic()
|
||
result = run([sys.executable, ROTATION, *args], env=self.operator_env())
|
||
seconds = time.monotonic() - started
|
||
tail = " | ".join((result.stdout + result.stderr).strip().splitlines()[-2:])
|
||
return result.returncode, seconds, tail[:300]
|
||
|
||
def jobs(self, repair: bool) -> tuple:
|
||
result = run(
|
||
["sh", JOBS, "repair" if repair else "audit"],
|
||
env={**self.operator_env(), "STALE_SECONDS": "20"},
|
||
)
|
||
return result.returncode, result.stdout
|
||
|
||
def widen(self) -> None:
|
||
"""Контроль wide-rights: права worker шире своих (роль, брокер, S3)."""
|
||
self.sql("ALTER ROLE worker SUPERUSER;")
|
||
self.dc(
|
||
"exec",
|
||
"-T",
|
||
"-u",
|
||
"rabbitmq",
|
||
"rabbitmq",
|
||
"rabbitmqctl",
|
||
"set_permissions",
|
||
"-p",
|
||
"/",
|
||
"worker",
|
||
".*",
|
||
".*",
|
||
".*",
|
||
check=True,
|
||
)
|
||
policy = json.dumps(
|
||
{
|
||
"Version": "2012-10-17",
|
||
"Statement": [
|
||
{
|
||
"Effect": "Allow",
|
||
"Action": ["s3:*"],
|
||
"Resource": [
|
||
"arn:aws:s3:::messenger-attachments/*",
|
||
"arn:aws:s3:::messenger-attachments",
|
||
],
|
||
}
|
||
],
|
||
}
|
||
)
|
||
script = (
|
||
"cat > /tmp/wide.json && printf 's3.policy -put -name=worker-objects "
|
||
"-file=/tmp/wide.json\\n' | weed shell -master=127.0.0.1:9333 "
|
||
">/dev/null"
|
||
)
|
||
self.dc("exec", "-T", "s3", "sh", "-c", script, stdin=policy, check=True)
|
||
time.sleep(12)
|
||
|
||
|
||
class Before(Probing):
|
||
"""Стенд «до»: её лаба 6 из git archive, свой проект, env-файл прогона."""
|
||
|
||
def __init__(self, working: str, commit: str) -> None:
|
||
self.project = f"{working}-track1-before"
|
||
self.commit = commit
|
||
self.dir = Path(tempfile.mkdtemp(prefix=f"{self.project}-"))
|
||
self.src = self.dir / "src"
|
||
self.env_file = self.dir / "run.env"
|
||
self.port = standmod.free_port()
|
||
self.base_url = f"http://localhost:{self.port}"
|
||
|
||
def compose_args(self) -> list:
|
||
return [
|
||
"docker",
|
||
"compose",
|
||
"-p",
|
||
self.project,
|
||
"--project-directory",
|
||
str(self.src),
|
||
"--env-file",
|
||
str(self.env_file),
|
||
"-f",
|
||
str(self.src / "compose.yaml"),
|
||
"-f",
|
||
str(TRACK1 / "before.compose.yml"),
|
||
]
|
||
|
||
def env_for_compose(self) -> dict:
|
||
return host_env()
|
||
|
||
def up(self) -> None:
|
||
self.src.mkdir()
|
||
archive = subprocess.Popen(
|
||
["git", "-C", str(ROOT), "archive", self.commit], stdout=subprocess.PIPE
|
||
)
|
||
subprocess.run(
|
||
["tar", "-x", "-C", str(self.src)], stdin=archive.stdout, check=True
|
||
)
|
||
if archive.wait() != 0:
|
||
raise RuntimeError(f"git archive {self.commit} failed")
|
||
lines = []
|
||
for line in (self.src / ".env.example").read_text().splitlines():
|
||
if not line or line.startswith("#") or "=" not in line:
|
||
continue
|
||
name, value = line.split("=", 1)
|
||
if not value and name.endswith(("PASSWORD", "_KEY")):
|
||
value = secrets.token_hex(16)
|
||
lines.append(f"{name}={value}")
|
||
lines += ["OTEL_SDK_DISABLED=true", f"TRACK1_LB_PORT={self.port}"]
|
||
write_private(self.env_file, "\n".join(lines) + "\n")
|
||
say(f"before: build {BEFORE_IMAGE} from {self.commit}")
|
||
self.dc("build", "api", check=True)
|
||
self.dc(
|
||
"up", "-d", "--wait", "postgres", "valkey", "s3", "rabbitmq", check=True
|
||
)
|
||
self.dc(
|
||
"up",
|
||
"--no-deps",
|
||
"--exit-code-from",
|
||
"s3-bootstrap",
|
||
"s3-bootstrap",
|
||
check=True,
|
||
)
|
||
self.dc("run", "--rm", "migrate", check=True)
|
||
self.dc(
|
||
"up",
|
||
"-d",
|
||
"--wait",
|
||
"--no-build",
|
||
"api",
|
||
"relay",
|
||
"worker",
|
||
"cleaner",
|
||
"haproxy",
|
||
check=True,
|
||
)
|
||
|
||
def cleanup(self) -> bool:
|
||
self.dc("down", "-v", "--remove-orphans", "--timeout", "3")
|
||
run(["docker", "rmi", "-f", BEFORE_IMAGE])
|
||
shutil.rmtree(self.dir, ignore_errors=True)
|
||
left = run(
|
||
[
|
||
"docker",
|
||
"ps",
|
||
"-aq",
|
||
"--filter",
|
||
f"label=com.docker.compose.project={self.project}",
|
||
]
|
||
).stdout.split()
|
||
return not left and not self.dir.exists()
|
||
|
||
|
||
# ------------------------------------------------------------------ учения
|
||
|
||
|
||
def ids_literal(ids: list) -> str:
|
||
return ", ".join(f"'{uuid.UUID(i)}'" for i in ids)
|
||
|
||
|
||
class Drill:
|
||
def __init__(self, args: argparse.Namespace) -> None:
|
||
self.args = args
|
||
self.hypotheses = json.loads(HYPOTHESES.read_text())
|
||
self.measured: dict = {}
|
||
self.report: list = []
|
||
self.a2: subprocess.Popen | None = None
|
||
self.a2_name = ""
|
||
self.attack_process: subprocess.Popen | None = None
|
||
self.seed = random.randrange(1 << 30)
|
||
self.uploaded: dict = {}
|
||
|
||
def note(self, text: str) -> None:
|
||
say(text)
|
||
self.report.append(text)
|
||
|
||
def data(self) -> bytes:
|
||
self.seed += 1
|
||
return png(self.seed)
|
||
|
||
def upload(self, stand, api: Api, user: dict, chat: str, n: int) -> list:
|
||
ids = []
|
||
for _ in range(n):
|
||
data = self.data()
|
||
ident = api.upload(user, chat, data)
|
||
if ident is None:
|
||
raise RuntimeError("upload refused")
|
||
self.uploaded[ident] = hashlib.sha256(data).hexdigest()
|
||
ids.append(ident)
|
||
return ids
|
||
|
||
# --- стенд «до» ---------------------------------------------------------
|
||
|
||
def before(self, stand: Before) -> dict:
|
||
stand.up()
|
||
api = Api(stand.base_url, None)
|
||
victim, a, b = api.user("victim"), api.user("alice"), api.user("bob")
|
||
victim_chat, ab_chat = api.chat(victim), api.chat(a, b)
|
||
ready = self.upload(stand, api, victim, victim_chat, 3)
|
||
mine = self.upload(stand, api, b, ab_chat, 1)
|
||
states, _ = stand.wait_status(api, victim, ready, {"ready", "failed"}, 60)
|
||
stand.wait_status(api, b, mine, {"ready", "failed"}, 60)
|
||
att, other, pending = ready
|
||
say("before: operation table (A1 in the worker container)")
|
||
table = stand.table({"att": att, "other": other})
|
||
stand.signal_worker("STOP")
|
||
rewrite, deleted = self.upload(stand, api, victim, victim_chat, 2)
|
||
time.sleep(3)
|
||
forged = f"forged {uuid.uuid4().hex[:8]}"
|
||
actions = [
|
||
{"do": "source_put", "id": rewrite},
|
||
{
|
||
"do": "delete_job",
|
||
"sql": [
|
||
f"DELETE FROM attachment_jobs WHERE attachment_id = '{deleted}'"
|
||
],
|
||
},
|
||
{
|
||
"do": "pending",
|
||
"sql": [
|
||
"UPDATE attachments SET status = 'pending', created_at = now() - "
|
||
"interval '1 hour', updated_at = now() - interval '1 hour' "
|
||
f"WHERE id = '{pending}'"
|
||
],
|
||
},
|
||
{
|
||
"do": "read_sessions",
|
||
"sql": [
|
||
"SELECT count(token_hash) FROM sessions",
|
||
"SELECT count(password_hash) FROM users",
|
||
],
|
||
},
|
||
{
|
||
"do": "forge_message",
|
||
"sql": [
|
||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
||
f"VALUES (gen_random_uuid(), '{ab_chat}', '{a['id']}', '{forged}', "
|
||
"now())"
|
||
],
|
||
},
|
||
{
|
||
"do": "foreign_object",
|
||
# ключ, размер и тип чужого оригинала: API отдаёт объект по
|
||
# строке варианта и сверяет только размер
|
||
"sql": [
|
||
"UPDATE attachment_variants v SET object_key = a.object_key, "
|
||
"size_bytes = a.size_bytes, sha256 = a.sha256, "
|
||
"content_type = a.content_type FROM attachments a "
|
||
f"WHERE a.id = '{att}' AND v.attachment_id = '{mine[0]}' "
|
||
"AND v.name = 'thumbnail'"
|
||
],
|
||
},
|
||
]
|
||
results = stand.attack(actions)
|
||
stand.signal_worker("CONT")
|
||
failed_actions = sum(1 for r in results if not r["outcome"].startswith("ok"))
|
||
time.sleep(35)
|
||
after_rewrite = api.status(victim, rewrite)
|
||
after_delete = api.status(victim, deleted)
|
||
after_pending = api.status(victim, pending)
|
||
status, raw = api.call(
|
||
"GET", f"{API}/chats/{ab_chat}/messages", token=b["token"]
|
||
)
|
||
seen = status == 200 and any(
|
||
m.get("text") == forged and m.get("sender_id") == a["id"]
|
||
for m in json.loads(raw).get("items", [])
|
||
)
|
||
stolen = api.content(b, mine[0], "thumbnail")
|
||
original = api.content(victim, att)
|
||
foreign = stolen is not None and stolen == original
|
||
failed_actions += int(not seen) + int(not foreign)
|
||
lost = {
|
||
"source_rewrite": int(after_rewrite != "ready"),
|
||
"job_row_delete": int(after_delete != "ready"),
|
||
"return_to_pending": int(after_pending != "ready"),
|
||
}
|
||
self.note(
|
||
f"before H5: source rewrite -> {after_rewrite}, job row delete -> "
|
||
f"{after_delete}, return to pending -> {after_pending}; message under "
|
||
f"another name visible {seen}; foreign object through the API {foreign}; "
|
||
f"actions {[(r['do'], r['outcome'].split(':')[0]) for r in results]}"
|
||
)
|
||
self.measured["H5"] = {"lost": lost, "failed_actions": failed_actions}
|
||
del states
|
||
return table
|
||
|
||
# --- стенд «после» -------------------------------------------------------
|
||
|
||
def a2_start(self, stand: After, materials: dict) -> None:
|
||
self.a2_name = f"{stand.project}-a2"
|
||
self.a2 = subprocess.Popen(
|
||
[
|
||
"docker",
|
||
"run",
|
||
"--rm",
|
||
"-i",
|
||
"--name",
|
||
self.a2_name,
|
||
"--label",
|
||
f"vladimirceva.track1={stand.project}",
|
||
"--network",
|
||
f"{stand.project}_default",
|
||
"--read-only",
|
||
"--cap-drop",
|
||
"ALL",
|
||
"--security-opt",
|
||
"no-new-privileges",
|
||
"--pids-limit",
|
||
"256",
|
||
"--memory",
|
||
"384m",
|
||
"--cpus",
|
||
"0.5",
|
||
"--no-healthcheck",
|
||
"--tmpfs",
|
||
"/tmp:size=8m,mode=1777",
|
||
"--user",
|
||
"10001:10001",
|
||
"--entrypoint",
|
||
"python",
|
||
AFTER_IMAGE,
|
||
"-I",
|
||
"-c",
|
||
BOOT,
|
||
],
|
||
stdin=subprocess.PIPE,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
text=True,
|
||
)
|
||
self.a2.stdin.write(
|
||
json.dumps(
|
||
{"code": PROBE.read_text(), "mode": "hold", "materials": materials}
|
||
)
|
||
+ "\n"
|
||
)
|
||
self.a2.stdin.flush()
|
||
time.sleep(4)
|
||
|
||
def a2_mark(self, name: str) -> None:
|
||
self.a2.stdin.write(f"mark {name}\n")
|
||
self.a2.stdin.flush()
|
||
|
||
def a2_stop(self) -> list:
|
||
self.a2.stdin.write("stop\n")
|
||
self.a2.stdin.flush()
|
||
out, _ = self.a2.communicate(timeout=60)
|
||
self.a2 = None
|
||
return [json.loads(x) for x in out.splitlines() if x.startswith("{")]
|
||
|
||
def round(
|
||
self, stand: After, api: Api, owner: dict, chat: str, number: int, totals: dict
|
||
) -> None:
|
||
control = self.args.control
|
||
cohort_a = self.upload(stand, api, owner, chat, 3)
|
||
stand.wait_status(api, owner, cohort_a, {"ready", "failed"}, 90)
|
||
# перезапись — у готового, чей результат уборщик уже сверил (исходника
|
||
# нет): раньше сверки уборщик исходник оставит, и jobs-audit вернёт
|
||
# оригинал сам (прогон 3 переноса) — это другой, защищённый случай
|
||
for _ in range(60):
|
||
left = stand.sql(
|
||
"SELECT count(*) FROM attachments WHERE staging_key IS NOT NULL "
|
||
f"AND id IN ({ids_literal(cohort_a)});"
|
||
)[0][0]
|
||
if left == "0":
|
||
break
|
||
time.sleep(0.5)
|
||
sacrificed = cohort_a[0]
|
||
size = int(
|
||
stand.sql(f"SELECT size_bytes FROM attachments WHERE id = '{sacrificed}';")[
|
||
0
|
||
][0]
|
||
)
|
||
stand.signal_worker("STOP")
|
||
cohort_b = self.upload(stand, api, owner, chat, COHORT_B)
|
||
for _ in range(30):
|
||
left = stand.sql(
|
||
f"SELECT count(*) FROM attachment_jobs WHERE "
|
||
f"attachment_id IN ({ids_literal(cohort_b)}) AND "
|
||
"published_at IS NULL;"
|
||
)[0][0]
|
||
if left == "0":
|
||
break
|
||
time.sleep(0.5)
|
||
if control == "no-republish":
|
||
# сообщения уже в брокере: подтверждённое атакующим никто не вернёт
|
||
stand.compose("stop", "relay", quiet=True)
|
||
b = cohort_b
|
||
damaged = {
|
||
"lease_2100": b[1],
|
||
"next_2100": b[2],
|
||
"published_future": b[3],
|
||
"false_ready": b[4],
|
||
"mismatch": b[6],
|
||
"future_updated": b[7],
|
||
}
|
||
sql = {
|
||
"lease_2100": [
|
||
"UPDATE attachment_jobs SET state = 'processing', lease_until = "
|
||
f"'2100-01-01' WHERE attachment_id = '{b[1]}'",
|
||
f"UPDATE attachments SET status = 'processing' WHERE id = '{b[1]}'",
|
||
],
|
||
"next_2100": [
|
||
"UPDATE attachment_jobs SET published_at = NULL, next_attempt_at = "
|
||
f"'2100-01-01' WHERE attachment_id = '{b[2]}'"
|
||
],
|
||
"published_future": [
|
||
"UPDATE attachment_jobs SET published_at = '2100-01-01' "
|
||
f"WHERE attachment_id = '{b[3]}'"
|
||
],
|
||
"false_ready": [
|
||
f"UPDATE attachment_jobs SET state = 'ready' WHERE attachment_id = "
|
||
f"'{b[4]}'",
|
||
f"UPDATE attachments SET status = 'ready' WHERE id = '{b[4]}'",
|
||
],
|
||
"false_failed": [
|
||
"UPDATE attachment_jobs SET state = 'failed', last_error = 'track1' "
|
||
f"WHERE attachment_id = '{b[5]}'",
|
||
"UPDATE attachments SET status = 'failed', error_code = "
|
||
f"'processing_failed' WHERE id = '{b[5]}'",
|
||
],
|
||
"mismatch": [
|
||
f"UPDATE attachments SET status = 'ready' WHERE id = '{b[6]}'"
|
||
],
|
||
"future_updated": [
|
||
f"UPDATE attachments SET updated_at = '2100-01-01' WHERE id = '{b[7]}'"
|
||
],
|
||
# запрещённые правилами БД: ни одна не должна пройти
|
||
"pending": [
|
||
f"UPDATE attachments SET status = 'pending' WHERE id = '{b[0]}'"
|
||
],
|
||
"foreign_variant": [
|
||
"INSERT INTO attachment_variants (attachment_id, pipeline_version, "
|
||
"name, content_type, size_bytes, width, height, sha256, created_at, "
|
||
f"object_key) SELECT '{b[0]}', 1, 'crop', 'image/jpeg', 1, 1, 1, "
|
||
f"sha256, now(), object_key FROM attachments WHERE id = '{sacrificed}'"
|
||
],
|
||
}
|
||
actions = [
|
||
{"do": name, "id": None, "sql": statements}
|
||
for name, statements in sql.items()
|
||
]
|
||
actions += [
|
||
{"do": "source_put", "id": b[0]},
|
||
{"do": "source_delete", "id": b[0]},
|
||
{"do": "overwrite_original", "id": sacrificed, "size": size},
|
||
{"do": "get_ack"},
|
||
{"do": "get_ack"},
|
||
{"do": "reject_drop"},
|
||
{"do": "reject_drop"},
|
||
{"do": "hold"},
|
||
{"do": "hold"},
|
||
{"do": "purge"},
|
||
]
|
||
self.attack_process = stand.probe_open({"mode": "attack", "actions": actions})
|
||
results = []
|
||
while True:
|
||
line = self.attack_process.stdout.readline()
|
||
if not line:
|
||
break
|
||
item = json.loads(line)
|
||
if "held" in item:
|
||
break
|
||
results.append(item)
|
||
refused = {r["do"]: r["outcome"] for r in results}
|
||
must_refuse = ("pending", "foreign_variant", "source_put", "source_delete")
|
||
crossed = [n for n in must_refuse if refused.get(n, "ok").startswith("ok")]
|
||
self.note(
|
||
f"round {number}: attack "
|
||
+ ", ".join(f"{r['do']} {r['outcome']}" for r in results)
|
||
)
|
||
# сверка сразу после атаки (worker остановлен — состояние не меняется):
|
||
# K из K — шесть классов, внесённых атакующим
|
||
code, out = stand.jobs(False)
|
||
found = int(out.strip().splitlines()[-1].split()[-1]) if out else -1
|
||
totals["damaged"] += len(damaged)
|
||
totals["found"] += max(0, min(found, len(damaged)))
|
||
totals["extra"] += max(0, found - len(damaged))
|
||
self.note(
|
||
f"round {number}: jobs-audit after the attack code {code}: "
|
||
+ "; ".join(
|
||
line
|
||
for line in out.splitlines()
|
||
if line.startswith(("class", "info", "damaged"))
|
||
)
|
||
)
|
||
materials = stand.materials()
|
||
self.a2_start(stand, materials)
|
||
# когорта C — загрузки через LB (identity api) во время порядка
|
||
cohort_c: list = []
|
||
failed_requests = [0]
|
||
stop = threading.Event()
|
||
|
||
def uploads() -> None:
|
||
while not stop.is_set():
|
||
data = self.data()
|
||
ident = api.upload(owner, chat, data)
|
||
if ident is None:
|
||
failed_requests[0] += 1
|
||
else:
|
||
self.uploaded[ident] = hashlib.sha256(data).hexdigest()
|
||
cohort_c.append(ident)
|
||
stop.wait(3)
|
||
|
||
thread = threading.Thread(target=uploads, daemon=True)
|
||
thread.start()
|
||
self.a2_mark("start")
|
||
steps = [
|
||
("revoke", "worker"),
|
||
("secret", "postgres/worker"),
|
||
("secret", "s3/worker"),
|
||
("recreate", "worker"),
|
||
("leaf", "worker"),
|
||
]
|
||
if control == "no-revoke":
|
||
steps = steps[1:]
|
||
timings = []
|
||
for command, target in steps:
|
||
self.a2_mark(f"{command} {target}")
|
||
if command == "recreate":
|
||
started = time.monotonic()
|
||
code = stand.compose(
|
||
"up",
|
||
"-d",
|
||
"--no-deps",
|
||
"--no-build",
|
||
"--force-recreate",
|
||
"worker",
|
||
check=False,
|
||
quiet=True,
|
||
).returncode
|
||
seconds, tail = time.monotonic() - started, ""
|
||
else:
|
||
code, seconds, tail = stand.rotation(command, target)
|
||
timings.append(f"{command} {target} {seconds:.1f} s code {code}")
|
||
if code != 0:
|
||
self.note(f"round {number}: {command} {target}: code {code}: {tail}")
|
||
self.a2_mark("end")
|
||
leaf_done = time.monotonic()
|
||
time.sleep(5)
|
||
stop.set()
|
||
thread.join()
|
||
events = self.a2_stop()
|
||
self.attack_process.stdin.close()
|
||
self.attack_process.wait(timeout=30)
|
||
self.attack_process = None
|
||
found_windows = windows(events)
|
||
attacked = next((e.get("attacked", 0) for e in events if e.get("done")), 0)
|
||
self.note(f"round {number}: response " + "; ".join(timings))
|
||
self.note(
|
||
f"round {number}: windows "
|
||
+ ", ".join(
|
||
f"{m} {w['window']} s{' AFTER END' if w['after_end'] else ''}"
|
||
for m, w in found_windows.items()
|
||
)
|
||
+ f"; A2 damaged {attacked} new jobs"
|
||
)
|
||
# первая неудача каждого материала (код, без текста): по ней видно, чем
|
||
# отрезан материал, и что сломалось, если успеха не было вовсе
|
||
first_refusal: dict = {}
|
||
for event in events:
|
||
if "m" in event and not event.get("ok"):
|
||
first_refusal.setdefault(event["m"], event.get("detail") or "?")
|
||
self.note(
|
||
f"round {number}: first refusal "
|
||
+ ", ".join(f"{m} {d}" for m, d in sorted(first_refusal.items()))
|
||
)
|
||
totals["windows"].append(found_windows)
|
||
totals["failed_requests"] += failed_requests[0]
|
||
# сверка после порядка (с порчей A2) и возврат
|
||
code, out = stand.jobs(False)
|
||
self.note(
|
||
f"round {number}: jobs-audit after the response code {code}: "
|
||
+ "; ".join(
|
||
line
|
||
for line in out.splitlines()
|
||
if line.startswith(("class", "info", "damaged"))
|
||
)
|
||
)
|
||
code, out = stand.jobs(True)
|
||
left = int(out.strip().splitlines()[-1].split()[-1]) if out else -1
|
||
totals["left"] += max(left, 0)
|
||
self.note(
|
||
f"round {number}: jobs-audit REPAIR=1 code {code}, damaged after {left}"
|
||
)
|
||
replay = stand.compose(
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"relay",
|
||
"replay",
|
||
"--attachment",
|
||
b[5],
|
||
"--apply",
|
||
"--operator",
|
||
"track1",
|
||
"--reason",
|
||
"track1 false failed",
|
||
check=False,
|
||
quiet=True,
|
||
)
|
||
self.note(
|
||
f"round {number}: replay of the false failed: code {replay.returncode}"
|
||
)
|
||
accepted = cohort_a[1:] + cohort_b + list(cohort_c)
|
||
states, waited = stand.wait_status(api, owner, accepted, {"ready"}, READY_WAIT)
|
||
totals["ready_seconds"] = max(
|
||
totals["ready_seconds"], time.monotonic() - leaf_done
|
||
)
|
||
cohort_d = self.upload(stand, api, owner, chat, 3)
|
||
states_d, _ = stand.wait_status(api, owner, cohort_d, {"ready"}, 60)
|
||
states.update(states_d)
|
||
accepted += cohort_d
|
||
totals["accepted"] += accepted
|
||
totals["sacrificed"].append(sacrificed)
|
||
not_ready = [i for i, s in states.items() if s != "ready"]
|
||
totals["not_ready"] += len(not_ready)
|
||
self.note(
|
||
f"round {number}: accepted {len(accepted)} (A {len(cohort_a) - 1} + "
|
||
f"B {len(cohort_b)} + C {len(cohort_c)} + D {len(cohort_d)}), not "
|
||
f"ready {len(not_ready)}, waited {waited:.0f} s; LB failures "
|
||
f"{failed_requests[0]}; denied attack steps that passed {crossed}"
|
||
)
|
||
|
||
def after(self, stand: After) -> dict:
|
||
stand.up()
|
||
api = Api(stand.base_url, stand.ca_file)
|
||
owner, other_user = api.user("owner"), api.user("other")
|
||
chat = api.chat(owner)
|
||
other_chat = api.chat(other_user)
|
||
first = self.upload(stand, api, owner, chat, 1)
|
||
second = self.upload(stand, api, other_user, other_chat, 1)
|
||
stand.wait_status(api, owner, first, {"ready", "failed"}, 90)
|
||
stand.wait_status(api, other_user, second, {"ready", "failed"}, 90)
|
||
if self.args.control == "wide-rights":
|
||
say("control wide-rights: worker superuser, broker .* .* .*, S3 s3:*")
|
||
stand.widen()
|
||
table: dict = {}
|
||
if self.args.control in (None, "wide-rights"):
|
||
say("after: operation table (A1 in the worker container)")
|
||
table = stand.table({"att": first[0], "other": second[0]})
|
||
if self.args.control == "wide-rights":
|
||
stand.signal_worker("STOP")
|
||
victim = self.upload(stand, api, owner, chat, 1)
|
||
time.sleep(3)
|
||
result = stand.attack([{"do": "source_put", "id": victim[0]}])
|
||
stand.signal_worker("CONT")
|
||
states, _ = stand.wait_status(api, owner, victim, {"ready", "failed"}, 60)
|
||
lost = int(states[victim[0]] != "ready")
|
||
self.note(
|
||
f"control: source rewrite {result[0]['outcome']} -> {states[victim[0]]}"
|
||
)
|
||
self.measured["H3"] = {
|
||
"accepted": 1,
|
||
"lost": lost,
|
||
"duplicated": 0,
|
||
"wrong_sha256": 0,
|
||
"ready_seconds": 0.0,
|
||
}
|
||
return table
|
||
totals = {
|
||
"windows": [],
|
||
"failed_requests": 0,
|
||
"damaged": 0,
|
||
"found": 0,
|
||
"extra": 0,
|
||
"left": 0,
|
||
"accepted": [],
|
||
"sacrificed": [],
|
||
"ready_seconds": 0.0,
|
||
"not_ready": 0,
|
||
}
|
||
for number in range(1, self.args.rounds + 1):
|
||
self.round(stand, api, owner, chat, number, totals)
|
||
accepted = totals["accepted"]
|
||
lost = wrong = 0
|
||
for ident in accepted:
|
||
body = api.content(owner, ident)
|
||
if body is None:
|
||
lost += 1
|
||
elif hashlib.sha256(body).hexdigest() != self.uploaded[ident]:
|
||
wrong += 1
|
||
rows = stand.sql(
|
||
"SELECT a.id, (SELECT count(*) FROM attachment_variants v WHERE "
|
||
"v.attachment_id = a.id), (SELECT count(*) FROM attachment_jobs j WHERE "
|
||
f"j.attachment_id = a.id) FROM attachments a WHERE a.id IN "
|
||
f"({ids_literal(accepted)});"
|
||
)
|
||
# второй результат: больше трёх строк вариантов или второе задание;
|
||
# недоделанное (меньше трёх) — это потеря, её считает lost
|
||
duplicated = sum(1 for _, v, j in rows if int(v) > 3 or int(j) > 1)
|
||
deep = stand.compose(
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"cleaner",
|
||
"reconcile",
|
||
"--deep",
|
||
check=False,
|
||
quiet=True,
|
||
)
|
||
mismatches = [
|
||
line
|
||
for line in (deep.stdout + deep.stderr).splitlines()
|
||
if "kind=checksum_mismatch" in line
|
||
]
|
||
found_overwrites = sum(
|
||
1
|
||
for ident in totals["sacrificed"]
|
||
if any(f"attachment_id={ident}" in line for line in mismatches)
|
||
)
|
||
self.measured["H2"] = {
|
||
"rounds": totals["windows"],
|
||
"failed_requests": totals["failed_requests"],
|
||
}
|
||
# потерянное — не готовое к концу своего раунда или без содержимого в
|
||
# конце учений (relay контроля no-republish так и не запущен)
|
||
self.measured["H3"] = {
|
||
"accepted": len(accepted),
|
||
"lost": max(lost, totals["not_ready"]),
|
||
"duplicated": duplicated,
|
||
"wrong_sha256": wrong,
|
||
"ready_seconds": totals["ready_seconds"],
|
||
}
|
||
self.note(
|
||
f"after: audit found {totals['extra']} damaged rows beyond the six "
|
||
"injected classes"
|
||
)
|
||
self.measured["H4"] = {
|
||
"damaged": totals["damaged"],
|
||
"found": totals["found"],
|
||
"missed_damage": totals["damaged"] - totals["found"],
|
||
"left_after_repair": totals["left"],
|
||
"overwrites": len(totals["sacrificed"]),
|
||
"missed_overwrites": len(totals["sacrificed"]) - found_overwrites,
|
||
}
|
||
self.note(
|
||
f"after: reconcile --deep exit {deep.returncode}, overwritten "
|
||
f"originals found {found_overwrites} of {len(totals['sacrificed'])}"
|
||
)
|
||
return table
|
||
|
||
# --- итог ----------------------------------------------------------------
|
||
|
||
def finish(self, before: dict, after: dict) -> int:
|
||
if after:
|
||
summary = table_summary(before, after)
|
||
self.measured["H1"] = summary
|
||
self.print_table(before, after, summary)
|
||
results = verdicts(self.hypotheses["hypotheses"], self.measured)
|
||
code = 0
|
||
say("verdicts (thresholds from infra/track1/hypotheses.json):")
|
||
for name in sorted(results):
|
||
ok, text = results[name]
|
||
code = code if ok else 1
|
||
self.note(f"{name}: {'CONFIRMED' if ok else 'REFUTED'} — {text}")
|
||
self.note(f"worker-compromise: {'PASS' if code == 0 else 'FAIL'}")
|
||
if self.args.out:
|
||
Path(self.args.out).write_text("\n".join(self.report) + "\n")
|
||
return code
|
||
|
||
def print_table(self, before: dict, after: dict, summary: dict) -> None:
|
||
self.note("| operation | before (expected) | after (expected) | scope | why |")
|
||
self.note("|---|---|---|---|---|")
|
||
for op in operations.OPERATIONS:
|
||
got_b, got_a = before.get(op.id, "-"), after.get(op.id, "-")
|
||
mark_b = "" if got_b in (op.before, "-") else " **!**"
|
||
mark_a = "" if got_a == op.after else " **!**"
|
||
why = op.why[1] if op.why else ""
|
||
self.note(
|
||
f"| {op.id} | {got_b} ({op.before}){mark_b} | {got_a} "
|
||
f"({op.after}){mark_a} | {op.scope} | {why} |"
|
||
)
|
||
for name in ("unexpected_after", "unexpected_before"):
|
||
for op_id, want, got in summary[name]:
|
||
self.note(f"{name}: {op_id} expected {want} got {got}")
|
||
if self.args.control == "wide-rights":
|
||
opened = [x[0] for x in summary["unexpected_after"]]
|
||
self.note(f"OPENED by wide rights: {', '.join(opened) or 'none'}")
|
||
|
||
|
||
# ------------------------------------------------------------ предусловия
|
||
|
||
|
||
def preconditions(args: argparse.Namespace, working: str, hypotheses: dict) -> None:
|
||
if not ssl.HAS_TLSv1_3:
|
||
raise Precondition("python3 has no TLS 1.3")
|
||
running = run(
|
||
[
|
||
"docker",
|
||
"ps",
|
||
"-q",
|
||
"--filter",
|
||
f"label=com.docker.compose.project={working}",
|
||
]
|
||
).stdout.split()
|
||
if running:
|
||
raise Precondition(f"the working stand {working} is running: make stop first")
|
||
if args.control is None and args.rounds < hypotheses["min_rounds"]:
|
||
raise Precondition(f"--rounds must be at least {hypotheses['min_rounds']}")
|
||
commit = hypotheses["before_commit"]
|
||
if run(["git", "cat-file", "-e", f"{commit}^{{commit}}"]).returncode != 0:
|
||
raise Precondition(f"commit {commit} of the before stand is not available")
|
||
dirty = run(["git", "status", "--porcelain"]).stdout.strip()
|
||
tracked = run(["git", "ls-files", "--error-unmatch", str(HYPOTHESES)]).returncode
|
||
if (dirty or tracked) and not args.dirty:
|
||
raise Precondition(
|
||
"the tree or hypotheses.json is not committed: commit "
|
||
"first or pass DIRTY=1 (then the run is not a proof)"
|
||
)
|
||
memory = run(["docker", "info", "--format", "{{.MemTotal}}"]).stdout.strip()
|
||
if not memory.isdigit() or int(memory) < MEMORY_MIN:
|
||
raise Precondition(f"Docker VM memory {memory} < {MEMORY_MIN}")
|
||
names = run(["docker", "network", "ls", "-q"]).stdout.split()
|
||
if names:
|
||
inspect = run(
|
||
[
|
||
"docker",
|
||
"network",
|
||
"inspect",
|
||
"-f",
|
||
"{{.Name}} {{range .IPAM.Config}}{{.Subnet}} {{end}}",
|
||
*names,
|
||
]
|
||
)
|
||
for line in inspect.stdout.splitlines():
|
||
name, *subnets = line.split()
|
||
if name.startswith(f"{working}-track1"):
|
||
continue
|
||
for subnet in subnets:
|
||
try:
|
||
if ipaddress.ip_network(subnet).overlaps(SUBNETS):
|
||
raise Precondition(
|
||
f"subnet {subnet} of {name} overlaps {SUBNETS}"
|
||
)
|
||
except ValueError:
|
||
continue
|
||
|
||
|
||
def leftovers(working: str) -> None:
|
||
"""Остаток прогона, убитого SIGKILL: проекты учений и контейнер A2."""
|
||
for project in (f"{working}-track1", f"{working}-track1-before"):
|
||
run(["docker", "rm", "-f", f"{project}-a2"])
|
||
run(
|
||
[
|
||
"docker",
|
||
"compose",
|
||
"-p",
|
||
project,
|
||
"down",
|
||
"-v",
|
||
"--remove-orphans",
|
||
"--timeout",
|
||
"3",
|
||
]
|
||
)
|
||
|
||
|
||
def passport(args: argparse.Namespace, hypotheses: dict) -> None:
|
||
head = run(["git", "rev-parse", "--short", "HEAD"]).stdout.strip()
|
||
dirty = bool(run(["git", "status", "--porcelain"]).stdout.strip())
|
||
file_commit = run(["git", "log", "-1", "--format=%h", "--", str(HYPOTHESES)])
|
||
digest = hashlib.sha256(HYPOTHESES.read_bytes()).hexdigest()[:16]
|
||
info = run(
|
||
[
|
||
"docker",
|
||
"info",
|
||
"--format",
|
||
"{{.ServerVersion}} {{.NCPU}} CPU {{.MemTotal}} B",
|
||
]
|
||
).stdout.strip()
|
||
say(
|
||
f"passport: HEAD {head}{' (dirty tree: NOT A PROOF)' if dirty else ''}; "
|
||
f"hypotheses.json commit {file_commit.stdout.strip() or 'none'} sha256 "
|
||
f"{digest}; before {hypotheses['before_commit']}; rounds {args.rounds}; "
|
||
f"control {args.control or 'none'}; docker {info}; "
|
||
# timezone.utc, а не UTC: системный python3 — 3.9
|
||
f"{datetime.datetime.now(datetime.timezone.utc):%Y-%m-%dT%H:%M:%SZ}" # noqa: UP017
|
||
)
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
parser.add_argument("--rounds", type=int, default=3)
|
||
parser.add_argument("--control", choices=CONTROLS)
|
||
parser.add_argument("--out")
|
||
parser.add_argument("--dirty", action="store_true")
|
||
args = parser.parse_args()
|
||
if args.out and Path(args.out).resolve().is_relative_to(ROOT):
|
||
say("--out must be outside the repository")
|
||
return 2
|
||
hypotheses = json.loads(HYPOTHESES.read_text())
|
||
working = standmod.working_project()
|
||
try:
|
||
preconditions(args, working, hypotheses)
|
||
except Precondition as error:
|
||
say(f"precondition: {error}")
|
||
return 2
|
||
passport(args, hypotheses)
|
||
for name in ("SIGTERM", "SIGHUP"):
|
||
signal.signal(getattr(signal, name), interrupt)
|
||
leftovers(working)
|
||
drill = Drill(args)
|
||
before_stand: Before | None = None
|
||
after_stand: After | None = None
|
||
before: dict = {}
|
||
after: dict = {}
|
||
code = 1
|
||
started = time.monotonic()
|
||
try:
|
||
if args.control is None:
|
||
before_stand = Before(working, hypotheses["before_commit"])
|
||
before = drill.before(before_stand)
|
||
say("before: cleanup")
|
||
before_stand.cleanup()
|
||
before_stand = None
|
||
after_stand = After()
|
||
say(f"after: project {after_stand.project}, run PKI {after_stand.pki}")
|
||
after = drill.after(after_stand)
|
||
code = drill.finish(before, after)
|
||
except KeyboardInterrupt:
|
||
say("interrupted")
|
||
code = 130
|
||
except (RuntimeError, subprocess.CalledProcessError, standmod.BaoNotReady) as error:
|
||
say(f"failed: {error}")
|
||
code = 1
|
||
finally:
|
||
for name in ("SIGINT", "SIGTERM", "SIGHUP"):
|
||
signal.signal(getattr(signal, name), signal.SIG_IGN)
|
||
say("cleanup")
|
||
for process in (drill.a2, drill.attack_process):
|
||
if process is not None:
|
||
process.kill()
|
||
if drill.a2_name:
|
||
run(["docker", "rm", "-f", drill.a2_name])
|
||
if before_stand is not None and not before_stand.cleanup():
|
||
say("before stand leftovers")
|
||
code = code or 1
|
||
if after_stand is not None and not (
|
||
after_stand.cleanup() and after_stand.remove_pki()
|
||
):
|
||
say(f"after stand leftovers: {after_stand.pki}")
|
||
code = code or 1
|
||
say(f"took {time.monotonic() - started:.0f} s, exit {code}")
|
||
return code
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|