Pin feed connections to the address that was validated (R2-S2, #34)

The SSRF guard checked that a hostname resolved to public addresses,
then let requests resolve it again to connect — so a DNS answer that
changed in between (DNS rebinding) could point the connection at an
internal address.

Connections now go through a pinned adapter whose socket factory
resolves, checks and connects inside one function: whatever the name
resolves to at connect time is what gets validated and used. Only the
socket is replaced, so TLS still verifies against the original
hostname. The up-front validate_fetch_url check stays as defense in
depth. Tests cover a rebinding answer at connect time being refused and
a real loopback round trip with the original Host header preserved;
checked live: a real HTTPS feed fetches, 127.0.0.1/169.254.169.254/
localhost are blocked, and a wrong-hostname certificate is still
rejected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5.5 committed 2026-11-01 12:00:03 -07:00
1 parent 10ba491e10
commit 2e1c0e31a8
2 files changed
+163 -10

No files matched your search

+71
View File
@@ -136,3 +136,74 @@ class TestSafeGet:
)
response = safe_get("https://example.com/feed.xml", headers={}, timeout=5)
assert response.headers.get("ETag") == "abc123"
class TestConnectionPinning:
"""R2-S2: the address that's validated is the address that's connected
to — a hostname that resolves differently at connect time can't slip an
internal address past a pre-check."""
def test_a_rebinding_dns_answer_at_connect_time_is_blocked(self, monkeypatch):
import socket
calls = []
def rebinding_getaddrinfo(host, *args, **kwargs):
calls.append(host)
ip = "93.184.216.34" if len(calls) == 1 else "127.0.0.1"
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, 0))]
monkeypatch.setattr(socket, "getaddrinfo", rebinding_getaddrinfo)
# The up-front check sees the public answer...
validate_fetch_url("http://rebind.example.com/feed.xml")
# ...but the connection's own lookup gets the internal one and must refuse.
with pytest.raises(SSRFBlocked, match="non-public"):
safe_get("http://rebind.example.com/feed.xml", headers={}, timeout=2)
def test_connects_to_the_validated_address_and_keeps_the_original_host_header(
self, monkeypatch
):
import socket
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from apps.feeds.services import ssrf_guard
seen = {}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
seen["host"] = self.headers["Host"]
body = b"<rss/>"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.handle_request, daemon=True).start()
real_getaddrinfo = socket.getaddrinfo
monkeypatch.setattr(
socket,
"getaddrinfo",
lambda host, *a, **k: (
[(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))]
if host == "feed.test"
else real_getaddrinfo(host, *a, **k)
),
)
# Allow loopback for this test only, standing in for a public address.
monkeypatch.setattr(ssrf_guard, "_is_allowed_ip", lambda ip: True)
response = safe_get(f"http://feed.test:{port}/feed.xml", headers={}, timeout=5)
server.server_close()
assert response.status_code == 200
assert response.content == b"<rss/>"
assert seen["host"] == f"feed.test:{port}"