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(security): close obfuscated-IPv4 + FQDN + IPv6 + OAuth race bypasses
Daniel3c595c22c5c2
diff --git a/scripts/google_auth.py b/scripts/google_auth.pyindex f3fba43..bb5e695 100644--- a/scripts/google_auth.py+++ b/scripts/google_auth.py@@ -189,15 +189,30 @@ def _load_oauth_token() -> Optional[dict]:def _save_oauth_token(token_data: dict):"""Save OAuth token to TOKEN_PATH with secure (0o600) permissions.- Uses os.open with O_CREAT|O_WRONLY|O_TRUNC and an explicit mode so the- file is never world-readable, even briefly between create and chmod.- Existing files have their mode forced to 0o600 before truncation.+ Belt-and-suspenders sequence:+ 1. Pre-chmod any existing file (closes a v1.9.x umask=022 legacy).+ 2. ``os.open`` with explicit mode 0o600 (mode applies only to+ newly-created files, ignored when the file already exists).+ 3. ``os.fchmod`` on the open fd to *force* 0o600 even if the+ file pre-existed at step 2 — defeats the+ os.path.exists()/os.open() TOCTOU race where an external+ creator could install a 0o644 file between the two calls.++ The token file is never world-readable, even briefly."""os.makedirs(os.path.dirname(TOKEN_PATH), exist_ok=True)if os.path.exists(TOKEN_PATH):_chmod_quiet(TOKEN_PATH, 0o600)flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNCfd = os.open(TOKEN_PATH, flags, 0o600)+ # fchmod on the open fd guarantees 0o600 even if the file existed at+ # open time (in which case os.open's mode arg is ignored by the OS).+ # os.fdopen takes ownership of fd — it closes the fd whether the+ # write succeeds or raises, so there is no fd-leak path here.+ try:+ os.fchmod(fd, 0o600)+ except OSError:+ pass # FS may not support fchmod (e.g. some Windows filesystems)with os.fdopen(fd, "w") as f:json.dump(token_data, f, indent=2)diff --git a/scripts/url_safety.py b/scripts/url_safety.pyindex b212396..50ffa28 100644--- a/scripts/url_safety.py+++ b/scripts/url_safety.py@@ -69,6 +69,7 @@ in SECURITY.md.from __future__ import annotationsimport ipaddress+import reimport socketimport threadingfrom contextlib import contextmanager@@ -87,6 +88,7 @@ except ImportError as exc: # pragma: no cover - hard dependency__all__ = ["URLSafetyError","is_safe_ip",+ "normalize_hostname","validate_url","validate_url_strict","safe_requests_get",@@ -95,6 +97,25 @@ __all__ = []+# Regex matching any glibc / inet_aton-friendly IPv4 obfuscation. This is the+# allowlist of "looks like a numeric address" forms we want to canonicalize+# before SSRF policy is applied. Matches:+# - dotted-quad (127.0.0.1)+# - dotted with leading zeros (127.0.0.001)+# - dotted octal (0177.0.0.1)+# - dotted hex (0x7f.0.0.1)+# - three-part (a.b.c -> a.b.(c & 0xffff))+# - two-part (a.b -> a.(b & 0xffffff))+# - single integer (decimal/hex/octal: 2130706433, 0x7f000001, 017700000001)+# Any string matching this regex is normalized through socket.inet_aton, which+# produces the canonical dotted form (or raises OSError if invalid). Strings+# that don't match the regex are treated as DNS hostnames.+_IPV4_OBFUSCATED_RE = re.compile(+ r"^(?:0x[0-9a-f]+|[0-9]+)(?:\.(?:0x[0-9a-f]+|[0-9]+)){0,3}$",+ re.IGNORECASE,+)++# Hard-blocked hostnames. Anything here is refused even before DNS resolution.# Cloud metadata endpoints are the most common SSRF target; we list every# documented address across AWS, Azure, GCP, Oracle, and Alibaba so a single@@ -127,7 +148,13 @@ class URLSafetyError(ValueError):def is_safe_ip(ip_str: str) -> bool:- """Return True iff ``ip_str`` is a public unicast address."""+ """Return True iff ``ip_str`` is a public unicast address.++ Handles IPv4-mapped IPv6 (``::ffff:127.0.0.1`` correctly returns False+ because Python 3.9+'s ``ipaddress`` propagates ``is_loopback`` /+ ``is_private`` through IPv4-mapped form). IPv6 unique-local+ (``fc00::/7``) and link-local (``fe80::/10``) are also rejected.+ """try:ip = ipaddress.ip_address(ip_str)except ValueError:@@ -142,6 +169,50 @@ def is_safe_ip(ip_str: str) -> bool:)+def normalize_hostname(hostname: str) -> str:+ """+ Canonicalize a hostname so that obfuscated forms cannot bypass the+ SSRF policy. Performs three normalizations:++ 1. Lowercase (DNS is case-insensitive).+ 2. Strip a single trailing dot (RFC 1034 FQDN form). Without this,+ ``metadata.google.internal.`` would bypass the hostname+ blocklist (which holds exact strings).+ 3. If the result matches an IPv4 obfuscation pattern+ (decimal integer, hex, octal, leading zeros, short forms),+ canonicalize via ``socket.inet_aton`` to dotted-quad. This+ closes the classic SSRF bypass where ``http://2130706433/``+ (decimal 127.0.0.1), ``http://0x7f000001/``, or+ ``http://0177.0.0.1/`` would parse as a hostname rather than+ an IP literal and skip the IP-range check.++ Raises:+ URLSafetyError if the hostname is empty after normalization, or+ if an obfuscated form cannot be canonicalized (malformed input).+ """+ if not hostname:+ raise URLSafetyError("Empty hostname")++ h = hostname.lower().strip()+ # Strip a single trailing dot — FQDN form is semantically identical to+ # the bare form for the purposes of resolution and policy.+ if h.endswith(".") and not h.endswith(".."):+ h = h[:-1]++ if _IPV4_OBFUSCATED_RE.match(h):+ # inet_aton accepts the same obfuscated forms the glibc resolver+ # accepts, so canonicalization here matches what getaddrinfo+ # would produce at connect time.+ try:+ packed = socket.inet_aton(h)+ except OSError as exc:+ raise URLSafetyError(+ f"Malformed IPv4 obfuscation refused: {hostname!r} ({exc})"+ ) from exc+ h = socket.inet_ntoa(packed)+ return h++def validate_url(url: str) -> bool:"""Back-compat boolean validator. Does not resolve DNS.@@ -149,18 +220,26 @@ def validate_url(url: str) -> bool:Returns False when:- Scheme is not http or https- Hostname is missing- - Hostname is in the hard-block list- - Hostname is an IP literal that fails ``is_safe_ip``- Returns True for any other well-formed http(s) URL with a public-looking- hostname. Use ``validate_url_strict`` if the caller will open a socket- using the hostname (DNS rebinding cannot be defeated at parse time).+ - Hostname normalizes to a hard-block list entry+ (including FQDN-form metadata endpoints like+ ``metadata.google.internal.`` and obfuscated IPv4 like+ ``2130706433`` -> ``127.0.0.1``)+ - Normalized hostname is an IP literal that fails ``is_safe_ip``+ - Normalization itself fails (malformed obfuscated input)+ Returns True for any other well-formed http(s) URL with a+ public-looking hostname. Use ``validate_url_strict`` whenever the+ caller will open a socket — only the strict form catches a DNS+ record that resolves to a non-public IP at connect time."""parsed = urlparse(url)if parsed.scheme not in ("http", "https"):return Falseif not parsed.hostname:return False- hostname = parsed.hostname.lower()+ try:+ hostname = normalize_hostname(parsed.hostname)+ except URLSafetyError:+ return Falseif hostname in _BLOCKED_HOSTNAMES:return Falsetry:@@ -190,7 +269,7 @@ def validate_url_strict(url: str) -> tuple[str, str]:if not parsed.hostname:raise URLSafetyError("URL has no hostname")- hostname = parsed.hostname.lower()+ hostname = normalize_hostname(parsed.hostname)if hostname in _BLOCKED_HOSTNAMES:raise URLSafetyError(f"Blocked hostname: {hostname}")@@ -391,15 +470,33 @@ def make_safe_playwright_route_handler(route.abort()return+ try:+ normalized = normalize_hostname(host)+ except URLSafetyError:+ route.abort()+ return++ # Hostname-level blocks short-circuit DNS resolution entirely+ # (e.g. attacker.example/redirect -> metadata.google.internal).+ if normalized in _BLOCKED_HOSTNAMES:+ route.abort()+ return++ # Dual-stack resolution: Chromium may use IPv6 even when a+ # host has IPv4 records. AF_UNSPEC returns both families;+ # any single non-public record aborts the request.try:addrinfo = socket.getaddrinfo(- host, None, family=socket.AF_INET, type=socket.SOCK_STREAM+ normalized,+ None,+ family=socket.AF_UNSPEC,+ type=socket.SOCK_STREAM,)except socket.gaierror:route.abort()returnips = {info[4][0] for info in addrinfo}- if any(not is_safe_ip(ip) for ip in ips):+ if not ips or any(not is_safe_ip(ip) for ip in ips):route.abort()returnroute.continue_()diff --git a/tests/test_url_safety.py b/tests/test_url_safety.pyindex ef6ef41..9ebdb01 100644--- a/tests/test_url_safety.py+++ b/tests/test_url_safety.py@@ -26,6 +26,75 @@ if _SCRIPTS not in sys.path:import url_safety # noqa: E402+# ---------------------------------------------------------------------------+# normalize_hostname (v2 self-audit: closes obfuscated-IPv4 + FQDN bypasses)+# ---------------------------------------------------------------------------+++ "raw,expected",+ [+ # Trailing dot (FQDN form) collapses to bare form so blocklists match+ ("metadata.google.internal.", "metadata.google.internal"),+ ("example.com.", "example.com"),+ # Casing+ ("Example.COM", "example.com"),+ # Obfuscated IPv4 — every glibc-accepted form canonicalises+ ("2130706433", "127.0.0.1"), # decimal integer+ ("0x7f000001", "127.0.0.1"), # hex integer+ ("017700000001", "127.0.0.1"), # octal integer+ ("127.0.0.001", "127.0.0.1"), # leading zeros+ ("0177.0.0.1", "127.0.0.1"), # octal dotted+ ("0x7f.0.0.1", "127.0.0.1"), # hex dotted+ ("127.1", "127.0.0.1"), # two-part form+ ("127.0.1", "127.0.0.1"), # three-part form+ # Public addresses pass through (verifies normalisation doesn't+ # accidentally rewrite legitimate IPs)+ ("1.1.1.1", "1.1.1.1"),+ ("8.8.8.8", "8.8.8.8"),+ ],+)+def test_normalize_hostname(raw: str, expected: str) -> None:+ assert url_safety.normalize_hostname(raw) == expected+++def test_normalize_hostname_rejects_empty() -> None:+ with pytest.raises(url_safety.URLSafetyError, match="Empty hostname"):+ url_safety.normalize_hostname("")+++def test_normalize_hostname_passes_through_dns_names() -> None:+ assert url_safety.normalize_hostname("example.com") == "example.com"+ assert url_safety.normalize_hostname("sub.deep.example.org") == "sub.deep.example.org"+++# ---------------------------------------------------------------------------+# Obfuscated IPv4 bypass regression — validate_url MUST reject these.+# Before the v2 self-audit, validate_url returned True for these forms;+# only validate_url_strict caught them at DNS time. Anyone using the+# parse-only function as a pre-flight gate would have been vulnerable.+# ---------------------------------------------------------------------------+++ "url",+ [+ "http://2130706433/", # decimal 127.0.0.1+ "http://0x7f000001/", # hex 127.0.0.1+ "http://017700000001/", # octal 127.0.0.1+ "http://127.0.0.001/", # leading zeros+ "http://0177.0.0.1/", # octal dotted+ "http://0x7f.0.0.1/", # hex dotted+ "https://metadata.google.internal./", # FQDN trailing dot+ "https://METADATA.GOOGLE.INTERNAL/", # case bypass+ "http://Metadata.Google.Internal./", # case + FQDN combined+ ],+)+def test_validate_url_blocks_obfuscated_bypasses(url: str) -> None:+ """Each of these would have bypassed v1.x parse-mode validation."""+ assert url_safety.validate_url(url) is False++# ---------------------------------------------------------------------------# is_safe_ip# ---------------------------------------------------------------------------@@ -320,3 +389,103 @@ def test_route_handler_aborts_on_dns_failure() -> None:route = _FakeRoute()handler(route, _FakeRequest("https://nx.example/"))assert route.action == "abort"+++def test_route_handler_blocks_metadata_via_fqdn_form() -> None:+ """A redirect or subresource targeting metadata.google.internal. (with+ trailing dot) is short-circuited before DNS resolution."""+ handler = url_safety.make_safe_playwright_route_handler()+ route = _FakeRoute()+ handler(route, _FakeRequest("http://metadata.google.internal./latest"))+ assert route.action == "abort"+++def test_route_handler_blocks_obfuscated_ipv4_in_subresource() -> None:+ """Chromium might be tricked into fetching http://2130706433/... via a+ crafted script tag. The route handler normalises the host before+ resolution."""+ handler = url_safety.make_safe_playwright_route_handler()+ route = _FakeRoute()+ # 2130706433 normalises to 127.0.0.1 which is in the hard-block set.+ handler(route, _FakeRequest("http://2130706433/exfil"))+ assert route.action == "abort"+++def test_route_handler_blocks_when_ipv6_resolution_is_private() -> None:+ """Dual-stack regression: AF_UNSPEC returns both IPv4 and IPv6. If any+ record (including an IPv6 ULA) is non-public, abort.+ """+ handler = url_safety.make_safe_playwright_route_handler()+ fake = [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("1.1.1.1", 0)),+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fd00::1", 0, 0, 0)),+ ]+ with patch.object(url_safety.socket, "getaddrinfo", return_value=fake):+ route = _FakeRoute()+ handler(route, _FakeRequest("https://dualstack.example/"))+ assert route.action == "abort"+++def test_route_handler_continues_when_both_ipv4_and_ipv6_public() -> None:+ handler = url_safety.make_safe_playwright_route_handler()+ fake = [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("1.1.1.1", 0)),+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("2606:4700:4700::1111", 0, 0, 0)),+ ]+ with patch.object(url_safety.socket, "getaddrinfo", return_value=fake):+ route = _FakeRoute()+ handler(route, _FakeRequest("https://safe-dualstack.example/"))+ assert route.action == "continue"+++# ---------------------------------------------------------------------------+# OAuth token file permission hardening (Phase H)+# ---------------------------------------------------------------------------+++def test_save_oauth_token_writes_0o600(tmp_path, monkeypatch) -> None:+ """_save_oauth_token must produce a 0o600 file regardless of whether+ the path existed beforehand or what the umask is."""+ import google_auth # noqa: WPS433++ target = tmp_path / "config" / "oauth-token.json"+ monkeypatch.setattr(google_auth, "TOKEN_PATH", str(target))+ # Permissive umask: 0o022 would yield 0o644 without our explicit chmod.+ old_umask = os.umask(0o022)+ try:+ google_auth._save_oauth_token({"access_token": "abc"})+ mode = target.stat().st_mode & 0o777+ assert mode == 0o600, f"expected 0o600, got {oct(mode)}"+ finally:+ os.umask(old_umask)+++def test_save_oauth_token_remediates_legacy_0o644(tmp_path, monkeypatch) -> None:+ """A pre-existing 0o644 token (v1.9.x default) is locked down on save."""+ import google_auth # noqa: WPS433++ target = tmp_path / "config" / "oauth-token.json"+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text('{"legacy": true}')+ os.chmod(target, 0o644)+ assert target.stat().st_mode & 0o777 == 0o644++ monkeypatch.setattr(google_auth, "TOKEN_PATH", str(target))+ google_auth._save_oauth_token({"access_token": "new"})+ assert target.stat().st_mode & 0o777 == 0o600+++def test_load_oauth_token_remediates_legacy_0o644(tmp_path, monkeypatch) -> None:+ """_load_oauth_token chmods the file before reading, so the next read+ by any other process sees 0o600 even without a re-save."""+ import google_auth # noqa: WPS433++ target = tmp_path / "config" / "oauth-token.json"+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text('{"access_token": "x"}')+ os.chmod(target, 0o644)++ monkeypatch.setattr(google_auth, "TOKEN_PATH", str(target))+ data = google_auth._load_oauth_token()+ assert data == {"access_token": "x"}+ assert target.stat().st_mode & 0o777 == 0o600