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): batch 2 - JWT secret, eval removal, execute_js, hook sandbox

unclecode0f20f8bb8390
diff --git a/SECURITY-CREDITS.md b/SECURITY-CREDITS.md
new file mode 100644
index 00000000..7167b8d3
--- /dev/null
+++ b/SECURITY-CREDITS.md
@@ -0,0 +1,10 @@
+# Security Credits
+
+We thank the following security researchers for their responsible disclosure:
+
+| Researcher | Contact | Vulnerability | Date Reported |
+|---|---|---|---|
+| Song Binglin (q1uf3ng) | [email protected] | AST sandbox escape via gi_frame.f_back chain (CVSS 9.8) | 2026-03-29 |
+| Jeongbean Jeon | [email protected] | File write, SSRF, monitor auth bypass, stored XSS | 2026-04-13 |
+| Lonchia Wu | [email protected] | File write via output_path (independent report) | 2026-04-13 |
+| by111 (August829) | GitHub: [August829](https://github.com/August829) | Hardcoded JWT secret, eval in /config/dump, /execute_js, hook sandbox escape | 2026-04-14 |
diff --git a/deploy/docker/auth.py b/deploy/docker/auth.py
index ebc4eea1..4a5f7332 100644
--- a/deploy/docker/auth.py
+++ b/deploy/docker/auth.py
@@ -11,9 +11,39 @@ import base64
instance = JWT()
security = HTTPBearer(auto_error=False)
-SECRET_KEY = os.environ.get("SECRET_KEY", "mysecret")
ACCESS_TOKEN_EXPIRE_MINUTES = 60
+_WEAK_SECRETS = {"mysecret", "secret", "password", "changeme", "test", "12345678"}
+
+
+def _resolve_secret_key() -> str:
+ """Resolve SECRET_KEY: validate if set, auto-generate if JWT enabled but unset."""
+ import logging
+ import secrets as _secrets
+ key = os.environ.get("SECRET_KEY", "")
+ if key:
+ if key.lower() in _WEAK_SECRETS:
+ raise RuntimeError(
+ "FATAL: SECRET_KEY is a known weak value. "
+ "Generate a strong one: python3 -c \"import secrets; print(secrets.token_hex(32))\""
+ )
+ if len(key) < 32:
+ raise RuntimeError(
+ "FATAL: SECRET_KEY must be at least 32 characters. "
+ "Generate one: python3 -c \"import secrets; print(secrets.token_hex(32))\""
+ )
+ return key
+ # No key set -- auto-generate ephemeral key
+ generated = _secrets.token_hex(32)
+ logging.getLogger("crawl4ai.security").warning(
+ "No SECRET_KEY set. Auto-generated ephemeral key (changes on restart). "
+ "Set SECRET_KEY env var for production."
+ )
+ return generated
+
+
+SECRET_KEY = _resolve_secret_key()
+
def get_jwk_from_secret(secret: str):
"""Convert a secret string into a JWK object."""
secret_bytes = secret.encode('utf-8')
diff --git a/deploy/docker/config.yml b/deploy/docker/config.yml
index 3383c125..08af889c 100644
--- a/deploy/docker/config.yml
+++ b/deploy/docker/config.yml
@@ -78,7 +78,7 @@ crawler:
- "--disable-dev-shm-usage"
- "--disable-gpu"
- "--disable-software-rasterizer"
- - "--disable-web-security"
+ # --disable-web-security removed for security (enables cross-origin access)
- "--allow-insecure-localhost"
- "--ignore-certificate-errors"
diff --git a/deploy/docker/hook_manager.py b/deploy/docker/hook_manager.py
index 4cf26109..7c93e278 100644
--- a/deploy/docker/hook_manager.py
+++ b/deploy/docker/hook_manager.py
@@ -122,15 +122,17 @@ class UserHookManager:
safe_builtins = {}
# Add safe built-in functions (no __import__ for security)
- # SECURITY: getattr/setattr removed - classic sandbox escape vectors.
- # hasattr kept (read-only attribute check, not exploitable).
+ # SECURITY: Minimal builtins only. Removed:
+ # - getattr/setattr: sandbox escape via attribute access
+ # - type: enables __subclasses__() MRO chain attacks
+ # - __build_class__: enables malicious __init_subclass__
+ # - hasattr: information disclosure
allowed_builtins = [
'print', 'len', 'str', 'int', 'float', 'bool',
'list', 'dict', 'set', 'tuple', 'range', 'enumerate',
'zip', 'map', 'filter', 'any', 'all', 'sum', 'min', 'max',
- 'sorted', 'reversed', 'abs', 'round', 'isinstance', 'type',
- 'hasattr', 'callable', 'iter', 'next',
- '__build_class__' # Required for class definitions in exec
+ 'sorted', 'reversed', 'abs', 'round', 'isinstance',
+ 'callable', 'iter', 'next',
]
for name in allowed_builtins:
@@ -151,22 +153,31 @@ class UserHookManager:
import re as _re_mod
from typing import Dict as _Dict, List as _List, Optional as _Optional
- # SECURITY: Sanitize asyncio to prevent RCE via
- # asyncio.subprocess.create_subprocess_shell() etc.
- # Hooks need asyncio for sleep/gather/etc but NOT subprocess.
+ # SECURITY: Create safe module proxies that strip __builtins__
+ # and dangerous sub-modules. Without this, hook code can reach
+ # real __import__ via e.g. asyncio.__builtins__['__import__'].
import types
- safe_asyncio = types.ModuleType("asyncio")
- for _attr in dir(_asyncio_mod):
- if _attr not in ("subprocess", "create_subprocess_exec",
- "create_subprocess_shell"):
+
+ def _safe_module(mod, exclude_attrs=None):
+ """Create a proxy module without __builtins__ or dangerous attrs."""
+ proxy = types.ModuleType(mod.__name__)
+ skip = {"__builtins__", "__loader__", "__spec__"}
+ if exclude_attrs:
+ skip.update(exclude_attrs)
+ for attr in dir(mod):
+ if attr in skip:
+ continue
try:
- setattr(safe_asyncio, _attr, getattr(_asyncio_mod, _attr))
+ setattr(proxy, attr, getattr(mod, attr))
except (AttributeError, TypeError):
pass
+ return proxy
- namespace["asyncio"] = safe_asyncio
- namespace["json"] = _json_mod
- namespace["re"] = _re_mod
+ namespace["asyncio"] = _safe_module(_asyncio_mod, {
+ "subprocess", "create_subprocess_exec", "create_subprocess_shell"
+ })
+ namespace["json"] = _safe_module(_json_mod)
+ namespace["re"] = _safe_module(_re_mod)
namespace["Dict"] = _Dict
namespace["List"] = _List
namespace["Optional"] = _Optional
diff --git a/deploy/docker/server.py b/deploy/docker/server.py
index 6633bba3..a5bfe53e 100644
--- a/deploy/docker/server.py
+++ b/deploy/docker/server.py
@@ -85,6 +85,9 @@ GLOBAL_SEM = asyncio.Semaphore(MAX_PAGES)
# Hooks are disabled by default for security (RCE risk). Set to "true" to enable.
HOOKS_ENABLED = os.environ.get("CRAWL4AI_HOOKS_ENABLED", "false").lower() == "true"
+# /execute_js disabled by default (arbitrary JS + SSRF risk). Set to "true" to enable.
+EXECUTE_JS_ENABLED = os.environ.get("CRAWL4AI_EXECUTE_JS_ENABLED", "false").lower() == "true"
+
# Warn loudly if API token is not set (all endpoints unauthenticated)
_api_token = config.get("security", {}).get("api_token", "") or os.environ.get("CRAWL4AI_API_TOKEN", "")
if not _api_token:
@@ -282,103 +285,17 @@ ALLOWED_TYPES = {
}
-_SAFE_CONFIG_ALLOWED_NAMES = {
- # Config constructors
- "CrawlerRunConfig", "BrowserConfig", "HTTPCrawlerConfig",
- # Sub-config types
- "LLMConfig", "ProxyConfig", "GeolocationConfig",
- "SeedingConfig", "VirtualScrollConfig", "LinkPreviewConfig",
- # Extraction strategies
- "JsonCssExtractionStrategy", "JsonXPathExtractionStrategy",
- "JsonLxmlExtractionStrategy", "LLMExtractionStrategy",
- "CosineStrategy", "RegexExtractionStrategy",
- # Markdown / content filters
- "DefaultMarkdownGenerator",
- "PruningContentFilter", "BM25ContentFilter", "LLMContentFilter",
- "LXMLWebScrapingStrategy",
- # Chunking
- "RegexChunking",
- # Deep crawl
- "BFSDeepCrawlStrategy", "DFSDeepCrawlStrategy", "BestFirstCrawlingStrategy",
- # Filters & scorers
- "FilterChain", "URLPatternFilter", "DomainFilter",
- "ContentTypeFilter", "URLFilter", "SEOFilter", "ContentRelevanceFilter",
- "KeywordRelevanceScorer", "URLScorer", "CompositeScorer",
- "DomainAuthorityScorer", "FreshnessScorer", "PathDepthScorer",
- # Enums
- "CacheMode", "MatchMode", "DisplayMode",
- # Dispatchers
- "MemoryAdaptiveDispatcher", "SemaphoreDispatcher",
- # Table extraction
- "DefaultTableExtraction", "NoTableExtraction",
- # Proxy
- "RoundRobinProxyStrategy",
-}
-
-# Attributes safe to access in config constructor args (e.g. CacheMode.BYPASS)
-_SAFE_CONFIG_ALLOWED_ATTRS = frozenset({
- # Enum values commonly used in config
- "BYPASS", "READ_ONLY", "WRITE_ONLY", "ENABLED", "DISABLED",
- "READ_WRITE", "BYPASS_CACHE", "STANDARD", "COMPACT", "DETAILED",
- # Common config field names accessed via dot notation
- "value", "name",
-})
-
-
-def _safe_eval_config(expr: str) -> dict:
- """
- Accept exactly one top-level call to CrawlerRunConfig(...) or BrowserConfig(...).
- Hardened with allowlists for names, attributes, and blocked AST constructs.
- """
- tree = ast.parse(expr, mode="eval")
-
- # must be a single call
- if not isinstance(tree.body, ast.Call):
- raise ValueError("Expression must be a single constructor call")
-
- call = tree.body
- if not (isinstance(call.func, ast.Name) and call.func.id in {"CrawlerRunConfig", "BrowserConfig"}):
- raise ValueError(
- "Only CrawlerRunConfig(...) or BrowserConfig(...) are allowed")
-
- for node in ast.walk(call):
- # Block nested function calls
- if isinstance(node, ast.Call) and node is not call:
- raise ValueError("Nested function calls are not permitted")
-
- # Block lambdas
- if isinstance(node, ast.Lambda):
- raise ValueError("Lambda expressions are not permitted")
-
- # Block generators and comprehensions
- if isinstance(node, (ast.GeneratorExp, ast.ListComp, ast.SetComp, ast.DictComp)):
- raise ValueError("Comprehensions and generators are not permitted")
-
- # Allowlist attribute access
- if isinstance(node, ast.Attribute):
- if node.attr not in _SAFE_CONFIG_ALLOWED_ATTRS:
- raise ValueError(
- f"Attribute access '{node.attr}' is not permitted in config expressions")
-
- # Allowlist name references
- if isinstance(node, ast.Name) and node.id not in _SAFE_CONFIG_ALLOWED_NAMES:
- # Allow Python literals/constants used as keyword arg values
- if node.id not in {"True", "False", "None"}:
- raise ValueError(
- f"Name '{node.id}' is not permitted in config expressions")
-
- # Only expose allowlisted names from crawl4ai
- safe_env = {}
- for name in _SAFE_CONFIG_ALLOWED_NAMES:
- obj = getattr(_c4, name, None)
- if obj is not None:
- safe_env[name] = obj
- safe_env["True"] = True
- safe_env["False"] = False
- safe_env["None"] = None
-
- obj = eval(compile(tree, "<config>", "eval"),
- {"__builtins__": {}}, safe_env)
+def _config_from_json(data: dict) -> dict:
+ """Create CrawlerRunConfig or BrowserConfig from JSON {type, params}.
+ No eval() -- uses Pydantic constructors directly."""
+ config_type = data.get("type")
+ params = data.get("params", {})
+ if config_type == "CrawlerRunConfig":
+ obj = CrawlerRunConfig(**params)
+ elif config_type == "BrowserConfig":
+ obj = BrowserConfig(**params)
+ else:
+ raise ValueError("type must be 'CrawlerRunConfig' or 'BrowserConfig'")
return obj.dump()
@@ -404,10 +321,13 @@ async def get_token(req: TokenRequest):
@app.post("/config/dump")
-async def config_dump(raw: RawCode):
+async def config_dump(
+ data: dict,
+ _td: Dict = Depends(token_dep),
+):
try:
- return JSONResponse(_safe_eval_config(raw.code.strip()))
- except Exception as e:
+ return JSONResponse(_config_from_json(data))
+ except (TypeError, ValueError) as e:
raise HTTPException(400, str(e))
@@ -608,7 +528,14 @@ async def execute_js(
```
"""
+ if not EXECUTE_JS_ENABLED:
+ raise HTTPException(403, "execute_js endpoint is disabled. Set CRAWL4AI_EXECUTE_JS_ENABLED=true to enable.")
validate_url_scheme(body.url)
+ # Block SSRF: reject internal/private IPs
+ try:
+ validate_webhook_url(body.url) # reuse SSRF blocklist
+ except ValueError as e:
+ raise HTTPException(400, str(e))
crawler = None
try:
cfg = CrawlerRunConfig(js_code=body.scripts)
diff --git a/deploy/docker/tests/test_security_2026_04_b2.py b/deploy/docker/tests/test_security_2026_04_b2.py
new file mode 100644
index 00000000..47e701b5
--- /dev/null
+++ b/deploy/docker/tests/test_security_2026_04_b2.py
@@ -0,0 +1,358 @@
+#!/usr/bin/env python3
+"""
+Adversarial security tests for Batch 2 vulns reported 2026-04-14 (by111/August829).
+Self-contained tests that verify fixes at the code/source level.
+
+B2-V1: /execute_js disabled by default + SSRF block
+B2-V2: Hardcoded JWT secret removed
+B2-V3: eval() in /config/dump replaced with JSON
+B2-V4: Hook sandbox __builtins__ escape fixed
+"""
+
+import os
+import sys
+import ast
+import unittest
+import builtins
+import types
+
+DEPLOY_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
+
+
+# ============================================================================
+# B2-V2: Hardcoded JWT Secret
+# ============================================================================
+
+class TestJWTSecretHardened(unittest.TestCase):
+ """Verify the hardcoded 'mysecret' default is gone from auth.py."""
+
+ def test_no_mysecret_as_default(self):
+ """auth.py must not use 'mysecret' as a fallback default for SECRET_KEY."""
+ with open(os.path.join(DEPLOY_DIR, "auth.py")) as f:
+ source = f.read()
+ # The old dangerous pattern: os.environ.get("SECRET_KEY", "mysecret")
+ self.assertNotIn('get("SECRET_KEY", "mysecret")', source,
+ "auth.py must not use 'mysecret' as env var default")
+
+ def test_weak_secret_validation_exists(self):
+ """auth.py must validate against known weak secrets."""
+ with open(os.path.join(DEPLOY_DIR, "auth.py")) as f:
+ source = f.read()
+ self.assertIn("_WEAK_SECRETS", source,
+ "auth.py must have weak secrets blocklist")
+ self.assertIn("< 32", source,
+ "auth.py must enforce minimum key length")
+
+ def test_mysecret_in_weak_list(self):
+ """'mysecret' must be in the weak secrets blocklist."""
+ with open(os.path.join(DEPLOY_DIR, "auth.py")) as f:
+ source = f.read()
+ # Parse the source to find _WEAK_SECRETS set
+ self.assertIn("mysecret", source,
+ "'mysecret' must be listed in _WEAK_SECRETS blocklist")
+
+ def test_auto_generation_exists(self):
+ """auth.py must auto-generate key when none is set."""
+ with open(os.path.join(DEPLOY_DIR, "auth.py")) as f:
+ source = f.read()
+ self.assertIn("token_hex", source,
+ "auth.py must use secrets.token_hex for auto-generation")
+
+
+# ============================================================================
+# B2-V3: eval() removed from /config/dump
+# ============================================================================
+
+class TestConfigDumpNoEval(unittest.TestCase):
+ """Verify eval() is completely removed from the /config/dump path."""
+
+ def test_no_safe_eval_config(self):
+ """_safe_eval_config function must be removed from server.py."""
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ self.assertNotIn("def _safe_eval_config", source,
+ "_safe_eval_config must be deleted (replaced with JSON input)")
+
+ def test_config_from_json_exists(self):
+ """_config_from_json function must exist."""
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ self.assertIn("def _config_from_json", source,
+ "_config_from_json must replace _safe_eval_config")
+
+ def test_config_dump_has_auth(self):
+ """config_dump endpoint must require authentication."""
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ # Find the config_dump function and check it has token_dep
+ idx = source.index("config_dump")
+ # Look backwards for the decorator/function definition area
+ nearby = source[max(0, idx-200):idx+200]
+ self.assertIn("token_dep", nearby,
+ "/config/dump must require token_dep authentication")
+
+ def test_no_eval_in_config_path(self):
+ """No eval() call should exist in the config dump code path."""
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ # The old allowlist constants should be gone
+ self.assertNotIn("_SAFE_CONFIG_ALLOWED_NAMES", source,
+ "Old eval allowlist constants should be removed")
+ self.assertNotIn("_SAFE_CONFIG_ALLOWED_ATTRS", source,
+ "Old eval allowlist constants should be removed")
+
+
+# ============================================================================
+# B2-V1: /execute_js disabled by default
+# ============================================================================
+
+class TestExecuteJsDisabled(unittest.TestCase):
+ """Verify /execute_js is disabled by default with proper guards."""
+
+ def test_execute_js_flag_exists(self):
+ """EXECUTE_JS_ENABLED flag must exist in server.py."""
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ self.assertIn("EXECUTE_JS_ENABLED", source)
+
+ def test_execute_js_disabled_by_default(self):
+ """EXECUTE_JS_ENABLED must default to false."""
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ # Find the line that sets EXECUTE_JS_ENABLED
+ for line in source.splitlines():
+ if "EXECUTE_JS_ENABLED" in line and "os.environ" in line:
+ self.assertIn('"false"', line,
+ "EXECUTE_JS_ENABLED must default to 'false'")
+ return
+ self.fail("Could not find EXECUTE_JS_ENABLED env var line")
+
+ def test_execute_js_checks_flag(self):
+ """execute_js endpoint must check EXECUTE_JS_ENABLED."""
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ idx = source.index("async def execute_js")
+ func_body = source[idx:idx+3000]
+ self.assertIn("EXECUTE_JS_ENABLED", func_body,
+ "execute_js must check EXECUTE_JS_ENABLED flag")
+
+ def test_execute_js_has_ssrf_check(self):
+ """execute_js must validate URL against SSRF blocklist."""
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ idx = source.index("async def execute_js")
+ func_body = source[idx:idx+3000]
+ self.assertIn("validate_webhook_url", func_body,
+ "execute_js must validate URL against SSRF blocklist")
+
+ def test_disable_web_security_removed_from_defaults(self):
+ """--disable-web-security must not be in default browser args."""
+ with open(os.path.join(DEPLOY_DIR, "utils.py")) as f:
+ source = f.read()
+ # Find the DEFAULT_CONFIG extra_args
+ tree = ast.parse(source)
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Constant) and node.value == "--disable-web-security":
+ self.fail("--disable-web-security must not be in DEFAULT_CONFIG extra_args")
+
+ def test_disable_web_security_removed_from_config_yml(self):
+ """--disable-web-security must not be active in config.yml."""
+ with open(os.path.join(DEPLOY_DIR, "config.yml")) as f:
+ for line in f:
+ stripped = line.strip()
+ if stripped == '- "--disable-web-security"':
+ self.fail("--disable-web-security must not be an active entry in config.yml")
+
+
+# ============================================================================
+# B2-V4: Hook Sandbox __builtins__ Escape
+# ============================================================================
+
+class TestHookSandboxBugreport(unittest.TestCase):
+ """Test the specific __builtins__ escape vector reported by by111."""
+
+ @classmethod
+ def setUpClass(cls):
+ """Build hook sandbox exactly as hook_manager does."""
+ safe_builtins = {}
+ allowed_builtins = [
+ 'print', 'len', 'str', 'int', 'float', 'bool',
+ 'list', 'dict', 'set', 'tuple', 'range', 'enumerate',
+ 'zip', 'map', 'filter', 'any', 'all', 'sum', 'min', 'max',
+ 'sorted', 'reversed', 'abs', 'round', 'isinstance',
+ 'callable', 'iter', 'next',
+ ]
+ for name in allowed_builtins:
+ if hasattr(builtins, name):
+ safe_builtins[name] = getattr(builtins, name)
+ cls.safe_builtins = safe_builtins
+
+ def _make_namespace(self):
+ import asyncio as _asyncio_mod
+ import json as _json_mod
+ import re as _re_mod
+ from typing import Dict, List, Optional
+
+ def _safe_module(mod, exclude_attrs=None):
+ proxy = types.ModuleType(mod.__name__)
+ skip = {"__builtins__", "__loader__", "__spec__"}
+ if exclude_attrs:
+ skip.update(exclude_attrs)
+ for attr in dir(mod):
+ if attr in skip:
+ continue
+ try:
+ setattr(proxy, attr, getattr(mod, attr))
+ except (AttributeError, TypeError):
+ pass
+ return proxy
+
+ namespace = {
+ '__name__': 'test_hook',
+ '__builtins__': dict(self.safe_builtins),
+ }
+ namespace["asyncio"] = _safe_module(_asyncio_mod, {
+ "subprocess", "create_subprocess_exec", "create_subprocess_shell"
+ })
+ namespace["json"] = _safe_module(_json_mod)
+ namespace["re"] = _safe_module(_re_mod)
+ namespace["Dict"] = Dict
+ namespace["List"] = List
+ namespace["Optional"] = Optional
+ return namespace
+
+ # -- The exact attack from by111's report --
+
+ def test_asyncio_builtins_import_blocked(self):
+ """asyncio.__builtins__['__import__'] must not be accessible."""
+ ns = self._make_namespace()
+ self.assertFalse(hasattr(ns["asyncio"], "__builtins__"),
+ "asyncio proxy must not have __builtins__")
+
+ def test_json_builtins_import_blocked(self):
+ """json.__builtins__['__import__'] must not be accessible."""
+ ns = self._make_namespace()
+ self.assertFalse(hasattr(ns["json"], "__builtins__"),
+ "json proxy must not have __builtins__")
+
+ def test_re_builtins_import_blocked(self):
+ """re.__builtins__['__import__'] must not be accessible."""
+ ns = self._make_namespace()
+ self.assertFalse(hasattr(ns["re"], "__builtins__"),
+ "re proxy must not have __builtins__")
+
+ def test_module_loader_not_copied(self):
+ """Real module's __loader__ must not be copied to proxy."""
+ import asyncio as real_asyncio
+ ns = self._make_namespace()
+ # Proxy may have a default __loader__ from types.ModuleType,
+ # but it must NOT be the real module's loader
+ proxy_loader = getattr(ns["asyncio"], "__loader__", None)
+ real_loader = getattr(real_asyncio, "__loader__", None)
+ if proxy_loader is not None and real_loader is not None:
+ self.assertIsNot(proxy_loader, real_loader,
+ "Proxy must not have the real module's __loader__")
+
+ def test_module_spec_not_copied(self):
+ """Real module's __spec__ must not be copied to proxy."""
+ import asyncio as real_asyncio
+ ns = self._make_namespace()
+ proxy_spec = getattr(ns["asyncio"], "__spec__", None)
+ real_spec = getattr(real_asyncio, "__spec__", None)
+ if proxy_spec is not None and real_spec is not None:
+ self.assertIsNot(proxy_spec, real_spec,
+ "Proxy must not have the real module's __spec__")
+
+ def test_by111_exploit_via_asyncio(self):
+ """Exact exploit from by111: asyncio.__builtins__['__import__']('os')."""
+ ns = self._make_namespace()
+ code = '''
+async def hook(page, **kw):
+ real_import = asyncio.__builtins__['__import__']
+ os = real_import('os')
+ return os.system('id')
+'''
+ with self.assertRaises((AttributeError, KeyError, TypeError)):
+ exec(code, ns)
+ import asyncio
+ asyncio.get_event_loop().run_until_complete(ns['hook'](None))
+
+ def test_getattr_not_in_builtins(self):
+ """getattr must not be available (enables attribute-based escape)."""
+ ns = self._make_namespace()
+ self.assertNotIn('getattr', ns['__builtins__'])
+
+ def test_type_not_in_builtins(self):
+ """type must not be available (enables __subclasses__ MRO chain)."""
+ ns = self._make_namespace()
+ self.assertNotIn('type', ns['__builtins__'])
+
+ def test_build_class_not_in_builtins(self):
+ """__build_class__ must not be available."""
+ ns = self._make_namespace()
+ self.assertNotIn('__build_class__', ns['__builtins__'])
+
+ def test_hasattr_not_in_builtins(self):
+ """hasattr must not be available (information disclosure)."""
+ ns = self._make_namespace()
+ self.assertNotIn('hasattr', ns['__builtins__'])
+
+ # -- asyncio still works for legitimate hooks --
+
+ def test_asyncio_sleep_works(self):
+ ns = self._make_namespace()
+ self.assertTrue(hasattr(ns["asyncio"], "sleep"))
+
+ def test_asyncio_gather_works(self):
+ ns = self._make_namespace()
+ self.assertTrue(hasattr(ns["asyncio"], "gather"))
+
+ def test_json_loads_works(self):
+ ns = self._make_namespace()
+ self.assertTrue(hasattr(ns["json"], "loads"))
+
+ def test_re_compile_works(self):
+ ns = self._make_namespace()
+ self.assertTrue(hasattr(ns["re"], "compile"))
+
+
+# ============================================================================
+# Source-level verification for hook_manager.py
+# ============================================================================
+
+class TestHookManagerSourceClean(unittest.TestCase):
+ """Verify hook_manager.py source has all dangerous builtins removed."""
+
+ def test_getattr_removed(self):
+ with open(os.path.join(DEPLOY_DIR, "hook_manager.py")) as f:
+ source = f.read()
+ tree = ast.parse(source)
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Assign):
+ for target in node.targets:
+ if isinstance(target, ast.Name) and target.id == "allowed_builtins":
+ if isinstance(node.value, ast.List):
+ vals = [e.value for e in node.value.elts if isinstance(e, ast.Constant)]
+ self.assertNotIn("getattr", vals)
+ self.assertNotIn("setattr", vals)
+ self.assertNotIn("hasattr", vals)
+ self.assertNotIn("type", vals)
+ self.assertNotIn("__build_class__", vals)
+ return
+ self.fail("Could not find allowed_builtins in hook_manager.py")
+
+ def test_safe_module_strips_builtins(self):
+ """_safe_module function must skip __builtins__."""
+ with open(os.path.join(DEPLOY_DIR, "hook_manager.py")) as f:
+ source = f.read()
+ self.assertIn("__builtins__", source)
+ self.assertIn("__loader__", source)
+ self.assertIn("__spec__", source)
+
+
+if __name__ == "__main__":
+ print("=" * 70)
+ print("Crawl4AI Security Tests - Batch 2 (2026-04-14)")
+ print("=" * 70)
+ print()
+ unittest.main(verbosity=2)
diff --git a/deploy/docker/utils.py b/deploy/docker/utils.py
index 2a82b22b..e2ae562b 100644
--- a/deploy/docker/utils.py
+++ b/deploy/docker/utils.py
@@ -72,7 +72,6 @@ DEFAULT_CONFIG = {
"--disable-dev-shm-usage",
"--disable-gpu",
"--disable-software-rasterizer",
- "--disable-web-security",
"--allow-insecure-localhost",
"--ignore-certificate-errors",
],