|
| 1 | +"""SSRF guard for outbound HTTP fetches. |
| 2 | +
|
| 3 | +Every fetcher in this codebase pulls URLs that originated outside our |
| 4 | +control: yc-oss/api gives us company website URLs, the LLM cites |
| 5 | +``oss_evidence_url`` and traction-source URLs, the depth=1 crawler |
| 6 | +follows ``href`` attributes, and the link verifier re-fetches every cited |
| 7 | +URL before any artifact is published. |
| 8 | +
|
| 9 | +Without an SSRF guard, a poisoned upstream value or a hallucinated LLM |
| 10 | +output could direct the verifier to scan loopback / RFC1918 / link-local |
| 11 | +ranges — including AWS/GCP/Azure metadata endpoints |
| 12 | +(``169.254.169.254``) when this is run on cloud infrastructure. |
| 13 | +
|
| 14 | +Use ``is_safe_external_url`` before any outbound call. It rejects: |
| 15 | +- non-http/https schemes (file://, ftp://, gopher://, etc.) |
| 16 | +- malformed URLs (no host) |
| 17 | +- hostnames whose resolved IPs are loopback, link-local, private, |
| 18 | + reserved, multicast, or unspecified |
| 19 | +- a few well-known cloud metadata hostnames |
| 20 | +
|
| 21 | +The check resolves the host via DNS. The resolved-IP set is checked, |
| 22 | +not just the first record, to defend against DNS rebinding (where a |
| 23 | +hostname returns one address now and a different one on the next |
| 24 | +lookup). Callers that re-resolve later should either pin the address |
| 25 | +returned here or accept the residual risk. |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +import ipaddress |
| 31 | +import logging |
| 32 | +import socket |
| 33 | +from urllib.parse import urlparse |
| 34 | + |
| 35 | +log = logging.getLogger(__name__) |
| 36 | + |
| 37 | +# Hostnames that are not in private IP ranges but are known SSRF targets |
| 38 | +# (cloud-provider instance-metadata services). |
| 39 | +_BLOCKED_HOSTS: frozenset[str] = frozenset( |
| 40 | + { |
| 41 | + "metadata.google.internal", |
| 42 | + "metadata.goog", |
| 43 | + "metadata", # Some clouds resolve bare 'metadata' on the local network |
| 44 | + } |
| 45 | +) |
| 46 | + |
| 47 | +# RFC 2606 reserved TLDs that are guaranteed never to resolve and are |
| 48 | +# explicitly intended for documentation, testing, and example use. We |
| 49 | +# allow them through the safety check because they're harmless (the |
| 50 | +# fetch will fail with a DNS error, never reach a real host) and tests |
| 51 | +# in this codebase rely on them. ``.localhost`` is *not* in this set — |
| 52 | +# it resolves to 127.0.0.1 and must be blocked. |
| 53 | +_RESERVED_TEST_TLDS: tuple[str, ...] = (".example", ".test", ".invalid") |
| 54 | + |
| 55 | + |
| 56 | +def _resolve_all(host: str) -> list[str]: |
| 57 | + """Return every IP address ``host`` resolves to, or ``[]`` on failure.""" |
| 58 | + try: |
| 59 | + infos = socket.getaddrinfo(host, None) |
| 60 | + except (socket.gaierror, UnicodeError): |
| 61 | + return [] |
| 62 | + seen: set[str] = set() |
| 63 | + out: list[str] = [] |
| 64 | + for info in infos: |
| 65 | + # sockaddr layout: IPv4 = (host, port); IPv6 = (host, port, flow, scope). |
| 66 | + sockaddr = info[4] |
| 67 | + ip = str(sockaddr[0]) |
| 68 | + if ip not in seen: |
| 69 | + seen.add(ip) |
| 70 | + out.append(ip) |
| 71 | + return out |
| 72 | + |
| 73 | + |
| 74 | +def is_safe_external_url(url: str) -> bool: |
| 75 | + """Return True if ``url`` is safe to fetch from an outbound HTTP client. |
| 76 | +
|
| 77 | + "Safe" here means: the URL resolves to a public, routable address |
| 78 | + on the open Internet — not loopback, not RFC1918, not link-local |
| 79 | + (which includes cloud metadata endpoints), not multicast, not |
| 80 | + reserved. |
| 81 | + """ |
| 82 | + try: |
| 83 | + parsed = urlparse(url) |
| 84 | + except ValueError: |
| 85 | + return False |
| 86 | + if parsed.scheme not in ("http", "https"): |
| 87 | + return False |
| 88 | + host = (parsed.hostname or "").lower() |
| 89 | + if not host: |
| 90 | + return False |
| 91 | + if host in _BLOCKED_HOSTS: |
| 92 | + log.debug("blocked SSRF host: %s", host) |
| 93 | + return False |
| 94 | + if any(host == tld[1:] or host.endswith(tld) for tld in _RESERVED_TEST_TLDS): |
| 95 | + # Reserved TLDs (RFC 2606): allowed because they cannot resolve to |
| 96 | + # a real host. The eventual fetch will fail with NXDOMAIN. |
| 97 | + return True |
| 98 | + # If the URL embeds a literal IP, check it directly without DNS. |
| 99 | + try: |
| 100 | + ip = ipaddress.ip_address(host) |
| 101 | + except ValueError: |
| 102 | + ips = _resolve_all(host) |
| 103 | + if not ips: |
| 104 | + log.debug("DNS resolution failed for %s; refusing fetch", host) |
| 105 | + return False |
| 106 | + return all(_ip_is_public(addr) for addr in ips) |
| 107 | + return _ip_is_public(str(ip)) |
| 108 | + |
| 109 | + |
| 110 | +def _ip_is_public(ip_str: str) -> bool: |
| 111 | + """True if ``ip_str`` is a public, routable address.""" |
| 112 | + try: |
| 113 | + ip = ipaddress.ip_address(ip_str) |
| 114 | + except ValueError: |
| 115 | + return False |
| 116 | + if ip.is_loopback: |
| 117 | + return False |
| 118 | + if ip.is_private: |
| 119 | + return False |
| 120 | + if ip.is_link_local: |
| 121 | + return False |
| 122 | + if ip.is_multicast: |
| 123 | + return False |
| 124 | + if ip.is_reserved: |
| 125 | + return False |
| 126 | + return not ip.is_unspecified |
| 127 | + |
| 128 | + |
| 129 | +__all__ = ["is_safe_external_url"] |
0 commit comments