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 cache-path traversal and WHOIS referral SSRF
Claude0cea1ddfc078
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b5102d8..5c8f2c0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- `commoncrawl_graph.py` no longer writes outside its cache directory. The+ `--release` value was interpolated raw into the cache filename, so+ `--release ../../../../tmp/x` escaped the cache dir and `_save_cache`'s+ `open(..., "w")` followed it. The value also reaches a download URL, so a+ malformed release is now rejected at the CLI rather than silently rewritten+ (which would leave the cache key disagreeing with what was fetched); path+ components are sanitised and containment asserted as defence in depth.+- `domain_history.py` no longer follows an unvalidated WHOIS referral. It asks+ IANA for the authoritative server and dialled whatever host came back, over+ plaintext port 43: so anyone able to tamper with that response could point+ it at an internal address and use it to probe the operator's private network.+ The referral is now resolved and validated through `url_safety` and the+ connection is made to the pinned address; an unusable referral degrades to+ IANA's own answer rather than blanking the lookup.+## [2.2.5] - 2026-08-25### Addeddiff --git a/scripts/commoncrawl_graph.py b/scripts/commoncrawl_graph.pyindex 460129c..884d69e 100644--- a/scripts/commoncrawl_graph.py+++ b/scripts/commoncrawl_graph.py@@ -21,6 +21,7 @@ import gzipimport ioimport jsonimport os+import reimport sysimport timefrom typing import Optional@@ -95,11 +96,47 @@ def _get_latest_release() -> Optional[str]:return None+_CACHE_COMPONENT_RE = re.compile(r"[^A-Za-z0-9._-]")++# A Common Crawl release id, e.g. cc-main-2026-jan-feb-mar. Anchored, and no+# '..' anywhere, because this value lands in a filesystem path and a URL path.+_RELEASE_RE = re.compile(r"^(?!.*\.\.)[A-Za-z0-9._-]+$")+++def _safe_cache_component(value: str) -> str:+ """Reduce one path component to a conservative charset.++ Everything outside [A-Za-z0-9._-] becomes '_', then any run of dots is+ collapsed so '..' can never survive. Both halves matter: stripping+ separators alone still lets '..' through on a caller that joins+ differently, and collapsing dots alone still lets a separator through.+ """+ cleaned = _CACHE_COMPONENT_RE.sub("_", value)+ while ".." in cleaned:+ cleaned = cleaned.replace("..", "_")+ return cleaned.strip("._") or "_"++def _get_cache_path(domain: str, release: str, data_type: str) -> str:- """Get the cache file path for a domain's data."""+ """Get the cache file path for a domain's data.++ Both `domain` and `release` reach this from the CLI. `release` used to be+ interpolated raw, so `--release ../../../../tmp/x` escaped the cache+ directory and `_save_cache`'s open(..., "w") wrote outside it. Every+ component is now sanitised, and the joined result is asserted to stay+ inside the cache directory as defence in depth.+ """cache_dir = get_cache_dir()- safe_domain = domain.replace("/", "_").replace(":", "_")- return os.path.join(cache_dir, f"{safe_domain}-{release}-{data_type}.json")+ safe_domain = _safe_cache_component(domain)+ safe_release = _safe_cache_component(release)+ safe_type = _safe_cache_component(data_type)+ path = os.path.join(cache_dir, f"{safe_domain}-{safe_release}-{safe_type}.json")++ resolved = os.path.realpath(path)+ root = os.path.realpath(cache_dir)+ if not (resolved == root or resolved.startswith(root + os.sep)):+ raise ValueError(f"refusing to build a cache path outside {root}")+ return pathdef _is_cached(domain: str, release: str) -> Optional[dict]:@@ -431,6 +468,19 @@ def main():print("Error: domain argument required (or use --info)", file=sys.stderr)sys.exit(1)+ # Reject a malformed release rather than silently sanitising it. The value+ # is interpolated into both a cache filename and a download URL+ # (_graph_file_url), so quietly rewriting it for one and not the other+ # would make the cache key disagree with what was actually fetched.+ if args.release is not None and not _RELEASE_RE.match(args.release):+ print(+ f"Error: invalid --release {args.release!r}. Expected a release id "+ "such as cc-main-2026-jan-feb-mar (letters, digits, dot, dash, "+ "underscore only).",+ file=sys.stderr,+ )+ sys.exit(1)+result = get_domain_metrics(domain=args.domain,release=args.release,diff --git a/scripts/domain_history.py b/scripts/domain_history.pyindex f271294..80841ac 100644--- a/scripts/domain_history.py+++ b/scripts/domain_history.py@@ -54,6 +54,7 @@ from __future__ import annotationsimport argparseimport json+import osimport reimport shutilimport socket@@ -62,6 +63,12 @@ import sysfrom datetime import datetime, timezonefrom typing import Optional+_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+from url_safety import URLSafetyError, validate_url_strict # noqa: E402++_DATE_LABELS = {"created": ("creation date", "created on", "registered on", "registered",@@ -124,8 +131,23 @@ def _socket_whois(domain: str) -> Optional[str]:return iana_textreferral = m.group(1).strip()++ # The referral host is attacker-influenceable: WHOIS runs unencrypted on+ # port 43, so anyone able to tamper with the IANA response can inject a+ # `refer:` line pointing at an internal address, turning this fallback into+ # a port-43 probe of the operator's private network. Resolve and validate+ # it through the same guard every other outbound call uses, then connect to+ # the pinned address so the answer cannot be re-pointed after the check.+ # WHOIS is plaintext with no SNI, so dialling the IP directly is lossless.+ try:+ _, pinned_ip = validate_url_strict(f"https://{referral}/")+ except URLSafetyError:+ # A referral we cannot vouch for is not worth following. IANA's own+ # answer is still useful, so return that rather than nothing.+ return iana_text+try:- with socket.create_connection((referral, 43), timeout=10) as sock:+ with socket.create_connection((pinned_ip, 43), timeout=10) as sock:sock.sendall(f"{domain}\r\n".encode("ascii"))buf = b""while True:diff --git a/tests/test_commoncrawl_graph.py b/tests/test_commoncrawl_graph.pynew file mode 100644index 0000000..bc12d34--- /dev/null+++ b/tests/test_commoncrawl_graph.py@@ -0,0 +1,87 @@+"""+Tests for scripts/commoncrawl_graph.py.++Focus: cache-path construction. `--release` reached `_get_cache_path`+completely unsanitised and the result is opened for writing in `_save_cache`,+so `--release ../../../../tmp/x` wrote outside the cache directory. The same+value is also interpolated into a download URL by `_graph_file_url`, so it is+rejected at the CLI boundary rather than silently rewritten -- otherwise the+cache key would disagree with what was actually fetched.++No network: only the pure path/validation helpers are exercised.+"""++from __future__ import annotations++import os+import sys++import pytest++_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")+if _SCRIPTS not in sys.path:+ sys.path.insert(0, _SCRIPTS)++import commoncrawl_graph as ccg # noqa: E402+++def _inside_cache_dir(path: str) -> bool:+ root = os.path.realpath(ccg.get_cache_dir())+ resolved = os.path.realpath(path)+ return resolved == root or resolved.startswith(root + os.sep)+++# ---------------------------------------------------------------------------+# path traversal+# ---------------------------------------------------------------------------+++ "domain,release",+ [+ ("example.com", "../../../../tmp/pwned"),+ ("example.com", ".."),+ ("../../../../tmp/evil", "cc-main-2026-jan-feb-mar"),+ ("../..", ".."),+ ("example.com/../../etc", "cc-main-2026-jan-feb-mar"),+ ],+)+def test_cache_path_never_escapes_the_cache_dir(domain, release):+ assert _inside_cache_dir(ccg._get_cache_path(domain, release, "combined"))+++def test_cache_path_preserves_legitimate_values():+ """Sanitising must not mangle real inputs, or every cache miss forever."""+ path = ccg._get_cache_path("example.com", "cc-main-2026-jan-feb-mar", "combined")+ assert os.path.basename(path) == "example.com-cc-main-2026-jan-feb-mar-combined.json"+ assert _inside_cache_dir(path)+++def test_safe_cache_component_collapses_dot_runs_and_separators():+ assert ".." not in ccg._safe_cache_component("../../etc/passwd")+ assert "/" not in ccg._safe_cache_component("a/b/c")+ assert os.sep not in ccg._safe_cache_component("a\\b")+ # Never returns empty, which would produce a path like "-release-type.json".+ assert ccg._safe_cache_component("...") != ""+ assert ccg._safe_cache_component("") != ""+++# ---------------------------------------------------------------------------+# release validation (also guards the URL built by _graph_file_url)+# ---------------------------------------------------------------------------+++ "release",+ ["cc-main-2026-jan-feb-mar", "cc-main-2024-oct-nov-dec", "CC-MAIN-2024-33", "a_b.c-1"],+)+def test_release_pattern_accepts_real_release_ids(release):+ assert ccg._RELEASE_RE.match(release)+++ "release",+ ["../../../../tmp/pwned", "..", "a/../b", "a..b", "with space", "", "a/b", "x\ty"],+)+def test_release_pattern_rejects_traversal_and_junk(release):+ assert not ccg._RELEASE_RE.match(release)diff --git a/tests/test_domain_history.py b/tests/test_domain_history.pynew file mode 100644index 0000000..b676a65--- /dev/null+++ b/tests/test_domain_history.py@@ -0,0 +1,106 @@+"""+Tests for scripts/domain_history.py.++Focus: the WHOIS referral chain in `_socket_whois`. It asks IANA for the+authoritative WHOIS server and then connects to whatever host IANA names. WHOIS+is plaintext on port 43, so anyone able to tamper with that response can inject+a `refer:` line pointing at an internal address and turn the fallback into a+port-43 probe of the operator's private network. The referral is now resolved+and validated through url_safety before being dialled.++No network: socket.create_connection is stubbed throughout.+"""++from __future__ import annotations++import os+import sys++import pytest++_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")+if _SCRIPTS not in sys.path:+ sys.path.insert(0, _SCRIPTS)++import domain_history as dh # noqa: E402+++class _FakeSock:+ """Minimal stand-in for a connected socket that yields one payload."""++ def __init__(self, payload: bytes) -> None:+ self._payload = payload+ self._drained = False+ self.sent = b""++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def sendall(self, data: bytes) -> None:+ self.sent += data++ def recv(self, _n: int) -> bytes:+ if self._drained:+ return b""+ self._drained = True+ return self._payload+++def _stub_chain(monkeypatch, referral_line: bytes, referral_payload: bytes):+ """Stub the IANA hop and the referral hop, recording every dial."""+ attempts: list[tuple] = []++ def fake_connection(address, timeout=None):+ attempts.append(address)+ if address[0] == "whois.iana.org":+ return _FakeSock(referral_line)+ return _FakeSock(referral_payload)++ monkeypatch.setattr(dh.socket, "create_connection", fake_connection)+ return attempts+++ "hostile",+ [+ b"refer: 169.254.169.254\n", # cloud metadata endpoint+ b"refer: 127.0.0.1\n", # loopback+ b"refer: 10.0.0.5\n", # RFC1918+ b"refer: localhost\n",+ ],+)+def test_hostile_referral_is_never_dialled(monkeypatch, hostile):+ attempts = _stub_chain(monkeypatch, hostile, b"SHOULD NOT BE REACHED\n")+ result = dh._socket_whois("example.com")++ dialled = [host for host, _port in attempts]+ assert dialled == ["whois.iana.org"], f"followed a hostile referral: {dialled}"+ assert "SHOULD NOT BE REACHED" not in (result or "")+ # IANA's own answer is still returned -- a bad referral degrades the+ # lookup, it does not blank it.+ assert "refer:" in (result or "")+++def test_legitimate_referral_is_still_followed(monkeypatch):+ """The guard must not break the normal path."""+ attempts = _stub_chain(+ monkeypatch,+ b"refer: whois.verisign-grs.com\n",+ b"Creation Date: 1995-08-14T04:00:00Z\n",+ )+ result = dh._socket_whois("example.com")++ assert len(attempts) == 2, "referral hop did not happen"+ assert "Creation Date" in (result or "")+++def test_direct_iana_answer_needs_no_referral(monkeypatch):+ """.arpa and friends come back without a refer: line."""+ attempts = _stub_chain(monkeypatch, b"domain: ARPA\nstatus: ACTIVE\n", b"unused")+ result = dh._socket_whois("in-addr.arpa")++ assert len(attempts) == 1+ assert "ARPA" in (result or "")