Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(url_safety): validate the configured proxy before exempting it

Agrici Daniel94f1849244e6
diff --git a/SECURITY.md b/SECURITY.md
index 92e466e..464bb0e 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -56,6 +56,7 @@ claude-seo is a research and audit toolkit that runs on a user's workstation. It
## Known residual risks
- **Playwright + Chromium DNS rebinding.** Chromium does its own DNS resolution inside the renderer process. claude-seo's Python-layer DNS pin (`url_safety._pin_dns`) cannot reach it. The Playwright `route()` handler re-validates every subresource host (`make_safe_playwright_route_handler`), which closes the common case, but a true rebinding attacker can still race Chromium's resolver after our pre-flight returns. Mitigation: do not point `/seo` skills at untrusted sites with high-frequency redirects.
+- **CONNECT proxies weaken DNS pinning.** Behind a configured HTTP proxy (`HTTPS_PROXY` and friends) the proxy resolves the final host itself, so `url_safety`'s pin degrades to the pre-flight check in `validate_url_strict`; the proxy host itself is exempted from the pinned scope only after passing the same hostname blocklist and `is_safe_ip` policy as an audit target, so a proxy on loopback, RFC 1918, RFC 6598, link-local, or a metadata address is refused rather than exempted.
- **IPv6-only audit targets.** The strict validator queries `family=AF_INET` for the initial resolution. Hosts with AAAA records only will surface as "DNS resolution failed". This is **fail-closed** by design — we'd rather refuse than connect to an unvalidated IPv6 endpoint. Tracked for a future patch (full dual-stack pinning, similar to the Playwright handler which already uses `AF_UNSPEC`).
- **Windows file permissions.** `os.fchmod(fd, 0o600)` is a no-op on Windows for non-ACL filesystems. Users on Windows should rely on per-user directory ACLs instead of POSIX mode bits.
diff --git a/scripts/url_safety.py b/scripts/url_safety.py
index 5dfb279..21c3189 100644
--- a/scripts/url_safety.py
+++ b/scripts/url_safety.py
@@ -373,6 +373,89 @@ def _proxy_hosts(url: str, proxies: Optional[dict] = None) -> frozenset:
return frozenset({host.lower()}) if host else frozenset()
+def _assert_proxy_host_is_public(host: str) -> str:
+ """Resolve one configured proxy host and refuse it unless it is public.
+
+ The exemption in :func:`_pin_dns` removes a proxy host from the
+ fall-through validation, so without this check anything the environment
+ can set (``HTTPS_PROXY``, ``ALL_PROXY``, a stray ``.bashrc`` export, a
+ hostile devcontainer image) would become an unvalidated egress target.
+ ``HTTPS_PROXY=http://169.254.169.254:3128`` would turn every audit into a
+ cloud-metadata read.
+
+ The proxy therefore goes through exactly the same policy as an audit
+ target: the hostname blocklist, then :func:`is_safe_ip` on every resolved
+ address across both families. Loopback, RFC 1918, RFC 6598, link-local,
+ and the metadata endpoints are refused with a message that names the
+ address, rather than being silently exempted.
+
+ Returns the normalized hostname. Raises ``URLSafetyError`` otherwise.
+ """
+ normalized = normalize_hostname(host)
+ hint = (
+ "Point the proxy environment variable at a publicly routable "
+ "address, or unset it."
+ )
+ if normalized in _BLOCKED_HOSTNAMES:
+ raise URLSafetyError(
+ f"Refusing configured HTTP proxy {host!r}: blocked hostname "
+ f"{normalized}. {hint}"
+ )
+
+ try:
+ literal = ipaddress.ip_address(normalized)
+ except ValueError:
+ literal = None
+
+ if literal is not None:
+ if not is_safe_ip(normalized):
+ raise URLSafetyError(
+ f"Refusing configured HTTP proxy {host!r}: non-public "
+ f"address {normalized}. {hint}"
+ )
+ return normalized
+
+ try:
+ addrinfo = socket.getaddrinfo(
+ normalized,
+ None,
+ family=socket.AF_UNSPEC,
+ type=socket.SOCK_STREAM,
+ )
+ except (socket.gaierror, UnicodeError) as exc:
+ raise URLSafetyError(
+ f"Refusing configured HTTP proxy {host!r}: DNS resolution "
+ f"failed ({exc}). {hint}"
+ ) from exc
+
+ resolved_ips = sorted({info[4][0] for info in addrinfo if info[4]})
+ if not resolved_ips:
+ raise URLSafetyError(
+ f"Refusing configured HTTP proxy {host!r}: no address records. "
+ f"{hint}"
+ )
+ for ip_str in resolved_ips:
+ if not is_safe_ip(ip_str):
+ raise URLSafetyError(
+ f"Refusing configured HTTP proxy {host!r}: it resolves to "
+ f"non-public IP {ip_str}. {hint}"
+ )
+ return normalized
+
+
+def _validated_proxy_hosts(url: str, proxies: Optional[dict] = None) -> frozenset:
+ """The proxy hosts to exempt from the pinned scope, each policy-checked.
+
+ Thin wrapper over :func:`_proxy_hosts` and
+ :func:`_assert_proxy_host_is_public`. Must be called *before* entering
+ :func:`_pin_dns`, so the resolution it performs goes through the real
+ resolver rather than the patched one.
+ """
+ return frozenset(
+ _assert_proxy_host_is_public(host) for host in _proxy_hosts(url, proxies)
+ )
+
+
# A single non-blocking lock guards the global getaddrinfo monkey-patch.
# This is a deliberate choice: claude-seo scripts run one URL fetch at a
# time, and we'd rather raise loudly than silently corrupt resolver state
@@ -395,12 +478,15 @@ def _pin_dns(
which ``requests`` surfaces as ``ConnectionError`` — the caller's
existing error path.
- ``exempt_hosts`` are resolved by the real resolver without validation.
- It carries the configured HTTP proxy, if any (see :func:`_proxy_hosts`):
- the proxy is the process's own egress and commonly sits on loopback, so
- refusing it refused every fetch. Behind a CONNECT proxy the target is
- resolved by the proxy, and :func:`validate_url_strict`'s pre-flight
- check remains the guard for it.
+ ``exempt_hosts`` are resolved by the real resolver without the
+ fall-through check. It carries the configured HTTP proxy, if any: the
+ proxy is the process's own egress, and requests must resolve it to open
+ the tunnel, which the fall-through check otherwise refused. Callers pass
+ :func:`_validated_proxy_hosts`, which has already put that host through
+ the hostname blocklist and :func:`is_safe_ip`, so a proxy on loopback or
+ at a metadata address never reaches this set. Behind a CONNECT proxy the
+ target is resolved by the proxy, and :func:`validate_url_strict`'s
+ pre-flight check remains the guard for it.
The fall-through validation is the v2 fix for redirect-target DNS
rebinding: ``requests.Session.get(allow_redirects=True)`` may follow
@@ -483,7 +569,7 @@ def safe_requests_get(
parsed = urlparse(norm_url)
port = parsed.port or (443 if parsed.scheme == "https" else 80)
assert parsed.hostname is not None # validate_url_strict guarantees this
- exempt = _proxy_hosts(norm_url, kwargs.get("proxies"))
+ exempt = _validated_proxy_hosts(norm_url, kwargs.get("proxies"))
with _pin_dns(parsed.hostname, pinned_ip, port, exempt_hosts=exempt):
return requests.get(norm_url, timeout=timeout, **kwargs)
@@ -504,7 +590,7 @@ def safe_requests_head(
parsed = urlparse(norm_url)
port = parsed.port or (443 if parsed.scheme == "https" else 80)
assert parsed.hostname is not None
- exempt = _proxy_hosts(norm_url, kwargs.get("proxies"))
+ exempt = _validated_proxy_hosts(norm_url, kwargs.get("proxies"))
with _pin_dns(parsed.hostname, pinned_ip, port, exempt_hosts=exempt):
return requests.head(norm_url, timeout=timeout, **kwargs)
@@ -521,7 +607,7 @@ def safe_requests_session(url: str) -> Iterator[requests.Session]:
port = parsed.port or (443 if parsed.scheme == "https" else 80)
assert parsed.hostname is not None
session = requests.Session()
- exempt = _proxy_hosts(norm_url, session.proxies)
+ exempt = _validated_proxy_hosts(norm_url, session.proxies)
with _pin_dns(parsed.hostname, pinned_ip, port, exempt_hosts=exempt):
try:
yield session
diff --git a/tests/test_url_safety.py b/tests/test_url_safety.py
index 86de415..0906704 100644
--- a/tests/test_url_safety.py
+++ b/tests/test_url_safety.py
@@ -20,7 +20,6 @@ from types import SimpleNamespace
from unittest.mock import patch
import pytest
-import requests
_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")
if _SCRIPTS not in sys.path:
@@ -658,6 +657,9 @@ def test_proxy_hosts_is_empty_without_a_proxy(monkeypatch) -> None:
def test_pin_dns_lets_the_exempt_proxy_host_resolve_to_loopback() -> None:
+ """The primitive honours whatever exempt set it is handed. Callers reach it
+ through _validated_proxy_hosts, which refuses a loopback proxy before it can
+ ever land in that set; this test pins the low-level contract only."""
original_getaddrinfo = socket.getaddrinfo
def fake_getaddrinfo(host, port, *args, **kwargs):
@@ -693,28 +695,129 @@ def test_pin_dns_exemption_does_not_leak_to_other_hosts() -> None:
socket.getaddrinfo("redirected.example", 80)
-def test_safe_requests_get_reaches_a_loopback_proxy(monkeypatch) -> None:
- """End to end, offline: with HTTPS_PROXY on loopback the request must get
- as far as the proxy socket. A closed port turns that into a plain
- connection refusal, whereas before the fix url_safety refused to resolve
- the proxy at all."""
- probe = socket.socket()
- probe.bind(("127.0.0.1", 0))
- closed_port = probe.getsockname()[1]
- probe.close()
- _system_proxies(monkeypatch, {"https": f"http://127.0.0.1:{closed_port}"})
+def _fake_resolver(mapping: dict):
+ """getaddrinfo stand-in resolving only the named hosts, refusing the rest.
+
+ Refusing everything else keeps these tests from touching the developer's
+ real resolver, which would make them slow and network-dependent.
+ """
+ def fake_getaddrinfo(host, port, *args, **kwargs):
+ if host in mapping:
+ return _addrinfo(mapping[host], port or 0)
+ raise socket.gaierror(socket.EAI_NONAME, f"unmocked host {host!r}")
+
+ return fake_getaddrinfo
+
+
+def test_assert_proxy_host_is_public_accepts_a_public_proxy() -> None:
+ resolver = _fake_resolver({"proxy.corp.example": "8.8.4.4"})
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=resolver):
+ assert (
+ url_safety._assert_proxy_host_is_public("Proxy.Corp.Example")
+ == "proxy.corp.example"
+ )
+
+
+ "proxy_host",
+ [
+ "127.0.0.1", # loopback
+ "10.0.0.5", # RFC 1918
+ "192.168.1.10", # RFC 1918
+ "169.254.169.254", # cloud metadata / link-local
+ "100.100.100.200", # RFC 6598, Alibaba metadata
+ "metadata.google.internal",
+ "localhost",
+ ],
+)
+def test_assert_proxy_host_is_public_refuses_non_public_proxies(proxy_host) -> None:
+ """A proxy is exempt from the pinned scope, so it gets the same policy as
+ an audit target. Anything the environment can point at the local network
+ or a metadata endpoint must be refused, not exempted."""
+ with pytest.raises(url_safety.URLSafetyError, match="Refusing configured HTTP proxy"):
+ url_safety._assert_proxy_host_is_public(proxy_host)
+
+
+def test_assert_proxy_host_is_public_refuses_a_proxy_that_resolves_private() -> None:
+ """The literal is public-looking; only resolution reveals the private IP."""
+ resolver = _fake_resolver({"proxy.evil.example": "10.1.2.3"})
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=resolver):
+ with pytest.raises(url_safety.URLSafetyError, match="non-public IP 10.1.2.3"):
+ url_safety._assert_proxy_host_is_public("proxy.evil.example")
+
+
+def test_validated_proxy_hosts_is_empty_without_a_proxy(monkeypatch) -> None:
+ _system_proxies(monkeypatch, {})
+ assert url_safety._validated_proxy_hosts("https://example.com/") == frozenset()
+
+
+def _run_safe_get_with_proxy(monkeypatch, proxy_url: str, resolves: dict):
+ """Drive safe_requests_get with a pinned environment proxy, capturing the
+ exempt set handed to _pin_dns. Returns that captured dict."""
+ captured: dict = {}
+ _system_proxies(monkeypatch, {"https": proxy_url})
monkeypatch.delenv("NO_PROXY", raising=False)
+ monkeypatch.delenv("no_proxy", raising=False)
- original_getaddrinfo = socket.getaddrinfo
+ @contextmanager
+ def fake_pin(hostname: str, pinned_ip: str, port: int, exempt_hosts=frozenset()):
+ captured["exempt"] = exempt_hosts
+ yield
- def fake_getaddrinfo(host, port, *args, **kwargs):
- if host == "example.com":
- return _addrinfo("93.184.216.34", port or 443)
- if host == "127.0.0.1":
- return _addrinfo("127.0.0.1", port or closed_port)
- return original_getaddrinfo(host, port, *args, **kwargs)
+ with patch.object(
+ url_safety.socket, "getaddrinfo", side_effect=_fake_resolver(resolves)
+ ), patch.object(
+ url_safety, "_pin_dns", side_effect=fake_pin
+ ), patch.object(
+ url_safety.requests, "get", return_value=SimpleNamespace(status_code=200)
+ ):
+ captured["response"] = url_safety.safe_requests_get(
+ "https://example.com/", timeout=5
+ )
+ return captured
- with patch.object(url_safety.socket, "getaddrinfo", side_effect=fake_getaddrinfo):
- with pytest.raises(requests.exceptions.ProxyError) as excinfo:
+
+def test_safe_requests_get_exempts_a_public_proxy(monkeypatch) -> None:
+ """Positive control: a proxy on a public address is still exempted, so the
+ #280 fix keeps working for a real corporate proxy."""
+ captured = _run_safe_get_with_proxy(
+ monkeypatch,
+ "http://proxy.corp.example:8080",
+ {"example.com": "93.184.216.34", "proxy.corp.example": "8.8.4.4"},
+ )
+ assert captured["exempt"] == frozenset({"proxy.corp.example"})
+ assert captured["response"].status_code == 200
+
+
+ "proxy_url",
+ ["http://169.254.169.254:3128", "http://127.0.0.1:8080"],
+)
+def test_safe_requests_get_refuses_a_non_public_proxy(monkeypatch, proxy_url) -> None:
+ """Negative control: the exemption must never be granted to a proxy on
+ loopback or at a metadata address. Before this check, setting HTTPS_PROXY
+ was enough to read cloud metadata through every audit."""
+ _system_proxies(monkeypatch, {"https": proxy_url})
+ monkeypatch.delenv("NO_PROXY", raising=False)
+ monkeypatch.delenv("no_proxy", raising=False)
+
+ resolver = _fake_resolver({"example.com": "93.184.216.34"})
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=resolver):
+ with pytest.raises(
+ url_safety.URLSafetyError, match="Refusing configured HTTP proxy"
+ ):
url_safety.safe_requests_get("https://example.com/", timeout=5)
- assert "url_safety: refused to resolve" not in str(excinfo.value)
+
+
+def test_safe_requests_session_refuses_a_non_public_proxy(monkeypatch) -> None:
+ _system_proxies(monkeypatch, {"https": "http://127.0.0.1:8080"})
+ monkeypatch.delenv("NO_PROXY", raising=False)
+ monkeypatch.delenv("no_proxy", raising=False)
+
+ resolver = _fake_resolver({"example.com": "93.184.216.34"})
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=resolver):
+ with pytest.raises(
+ url_safety.URLSafetyError, match="Refusing configured HTTP proxy"
+ ):
+ with url_safety.safe_requests_session("https://example.com/"):
+ pass