- track the authenticated session TMSI from server responses - return empty frames for every cross-subscriber read variant
152 lines
5.2 KiB
Python
Executable File
152 lines
5.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import asyncio
|
|
import contextlib
|
|
import os
|
|
|
|
HEADER_SIZE = 16
|
|
READ_OPCODES = frozenset((0x21, 0x23))
|
|
SUBSCRIBER_TAG = 0x0B
|
|
HANDOVER_PREPARE = 0x40
|
|
HANDOVER_FINISH = frozenset((0x41, 0x42))
|
|
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 tlvs(frame: bytes) -> list[tuple[int, bytes]]:
|
|
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")
|
|
payload = frame[HEADER_SIZE:]
|
|
values: list[tuple[int, bytes]] = []
|
|
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")
|
|
values.append((tag, payload[offset : offset + size]))
|
|
offset += size
|
|
return values
|
|
|
|
|
|
def tlv_tags(frame: bytes) -> list[int]:
|
|
return [tag for tag, _ in tlvs(frame)]
|
|
|
|
|
|
def should_block(frame: bytes) -> bool:
|
|
return frame[3] in READ_OPCODES and tlv_tags(frame).count(SUBSCRIBER_TAG) > 1
|
|
|
|
|
|
def empty_response(frame: bytes) -> bytes:
|
|
return frame[:14] + b"\0\0"
|
|
|
|
|
|
|
|
class ConnectionGuard:
|
|
def __init__(self) -> None:
|
|
self.handover_pending = False
|
|
self.own_tmsi: int | None = None
|
|
|
|
def observe_server(self, frame: bytes) -> None:
|
|
if frame[3] not in (0x02, 0x04, 0x41):
|
|
return
|
|
for tag, value in tlvs(frame):
|
|
if tag == 0x09 and len(value) == 4:
|
|
self.own_tmsi = int.from_bytes(value, "little")
|
|
return
|
|
|
|
def should_block(self, frame: bytes) -> bool:
|
|
opcode = frame[3]
|
|
fields = tlvs(frame)
|
|
selectors = [value for tag, value in fields if tag == SUBSCRIBER_TAG]
|
|
if opcode in READ_OPCODES and len(selectors) > 1:
|
|
return True
|
|
if opcode in READ_OPCODES and selectors and self.own_tmsi is not None:
|
|
selector = selectors[0]
|
|
if len(selector) != 8 or int.from_bytes(selector[:4], "little") != self.own_tmsi:
|
|
return True
|
|
if opcode == HANDOVER_PREPARE and selectors:
|
|
self.handover_pending = True
|
|
return False
|
|
if opcode in HANDOVER_FINISH:
|
|
self.handover_pending = False
|
|
return False
|
|
return self.handover_pending and opcode in READ_OPCODES and bool(selectors)
|
|
|
|
async def client_frames(
|
|
reader: asyncio.StreamReader,
|
|
backend_writer: asyncio.StreamWriter,
|
|
client_writer: asyncio.StreamWriter,
|
|
guard: ConnectionGuard,
|
|
) -> 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 guard.should_block(frame):
|
|
client_writer.write(empty_response(frame))
|
|
await client_writer.drain()
|
|
continue
|
|
backend_writer.write(frame)
|
|
await backend_writer.drain()
|
|
|
|
|
|
async def server_frames(
|
|
reader: asyncio.StreamReader,
|
|
writer: asyncio.StreamWriter,
|
|
guard: ConnectionGuard,
|
|
) -> 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
|
|
guard.observe_server(frame)
|
|
writer.write(frame)
|
|
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)
|
|
guard = ConnectionGuard()
|
|
upstream = asyncio.create_task(client_frames(client_reader, backend_writer, client_writer, guard))
|
|
downstream = asyncio.create_task(server_frames(backend_reader, client_writer, guard))
|
|
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())
|