feat: Pin webmention connections; re-send when responses change (v2.7.2)
- Connect to the address that passed the SSRF check (Host header and SNI carry the hostname, so TLS still verifies it), closing the DNS rebinding gap (spec 4.5). The webmention POST uses the same path. - Treat a change in the responses a note shows as an update and re-send its webmentions (spec 3.1.4), from validation and from admin moderation. Unchanged re-validations send nothing, so there is no ping-pong. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
51f711ea4a
commit
0640730416
10 files changed
+315
-26
No files matched your search
@@ -4,6 +4,8 @@ SSRF protection for webmention fetches
|
||||
Per ADR-063 Decision 9 and Webmention sections 4.2, 4.3 and 4.5:
|
||||
- Every address a hostname resolves to must be public
|
||||
- Redirects are followed by hand so each hop is checked
|
||||
- Each request connects to the address that was checked (no second DNS
|
||||
lookup that a rebinding DNS server could answer differently)
|
||||
- Redirect count, response size and total time are limited
|
||||
- DEV_MODE exception for localhost testing
|
||||
|
||||
@@ -89,7 +91,7 @@ def safe_resolve(hostname: str) -> str:
|
||||
Per background-worker.md: DEV_MODE exception for localhost testing.
|
||||
|
||||
Returns:
|
||||
First resolved IP address
|
||||
Address to connect to (IPv4 preferred)
|
||||
|
||||
Raises:
|
||||
SSRFBlockedError: If any address is blocked
|
||||
@@ -98,7 +100,8 @@ def safe_resolve(hostname: str) -> str:
|
||||
if current_app.config.get('DEV_MODE') and hostname in ('localhost', '127.0.0.1', '::1'):
|
||||
return '127.0.0.1'
|
||||
|
||||
addresses = sorted({info[4][0] for info in socket.getaddrinfo(hostname, None)})
|
||||
addresses = sorted({info[4][0] for info in socket.getaddrinfo(hostname, None)},
|
||||
key=lambda ip: (':' in ip, ip))
|
||||
for ip in addresses:
|
||||
if is_private_ip(ip):
|
||||
raise SSRFBlockedError(f"Blocked request to private IP: {ip}")
|
||||
@@ -106,10 +109,13 @@ def safe_resolve(hostname: str) -> str:
|
||||
return addresses[0]
|
||||
|
||||
|
||||
def validate_url_for_fetch(url: str) -> None:
|
||||
def validate_url_for_fetch(url: str) -> str:
|
||||
"""
|
||||
Validate URL is safe to fetch (http(s), public addresses only).
|
||||
|
||||
Returns:
|
||||
The checked IP address to connect to
|
||||
|
||||
Raises:
|
||||
SSRFBlockedError: If URL points to a blocked address
|
||||
ValueError: If URL is malformed or its host does not resolve
|
||||
@@ -123,11 +129,48 @@ def validate_url_for_fetch(url: str) -> None:
|
||||
raise ValueError("URL must include a hostname")
|
||||
|
||||
try:
|
||||
safe_resolve(parsed.hostname)
|
||||
return safe_resolve(parsed.hostname)
|
||||
except socket.gaierror as e:
|
||||
raise ValueError(f"Could not resolve {parsed.hostname}: {e}")
|
||||
|
||||
|
||||
def _pinned_request(client: httpx.Client, method: str, url: str, headers: dict,
|
||||
**kwargs) -> httpx.Request:
|
||||
"""
|
||||
Build a request that connects to the checked address for url's host.
|
||||
|
||||
The URL's host is replaced by the IP that passed the SSRF check; the
|
||||
real host goes in the Host header and, for https, in SNI, so virtual
|
||||
hosting and certificate verification still use the hostname.
|
||||
"""
|
||||
ip = validate_url_for_fetch(url)
|
||||
parsed = urlparse(url)
|
||||
ip_host = f"[{ip}]" if ':' in ip else ip
|
||||
port = f":{parsed.port}" if parsed.port else ''
|
||||
pinned_url = parsed._replace(netloc=f"{ip_host}{port}").geturl()
|
||||
host_header = f"{parsed.hostname}{port}"
|
||||
|
||||
extensions = {'sni_hostname': parsed.hostname} if parsed.scheme == 'https' else {}
|
||||
return client.build_request(
|
||||
method, pinned_url, headers={**headers, 'Host': host_header},
|
||||
extensions=extensions, **kwargs,
|
||||
)
|
||||
|
||||
|
||||
def safe_post(url: str, data: dict, headers: dict, timeout: float = TIMEOUT) -> httpx.Response:
|
||||
"""
|
||||
POST form data to a checked, pinned address. Redirects are not followed.
|
||||
|
||||
Raises:
|
||||
SSRFBlockedError, ValueError: URL is not allowed
|
||||
httpx.HTTPError: Network errors
|
||||
"""
|
||||
with httpx.Client(follow_redirects=False, transport=TRANSPORT, timeout=timeout) as client:
|
||||
response = client.send(_pinned_request(client, 'POST', url, headers, data=data))
|
||||
response.read()
|
||||
return response
|
||||
|
||||
|
||||
@dataclass
|
||||
class FetchResult:
|
||||
"""A fetched response, after redirects"""
|
||||
@@ -169,12 +212,13 @@ def safe_get(url: str, headers: dict, max_bytes: int = MAX_BYTES,
|
||||
|
||||
with httpx.Client(follow_redirects=False, transport=TRANSPORT) as client:
|
||||
for _ in range(max_redirects + 1):
|
||||
validate_url_for_fetch(url)
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise httpx.TimeoutException("Fetch exceeded time limit")
|
||||
|
||||
with client.stream('GET', url, headers=headers, timeout=remaining) as response:
|
||||
request = _pinned_request(client, 'GET', url, headers, timeout=remaining)
|
||||
response = client.send(request, stream=True)
|
||||
try:
|
||||
location = response.headers.get('Location')
|
||||
if response.is_redirect and location:
|
||||
url = urljoin(url, location)
|
||||
@@ -199,5 +243,7 @@ def safe_get(url: str, headers: dict, max_bytes: int = MAX_BYTES,
|
||||
content=content,
|
||||
encoding=response.charset_encoding or 'utf-8',
|
||||
)
|
||||
finally:
|
||||
response.close()
|
||||
|
||||
raise httpx.TooManyRedirects(f"More than {max_redirects} redirects")
|
||||
Reference in new issue
Block a user