Files
mctf/towercore/guard.py
T
TakuyaYagam1 ea9f241058 fix(towercore): block cross-subscriber bulk reads
- Proxy TowerCore frames and reject opcode 0x23 requests containing subscriber selectors.
- Preserve checker bulk reads that address authenticated message IDs.
2026-11-29 15:24:45 +03:00

92 lines
3.2 KiB
Python
Executable File

#!/usr/bin/env python3
import asyncio
import contextlib
import os
HEADER_SIZE = 16
BULK_READ_OPCODE = 0x23
SUBSCRIBER_TAG = 0x0B
BACKEND_HOST = os.environ.get("BACKEND_HOST", "towercore")
BACKEND_PORT = int(os.environ.get("BACKEND_PORT", "7250"))
LISTEN_PORT = int(os.environ.get("LISTEN_PORT", "7250"))
def tlv_tags(payload: bytes) -> set[int]:
tags: set[int] = set()
offset = 0
while offset < len(payload):
if len(payload) - offset < 4:
raise ValueError("truncated TLV header")
tag = int.from_bytes(payload[offset : offset + 2], "little")
size = int.from_bytes(payload[offset + 2 : offset + 4], "little")
offset += 4
if size > len(payload) - offset:
raise ValueError("truncated TLV value")
tags.add(tag)
offset += size
return tags
def should_block(frame: bytes) -> bool:
if len(frame) < HEADER_SIZE or frame[:2] != b"LT":
raise ValueError("invalid frame header")
payload_size = int.from_bytes(frame[14:16], "little")
if len(frame) != HEADER_SIZE + payload_size:
raise ValueError("invalid frame length")
return frame[3] == BULK_READ_OPCODE and SUBSCRIBER_TAG in tlv_tags(frame[HEADER_SIZE:])
async def client_frames(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
while True:
header = await reader.readexactly(HEADER_SIZE)
payload_size = int.from_bytes(header[14:16], "little")
payload = await reader.readexactly(payload_size)
frame = header + payload
if should_block(frame):
return
writer.write(frame)
await writer.drain()
async def copy_stream(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
while data := await reader.read(65536):
writer.write(data)
await writer.drain()
async def handle_client(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter) -> None:
backend_writer = None
try:
backend_reader, backend_writer = await asyncio.open_connection(BACKEND_HOST, BACKEND_PORT)
upstream = asyncio.create_task(client_frames(client_reader, backend_writer))
downstream = asyncio.create_task(copy_stream(backend_reader, client_writer))
done, pending = await asyncio.wait((upstream, downstream), return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
for task in done:
with contextlib.suppress(asyncio.IncompleteReadError, ConnectionError, ValueError):
task.result()
if pending:
await asyncio.gather(*pending, return_exceptions=True)
except (ConnectionError, OSError):
pass
finally:
client_writer.close()
with contextlib.suppress(Exception):
await client_writer.wait_closed()
if backend_writer is not None:
backend_writer.close()
with contextlib.suppress(Exception):
await backend_writer.wait_closed()
async def main() -> None:
server = await asyncio.start_server(handle_client, "0.0.0.0", LISTEN_PORT)
async with server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())