Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(security): validate destination hosts with the shared SSRF validator (#93589)

Ross70519cabe7d3
diff --git a/posthog/models/integration/postgres.py b/posthog/models/integration/postgres.py
index 1c1b2258e840..81627719638e 100644
--- a/posthog/models/integration/postgres.py
+++ b/posthog/models/integration/postgres.py
@@ -3,7 +3,12 @@
from typing import ClassVar, Literal, NamedTuple
from posthog.models.user import User
-from posthog.security.url_validation import resolve_and_validate_host
+from posthog.security.url_validation import (
+ INVALID_HOST_MESSAGE,
+ UNREACHABLE_HOST_MESSAGE,
+ ShapeError,
+ validate_external_host,
+)
from . import common, model
@@ -78,9 +83,11 @@ class PostgreSQLServerIntegration:
) -> model.Integration:
host = common._return_non_empty_str_from_config(config, "host", friendly_name="Host", kind=cls.integration_kind)
try:
- resolve_and_validate_host(host)
+ validate_external_host(host)
+ except ShapeError:
+ raise common.IntegrationError(INVALID_HOST_MESSAGE)
except ValueError:
- raise common.IntegrationError(f"Provided host '{host}' is not valid")
+ raise common.IntegrationError(UNREACHABLE_HOST_MESSAGE)
port = config.get("port", None)
try:
diff --git a/posthog/security/test/test_url_validation.py b/posthog/security/test/test_url_validation.py
index b74670ad6450..38ceb23bfe77 100644
--- a/posthog/security/test/test_url_validation.py
+++ b/posthog/security/test/test_url_validation.py
@@ -13,6 +13,13 @@ def force_prod(monkeypatch):
monkeypatch.setattr(uv, "is_dev_mode", lambda: False)
+def enforce_destination_validation(settings):
+ # By default, we bypass URL and host validation in tests. We want to test the validation
+ # logic, so we opt back in.
+ settings.FORCE_URL_VALIDATION = True
+
+
class TestUrlValidation:
def test_resolve_host_ips_uses_bounded_lifetime(self, monkeypatch):
class Answers:
@@ -29,6 +36,27 @@ class TestUrlValidation:
assert uv.resolve_host_ips("example.com") == {ipaddress.ip_address("93.184.216.34")}
+ def test_resolve_host_ips_resolves_an_idn_host_but_not_a_url(self, monkeypatch):
+ # Every other test replaces resolve_host_ips itself, so nothing else runs a real host
+ # string through its shape gate. The gate has to admit an internationalized name, whose
+ # punycode form is a hostname, while still keeping a URL away from the resolver.
+ queried: list[str] = []
+
+ class Answers:
+ def addresses(self):
+ return iter(["93.184.216.34"])
+
+ class Resolver:
+ def resolve_name(self, host, *, lifetime):
+ queried.append(host)
+ return Answers()
+
+ monkeypatch.setattr(uv.dns.resolver, "Resolver", Resolver)
+
+ assert uv.resolve_host_ips("münchen.de") == {ipaddress.ip_address("93.184.216.34")}
+ assert uv.resolve_host_ips("postgresql://db.example.com:5432/analytics") == set()
+ assert queried == ["münchen.de"]
+
def test_resolve_url_hosts_ips_deduplicates_hosts(self, monkeypatch):
def fake_resolve_hosts_ips(hosts):
assert hosts == {"shared.example.com"}
@@ -84,9 +112,17 @@ class TestUrlValidation:
assert uv.resolve_hosts_ips({"busy.example.com"}) == {"busy.example.com": set()}
- def test_is_url_allowed_disallowed_scheme(self):
- ok, err = uv.is_url_allowed("javascript:alert(1)")
- assert not ok and "scheme" in (err or "")
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "javascript:alert(1)",
+ "not-a-url",
+ ],
+ )
+ def test_is_url_allowed_rejects_anything_that_is_not_http(self, url):
+ ok, err = uv.is_url_allowed(url)
+ assert not ok
+ assert "must start with http" in (err or "")
def test_is_url_allowed_localhost(self):
ok, err = uv.is_url_allowed("http://localhost")
@@ -118,6 +154,147 @@ class TestUrlValidation:
ok, err = uv.is_url_allowed("http://localhost")
assert ok and err is None
+ @pytest.mark.parametrize(
+ "resolved_ips, expected_error",
+ [
+ # An internal IP and a host that does not resolve report the same thing on purpose,
+ # so the error cannot be used to find which addresses exist inside our network.
+ ({ipaddress.ip_address("10.0.0.1")}, "does not resolve to a valid IP address"),
+ (set(), "does not resolve to a valid IP address"),
+ ({ipaddress.ip_address("93.184.216.34")}, None),
+ ],
+ )
+ def test_validate_external_host_enforced(
+ self, monkeypatch, enforce_destination_validation, resolved_ips, expected_error
+ ):
+ # This path resolves and judges IPs itself rather than calling is_url_allowed, so the
+ # cases above do not cover it. A host that resolves to no IPs is rejected, because
+ # there is then nothing to judge it by.
+ monkeypatch.setattr(uv, "resolve_host_ips", lambda host: resolved_ips)
+ if expected_error is None:
+ uv.validate_external_host("db.example.com")
+ else:
+ with pytest.raises(ValueError, match=expected_error):
+ uv.validate_external_host("db.example.com")
+
+ @pytest.mark.parametrize(
+ "url, resolved_ip, should_raise",
+ [
+ ("http://127.0.0.1", None, True),
+ ("https://example.com", "93.184.216.34", False),
+ ],
+ )
+ def test_validate_external_url_enforced(
+ self, monkeypatch, enforce_destination_validation, url, resolved_ip, should_raise
+ ):
+ # This path takes its rules from is_url_allowed, so what is under test is the
+ # translation of its verdict: a blocked one has to raise, an allowed one has to return.
+ if resolved_ip is not None:
+ monkeypatch.setattr(uv, "resolve_host_ips", lambda host: {ipaddress.ip_address(resolved_ip)})
+ if should_raise:
+ with pytest.raises(ValueError):
+ uv.validate_external_url(url)
+ else:
+ uv.validate_external_url(url)
+
+ @pytest.mark.parametrize(
+ "dev_mode, test_mode, force, bypassed",
+ [
+ (True, False, False, True), # local dev
+ (False, True, False, True), # in tests
+ (False, True, True, False), # override using FORCE_URL_VALIDATION
+ (False, False, False, False), # production
+ ],
+ )
+ def test_validate_external_url_and_host_bypass_validation_only_in_dev_and_test(
+ self, monkeypatch, settings, dev_mode, test_mode, force, bypassed
+ ):
+ monkeypatch.setattr(uv, "is_dev_mode", lambda: dev_mode)
+ settings.TEST = test_mode
+ settings.FORCE_URL_VALIDATION = force
+
+ if bypassed:
+ uv.validate_external_host("10.0.0.1")
+ uv.validate_external_url("http://localhost:9000")
+ else:
+ with pytest.raises(ValueError):
+ uv.validate_external_host("10.0.0.1")
+ with pytest.raises(ValueError):
+ uv.validate_external_url("http://localhost:9000")
+
+ @pytest.mark.parametrize(
+ "host, expected_reason",
+ [
+ ("db.corp", "Internal domain pattern blocked"), # the suffix loop
+ ("metadata.google.internal", "Local/metadata host"), # exact match, a separate branch
+ # The suffix match is case sensitive, and canonicalization lowercases first.
+ ("DB.CORP", "Internal domain pattern blocked"),
+ ("db.corp.", "Internal domain pattern blocked"), # a root dot must not hide a suffix
+ ("localhost.", "Local/Loopback host not allowed"), # nor an exact match
+ # The whole of 127.0.0.0/8 is loopback, not just 127.0.0.1. Caught by parsing the
+ # address, so no DNS lookup happens and every long form is caught the same way.
+ ("127.0.0.2", "Private IP address not allowed"),
+ # IDNA maps fullwidth characters onto ASCII ones, so this is the resolver's
+ # "evil.corp". The name checks have to see the form the resolver will query.
+ ("evil.corp", "Internal domain pattern blocked"),
+ ("localhost", "Local/Loopback host not allowed"),
+ ],
+ )
+ def test_host_and_url_paths_agree_on_internal_names(self, enforce_destination_validation, host, expected_reason):
+ with pytest.raises(ValueError, match=expected_reason):
+ uv.validate_external_host(host)
+ allowed, reason = uv.is_url_allowed(f"https://{host}")
+ assert not allowed
+ assert expected_reason in (reason or "")
+
+ @pytest.mark.parametrize(
+ "validate, value",
+ [
+ (uv.validate_external_url, "not-a-url"),
+ (uv.validate_external_url, "javascript:alert(1)"),
+ (uv.validate_external_url, "ftp://internal"),
+ (uv.validate_external_url, "https://"),
+ (uv.validate_external_host, ""),
+ (uv.validate_external_host, " "),
+ ],
+ )
+ def test_malformed_target_is_rejected_even_where_validation_is_bypassed(self, validate, value):
+ # No enforce_destination_validation here on purpose; the form of a target does not
+ # depend on the environment.
+ with pytest.raises(ValueError):
+ validate(value)
+
+ @pytest.mark.parametrize(
+ "host, usable",
+ [
+ ("db.example.com", True),
+ ("8.8.8.8", True),
+ # A bare IPv6 literal is a host, and its colons are not a path. It has to be a
+ # globally routable one, because the name check rejects every internal address.
+ ("2606:4700:4700::1111", True),
+ ("10.example.com", True), # a name that starts like a private range is still a name
+ ("db.example.com.", True), # the root dot of an absolute FQDN
+ ("db.acme.com:5432", False),
+ ("[email protected]", False),
+ ("http://db.acme.com", False),
+ ],
+ )
+ def test_host_field_takes_a_hostname_or_ip_only(self, enforce_destination_validation, monkeypatch, host, usable):
+ monkeypatch.setattr(uv, "resolve_host_ips", lambda _host: {ipaddress.ip_address("93.184.216.34")})
+ if usable:
+ uv.validate_external_host(host)
+ else:
+ with pytest.raises(ValueError, match="hostname or IP address"):
+ uv.validate_external_host(host)
+
+ @pytest.mark.parametrize("value", [None, 123])
+ def test_non_string_target_is_a_client_error(self, value):
+ # A non-string has to read as bad input rather than surface as a TypeError
+ with pytest.raises(ValueError):
+ uv.validate_external_host(value)
+ with pytest.raises(ValueError):
+ uv.validate_external_url(value)
+
@pytest.mark.parametrize(
"resolved_ip",
[
diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.py
index a965507aea7d..cd2357958044 100644
--- a/posthog/security/url_validation.py
+++ b/posthog/security/url_validation.py
@@ -1,5 +1,4 @@
import re
-import socket
import ipaddress
import urllib.parse as urlparse
from collections.abc import Iterable, Mapping
@@ -36,9 +35,6 @@ _dns_resolution_executor = ThreadPoolExecutor(
)
_dns_resolution_capacity = BoundedSemaphore(DNS_RESOLUTION_MAX_WORKERS)
-# Schemes that should never be allowed for external URLs
-DISALLOWED_SCHEMES = {"file", "ftp", "gopher", "ws", "wss", "data", "javascript"}
-
# Cloud metadata service hosts that should be blocked to prevent SSRF
METADATA_HOSTS = {"169.254.169.254", "metadata.google.internal"}
@@ -64,11 +60,15 @@ INTERNAL_DOMAIN_PATTERNS = (
def resolve_host_ips(host: str) -> ResolvedIPs:
- """Resolve a hostname to its IP addresses."""
- try:
- return {ipaddress.ip_address(host)}
- except ValueError:
- pass
+ """Resolve a canonical hostname to its IP addresses."""
+ ip = _parse_ip_literal(host)
+ if ip is not None:
+ return {ip}
+
+ # dnspython repeats the queried name in its error text, so a value that is not a host
+ # would reach both the message and the host field of the warning below.
+ if _host_shape_error(host) is not None:
+ return set()
try:
answers = dns.resolver.Resolver().resolve_name(host, lifetime=DNS_RESOLUTION_LIFETIME_SECONDS)
@@ -131,6 +131,18 @@ def resolve_hosts_ips(hosts: Iterable[str]) -> dict[str, ResolvedIPs]:
_CGNAT_NETWORK = ipaddress.ip_network("100.64.0.0/10")
+def _parse_ip_literal(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
+ """Parse a host written as an IP address, or None when it is a name."""
+
+ # ``ipaddress.ip_address`` also takes an integer, where 123 becomes 0.0.0.123.
+ if not isinstance(host, str):
+ raise TypeError("host must be a string")
+ try:
+ return ipaddress.ip_address(host)
+ except ValueError:
+ return None
+
+
def _is_internal_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
"""Check if an IP address is internal/private and should be blocked."""
# An IPv4-mapped IPv6 address (::ffff:a.b.c.d) reaches the IPv4 host it embeds, and
@@ -150,29 +162,124 @@ def _is_internal_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
)
-def _is_private_ip_literal(host: str) -> bool:
- """Quick check for RFC1918 and link-local IP literals (avoids DNS lookup)."""
- return (
- host.startswith("10.")
- or host.startswith("192.168.")
- or host.startswith("169.254.")
- or host.startswith("172.16.")
- or host.startswith("172.17.")
- or host.startswith("172.18.")
- or host.startswith("172.19.")
- or host.startswith("172.20.")
- or host.startswith("172.21.")
- or host.startswith("172.22.")
- or host.startswith("172.23.")
- or host.startswith("172.24.")
- or host.startswith("172.25.")
- or host.startswith("172.26.")
- or host.startswith("172.27.")
- or host.startswith("172.28.")
- or host.startswith("172.29.")
- or host.startswith("172.30.")
- or host.startswith("172.31.")
- )
+def _is_internal_ip_literal(host: str) -> bool:
+ """True when the host is written as an IP address we must not reach, so DNS is not needed."""
+ ip = _parse_ip_literal(host)
+ return ip is not None and _is_internal_ip(ip)
+
+
+# Labels joined by dots, with an optional root dot. ASCII on purpose, because callers match
+# the punycode form. Underscores are not valid under RFC 1123 but resolve in practice, so the
+# pattern keeps them: the job is to reject the parts of a URL, not to enforce the RFC.
+_HOSTNAME_LABEL = r"[A-Za-z0-9_](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?"
+_BARE_HOSTNAME = re.compile(rf"{_HOSTNAME_LABEL}(?:\.{_HOSTNAME_LABEL})*\.?")
+_MAX_HOSTNAME_LENGTH = 253
+
+
+def _matches_hostname_pattern(host: str) -> bool:
+ return len(host) <= _MAX_HOSTNAME_LENGTH and _BARE_HOSTNAME.fullmatch(host) is not None
+
+
+def _canonicalize_host(host: str) -> str:
+ """The one form every host check runs on.
+
+ We strip any trailing "." because an absolute FQDN carries the DNS root dot ("db.corp.").
+ The block list matches exactly or by suffix, so it would otherwise miss that form.
+
+ An internationalized name becomes the punycode form the resolver queries. IDNA maps some
+ characters onto ASCII ones, so "evil.corp" and "evil.corp" reach the same server. The
+ block list would recognize only the second. A name the codec rejects comes back unchanged,
+ and the shape check refuses it.
+ """
+ try:
+ host = host.encode("idna").decode("ascii")
+ except ValueError: # UnicodeError, which the codec raises, subclasses this
+ pass
+ return host.lower().rstrip(".")
+
+
+def _host_shape_error(host: str) -> str | None:
+ """Reason to reject a host on its form alone, or None when the form is usable.
+
+ A host field takes a hostname or an IP address, so a pasted connection string is rejected
+ before its credentials reach DNS or a log line.
+
+ An IP address is accepted first, because an IPv6 literal carries colons and can never match
+ the hostname pattern. Everything else is judged in canonical form, the one the checks below
+ and the resolver use.
+ """
+ if not host.strip():
+ return "Host is empty"
+ if _parse_ip_literal(host) is not None:
+ return None
+ if not _matches_hostname_pattern(_canonicalize_host(host)):
+ return "Host must be a hostname or IP address"
+ return None
+
+
+def _url_log_fields(raw_url: str) -> dict[str, str]:
+ """Discrete fields for a blocked-URL log line, so a query can group by them.
+
+ The reason string carries no scheme, and an investigation starts from the scheme more
+ often than from anything else. Neither field can hold a credential: ``hostname`` excludes
+ the userinfo, and a scheme is a short token before the colon.
+ """
+ try:
+ parsed = urlparse.urlsplit(raw_url)
+ except ValueError:
+ return {}
+ return {"scheme": parsed.scheme, "host": parsed.hostname or ""}
+
+
+def _url_shape_error(raw_url: str) -> str | None:
+ """Reason to reject a URL on its form alone, or None when the form is usable."""
+ if has_authority_bypass_chars(raw_url):
+ return "Invalid URL: ambiguous authority"
+ try:
+ parsed = urlparse.urlparse(raw_url)
+ except Exception:
+ return "Invalid URL"
+ # The scheme stays out of the message: it is caller-supplied text, and it is empty for
+ # anything urlparse does not read as a URL.
+ if parsed.scheme not in {"http", "https"}:
+ return "URL must start with http:// or https://"
+ if not parsed.netloc:
+ return "Missing host"
+ return None
+
+
+@frozen
+class BlockedName:
+ """Why a host name is blocked, and which internal pattern matched it.
+
+ The pattern travels beside the reason so a log query can group by it. Deriving it again at
+ the log site would mean a second copy of the matching.
+ """
+
+ reason: str
+ pattern: str | None = None
+
+
+def _blocked_host_name(host: str) -> BlockedName | None:
+ """Why to reject a host on its name alone, or None when the name is acceptable.
+
+ These checks run before resolution, so they also catch a name that resolves to a public
+ IP: split-horizon DNS, and a registered domain shaped like an internal one.
+
+ Canonicalizes again although every caller does. Matching below is exact or by suffix, so
+ an un-normalized host would fail it open.
+ """
+ host = _canonicalize_host(host)
+ if host in METADATA_HOSTS:
+ return BlockedName(reason="Local/metadata host")
+ if host in {"localhost", "127.0.0.1", "::1"}:
+ return BlockedName(reason="Local/Loopback host not allowed")
+ for pattern in INTERNAL_DOMAIN_PATTERNS:
+ if host.endswith(pattern):
+ return BlockedName(reason=f"Internal domain pattern blocked: {pattern}", pattern=pattern)
+ if _is_internal_ip_literal(host):
+ return BlockedName(reason="Private IP address not allowed")
+ return None
def has_ambiguous_authority(url: str) -> bool:
@@ -308,17 +415,11 @@ def resolve_url_hosts_ips(raw_urls: Iterable[str]) -> dict[str, ResolvedIPs]:
continue
try:
parsed_url = urlparse.urlparse(raw_url)
- host = (parsed_url.hostname or "").lower()
+ host = _canonicalize_host(parsed_url.hostname or "")
except Exception:
continue
- if (
- parsed_url.scheme not in {"http", "https"}
- or not parsed_url.netloc
- or host in METADATA_HOSTS
- or host in {"localhost", "127.0.0.1", "::1"}
- or any(host.endswith(pattern) for pattern in INTERNAL_DOMAIN_PATTERNS)
- or _is_private_ip_literal(host)
- ):
+ # Skip what the validator will reject anyway. This shares the rule rather than restating it.
+ if parsed_url.scheme not in {"http", "https"} or not parsed_url.netloc or _blocked_host_name(host) is not None:
continue
hosts.add(host)
return resolve_hosts_ips(hosts)
@@ -366,30 +467,14 @@ def _validate_url_with_ips(
logger.warning("url_validation.blocked", reason=reason, **log_kwargs)
return PinnedUrlVerdict(allowed=False, reason=reason, pinned_ips=empty)
- if has_authority_bypass_chars(raw_url):
- return _blocked("Invalid URL: ambiguous authority")
- try:
- u = urlparse.urlparse(raw_url)
- except Exception:
- return _blocked("Invalid URL")
- if u.scheme not in {"http", "https"} or u.scheme in DISALLOWED_SCHEMES:
- return _blocked("Disallowed scheme", scheme=u.scheme)
- if not u.netloc:
- return _blocked("Missing host")
- host = (u.hostname or "").lower()
- if host in METADATA_HOSTS:
- return _blocked("Local/metadata host", host=host)
- if host in {"localhost", "127.0.0.1", "::1"}:
- return _blocked("Local/Loopback host not allowed", host=host)
-
- # Check internal domain patterns
- for pattern in INTERNAL_DOMAIN_PATTERNS:
- if host.endswith(pattern):
- return _blocked(f"Internal domain pattern blocked: {pattern}", host=host, pattern=pattern)
-
- # Quick check for private IP literals (avoids DNS lookup)
- if _is_private_ip_literal(host):
- return _blocked("Private IP address not allowed", host=host)
+ shape_reason = _url_shape_error(raw_url)
+ if shape_reason is not None:
+ return _blocked(shape_reason, **_url_log_fields(raw_url))
+ u = urlparse.urlparse(raw_url)
+ host = _canonicalize_host(u.hostname or "")
+ blocked_name = _blocked_host_name(host)
+ if blocked_name is not None:
+ return _blocked(blocked_name.reason, host=host, pattern=blocked_name.pattern)
ips = resolve_host_ips(host) if resolved_ips_by_host is None else resolved_ips_by_host.get(host, empty)
if not ips:
@@ -410,78 +495,76 @@ def should_block_url(u: str) -> bool:
return not allowed
-# The destination-host check below guards a batch export or warehouse-import target that a
-# customer supplies and our servers later connect to. It duplicates the concern the rest of
-# this module already covers, with its own ranges and its own resolver, and it is kept
-# unchanged here only so the move carries no behavior change. Unifying it with
-# `is_url_allowed` changes what we reject, so that lands separately.
-
-INTERNAL_NETWORKS = (
- ipaddress.ip_network("10.0.0.0/8"),
- ipaddress.ip_network("172.16.0.0/12"),
- ipaddress.ip_network("192.168.0.0/16"),
- ipaddress.ip_network("127.0.0.0/8"),
- ipaddress.ip_network("169.254.0.0/16"),
- ipaddress.ip_network("0.0.0.0/8"),
- ipaddress.ip_network("::1/128"),
- ipaddress.ip_network("fc00::/7"),
- ipaddress.ip_network("fe80::/10"),
-)
+def _test_bypass_enabled() -> bool:
+ return settings.TEST and not settings.FORCE_URL_VALIDATION
-def is_ip_internal(ip: str) -> bool:
- """Check if IP belongs to an internal network."""
- try:
- addr = ipaddress.ip_address(ip)
- except ValueError:
- raise ValueError("Could not parse IP")
+def validate_external_url(url: str) -> None:
+ """Raise ``ValueError`` unless ``url`` is safe for our servers to reach.
- if any(addr in network for network in INTERNAL_NETWORKS):
- return True
- return False
+ SSRF guard for a stored URL a destination later fetches (an S3-compatible endpoint,
+ a webhook). Bypassed in local dev and in tests, unless the
+ ``FORCE_URL_VALIDATION`` setting is true.
+ """
+ # The URL could come from untyped config, so check its type first
+ if not isinstance(url, str):
+ raise ShapeError("URL must be a string")
+ shape_reason = _url_shape_error(url)
+ if shape_reason is not None:
+ raise ShapeError(shape_reason)
-def resolve_and_validate_url(url: str) -> None:
- """Ensure provided url point to a non-internal IP."""
- try:
- parsed = urlparse.urlparse(url)
- except Exception as e:
- raise ValueError(f"Invalid URL'{url}': {e}") from e
+ if _dev_bypass_enabled() or _test_bypass_enabled():
+ return
- host = parsed.hostname
- if not host:
- raise ValueError("URL has no hostname")
+ allowed, reason = is_url_allowed(url)
+ if not allowed:
+ raise ValueError(reason or "URL is not allowed")
- resolve_and_validate_host(host)
+class ShapeError(ValueError):
+ """The value cannot be a host or a URL, judged from its form alone before any lookup.
-def is_local_dev_or_test() -> bool:
- return settings.DEBUG or settings.TEST
+ Safe to report in detail, because nothing about our network went into the decision and the
+ user has something they can fix.
+ """
-def resolve_and_validate_host(host: str) -> None:
- """Ensure provided host resolves to a non-internal IP."""
- if host == "localhost" and is_local_dev_or_test():
- return
+# A shape error is safe to describe. Every other reason shares one message, so an error cannot
+# be used to find which addresses exist inside our network. Neither echoes the value it
+# rejected.
+INVALID_HOST_MESSAGE = "Invalid host. Enter a hostname or IP address without credentials, scheme, or path."
+UNREACHABLE_HOST_MESSAGE = (
+ "Could not reach this host. Check that the hostname is correct and reachable from the internet."
+)
- # Host may already be an IP literal
- try:
- if is_ip_internal(host) and not is_local_dev_or_test():
- raise ValueError("Host resolved to internal IP")
- return
- except ValueError:
- # Not an IP literal, requires DNS
- pass
- try:
- # getaddrinfo supports both ipv4 and ipv6
- results = socket.getaddrinfo(host, None)
- except socket.gaierror as e:
- raise ValueError(f"Could not resolve '{host}': {e}") from e
+def validate_external_host(host: str) -> None:
+ """Raise ``ValueError`` unless ``host`` is safe for our servers to reach.
+
+ SSRF guard for a destination that stores a bare host rather than a URL (Postgres,
+ Redshift). Applies the same name and IP rules as ``validate_external_url``, so the two
+ cannot drift apart. Bypassed in local dev and in tests, unless the
+ ``FORCE_URL_VALIDATION`` setting is true.
+ """
+
+ # The host could come from untyped config, so check its type first
+ if not isinstance(host, str):
+ raise ShapeError("Host must be a string")
+ shape_reason = _host_shape_error(host)
+ if shape_reason is not None:
+ raise ShapeError(shape_reason)
+ host = _canonicalize_host(host)
+
+ if _dev_bypass_enabled() or _test_bypass_enabled():
+ return
- # Keeps only unique ips from the result tuple
- resolved_ips = {str(r[4][0]) for r in results}
+ blocked_name = _blocked_host_name(host)
+ if blocked_name is not None:
+ raise ValueError(blocked_name.reason)
- for ip in resolved_ips:
- if is_ip_internal(ip) and not is_local_dev_or_test():
- raise ValueError("Host resolved to internal IP")
+ # Return the same error message in both cases, to avoid exposing details of our internal
+ # network.
+ ips = resolve_host_ips(host)
+ if not ips or any(_is_internal_ip(ip) for ip in ips):
+ raise ValueError("Host does not resolve to a valid IP address")
diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.py
index e64e37556f88..9dec48e96ed3 100644
--- a/products/batch_exports/backend/api/batch_export.py
+++ b/products/batch_exports/backend/api/batch_export.py
@@ -41,7 +41,12 @@ from posthog.models.integration import (
DatabricksIntegrationError,
Integration,
)
-from posthog.security.url_validation import resolve_and_validate_host
+from posthog.security.url_validation import (
+ INVALID_HOST_MESSAGE,
+ UNREACHABLE_HOST_MESSAGE,
+ ShapeError,
+ validate_external_host,
+)
from posthog.temporal.common.client import sync_connect
from posthog.utils import relative_date_parse, str_to_bool
@@ -1080,9 +1085,6 @@ class _DatabaseFieldFinder(TraversingVisitor):
super().visit_field(node)
-INVALID_HOST_MESSAGE = "Invalid host. Enter a hostname or IP address without credentials, scheme, or path."
-
-
class BatchExportSerializer(serializers.ModelSerializer):
"""Serializer for a BatchExport model."""
@@ -1620,9 +1622,11 @@ class BatchExportSerializer(serializers.ModelSerializer):
if host is not None:
try:
- resolve_and_validate_host(host)
- except ValueError:
+ validate_external_host(host)
+ except ShapeError:
raise serializers.ValidationError(INVALID_HOST_MESSAGE)
+ except ValueError:
+ raise serializers.ValidationError(UNREACHABLE_HOST_MESSAGE)
return destination_attrs
diff --git a/products/batch_exports/backend/tests/api/test_create_postgres.py b/products/batch_exports/backend/tests/api/test_create_postgres.py
index e0011adc6e25..7100ce873ab5 100644
--- a/products/batch_exports/backend/tests/api/test_create_postgres.py
+++ b/products/batch_exports/backend/tests/api/test_create_postgres.py
@@ -6,8 +6,8 @@ from django.test.client import Client as HttpClient
from rest_framework import status
from posthog.models.integration import Integration
+from posthog.security.url_validation import INVALID_HOST_MESSAGE, UNREACHABLE_HOST_MESSAGE
-from products.batch_exports.backend.api.batch_export import INVALID_HOST_MESSAGE
from products.batch_exports.backend.tests.api.operations import create_batch_export
pytestmark = [
@@ -72,17 +72,20 @@ def test_creating_postgres_batch_export_using_integration(client: HttpClient, te
@pytest.mark.parametrize(
- "host",
+ "host, expected_message",
[
- "169.254.169.254",
- "127.0.0.1",
- "10.0.0.1",
- "192.168.1.1",
- "postgres://alice:[email protected]/app",
+ # A blocked name and a name that does not resolve report the same thing, so the error
+ # cannot be used to find which addresses exist inside our network.
+ ("169.254.169.254", UNREACHABLE_HOST_MESSAGE),
+ ("127.0.0.1", UNREACHABLE_HOST_MESSAGE),
+ ("10.0.0.1", UNREACHABLE_HOST_MESSAGE),
+ ("192.168.1.1", UNREACHABLE_HOST_MESSAGE),
+ # The form is wrong, which is settled before any lookup, so this one says what to fix.
+ ("postgres://alice:[email protected]/app", INVALID_HOST_MESSAGE),
],
)
def test_creating_postgres_batch_export_validates_integration_host(
- client: HttpClient, temporal, organization, team, user, host
+ client: HttpClient, temporal, organization, team, user, host, expected_message
):
"""Test that the integration's host is SSRF-validated when creating a Postgres batch export.
@@ -112,7 +115,7 @@ def test_creating_postgres_batch_export_validates_integration_host(
response = create_batch_export(client, team.pk, batch_export_data)
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
- assert response.json()["detail"] == INVALID_HOST_MESSAGE
+ assert response.json()["detail"] == expected_message
assert host not in response.content.decode()
assert "hunter2" not in response.content.decode()
diff --git a/products/batch_exports/backend/tests/api/test_create_redshift.py b/products/batch_exports/backend/tests/api/test_create_redshift.py
index 6ce357042194..f0eb06786ec7 100644
--- a/products/batch_exports/backend/tests/api/test_create_redshift.py
+++ b/products/batch_exports/backend/tests/api/test_create_redshift.py
@@ -6,8 +6,8 @@ from django.test.client import Client as HttpClient
from rest_framework import status
from posthog.models.integration import Integration
+from posthog.security.url_validation import INVALID_HOST_MESSAGE, UNREACHABLE_HOST_MESSAGE
-from products.batch_exports.backend.api.batch_export import INVALID_HOST_MESSAGE
from products.batch_exports.backend.tests.api.fixtures import create_organization, create_team, create_user
from products.batch_exports.backend.tests.api.operations import create_batch_export, get_batch_export_ok
@@ -201,19 +201,23 @@ def test_create_redshift_batch_export_rejects_invalid_authorization_type(
@pytest.mark.parametrize(
- "host",
+ "host, expected_message",
[
- "192.168.1.1",
- "127.0.0.1",
- "[::1]",
- "10.0.0.1",
- "169.254.0.0",
- "localhost",
- "postgres://alice:[email protected]/app",
+ # A blocked name and a name that does not resolve report the same thing, so the error
+ # cannot be used to find which addresses exist inside our network.
+ ("192.168.1.1", UNREACHABLE_HOST_MESSAGE),
+ ("127.0.0.1", UNREACHABLE_HOST_MESSAGE),
+ ("10.0.0.1", UNREACHABLE_HOST_MESSAGE),
+ ("169.254.0.0", UNREACHABLE_HOST_MESSAGE),
+ ("localhost", UNREACHABLE_HOST_MESSAGE),
+ # These two are settled by form before any lookup, so they say what to fix. A bare
+ # IPv6 literal is a host, but the brackets a URL wraps it in are not.
+ ("[::1]", INVALID_HOST_MESSAGE),
+ ("postgres://alice:[email protected]/app", INVALID_HOST_MESSAGE),
],
)
def test_create_redshift_batch_export_fails_with_invalid_host(
- client: HttpClient, temporal, organization, team, user, host, aws_redshift_integration
+ client: HttpClient, temporal, organization, team, user, host, expected_message, aws_redshift_integration
):
"""Test creating a BatchExport with a Redshift destination rejects an internal host.
@@ -248,7 +252,7 @@ def test_create_redshift_batch_export_fails_with_invalid_host(
)
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
- assert response.json()["detail"] == INVALID_HOST_MESSAGE
+ assert response.json()["detail"] == expected_message
assert host not in response.content.decode()
assert "hunter2" not in response.content.decode()
diff --git a/products/data_warehouse/backend/tests/api/test_table.py b/products/data_warehouse/backend/tests/api/test_table.py
index a9d138f73545..d5f6a5b73641 100644
--- a/products/data_warehouse/backend/tests/api/test_table.py
+++ b/products/data_warehouse/backend/tests/api/test_table.py
@@ -52,8 +52,9 @@ class TestTable(APIBaseTest):
("localhost", "https://localhost/path/*.csv", "Local/Loopback host not allowed"),
("literal_ipv4_loopback", "https://127.0.0.1/path/*.csv", "Local/Loopback host not allowed"),
("literal_ipv4_linklocal", "https://169.254.169.254/path/*.csv", "Local/metadata host"),
- ("literal_ipv6_mapped_loopback", "https://[::ffff:127.0.0.1]/path/*.csv", "Disallowed target IP"),
- ("literal_ipv6_6to4_loopback", "https://[2002:7f00:1::]/path/*.csv", "Disallowed target IP"),
+ # Both are IP literals, so the address is parsed and judged without a DNS lookup.
+ ("literal_ipv6_mapped_loopback", "https://[::ffff:127.0.0.1]/path/*.csv", "Private IP address not allowed"),
+ ("literal_ipv6_6to4_loopback", "https://[2002:7f00:1::]/path/*.csv", "Private IP address not allowed"),
]
)
def test_create_columns_blocks_unsafe_url_patterns(self, _: str, url_pattern: str, expected_error: str):
@@ -89,12 +90,12 @@ class TestTable(APIBaseTest):
"Disallowed target IP",
),
(
- # The hostname string itself starts with "169.254." (a link-local prefix), so this
- # is blocked by the literal-prefix check before resolve_host_ips is ever called.
+ # The hostname is a name rather than an address, so it is judged by what it
+ # resolves to, like every other wildcard-DNS name in this list.
"sslip_io_linklocal",
"https://169.254.169.254.sslip.io/latest/meta-data/",
{ipaddress.ip_address("169.254.169.254")},
- "Private IP address not allowed",
+ "Disallowed target IP",
),
(
"custom_dns_rebinding",
diff --git a/products/managed_migrations/backend/api/batch_imports.py b/products/managed_migrations/backend/api/batch_imports.py
index 70454eada969..0e36f82f9448 100644
--- a/products/managed_migrations/backend/api/batch_imports.py
+++ b/products/managed_migrations/backend/api/batch_imports.py
@@ -24,7 +24,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.exceptions_capture import capture_exception
from posthog.models.user import User
-from posthog.security.url_validation import resolve_and_validate_url
+from posthog.security.url_validation import UNREACHABLE_HOST_MESSAGE, ShapeError, validate_external_url
from products.managed_migrations.backend import trial_storage
from products.managed_migrations.backend.models.batch_imports import (
@@ -123,9 +123,15 @@ class BatchImportSerializer(serializers.ModelSerializer):
if not value or not value.strip():
return None
try:
- resolve_and_validate_url(value)
+ validate_external_url(value)
+ except ShapeError:
+ # The value is never echoed: a URL carries its credentials in the userinfo, and
+ # this message reaches the response body, the request log and error tracking.
+ raise serializers.ValidationError(
+ "Invalid endpoint URL. Check that it starts with http:// or https:// and carries no credentials."
+ )
except ValueError:
- raise serializers.ValidationError(f"Invalid endpoint URL: '{value}'")
+ raise serializers.ValidationError(UNREACHABLE_HOST_MESSAGE)
return value
def create(self, validated_data: dict) -> BatchImport:
diff --git a/products/managed_migrations/backend/api/test/test_batch_imports.py b/products/managed_migrations/backend/api/test/test_batch_imports.py
index 22212c555969..e0f33b816b5c 100644
--- a/products/managed_migrations/backend/api/test/test_batch_imports.py
+++ b/products/managed_migrations/backend/api/test/test_batch_imports.py
@@ -12,6 +12,8 @@ from django.test import RequestFactory, SimpleTestCase, override_settings
from parameterized import parameterized
+from posthog.security.url_validation import UNREACHABLE_HOST_MESSAGE
+
from products.managed_migrations.backend import trial_storage
from products.managed_migrations.backend.admin.batch_imports import BatchImportAdmin
from products.managed_migrations.backend.api.batch_imports import BatchImportS3SourceCreateSerializer
@@ -1124,6 +1126,30 @@ class TestBatchImportAPI(APIBaseTest):
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["attr"], "endpoint_url")
+ self.assertIn("starts with http:// or https://", response.json()["detail"])
+
+ @override_settings(FORCE_URL_VALIDATION=True)
+ def test_s3_import_with_blocked_endpoint_url_returns_400(self):
+ # FORCE_URL_VALIDATION defeats both bypasses, which is what this needs: a blocked URL
+ # is well formed, so it only reaches this branch with the real check running. It must
+ # not be told to fix its scheme or drop credentials when it has neither problem.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/managed_migrations",
+ {
+ "source_type": "s3",
+ "content_type": "captured",
+ "s3_bucket": "test-bucket",
+ "s3_region": "us-east-1",
+ "s3_prefix": "data/",
+ "access_key": "test-key",
+ "secret_key": "test-secret",
+ "endpoint_url": "http://10.0.0.1/",
+ },
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.json()["attr"], "endpoint_url")
+ self.assertEqual(response.json()["detail"], UNREACHABLE_HOST_MESSAGE)
@override_settings(MANAGED_MIGRATIONS_IMPORT_ROLE_ARN="arn:aws:iam::999999999999:role/PostHogBatchImport")
@patch("products.managed_migrations.backend.api.batch_imports.posthoganalytics.feature_enabled", return_value=True)