Skip to content

Official Crawl4AI Cloud: a hosted web scraping, extraction, and search API for AI agents. Free API key, 1,000 credits a month, no card. Fully open source: this repo is the Apache-2.0 crawler that powers it, and you can self-host it.

fix(security): tighten Docker hardening guards

ntohidi171453f879ad
diff --git a/deploy/docker/artifacts.py b/deploy/docker/artifacts.py
index a5aac1b5..2f53a5c5 100644
--- a/deploy/docker/artifacts.py
+++ b/deploy/docker/artifacts.py
@@ -100,7 +100,7 @@ def resolve_artifact(artifact_id: str) -> Tuple[str, str]:
Raises ArtifactNotFound for an invalid id, a non-regular/symlink file, a
missing file, or an expired artifact (so existence is never revealed).
"""
- if not isinstance(artifact_id, str) or not _HEX32.match(artifact_id):
+ if not isinstance(artifact_id, str) or not _HEX32.fullmatch(artifact_id):
raise ArtifactNotFound()
for ext, mime in _KIND.values():
path = os.path.join(ARTIFACT_DIR, artifact_id + ext)
diff --git a/deploy/docker/egress_broker.py b/deploy/docker/egress_broker.py
index 873b6a12..0729401e 100644
--- a/deploy/docker/egress_broker.py
+++ b/deploy/docker/egress_broker.py
@@ -25,12 +25,15 @@ leaks a resolved internal IP, hostname, or traceback (the old DNS oracle).
from __future__ import annotations
import ipaddress
+import logging
import os
import socket
from dataclasses import dataclass
from typing import List, Optional
from urllib.parse import urlparse
+logger = logging.getLogger("crawl4ai.security")
+
# Operator escape hatch for trusted internal deployments (off by default).
ALLOW_INTERNAL = os.environ.get("CRAWL4AI_ALLOW_INTERNAL_URLS", "false").lower() == "true"
@@ -200,7 +203,16 @@ def enforce_egress(browser_config) -> None:
from crawl4ai import ProxyConfig
browser_config.proxy_config = ProxyConfig(server=_EGRESS_PROXY_URL)
except Exception:
- pass
+ # Fail closed: a browser_config that can't be pinned must not be
+ # allowed to crawl unpinned (that reopens DNS rebinding). Every
+ # caller of enforce_egress either runs inside a try/except that
+ # turns this into a clean 4xx/5xx response, or (app startup) is
+ # meant to abort loudly rather than serve traffic unprotected.
+ logger.error(
+ "enforce_egress: failed to set the egress pinning proxy; "
+ "refusing to crawl unpinned", exc_info=True
+ )
+ raise EgressBlocked("egress pinning unavailable")
args = getattr(browser_config, "extra_args", None)
if args:
browser_config.extra_args = [
diff --git a/deploy/docker/governor.py b/deploy/docker/governor.py
index 73534e99..372a3c37 100644
--- a/deploy/docker/governor.py
+++ b/deploy/docker/governor.py
@@ -19,8 +19,11 @@ integration-tested pass; gunicorn --limit-request-* covers the transport layer.
from __future__ import annotations
import json
+import logging
import math
+logger = logging.getLogger("crawl4ai.security")
+
DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024 # 10 MiB
DEFAULT_MAX_PAGES = 100
DEFAULT_MAX_DEPTH = 5
@@ -79,13 +82,19 @@ def clamp_deep_crawl(crawler_config, *, max_pages: int = DEFAULT_MAX_PAGES,
try:
dc.max_pages = max_pages
except Exception:
- pass
+ logger.warning(
+ "clamp_deep_crawl: could not clamp max_pages on %r; "
+ "deep crawl may run with an unbounded page budget", dc, exc_info=True
+ )
md = getattr(dc, "max_depth", None)
if md is None or md > max_depth:
try:
dc.max_depth = max_depth
except Exception:
- pass
+ logger.warning(
+ "clamp_deep_crawl: could not clamp max_depth on %r; "
+ "deep crawl may run with an unbounded depth budget", dc, exc_info=True
+ )
def max_body_bytes_from_config(config: dict) -> int:
diff --git a/deploy/docker/hook_registry.py b/deploy/docker/hook_registry.py
index c20e256d..2aada7b0 100644
--- a/deploy/docker/hook_registry.py
+++ b/deploy/docker/hook_registry.py
@@ -72,7 +72,7 @@ class SetHeadersParams(BaseModel):
if len(v) > _MAX_HEADERS:
raise ValueError(f"too many headers (max {_MAX_HEADERS})")
for name, value in v.items():
- if not _HEADER_NAME_RE.match(name):
+ if not _HEADER_NAME_RE.fullmatch(name):
raise ValueError(f"invalid header name {name!r}")
if any(c in value for c in "\r\n\x00"):
raise ValueError(f"control characters in value for header {name!r}")
diff --git a/deploy/docker/tests/test_security_hardening_2026_10.py b/deploy/docker/tests/test_security_hardening_2026_10.py
new file mode 100644
index 00000000..9e7aed6c
--- /dev/null
+++ b/deploy/docker/tests/test_security_hardening_2026_10.py
@@ -0,0 +1,101 @@
+"""
+2026-10 hardening regression tests.
+
+A) Header-name validators used `.match` against a `^...$` pattern. In Python,
+`$` also matches just before a trailing "\n", so "X-Injected\n" passed
+validation (not exploitable today since aiohttp/Chromium reject it later, but
+the validator itself must reject it). Fixed by switching to `.fullmatch`.
+
+B) `governor.clamp_deep_crawl` and `egress_broker.enforce_egress` silently
+swallowed exceptions from hardening guards (`except Exception: pass`). Fixed
+to log a warning (governor) and to fail closed with EgressBlocked (the egress
+pinning proxy - crawling unpinned would reopen DNS rebinding).
+"""
+
+import logging
+
+import pytest
+
+pytestmark = pytest.mark.posture
+
+
+class TestHeaderNameTrailingNewline:
+ def test_hook_registry_rejects_trailing_newline(self):
+ from hook_registry import SetHeadersParams
+
+ with pytest.raises(Exception):
+ SetHeadersParams(headers={"X-Injected\n": "v"})
+
+ def test_hook_registry_accepts_normal_name(self):
+ from hook_registry import SetHeadersParams
+
+ p = SetHeadersParams(headers={"X-Injected": "v"})
+ assert p.headers == {"X-Injected": "v"}
+
+ def test_webhook_rejects_trailing_newline(self):
+ from webhook import sanitize_webhook_headers
+
+ with pytest.raises(ValueError):
+ sanitize_webhook_headers({"X-Custom\n": "v"})
+
+ def test_webhook_accepts_normal_name(self):
+ from webhook import sanitize_webhook_headers
+
+ clean = sanitize_webhook_headers({"X-Custom": "v"})
+ assert clean == {"X-Custom": "v"}
+
+
+class _RaisingDeepCrawl:
+ """Stand-in whose attribute assignment always raises, to exercise the
+ except branch in clamp_deep_crawl without needing a real strategy."""
+
+ max_pages = None
+ max_depth = None
+
+ def __setattr__(self, name, value):
+ raise RuntimeError("cannot set attribute")
+
+
+class _RaisingConfig:
+ deep_crawl_strategy = _RaisingDeepCrawl()
+
+
+class TestClampDeepCrawlLogsOnFailure(object):
+ def test_logs_warning_when_clamp_fails(self, caplog):
+ from governor import clamp_deep_crawl
+
+ with caplog.at_level(logging.WARNING, logger="crawl4ai.security"):
+ clamp_deep_crawl(_RaisingConfig())
+
+ assert any("clamp_deep_crawl" in r.message for r in caplog.records)
+
+
+class _RaisingBrowserConfig:
+ """hasattr(obj, 'proxy_config') must be True so enforce_egress attempts
+ to set the pinning proxy; the setter then raises."""
+
+ ignore_https_errors = True
+ proxy = None
+ extra_args = None
+
+ @property
+ def proxy_config(self):
+ return None
+
+ @proxy_config.setter
+ def proxy_config(self, value):
+ raise RuntimeError("cannot set proxy_config")
+
+
+class TestEnforceEgressFailsClosed:
+ def test_raises_when_pinning_proxy_cannot_be_set(self, monkeypatch, caplog):
+ import egress_broker
+
+ monkeypatch.setattr(egress_broker, "_EGRESS_PROXY_URL", "http://127.0.0.1:1")
+ try:
+ with caplog.at_level(logging.ERROR, logger="crawl4ai.security"):
+ with pytest.raises(egress_broker.EgressBlocked):
+ egress_broker.enforce_egress(_RaisingBrowserConfig())
+ assert any("enforce_egress" in r.message for r in caplog.records)
+ finally:
+ monkeypatch.setattr(egress_broker, "_EGRESS_PROXY_URL", None)
diff --git a/deploy/docker/webhook.py b/deploy/docker/webhook.py
index a05e6e40..4b233f41 100644
--- a/deploy/docker/webhook.py
+++ b/deploy/docker/webhook.py
@@ -68,7 +68,7 @@ def sanitize_webhook_headers(headers: Optional[Dict[str, str]]) -> Dict[str, str
raise ValueError("too many webhook headers")
clean: Dict[str, str] = {}
for name, value in headers.items():
- if not isinstance(name, str) or not _WEBHOOK_HEADER_NAME.match(name):
+ if not isinstance(name, str) or not _WEBHOOK_HEADER_NAME.fullmatch(name):
raise ValueError(f"invalid webhook header name: {name!r}")
if name.lower() in _WEBHOOK_DENY_HEADERS:
raise ValueError(f"webhook header not allowed: {name}")