diff --git a/AGENTS.md b/AGENTS.md index 62aeb59..290378d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,7 @@ Challenge corpus: `tests/fixtures/challenge/` is the single interstitial fixture ## Safety - SSRF: localhost/domain checks + blocked IP classes (loopback/private/link-local/multicast/reserved/unspecified) in `app/security/`. Do not weaken without explicit request + docs/tests. +- In-browser egress: `UrlGuard.resolve_host` is the single policy owner. `app/security/egress_proxy.py` applies it to every Chromium and request-tier connection, connecting to the IP it checked (pinned DNS). Drivers come only from `create_driver_from_fingerprint`, which binds the listener; `close_driver` releases it. Never pass `proxy=` to Botasaurus, and never drop `--proxy-bypass-list=<-loopback>`. ## Performance diff --git a/README.md b/README.md index 9e87224..e95cfed 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ Request options (contract): - `window_size`: viewport object `{ "width": 1920, "height": 1080 }` passed to driver. - `lang`: browser language passed to driver (for example `en-US`). - `headless`: pass headless browser mode to driver. Default `false`. -- `proxy`: proxy URL passed to driver. Invalid or blocked proxy URLs are rejected by SSRF guardrails. +- `proxy`: upstream `http://` proxy URL (credentials allowed) for the browser and request tiers, chained behind the service's egress guard. Invalid or blocked proxy URLs are rejected by SSRF guardrails. Success response (`ScrapeSuccess`, HTTP 200): @@ -318,13 +318,23 @@ Blocked targets include: - `localhost` and `*.localhost` - loopback addresses -- private network ranges +- private network ranges, including CGNAT shared space `100.64.0.0/10` - link-local addresses - multicast, reserved, and unspecified addresses Exception: -- IPv6 NAT64 well-known prefix `64:ff9b::/96` is allowed. +- IPv6 NAT64 well-known prefix `64:ff9b::/96` is allowed when the embedded IPv4 address is public. IPv4-mapped IPv6 (`::ffff:a.b.c.d`) is judged by its IPv4 address. + +The same policy also runs inside the browser and the request tier, not only on the input URL. Each Chromium driver (warm spares included) and each request-tier call sends all traffic through its own loopback egress proxy. That covers navigations, redirects, sub-resources, XHR/fetch, iframes and websockets. The proxy resolves each destination once, refuses blocked addresses, and connects to the exact IP it checked, so DNS rebinding cannot switch a host to a private address after the check. Chromium runs with `--proxy-bypass-list=<-loopback>` and `--disable-quic`. Each profile is seeded with the WebRTC preference `disable_non_proxied_udp`, because the matching command-line flag is ignored by the bundled Chromium. WebRTC then gathers no candidates, so it can neither send UDP to a page-chosen STUN address nor reveal the host IP. No traffic skips the proxy. + +- A refused sub-request is dropped and logged as `egress_blocked` (`dest_host`, `dest_port`, `reason`, plus the scrape's `request_id` and `host`). Each host is logged once per navigation attempt, and repeats are only counted. The page still succeeds. +- When anything was refused or failed, each egress proxy logs one `egress_summary` as it closes. The fields are `lookups`, `blocked_connections`, `blocked_unrecorded` (hosts beyond the 1024-host ledger), `dns_timeouts`, `dns_failures`, `connect_failures`, `upstream_refused`, `upstream_status` (for example `407` or `402` from a residential gateway), `upstream_configured`, `request_id` and `host`. The level is `WARNING` when the upstream refused a tunnel or DNS timed out, and `INFO` otherwise. +- A refused main-frame navigation or redirect returns `403` with `error_category: validation`, the same as the pre-check. Only hosts in the page's own navigation chain count. In the browser that is the target plus its redirect hops, taken from CDP. The request tier only follows the redirect chain, so any refusal there counts. Blocks count per navigation attempt, so a sub-request refused on an earlier retry cannot turn a later failure into a 403. +- A request `proxy` becomes the egress proxy's upstream. The proxy host is resolved and pinned the same way, and its credentials are sent as `Proxy-Authorization`. Each destination is still resolved and checked locally first, so a blocked host is refused and a host the service cannot resolve fails even if the upstream could resolve it. After the check, the upstream receives the hostname (`CONNECT host:port`, or an absolute-form URL with the original authority) and resolves it on its own network. Our private network is not reachable from there. TLS-inspecting upstreams need the name (they also need their CA trusted, which this service does not do), and geo-routed CDNs then pick the edge nearest the exit node. Only `http://` upstream proxies are supported. +- Each egress proxy resolves a host once per scrape and reuses that checked answer for the page's later connections. It holds at most 4 lookups on the shared DNS pool at once, counted until the lookup thread returns. A page that floods slow DNS names therefore stalls only its own scrape. + +Host-level egress filtering of the container network is out of scope. ## Isolation Guarantee diff --git a/app/domain/scrape_service.py b/app/domain/scrape_service.py index 382393d..73c4158 100644 --- a/app/domain/scrape_service.py +++ b/app/domain/scrape_service.py @@ -101,6 +101,17 @@ def _emit_scrape_finished( ) +def _engine_status(result: ScrapeSuccess | ScrapeError) -> int: + """HTTP status for an engine result. + + The engine's only ``validation`` error is the egress guard refusing the + page's own navigation, which is the same SSRF contract as the pre-check. + """ + if isinstance(result, ScrapeSuccess): + return 200 + return 403 if result.error_category == ErrorCategory.VALIDATION else 502 + + def _finish_outcome( *, payload: ScrapeRequest, @@ -287,7 +298,7 @@ async def _run( payload=payload, host=host, body=result, - status_code=200 if isinstance(result, ScrapeSuccess) else 502, + status_code=_engine_status(result), lease=lease, started_monotonic=started_monotonic, ) diff --git a/app/engine/browser_tier.py b/app/engine/browser_tier.py index bb64e0b..bcf9202 100644 --- a/app/engine/browser_tier.py +++ b/app/engine/browser_tier.py @@ -37,7 +37,13 @@ from app.logging_config import get_logger, log_event from app.schemas.enums import ErrorCategory, ExecutionTier, NavigationMode, TimeoutPhase from app.schemas.request import ScrapeRequest -from app.schemas.response import ScrapeError, ScrapeSuccess, XhrResponse +from app.schemas.response import ( + ScrapeError, + ScrapeSuccess, + XhrResponse, + validation_error, +) +from app.security.egress_proxy import EgressListener, driver_listener logger = get_logger() @@ -93,6 +99,21 @@ def settle_page_state( return html, meta, assessment, xhr_responses +def _egress_block( + listener: EgressListener | None, + collector: XhrCollector, + target_url: str, + request_id: str, +) -> ScrapeError | None: + """Map a refused hop of the main-frame navigation chain to the SSRF error.""" + if listener is None: + return None + reason = listener.main_frame_block(collector.main_frame_hosts) + if reason is None: + return None + return validation_error(target_url, reason, request_id=request_id) + + def _inspect_assessment( driver: DriverProtocol, collector: XhrCollector ) -> ChallengeAssessment | None: @@ -355,8 +376,16 @@ def run_browser_tier( execution_tier=ExecutionTier.BROWSER_DRIVER, ) + listener = driver_listener(driver) + if listener is not None: + # A warm spare's listener was built outside this request's context. + listener.attach_request() for attempt_index, strategy in enumerate(strategies, start=1): attempts = attempt_index + if listener is not None: + # Blocks are attributed per attempt: an earlier attempt's refused + # sub-request must not turn a later failure into an SSRF error. + listener.clear_blocked() has_more = attempt_index < len(strategies) lease.mark( TimeoutPhase.WORK, @@ -377,6 +406,10 @@ def run_browser_tier( ) try: navigate(driver, target_url, strategy, step_budget) + if ( + blocked := _egress_block(listener, collector, target_url, request_id) + ) is not None: + return blocked mid_wait = wait_for_readiness( driver, selector=payload.wait_for_selector, @@ -437,6 +470,10 @@ def run_browser_tier( attempt=attempt_index, error=str(exc), ) + if ( + blocked := _egress_block(listener, collector, target_url, request_id) + ) is not None: + return blocked assessment = _inspect_assessment(driver, collector) if assessment is None or not assessment.is_clean: return _surface_unclean( diff --git a/app/engine/driver_protocol.py b/app/engine/driver_protocol.py index 0a57dbe..9d0f06d 100644 --- a/app/engine/driver_protocol.py +++ b/app/engine/driver_protocol.py @@ -8,6 +8,7 @@ from typing import Any, Protocol from app.logging_config import get_logger, log_event +from app.security.egress_proxy import release_driver logger = get_logger() @@ -94,3 +95,5 @@ def close_driver(driver: DriverProtocol) -> None: driver.close() except Exception as exc: log_event(logger, logging.WARNING, "driver_close_failed", error=str(exc)) + finally: + release_driver(driver) diff --git a/app/engine/request_tier.py b/app/engine/request_tier.py index f7982d0..52b6400 100644 --- a/app/engine/request_tier.py +++ b/app/engine/request_tier.py @@ -17,7 +17,8 @@ from app.logging_config import get_logger, log_event from app.schemas.enums import ErrorCategory, ExecutionMode, ExecutionTier, TimeoutPhase from app.schemas.request import ScrapeRequest -from app.schemas.response import ScrapeError, ScrapeSuccess +from app.schemas.response import ScrapeError, ScrapeSuccess, validation_error +from app.security.egress_proxy import EgressListener logger = get_logger() @@ -25,6 +26,18 @@ from botasaurus.request import HttpResponse +def _redirect_chain_block( + listener: EgressListener, target_url: str, request_id: str +) -> ScrapeError | None: + """The request tier fetches only the redirect chain, so any block is SSRF.""" + blocked = listener.blocked + if not blocked: + return None + return validation_error( + target_url, next(reversed(blocked.values())), request_id=request_id + ) + + def run_request_tier( payload: ScrapeRequest, request_id: str, @@ -61,21 +74,37 @@ def run_request_tier( ) req_headers = dict(payload.headers) if payload.headers else {} - proxies = {"http": payload.proxy, "https": payload.proxy} if payload.proxy else None + # Every hop (redirects included) goes through a per-call egress listener + # that pins DNS and refuses blocked addresses; payload.proxy is its upstream. + listener = EgressListener(payload.proxy) + proxies = {"http": listener.url, "https": listener.url} - req = Request() + req: Request | None = None resp: HttpResponse | None = None try: - resp = req.get( - target_url, - headers=req_headers if req_headers else None, - cookies=payload.cookies, - user_agent=payload.effective_user_agent, - proxies=proxies, - timeout=remaining_budget, - browser="chrome", - allow_redirects=True, - ) + req = Request() + try: + resp = req.get( + target_url, + headers=req_headers if req_headers else None, + cookies=payload.cookies, + user_agent=payload.effective_user_agent, + proxies=proxies, + timeout=remaining_budget, + browser="chrome", + allow_redirects=True, + ) + except Exception: + if ( + blocked := _redirect_chain_block(listener, target_url, request_id) + ) is not None: + return blocked + raise + # A refused plain-http hop comes back as the proxy's own 403 response. + if ( + blocked := _redirect_chain_block(listener, target_url, request_id) + ) is not None: + return blocked html = resp.text or "" status_code = int(resp.status_code) if resp.status_code is not None else 200 @@ -172,7 +201,9 @@ def run_request_tier( cookies=jar_cookies(resp.cookies, target_url, final_url), ) finally: - try: - req.close() - except Exception: - pass + listener.close() + if req is not None: + try: + req.close() + except Exception: + pass diff --git a/app/engine/warm_pool.py b/app/engine/warm_pool.py index 4017011..09930a6 100644 --- a/app/engine/warm_pool.py +++ b/app/engine/warm_pool.py @@ -28,6 +28,7 @@ ) from app.infra.cgroup import cgroup_memory_under_pressure, read_cgroup_memory from app.logging_config import get_logger, log_event +from app.security.egress_proxy import EgressListener, bind_driver, seed_profile if TYPE_CHECKING: from app.schemas.request import ScrapeRequest @@ -49,7 +50,12 @@ def create_driver_from_fingerprint( fingerprint: DriverFingerprint, spare_dir: Path ) -> DriverProtocol: - """Build a Botasaurus Driver for a warm spare (lazy vendor import).""" + """Build a Botasaurus Driver behind its own egress listener (lazy vendor import). + + The user's proxy becomes the listener's upstream; Botasaurus never sees it, + so every Chromium connection passes the SSRF policy with pinned DNS. + The profile is seeded first so WebRTC cannot send UDP around the listener. + """ from typing import cast from botasaurus.browser import Driver @@ -59,12 +65,13 @@ def create_driver_from_fingerprint( if fingerprint.window_size is not None else None ) - return cast( - DriverProtocol, - Driver( + seed_profile(spare_dir) + listener = EgressListener(fingerprint.proxy) + try: + driver = Driver( headless=fingerprint.headless, enable_xvfb_virtual_display=not fingerprint.headless, - proxy=fingerprint.proxy, + arguments=listener.chrome_arguments, profile=str(spare_dir), tiny_profile=False, block_images=fingerprint.block_images, @@ -74,8 +81,12 @@ def create_driver_from_fingerprint( window_size=window_size, lang=fingerprint.lang, remove_default_browser_check_argument=True, - ), - ) + ) + except BaseException: + listener.close() + raise + bind_driver(driver, listener) + return cast(DriverProtocol, driver) @dataclass(frozen=True, slots=True) diff --git a/app/infra/xhr_collector.py b/app/infra/xhr_collector.py index cad7ad7..d2da42e 100644 --- a/app/infra/xhr_collector.py +++ b/app/infra/xhr_collector.py @@ -8,7 +8,9 @@ import base64 import threading -from typing import cast +from collections.abc import Generator +from typing import Any, cast +from urllib.parse import urlsplit from app.engine.driver_protocol import CdpTabProtocol from app.infra.cdp_types import PendingXhrMeta @@ -19,6 +21,12 @@ logger = get_logger() +def _main_frame_id() -> Generator[dict[str, object], dict[str, Any], str]: + """CDP ``Page.getFrameTree`` reduced to the top-level frame id.""" + result = yield {"method": "Page.getFrameTree"} + return str(result["frameTree"]["frame"]["id"]) + + class XhrCollector: """Collects JSON XHR/fetch response bodies via CDP handlers.""" @@ -35,6 +43,8 @@ def __init__(self, target_url: str) -> None: self._collected: list[XhrResponse] = [] self._aggregate_bytes: int = 0 self._document: DocumentResponse | None = None + self._main_frame_hosts: list[str] = [] + self._main_frame_id: str | None = None self._lock = threading.Lock() def install(self, tab: CdpTabProtocol) -> None: @@ -45,6 +55,14 @@ def install(self, tab: CdpTabProtocol) -> None: tab.send(enable_network()) tab.after_response_received(self._on_response) tab.add_handler(cdp.network.LoadingFinished, self._on_finished) + tab.add_handler(cdp.network.RequestWillBeSent, self._on_request) + try: + main_frame_id = tab.send(_main_frame_id()) + except Exception as exc: + logger.debug("main_frame_id_unavailable error=%s", exc) + main_frame_id = None + with self._lock: + self._main_frame_id = main_frame_id def reset(self) -> None: """Clear pending/ready/collected state between strategy attempts.""" @@ -54,6 +72,7 @@ def reset(self) -> None: self._collected.clear() self._aggregate_bytes = 0 self._document = None + self._main_frame_hosts.clear() @property def document(self) -> DocumentResponse | None: @@ -61,6 +80,32 @@ def document(self) -> DocumentResponse | None: with self._lock: return self._document + @property + def main_frame_hosts(self) -> tuple[str, ...]: + """Hosts the main frame navigated to: target plus every redirect hop.""" + with self._lock: + return tuple(self._main_frame_hosts) + + def _on_request(self, event: object) -> None: + # Iframe navigations are Documents with request id == loader id too; + # only the top-level frame counts. Redirect hops re-fire per hop. + resource_type = getattr(getattr(event, "type_", None), "value", None) + frame_id = getattr(event, "frame_id", None) + if ( + resource_type != "Document" + or self._main_frame_id is None + or frame_id is None + or str(frame_id) != self._main_frame_id + ): + return + url = str(getattr(getattr(event, "request", None), "url", "") or "") + host = urlsplit(url).hostname + if host is None: + return + with self._lock: + if host not in self._main_frame_hosts: + self._main_frame_hosts.append(host) + @classmethod def _allowlisted_headers(cls, headers: object) -> dict[str, str]: """Keep only content-type; drop Set-Cookie and other headers.""" diff --git a/app/logging_config.py b/app/logging_config.py index 74f4f78..4375ecf 100644 --- a/app/logging_config.py +++ b/app/logging_config.py @@ -26,6 +26,11 @@ def get_logger() -> logging.Logger: return logging.getLogger(LOGGER_NAME) +def request_log_fields() -> dict[str, str]: + """Current request context, for events logged later from another thread.""" + return dict(_request_context.get()) + + @contextmanager def request_log_context(**fields: str) -> Generator[None]: """Attach ``fields`` (request_id, host) to every JSON record in this scope. diff --git a/app/schemas/request.py b/app/schemas/request.py index d9e26be..2d2deb7 100644 --- a/app/schemas/request.py +++ b/app/schemas/request.py @@ -140,7 +140,12 @@ class ScrapeRequest(BaseModel): ) proxy: str | None = Field( default=None, - description="Proxy URL passed to the driver. Invalid or blocked proxy URLs are rejected by SSRF guardrails.", + description=( + "Upstream proxy URL (http:// only, credentials allowed). It is the egress " + "guard's next hop for both tiers; every destination is still resolved and " + "checked locally against the SSRF policy first. Non-http, invalid, or " + "blocked proxy URLs are rejected by SSRF guardrails." + ), examples=["http://user:pass@proxy.example:8080"], ) diff --git a/app/security/egress_proxy.py b/app/security/egress_proxy.py new file mode 100644 index 0000000..2677390 --- /dev/null +++ b/app/security/egress_proxy.py @@ -0,0 +1,476 @@ +"""Pinned-DNS egress proxy: the SSRF policy applied to every outbound connection. + +Chromium (``--proxy-server``) and the request tier send all traffic through a +per-driver/per-call loopback listener. The listener resolves each destination +once via ``UrlGuard.resolve_host``, refuses blocked addresses, and connects to +the exact IP it checked, so DNS rebinding cannot swap the address afterwards. +WebRTC, which would send UDP around any HTTP proxy, is limited to proxied +transports through the profile (``seed_profile``). +With an upstream proxy, the destination is still checked first, but the +upstream receives the hostname and resolves it on its own network. +""" + +import asyncio +import base64 +import json +import logging +import threading +import time +import weakref +from collections import Counter +from collections.abc import Awaitable, Callable, Iterable +from concurrent.futures import ThreadPoolExecutor +from functools import partial +from pathlib import Path +from types import TracebackType +from typing import Any, Self +from urllib.parse import unquote, urlsplit + +from app.logging_config import get_logger, log_event, request_log_fields +from app.security.url_guard import PinnedHost, UrlGuard, ValidationResult + +logger = get_logger() + +type Streams = tuple[asyncio.StreamReader, asyncio.StreamWriter] +type Connector = Callable[[str, int], Awaitable[Streams]] +type HostResolver = Callable[[str, int], PinnedHost | ValidationResult] + +# Module-level so tests can shorten them. +RESOLVE_TIMEOUT_SECONDS = 5.0 +# Lookups one listener may hold on the DNS pool, counted until the thread +# returns (a timed-out getaddrinfo keeps its thread). +DNS_SLOTS_PER_LISTENER = 4 +HEAD_TIMEOUT_SECONDS = 10.0 +BLOCKED_LEDGER_LIMIT = 1024 +_HEAD_LIMIT = 64 * 1024 +_PUMP_CHUNK = 64 * 1024 +_HOP_HEADERS = frozenset( + {"connection", "keep-alive", "proxy-connection", "proxy-authorization"} +) +_FORBIDDEN = b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" +_BAD_GATEWAY = ( + b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" +) +_ESTABLISHED = b"HTTP/1.1 200 Connection Established\r\n\r\n" + +# getaddrinfo is blocking and cannot be cancelled; a dedicated pool keeps slow +# DNS off the loop's default executor. 32 workers hold the slots of 8 +# listeners (default 4 scrape workers plus a warm spare fit), so one hostile +# page cannot starve another scrape's lookups. +_dns_executor = ThreadPoolExecutor(max_workers=32, thread_name_prefix="egress-dns") +_loop_lock = threading.Lock() +_loop: asyncio.AbstractEventLoop | None = None +_driver_listeners: weakref.WeakKeyDictionary[object, EgressListener] = ( + weakref.WeakKeyDictionary() +) + + +class EgressBlockedError(Exception): + """Destination refused by the SSRF policy.""" + + +_monotonic = time.monotonic + + +class _EgressLoop(asyncio.SelectorEventLoop): + # Bound at import so patched ``time.monotonic`` (tests) cannot stall it. + def time(self) -> float: + return _monotonic() + + +def _shared_loop() -> asyncio.AbstractEventLoop: + global _loop + with _loop_lock: + if _loop is None: + loop = _EgressLoop() + threading.Thread( + target=loop.run_forever, name="egress-proxy", daemon=True + ).start() + _loop = loop + return _loop + + +async def _open_tcp(host: str, port: int) -> Streams: + return await asyncio.open_connection(host, port, limit=_HEAD_LIMIT) + + +async def _pump(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None: + try: + while chunk := await src.read(_PUMP_CHUNK): + dst.write(chunk) + await dst.drain() + # Half-close: the peer may still be answering the other direction. + if dst.can_write_eof(): + dst.write_eof() + except OSError: + dst.close() + + +def _authority(address: str, port: int) -> str: + return f"[{address}]:{port}" if ":" in address else f"{address}:{port}" + + +def _split_authority(authority: str, default_port: int) -> tuple[str, int]: + parsed = urlsplit(f"//{authority}") + if not parsed.hostname: + raise ValueError(f"invalid authority: {authority!r}") + return parsed.hostname, parsed.port or default_port + + +class EgressListener: + """One loopback proxy listener; ``upstream`` is the user's optional next hop.""" + + def __init__( + self, + upstream: str | None = None, + *, + resolve: HostResolver = UrlGuard.resolve_host, + connect: Connector = _open_tcp, + ) -> None: + self._resolve = resolve + self._connect = connect + self._upstream_host: str | None = None + self._upstream_port = 0 + self._upstream_auth: str | None = None + if upstream: + parsed = urlsplit(upstream) + if parsed.scheme != "http" or not parsed.hostname: + raise ValueError("Only http:// upstream proxies are supported") + self._upstream_host = parsed.hostname + self._upstream_port = parsed.port or 80 + if parsed.username is not None: + raw = f"{unquote(parsed.username)}:{unquote(parsed.password or '')}" + self._upstream_auth = base64.b64encode(raw.encode()).decode("ascii") + self._blocked: dict[str, str] = {} + self._blocked_lock = threading.Lock() + # Loop-thread only: per-scrape pins (failures are not kept) and slots. + self._pins: dict[tuple[str, int], asyncio.Future[PinnedHost]] = {} + self._dns_slots = asyncio.Semaphore(DNS_SLOTS_PER_LISTENER) + # The listener logs from its loop and DNS threads, which never see the + # caller's request context; ``attach_request`` re-captures it. + self._log_fields = request_log_fields() + self._stats: Counter[str] = Counter() + self._upstream_status: str | None = None + self._closed = False + self._loop = _shared_loop() + self._server = asyncio.run_coroutine_threadsafe( + asyncio.start_server(self._handle, "127.0.0.1", 0, limit=_HEAD_LIMIT), + self._loop, + ).result(timeout=5) + self.port: int = self._server.sockets[0].getsockname()[1] + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self.port}" + + @property + def chrome_arguments(self) -> list[str]: + # Chromium bypasses proxies for loopback unless told otherwise; QUIC + # would also skip the guard. WebRTC UDP is closed by ``seed_profile``. + return [ + f"--proxy-server={self.url}", + "--proxy-bypass-list=<-loopback>", + "--disable-quic", + ] + + @property + def blocked(self) -> dict[str, str]: + """Blocked destination host → policy reason, in block order.""" + with self._blocked_lock: + return dict(self._blocked) + + def clear_blocked(self) -> None: + """Start a new navigation attempt with an empty ledger.""" + with self._blocked_lock: + self._blocked.clear() + + def main_frame_block(self, navigation_hosts: Iterable[str]) -> str | None: + """Reason when a host of the page's own navigation chain was refused. + + Only hosts the main frame navigated to (target plus redirect hops) + count; refused sub-requests never turn into an SSRF error. + """ + blocked = self.blocked + for host in navigation_hosts: + if (reason := blocked.get(host.lower().rstrip("."))) is not None: + return reason + return None + + def attach_request(self) -> None: + """Tag later egress events with the current request (warm spares).""" + self._log_fields = request_log_fields() + + def close(self) -> None: + def _shutdown() -> None: + self._server.close() + self._server.close_clients() + + if not self._loop.is_closed(): + self._loop.call_soon_threadsafe(_shutdown) + with self._blocked_lock: + if self._closed: + return + self._closed = True + stats = dict(self._stats) + self._log_summary(stats) + + def _log_summary(self, stats: dict[str, int]) -> None: + """One event per listener (scrape) when anything was refused or failed.""" + if not any(v for k, v in stats.items() if k != "lookups"): + return + degraded = stats.get("upstream_refused", 0) or stats.get("dns_timeouts", 0) + log_event( + logger, + logging.WARNING if degraded else logging.INFO, + "egress_summary", + upstream_configured=self._upstream_host is not None, + upstream_status=self._upstream_status, + lookups=stats.get("lookups", 0), + blocked_connections=stats.get("blocked_connections", 0), + blocked_unrecorded=stats.get("blocked_unrecorded", 0), + dns_timeouts=stats.get("dns_timeouts", 0), + dns_failures=stats.get("dns_failures", 0), + connect_failures=stats.get("connect_failures", 0), + upstream_refused=stats.get("upstream_refused", 0), + request_id=self._log_fields.get("request_id"), + host=self._log_fields.get("host"), + ) + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + def _decide(self, host: str, port: int) -> PinnedHost: + decision = self._resolve(host, port) + if isinstance(decision, PinnedHost): + return decision + if decision.status_code != 403: + raise OSError(decision.error_message or "Hostname could not be resolved") + reason = decision.error_message or "Target is blocked" + key = host.lower().rstrip(".") + # One entry per host, first reason kept; once full, new hosts are still + # refused but not recorded, so a flood can never evict an earlier + # (typically main-frame) hit. + with self._blocked_lock: + self._stats["blocked_connections"] += 1 + first = key not in self._blocked + if first and len(self._blocked) >= BLOCKED_LEDGER_LIMIT: + self._stats["blocked_unrecorded"] += 1 + first = False + elif first: + self._blocked[key] = reason + # Logged once per host and attempt; repeats only count in the summary. + if first: + log_event( + logger, + logging.WARNING, + "egress_blocked", + dest_host=host, + dest_port=port, + reason=reason, + request_id=self._log_fields.get("request_id"), + host=self._log_fields.get("host"), + ) + raise EgressBlockedError(reason) + + async def _pin(self, host: str, port: int) -> PinnedHost: + """Resolve once per scrape; concurrent connections share one lookup. + + A pinned answer is reused for the listener's lifetime (one scrape), so + a page's many connections cost one lookup per host. Refusals and + failures are dropped, so each attempt re-records its blocks. + """ + key = (host.lower().rstrip("."), port) + pinned = self._pins.get(key) + if pinned is None: + pinned = asyncio.ensure_future( + asyncio.wait_for(self._lookup(host, port), RESOLVE_TIMEOUT_SECONDS) + ) + self._pins[key] = pinned + self._count("lookups") + pinned.add_done_callback(partial(self._forget_failed, key)) + return await asyncio.shield(pinned) + + def _forget_failed( + self, key: tuple[str, int], pinned: asyncio.Future[PinnedHost] + ) -> None: + if pinned.cancelled(): + self._pins.pop(key, None) + return + error = pinned.exception() + if error is None: + return + self._pins.pop(key, None) + if isinstance(error, TimeoutError): + self._count("dns_timeouts") + elif not isinstance(error, EgressBlockedError): + self._count("dns_failures") + + def _count(self, stat: str) -> None: + with self._blocked_lock: + self._stats[stat] += 1 + + async def _lookup(self, host: str, port: int) -> PinnedHost: + loop = asyncio.get_running_loop() + await self._dns_slots.acquire() + job = _dns_executor.submit(self._decide, host, port) + # Free the slot when the thread returns, not when the caller gives up. + job.add_done_callback( + lambda _: loop.call_soon_threadsafe(self._dns_slots.release) + ) + return await asyncio.wrap_future(job) + + async def _pinned_connect(self, host: str, port: int) -> Streams: + pinned = await self._pin(host, port) + last_error: OSError | None = None + for address in pinned.addresses: + try: + return await self._connect(str(address), port) + except OSError as exc: + last_error = exc + self._count("connect_failures") + raise last_error or OSError(f"no address for {host}") + + async def _open_destination(self, host: str, port: int) -> tuple[Streams, str]: + """Open the next hop; returns streams and the authority for the upstream.""" + if self._upstream_host is None: + streams = await self._pinned_connect(host, port) + return streams, "" + # The destination must still pass the local check, but the upstream gets + # the hostname: it resolves on its own network, which cannot reach ours, + # and TLS-inspecting or geo-routing upstreams need the name. The upstream + # hop itself is pinned like any destination. + await self._pin(host, port) + streams = await self._pinned_connect(self._upstream_host, self._upstream_port) + return streams, _authority(host, port) + + def _proxy_auth_line(self) -> str: + if self._upstream_auth is None: + return "" + return f"Proxy-Authorization: Basic {self._upstream_auth}\r\n" + + async def _handle( + self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter + ) -> None: + try: + head = await asyncio.wait_for( + reader.readuntil(b"\r\n\r\n"), HEAD_TIMEOUT_SECONDS + ) + request_line, *header_lines = head.decode("latin-1").split("\r\n") + method, target, version = request_line.split(" ", 2) + if method.upper() == "CONNECT": + host, port = _split_authority(target, 443) + (up_reader, up_writer), authority = await self._open_destination( + host, port + ) + if self._upstream_host is not None: + up_writer.write( + ( + f"CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n" + f"{self._proxy_auth_line()}\r\n" + ).encode("latin-1") + ) + reply = await asyncio.wait_for( + up_reader.readuntil(b"\r\n\r\n"), HEAD_TIMEOUT_SECONDS + ) + if (status := reply.split(b" ", 2)[1:2]) != [b"200"]: + # e.g. 407 bad credentials or 402 quota: the operator's + # proxy, not the target, refused the tunnel. + self._count("upstream_refused") + self._upstream_status = ( + status[0].decode("latin-1") if status else "invalid" + ) + up_writer.close() + writer.write(_BAD_GATEWAY) + return + writer.write(_ESTABLISHED) + else: + parsed = urlsplit(target) + if parsed.scheme != "http" or not parsed.hostname: + raise ValueError(f"unsupported proxy target: {target!r}") + (up_reader, up_writer), authority = await self._open_destination( + parsed.hostname, parsed.port or 80 + ) + origin = parsed.path or "/" + if parsed.query: + origin = f"{origin}?{parsed.query}" + if self._upstream_host is None: + line = f"{method} {origin} {version}\r\n" + else: + line = ( + f"{method} http://{authority}{origin} {version}\r\n" + f"{self._proxy_auth_line()}" + ) + kept = [ + h + for h in header_lines + if h and h.split(":", 1)[0].strip().lower() not in _HOP_HEADERS + ] + up_writer.write( + ( + line + + "".join(f"{h}\r\n" for h in kept) + + "Connection: close\r\n\r\n" + ).encode("latin-1") + ) + await writer.drain() + try: + await asyncio.gather(_pump(reader, up_writer), _pump(up_reader, writer)) + finally: + up_writer.close() + except EgressBlockedError: + writer.write(_FORBIDDEN) + except ( + OSError, + ValueError, + asyncio.IncompleteReadError, + asyncio.LimitOverrunError, + ): + writer.write(_BAD_GATEWAY) + finally: + writer.close() + + +def seed_profile(profile_dir: Path) -> None: + """Restrict WebRTC to proxied transports before Chromium starts. + + WebRTC sends STUN/TURN over raw UDP to page-chosen addresses, which no + HTTP proxy sees. ``--force-webrtc-ip-handling-policy`` is ignored by the + bundled Chromium, so the policy is set in the profile's preferences; with + no UDP proxy, WebRTC then gathers no candidates at all. + """ + prefs_path = profile_dir / "Default" / "Preferences" + prefs_path.parent.mkdir(parents=True, exist_ok=True) + prefs: dict[str, Any] = ( + json.loads(prefs_path.read_text()) if prefs_path.exists() else {} + ) + prefs["webrtc"] = { + **prefs.get("webrtc", {}), + "ip_handling_policy": "disable_non_proxied_udp", + "multiple_routes_enabled": False, + "nonproxied_udp_enabled": False, + } + prefs_path.write_text(json.dumps(prefs)) + + +def bind_driver(driver: object, listener: EgressListener) -> None: + """Tie ``listener`` to ``driver``; it closes with the driver (or its GC).""" + _driver_listeners[driver] = listener + weakref.finalize(driver, listener.close) + + +def driver_listener(driver: object) -> EgressListener | None: + return _driver_listeners.get(driver) + + +def release_driver(driver: object) -> None: + listener = _driver_listeners.pop(driver, None) + if listener is not None: + listener.close() diff --git a/app/security/url_guard.py b/app/security/url_guard.py index ce65f48..6f2fb50 100644 --- a/app/security/url_guard.py +++ b/app/security/url_guard.py @@ -2,10 +2,33 @@ import ipaddress import socket +from collections.abc import Callable, Sequence from dataclasses import dataclass from urllib.parse import urlparse _NAT64_WELL_KNOWN_PREFIX = ipaddress.ip_network("64:ff9b::/96") +# Not globally routable, yet missed by the stdlib ``is_*`` flags. +_EXTRA_BLOCKED_NETWORKS = ( + # RFC 6598 shared space (CGNAT); cloud-internal (e.g. 100.100.100.200). + ipaddress.ip_network("100.64.0.0/10"), + # Deprecated 6to4 relay anycast (RFC 7526). + ipaddress.ip_network("192.88.99.0/24"), + # ORCHIDv2 (RFC 7343), non-routable identifiers. + ipaddress.ip_network("2001:20::/28"), + # Deprecated IPv6 site-local (RFC 3879). + ipaddress.ip_network("fec0::/10"), +) +# Local and cloud-metadata names, refused before resolution. +_BLOCKED_HOSTNAMES = frozenset({"localhost", "metadata.google.internal"}) + +type IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address +type Resolver = Callable[[str, int | None], Sequence[str]] + + +def system_resolve(host: str, port: int | None) -> list[str]: + """Resolve every address for ``host``; raises ``socket.gaierror``.""" + infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) + return [str(info[4][0]) for info in infos if info[4]] @dataclass(frozen=True, slots=True) @@ -15,11 +38,21 @@ class ValidationResult: error_message: str | None = None +@dataclass(frozen=True, slots=True) +class PinnedHost: + """Addresses checked for ``host``; callers connect to these, never re-resolve.""" + + host: str + addresses: tuple[IPAddress, ...] + + class UrlGuard: """Deep module enforcing network security and SSRF prevention guardrails.""" @classmethod - def is_blocked_ip(cls, ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: + def is_blocked_ip(cls, ip: IPAddress) -> bool: + if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None: + return cls.is_blocked_ip(ip.ipv4_mapped) if isinstance(ip, ipaddress.IPv6Address) and ip in _NAT64_WELL_KNOWN_PREFIX: try: embedded_ipv4 = ipaddress.IPv4Address(ip.packed[-4:]) @@ -29,6 +62,7 @@ def is_blocked_ip(cls, ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> boo return ( ip.is_loopback + or any(ip in network for network in _EXTRA_BLOCKED_NETWORKS) or ip.is_private or ip.is_link_local or ip.is_multicast @@ -54,8 +88,20 @@ def validate(cls, raw_url: str) -> ValidationResult: error_message="URL must include a hostname", ) - normalized_host = host.strip().lower().rstrip(".") - if normalized_host == "localhost" or normalized_host.endswith(".localhost"): + decision = cls.resolve_host(host, parsed.port) + if isinstance(decision, ValidationResult): + return decision + return ValidationResult(is_allowed=True, status_code=200, error_message=None) + + @classmethod + def resolve_host( + cls, host: str, port: int | None, resolver: Resolver = system_resolve + ) -> PinnedHost | ValidationResult: + """Resolve ``host`` once and allow it only if every address is public.""" + normalized_host = host.strip().strip("[]").lower().rstrip(".") + if normalized_host in _BLOCKED_HOSTNAMES or normalized_host.endswith( + ".localhost" + ): return ValidationResult( is_allowed=False, status_code=403, @@ -63,23 +109,18 @@ def validate(cls, raw_url: str) -> ValidationResult: ) try: - addr_infos = socket.getaddrinfo(host, parsed.port, type=socket.SOCK_STREAM) - except socket.gaierror: + ip_texts = resolver(normalized_host, port) + except OSError, UnicodeError: return ValidationResult( is_allowed=False, status_code=400, error_message="Hostname could not be resolved", ) - resolved_ips: set[str] = set() - for info in addr_infos: - sockaddr = info[4] - if sockaddr: - resolved_ips.add(str(sockaddr[0])) - - for ip_text in resolved_ips: + addresses: list[IPAddress] = [] + for ip_text in dict.fromkeys(ip_texts): try: - ip = ipaddress.ip_address(ip_text) + ip = ipaddress.ip_address(ip_text.split("%", 1)[0]) except ValueError: continue if cls.is_blocked_ip(ip): @@ -88,11 +129,24 @@ def validate(cls, raw_url: str) -> ValidationResult: status_code=403, error_message=f"Target resolved to blocked IP address: {ip_text}", ) - - return ValidationResult(is_allowed=True, status_code=200, error_message=None) + addresses.append(ip) + if not addresses: + return ValidationResult( + is_allowed=False, + status_code=400, + error_message="Hostname could not be resolved", + ) + return PinnedHost(host=normalized_host, addresses=tuple(addresses)) @classmethod def validate_proxy(cls, proxy_url: str) -> ValidationResult: + # The egress proxy chains to plain-HTTP upstreams only. + if urlparse(proxy_url).scheme != "http": + return ValidationResult( + is_allowed=False, + status_code=400, + error_message="Proxy URL is invalid or blocked: Only http:// proxy URLs are supported", + ) result = cls.validate(proxy_url) if not result.is_allowed: return ValidationResult( diff --git a/openapi.yaml b/openapi.yaml index 16b9c78..cb40024 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -525,8 +525,10 @@ components: - type: string - type: 'null' title: Proxy - description: Proxy URL passed to the driver. Invalid or blocked proxy URLs - are rejected by SSRF guardrails. + description: Upstream proxy URL (http:// only, credentials allowed). It + is the egress guard's next hop for both tiers; every destination is still + resolved and checked locally against the SSRF policy first. Non-http, + invalid, or blocked proxy URLs are rejected by SSRF guardrails. examples: - http://user:pass@proxy.example:8080 type: object diff --git a/scripts/smoke.sh b/scripts/smoke.sh index d748b58..e956bf7 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -334,6 +334,100 @@ assert_no_tmp_bota() { echo "[smoke] /tmp usage after browser scrape: ${tmp_usage}" } +assert_chrome_egress_guard() { + # The /scrape pre-check rejects private targets before Chromium boots, so + # drive the service's own driver factory inside the container: sub-requests + # and a main-frame navigation to internal targets must be refused by the + # egress listener (the API on :4010 must never be served to Chromium). + echo "[smoke] Checking in-Chromium egress guard (sub-requests + main frame)" + local probe_out + probe_out="$(docker exec -i "${CONTAINER_NAME}" python - <<'PY' 2>&1 +import tempfile +import time +from pathlib import Path + +from app.engine.driver_protocol import close_driver, resolve_cdp_tab +from app.infra.xhr_collector import XhrCollector +from app.engine.warm_pool import DriverFingerprint, create_driver_from_fingerprint +from app.security.egress_proxy import driver_listener + +fingerprint = DriverFingerprint( + headless=True, proxy=None, block_images=False, block_images_and_css=False, + wait_for_complete_page_load=False, user_agent=None, window_size=None, lang=None, +) +driver = create_driver_from_fingerprint(fingerprint, Path(tempfile.mkdtemp(dir="/tmp"))) +try: + listener = driver_listener(driver) + assert listener is not None, "driver has no egress listener" + collector = XhrCollector("http://127.0.0.1:4010/health") + tab = resolve_cdp_tab(driver) + assert tab is not None, "no CDP tab" + collector.install(tab) + driver.get( + "data:text/html,