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): patch 4 vulns - file write, SSRF, monitor auth, XSS

unclecode7976b45817f6
diff --git a/deploy/docker/job.py b/deploy/docker/job.py
index 8fae16cd..51f49a59 100644
--- a/deploy/docker/job.py
+++ b/deploy/docker/job.py
@@ -4,7 +4,7 @@ Relies on the existing Redis task helpers in api.py
"""
from typing import Dict, Optional, Callable
-from fastapi import APIRouter, BackgroundTasks, Depends, Request
+from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request
from pydantic import BaseModel, HttpUrl
from api import (
@@ -60,6 +60,11 @@ async def llm_job_enqueue(
):
webhook_config = None
if payload.webhook_config:
+ from utils import validate_webhook_url
+ try:
+ validate_webhook_url(str(payload.webhook_config.webhook_url))
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e))
webhook_config = payload.webhook_config.model_dump(mode='json')
return await handle_llm_request(
@@ -96,6 +101,11 @@ async def crawl_job_enqueue(
):
webhook_config = None
if payload.webhook_config:
+ from utils import validate_webhook_url
+ try:
+ validate_webhook_url(str(payload.webhook_config.webhook_url))
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e))
webhook_config = payload.webhook_config.model_dump(mode='json')
return await handle_crawl_job(
diff --git a/deploy/docker/monitor.py b/deploy/docker/monitor.py
index 62a59777..bbe48f1f 100644
--- a/deploy/docker/monitor.py
+++ b/deploy/docker/monitor.py
@@ -1,4 +1,5 @@
# monitor.py - Real-time monitoring stats with Redis persistence
+import html
import time
import json
import asyncio
@@ -42,7 +43,7 @@ class MonitorStats:
req_info = {
"id": request_id,
"endpoint": endpoint,
- "url": url[:100], # Truncate long URLs
+ "url": html.escape(url[:100]), # Truncate + escape for XSS prevention
"start_time": time.time(),
"config_sig": config.get("sig", "default") if config else "default",
"mem_start": psutil.Process().memory_info().rss / (1024 * 1024)
@@ -105,7 +106,7 @@ class MonitorStats:
"timestamp": end_time,
"endpoint": endpoint,
"url": req_info["url"],
- "error": error,
+ "error": html.escape(str(error)),
"request_id": request_id
})
diff --git a/deploy/docker/monitor_routes.py b/deploy/docker/monitor_routes.py
index fdf156de..d77f47c1 100644
--- a/deploy/docker/monitor_routes.py
+++ b/deploy/docker/monitor_routes.py
@@ -360,6 +360,15 @@ async def websocket_endpoint(websocket: WebSocket):
- Browser pool status
- Timeline data
"""
+ # WebSocket endpoints don't inherit router dependencies in FastAPI.
+ # Validate token from query params if auth is configured.
+ import os
+ expected_token = os.environ.get("CRAWL4AI_API_TOKEN", "")
+ if expected_token:
+ token = websocket.query_params.get("token", "")
+ if token != expected_token:
+ await websocket.close(code=4003, reason="Authentication required")
+ return
await websocket.accept()
logger.info("WebSocket client connected")
diff --git a/deploy/docker/schemas.py b/deploy/docker/schemas.py
index ef75ce8b..8656c491 100644
--- a/deploy/docker/schemas.py
+++ b/deploy/docker/schemas.py
@@ -1,6 +1,6 @@
from typing import List, Optional, Dict
from enum import Enum
-from pydantic import BaseModel, Field, HttpUrl
+from pydantic import BaseModel, Field, HttpUrl, field_validator
from utils import FilterType
@@ -76,10 +76,28 @@ class ScreenshotRequest(BaseModel):
wait_for_images: Optional[bool] = False
output_path: Optional[str] = None
+ @field_validator("output_path")
+ @classmethod
+ def reject_traversal(cls, v):
+ if v is None:
+ return v
+ if ".." in v.replace("\\", "/").split("/"):
+ raise ValueError("output_path must not contain path traversal sequences")
+ return v
+
class PDFRequest(BaseModel):
url: str
output_path: Optional[str] = None
+ @field_validator("output_path")
+ @classmethod
+ def reject_traversal(cls, v):
+ if v is None:
+ return v
+ if ".." in v.replace("\\", "/").split("/"):
+ raise ValueError("output_path must not contain path traversal sequences")
+ return v
+
class JSEndpointRequest(BaseModel):
url: str
diff --git a/deploy/docker/server.py b/deploy/docker/server.py
index b027ee1f..6633bba3 100644
--- a/deploy/docker/server.py
+++ b/deploy/docker/server.py
@@ -35,7 +35,8 @@ from schemas import (
)
from utils import (
- FilterType, load_config, setup_logging, verify_email_domain
+ FilterType, load_config, setup_logging, verify_email_domain,
+ validate_output_path, validate_webhook_url,
)
import os
import sys
@@ -386,7 +387,7 @@ app.include_router(init_job_router(redis, config, token_dep))
# ── monitor router ──────────────────────────────────────────
from monitor_routes import router as monitor_router
-app.include_router(monitor_router)
+app.include_router(monitor_router, dependencies=[Depends(token_dep)])
logger = logging.getLogger(__name__)
@@ -503,7 +504,7 @@ async def generate_screenshot(
raise HTTPException(500, detail=results[0].error_message or "Crawl failed")
screenshot_data = results[0].screenshot
if body.output_path:
- abs_path = os.path.abspath(body.output_path)
+ abs_path = validate_output_path(body.output_path)
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
with open(abs_path, "wb") as f:
f.write(base64.b64decode(screenshot_data))
@@ -541,7 +542,7 @@ async def generate_pdf(
raise HTTPException(500, detail=results[0].error_message or "Crawl failed")
pdf_data = results[0].pdf
if body.output_path:
- abs_path = os.path.abspath(body.output_path)
+ abs_path = validate_output_path(body.output_path)
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
with open(abs_path, "wb") as f:
f.write(pdf_data)
diff --git a/deploy/docker/static/monitor/index.html b/deploy/docker/static/monitor/index.html
index a9f8ed39..d0ff878a 100644
--- a/deploy/docker/static/monitor/index.html
+++ b/deploy/docker/static/monitor/index.html
@@ -458,6 +458,14 @@
document.getElementById('last-update').textContent = 'Live: ' + new Date().toLocaleTimeString();
}
+ // XSS prevention: escape user-supplied content before innerHTML injection
+ function escapeHtml(text) {
+ if (text == null) return '';
+ const div = document.createElement('div');
+ div.textContent = String(text);
+ return div.innerHTML;
+ }
+
function updateRequestsDisplay(requests) {
// Update active requests count
const activeCount = document.getElementById('active-count');
@@ -471,9 +479,9 @@
} else {
activeList.innerHTML = requests.active.map(req => `
<div class="flex items-center justify-between p-2 bg-dark rounded border border-border">
- <span class="text-primary">${req.id.substring(0, 8)}</span>
- <span class="text-secondary">${req.endpoint}</span>
- <span class="text-light truncate max-w-[200px]" title="${req.url}">${req.url}</span>
+ <span class="text-primary">${escapeHtml(req.id.substring(0, 8))}</span>
+ <span class="text-secondary">${escapeHtml(req.endpoint)}</span>
+ <span class="text-light truncate max-w-[200px]" title="${escapeHtml(req.url)}">${escapeHtml(req.url)}</span>
<span class="text-accent">${req.elapsed.toFixed(1)}s</span>
<span class="pulse-slow">⏳</span>
</div>
@@ -489,9 +497,9 @@
} else {
completedList.innerHTML = requests.completed.map(req => `
<div class="flex items-center gap-3 p-2 bg-dark rounded">
- <span class="text-secondary w-16 flex-shrink-0">${req.id.substring(0, 8)}</span>
- <span class="text-secondary w-16 flex-shrink-0">${req.endpoint}</span>
- <span class="text-light truncate flex-1" title="${req.url}">${req.url}</span>
+ <span class="text-secondary w-16 flex-shrink-0">${escapeHtml(req.id.substring(0, 8))}</span>
+ <span class="text-secondary w-16 flex-shrink-0">${escapeHtml(req.endpoint)}</span>
+ <span class="text-light truncate flex-1" title="${escapeHtml(req.url)}">${escapeHtml(req.url)}</span>
<span class="w-12 flex-shrink-0 text-right">${req.elapsed.toFixed(2)}s</span>
<span class="text-secondary w-16 flex-shrink-0 text-right">${req.mem_delta > 0 ? '+' : ''}${req.mem_delta}MB</span>
<span class="w-12 flex-shrink-0 text-right">${req.success ? '✅' : '❌'} ${req.status_code}</span>
@@ -585,10 +593,10 @@
return `<div class="p-2 bg-dark rounded border border-red-500">
<div class="flex justify-between">
<span class="text-secondary">${time}</span>
- <span class="text-red-500">${err.endpoint}</span>
+ <span class="text-red-500">${escapeHtml(err.endpoint)}</span>
</div>
- <div class="text-xs text-light mt-1">${err.url}</div>
- <div class="text-xs text-red-400 mt-1 font-mono">${err.error}</div>
+ <div class="text-xs text-light mt-1">${escapeHtml(err.url)}</div>
+ <div class="text-xs text-red-400 mt-1 font-mono">${escapeHtml(err.error)}</div>
</div>`;
}).join('');
}
@@ -695,9 +703,9 @@
} else {
activeList.innerHTML = data.active.map(req => `
<div class="flex items-center justify-between p-2 bg-dark rounded border border-border">
- <span class="text-primary">${req.id.substring(0, 8)}</span>
- <span class="text-secondary">${req.endpoint}</span>
- <span class="text-light truncate max-w-[200px]" title="${req.url}">${req.url}</span>
+ <span class="text-primary">${escapeHtml(req.id.substring(0, 8))}</span>
+ <span class="text-secondary">${escapeHtml(req.endpoint)}</span>
+ <span class="text-light truncate max-w-[200px]" title="${escapeHtml(req.url)}">${escapeHtml(req.url)}</span>
<span class="text-accent">${req.elapsed.toFixed(1)}s</span>
<span class="pulse-slow">⏳</span>
</div>
@@ -711,9 +719,9 @@
} else {
completedList.innerHTML = data.completed.map(req => `
<div class="flex items-center gap-3 p-2 bg-dark rounded">
- <span class="text-secondary w-16 flex-shrink-0">${req.id.substring(0, 8)}</span>
- <span class="text-secondary w-16 flex-shrink-0">${req.endpoint}</span>
- <span class="text-light truncate flex-1" title="${req.url}">${req.url}</span>
+ <span class="text-secondary w-16 flex-shrink-0">${escapeHtml(req.id.substring(0, 8))}</span>
+ <span class="text-secondary w-16 flex-shrink-0">${escapeHtml(req.endpoint)}</span>
+ <span class="text-light truncate flex-1" title="${escapeHtml(req.url)}">${escapeHtml(req.url)}</span>
<span class="w-12 flex-shrink-0 text-right">${req.elapsed.toFixed(2)}s</span>
<span class="text-secondary w-16 flex-shrink-0 text-right">${req.mem_delta > 0 ? '+' : ''}${req.mem_delta}MB</span>
<span class="w-12 flex-shrink-0 text-right">${req.success ? '✅' : '❌'} ${req.status_code}</span>
@@ -808,10 +816,10 @@
return `<div class="p-2 bg-dark rounded border border-red-500">
<div class="flex justify-between">
<span class="text-secondary">${time}</span>
- <span class="text-red-500">${err.endpoint}</span>
+ <span class="text-red-500">${escapeHtml(err.endpoint)}</span>
</div>
- <div class="text-xs text-light mt-1">${err.url}</div>
- <div class="text-xs text-red-400 mt-1 font-mono">${err.error}</div>
+ <div class="text-xs text-light mt-1">${escapeHtml(err.url)}</div>
+ <div class="text-xs text-red-400 mt-1 font-mono">${escapeHtml(err.error)}</div>
</div>`;
}).join('');
}
diff --git a/deploy/docker/tests/test_security_2026_04.py b/deploy/docker/tests/test_security_2026_04.py
new file mode 100644
index 00000000..e7ecebdd
--- /dev/null
+++ b/deploy/docker/tests/test_security_2026_04.py
@@ -0,0 +1,295 @@
+#!/usr/bin/env python3
+"""
+Adversarial security tests for the 4 vulns reported 2026-04-13.
+Self-contained: copies validation logic to avoid import issues with dns.resolver etc.
+
+Vuln 1: Arbitrary File Write via /screenshot + /pdf output_path
+Vuln 2: Monitor Auth Bypass (structural source check)
+Vuln 3: Stored XSS in Monitor Dashboard (server-side + client-side)
+Vuln 4: SSRF via Webhook URL
+"""
+
+import os
+import sys
+import unittest
+import ipaddress
+import socket
+from urllib.parse import urlparse
+
+
+# ============================================================================
+# Local copies of security utilities (to avoid dns.resolver import in utils.py)
+# ============================================================================
+
+ALLOWED_OUTPUT_DIR = os.environ.get("CRAWL4AI_OUTPUT_DIR", "/tmp/crawl4ai-outputs")
+
+
+def validate_output_path(user_path):
+ safe_path = os.path.normpath(user_path).lstrip(os.sep)
+ abs_path = os.path.abspath(os.path.join(ALLOWED_OUTPUT_DIR, safe_path))
+ abs_allowed = os.path.abspath(ALLOWED_OUTPUT_DIR) + os.sep
+ if not abs_path.startswith(abs_allowed):
+ raise ValueError(f"output_path must resolve within {ALLOWED_OUTPUT_DIR}")
+ return abs_path
+
+
+_BLOCKED_NETWORKS = [
+ ipaddress.ip_network("0.0.0.0/8"),
+ ipaddress.ip_network("10.0.0.0/8"),
+ ipaddress.ip_network("100.64.0.0/10"),
+ ipaddress.ip_network("127.0.0.0/8"),
+ ipaddress.ip_network("169.254.0.0/16"),
+ ipaddress.ip_network("172.16.0.0/12"),
+ ipaddress.ip_network("192.0.0.0/24"),
+ ipaddress.ip_network("192.168.0.0/16"),
+ ipaddress.ip_network("198.18.0.0/15"),
+ ipaddress.ip_network("::1/128"),
+ ipaddress.ip_network("fc00::/7"),
+ ipaddress.ip_network("fe80::/10"),
+]
+_BLOCKED_HOSTNAMES = {
+ "localhost", "metadata.google.internal", "metadata",
+ "kubernetes.default", "kubernetes.default.svc",
+}
+
+
+def validate_webhook_url(url):
+ parsed = urlparse(str(url))
+ hostname = parsed.hostname
+ if not hostname:
+ raise ValueError("Webhook URL must have a valid hostname")
+ hostname_lower = hostname.lower()
+ if hostname_lower in _BLOCKED_HOSTNAMES:
+ raise ValueError(f"Webhook URL hostname '{hostname}' is blocked")
+ if hostname_lower.startswith("host.docker.internal"):
+ raise ValueError(f"Webhook URL hostname '{hostname}' is blocked")
+ try:
+ resolved = socket.getaddrinfo(hostname, None)
+ except socket.gaierror:
+ raise ValueError(f"Cannot resolve webhook hostname '{hostname}'")
+ for _, _, _, _, sockaddr in resolved:
+ ip = ipaddress.ip_address(sockaddr[0])
+ for network in _BLOCKED_NETWORKS:
+ if ip in network:
+ raise ValueError(f"Webhook URL resolves to blocked address: {ip}")
+
+
+DEPLOY_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
+
+
+# ============================================================================
+# VULN 1: Arbitrary File Write - Path Traversal
+# ============================================================================
+
+class TestPathTraversalBlocked(unittest.TestCase):
+ """Test validate_output_path blocks all traversal attempts."""
+
+ def test_absolute_path_gets_jailed(self):
+ """Absolute paths get stripped and jailed inside allowed dir."""
+ result = validate_output_path("/app/server.py")
+ self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))
+ self.assertNotEqual(result, "/app/server.py")
+
+ def test_absolute_etc_passwd_gets_jailed(self):
+ result = validate_output_path("/etc/passwd")
+ self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))
+ self.assertNotEqual(result, "/etc/passwd")
+
+ def test_relative_traversal_simple(self):
+ with self.assertRaises(ValueError):
+ validate_output_path("../../etc/passwd")
+
+ def test_relative_traversal_deep(self):
+ with self.assertRaises(ValueError):
+ validate_output_path("foo/../../bar/../../../app/evil.py")
+
+ def test_absolute_path_home_gets_jailed(self):
+ result = validate_output_path("/home/appuser/.bashrc")
+ self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))
+
+ def test_absolute_path_tmp_outside_gets_jailed(self):
+ result = validate_output_path("/tmp/other-dir/evil.py")
+ self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))
+
+ def test_simple_filename(self):
+ result = validate_output_path("test.png")
+ self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))
+ self.assertTrue(result.endswith("test.png"))
+
+ def test_subdirectory(self):
+ result = validate_output_path("subdir/deep/test.png")
+ self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))
+
+ def test_filename_with_dots(self):
+ result = validate_output_path("my.screenshot.2024.png")
+ self.assertTrue(result.endswith("my.screenshot.2024.png"))
+
+
+class TestPydanticPathValidator(unittest.TestCase):
+ """Verify schemas.py has traversal rejection on output_path."""
+
+ def test_schemas_has_validator(self):
+ with open(os.path.join(DEPLOY_DIR, "schemas.py")) as f:
+ source = f.read()
+ self.assertIn("reject_traversal", source,
+ "schemas.py must have reject_traversal validator on output_path")
+ self.assertIn('".."', source,
+ "Validator must check for '..' traversal")
+
+
+# ============================================================================
+# VULN 2: Monitor Auth Bypass (structural check)
+# ============================================================================
+
+class TestMonitorAuthStructural(unittest.TestCase):
+
+ def test_monitor_router_has_auth(self):
+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:
+ source = f.read()
+ # Find the line with monitor_router
+ for line in source.splitlines():
+ if "monitor_router" in line and "include_router" in line:
+ self.assertIn("dependencies=", line,
+ "Monitor router must have dependencies=[Depends(token_dep)]")
+ return
+ self.fail("Could not find monitor_router include_router line")
+
+ def test_websocket_has_token_check(self):
+ with open(os.path.join(DEPLOY_DIR, "monitor_routes.py")) as f:
+ source = f.read()
+ self.assertIn("CRAWL4AI_API_TOKEN", source,
+ "WebSocket endpoint must check CRAWL4AI_API_TOKEN")
+ self.assertIn("websocket.close", source,
+ "WebSocket must close connection on auth failure")
+
+
+# ============================================================================
+# VULN 3: Stored XSS (server-side + client-side)
+# ============================================================================
+
+class TestXSSPrevention(unittest.TestCase):
+
+ def test_html_escape_blocks_script_tags(self):
+ import html
+ payload = '<script>alert(document.cookie)</script>'
+ escaped = html.escape(payload)
+ self.assertNotIn("<script>", escaped)
+ self.assertIn("&lt;script&gt;", escaped)
+
+ def test_html_escape_blocks_img_tag(self):
+ import html
+ payload = '"><img src=x onerror=alert(1)>'
+ escaped = html.escape(payload)
+ self.assertNotIn("<img", escaped)
+ self.assertIn("&lt;img", escaped)
+
+ def test_monitor_py_uses_html_escape(self):
+ with open(os.path.join(DEPLOY_DIR, "monitor.py")) as f:
+ source = f.read()
+ self.assertIn("import html", source)
+ self.assertIn("html.escape(url", source)
+ self.assertIn("html.escape(str(error)", source)
+
+ def test_index_html_has_escape_function(self):
+ html_path = os.path.join(DEPLOY_DIR, "static", "monitor", "index.html")
+ with open(html_path) as f:
+ source = f.read()
+ self.assertIn("function escapeHtml(", source)
+
+ def test_index_html_no_raw_url_injection(self):
+ html_path = os.path.join(DEPLOY_DIR, "static", "monitor", "index.html")
+ with open(html_path) as f:
+ source = f.read()
+ self.assertNotIn("${req.url}", source, "Raw ${req.url} found")
+ self.assertNotIn("${err.url}", source, "Raw ${err.url} found")
+ self.assertNotIn("${err.error}", source, "Raw ${err.error} found")
+
+
+# ============================================================================
+# VULN 4: SSRF via Webhook URL
+# ============================================================================
+
+class TestSSRFBlocked(unittest.TestCase):
+
+ def test_localhost_ip(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://127.0.0.1:9999/steal")
+
+ def test_localhost_hostname(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://localhost:9999/steal")
+
+ def test_loopback_127_x(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://127.0.0.2:9999/steal")
+
+ def test_10_network(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://10.0.0.1:8080/admin")
+
+ def test_172_16_network(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://172.16.0.1:8080/admin")
+
+ def test_192_168_network(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://192.168.1.1:8080/admin")
+
+ def test_aws_metadata_ip(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://169.254.169.254/latest/meta-data/")
+
+ def test_gcp_metadata_hostname(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://metadata.google.internal/computeMetadata/v1/")
+
+ def test_docker_internal(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://host.docker.internal:9998/steal")
+
+ def test_kubernetes_default(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http://kubernetes.default/api/v1/secrets")
+
+ def test_empty_hostname(self):
+ with self.assertRaises(ValueError):
+ validate_webhook_url("http:///steal")
+
+ def test_valid_external_url(self):
+ validate_webhook_url("https://webhook.site/test-uuid")
+ validate_webhook_url("https://hooks.slack.com/services/T00/B00/xxx")
+
+ def test_valid_external_with_port(self):
+ """External URL with port -- may fail DNS in CI, that's expected."""
+ try:
+ validate_webhook_url("https://google.com:443/webhook")
+ except ValueError as e:
+ if "Cannot resolve" in str(e):
+ self.skipTest("DNS resolution unavailable in this environment")
+ raise
+
+
+class TestWebhookSourceChecks(unittest.TestCase):
+
+ def test_follow_redirects_disabled(self):
+ with open(os.path.join(DEPLOY_DIR, "webhook.py")) as f:
+ source = f.read()
+ self.assertIn("follow_redirects=False", source)
+
+ def test_webhook_validates_at_send_time(self):
+ with open(os.path.join(DEPLOY_DIR, "webhook.py")) as f:
+ source = f.read()
+ self.assertIn("validate_webhook_url", source)
+
+ def test_job_validates_webhook(self):
+ with open(os.path.join(DEPLOY_DIR, "job.py")) as f:
+ source = f.read()
+ self.assertIn("validate_webhook_url", source)
+
+
+if __name__ == "__main__":
+ print("=" * 70)
+ print("Crawl4AI Security Tests - 2026-04-13 Vulnerabilities")
+ print("=" * 70)
+ print()
+ unittest.main(verbosity=2)
diff --git a/deploy/docker/utils.py b/deploy/docker/utils.py
index 585d8941..2a82b22b 100644
--- a/deploy/docker/utils.py
+++ b/deploy/docker/utils.py
@@ -293,6 +293,73 @@ def get_llm_base_url(config: Dict, provider: Optional[str] = None) -> Optional[s
return os.environ.get("LLM_BASE_URL")
+# ── Security utilities ──────────────────────────────────────
+
+ALLOWED_OUTPUT_DIR = os.environ.get("CRAWL4AI_OUTPUT_DIR", "/tmp/crawl4ai-outputs")
+
+
+def validate_output_path(user_path: str) -> str:
+ """Resolve and restrict output_path to ALLOWED_OUTPUT_DIR.
+ Prevents arbitrary file write via path traversal."""
+ from fastapi import HTTPException
+ safe_path = os.path.normpath(user_path).lstrip(os.sep)
+ abs_path = os.path.abspath(os.path.join(ALLOWED_OUTPUT_DIR, safe_path))
+ abs_allowed = os.path.abspath(ALLOWED_OUTPUT_DIR) + os.sep
+ if not abs_path.startswith(abs_allowed):
+ raise HTTPException(
+ status_code=400,
+ detail=f"output_path must resolve within {ALLOWED_OUTPUT_DIR}"
+ )
+ return abs_path
+
+
+import ipaddress
+import socket
+from urllib.parse import urlparse
+
+_BLOCKED_NETWORKS = [
+ ipaddress.ip_network("0.0.0.0/8"),
+ ipaddress.ip_network("10.0.0.0/8"),
+ ipaddress.ip_network("100.64.0.0/10"),
+ ipaddress.ip_network("127.0.0.0/8"),
+ ipaddress.ip_network("169.254.0.0/16"),
+ ipaddress.ip_network("172.16.0.0/12"),
+ ipaddress.ip_network("192.0.0.0/24"),
+ ipaddress.ip_network("192.168.0.0/16"),
+ ipaddress.ip_network("198.18.0.0/15"),
+ ipaddress.ip_network("::1/128"),
+ ipaddress.ip_network("fc00::/7"),
+ ipaddress.ip_network("fe80::/10"),
+]
+
+_BLOCKED_HOSTNAMES = {
+ "localhost", "metadata.google.internal", "metadata",
+ "kubernetes.default", "kubernetes.default.svc",
+}
+
+
+def validate_webhook_url(url: str) -> None:
+ """Reject webhook URLs targeting internal/private/reserved networks (SSRF protection)."""
+ parsed = urlparse(str(url))
+ hostname = parsed.hostname
+ if not hostname:
+ raise ValueError("Webhook URL must have a valid hostname")
+ hostname_lower = hostname.lower()
+ if hostname_lower in _BLOCKED_HOSTNAMES:
+ raise ValueError(f"Webhook URL hostname '{hostname}' is blocked")
+ if hostname_lower.startswith("host.docker.internal"):
+ raise ValueError(f"Webhook URL hostname '{hostname}' is blocked")
+ try:
+ resolved = socket.getaddrinfo(hostname, None)
+ except socket.gaierror:
+ raise ValueError(f"Cannot resolve webhook hostname '{hostname}'")
+ for _, _, _, _, sockaddr in resolved:
+ ip = ipaddress.ip_address(sockaddr[0])
+ for network in _BLOCKED_NETWORKS:
+ if ip in network:
+ raise ValueError(f"Webhook URL resolves to blocked address: {ip}")
+
+
def verify_email_domain(email: str) -> bool:
try:
domain = email.split('@')[1]
diff --git a/deploy/docker/webhook.py b/deploy/docker/webhook.py
index ebee9dff..4c409ae8 100644
--- a/deploy/docker/webhook.py
+++ b/deploy/docker/webhook.py
@@ -45,11 +45,15 @@ class WebhookDeliveryService:
Returns:
bool: True if delivered successfully, False otherwise
"""
+ # SECURITY: Validate webhook URL at send time (defense-in-depth against SSRF)
+ from utils import validate_webhook_url
+ validate_webhook_url(webhook_url)
+
default_headers = self.config.get("headers", {})
merged_headers = {**default_headers, **(headers or {})}
merged_headers["Content-Type"] = "application/json"
- async with httpx.AsyncClient(timeout=self.timeout) as client:
+ async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=False) as client:
for attempt in range(self.max_attempts):
try:
logger.info(