Compare commits

..
Author SHA1 Message Date
scandalist-trash b4870b401a fix(starpost): bound authentication memory 2026-10-25 10:21:50 -04:00
scandal 393e7a13f4 Merge pull request 'Exploit/starpost warehouse dos poc' (#19) from exploit/starpost-warehouse-dos-poc into main
Reviewed-on: #19
2026-10-25 16:50:46 +03:00
scandalist-trash e90414b4b8 Merge remote-tracking branch 'origin/main' into exploit/starpost-warehouse-dos-poc 2026-10-25 09:50:16 -04:00
scandalist-trash 7d52945c80 starpost: model single-checkout job amplification 2026-10-25 09:50:14 -04:00
scandal 50233c1920 Merge pull request 'starpost: add bounded warehouse fanout PoC' (#18) from exploit/starpost-warehouse-dos-poc into main
Reviewed-on: #18
2026-10-25 16:46:36 +03:00
scandalist-trash e2e5f02ac2 starpost: add bounded warehouse fanout PoC 2026-10-25 09:44:59 -04: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
11 changed files with 253 additions and 14 deletions

No files matched your search

+1
View File
@@ -7,6 +7,7 @@
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
- L-06: одновременно работают не более двух компиляций; после исчерпания слотов допускается не более восьми ожидающих запросов и не более пятнадцати секунд ожидания, а лишние запросы получают `429`. Лимит выбран по наблюдаемой очереди: восемь работ при двух слотах и трёхсекундном пределе на compile/listing укладываются примерно в двенадцать секунд, тогда как checker ограничен тридцатью секундами. HTTP pool содержит 32-64 потока и ограниченную очередь 256, чтобы compiler flood не вытеснял health и обычные API-вызовы. Keep-alive и socket timeout уменьшены. `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.
+4
View File
@@ -2,7 +2,11 @@ name: lighthouse
services:
lighthouse:
restart: unless-stopped
build: .
pids_limit: 256
mem_limit: 1g
cpus: 2.0
ports:
- "8085:8080"
volumes:
+11 -4
View File
@@ -23,12 +23,19 @@ class Slots {
std::mutex lock_;
std::condition_variable room_;
int held_ = 0;
int waiting_ = 0;
int limit_;
public:
explicit Slots(int limit) : limit_(limit) {}
void acquire() {
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_;
}
void release() {
@@ -101,7 +108,7 @@ public:
bool cc() {
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",
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
@@ -127,7 +134,7 @@ public:
fs::copy_file(module_, artifact);
result.path = artifact.string();
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",
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
@@ -140,7 +147,7 @@ public:
};
inline Artifact compile(const std::string& source) {
static Slots slots(4);
static Slots slots(2);
Slot slot(slots);
Build build(source);
recipe::run(recipe::filter, build);
+5
View File
@@ -344,6 +344,11 @@ int main() {
try {
initialize();
httplib::Server server;
server.new_task_queue = [] { return new httplib::ThreadPool(32, 64, 256); };
server.set_keep_alive_max_count(8);
server.set_keep_alive_timeout(2);
server.set_read_timeout(3, 0);
server.set_write_timeout(3, 0);
server.set_payload_max_length(32768);
server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) {
if (request.has_header("Range")) {
+1 -1
View File
@@ -5,4 +5,4 @@ COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
COPY *.py /app/
WORKDIR /app
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "4", "--bind", "0.0.0.0:5000", "app:app"]
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "2", "--bind", "0.0.0.0:5000", "app:app"]
+13 -4
View File
@@ -10,13 +10,18 @@ from functools import lru_cache, wraps
import psycopg
from flask import Flask, jsonify, request, send_file, session
from werkzeug.security import check_password_hash, generate_password_hash
from contracts import CONTRACT_DIR, create_contract
from database import CARGO_PURCHASE_WINDOW_SECONDS, 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 get_health as get_warehouse_health
from warehouse_client import submit_jobs as submit_warehouse_jobs
from passwords import hash_password, password_matches
app = Flask(__name__)
@@ -170,7 +175,7 @@ def register():
return error(str(exc))
try:
with db() as conn, conn.cursor() as cur:
cur.execute("INSERT INTO users(username,password_hash,role,company_name,tax_id) VALUES(%s,%s,%s,%s,%s) RETURNING id", (username, generate_password_hash(password), role, company, tax_id))
cur.execute("INSERT INTO users(username,password_hash,role,company_name,tax_id) VALUES(%s,%s,%s,%s,%s) RETURNING id", (username, hash_password(password), role, company, tax_id))
user_id = cur.fetchone()["id"]
if role == "seller":
cur.execute("UPDATE users SET contract_file=%s WHERE id=%s", (create_contract(user_id, company, tax_id, signature), user_id))
@@ -192,7 +197,7 @@ def login():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT * FROM users WHERE username=%s", (data.get("username"),))
user = cur.fetchone()
if not user or not isinstance(data.get("password"), str) or not check_password_hash(user["password_hash"], data["password"]):
if not user or not isinstance(data.get("password"), str) or not password_matches(user["password_hash"], data["password"]):
return error("invalid credentials", 401)
session.clear()
session.update(user_id=user["id"], username=user["username"], role=user["role"])
@@ -526,6 +531,7 @@ def create_order(cur, buyer_id, product_id, price, tracking, buyer_created_at, p
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,
@@ -534,6 +540,9 @@ def create_order(cur, buyer_id, product_id, price, tracking, buyer_created_at, p
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,
),
+4 -2
View File
@@ -5,7 +5,9 @@ from psycopg.rows import dict_row
DATABASE_URL = os.environ["DATABASE_URL"]
CARGO_PURCHASE_WINDOW_SECONDS = 2
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS = 3
CARGO_PURCHASE_WINDOW_SECONDS = 5
LEGACY_CARGO_PURCHASE_WINDOW_SECONDS = 2
def connect():
@@ -34,7 +36,7 @@ def migrate():
"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",
(CARGO_PURCHASE_WINDOW_SECONDS,),
(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")
+16
View File
@@ -0,0 +1,16 @@
from werkzeug.security import check_password_hash, generate_password_hash
# Werkzeug's default scrypt hash needs about 32 MiB of working memory per
# concurrent request. The API serves up to four authentication requests at a
# time, so use a CPU-bound hash for new accounts while retaining verification
# support for existing scrypt hashes.
PASSWORD_HASH_METHOD = "pbkdf2:sha256:600000"
def hash_password(password):
return generate_password_hash(password, method=PASSWORD_HASH_METHOD)
def password_matches(password_hash, password):
return check_password_hash(password_hash, password)
+3 -3
View File
@@ -44,7 +44,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Minimal patch
- Emergency cargo containment records a `cargo_entitled` decision on every new order. The entitlement requires the buyer account to be created after the product and the order transaction to start within two seconds of product creation. In 62 observed checker-like flows the checker created a new buyer after the product and purchased after 0.232-0.563 seconds. A live purchase correlated with the reported theft used a buyer created roughly 124 seconds before the product, so an equivalent order created after deployment retains the normal delivered response but receives `cargo=null`. Both direct buy and checkout use the same order helper. Existing orders are backfilled with the previous two-second rule so their current/get-old behavior does not change. This is containment against pre-staged buyers, not a durable authorization boundary: an attacker that registers after publication can still race the checker.
- 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.
- 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.
@@ -53,7 +53,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Checker and SLA invariants
- Existing orders retain their previous cargo visibility after migration. New checker orders whose buyer was created after the product and whose order transaction began inside the two-second window continue to reveal cargo after delivery and on later get-old checks. Entitlement is stored 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 contract filenames and files are not renamed or migrated.
- Existing promo rows receive `credited_at=NULL` and remain redeemable once.
@@ -69,7 +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.
- 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.
- Cargo entitlement regression: a disposable PostgreSQL 16 and patched Flask API matrix preserved a legacy delivered order through migration, returned `cargo=null` for a new order from a pre-staged buyer, preserved cargo for a new buyer through both direct buy and checkout, and preserved get-old. Only synthetic non-flag markers were used.
- 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.
- `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.
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
from werkzeug.security import generate_password_hash
API_DIR = Path(__file__).resolve().parents[1] / "api"
sys.path.insert(0, str(API_DIR))
from passwords import hash_password, password_matches # noqa: E402
def main():
password = "correct horse battery staple"
current_hash = hash_password(password)
assert current_hash.startswith("pbkdf2:sha256:600000$")
assert password_matches(current_hash, password)
assert not password_matches(current_hash, password + "!")
legacy_hash = generate_password_hash(password, method="scrypt:32768:8:1")
assert password_matches(legacy_hash, password)
assert not password_matches(legacy_hash, password + "!")
print("password hash compatibility: ok")
if __name__ == "__main__":
main()
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
import importlib
import importlib.util
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType, SimpleNamespace
TOKEN = "synthetic-local-token"
CART_ITEMS = 20
QUANTITY = 10
def load_modules():
root = Path(__file__).resolve().parents[1]
os.environ["DATABASE_URL"] = "postgresql://unused"
os.environ["SECRET_KEY"] = "synthetic-local-session-key"
os.environ["WAREHOUSE_URL"] = "http://127.0.0.1:9"
os.environ["WAREHOUSE_API_URL"] = "http://127.0.0.1:9"
os.environ["WAREHOUSE_CALLBACK_TOKEN"] = TOKEN
api_dir = root / "api"
sys.path.insert(0, str(api_dir))
contracts = ModuleType("contracts")
contracts.CONTRACT_DIR = root / "contracts"
contracts.create_contract = lambda *args: "synthetic.pdf"
sys.modules["contracts"] = contracts
database = importlib.import_module("database")
database.migrate = lambda: None
api = importlib.import_module("app")
worker_path = root / "warehouse" / "worker.py"
spec = importlib.util.spec_from_file_location("starpost_warehouse_poc", worker_path)
if spec is None or spec.loader is None:
raise RuntimeError("cannot load warehouse worker")
worker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(worker)
return api, worker
class FakeCursor:
def __init__(self):
timestamp = datetime.now(timezone.utc)
self.buyer = {"balance": CART_ITEMS * QUANTITY, "buyer_created_at": timestamp}
self.items = [
{
"product_id": product_id,
"seller_id": 1000 + product_id,
"price": 1,
"is_active": True,
"product_created_at": timestamp,
"quantity": QUANTITY,
}
for product_id in range(1, CART_ITEMS + 1)
]
self.one = None
self.many = []
self.order_id = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc, traceback):
return False
def execute(self, query, parameters=()):
normalized = " ".join(query.split())
self.one = None
self.many = []
if normalized.startswith("SELECT balance,created_at buyer_created_at"):
self.one = self.buyer
elif normalized.startswith("SELECT p.id product_id"):
self.many = self.items
elif normalized.startswith("INSERT INTO orders"):
self.order_id += 1
self.one = {"id": self.order_id}
def fetchone(self):
return self.one
def fetchall(self):
return self.many
class FakeConnection:
def __init__(self):
self.fake_cursor = FakeCursor()
def __enter__(self):
return self
def __exit__(self, exc_type, exc, traceback):
return False
def cursor(self):
return self.fake_cursor
def main():
api, worker = load_modules()
starts = []
class FakeThread:
def __init__(self, target, args, daemon):
self.target = target
self.args = args
self.daemon = daemon
def start(self):
starts.append((self.target, self.args, self.daemon))
worker.threading = SimpleNamespace(Thread=FakeThread)
warehouse = worker.app.test_client()
internal_statuses = []
def submit_jobs(orders):
for order in orders:
response = warehouse.post(
"/jobs",
json={"order_id": order["id"]},
headers={"X-Warehouse-Token": TOKEN},
)
internal_statuses.append(response.status_code)
api.db = lambda: FakeConnection()
api.submit_warehouse_jobs = submit_jobs
api.app.config.update(TESTING=True)
client = api.app.test_client()
with client.session_transaction() as session:
session.update(user_id=1, username="synthetic", role="buyer")
response = client.post("/api/cart/checkout", json={})
document = response.get_json(silent=True) or {}
orders = document.get("orders", [])
result = {
"external_checkout_requests": 1,
"prepared_cart_items": CART_ITEMS,
"orders_created": len(orders),
"internal_jobs_accepted": internal_statuses.count(202),
"jobs_retained": len(worker.jobs),
"worker_threads_started": len(starts),
"compose_pid_limit": 128,
"checkout_status": response.status_code,
}
print(json.dumps(result, sort_keys=True))
expected = CART_ITEMS * QUANTITY
if response.status_code != 201 or len(orders) != expected:
return 1
if result["internal_jobs_accepted"] != expected:
return 1
if result["jobs_retained"] != expected or result["worker_threads_started"] != expected:
return 1
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as error:
print(f"error: {error}", file=sys.stderr)
raise SystemExit(1)