forked from mtusi2026/mtusi2026lab7
- narrow the worker S3 user to staging reads and attachments writes - add database rules the worker role cannot bypass: no return to pending, variant keys of its own attachment, known error codes only - let the cleaner remove a ready source only after its own SHA-256 check - add make jobs_audit [REPAIR=1] to name and requeue damaged jobs - add make worker_compromise: isolated before/after stands, one operation table, response windows, job safety, controls and committed hypotheses Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
475 lines
14 KiB
Python
475 lines
14 KiB
Python
"""Копия атакующего A2 (change track1-worker-compromise, design, решения 3 и 10):
|
|
отдельный контейнер сети стенда с материалами worker, который живёт дольше
|
|
worker, держит соединения и непрерывно пробует каждый материал.
|
|
|
|
Материалы — первая строка стандартного ввода (JSON), файлы identity — tmpfs 0600.
|
|
Дальше каждая строка ввода — метка; её время ставит этот процесс, часы одни на
|
|
успехи и метки. Строка вывода — JSON:
|
|
{"ready": {материал: исход}} — все начальные пробы;
|
|
{"mark": имя, "t": секунды} — метка принята;
|
|
{"t": секунды, "m": материал, "o": исход} — проба (`ok` или `denied:<код>`).
|
|
Последняя метка `stop` заканчивает процесс. Значений в выводе нет.
|
|
"""
|
|
|
|
import asyncio
|
|
import http.client
|
|
import json
|
|
import os
|
|
import socket
|
|
import ssl
|
|
import struct
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
PERIOD_S = 0.25
|
|
# через сколько секунд завершаются начатые до отзыва входы AMQP: до предела
|
|
# брокера (10 с) — вход, начатый под самый CRL, завершается позже всех
|
|
EARLY_DELAYS = (2.0, 5.0, 8.0, 9.2)
|
|
LOCK = threading.Lock()
|
|
STOP = threading.Event()
|
|
STARTED = time.monotonic()
|
|
DIR = "/tmp/track1"
|
|
|
|
|
|
def emit(**fields):
|
|
with LOCK:
|
|
print(json.dumps(fields), flush=True)
|
|
|
|
|
|
def now():
|
|
return round(time.monotonic() - STARTED, 3)
|
|
|
|
|
|
def report(material, outcome):
|
|
emit(t=now(), m=material, o=outcome)
|
|
|
|
|
|
def context(cert=True):
|
|
made = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
made.load_verify_locations(f"{DIR}/ca.crt")
|
|
made.minimum_version = ssl.TLSVersion.TLSv1_3
|
|
if cert:
|
|
made.load_cert_chain(f"{DIR}/worker.crt", f"{DIR}/worker.key")
|
|
return made
|
|
|
|
|
|
def failure(error):
|
|
state = getattr(error, "sqlstate", None)
|
|
return f"denied:{state or type(error).__name__}"
|
|
|
|
|
|
def every(material, probe):
|
|
"""Проба материала по кругу до остановки."""
|
|
|
|
def work():
|
|
while not STOP.is_set():
|
|
try:
|
|
outcome = probe()
|
|
except Exception as error:
|
|
outcome = failure(error)
|
|
report(material, outcome)
|
|
STOP.wait(PERIOD_S)
|
|
|
|
threading.Thread(target=work, daemon=True).start()
|
|
|
|
|
|
# брокер: протокол AMQP без библиотеки — вход нужен остановленным на полпути
|
|
|
|
|
|
def exactly(sock, size):
|
|
data = b""
|
|
while len(data) < size:
|
|
part = sock.recv(size - len(data))
|
|
if not part:
|
|
raise EOFError
|
|
data += part
|
|
return data
|
|
|
|
|
|
def frame(sock):
|
|
"""Следующий кадр method: (класс, метод)."""
|
|
while True:
|
|
kind, _, size = struct.unpack(">BHI", exactly(sock, 7))
|
|
payload = exactly(sock, size + 1)
|
|
if kind == 1:
|
|
return struct.unpack(">HH", payload[:4])
|
|
|
|
|
|
def method(number, body, channel=0, klass=10):
|
|
payload = struct.pack(">HH", klass, number) + body
|
|
return struct.pack(">BHI", 1, channel, len(payload)) + payload + b"\xce"
|
|
|
|
|
|
def amqp_begin(data):
|
|
"""TLS готов, заголовок AMQP не отправлен."""
|
|
source = data["broker"]
|
|
raw = socket.create_connection(
|
|
(source["host"], source["port"]),
|
|
timeout=5,
|
|
)
|
|
sock = context().wrap_socket(raw, server_hostname=source["host"])
|
|
# отказ клиента в TLS 1.3 приходит после рукопожатия
|
|
sock.settimeout(0.3)
|
|
try:
|
|
if sock.recv(1) == b"":
|
|
raise EOFError
|
|
except TimeoutError:
|
|
pass
|
|
sock.settimeout(5)
|
|
return sock
|
|
|
|
|
|
def amqp_login(sock):
|
|
sock.sendall(b"AMQP\x00\x00\x09\x01")
|
|
assert frame(sock) == (10, 10)
|
|
sock.sendall(
|
|
method(
|
|
11,
|
|
struct.pack(">I", 0)
|
|
+ b"\x08EXTERNAL"
|
|
+ struct.pack(">I", 0)
|
|
+ b"\x05en_US",
|
|
),
|
|
)
|
|
assert frame(sock) == (10, 30)
|
|
sock.sendall(
|
|
method(31, struct.pack(">HIH", 2047, 131072, 0))
|
|
+ method(40, b"\x01/\x00\x00"),
|
|
)
|
|
assert frame(sock) == (10, 41)
|
|
sock.sendall(method(10, b"\x00", channel=1, klass=20))
|
|
assert frame(sock) == (20, 11)
|
|
return sock
|
|
|
|
|
|
def amqp_use(sock, queue):
|
|
"""Пассивная проверка очереди (право worker `read`): соединение принимает
|
|
команды, сообщений не берёт."""
|
|
name = queue.encode()
|
|
sock.sendall(
|
|
method(
|
|
10,
|
|
b"\x00\x00" + bytes([len(name)]) + name + b"\x01\x00\x00\x00\x00",
|
|
channel=1,
|
|
klass=50,
|
|
),
|
|
)
|
|
if frame(sock) != (50, 11):
|
|
raise EOFError
|
|
return "ok"
|
|
|
|
|
|
def probe_amqp_new(data):
|
|
sock = amqp_login(amqp_begin(data))
|
|
try:
|
|
return amqp_use(sock, data["queue"])
|
|
finally:
|
|
sock.close()
|
|
|
|
|
|
def early_logins(data):
|
|
"""Входы, начатые до отзыва: соединение без пользователя брокер не найдёт.
|
|
Начинаются каждые полсекунды, пока брокер принимает рукопожатие, то есть до
|
|
самого CRL; завершаются через `EARLY_DELAYS` (срок брокера на вход — 10 с).
|
|
Открытое так соединение пробуется, пока его не закроют."""
|
|
|
|
def finish(delay, sock):
|
|
STOP.wait(delay)
|
|
try:
|
|
amqp_login(sock)
|
|
except Exception as error:
|
|
report("amqp_early", failure(error))
|
|
return
|
|
while not STOP.is_set():
|
|
try:
|
|
outcome = amqp_use(sock, data["queue"])
|
|
except Exception as error:
|
|
report("amqp_early", failure(error))
|
|
return
|
|
report("amqp_early", outcome)
|
|
STOP.wait(PERIOD_S)
|
|
|
|
def begin():
|
|
number = 0
|
|
while not STOP.is_set():
|
|
try:
|
|
sock = amqp_begin(data)
|
|
except Exception:
|
|
# новый CRL: начать больше нельзя (это меряет amqp_new)
|
|
return
|
|
threading.Thread(
|
|
target=finish,
|
|
args=(EARLY_DELAYS[number % len(EARLY_DELAYS)], sock),
|
|
daemon=True,
|
|
).start()
|
|
number += 1
|
|
STOP.wait(0.2)
|
|
|
|
threading.Thread(target=begin, daemon=True).start()
|
|
|
|
|
|
# OTLP и OpenBao ---------------------------------------------------------------
|
|
|
|
|
|
def https(host, port, *, cert=True):
|
|
connection = http.client.HTTPSConnection(
|
|
host,
|
|
port,
|
|
timeout=5,
|
|
context=context(cert),
|
|
)
|
|
connection.connect()
|
|
return connection
|
|
|
|
|
|
def otlp(connection):
|
|
connection.request(
|
|
"POST",
|
|
"/v1/traces",
|
|
"{}",
|
|
{"Content-Type": "application/json"},
|
|
)
|
|
response = connection.getresponse()
|
|
response.read()
|
|
return "ok" if response.status < 400 else f"denied:{response.status}"
|
|
|
|
|
|
def probe_otlp_new(_data):
|
|
connection = https("otel-collector", 4318)
|
|
try:
|
|
return otlp(connection)
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def bao(method_name, path, body=None, token=None):
|
|
connection = https("openbao", 8200)
|
|
try:
|
|
connection.request(
|
|
method_name,
|
|
"/v1/" + path,
|
|
None if body is None else json.dumps(body),
|
|
{"X-Vault-Token": token} if token else {},
|
|
)
|
|
response = connection.getresponse()
|
|
raw = response.read()
|
|
finally:
|
|
connection.close()
|
|
return response.status, json.loads(raw) if raw else {}
|
|
|
|
|
|
def probe_bao_login(_data):
|
|
status, _ = bao("POST", "auth/cert/login", {"name": "worker"})
|
|
return "ok" if status == 200 else f"denied:{status}"
|
|
|
|
|
|
def probe_bao_token(data):
|
|
status, _ = bao(
|
|
"GET",
|
|
"messenger/data/postgres/worker",
|
|
token=data["bao"]["token"],
|
|
)
|
|
return "ok" if status == 200 else f"denied:{status}"
|
|
|
|
|
|
# PostgreSQL ------------------------------------------------------------------
|
|
|
|
|
|
async def pg_connect(data):
|
|
import asyncpg
|
|
|
|
source = data["database"]
|
|
return await asyncpg.connect(
|
|
host=source["host"],
|
|
port=source["port"],
|
|
user=source["user"],
|
|
password=source["password"],
|
|
database=source["name"],
|
|
timeout=5,
|
|
ssl=context(cert=False),
|
|
)
|
|
|
|
|
|
class Loop:
|
|
"""Цикл событий в потоке: соединения asyncpg пробуются из потоков."""
|
|
|
|
def __init__(self):
|
|
self.loop = asyncio.new_event_loop()
|
|
threading.Thread(target=self.loop.run_forever, daemon=True).start()
|
|
|
|
def run(self, coroutine, timeout=10):
|
|
return asyncio.run_coroutine_threadsafe(
|
|
coroutine,
|
|
self.loop,
|
|
).result(timeout)
|
|
|
|
|
|
LOOP = Loop()
|
|
|
|
|
|
def probe_pg_new(data):
|
|
async def login():
|
|
connection = await pg_connect(data)
|
|
try:
|
|
await connection.fetchval("SELECT 1 FROM attachments LIMIT 1")
|
|
finally:
|
|
await connection.close(timeout=2)
|
|
|
|
LOOP.run(login())
|
|
return "ok"
|
|
|
|
|
|
# S3 ---------------------------------------------------------------------------
|
|
|
|
|
|
def s3_client(data):
|
|
import botocore.session
|
|
from botocore.config import Config
|
|
|
|
source = data["s3"]
|
|
return botocore.session.get_session().create_client(
|
|
"s3",
|
|
region_name="us-east-1",
|
|
endpoint_url=f"https://{source['host']}:{source['port']}",
|
|
verify=f"{DIR}/ca.crt",
|
|
aws_access_key_id=source["access"],
|
|
aws_secret_access_key=source["secret"],
|
|
config=Config(
|
|
connect_timeout=5,
|
|
read_timeout=5,
|
|
retries={"total_max_attempts": 1},
|
|
s3={"addressing_style": "path"},
|
|
),
|
|
)
|
|
|
|
|
|
def probe_s3(client, data):
|
|
try:
|
|
client.get_object(
|
|
Bucket=data["s3"]["bucket"],
|
|
Key=data["s3_key"],
|
|
)["Body"].read()
|
|
except Exception as error:
|
|
code = getattr(error, "response", {}).get("Error", {}).get("Code")
|
|
# отсутствующий объект под staging: ключ и право действуют
|
|
return "ok" if code == "NoSuchKey" else f"denied:{code or 'error'}"
|
|
return "ok"
|
|
|
|
|
|
# атака во время порядка: принятые после `start` задания --------------------
|
|
|
|
DAMAGE_SQL = (
|
|
"UPDATE attachments SET status = 'processing' WHERE created_at > $1 "
|
|
"AND status = 'queued'",
|
|
"UPDATE attachment_jobs SET state = 'processing', lease_expires_at = "
|
|
"'2100-01-01' WHERE created_at > $1 AND state = 'queued'",
|
|
)
|
|
|
|
|
|
def start_damage(data):
|
|
"""Порча строк и очистка очереди своими соединениями, пока их не закроют;
|
|
затем — попытки тем же материалом заново."""
|
|
|
|
def new_pg():
|
|
return LOOP.run(pg_connect(data))
|
|
|
|
state = {"pg": new_pg(), "mq": amqp_login(amqp_begin(data))}
|
|
since = LOOP.run(state["pg"].fetchval("SELECT clock_timestamp()"))
|
|
|
|
def rows():
|
|
if state["pg"].is_closed():
|
|
state["pg"] = new_pg()
|
|
|
|
async def damage():
|
|
changed = 0
|
|
async with state["pg"].transaction():
|
|
for statement in DAMAGE_SQL:
|
|
tag = await state["pg"].execute(statement, since)
|
|
changed += int(tag.split()[-1])
|
|
return changed
|
|
|
|
return f"ok:{LOOP.run(damage())}"
|
|
|
|
def queue():
|
|
if state["mq"] is None:
|
|
state["mq"] = amqp_login(amqp_begin(data))
|
|
sock, state["mq"] = state["mq"], None
|
|
name = data["queue"].encode()
|
|
sock.sendall(
|
|
method(
|
|
30,
|
|
b"\x00\x00" + bytes([len(name)]) + name + b"\x00",
|
|
channel=1,
|
|
klass=50,
|
|
),
|
|
)
|
|
if frame(sock) != (50, 31):
|
|
raise EOFError
|
|
state["mq"] = sock
|
|
return "ok"
|
|
|
|
every("damage_rows", rows)
|
|
every("damage_queue", queue)
|
|
|
|
|
|
def guarded(probe):
|
|
try:
|
|
return probe()
|
|
except Exception as error:
|
|
return failure(error)
|
|
|
|
|
|
def main():
|
|
data = json.loads(sys.stdin.readline())
|
|
os.umask(0o077)
|
|
os.makedirs(DIR, mode=0o700)
|
|
for name, text in data.pop("files").items():
|
|
with open(f"{DIR}/{name}", "w", encoding="ascii") as file:
|
|
file.write(text)
|
|
|
|
held_amqp = amqp_login(amqp_begin(data))
|
|
held_otlp = https("otel-collector", 4318)
|
|
held_pg = LOOP.run(pg_connect(data))
|
|
storage = s3_client(data)
|
|
|
|
def use_pg():
|
|
LOOP.run(
|
|
held_pg.fetchval("SELECT 1 FROM attachments LIMIT 1"),
|
|
)
|
|
return "ok"
|
|
|
|
probes = {
|
|
"amqp_new": lambda: probe_amqp_new(data),
|
|
"amqp_open": lambda: amqp_use(held_amqp, data["queue"]),
|
|
"otlp_new": lambda: probe_otlp_new(data),
|
|
"otlp_open": lambda: otlp(held_otlp),
|
|
"bao_login": lambda: probe_bao_login(data),
|
|
"bao_token": lambda: probe_bao_token(data),
|
|
"pg_new": lambda: probe_pg_new(data),
|
|
"pg_open": use_pg,
|
|
"s3_key": lambda: probe_s3(storage, data),
|
|
}
|
|
emit(ready={name: guarded(probe) for name, probe in probes.items()})
|
|
for line in sys.stdin:
|
|
mark = line.strip()
|
|
if mark == "start":
|
|
for name, probe in probes.items():
|
|
every(name, probe)
|
|
try:
|
|
start_damage(data)
|
|
early_logins(data)
|
|
except Exception as error:
|
|
report("amqp_early", failure(error))
|
|
emit(mark=mark, t=now())
|
|
if mark == "stop":
|
|
break
|
|
STOP.set()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
# соединения и потоки не дожидаются: их закрытие — не проба
|
|
sys.stdout.flush()
|
|
os._exit(0)
|