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.

harden(ssrf): NAT64 opt-in respects the private-IP policy + notification review nits (#5594)

LearningCircuit0d29e1e3cb9e
diff --git a/.pre-commit-hooks/check-no-src-test-imports.py b/.pre-commit-hooks/check-no-src-test-imports.py
index 249dbf1d20..679a2defa8 100755
--- a/.pre-commit-hooks/check-no-src-test-imports.py
+++ b/.pre-commit-hooks/check-no-src-test-imports.py
@@ -26,10 +26,12 @@ keeps it that way. It flags, in ``tests/**/*.py``:
which import the ``src.`` module tree when the patch is entered exactly as a
real import would.
-Backtick-wrapped prose in comments/docstrings that merely NAMES the banned
-alias is not flagged (AST ignores comments; a docstring value does not *start*
-with the alias). ``tests/hooks/`` is exempt: those tests carry the alias as
-literal test data for the hook checks themselves.
+Comments naming the banned alias are never flagged (the AST drops comments).
+Prose in a docstring is only flagged if the docstring string literal itself
+*starts with* ``src.local_deep_research`` (``visit_Constant`` matches any such
+string constant); ordinary docstrings that merely mention the alias mid-text do
+not. ``tests/hooks/`` is exempt: those tests carry the alias as literal test
+data for the hook checks themselves.
"""
import ast
diff --git a/SECURITY.md b/SECURITY.md
index 99cacb19be..a6322c5899 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -118,7 +118,7 @@ This window is closed at the socket layer for the delivery path. The deliverable
- **Synchronous, in-thread delivery.** The notification service builds its Apprise instances with `AppriseAsset(async_mode=False)`, so every plugin's `notify()` runs in the sending thread rather than a `ThreadPoolExecutor` worker. This is what lets the thread-local guards below apply to Apprise's own resolution.
- **Redirect-following disabled → the redirect attack class is closed.** The Apprise instances are built with `AppriseAsset(http_redirects=False)`, and each parsed plugin additionally has its `redirects` flag re-forced to `False` after `add()` so a user-supplied `?redirect=yes` query parameter cannot override the default. A user-configured webhook therefore can no longer 30x-redirect the send to a private/loopback host **or** to an arbitrary public host for data exfiltration — the send is simply not redirected. Redirect-following is never needed for legitimate webhook delivery (endpoints answer 2xx directly). Most plugins honour the per-plugin flag (`allow_redirects=self.redirects`), including the raw-webhook `json`/`xml`/`form` schemes and `ntfy`/`gotify`; a few (e.g. `matrix://`) issue their HTTP calls without threading that flag through, so the per-plugin re-force does not reach them — for those the **block-private send window** below is the backstop that still refuses a redirect/rebind to a blocked address at the socket layer.
- **Pin the validated address → the original host's rebind is closed.** Each `notify()` is wrapped in `dns_pinning.pinned_notification_send` (see the general fetch path below), which **pins** every raw-webhook host in the batch to the address just validated. `requests`/`urllib3` cannot then connect to a rebind target: the address validated is the address connected to.
-- **Block-private send window.** For the duration of the send a thread-local **block-private** mode also refuses any *unpinned* lookup (a plugin scheme's endpoint) that resolves to a private/loopback/link-local/cloud-metadata address, at the `getaddrinfo` layer before any socket is opened. The check runs on the very resolution the client is about to connect to, so there is no residual race. That send-time resolution is bounded by a timeout so a slow / hostile DNS authority cannot hang the sending thread — a timeout fails closed (refuses the send).
+- **Block-private send window.** For the duration of the send a thread-local **block-private** mode also refuses any *unpinned* lookup (a plugin scheme's endpoint) that resolves to a private/loopback/link-local/cloud-metadata address, at the `getaddrinfo` layer before any socket is opened. The check runs on the very resolution the client is about to connect to, so there is no residual race. That send-time resolution is bounded by a timeout so a slow / hostile DNS authority cannot hang the sending thread — a timeout fails closed (refuses the send). The bounded lookup runs on a short-lived daemon thread that is abandoned (not force-killed) on timeout, so a sustained hostile-DNS attack against an outbound-enabled instance can accumulate a small number of parked daemon threads (each blocked in libc `getaddrinfo`) before the send gives up; this is a bounded resource cost, not a bypass — the send is still refused.
- **Per-scheme policy, matching the validator.** `http`/`https` block private + metadata unless the operator set `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS=true`; plugin and raw-webhook schemes (`json://`, `xml://`, `form://`, `discord://`, `ntfy://`, `gotify://`, …) allow private/LAN targets (self-hosted notifiers keep working) but **always** block cloud-metadata **and the entire link-local range** (IPv4 `169.254.0.0/16`, IPv6 `fe80::/10`) regardless of any operator flag. The link-local block matters because cloud-provider metadata lives across the whole link-local range, not just the always-blocked literals (e.g. Scaleway serves instance metadata at `169.254.42.42`), and no legitimate self-hosted notifier lives on link-local. It is scoped to the plugin/raw-webhook partition: RFC1918, CGNAT, loopback, and non-link-local IPv6 ULA self-hosted notifiers are unaffected, and `http`/`https` still treats link-local as operator-recoverable via `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS`. It is threaded end-to-end (a `block_link_local` flag on `is_ip_blocked` / `pinned_notification_send` and the validator's plugin-scheme IMDS guard) rather than changing `is_ip_blocked`'s default, so the general fetch/LLM paths keep their existing link-local-under-`allow_private_ips` behaviour. TLS is unaffected: only name resolution is redirected, so SNI and certificate verification still use the original hostname.
- **Fail-closed invariants.** The send is refused (never sent unguarded) if the `getaddrinfo` shim is not the active resolver, or if the Apprise instance is not synchronous, or if a `tag` is supplied — any of which would let delivery fan out to worker threads the thread-local guards do not cover. A confirmed security block is **not retried**: the pin's connect-time rebind catch raises a non-retryable error directly, and a block-private window refusal (which Apprise swallows into a generic delivery failure) is recognised after the failed send via a thread-local marker and re-raised non-retryably — so a hostile / misconfigured destination fails fast in one attempt instead of being retried three times against a slow DNS authority. Invariant violations likewise fail fast.
- **Thread-scoped.** The pin and the block are thread-local, so they only affect the sending thread and can never wrongly block a legitimate private request running concurrently elsewhere.
diff --git a/changelog.d/+nat64-embedded-ip-policy.security.md b/changelog.d/+nat64-embedded-ip-policy.security.md
new file mode 100644
index 0000000000..3cf9cb541c
--- /dev/null
+++ b/changelog.d/+nat64-embedded-ip-policy.security.md
@@ -0,0 +1 @@
+The `LDR_SECURITY_ALLOW_NAT64` operator opt-in (for IPv6-only deployments that reach IPv4 via DNS64/NAT64) no longer widens the private-IP policy, and now decodes NAT64-wrapped addresses at the correct RFC 6052 §2.2 byte positions. A NAT64-wrapped destination is evaluated exactly as a direct connection to its embedded IPv4 would be: a wrapped RFC1918 or loopback address is blocked unless the matching private-IP / localhost allowance is also enabled, the six always-blocked cloud-metadata literals stay blocked unconditionally, and link-local wraps are blocked wherever a direct connection to the embedded address would be — including in the RFC 8215 `/48` local-use form, where the embedded IPv4 lives at different byte positions than the trailing 32 bits (previously a crafted `/48` address could hide a metadata target behind a public-looking suffix). Note that the general fetch path calls `validate_url`, which does not set `block_link_local`, so a NAT64-wrapped link-local address outside those six literals (for example a wrap of Scaleway's `169.254.42.42`) is reachable once `allow_private_ips` is enabled — exactly as a direct connection to it already is. That is a pre-existing limitation of the private-IP opt-in, not something this change widens; the point of this fix is that enabling NAT64 grants nothing beyond it. NAT64-wrapped public addresses — the opt-in's intended use — remain reachable. Closes a gap where enabling NAT64 could reach internal or metadata IPv4 targets through the general fetch path.
diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.py
index 99140c8ed2..9e2d3d8312 100644
--- a/src/local_deep_research/notifications/service.py
+++ b/src/local_deep_research/notifications/service.py
@@ -244,7 +244,10 @@ class NotificationService:
the send runs inside the pin + block-private window it returns. The
per-thread SSRF-block marker is reset first so a block during THIS
``notify`` is attributable to it (see
- ``dns_pinning.consume_ssrf_block``). ``None`` sends without a guard.
+ ``dns_pinning.consume_ssrf_block``). ``guard_factory=None`` sends
+ WITHOUT a guard and is for tests ONLY — it exercises the unguarded
+ baseline the SSRF teeth-tests assert against; every production caller
+ MUST pass a ``guard_factory``.
Args:
title: Notification title
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index e4c00fc4e7..d4dd9a9f9c 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -60,28 +60,82 @@ LINK_LOCAL_RANGES = [
ALLOWED_SCHEMES = {"http", "https"}
+# RFC 6052 §2.2 places the embedded IPv4 at prefix-length-specific byte
+# positions — NOT always the trailing 32 bits. Only /96 puts the IPv4 in the
+# low 32 bits; shorter prefixes split it around the reserved octet at byte 8.
+# Reading the wrong bytes lets a crafted address (e.g. a /48 form) hide a real
+# metadata/internal target at the RFC positions while a decoy sits in the
+# trailing 32 bits. Map each supported prefix length to the four byte indices
+# (of the 16-byte address) that hold the embedded IPv4, in order.
+#
+# All six RFC 6052 lengths are mapped on purpose, though NAT64_PREFIXES
+# currently carries only /48 and /96 — so the 32/40/56/64 rows are unreachable
+# today and untested. That is deliberate: adding a prefix to NAT64_PREFIXES
+# should not also require editing this table, because a missing row here fails
+# CLOSED but silently (extraction returns None, the caller blocks, and a
+# legitimate NAT64 deployment simply stops resolving). A spec-complete table
+# makes that impossible. Anything added here must come from RFC 6052 §2.2, not
+# from inference.
+_NAT64_V4_BYTE_INDICES = {
+ 32: (4, 5, 6, 7),
+ 40: (5, 6, 7, 9),
+ 48: (6, 7, 9, 10),
+ 56: (7, 9, 10, 11),
+ 64: (9, 10, 11, 12),
+ 96: (12, 13, 14, 15),
+}
+
+
+def nat64_embedded_ipv4(
+ ip: ipaddress._BaseAddress,
+) -> Optional[ipaddress.IPv4Address]:
+ """Return the IPv4 embedded in a NAT64-prefixed IPv6 address per RFC 6052
+ §2.2 (keyed on the matched prefix's length), or ``None`` if ``ip`` is not
+ inside a known NAT64 prefix (or the prefix length has no defined embedding).
+
+ Using the trailing 32 bits for every length misreads a non-/96 embedding —
+ see ``_NAT64_V4_BYTE_INDICES``. Centralized so ``is_ip_blocked`` and the
+ two wrap checks below extract identically and cannot drift.
+
+ Byte 8 — the octet RFC 6052 §2.2 reserves as zero for every embedding
+ shorter than /96 — is deliberately NOT validated: a malformed embedding is
+ policy-CHECKED, not rejected. Extraction reads the RFC byte positions
+ either way, so a crafted address still has its real embedded target
+ policy-checked (it cannot under-block). Rejecting malformed embeddings
+ would also fail closed (``None`` → the caller blocks), but would over-block
+ anything a lenient translator would in fact route.
+ """
+ if not isinstance(ip, ipaddress.IPv6Address):
+ return None
+ packed = ip.packed
+ for nat64_prefix in NAT64_PREFIXES:
+ if ip in nat64_prefix:
+ idx = _NAT64_V4_BYTE_INDICES.get(nat64_prefix.prefixlen)
+ if idx is None:
+ return None
+ return ipaddress.IPv4Address(bytes(packed[i] for i in idx))
+ return None
+
+
def is_nat64_wrapped_metadata_ip(ip: ipaddress._BaseAddress) -> bool:
- """True iff ``ip`` is an IPv6 address inside a NAT64 prefix whose
- embedded IPv4 (low 32 bits) is in ``ALWAYS_BLOCKED_METADATA_IPS``.
+ """True iff ``ip`` is an IPv6 address inside a NAT64 prefix whose embedded
+ IPv4 (extracted per RFC 6052 §2.2) is in ``ALWAYS_BLOCKED_METADATA_IPS``.
Both ``is_ip_blocked`` and ``NotificationURLValidator._ip_matches_blocked_range``
consult this before honoring the ``security.allow_nat64`` operator
opt-in, so cloud-metadata access cannot be re-opened through an
- IPv6-wrapped destination on a NAT64-equipped host. Keeping the
- extraction in one place prevents the two validators from drifting.
+ IPv6-wrapped destination on a NAT64-equipped host.
"""
- if not isinstance(ip, ipaddress.IPv6Address):
- return False
- for nat64_prefix in NAT64_PREFIXES:
- if ip in nat64_prefix:
- embedded_v4 = ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF)
- return str(embedded_v4) in ALWAYS_BLOCKED_METADATA_IPS
- return False
+ embedded_v4 = nat64_embedded_ipv4(ip)
+ return (
+ embedded_v4 is not None
+ and str(embedded_v4) in ALWAYS_BLOCKED_METADATA_IPS
+ )
def is_nat64_wrapped_link_local_ip(ip: ipaddress._BaseAddress) -> bool:
"""True iff ``ip`` is an IPv6 address inside a NAT64 prefix whose embedded
- IPv4 (low 32 bits) is IPv4 link-local (``169.254.0.0/16``).
+ IPv4 (per RFC 6052 §2.2) is IPv4 link-local (``169.254.0.0/16``).
Mirrors ``is_nat64_wrapped_metadata_ip`` for the ``block_link_local``
notification guard. The ``security.allow_nat64`` opt-in re-opens general
@@ -91,16 +145,11 @@ def is_nat64_wrapped_link_local_ip(ip: ipaddress._BaseAddress) -> bool:
set, so non-notification callers (which permit link-local under
``allow_private_ips``) keep the opt-in's reachability unchanged.
"""
- if not isinstance(ip, ipaddress.IPv6Address):
- return False
- for nat64_prefix in NAT64_PREFIXES:
- if ip in nat64_prefix:
- embedded_v4 = ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF)
- return any(
- isinstance(r, ipaddress.IPv4Network) and embedded_v4 in r
- for r in LINK_LOCAL_RANGES
- )
- return False
+ embedded_v4 = nat64_embedded_ipv4(ip)
+ return embedded_v4 is not None and any(
+ isinstance(r, ipaddress.IPv4Network) and embedded_v4 in r
+ for r in LINK_LOCAL_RANGES
+ )
# RFC 3986 forbids these characters in URLs; their presence in a URL signals
@@ -238,9 +287,35 @@ def is_ip_blocked(
for blocked_range in BLOCKED_IP_RANGES:
if ip in blocked_range:
# NAT64 carve-out: when the operator has opted in, the two
- # NAT64 prefixes don't block. 6to4 / Teredo / discard remain
- # blocked unconditionally.
+ # NAT64 prefixes don't block outright. 6to4 / Teredo / discard
+ # remain blocked unconditionally.
if nat64_allowed and blocked_range in NAT64_PREFIXES:
+ # The opt-in permits reaching only what a DIRECT connection
+ # to the embedded IPv4 would be allowed to reach — it is not
+ # a blanket bypass of the private / loopback / link-local /
+ # metadata policy. Re-apply the same policy to the embedded
+ # IPv4: block if the direct form would be blocked, otherwise
+ # allow the NAT64 reach. This closes the gap where
+ # allow_nat64=True ALONE made NAT64-wrapped RFC1918 /
+ # loopback reachable regardless of allow_private_ips.
+ # (Metadata and, when block_link_local is set, link-local
+ # wraps are already blocked above.) The embedded IPv4 is
+ # extracted per RFC 6052 §2.2 (byte positions vary by prefix
+ # length) so a crafted /48 form cannot hide a blocked target
+ # at the RFC positions behind a decoy in the trailing 32
+ # bits; fail closed if extraction is impossible. Recursion
+ # terminates at depth 1: the embedded value is plain IPv4,
+ # never in a NAT64 prefix, and allow_nat64=False prevents
+ # re-entry.
+ embedded_v4 = nat64_embedded_ipv4(ip)
+ if embedded_v4 is None or is_ip_blocked(
+ str(embedded_v4),
+ allow_localhost=allow_localhost,
+ allow_private_ips=allow_private_ips,
+ allow_nat64=False,
+ block_link_local=block_link_local,
+ ):
+ return True
continue
# If allow_private_ips is True, skip blocking for private + loopback
if allow_private_ips:
diff --git a/tests/security/test_notification_validator.py b/tests/security/test_notification_validator.py
index 52290262a0..48a04707d7 100644
--- a/tests/security/test_notification_validator.py
+++ b/tests/security/test_notification_validator.py
@@ -955,7 +955,7 @@ class TestNat64EnvOptOutInNotificationValidator:
def test_nat64_local_use_allowed_when_env_true(self, monkeypatch):
monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")
assert (
- NotificationURLValidator._is_private_ip("64:ff9b:1::808:808")
+ NotificationURLValidator._is_private_ip("64:ff9b:1:808:8:800::")
is False
)
@@ -975,7 +975,7 @@ class TestNat64EnvOptOutInNotificationValidator:
"""Same lock-in for the RFC 8215 local-use prefix wrap."""
monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")
assert (
- NotificationURLValidator._is_private_ip("64:ff9b:1::a9fe:a9fe")
+ NotificationURLValidator._is_private_ip("64:ff9b:1:a9fe:a9:fe00::")
is True
)
@@ -1081,7 +1081,7 @@ class TestNat64EnvOptOutInNotificationValidator:
self,
):
is_valid, _ = NotificationURLValidator.validate_service_url(
- "http://[64:ff9b:1::a9fe:a9fe]/", allow_private_ips=True
+ "http://[64:ff9b:1:a9fe:a9:fe00::]/", allow_private_ips=True
)
assert is_valid is False
diff --git a/tests/security/test_ssrf_validator.py b/tests/security/test_ssrf_validator.py
index b02cf841b4..968906d0a9 100644
--- a/tests/security/test_ssrf_validator.py
+++ b/tests/security/test_ssrf_validator.py
@@ -1290,7 +1290,7 @@ class TestIPv6TransitionPrefixesBlocked:
def test_nat64_local_use_prefix_blocked(self):
"""RFC 8215's 64:ff9b:1::/48 (NAT64 local-use) is the same SSRF
threat class as the well-known /96. On hosts configured to route
- the local-use prefix, [64:ff9b:1::a9fe:a9fe] reaches AWS IMDS
+ the local-use prefix, [64:ff9b:1:a9fe:a9:fe00::] reaches AWS IMDS
identically to the WKP form. Missing this prefix earned a
HackerOne bounty against the Ruby ssrf_filter library."""
from local_deep_research.security.ssrf_validator import (
@@ -1300,12 +1300,12 @@ class TestIPv6TransitionPrefixesBlocked:
assert validate_url("http://[64:ff9b:1::1]/") is False
def test_nat64_local_use_wraps_aws_metadata_blocked(self):
- """[64:ff9b:1::a9fe:a9fe] — local-use NAT64 wrap of 169.254.169.254."""
+ """[64:ff9b:1:a9fe:a9:fe00::] — local-use NAT64 wrap of 169.254.169.254."""
from local_deep_research.security.ssrf_validator import (
validate_url,
)
- assert validate_url("http://[64:ff9b:1::a9fe:a9fe]/") is False
+ assert validate_url("http://[64:ff9b:1:a9fe:a9:fe00::]/") is False
def test_ipv4_compatible_imds_blocked(self):
"""[::169.254.169.254] — RFC 4291 IPv4-Compatible IPv6 form
@@ -1511,7 +1511,7 @@ class TestNat64EnvOptOut:
)
monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")
- assert validate_url("http://[64:ff9b:1::808:808]/") is True
+ assert validate_url("http://[64:ff9b:1:808:8:800::]/") is True
def test_env_does_not_unblock_6to4(self, monkeypatch):
"""6to4 has no live legitimate use; the operator switch must
@@ -1571,7 +1571,7 @@ class TestNat64EnvOptOut:
# RFC 8215 local-use NAT64 prefix wrap of the same address.
assert (
is_ip_blocked(
- "64:ff9b:1::a9fe:2a2a",
+ "64:ff9b:1:a9fe:2a:2a00::",
allow_private_ips=True,
block_link_local=True,
allow_nat64=True,
@@ -1642,7 +1642,7 @@ class TestNat64EnvOptOut:
)
monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")
- assert validate_url("http://[64:ff9b:1::a9fe:a9fe]/") is False
+ assert validate_url("http://[64:ff9b:1:a9fe:a9:fe00::]/") is False
def test_env_does_not_unblock_ecs_metadata_via_nat64_wrap(
self, monkeypatch
@@ -1700,6 +1700,159 @@ class TestNat64EnvOptOut:
monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")
assert is_ip_blocked("fe80::1") is True
+ def test_nat64_wrap_of_rfc1918_blocked_without_private_opt_in(self):
+ """allow_nat64 alone must NOT reach a NAT64-wrapped RFC1918 address.
+ The opt-in permits reaching only what a DIRECT connection would be
+ allowed to, so the embedded IPv4 is re-checked against the same
+ private-IP policy. ``64:ff9b::a00:5`` wraps ``10.0.0.5``."""
+ from local_deep_research.security.ssrf_validator import is_ip_blocked
+
+ assert (
+ is_ip_blocked(
+ "64:ff9b::a00:5", allow_private_ips=False, allow_nat64=True
+ )
+ is True
+ )
+ # local-use prefix form of the same wrap
+ assert (
+ is_ip_blocked(
+ "64:ff9b:1:a00:0:500::",
+ allow_private_ips=False,
+ allow_nat64=True,
+ )
+ is True
+ )
+
+ def test_nat64_wrap_of_rfc1918_allowed_with_private_opt_in(self):
+ """With allow_private_ips=True the embedded RFC1918 is allowed, so the
+ NAT64 wrap is reachable too — same as a direct RFC1918 connection."""
+ from local_deep_research.security.ssrf_validator import is_ip_blocked
+
+ assert (
+ is_ip_blocked(
+ "64:ff9b::a00:5", allow_private_ips=True, allow_nat64=True
+ )
+ is False
+ )
+
+ def test_nat64_wrap_of_loopback_respects_allow_localhost(self):
+ """NAT64-wrapped loopback ``64:ff9b::7f00:1`` (127.0.0.1): blocked
+ without allow_localhost, allowed with it — mirroring the direct
+ form, instead of the opt-in unblocking it unconditionally."""
+ from local_deep_research.security.ssrf_validator import is_ip_blocked
+
+ assert is_ip_blocked("64:ff9b::7f00:1", allow_nat64=True) is True
+ assert (
+ is_ip_blocked(
+ "64:ff9b::7f00:1", allow_localhost=True, allow_nat64=True
+ )
+ is False
+ )
+
+ def test_nat64_wrap_of_public_still_reachable_under_opt_in(self):
+ """The point of the opt-in is preserved: a NAT64-wrapped PUBLIC IPv4
+ (``64:ff9b::808:808`` = 8.8.8.8) stays reachable with or without the
+ private-IP flag — only blocked embedded forms are refused now."""
+ from local_deep_research.security.ssrf_validator import is_ip_blocked
+
+ assert (
+ is_ip_blocked(
+ "64:ff9b::808:808", allow_private_ips=False, allow_nat64=True
+ )
+ is False
+ )
+
+
+class TestNat64Rfc6052Embedding:
+ """RFC 6052 §2.2: the embedded IPv4 sits at prefix-length-specific byte
+ positions, NOT always the trailing 32 bits. A /48 (RFC 8215 local-use)
+ address that places a blocked target at the RFC positions must be caught
+ even when the trailing 32 bits hold a public decoy — and, conversely, a
+ correctly-encoded /48 public destination must stay reachable."""
+
+ def test_extractor_matches_rfc6052_positions(self):
+ import ipaddress
+ from local_deep_research.security.ssrf_validator import (
+ nat64_embedded_ipv4,
+ )
+
+ # /96 embeds in the trailing 32 bits.
+ assert (
+ str(
+ nat64_embedded_ipv4(ipaddress.IPv6Address("64:ff9b::a9fe:a9fe"))
+ )
+ == "169.254.169.254"
+ )
+ # /48 embeds in bytes 6-7 and 9-10 (flanking the reserved octet 8).
+ assert (
+ str(
+ nat64_embedded_ipv4(
+ ipaddress.IPv6Address("64:ff9b:1:a9fe:a9:fe00::")
+ )
+ )
+ == "169.254.169.254"
+ )
+ assert (
+ str(
+ nat64_embedded_ipv4(
+ ipaddress.IPv6Address("64:ff9b:1:808:8:800::")
+ )
+ )
+ == "8.8.8.8"
+ )
+ # Not inside any NAT64 prefix -> None (not a spurious 0.0.0.0).
+ assert nat64_embedded_ipv4(ipaddress.IPv6Address("2001:db8::1")) is None
+
+ def test_48_byte_position_spoof_is_blocked(self):
+ """A /48 address hiding a blocked target at the RFC-6052 positions while
+ the trailing 32 bits forge a public 8.8.8.8 must NOT slip through under
+ allow_nat64 — it decodes to the real target, not the decoy."""
+ from local_deep_research.security.ssrf_validator import is_ip_blocked
+
+ # IMDS 169.254.169.254 at RFC positions, 8.8.8.8 decoy in the tail.
+ assert (
+ is_ip_blocked(
+ "64:ff9b:1:a9fe:a9:fe00:808:808",
+ allow_private_ips=False,
+ allow_nat64=True,
+ )
+ is True
+ )
+ # Scaleway link-local 169.254.42.42 at RFC positions, under block_link_local.
+ assert (
+ is_ip_blocked(
+ "64:ff9b:1:a9fe:2a:2a00:808:808",
+ allow_private_ips=True,
+ block_link_local=True,
+ allow_nat64=True,
+ )
+ is True
+ )
+ # RFC1918 10.0.0.1 at RFC positions, without the private opt-in.
+ assert (
+ is_ip_blocked(
+ "64:ff9b:1:a00:0:100:808:808",
+ allow_private_ips=False,
+ allow_nat64=True,
+ )
+ is True
+ )
+
+ def test_48_correctly_encoded_public_is_reachable(self):
+ """A correctly-encoded /48 public destination (zero suffix) decodes to a
+ public IPv4 and stays reachable under allow_nat64 — the previous
+ trailing-bits misread wrongly blocked it as 0.0.0.0."""
+ from local_deep_research.security.ssrf_validator import is_ip_blocked
+
+ assert (
+ is_ip_blocked(
+ "64:ff9b:1:808:8:800::",
+ allow_private_ips=False,
+ allow_nat64=True,
+ )
+ is False
+ )
+
class TestIsNat64WrappedMetadataIp:
"""Direct unit tests for the shared helper. Both validators rely on
@@ -1775,7 +1928,7 @@ class TestIsNat64WrappedMetadataIp:
assert (
is_nat64_wrapped_metadata_ip(
- ipaddress.IPv6Address("64:ff9b:1::a9fe:a9fe")
+ ipaddress.IPv6Address("64:ff9b:1:a9fe:a9:fe00::")
)
is True
)
diff --git a/tests/security/test_ssrf_validator_behavior.py b/tests/security/test_ssrf_validator_behavior.py
index 4bd5784d06..d43b9e1366 100644
--- a/tests/security/test_ssrf_validator_behavior.py
+++ b/tests/security/test_ssrf_validator_behavior.py
@@ -230,7 +230,7 @@ class TestPrivateIpRangesBehavior:
("::", "::/128 unspecified IPv6"),
("2002:7f00:1::", "2002::/16 6to4 wrapping loopback"),
("64:ff9b::a9fe:a9fe", "64:ff9b::/96 NAT64 well-known"),
- ("64:ff9b:1::a9fe:a9fe", "64:ff9b:1::/48 NAT64 local-use"),
+ ("64:ff9b:1:a9fe:a9:fe00::", "64:ff9b:1::/48 NAT64 local-use"),
("2001::1", "2001::/32 Teredo"),
("100::1", "100::/64 discard"),
("::7f00:1", "::/96 IPv4-compatible IPv6 wrapping loopback"),
diff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.py
index 2c81cf8f8c..d12f469c57 100644
--- a/tests/web/services/test_notification_coverage.py
+++ b/tests/web/services/test_notification_coverage.py
@@ -479,7 +479,7 @@ class TestNotificationService:
id="nat64-rfc6052-wrap-of-imds",
),
pytest.param(
- "http://[64:ff9b:1::a9fe:a9fe]/",
+ "http://[64:ff9b:1:a9fe:a9:fe00::]/",
False,
id="nat64-rfc8215-wrap-of-imds",
),
@@ -546,7 +546,7 @@ class TestNotificationService:
id="nat64-rfc6052-wrap-of-public",
),
pytest.param(
- "http://[64:ff9b:1::5db8:d822]/",
+ "http://[64:ff9b:1:5db8:d8:2200::]/",
True,
id="nat64-rfc8215-wrap-of-public",
),
@@ -643,7 +643,7 @@ class TestNotificationService:
# NAT64-wrapped NON-metadata IPv4 — hint is True ONLY via
# the NAT64 carve-out probe, not the private-IPs probe.
("http://[64:ff9b::5db8:d822]/", True),
- ("http://[64:ff9b:1::5db8:d822]/", True),
+ ("http://[64:ff9b:1:5db8:d8:2200::]/", True),
# Always-blocked: env var CANNOT unblock → False
("http://169.254.169.254/", False),
("http://169.254.170.2/", False),