Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): SSRF parser-differential bypass (GHSA-g23j-2vwm-5c25) (#3873)

LearningCircuit88e13ff718ed
diff --git a/SECURITY.md b/SECURITY.md
index c48e02f3f3..fc0944886f 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -129,6 +129,15 @@ By setting this, the operator acknowledges the residual risk above. To minimise
The same DNS-rebinding caveat applies to `safe_requests` / `ssrf_validator.validate_url`, used for general HTTP fetches (RAG sources, web scraping). Egress restriction is the primary defense for that path as well.
+### Parser-Differential URL Bypass (GHSA-g23j-2vwm-5c25)
+
+A reporter ([@Fushuling](https://github.com/Fushuling), [@RacerZ-fighting](https://github.com/RacerZ-fighting)) demonstrated that Python's `urllib.parse.urlparse` and the `requests`/`urllib3` parser disagreed on URLs like `http://127.0.0.1\@1.1.1.1` — `urlparse` extracted `1.1.1.1` (passing the SSRF check) while `requests` connected to `127.0.0.1` (the actual destination). The fix has two layers:
+
+- **Layer 1 — input hygiene:** `RFC_FORBIDDEN_URL_CHARS_RE` in `ssrf_validator.py` rejects URLs containing backslash, ASCII control bytes, or whitespace. RFC 3986 forbids these characters in URLs, so legitimate fetches are unaffected.
+- **Layer 2 — authoritative parser:** Hostname extraction now uses `urllib3.util.parse_url`, the same parser `requests` uses internally. Validator and HTTP client cannot disagree on destination by construction. This is the load-bearing defence on the `SafeSession.send` path, where `requests` has already canonicalised `\` to `%5C` during `.prepare()`.
+
+Both `ssrf_validator.validate_url` and `NotificationURLValidator.validate_service_url` (HTTP/HTTPS branch) carry the fix. Future edits to the SSRF path should preserve `RFC_FORBIDDEN_URL_CHARS_RE` and the `urllib3.util.parse_url` host extraction — reverting either reintroduces the bypass.
+
## Supported Versions
Security fixes are only provided for the latest release. Please upgrade to receive patches.
diff --git a/changelog.d/+ssrf-parser-differential.security.md b/changelog.d/+ssrf-parser-differential.security.md
new file mode 100644
index 0000000000..f54eb7025d
--- /dev/null
+++ b/changelog.d/+ssrf-parser-differential.security.md
@@ -0,0 +1,6 @@
+Fix SSRF parser-differential bypass (GHSA-g23j-2vwm-5c25). URLs containing
+backslash, whitespace, or ASCII control bytes are now rejected upfront by the
+SSRF validator and notification-URL validator; hostname extraction switched
+from `urllib.parse.urlparse` to `urllib3.util.parse_url` so the validator and
+the HTTP client agree on destination by construction. Credit: @Fushuling,
+@RacerZ-fighting.
diff --git a/src/local_deep_research/security/ip_ranges.py b/src/local_deep_research/security/ip_ranges.py
index af4e709e97..eb0c8adc14 100644
--- a/src/local_deep_research/security/ip_ranges.py
+++ b/src/local_deep_research/security/ip_ranges.py
@@ -21,5 +21,8 @@ PRIVATE_IP_RANGES = [
ipaddress.ip_network("169.254.0.0/16"), # Link-local
ipaddress.ip_network("fe80::/10"), # IPv6 link-local
ipaddress.ip_network("fc00::/7"), # IPv6 unique local
- ipaddress.ip_network("0.0.0.0/8"), # "This" network
+ ipaddress.ip_network("0.0.0.0/8"), # "This" network (IPv4 unspecified)
+ ipaddress.ip_network(
+ "::/128"
+ ), # IPv6 unspecified — Linux routes connections to local host
]
diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.py
index b6d9bdf615..6f2b4987f3 100644
--- a/src/local_deep_research/security/notification_validator.py
+++ b/src/local_deep_research/security/notification_validator.py
@@ -11,8 +11,11 @@ from concurrent.futures import ThreadPoolExecutor, TimeoutError
from typing import Optional, Tuple
from urllib.parse import urlparse
from loguru import logger
+from urllib3.exceptions import LocationParseError
+from urllib3.util import parse_url
from .ip_ranges import PRIVATE_IP_RANGES as _PRIVATE_IP_RANGES
+from .ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE
class NotificationURLValidationError(ValueError):
@@ -174,9 +177,24 @@ class NotificationURLValidator:
if not url or not isinstance(url, str):
return False, "Service URL must be a non-empty string"
- # Strip whitespace
+ # Strip whitespace (must run before the RFC-illegal char check
+ # so legitimate URLs with surrounding whitespace are not rejected).
url = url.strip()
+ # Reject URLs containing characters that drive parser-differential
+ # SSRF bypasses (backslash, whitespace, control bytes) — see
+ # GHSA-g23j-2vwm-5c25. The URL is omitted from the log line because
+ # userinfo (RFC 3986 §3.2.1) may contain credentials and rejected
+ # URLs are by definition adversarial-shaped.
+ if RFC_FORBIDDEN_URL_CHARS_RE.search(url):
+ logger.warning(
+ "Blocked notification URL containing RFC-illegal characters"
+ )
+ return (
+ False,
+ "URL contains characters that are not allowed (whitespace, backslash, or control bytes)",
+ )
+
# Parse URL
try:
parsed = urlparse(url)
@@ -208,18 +226,44 @@ class NotificationURLValidator:
f"Allowed: {', '.join(NotificationURLValidator.ALLOWED_SCHEMES[:5])}...",
)
- # For HTTP/HTTPS, check for private IPs (SSRF prevention)
+ # For HTTP/HTTPS, check for private IPs (SSRF prevention).
+ # Use urllib3 (the parser ``requests`` uses internally) instead of
+ # urlparse for hostname extraction — urlparse is vulnerable to
+ # parser-differential bypasses like ``http://127.0.0.1\@1.1.1.1``
+ # (GHSA-g23j-2vwm-5c25). For non-HTTP schemes (Apprise transports
+ # like discord://, slack://, mailto://) Apprise handles the URL
+ # itself and the parser-differential doesn't apply.
if scheme in ("http", "https") and not allow_private_ips:
- if parsed.hostname:
- if NotificationURLValidator._is_private_ip(parsed.hostname):
- logger.warning(
- f"Blocked private/internal IP in notification URL: "
- f"{parsed.hostname}"
- )
- return (
- False,
- f"Blocked private/internal IP address: {parsed.hostname}",
- )
+ try:
+ u3 = parse_url(url)
+ except LocationParseError:
+ logger.warning(
+ "Blocked notification URL: urllib3 parser rejected it"
+ )
+ return False, "Invalid URL format (parser rejected)"
+ hostname = u3.host
+ # Authority must be ASCII printable (forward-defence vs urllib3
+ # ever loosening its IDN handling).
+ if hostname and any(
+ ord(c) < 0x20 or ord(c) > 0x7E for c in hostname
+ ):
+ logger.warning(
+ "Blocked notification URL with non-ASCII / control bytes in host"
+ )
+ return False, "URL host contains disallowed characters"
+ if hostname and hostname.startswith("[") and hostname.endswith("]"):
+ hostname = hostname[1:-1]
+ if hostname:
+ hostname = hostname.rstrip(".")
+ if hostname and NotificationURLValidator._is_private_ip(hostname):
+ logger.warning(
+ f"Blocked private/internal IP in notification URL: "
+ f"{hostname}"
+ )
+ return (
+ False,
+ f"Blocked private/internal IP address: {hostname}",
+ )
# Passed all security checks
return True, None
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index 6d15123653..3591b862ad 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -6,10 +6,13 @@ by blocking requests to internal/private networks and enforcing safe schemes.
"""
import ipaddress
+import re
import socket
from urllib.parse import urlparse
from typing import Optional
from loguru import logger
+from urllib3.exceptions import LocationParseError
+from urllib3.util import parse_url
from .ip_ranges import PRIVATE_IP_RANGES as BLOCKED_IP_RANGES
@@ -20,6 +23,14 @@ AWS_METADATA_IP = "169.254.169.254"
# Allowed URL schemes
ALLOWED_SCHEMES = {"http", "https"}
+# RFC 3986 forbids these characters in URLs; their presence in a URL signals
+# a parser-differential attempt (GHSA-g23j-2vwm-5c25). \s covers space, \t,
+# \n, \r, \v, \f. Backslash is the load-bearing payload — Python's urlparse
+# treats it as a literal char while requests/urllib3 treat it as a path
+# delimiter, so a crafted URL like ``http://127.0.0.1\@1.1.1.1`` would
+# pass the urlparse-based hostname check but actually connect to 127.0.0.1.
+RFC_FORBIDDEN_URL_CHARS_RE = re.compile(r"[\\\s\x00-\x1f\x7f]")
+
def is_ip_blocked(
ip_str: str, allow_localhost: bool = False, allow_private_ips: bool = False
@@ -129,7 +140,18 @@ def validate_url(
Returns:
True if URL is safe, False otherwise
"""
+ if not isinstance(url, str):
+ return False
try:
+ url = url.strip()
+ # Layer 1: reject RFC-illegal characters that drive parser-differential
+ # attacks (backslash, whitespace, control bytes). The URL is omitted
+ # from this log line because userinfo (RFC 3986 §3.2.1) may contain
+ # credentials and rejected URLs are by definition adversarial-shaped.
+ if RFC_FORBIDDEN_URL_CHARS_RE.search(url):
+ logger.warning("Blocked URL containing RFC-illegal characters")
+ return False
+
parsed = urlparse(url)
# Check scheme
@@ -139,7 +161,33 @@ def validate_url(
)
return False
- hostname = parsed.hostname
+ # Layer 2: extract host using urllib3, the same parser ``requests``
+ # uses internally. ``urlparse`` and urllib3 disagree on URLs like
+ # ``http://127.0.0.1\@1.1.1.1`` — urlparse says ``1.1.1.1``,
+ # urllib3 says ``127.0.0.1``. Validating against urllib3 means the
+ # validator and the HTTP client cannot disagree on destination.
+ try:
+ u3 = parse_url(url)
+ except LocationParseError:
+ logger.warning("Blocked URL: urllib3 parser rejected it")
+ return False
+ hostname = u3.host
+ # Authority must be ASCII printable. urllib3 currently rejects
+ # non-ASCII via LocationParseError, but this guard keeps us
+ # independent of that staying constant — CVE-2019-9636 showed
+ # Python's stdlib loosened a similar restriction previously.
+ # Brackets/colon used in IPv6 hosts are within 0x20-0x7e, so this
+ # runs cleanly before bracket-strip.
+ if hostname and any(ord(c) < 0x20 or ord(c) > 0x7E for c in hostname):
+ logger.warning("Blocked URL with non-ASCII / control bytes in host")
+ return False
+ # Strip IPv6 brackets so ipaddress.ip_address can parse the host.
+ if hostname and hostname.startswith("[") and hostname.endswith("]"):
+ hostname = hostname[1:-1]
+ # rstrip(".") matches getaddrinfo behaviour — trailing dots are
+ # ignored at resolution time.
+ if hostname:
+ hostname = hostname.rstrip(".")
if not hostname:
logger.warning(f"Blocked URL with no hostname: {url}")
return False
diff --git a/tests/security/test_notification_validator.py b/tests/security/test_notification_validator.py
index 2033054661..01dc05dfc8 100644
--- a/tests/security/test_notification_validator.py
+++ b/tests/security/test_notification_validator.py
@@ -296,6 +296,93 @@ class TestValidateServiceUrl:
assert error is None
+class TestParserDifferentialBypass:
+ """
+ Tests for the parser-differential SSRF bypass (GHSA-g23j-2vwm-5c25)
+ in the notification flow. The same bypass that affected
+ ``ssrf_validator.validate_url`` also affected
+ ``NotificationURLValidator.validate_service_url`` because both used
+ ``urlparse(url).hostname`` for the SSRF check.
+ """
+
+ def test_advisory_canonical_payload_blocked(self):
+ is_valid, error = NotificationURLValidator.validate_service_url(
+ "http://127.0.0.1:6666\\@1.1.1.1"
+ )
+ assert is_valid is False
+ assert error is not None
+
+ def test_post_prepare_canonicalised_form_blocked(self):
+ """Layer-2 verification on the notification flow."""
+ is_valid, error = NotificationURLValidator.validate_service_url(
+ "http://127.0.0.1:6666/%[email protected]"
+ )
+ assert is_valid is False
+ assert error is not None
+ assert "127.0.0.1" in error # Layer 2 reports the actual host
+
+ def test_backslash_no_port(self):
+ is_valid, _ = NotificationURLValidator.validate_service_url(
+ "http://127.0.0.1\\@1.1.1.1"
+ )
+ assert is_valid is False
+
+ def test_tab_in_url_blocked(self):
+ is_valid, _ = NotificationURLValidator.validate_service_url(
+ "https://example.com/path\there"
+ )
+ assert is_valid is False
+
+ def test_null_byte_blocked(self):
+ is_valid, _ = NotificationURLValidator.validate_service_url(
+ "http://127.0.0.1\[email protected]"
+ )
+ assert is_valid is False
+
+ def test_apprise_discord_still_works(self):
+ is_valid, error = NotificationURLValidator.validate_service_url(
+ "discord://webhook_id/token"
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_apprise_slack_still_works(self):
+ is_valid, error = NotificationURLValidator.validate_service_url(
+ "slack://TestApp@TokenA/TokenB/TokenC"
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_apprise_mailto_with_credentials(self):
+ is_valid, error = NotificationURLValidator.validate_service_url(
+ "mailto://user:[email protected]"
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_ipv6_unspecified_blocked(self):
+ """``::`` (and equivalent forms) routes to local host on Linux."""
+ is_valid, _ = NotificationURLValidator.validate_service_url(
+ "http://[::]/"
+ )
+ assert is_valid is False
+
+ def test_ipv6_unspecified_zero_form_blocked(self):
+ """``0::`` bypasses the literal-string ``::`` allow-list at
+ ``_is_private_ip`` — must be caught via the ip_address normalisation
+ path against ``::/128`` in BLOCKED_IP_RANGES."""
+ is_valid, _ = NotificationURLValidator.validate_service_url(
+ "http://[0::]/"
+ )
+ assert is_valid is False
+
+ def test_ipv6_unspecified_full_form_blocked(self):
+ is_valid, _ = NotificationURLValidator.validate_service_url(
+ "http://[0:0:0:0:0:0:0:0]/"
+ )
+ assert is_valid is False
+
+
class TestValidateServiceUrlStrict:
"""Tests for validate_service_url_strict static method."""
diff --git a/tests/security/test_safe_requests.py b/tests/security/test_safe_requests.py
index 6b06b3c0a6..4a515cb896 100644
--- a/tests/security/test_safe_requests.py
+++ b/tests/security/test_safe_requests.py
@@ -704,3 +704,83 @@ class TestUserAgentInjection:
_, kwargs = mock_post.call_args
assert kwargs["headers"]["User-Agent"] == custom_ua
+
+
+class TestParserDifferentialEndToEnd:
+ """
+ End-to-end integration tests for the parser-differential SSRF bypass
+ fix (GHSA-g23j-2vwm-5c25).
+
+ Approach: bind a TCP socket on 127.0.0.1:<random> WITHOUT calling
+ listen() — the kernel responds RST to any incoming connect. If the
+ fix regresses and ``safe_get`` actually attempts to connect to the
+ bound port, ``requests`` raises ``ConnectionError`` (kernel RST), so
+ a strict ``pytest.raises(ValueError, match=...)`` distinguishes
+ "validator caught it" from "validator failed and the kernel saved us".
+ """
+
+ @staticmethod
+ def _bind_unused_port():
+ import socket as _socket
+
+ sock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
+ sock.bind(("127.0.0.1", 0))
+ return sock
+
+ def test_safe_get_blocks_parser_differential_no_socket_connect(self):
+ from local_deep_research.security.safe_requests import safe_get
+
+ sock = self._bind_unused_port()
+ try:
+ port = sock.getsockname()[1]
+ bypass_url = f"http://127.0.0.1:{port}\\@1.1.1.1"
+ with pytest.raises(ValueError, match="SSRF|security validation"):
+ safe_get(bypass_url, timeout=2)
+ finally:
+ sock.close()
+
+ def test_safe_post_blocks_parser_differential(self):
+ from local_deep_research.security.safe_requests import safe_post
+
+ sock = self._bind_unused_port()
+ try:
+ port = sock.getsockname()[1]
+ bypass_url = f"http://127.0.0.1:{port}\\@1.1.1.1"
+ with pytest.raises(ValueError, match="SSRF|security validation"):
+ safe_post(bypass_url, data={"k": "v"}, timeout=2)
+ finally:
+ sock.close()
+
+ def test_safesession_blocks_parser_differential(self):
+ """SafeSession validates at both request() and send() — exercises
+ the double-validation path. This URL contains ``\\`` so Layer 1
+ catches it at request() before .prepare() canonicalises it."""
+ from local_deep_research.security.safe_requests import SafeSession
+
+ sock = self._bind_unused_port()
+ try:
+ port = sock.getsockname()[1]
+ bypass_url = f"http://127.0.0.1:{port}\\@1.1.1.1"
+ with SafeSession() as sess:
+ with pytest.raises(
+ ValueError, match="SSRF|security validation"
+ ):
+ sess.get(bypass_url, timeout=2)
+ finally:
+ sock.close()
+
+ def test_safesession_send_blocks_canonicalised_form(self):
+ """
+ Layer-2 verification: ``SafeSession.send()`` is called with a
+ ``PreparedRequest`` whose URL contains ``%5C`` (the canonicalised
+ form of ``\\``). Layer 1 doesn't match ``%5C``, so Layer 2's
+ urllib3-based hostname extraction is what blocks this — proving
+ Layer 2 carries the load on this path.
+ """
+ from local_deep_research.security.safe_requests import SafeSession
+
+ with SafeSession() as sess:
+ req = requests.Request("GET", "http://127.0.0.1:6666/%[email protected]")
+ prepared = sess.prepare_request(req)
+ with pytest.raises(ValueError, match="SSRF|security validation"):
+ sess.send(prepared, timeout=2)
diff --git a/tests/security/test_ssrf_redirect_bypass.py b/tests/security/test_ssrf_redirect_bypass.py
index dff6447674..c626bc8d6f 100644
--- a/tests/security/test_ssrf_redirect_bypass.py
+++ b/tests/security/test_ssrf_redirect_bypass.py
@@ -908,3 +908,60 @@ class TestNonWhitelistedStatusCodes:
result = safe_get("https://example.com", allow_redirects=True)
assert result.status_code == 300
assert mock_get.call_count == 1
+
+
+class TestRedirectParserDifferentialBypass:
+ """
+ Redirect-path coverage of the parser-differential SSRF fix
+ (GHSA-g23j-2vwm-5c25). The redirect handler in ``safe_get`` calls
+ ``ssrf_validator.validate_url`` on each ``Location`` header, so the
+ fix propagates to redirects automatically. These tests lock that in.
+ """
+
+ def test_redirect_to_backslash_bypass_blocked(self):
+ """Initial URL is fine; Location: header has the parser-differential
+ payload — must be blocked by validate_url on hop 2."""
+ # Don't mock validate_url here — exercise the real validator.
+ redirect_resp = _make_response(
+ 302,
+ {"Location": "http://127.0.0.1:6666\\@1.1.1.1"},
+ "https://example.com",
+ )
+ final_resp = _make_response(200)
+
+ # Mock DNS for the initial URL validation only.
+ with (
+ patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ),
+ patch(
+ "local_deep_research.security.safe_requests.requests.get",
+ side_effect=[redirect_resp, final_resp],
+ ),
+ ):
+ with pytest.raises(ValueError, match="Redirect target failed SSRF"):
+ safe_get("https://example.com", allow_redirects=True)
+
+ def test_redirect_to_canonicalised_percent5c_blocked(self):
+ """Location: with the post-prepare ``%5C`` form — Layer-2 verifies
+ the urllib3-based hostname extraction blocks the redirect target."""
+ redirect_resp = _make_response(
+ 302,
+ {"Location": "http://127.0.0.1:6666/%[email protected]"},
+ "https://example.com",
+ )
+ final_resp = _make_response(200)
+
+ with (
+ patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ),
+ patch(
+ "local_deep_research.security.safe_requests.requests.get",
+ side_effect=[redirect_resp, final_resp],
+ ),
+ ):
+ with pytest.raises(ValueError, match="Redirect target failed SSRF"):
+ safe_get("https://example.com", allow_redirects=True)
diff --git a/tests/security/test_ssrf_validator.py b/tests/security/test_ssrf_validator.py
index 8d886e0948..9dae48a6cb 100644
--- a/tests/security/test_ssrf_validator.py
+++ b/tests/security/test_ssrf_validator.py
@@ -20,6 +20,8 @@ SearXNG or Ollama that may be running in containerized environments (Docker, Pod
or on a different machine on the local network.
"""
+import socket
+
import pytest
from unittest.mock import patch
@@ -450,6 +452,795 @@ class TestContainerNetworking:
)
+class TestParserDifferentialBypass:
+ """
+ Tests for the parser-differential SSRF bypass (GHSA-g23j-2vwm-5c25).
+
+ Python's ``urllib.parse.urlparse`` and the ``requests``/``urllib3``
+ parser disagree on URLs that contain a backslash before the userinfo
+ ``@``. ``urlparse`` treats ``\\`` as a literal char and ``@`` as the
+ userinfo separator (so it extracts the post-``@`` host); ``requests``
+ treats ``\\`` as a path delimiter and connects to the pre-``\\`` host.
+
+ A pre-fix ``validate_url`` based on ``urlparse(url).hostname`` would
+ pass URLs like ``http://127.0.0.1\\@1.1.1.1`` (it sees ``1.1.1.1``)
+ while ``requests.get(url)`` would actually connect to ``127.0.0.1``.
+ The fix combines a Layer-1 reject of RFC-illegal characters with a
+ Layer-2 swap to ``urllib3.util.parse_url`` for hostname extraction.
+ """
+
+ def test_advisory_canonical_payload(self):
+ """The exact PoC from the advisory must be rejected."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1:6666\\@1.1.1.1") is False
+
+ def test_backslash_no_port(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1\\@1.1.1.1") is False
+
+ def test_double_backslash(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1\\\\@1.1.1.1") is False
+
+ def test_slash_then_backslash(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1/\\@1.1.1.1") is False
+
+ def test_tab_at_seam(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1\[email protected]") is False
+
+ def test_carriage_return_at_seam(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1\[email protected]") is False
+
+ def test_newline_at_seam(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1\[email protected]") is False
+
+ def test_space_at_seam(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1 @1.1.1.1") is False
+
+ def test_ipv6_loopback_with_backslash(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::1]\\@1.1.1.1") is False
+
+ def test_ipv4_mapped_ipv6_with_backslash(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::ffff:127.0.0.1]\\@1.1.1.1") is False
+
+ def test_backslash_with_trailing_port(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1\\@1.1.1.1:80") is False
+
+ def test_trailing_dot_loopback_with_backslash(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1.\\@1.1.1.1") is False
+
+ def test_null_byte_in_userinfo(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1\[email protected]") is False
+
+ def test_idn_unicode_host_rejected(self):
+ """IDN/Unicode hosts are rejected by urllib3 / ASCII guard."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ # Circled-digit homoglyphs of '127' resolve via NFKC to '127' on
+ # some libcs. urllib3 currently rejects these via
+ # LocationParseError; the ASCII-printable guard backs that up.
+ assert validate_url("http://①②⑦.0.0.1/") is False
+
+ def test_octal_ip_resolves_to_loopback(self):
+ """Octal IP form '0177.0.0.1' resolves to 127.0.0.1 via getaddrinfo."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("127.0.0.1", 0))],
+ ):
+ assert validate_url("http://0177.0.0.1/") is False
+
+ def test_decimal_int_ip_resolves_to_loopback(self):
+ """Decimal-int IP form '2130706433' resolves to 127.0.0.1."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("127.0.0.1", 0))],
+ ):
+ assert validate_url("http://2130706433/") is False
+
+ def test_post_prepare_canonicalised_form(self):
+ """
+ Layer-2 verification: when ``requests.PreparedRequest.url``
+ canonicalises ``\\`` to ``%5C``, the urllib3-based hostname
+ extraction still returns ``127.0.0.1`` so the IP check fires.
+ Layer 1 doesn't match ``%5C`` (it's three printable ASCII chars);
+ Layer 2 is the load-bearing defence on the SafeSession.send path.
+ """
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1:6666/%[email protected]") is False
+
+ def test_backslash_deep_in_path(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://example.com/path\\@1.1.1.1") is False
+
+ def test_backslash_in_userinfo_password(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://user:pass\\@127.0.0.1/") is False
+
+ def test_backslash_with_port_on_trailing_host(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1\\@evil.com:8080") is False
+
+ def test_interior_whitespace_at_seam(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1 \\@1.1.1.1") is False
+
+ def test_ipv6_unspecified_blocked(self):
+ """``::`` is the IPv6 unspecified address — Linux routes
+ connections to ``[::]:port`` to a service bound on ``[::1]:port``,
+ so it must be blocked alongside ``0.0.0.0`` (the IPv4 equivalent,
+ already covered via 0.0.0.0/8 in BLOCKED_IP_RANGES)."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::]/") is False
+
+ def test_ipv6_unspecified_zero_form_blocked(self):
+ """Equivalent representation ``0::`` — must normalise to ``::``
+ before the IP-range check or this bypasses the literal-string
+ allow-list in notification_validator."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[0::]/") is False
+
+ def test_ipv6_unspecified_full_form_blocked(self):
+ """Equivalent representation ``0:0:0:0:0:0:0:0``."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[0:0:0:0:0:0:0:0]/") is False
+
+
+class TestDnsResolvedBypass:
+ """
+ The validator's load-bearing path for hostnames (not IP literals) is:
+ 1. ``ipaddress.ip_address(hostname)`` raises ``ValueError`` (not an IP)
+ 2. ``socket.getaddrinfo(hostname, ...)`` resolves to one or more IPs
+ 3. Each resolved IP is checked against ``BLOCKED_IP_RANGES``
+
+ These tests exercise step 3 directly by mocking ``getaddrinfo``.
+ """
+
+ def test_hostname_resolving_to_loopback_blocked(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("127.0.0.1", 0))],
+ ):
+ assert validate_url("http://attacker.example.com/") is False
+
+ def test_hostname_resolving_to_rfc1918_blocked(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("10.0.0.5", 0))],
+ ):
+ assert validate_url("http://attacker.example.com/") is False
+
+ def test_hostname_resolving_to_link_local_blocked(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("169.254.1.1", 0))],
+ ):
+ assert validate_url("http://attacker.example.com/") is False
+
+ def test_hostname_resolving_to_aws_metadata_blocked(self):
+ """Hardcoded AWS metadata block fires even with allow_private_ips."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("169.254.169.254", 0))],
+ ):
+ # Even with the most permissive flag, AWS metadata stays blocked.
+ assert (
+ validate_url(
+ "http://attacker.example.com/", allow_private_ips=True
+ )
+ is False
+ )
+
+ def test_multiple_resolved_ips_one_private_blocks(self):
+ """
+ DNS returning a public IP first then a private IP must still block.
+ Round-robin / multi-A-record DNS could otherwise be a bypass.
+ """
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[
+ (2, 1, 6, "", ("93.184.216.34", 0)), # public
+ (2, 1, 6, "", ("127.0.0.1", 0)), # private — must block
+ ],
+ ):
+ assert validate_url("http://attacker.example.com/") is False
+
+ def test_dns_resolution_failure_fails_closed(self):
+ """``getaddrinfo`` raising ``gaierror`` must return False (not allow)."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch("socket.getaddrinfo", side_effect=socket.gaierror()):
+ assert validate_url("http://nonexistent.invalid/") is False
+
+ def test_ipv6_dns_resolution_to_loopback_blocked(self):
+ """Hostname resolving to IPv6 ``::1`` must be blocked."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(10, 1, 6, "", ("::1", 0, 0, 0))],
+ ):
+ assert validate_url("http://attacker.example.com/") is False
+
+ def test_dns_resolves_to_ipv4_mapped_ipv6_loopback_blocked(self):
+ """
+ Hostname resolving to ``::ffff:127.0.0.1`` (IPv4-mapped IPv6) must
+ be blocked — exercises the IPv4-mapped unwrap in is_ip_blocked.
+ """
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(10, 1, 6, "", ("::ffff:127.0.0.1", 0, 0, 0))],
+ ):
+ assert validate_url("http://attacker.example.com/") is False
+
+
+class TestAlternateIpFormsBlocked:
+ """
+ Alternate textual representations of private IPv4/IPv6 addresses.
+ On Linux ``getaddrinfo`` accepts most of these and resolves them to
+ the canonical form, which the IP check then catches.
+ """
+
+ def test_octal_loopback_blocked(self):
+ """``0177.0.0.1`` → ``127.0.0.1`` via getaddrinfo on Linux."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("127.0.0.1", 0))],
+ ):
+ assert validate_url("http://0177.0.0.1/") is False
+
+ def test_decimal_int_loopback_blocked(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("127.0.0.1", 0))],
+ ):
+ assert validate_url("http://2130706433/") is False
+
+ def test_short_ipv4_form_loopback_blocked(self):
+ """``127.1`` (short form) → ``127.0.0.1`` via getaddrinfo on Linux."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("127.0.0.1", 0))],
+ ):
+ assert validate_url("http://127.1/") is False
+
+ def test_ipv4_mapped_ipv6_loopback_literal_blocked(self):
+ """``[::ffff:127.0.0.1]`` is an IPv4-mapped IPv6 of loopback."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::ffff:127.0.0.1]/") is False
+
+ def test_ipv4_mapped_ipv6_rfc1918_literal_blocked(self):
+ """``[::ffff:10.0.0.1]`` — IPv4-mapped IPv6 of RFC1918."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::ffff:10.0.0.1]/") is False
+
+ def test_ipv4_mapped_ipv6_aws_metadata_literal_blocked(self):
+ """``[::ffff:169.254.169.254]`` — AWS metadata via mapped IPv6."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::ffff:169.254.169.254]/") is False
+
+
+class TestAllowFlagMatrix:
+ """
+ Verify ``allow_localhost`` / ``allow_private_ips`` flag combinations
+ against the new ``::/128`` blocklist entry, and confirm the AWS
+ metadata hardcoded block holds under all flag combinations.
+ """
+
+ def test_loopback_default_blocked(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1/") is False
+
+ def test_loopback_with_allow_localhost(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1/", allow_localhost=True) is True
+
+ def test_loopback_with_allow_private_ips(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://127.0.0.1/", allow_private_ips=True) is True
+
+ def test_ipv6_loopback_with_allow_localhost(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::1]/", allow_localhost=True) is True
+
+ def test_ipv6_unspecified_blocked_even_with_allow_localhost(self):
+ """
+ ``::`` is the unspecified address, NOT the loopback address.
+ Linux happens to route it to local services, but conceptually
+ ``::`` is "any address" — distinct from ``::1``.
+ ``allow_localhost`` is therefore conservatively scoped to
+ ``::1`` and ``127.0.0.0/8`` and does NOT permit ``::``.
+ """
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::]/", allow_localhost=True) is False
+
+ def test_ipv6_unspecified_blocked_even_with_allow_private_ips(self):
+ """Same reasoning: ``::`` is not in any allowed-range carve-out."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::]/", allow_private_ips=True) is False
+
+ def test_aws_metadata_blocked_under_allow_localhost(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert (
+ validate_url("http://169.254.169.254/", allow_localhost=True)
+ is False
+ )
+
+ def test_aws_metadata_blocked_under_allow_private_ips(self):
+ """
+ Codebase comments call this out as ALWAYS blocked. Locks in that
+ the most permissive flag still doesn't reach AWS metadata.
+ """
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert (
+ validate_url("http://169.254.169.254/", allow_private_ips=True)
+ is False
+ )
+
+
+class TestSchemeRejection:
+ """Non-http(s) schemes must be rejected outright (not just the host check)."""
+
+ def test_file_scheme_rejected(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("file:///etc/passwd") is False
+
+ def test_ftp_scheme_rejected(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("ftp://example.com/") is False
+
+ def test_gopher_scheme_rejected(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("gopher://example.com/") is False
+
+ def test_dict_scheme_rejected(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("dict://example.com:11211/stat") is False
+
+ def test_no_scheme_rejected(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("127.0.0.1") is False
+
+ def test_scheme_relative_url_rejected(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("//127.0.0.1/") is False
+
+ def test_uppercase_https_scheme_accepted(self):
+ """Schemes are case-insensitive per RFC 3986."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ ):
+ assert validate_url("HTTPS://example.com/") is True
+
+
+class TestNeverRaises:
+ """
+ Property-based-style robustness: ``validate_url`` is a security
+ boundary that takes untrusted input. It must NEVER raise — only
+ return ``True``/``False``. A crash here is a DoS vector.
+ """
+
+ @pytest.mark.parametrize(
+ "weird_input",
+ [
+ "",
+ " ",
+ "\x00",
+ "\x00" * 100,
+ ":",
+ "::",
+ "://",
+ "http",
+ "http:",
+ "http:/",
+ "http://",
+ "http:// ",
+ "http://[",
+ "http://[::",
+ "http://]",
+ "http://@",
+ "http://@@@",
+ "http://:@",
+ "http://:80",
+ "http://:0",
+ "http://example.com:99999999", # overflow port
+ "http://example.com:-1", # negative port
+ "http://%00",
+ "http://%2F%2F",
+ "h" * 10_000,
+ "http://" + "a" * 100_000, # huge URL
+ "http://" + "[" * 100,
+ "http://." + ("a." * 1000) + "com",
+ "http://example.com/" + "?" * 1000,
+ "\udcff", # lone surrogate (Python str-only, raises on encode)
+ "http://\udcff/",
+ ],
+ )
+ def test_pathological_input_returns_bool(self, weird_input):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ result = validate_url(weird_input)
+ assert isinstance(result, bool)
+
+
+class TestOutOfScopeBehaviorLockedIn:
+ """
+ Behaviours documented as out-of-scope (filed as separate hardening
+ issues, not a bypass of GHSA-g23j-2vwm-5c25). Tests here lock in the
+ *current* behaviour so the gap is visible — if we later harden these,
+ these tests should flip and be moved into the bypass class.
+ """
+
+ def test_6to4_wrapped_loopback_currently_passes(self):
+ """
+ ``[2002:7f00:1::]`` is the 6to4 wrap of ``127.0.0.1``. On hosts
+ with kernel sit0/6to4 routes configured, this routes to ``127.0.0.1``.
+ Default Linux has no such route, so this is not exploitable in
+ the default configuration — but the validator does not catch it.
+ Filed separately.
+ """
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ # Document current behaviour: passes. If we ever add the IPv6
+ # transition prefixes to BLOCKED_IP_RANGES, flip this assertion.
+ assert validate_url("http://[2002:7f00:1::]/") is True
+
+ def test_nat64_wrapped_loopback_currently_passes(self):
+ """``[64:ff9b::7f00:1]`` is the NAT64 wrap of ``127.0.0.1``."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[64:ff9b::7f00:1]/") is True
+
+
+class TestValidateUrlEdgeCases:
+ """Robustness: validate_url must never raise, only return bool."""
+
+ def test_empty_string_returns_false(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("") is False
+
+ def test_whitespace_only_returns_false(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url(" ") is False
+
+ def test_tab_newline_only_returns_false(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("\t\n") is False
+
+ def test_none_returns_false(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url(None) is False
+
+ def test_int_returns_false(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url(123) is False
+
+ def test_malformed_ipv6_no_crash(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ assert validate_url("http://[::") is False
+
+ def test_extremely_long_url_no_crash(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ # Should reject (no DNS) but most importantly must not crash or
+ # consume excessive memory.
+ with patch(
+ "socket.getaddrinfo", side_effect=__import__("socket").gaierror()
+ ):
+ assert validate_url("http://" + "a" * 100_000) is False
+
+
+class TestLegitimateUrlsStillPass:
+ """Anti-regression: ensure the fix doesn't reject RFC-legal URLs."""
+
+ @staticmethod
+ def _public_dns_mock():
+ # 93.184.216.34 is the documented IP for example.com (RFC-2606).
+ return patch(
+ "socket.getaddrinfo",
+ return_value=[(2, 1, 6, "", ("93.184.216.34", 0))],
+ )
+
+ def test_simple_http_url(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://example.com/") is True
+
+ def test_explicit_port(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://example.com:8080/") is True
+
+ def test_userinfo_is_rfc_legal(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://user:[email protected]/") is True
+
+ def test_userinfo_with_port(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://user:[email protected]:8080/") is True
+
+ def test_trailing_dot_hostname(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://example.com./") is True
+
+ def test_path_query_fragment(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://example.com/path?q=1#frag") is True
+
+ def test_plus_in_query_string(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://example.com/?q=foo+bar") is True
+
+ def test_encoded_backslash_in_path_is_rfc_legal(self):
+ """%5C in a PATH (not a host bypass) is RFC-legal and must pass."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://example.com/path%5Cfile") is True
+
+ def test_encoded_space_in_path(self):
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert (
+ validate_url("http://example.com/path%20with%20encoded%20space")
+ is True
+ )
+
+ def test_uppercase_hostname_case_folded(self):
+ """Locks in case-folding parity between urlparse and urllib3."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ with self._public_dns_mock():
+ assert validate_url("http://EXAMPLE.COM/") is True
+
+ def test_ipv6_public(self):
+ """IPv6 hosts unwrap from brackets and check correctly."""
+ from src.local_deep_research.security.ssrf_validator import (
+ validate_url,
+ )
+
+ # 2001:db8::1 is the documentation prefix; not in any blocked
+ # range, so this should pass.
+ assert validate_url("http://[2001:db8::1]/") is True
+
+
class TestDocumentation:
"""Documentation tests explaining the security model."""