Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Fix SSRF DNS rebinding in the product-photo fetch (GHSA-7rwc-pg49-r48w)

Omega (QA)28423fa5031b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6fa7b8a..b770445 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
## 1.0.8 - Unreleased
+- **Product photo fetch pins the connection to the validated address (GHSA-7rwc-pg49-r48w):** the photo-by-URL fetch used to validate a hostname and then let the HTTP client resolve it again at connect time, so a DNS answer that changed between the two lookups could steer the connection to a private address the guard never saw. The fetch now resolves each hop hostname exactly once, validates every returned address, and connects to the first public one, with no second lookup and no failover. For https the connection still presents the original hostname as SNI and verifies the certificate against it, and the Host header still carries the original hostname. The fetch also no longer follows environment proxy settings, since a proxy would resolve the hostname itself.
+ - _Files: `backend/warranties_routes.py`, `tests/test_photo_url.py`_
+
- **Security and Python dependency updates (#295):** Apprise moves from 2.2.0 to 2.3.0, carrying upstream security fix GHSA-rmjg-h4cf-m74j along with OAuth token redaction in debug logs, slow-attachment timeout protection, and new notification services. Authlib moves from 1.9.5 to 1.9.10 (five patch releases for the OIDC client stack), and `email-validator` moves from 2.3.0 to 2.4.0 (enforcing IDNA Bidi rules, rejecting overlong IDN domains before encoding, and fixing quoted local-part normalization).
- _Files: `backend/requirements.txt`_
- **Docker base image and BuildKit syntax refreshed (#290, #296):** the pinned `python:3.15-slim-trixie` base image digest was refreshed in both Dockerfile stages to pick up upstream Python and Debian Trixie security updates, and the BuildKit Dockerfile syntax moves from 1.28.0 to 1.29.0.
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index 09a2396..10a7b0d 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -197,26 +197,87 @@ def _ip_address_is_public(addr):
return addr.is_global
-def _photo_url_host_is_public(hostname):
- """SSRF guard for photo-by-URL: every address the host resolves to must
- be a public (global) IP. Skipped only when the deployment explicitly sets
- ALLOW_PRIVATE_PHOTO_URLS (used by the test suite with a local server)."""
- if current_app.config.get('ALLOW_PRIVATE_PHOTO_URLS'):
- return True
- try:
- infos = socket.getaddrinfo(hostname, None)
- except Exception:
- return False
- if not infos:
- return False
- for info in infos:
+class _PhotoHostRejectedError(Exception):
+ """A photo URL host failed SSRF validation inside the transport
+ adapter. Deliberately not a ValueError: requests converts a
+ ValueError raised while building pool keys into InvalidURL,
+ which would change the user-facing error message, so the fetch
+ loop catches this type and raises the usual ValueError itself."""
+
+
+class _PinnedPhotoAdapter(requests.adapters.HTTPAdapter):
+ """Transport adapter for the product-photo fetch (SSRF-01).
+
+ The old guard resolved the hostname, checked the addresses, and
+ then let requests resolve the hostname again at connect time, so
+ a DNS answer that changed between the two lookups could steer
+ the connection to an address the guard never saw. This adapter
+ resolves each hop hostname exactly once with socket.getaddrinfo,
+ requires every returned address to be public (unless the
+ deployment sets ALLOW_PRIVATE_PHOTO_URLS), and connects to the
+ first public address. The validated address is the connected
+ address. There is no failover: a failed connect is a fetch
+ failure, never a fresh lookup.
+ """
+
+ def __init__(self, allow_private=False, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._allow_private = allow_private
+
+ def _resolve_and_pin(self, hostname):
+ """One resolve-validate-pin cycle for a hop hostname.
+ Returns the IP string to connect to."""
try:
- addr = ipaddress.ip_address(info[4][0])
- except ValueError:
- return False
- if not _ip_address_is_public(addr):
- return False
- return True
+ infos = socket.getaddrinfo(hostname, None)
+ except Exception:
+ raise _PhotoHostRejectedError(hostname)
+ if not infos:
+ raise _PhotoHostRejectedError(hostname)
+ pinned = None
+ for info in infos:
+ try:
+ addr = ipaddress.ip_address(info[4][0])
+ except ValueError:
+ raise _PhotoHostRejectedError(hostname)
+ if not self._allow_private and not _ip_address_is_public(addr):
+ raise _PhotoHostRejectedError(hostname)
+ if pinned is None:
+ pinned = info[4][0]
+ return pinned
+
+ def build_connection_pool_key_attributes(self, request, verify,
+ cert=None):
+ parsed = urllib.parse.urlparse(request.url)
+ hostname = parsed.hostname
+ if not hostname:
+ raise _PhotoHostRejectedError(hostname)
+ pinned = self._resolve_and_pin(hostname)
+ host_params, pool_kwargs = super().build_connection_pool_key_attributes(
+ request, verify, cert)
+ host_params["host"] = pinned
+ if parsed.scheme == "https":
+ # The pool is keyed by the pinned IP, so without these the
+ # connection would present the IP as SNI and verify the
+ # certificate against it. The pool key also carries both
+ # values, so two hostnames pinned to one IP never share a
+ # pool.
+ pool_kwargs["server_hostname"] = hostname
+ pool_kwargs["assert_hostname"] = hostname
+ return host_params, pool_kwargs
+
+ def add_headers(self, request, **kwargs):
+ parsed = urllib.parse.urlparse(request.url)
+ hostname = parsed.hostname
+ if hostname:
+ host = hostname
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ port = parsed.port
+ default = {"http": 80, "https": 443}.get(parsed.scheme)
+ if port is not None and port != default:
+ host = f"{host}:{port}"
+ request.headers["Host"] = host
+
def _detect_image_extension(data):
"""Magic-byte image sniffing (the upload path checks extensions only;
@@ -264,66 +325,81 @@ def download_product_photo(url):
# one chunk every few seconds hold a fetch open indefinitely.
total_timeout = current_app.config.get('PHOTO_FETCH_TIMEOUT_SECONDS') or 60
deadline = time.monotonic() + total_timeout
- for _ in range(4):
- parsed = urllib.parse.urlparse(current)
- if parsed.scheme not in ('http', 'https') or not parsed.hostname:
- raise ValueError("Photo URL must be a valid http(s) URL.")
- if not _photo_url_host_is_public(parsed.hostname):
- raise ValueError("Photo URL must point to a public address.")
- if time.monotonic() >= deadline:
- raise ValueError("Timed out fetching the photo URL.")
- try:
- resp = requests.get(current, timeout=min(10, deadline - time.monotonic()),
- stream=True, allow_redirects=False,
- headers={'User-Agent': 'Warracker photo fetch'})
- except requests.RequestException:
- raise ValueError("Could not fetch the photo URL.")
- if resp.status_code in (301, 302, 303, 307, 308):
- location = resp.headers.get('Location')
- resp.close()
- if not location:
+ # One session for the whole fetch (redirect hops included), with the
+ # pinning adapter mounted. The session is fresh per fetch, so no
+ # pool is ever shared with another fetch or hostname.
+ session = requests.Session()
+ # Never route the fetch through an environment proxy: a proxy
+ # would resolve the hostname itself, which is a second DNS lookup
+ # the pinning exists to prevent.
+ session.trust_env = False
+ adapter = _PinnedPhotoAdapter(
+ allow_private=bool(current_app.config.get('ALLOW_PRIVATE_PHOTO_URLS')))
+ session.mount('http://', adapter)
+ session.mount('https://', adapter)
+ try:
+ for _ in range(4):
+ parsed = urllib.parse.urlparse(current)
+ if parsed.scheme not in ('http', 'https') or not parsed.hostname:
+ raise ValueError("Photo URL must be a valid http(s) URL.")
+ if time.monotonic() >= deadline:
+ raise ValueError("Timed out fetching the photo URL.")
+ try:
+ resp = session.get(current, timeout=min(10, deadline - time.monotonic()),
+ stream=True, allow_redirects=False,
+ headers={'User-Agent': 'Warracker photo fetch'})
+ except _PhotoHostRejectedError:
+ raise ValueError("Photo URL must point to a public address.")
+ except requests.RequestException:
raise ValueError("Could not fetch the photo URL.")
- current = urllib.parse.urljoin(current, location)
- continue
- if resp.status_code != 200:
- resp.close()
- raise ValueError("Could not fetch the photo URL.")
- chunks, total = [], 0
- # A per-chunk deadline check alone does not bound a slow drip:
- # a read for a full chunk blocks until the chunk fills or the
- # connection closes, so the check may never run. A timer shuts
- # the socket down at the deadline, which unblocks the read;
- # the post-loop check then turns a shutdown-caused end of
- # stream into the timeout error instead of accepting bytes
- # that arrived after the deadline.
- timer = threading.Timer(
- max(0.0, deadline - time.monotonic()),
- _interrupt_photo_fetch, args=(resp,))
- timer.daemon = True
- timer.start()
- try:
- for chunk in resp.iter_content(chunk_size=65536):
+ if resp.status_code in (301, 302, 303, 307, 308):
+ location = resp.headers.get('Location')
+ resp.close()
+ if not location:
+ raise ValueError("Could not fetch the photo URL.")
+ current = urllib.parse.urljoin(current, location)
+ continue
+ if resp.status_code != 200:
+ resp.close()
+ raise ValueError("Could not fetch the photo URL.")
+ chunks, total = [], 0
+ # A per-chunk deadline check alone does not bound a slow drip:
+ # a read for a full chunk blocks until the chunk fills or the
+ # connection closes, so the check may never run. A timer shuts
+ # the socket down at the deadline, which unblocks the read;
+ # the post-loop check then turns a shutdown-caused end of
+ # stream into the timeout error instead of accepting bytes
+ # that arrived after the deadline.
+ timer = threading.Timer(
+ max(0.0, deadline - time.monotonic()),
+ _interrupt_photo_fetch, args=(resp,))
+ timer.daemon = True
+ timer.start()
+ try:
+ for chunk in resp.iter_content(chunk_size=65536):
+ if time.monotonic() >= deadline:
+ raise ValueError("Timed out fetching the photo URL.")
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError("Photo URL file is too large.")
+ chunks.append(chunk)
+ except requests.RequestException:
if time.monotonic() >= deadline:
raise ValueError("Timed out fetching the photo URL.")
- total += len(chunk)
- if total > max_bytes:
- raise ValueError("Photo URL file is too large.")
- chunks.append(chunk)
- except requests.RequestException:
+ raise ValueError("Could not fetch the photo URL.")
+ finally:
+ timer.cancel()
+ resp.close()
if time.monotonic() >= deadline:
raise ValueError("Timed out fetching the photo URL.")
- raise ValueError("Could not fetch the photo URL.")
- finally:
- timer.cancel()
- resp.close()
- if time.monotonic() >= deadline:
- raise ValueError("Timed out fetching the photo URL.")
- data = b''.join(chunks)
- ext = _detect_image_extension(data)
- if not ext:
- raise ValueError("Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)")
- return data, ext
- raise ValueError("Too many redirects fetching the photo URL.")
+ data = b''.join(chunks)
+ ext = _detect_image_extension(data)
+ if not ext:
+ raise ValueError("Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)")
+ return data, ext
+ raise ValueError("Too many redirects fetching the photo URL.")
+ finally:
+ session.close()
# Map of currency symbols to ISO codes (mirrors frontend js/lib/currency.js).
# Used to resolve a user's preferred currency symbol to a code for new warranties.
diff --git a/tests/test_photo_url.py b/tests/test_photo_url.py
index 8bf7827..24fd7f7 100644
--- a/tests/test_photo_url.py
+++ b/tests/test_photo_url.py
@@ -7,6 +7,7 @@ one test turns the guard back on to prove it bites.
"""
import base64
import os
+import socket
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -265,6 +266,265 @@ def test_photo_fetch_timeout_env_var(monkeypatch):
assert probe_app.config["PHOTO_FETCH_TIMEOUT_SECONDS"] == 12.0
+# --- SSRF-01: DNS rebinding (GHSA-7rwc-pg49-r48w) ---
+
+class _RebindingHandler(BaseHTTPRequestHandler):
+ """Canary server. Records every hit and the Host headers it saw,
+ serves the photo, and redirects /redir at an absolute hop2 URL."""
+ hits = []
+ hosts_seen = []
+ hop2_url = None
+
+ def do_GET(self):
+ type(self).hits.append(self.path)
+ type(self).hosts_seen.append(self.headers.get_all("Host"))
+ if self.path == "/photo.png":
+ body = PNG_BYTES
+ self.send_response(200)
+ self.send_header("Content-Type", "image/png")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ elif self.path == "/redir":
+ self.send_response(302)
+ self.send_header("Location", type(self).hop2_url)
+ self.end_headers()
+ else:
+ self.send_response(404)
+ self.end_headers()
+
+ def log_message(self, *args):
+ pass
+
+
+def _start_canary():
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _RebindingHandler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ return server
+
+
+def _scripted_resolver(real_getaddrinfo, script):
+ """getaddrinfo fake for the rebinding tests.
+
+ script maps a hostname to (validation_ip, connect_ip). The adapter
+ resolves with port=None, like the old guard did; the connector
+ resolves with the URL port. A rebinding answer gives the public
+ address to the validation call and the canary to the connect call,
+ which is exactly the advisory scenario.
+ """
+ calls = []
+
+ def fake(host, port, *args, **kwargs):
+ calls.append((host, port))
+ if host in script:
+ first_ip, later_ip = script[host]
+ ip = first_ip if port is None else later_ip
+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "",
+ (ip, port or 80))]
+ return real_getaddrinfo(host, port, *args, **kwargs)
+
+ fake.calls = calls
+ return fake
+
+
+def test_rebinding_flip_is_rejected(monkeypatch, app):
+ """The advisory scenario: the guard sees a public address, the
+ connect would see the canary. The fetch must fail and the canary
+ must receive nothing, with exactly one resolution for the host."""
+ import socket
+ from backend.warranties_routes import download_product_photo
+ server = _start_canary()
+ port = server.server_address[1]
+ _RebindingHandler.hits = []
+ _RebindingHandler.hosts_seen = []
+ real_getaddrinfo = socket.getaddrinfo
+ fake = _scripted_resolver(real_getaddrinfo, {
+ "rebind.example.invalid": ("8.8.8.8", "127.0.0.1"),
+ })
+ monkeypatch.setattr(socket, "getaddrinfo", fake)
+ # Keep the fetch off any environment proxy so the test exercises
+ # the direct connect path in every environment, including this
+ # one, where a proxy would otherwise answer for the fake host.
+ monkeypatch.setenv(
+ "no_proxy",
+ os.environ.get("no_proxy", "") + ",rebind.example.invalid")
+ previous_timeout = app.config.get("PHOTO_FETCH_TIMEOUT_SECONDS")
+ try:
+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = False
+ app.config["PHOTO_FETCH_TIMEOUT_SECONDS"] = 5
+ with app.app_context():
+ with pytest.raises(ValueError, match="Could not fetch"):
+ download_product_photo(
+ f"http://rebind.example.invalid:{port}/photo.png")
+ finally:
+ if previous_timeout is None:
+ app.config.pop("PHOTO_FETCH_TIMEOUT_SECONDS", None)
+ else:
+ app.config["PHOTO_FETCH_TIMEOUT_SECONDS"] = previous_timeout
+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = False
+ server.shutdown()
+ assert _RebindingHandler.hits == []
+ host_calls = [c for c in fake.calls
+ if c[0] == "rebind.example.invalid"]
+ assert len(host_calls) == 1 and host_calls[0][1] is None
+
+
+def test_redirect_hop_rebinding_is_rejected(monkeypatch, app):
+ """Same flip on the second hop: hop1 reaches the canary and
+ redirects, hop2 must fail closed without the canary serving the
+ photo. ALLOW_PRIVATE is on so hop1 can legitimately point at the
+ canary; the adapter still pins hop2 to its one resolved address."""
+ import socket
+ from backend.warranties_routes import download_product_photo
+ server = _start_canary()
+ port = server.server_address[1]
+ _RebindingHandler.hits = []
+ _RebindingHandler.hosts_seen = []
+ _RebindingHandler.hop2_url = f"http://hop2.example.invalid:{port}/photo.png"
+ real_getaddrinfo = socket.getaddrinfo
+ fake = _scripted_resolver(real_getaddrinfo, {
+ "hop1.example.invalid": ("127.0.0.1", "127.0.0.1"),
+ "hop2.example.invalid": ("8.8.8.8", "127.0.0.1"),
+ })
+ monkeypatch.setattr(socket, "getaddrinfo", fake)
+ # Keep the fetch off any environment proxy, as in the main
+ # rebinding test.
+ monkeypatch.setenv(
+ "no_proxy",
+ os.environ.get("no_proxy", "")
+ + ",hop1.example.invalid,hop2.example.invalid")
+ previous_timeout = app.config.get("PHOTO_FETCH_TIMEOUT_SECONDS")
+ try:
+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = True
+ app.config["PHOTO_FETCH_TIMEOUT_SECONDS"] = 5
+ with app.app_context():
+ with pytest.raises(ValueError, match="Could not fetch"):
+ download_product_photo(
+ f"http://hop1.example.invalid:{port}/redir")
+ finally:
+ if previous_timeout is None:
+ app.config.pop("PHOTO_FETCH_TIMEOUT_SECONDS", None)
+ else:
+ app.config["PHOTO_FETCH_TIMEOUT_SECONDS"] = previous_timeout
+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = False
+ server.shutdown()
+ assert _RebindingHandler.hits == ["/redir"]
+ hop2_calls = [c for c in fake.calls if c[0] == "hop2.example.invalid"]
+ assert len(hop2_calls) == 1 and hop2_calls[0][1] is None
+
+
+def test_host_with_any_private_address_is_rejected(monkeypatch, app):
+ """One private address among public answers rejects the host,
+ whichever order the answers arrive in."""
+ import socket
+ from backend.warranties_routes import download_product_photo
+ real_getaddrinfo = socket.getaddrinfo
+
+ def fake(host, port, *args, **kwargs):
+ if host == "multi-a.example.invalid":
+ answers = ["8.8.8.8", "10.0.0.1"]
+ elif host == "multi-b.example.invalid":
+ answers = ["10.0.0.1", "8.8.8.8"]
+ else:
+ return real_getaddrinfo(host, port, *args, **kwargs)
+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "",
+ (ip, port or 80)) for ip in answers]
+
+ monkeypatch.setattr(socket, "getaddrinfo", fake)
+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = False
+ with app.app_context():
+ with pytest.raises(ValueError, match="public address"):
+ download_product_photo("http://multi-a.example.invalid/photo.png")
+ with pytest.raises(ValueError, match="public address"):
+ download_product_photo("http://multi-b.example.invalid/photo.png")
+
+
+def test_pinned_pool_uses_original_hostname_for_tls(monkeypatch):
+ """Two hostnames pinned to one IP must never share a pool, and
+ each pool must carry its own hostname as SNI and as the
+ certificate check name. No live TLS server is involved; the
+ pool object itself is inspected."""
+ import socket
+ from requests import Request
+ from backend.warranties_routes import _PinnedPhotoAdapter
+ real_getaddrinfo = socket.getaddrinfo
+
+ def fake(host, port, *args, **kwargs):
+ if host in ("host-a.example.invalid", "host-b.example.invalid"):
+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "",
+ ("93.184.216.34", port or 443))]
+ return real_getaddrinfo(host, port, *args, **kwargs)
+
+ monkeypatch.setattr(socket, "getaddrinfo", fake)
+ adapter = _PinnedPhotoAdapter(allow_private=False)
+ req_a = Request("GET", "https://host-a.example.invalid/photo.png").prepare()
+ pool_a = adapter.get_connection_with_tls_context(req_a, True)
+ assert pool_a.host == "93.184.216.34"
+ assert pool_a.conn_kw["server_hostname"] == "host-a.example.invalid"
+ assert pool_a.assert_hostname == "host-a.example.invalid"
+ req_b = Request("GET", "https://host-b.example.invalid/photo.png").prepare()
+ pool_b = adapter.get_connection_with_tls_context(req_b, True)
+ assert pool_b is not pool_a
+ assert pool_b.host == "93.184.216.34"
+ assert pool_b.conn_kw["server_hostname"] == "host-b.example.invalid"
+ assert pool_b.assert_hostname == "host-b.example.invalid"
+
+
+def test_host_header_formatting():
+ """The Host header carries the original hostname, with a
+ non-default port when present, and no port for default ports."""
+ from requests import Request
+ from backend.warranties_routes import _PinnedPhotoAdapter
+ adapter = _PinnedPhotoAdapter()
+ req = Request("GET", "http://photos.example.invalid:8080/photo.png").prepare()
+ adapter.add_headers(req)
+ assert req.headers["Host"] == "photos.example.invalid:8080"
+ req = Request("GET", "https://photos.example.invalid/photo.png").prepare()
+ adapter.add_headers(req)
+ assert req.headers["Host"] == "photos.example.invalid"
+ req = Request("GET", "http://photos.example.invalid/photo.png").prepare()
+ adapter.add_headers(req)
+ assert req.headers["Host"] == "photos.example.invalid"
+
+
+def test_host_header_sent_is_original_hostname(monkeypatch, app):
+ """End to end over http: the canary is reached at its pinned IP,
+ but the one Host header it sees is the original hostname."""
+ import socket
+ from backend.warranties_routes import download_product_photo
+ server = _start_canary()
+ port = server.server_address[1]
+ _RebindingHandler.hits = []
+ _RebindingHandler.hosts_seen = []
+ real_getaddrinfo = socket.getaddrinfo
+
+ def fake(host, port_, *args, **kwargs):
+ if host == "host-a.example.invalid":
+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "",
+ ("127.0.0.1", port_ or 80))]
+ return real_getaddrinfo(host, port_, *args, **kwargs)
+
+ monkeypatch.setattr(socket, "getaddrinfo", fake)
+ # Keep the fetch off any environment proxy, as in the rebinding
+ # tests.
+ monkeypatch.setenv(
+ "no_proxy",
+ os.environ.get("no_proxy", "") + ",host-a.example.invalid")
+ try:
+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = True
+ with app.app_context():
+ data, ext = download_product_photo(
+ f"http://host-a.example.invalid:{port}/photo.png")
+ assert ext == ".png" and data == PNG_BYTES
+ finally:
+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = False
+ server.shutdown()
+ assert _RebindingHandler.hits == ["/photo.png"]
+ assert _RebindingHandler.hosts_seen == [
+ [f"host-a.example.invalid:{port}"]]
+
+
def test_photo_fetch_timeout_env_var_enforced_end_to_end(monkeypatch):
import time
from flask import Flask