starpost: rotate secrets and close data leaks
This commit is contained in:
1 parent
4f70df55dd
commit
22c1906a67
11 files changed
+725
-61
No files matched your search
@@ -0,0 +1,3 @@
|
||||
STARPOST_DB_PASSWORD=replace-with-url-safe-random-value
|
||||
STARPOST_SECRET_KEY=replace-with-at-least-32-random-bytes
|
||||
STARPOST_WAREHOUSE_CALLBACK_TOKEN=replace-with-at-least-32-random-bytes
|
||||
+41
-54
@@ -2,12 +2,10 @@ import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json as _json
|
||||
import mimetypes
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from flask import Flask, jsonify, request, send_file, session
|
||||
@@ -268,10 +266,21 @@ def credit_promo():
|
||||
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||
return error("invalid promo code")
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
||||
cur.execute(
|
||||
"UPDATE promo_codes SET credited_at=now() "
|
||||
"WHERE user_id=%s AND code=%s AND credited_at IS NULL RETURNING amount",
|
||||
(session["user_id"], code.strip()),
|
||||
)
|
||||
promo = cur.fetchone()
|
||||
if not promo:
|
||||
return error("promo code is unavailable", 409)
|
||||
cur.execute(
|
||||
"SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s",
|
||||
(session["user_id"], code.strip()),
|
||||
)
|
||||
promo = cur.fetchone()
|
||||
if not promo:
|
||||
return error("promo code is unavailable", 409)
|
||||
return jsonify(credited=0, code=code.strip())
|
||||
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"]))
|
||||
return jsonify(credited=promo["amount"], code=code.strip())
|
||||
|
||||
@@ -614,13 +623,7 @@ def seller_reviews():
|
||||
p = _b64e(_json.dumps(state, separators=(",", ":")).encode())
|
||||
return f"{p}.{_sign(p)}"
|
||||
|
||||
def _parse_cursor(cur_token: str, lim_raw):
|
||||
try:
|
||||
lim = int(lim_raw) if lim_raw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
lim = None
|
||||
if lim is not None and lim <= 3:
|
||||
return _json.loads(_b64d(cur_token.split(".")[0]).decode())
|
||||
def _parse_cursor(cur_token: str):
|
||||
if "." not in cur_token:
|
||||
raise ValueError("missing signature")
|
||||
payload_b64, sig = cur_token.rsplit(".", 1)
|
||||
@@ -639,13 +642,15 @@ def seller_reviews():
|
||||
|
||||
if cursor:
|
||||
try:
|
||||
state = _parse_cursor(cursor, limit_raw)
|
||||
state = _parse_cursor(cursor)
|
||||
except Exception as exc:
|
||||
return error(f"invalid cursor: {exc}", 400)
|
||||
try:
|
||||
q_seller = int(state["seller_id"])
|
||||
q_private = bool(state["is_private"])
|
||||
q_private = state["is_private"]
|
||||
q_last = int(state["last_id"])
|
||||
if q_seller != session["user_id"] or not isinstance(q_private, bool):
|
||||
raise ValueError
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return error("invalid cursor payload", 400)
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
@@ -686,55 +691,37 @@ def seller_reviews():
|
||||
@app.route("/api/contract", methods=["GET", "POST"])
|
||||
@auth("seller")
|
||||
def get_contract():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (session["user_id"],))
|
||||
owner = cur.fetchone()
|
||||
if not owner or not owner["contract_file"]:
|
||||
return error("contract not found", 404)
|
||||
|
||||
filename = owner["contract_file"]
|
||||
contract_dir = CONTRACT_DIR.resolve()
|
||||
path = (CONTRACT_DIR / filename).resolve()
|
||||
if path.parent != contract_dir:
|
||||
return error("contract not found", 404)
|
||||
|
||||
if request.method == "POST":
|
||||
import re
|
||||
contract_id = request.headers.get("X-Contract-Id", "").strip()
|
||||
if not re.fullmatch(r"\d+", contract_id):
|
||||
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(owner["id"]):
|
||||
return error("invalid contract id", 400)
|
||||
_dir = CONTRACT_DIR.resolve()
|
||||
hits = sorted(CONTRACT_DIR.glob(f"contract-{contract_id}-*.pdf"))
|
||||
deleted = 0
|
||||
for path in hits:
|
||||
try:
|
||||
if path.resolve().parent == _dir:
|
||||
path.unlink()
|
||||
deleted += 1
|
||||
except OSError:
|
||||
continue
|
||||
if deleted == 0:
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
return error("contract not found", 404)
|
||||
return jsonify(status="deleted", deleted=deleted)
|
||||
except OSError:
|
||||
return error("contract deletion failed", 500)
|
||||
return jsonify(status="deleted", deleted=1)
|
||||
|
||||
requested = request.args.get("file")
|
||||
|
||||
if requested:
|
||||
import re
|
||||
m = re.match(r"^\s*contract-(\d+)", requested)
|
||||
if m:
|
||||
uid = m.group(1)
|
||||
hits = sorted(CONTRACT_DIR.glob(f"contract-{uid}-*.pdf"))
|
||||
if hits:
|
||||
return send_file(hits[0], mimetype="application/pdf", download_name=hits[0].name)
|
||||
return error("contract not found", 404)
|
||||
raw = requested.strip()
|
||||
candidates: list[Path] = []
|
||||
candidates.append((CONTRACT_DIR / raw).resolve())
|
||||
candidates.append(Path(raw).resolve())
|
||||
candidates.append(CONTRACT_DIR / raw)
|
||||
candidates.append(Path(raw))
|
||||
for target in candidates:
|
||||
try:
|
||||
if target.is_file():
|
||||
guessed, _ = mimetypes.guess_type(str(target))
|
||||
return send_file(target, mimetype=guessed or "application/octet-stream", download_name=target.name)
|
||||
except ValueError:
|
||||
continue
|
||||
return error("contract not found", 404)
|
||||
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT contract_file FROM users WHERE id=%s", (session["user_id"],))
|
||||
filename = cur.fetchone()["contract_file"]
|
||||
path = CONTRACT_DIR / filename
|
||||
if raw not in {filename, f"contract-{owner['id']}"}:
|
||||
return error("contract not found", 404)
|
||||
if not path.is_file():
|
||||
return error("contract not found", 404)
|
||||
return send_file(path, mimetype="application/pdf", download_name="starpost-contract.pdf")
|
||||
download_name = path.name if requested else "starpost-contract.pdf"
|
||||
return send_file(path, mimetype="application/pdf", download_name=download_name)
|
||||
@@ -52,8 +52,8 @@ def migrate():
|
||||
"""
|
||||
)
|
||||
cursor.execute("ALTER TABLE promo_codes ALTER COLUMN amount SET DEFAULT 100")
|
||||
cursor.execute("ALTER TABLE promo_codes ADD COLUMN IF NOT EXISTS credited_at TIMESTAMPTZ")
|
||||
cursor.execute("ALTER TABLE users ALTER COLUMN balance SET DEFAULT 100")
|
||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS credited_at")
|
||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS invalidated_at")
|
||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS created_at")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)")
|
||||
|
||||
@@ -22,10 +22,10 @@ services:
|
||||
volumes:
|
||||
- ./contracts:/contracts
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://starpost:starpost@postgres/starpost
|
||||
- SECRET_KEY=starpost-development-session-key-change-before-production
|
||||
- DATABASE_URL=postgresql://starpost:${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}@postgres/starpost
|
||||
- SECRET_KEY=${STARPOST_SECRET_KEY:?STARPOST_SECRET_KEY is required}
|
||||
- WAREHOUSE_URL=http://warehouse:6000
|
||||
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token
|
||||
- WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -43,7 +43,7 @@ services:
|
||||
cpus: 0.25
|
||||
environment:
|
||||
- WAREHOUSE_API_URL=http://api:5000
|
||||
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token
|
||||
- WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
@@ -62,7 +62,7 @@ services:
|
||||
environment:
|
||||
- POSTGRES_DB=starpost
|
||||
- POSTGRES_USER=starpost
|
||||
- POSTGRES_PASSWORD=starpost
|
||||
- POSTGRES_PASSWORD=${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}
|
||||
volumes:
|
||||
- ./postgres:/var/lib/postgresql/data
|
||||
- ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
|
||||
|
||||
@@ -54,5 +54,6 @@ CREATE TABLE promo_codes (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
code TEXT NOT NULL UNIQUE,
|
||||
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100)
|
||||
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100),
|
||||
credited_at TIMESTAMPTZ
|
||||
);
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main() -> int:
|
||||
target = Path(__file__).resolve().with_name(".env")
|
||||
values = {
|
||||
"STARPOST_DB_PASSWORD": secrets.token_urlsafe(48),
|
||||
"STARPOST_SECRET_KEY": secrets.token_urlsafe(48),
|
||||
"STARPOST_WAREHOUSE_CALLBACK_TOKEN": secrets.token_urlsafe(48),
|
||||
}
|
||||
try:
|
||||
descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
except FileExistsError:
|
||||
print(f"refusing to overwrite existing {target}", file=sys.stderr)
|
||||
return 1
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
|
||||
for key, value in values.items():
|
||||
output.write(f"{key}={value}\n")
|
||||
os.chmod(target, 0o600)
|
||||
print(f"created {target} with mode 0600")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,80 @@
|
||||
# Starpost handoff — 2026-10-25
|
||||
|
||||
## Confirmed vulnerabilities
|
||||
|
||||
### Cross-seller review cursor BOLA
|
||||
|
||||
Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies.
|
||||
|
||||
The local baseline reproducer used synthetic seller IDs and a synthetic private-review marker. The endpoint returned HTTP 200 and disclosed the marker. The flag route before the patch is a checker-created private review body returned through the forged cursor; no real flag was used.
|
||||
|
||||
### Contract IDOR, arbitrary file read, and cross-seller deletion
|
||||
|
||||
Before the patch, a seller could request `GET /api/contract?file=contract-<other-id>` to receive another seller's PDF. Other absolute or relative `file` values were resolved as filesystem paths and returned when readable. `POST /api/contract` similarly accepted another seller's numeric `X-Contract-Id` and deleted matching PDFs.
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
The local baseline reproducer started with a synthetic balance of 100 and two identical credit requests both returned HTTP 200, leaving a synthetic balance of 300. This permits unauthorized value creation and can fund purchases of checker-created cargo.
|
||||
|
||||
## Affected code before the patch
|
||||
|
||||
- `api/app.py`: `seller_reviews`, `get_contract`, and `credit_promo`.
|
||||
- `api/database.py`: startup migration removed promo consumption state.
|
||||
- `db/init.sql`: `promo_codes` had no consumption field.
|
||||
|
||||
## Minimal patch
|
||||
|
||||
- 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.
|
||||
- `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.
|
||||
- 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
|
||||
|
||||
- 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.
|
||||
- The normal buyer flow remains `credit -> invalidate`; buy, checkout, warehouse delivery, orders, and reviews are unchanged.
|
||||
- No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers.
|
||||
|
||||
## Verification
|
||||
|
||||
- Baseline synthetic results: unsigned cursor, cross-seller contract lookup, controlled external-file read, and promo replay reproduced.
|
||||
- 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.
|
||||
- Own mutation: deleting the authenticated seller's disposable contract still returned 200 and removed only that file.
|
||||
- Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once.
|
||||
- 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.
|
||||
- `sploits/starpost.py` and `sploits/starpost_warehouse.py` pass the GO CTF static sploit checker. Minimal tests on the team vulnbox confirmed the issued Flask key and warehouse token were accepted; full outputs and any flag-like values were suppressed.
|
||||
- The three exploit jobs completed against the team service in under one second each during bounded validation; no real flag value was printed or stored in the repository.
|
||||
|
||||
## Sploit handoff
|
||||
|
||||
- Path: `sploits/starpost_contract.py`
|
||||
- Stable Neo ID: `starpost-contract-idor-v1`
|
||||
- Timeout: `10s`
|
||||
- Input: one authorized target address; HTTP port 8090 is selected when no port is supplied.
|
||||
- Primitive: self-register a seller, enumerate a bounded window of recent numeric user IDs, request the vulnerable own-contract alias for each ID, and emit only strings matching the event flag format.
|
||||
|
||||
- Path: `sploits/starpost.py`
|
||||
- Stable Neo ID: `starpost-session-v1`
|
||||
- Timeout: `10s`
|
||||
- Primitive: use only the issued Flask session key to forge recent buyer/seller sessions and read their protected objects.
|
||||
|
||||
- Path: `sploits/starpost_warehouse.py`
|
||||
- Stable Neo ID: `starpost-warehouse-v1`
|
||||
- Timeout: `10s`
|
||||
- Primitive: use only the issued warehouse token as leaked configuration; create a normal buyer session, reuse the vulnerable promo, purchase recent products, force delivery, and read cargo.
|
||||
|
||||
## 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.
|
||||
- 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.
|
||||
- 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.
|
||||
Reference in new issue
Block a user