| 1 | """Public-host checks for fetching addresses taken from remote content. |
| 2 | |
| 3 | ``lib/http.py`` follows any redirect and resolves any name. A lane that |
| 4 | fetches an address it read from a page, a sitemap or a guess about a |
| 5 | company's site uses these checks so that remote content cannot point it at a |
| 6 | service on the user's own network: the address must be http(s), on the site |
| 7 | the lane meant to read, and every address its name resolves to must be a |
| 8 | public one. ``redirect_guard`` gives the same check to ``http.get_text`` so a |
| 9 | redirect is refused before it is followed. |
| 10 | """ |
| 11 | |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import functools |
| 15 | import ipaddress |
| 16 | import socket |
| 17 | from typing import Callable |
| 18 | from urllib.parse import urlparse |
| 19 | |
| 20 | |
| 21 | def _host_of(url: str) -> str: |
| 22 | try: |
| 23 | parsed = urlparse(url if "://" in url else f"https://{url}") |
| 24 | except ValueError: |
| 25 | return "" |
| 26 | if parsed.username is not None or parsed.password is not None: |
| 27 | return "" |
| 28 | return (parsed.hostname or "").rstrip(".").lower() |
| 29 | |
| 30 | |
| 31 | def _parse_ip_literal(name: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None: |
| 32 | bare = name.split("%", 1)[0] |
| 33 | try: |
| 34 | return ipaddress.ip_address(bare) |
| 35 | except ValueError: |
| 36 | pass |
| 37 | try: |
| 38 | packed = socket.inet_aton(bare) |
| 39 | except OSError: |
| 40 | return None |
| 41 | return ipaddress.IPv4Address(packed) |
| 42 | |
| 43 | |
| 44 | def _same_site(host: str, site_host: str) -> bool: |
| 45 | base = site_host.rstrip(".").lower().removeprefix("www.") |
| 46 | cand = host.rstrip(".").lower().removeprefix("www.") |
| 47 | if not base or not cand: |
| 48 | return False |
| 49 | if _parse_ip_literal(base) is not None or _parse_ip_literal(cand) is not None: |
| 50 | return cand == base |
| 51 | return cand == base or cand.endswith("." + base) |
| 52 | |
| 53 | |
| 54 | _NAT64_WELL_KNOWN = ipaddress.IPv6Network("64:ff9b::/96") |
| 55 | _NAT64_LOCAL = ipaddress.IPv6Network("64:ff9b:1::/48") |
| 56 | |
| 57 | |
| 58 | def _is_public_ip(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: |
| 59 | if ( |
| 60 | not address.is_global |
| 61 | or address.is_multicast |
| 62 | or address.is_private |
| 63 | or address.is_loopback |
| 64 | or address.is_link_local |
| 65 | or address.is_reserved |
| 66 | or address.is_unspecified |
| 67 | ): |
| 68 | return False |
| 69 | if isinstance(address, ipaddress.IPv6Address): |
| 70 | for embedded in ( |
| 71 | address.ipv4_mapped, |
| 72 | address.sixtofour, |
| 73 | address.teredo[1] if address.teredo else None, |
| 74 | ): |
| 75 | if embedded is not None and not _is_public_ip(embedded): |
| 76 | return False |
| 77 | if address in _NAT64_WELL_KNOWN or address in _NAT64_LOCAL: |
| 78 | embedded = ipaddress.IPv4Address(int(address) & 0xFFFFFFFF) |
| 79 | if not _is_public_ip(embedded): |
| 80 | return False |
| 81 | return True |
| 82 | |
| 83 | |
| 84 | def is_public_address_syntax(url: str) -> bool: |
| 85 | """Zero-DNS check: ``url`` is http(s) with no userinfo, not localhost, and |
| 86 | not a non-public IP literal.""" |
| 87 | if not isinstance(url, str) or not url or url != url.strip(): |
| 88 | return False |
| 89 | if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in url): |
| 90 | return False |
| 91 | try: |
| 92 | parsed = urlparse(url) |
| 93 | _ = parsed.port |
| 94 | except ValueError: |
| 95 | return False |
| 96 | if parsed.scheme.lower() not in ("http", "https"): |
| 97 | return False |
| 98 | if parsed.username is not None or parsed.password is not None: |
| 99 | return False |
| 100 | name = (parsed.hostname or "").rstrip(".").lower() |
| 101 | if not name or name == "localhost" or name.endswith(".localhost"): |
| 102 | return False |
| 103 | ip = _parse_ip_literal(name) |
| 104 | if ip is not None: |
| 105 | return _is_public_ip(ip) |
| 106 | return True |
| 107 | |
| 108 | |
| 109 | class NonPublicAddressError(OSError): |
| 110 | """Raised when a host resolves to (or is) a non-public IP address.""" |
| 111 | |
| 112 | |
| 113 | def resolve_public_addresses(host: str, port: int) -> list[tuple]: |
| 114 | """Resolve ``host`` fresh (never cached) and return TCP addrinfo tuples |
| 115 | only if every resolved address is public; otherwise raise |
| 116 | :class:`NonPublicAddressError`.""" |
| 117 | bare = (host or "").strip() |
| 118 | if bare.startswith("[") and bare.endswith("]"): |
| 119 | bare = bare[1:-1] |
| 120 | bare = bare.rstrip(".").lower() |
| 121 | if not bare or bare == "localhost" or bare.endswith(".localhost"): |
| 122 | raise NonPublicAddressError("refused non-public address") |
| 123 | literal = _parse_ip_literal(bare) |
| 124 | if literal is not None: |
| 125 | if not _is_public_ip(literal): |
| 126 | raise NonPublicAddressError("refused non-public address") |
| 127 | family = socket.AF_INET6 if isinstance(literal, ipaddress.IPv6Address) else socket.AF_INET |
| 128 | sockaddr = (str(literal), port, 0, 0) if family == socket.AF_INET6 else (str(literal), port) |
| 129 | return [(family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", sockaddr)] |
| 130 | answers = socket.getaddrinfo(bare, port, 0, socket.SOCK_STREAM) |
| 131 | if not answers: |
| 132 | raise NonPublicAddressError("refused non-public address") |
| 133 | verified: list[tuple] = [] |
| 134 | for family, socktype, proto, canonname, sockaddr in answers: |
| 135 | try: |
| 136 | ip = ipaddress.ip_address(sockaddr[0].split("%", 1)[0]) |
| 137 | except ValueError as exc: |
| 138 | raise NonPublicAddressError("refused non-public address") from exc |
| 139 | if not _is_public_ip(ip): |
| 140 | raise NonPublicAddressError("refused non-public address") |
| 141 | verified.append((family, socktype, proto, canonname, sockaddr)) |
| 142 | return verified |
| 143 | |
| 144 | |
| 145 | def public_any_url(url: str, *, resolves: Callable[[str], bool] | None = None) -> bool: |
| 146 | """Whether ``url`` is an http(s) address with no userinfo whose host is a |
| 147 | public IP or resolves exclusively to public IPs (any site, uncached).""" |
| 148 | if not is_public_address_syntax(url): |
| 149 | return False |
| 150 | name = (urlparse(url).hostname or "").rstrip(".").lower() |
| 151 | ip = _parse_ip_literal(name) |
| 152 | if ip is not None: |
| 153 | return _is_public_ip(ip) |
| 154 | if resolves is not None: |
| 155 | return resolves(name) |
| 156 | try: |
| 157 | return bool(resolve_public_addresses(name, 80)) |
| 158 | except (OSError, UnicodeError): |
| 159 | return False |
| 160 | |
| 161 | |
| 162 | def public_url(url: str, host: str, *, resolves: Callable[[str], bool] | None = None) -> bool: |
| 163 | """Whether ``url`` is an http(s) address on the site of ``host`` whose host |
| 164 | is a name, not an address on a private, loopback or reserved network. |
| 165 | |
| 166 | ``resolves`` decides whether a name resolves only to public addresses; |
| 167 | it defaults to ``resolves_public``. |
| 168 | """ |
| 169 | if not is_public_address_syntax(url): |
| 170 | return False |
| 171 | name = (urlparse(url).hostname or "").rstrip(".").lower() |
| 172 | if not _same_site(name, host): |
| 173 | return False |
| 174 | ip = _parse_ip_literal(name) |
| 175 | if ip is not None: |
| 176 | return _is_public_ip(ip) |
| 177 | return (resolves or resolves_public)(name) |
| 178 | |
| 179 | |
| 180 | @functools.lru_cache(maxsize=256) |
| 181 | def resolves_public(name: str) -> bool: |
| 182 | """Whether every address ``name`` resolves to is a public one. A name that |
| 183 | points at a private network (an internal subdomain) is not fetched; a |
| 184 | name that does not resolve is not either.""" |
| 185 | try: |
| 186 | answers = socket.getaddrinfo(name, None, type=socket.SOCK_STREAM) |
| 187 | except (OSError, UnicodeError): |
| 188 | return False |
| 189 | addresses = set() |
| 190 | for answer in answers: |
| 191 | try: |
| 192 | addresses.add(ipaddress.ip_address(answer[4][0].split("%", 1)[0])) |
| 193 | except ValueError: |
| 194 | return False |
| 195 | return bool(addresses) and all(_is_public_ip(address) for address in addresses) |
| 196 | |
| 197 | |
| 198 | def redirect_guard(url: str, *, resolves: Callable[[str], bool] | None = None) -> Callable[[str], bool]: |
| 199 | """The redirect check for a fetch of ``url``: it may be redirected only to |
| 200 | an address on the same site that is not on a private network.""" |
| 201 | host = _host_of(url) |
| 202 | return lambda target: public_url(target, host, resolves=resolves) |
| 203 |