: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(proxy): validate proxy record domains before probing them (#82236)
Tom Piccirelloeab5fb088aca
diff --git a/posthog/api/proxy_record.py b/posthog/api/proxy_record.pyindex b18eb7b91d97..331c1436328a 100644--- a/posthog/api/proxy_record.py+++ b/posthog/api/proxy_record.py@@ -20,6 +20,7 @@ from posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import ProxyRecordfrom posthog.models.organization import Organization+from posthog.models.proxy_record import is_valid_proxy_domainfrom posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermissionfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.proxy_service import CreateManagedProxyInputs, DeleteManagedProxyInputs@@ -94,6 +95,16 @@ class ProxyRecordSerializer(serializers.ModelSerializer):read_only=True, help_text="ID of the user who created this proxy record.")+ def validate_domain(self, value: str) -> str:+ # The stored value is later used both as a DNS query name and as the authority of a+ # URL we request. Those two grammars accept different bytes, so a value that is not a+ # plain hostname can resolve as one host and be connected to as another.+ if not is_valid_proxy_domain(value):+ raise serializers.ValidationError(+ "Enter a domain name on its own, like e.example.com, with no protocol, port, or path."+ )+ return value+class ProxyRecordListResponseSerializer(serializers.Serializer):results = ProxyRecordSerializer(many=True)diff --git a/posthog/api/proxy_record_diagnostics.py b/posthog/api/proxy_record_diagnostics.pyindex dab388627598..1faf123d3fb8 100644--- a/posthog/api/proxy_record_diagnostics.py+++ b/posthog/api/proxy_record_diagnostics.py@@ -11,9 +11,9 @@ on-demand only."""import ssl as ssl_module-import jsonimport socketimport datetime as dt+import urllib.parse as urlparsefrom dataclasses import dataclass, fieldfrom typing import Final, Literal, Optional@@ -25,6 +25,9 @@ import dns.exceptionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import ProxyRecord+from posthog.models.proxy_record import is_valid_proxy_domain+from posthog.security.pinned_requests import SSRFBlockedError, pinned_request, select_pinned_ip+from posthog.security.url_validation import validate_url_and_pin_ipsfrom posthog.temporal.proxy_service.cloudflare import (CloudflareAPIError,CustomHostname,@@ -65,6 +68,14 @@ def _msg_caa_blocking(domain: str, restricting_zone: str, allowed: list[str], re)+def _msg_domain_not_a_hostname(domain: str) -> str:+ return (+ f"`{domain}` isn't a valid domain name, so we can't run any checks against it. "+ "Delete this proxy and create it again using just the domain, like `e.example.com`, "+ "with no protocol, port, or path."+ )++def _msg_cname_missing(domain: str) -> str:return f"`{domain}` doesn't have a CNAME DNS record yet. Add the record below at your DNS provider."@@ -181,6 +192,27 @@ def diagnose(record: ProxyRecord) -> DiagnosticReport:)log.info("Starting proxy diagnostics")+ # Every check below feeds `record.domain` to a resolver, a URL, or a socket. Records+ # created before the field was validated can hold a value that those parsers disagree+ # about, so a record that isn't a plain hostname fails here rather than being probed.+ if not is_valid_proxy_domain(record.domain):+ log.warning("Proxy diagnostics refused a domain that is not a hostname")+ domain_checks: list[CheckResult] = [+ CheckResult(+ id="domain",+ name="Domain name",+ status="failed",+ detail=_msg_domain_not_a_hostname(record.domain),+ remediation=Remediation(+ type="config",+ summary="Delete this proxy and create it again using just the domain name.",+ ),+ )+ ]+ return DiagnosticReport(+ ran_at=dt.datetime.now(dt.UTC), summary=_build_summary(domain_checks), checks=domain_checks+ )+is_cloudflare = is_cloudflare_proxy_by_cname(record.target_cname)cname_check = _check_cname(record)@@ -189,10 +221,12 @@ def diagnose(record: ProxyRecord) -> DiagnosticReport:# Primary signal: does the proxy actually serve HTTPS and accept an event? A pass means# the cert is live and deployed, regardless of what the provider API says.#- # Gate the probe on the CNAME first. `record.domain` is org-admin-controlled, so we only- # fire the outbound request once DNS confirms the domain points at our managed proxy- # target — otherwise Diagnose could be aimed at an internal address and used as an- # SSRF / port-scan primitive. A failed CNAME is the actionable issue anyway.+ # The CNAME gate below is a relevance check, not a security boundary: a failed CNAME is+ # the actionable issue anyway, so the probe would only add noise. It cannot stand in for+ # SSRF protection, because it proves nothing about where the probe will connect. The two+ # lookups are independent, so a low-TTL record can answer the CNAME query from a public+ # address and the probe's own resolution from an internal one. The probe carries its own+ # protection by validating and pinning the address it connects to.if cname_check.status == "passed":live_check = _check_live_event(record)else:@@ -267,7 +301,9 @@ def _build_summary(checks: list[CheckResult]) -> ReportSummary:return ReportSummary(status="healthy", primary_issue=None, next_action=None)# Walk in priority order: things the customer can act on first, then fallthrough.- priority = ("cname", "caa", "http_challenge", "cloudflare", "live_event", "cert_expiry")+ # Every check id must appear here. An id missing from this tuple is never matched, so+ # the walk falls through and reports a failing check as an overall healthy proxy.+ priority = ("domain", "cname", "caa", "http_challenge", "cloudflare", "live_event", "cert_expiry")for check_id in priority:c = by_id.get(check_id)if c is None or c.status not in ("failed", "warned"):@@ -559,20 +595,46 @@ def _check_http_challenge(record: ProxyRecord, hostname_info: CustomHostname) ->)+def _probe_url(domain: str, path: str) -> str:+ """Build a URL whose authority is exactly `domain` and nothing else.++ Interpolating into an f-string lets any authority-terminating byte in `domain` push the+ real host into the path, so the host that gets validated is not the host that gets+ connected to. Assembling from parsed components keeps `domain` in the authority slot.+ Callers must have cleared `domain` through `is_valid_proxy_domain` first.+ """+ return urlparse.urlunparse(("https", domain, path, "", "", ""))++def _check_live_event(record: ProxyRecord) -> CheckResult:try:# Same dummy payload the daily monitor uses (posthog/temporal/proxy_service/monitor.py# check_proxy_is_live). PostHog's capture endpoint accepts unknown api_keys and returns- # 2xx — team_id resolution happens later in the ingestion pipeline — so a working proxy- # forwards this to a 2xx response. allow_redirects=False is a security boundary: an org- # admin controlling the customer's domain could otherwise redirect us to internal- # targets (cloud metadata, management APIs). Same protection as _check_http_challenge.- response = requests.post(- f"https://{record.domain}/i/v0/e/",- headers={"Content-Type": "application/json"},- data=json.dumps({"event": "test", "api_key": "test", "distinct_id": "test"}),+ # 2xx, because team_id resolution happens later in the ingestion pipeline, so a working+ # proxy forwards this to a 2xx response.+ #+ # `record.domain` is org-admin-supplied, so the request goes through pinned_request:+ # it rejects hosts that resolve to non-public addresses, then connects to the address+ # it validated instead of re-resolving. Re-resolving is what makes a low-TTL record+ # exploitable, because the name can point somewhere public when it is checked and+ # somewhere internal a moment later when it is fetched. pinned_request also never+ # follows redirects, which would otherwise let the customer's server point us at an+ # internal target after the connection succeeds.+ response = pinned_request(+ "POST",+ _probe_url(record.domain, "/i/v0/e/"),+ json={"event": "test", "api_key": "test", "distinct_id": "test"},timeout=CHECK_TIMEOUT_S,- allow_redirects=False,+ )+ except SSRFBlockedError:+ return CheckResult(+ id="live_event",+ name="Live event probe",+ status="failed",+ detail=(+ f"`{record.domain}` doesn't resolve to a public address, so we didn't send a test event. "+ "Point the domain at a publicly reachable host and run diagnostics again."+ ),)except requests.exceptions.SSLError:return CheckResult(@@ -620,13 +682,31 @@ def _check_live_event(record: ProxyRecord) -> CheckResult:def _check_cert_expiry(record: ProxyRecord, *, is_cloudflare: bool) -> CheckResult:+ # A second connection to the same org-supplied host. The detail strings below name the+ # exception class, which tells a filtered port from a closed one from a TLS failure, so+ # connecting without validation would report the state of whatever address the name+ # points at. This resolution is its own, separate from the one the live probe pinned, so+ # it has to be validated and pinned here too. SNI stays on the hostname so certificate+ # verification still checks the name the customer configured.+ allowed, _reason, pinned_ips = validate_url_and_pin_ips(_probe_url(record.domain, "/"))+ if not allowed:+ return CheckResult(+ id="cert_expiry",+ name="Certificate expiry",+ status="warned",+ detail=f"Couldn't check the certificate because `{record.domain}` doesn't resolve to a public address.",+ )+ chosen_ip = select_pinned_ip(pinned_ips)+ # An empty set means validation was bypassed (dev mode), so fall back to the hostname.+ connect_host = str(chosen_ip) if chosen_ip is not None else record.domain+try:ctx = ssl_module.create_default_context()ctx.minimum_version = ssl_module.TLSVersion.TLSv1_2# Outer `with` on the raw socket guarantees the file descriptor closes# even if wrap_socket() raises before the inner context manager takes# ownership; closing twice is safe.- with socket.create_connection((record.domain, 443), timeout=CHECK_TIMEOUT_S) as sock:+ with socket.create_connection((connect_host, 443), timeout=CHECK_TIMEOUT_S) as sock:with ctx.wrap_socket(sock, server_hostname=record.domain) as wrapped:cert = wrapped.getpeercert()except (TimeoutError, OSError, ssl_module.SSLError) as e:diff --git a/posthog/api/test/test_proxy_record.py b/posthog/api/test/test_proxy_record.pyindex db5ee55c9a17..8213d58c86ac 100644--- a/posthog/api/test/test_proxy_record.py+++ b/posthog/api/test/test_proxy_record.py@@ -108,6 +108,46 @@ class TestProxyRecordAPI(APIBaseTest):)assert response.status_code == status.HTTP_400_BAD_REQUEST+ def test_diagnose_fails_closed_on_a_stored_domain_that_is_not_a_hostname(self):+ # Rows predate write-time validation, so the endpoint has to report a failed check+ # rather than raising into the viewset's catch-all and answering 500.+ record = ProxyRecord.objects.create(+ organization=self.organization,+ created_by=self.user,+ domain="169.254.169.254:80/pad.attacker.example",+ target_cname="abc123.proxy.posthog.com",+ status=ProxyRecord.Status.ERRORING,+ )++ response = self.client.post(+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/diagnose/",+ )++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["summary"]["status"] == "fail"+ assert data["summary"]["primary_issue"] == "domain"++ @parameterized.expand(+ [+ # Reads as one DNS name but as the authority `169.254.169.254:80` in a URL.+ ("smuggled_authority", "169.254.169.254:80/pad.attacker.example"),+ ("scheme", "https://e.example.com"),+ ("port", "e.example.com:8080"),+ ("ip_literal", "169.254.169.254"),+ ]+ )+ @patch("posthog.api.proxy_record.sync_connect")+ def test_create_rejects_domains_that_are_not_bare_hostnames(self, _name, domain, mock_sync_connect):+ response = self.client.post(+ f"/api/organizations/{self.organization.id}/proxy_records/",+ {"domain": domain},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not ProxyRecord.objects.filter(organization=self.organization, domain=domain).exists()+ mock_sync_connect.assert_not_called()+@patch("posthog.api.proxy_record.sync_connect")def test_create_cleans_up_on_temporal_failure(self, mock_sync_connect):mock_sync_connect.side_effect = Exception("connection failed")diff --git a/posthog/api/test/test_proxy_record_diagnostics.py b/posthog/api/test/test_proxy_record_diagnostics.pyindex f93cbf520dc5..a14aed4fc44b 100644--- a/posthog/api/test/test_proxy_record_diagnostics.py+++ b/posthog/api/test/test_proxy_record_diagnostics.py@@ -1,3 +1,5 @@+import ipaddress+from unittest.mock import MagicMock, patchfrom django.test import TestCase, override_settings@@ -7,6 +9,8 @@ import dns.resolverfrom parameterized import parameterizedfrom posthog.api import proxy_record_diagnostics as diagnostics+from posthog.models.proxy_record import is_valid_proxy_domain+from posthog.security.pinned_requests import SSRFBlockedErrorfrom posthog.temporal.proxy_service.cloudflare import (CloudflareAPIError,CustomHostname,@@ -225,32 +229,59 @@ class TestCheckLiveEvent(TestCase):("conn_error", requests.exceptions.ConnectionError("refused"), "failed", "connect"),])- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")def test_request_exceptions(self, _name, exc, expected_status, expected_substr, post_mock):post_mock.side_effect = excresult = diagnostics._check_live_event(_record())self.assertEqual(result.status, expected_status)self.assertIn(expected_substr, result.detail.lower())- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")def test_5xx_is_fail(self, post_mock):post_mock.return_value = MagicMock(status_code=502)result = diagnostics._check_live_event(_record())self.assertEqual(result.status, "failed")- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")def test_4xx_is_warn(self, post_mock):post_mock.return_value = MagicMock(status_code=403)result = diagnostics._check_live_event(_record())self.assertEqual(result.status, "warned")- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")def test_2xx_is_pass(self, post_mock):post_mock.return_value = MagicMock(status_code=200)result = diagnostics._check_live_event(_record())self.assertEqual(result.status, "passed")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")+ def test_ssrf_block_fails_the_check_instead_of_escaping(self, post_mock):+ # SSRFBlockedError is not a RequestException, so without its own handler it would+ # escape _check_live_event and surface as a 500 from the diagnose endpoint. A domain+ # that resolves somewhere internal has to read as a failed check.+ post_mock.side_effect = SSRFBlockedError("Private IP address not allowed")++ result = diagnostics._check_live_event(_record())++ self.assertEqual(result.status, "failed")+ self.assertIn("public address", result.detail)++ @patch("posthog.api.proxy_record_diagnostics.pinned_request")+ def test_probe_targets_the_domain_as_the_authority(self, post_mock):+ post_mock.return_value = MagicMock(status_code=200)+ diagnostics._check_live_event(_record())++ self.assertEqual(post_mock.call_args[0][1], "https://e.example.com/i/v0/e/")+++PUBLIC_IP = ipaddress.ip_address("203.0.113.10")+++@patch(+ "posthog.api.proxy_record_diagnostics.validate_url_and_pin_ips",+ return_value=(True, None, {PUBLIC_IP}),+)class TestCheckCertExpiry(TestCase):@parameterized.expand([@@ -261,7 +292,7 @@ class TestCheckCertExpiry(TestCase):@patch("posthog.api.proxy_record_diagnostics.ssl_module.create_default_context")@patch("posthog.api.proxy_record_diagnostics.socket.create_connection")def test_expiring_cert_remediation_depends_on_path(- self, _name, is_cloudflare, expected_type, _create_conn_mock, ctx_mock+ self, _name, is_cloudflare, expected_type, _create_conn_mock, ctx_mock, _validate_mock):# An expiring cert triggers the failed branch; the remediation differs by path — a# Cloudflare proxy can safely re-provision (retry), a legacy proxy must not (config),@@ -275,6 +306,74 @@ class TestCheckCertExpiry(TestCase):assert result.remediation is not Noneself.assertEqual(result.remediation.type, expected_type)+ @patch("posthog.api.proxy_record_diagnostics.ssl_module.create_default_context")+ @patch("posthog.api.proxy_record_diagnostics.socket.create_connection")+ def test_connects_to_the_validated_address_with_hostname_kept_for_sni(+ self, create_conn_mock, ctx_mock, _validate_mock+ ):+ # The detail strings name the exception class, so an unpinned connection would report+ # whether a port is open on whatever address the name resolves to at connect time.+ # Connecting to the validated address closes that, and SNI has to stay on the hostname+ # or certificate verification would check the literal address instead.+ wrapped = ctx_mock.return_value.wrap_socket.return_value.__enter__.return_value+ wrapped.getpeercert.return_value = {"notAfter": "Jan 1 00:00:00 2100 GMT"}++ diagnostics._check_cert_expiry(_record(), is_cloudflare=True)++ self.assertEqual(create_conn_mock.call_args[0][0], (str(PUBLIC_IP), 443))+ self.assertEqual(ctx_mock.return_value.wrap_socket.call_args.kwargs["server_hostname"], "e.example.com")++ @patch("posthog.api.proxy_record_diagnostics.socket.create_connection")+ def test_warns_without_connecting_when_the_host_is_not_public(self, create_conn_mock, validate_mock):+ validate_mock.return_value = (False, "Private IP address not allowed", set())++ result = diagnostics._check_cert_expiry(_record(), is_cloudflare=True)++ create_conn_mock.assert_not_called()+ self.assertEqual(result.status, "warned")+++class TestIsValidProxyDomain(TestCase):+ @parameterized.expand(+ [+ ("plain", "e.example.com"),+ ("deep_subdomain", "a.b.c.example.com"),+ ("hyphenated", "other-diagnose.example.com"),+ ("multi_part_tld", "ph.example.co.uk"),+ ("digits_in_label", "proxy0.example.com"),+ ("mixed_case", "Test.Example.COM"),+ ]+ )+ def test_accepts_real_domain_shapes(self, _name, domain):+ self.assertTrue(is_valid_proxy_domain(domain))++ @parameterized.expand(+ [+ # A legal DNS query name that `requests` reads as the authority+ # `169.254.169.254:80` with the rest demoted to the path.+ ("authority_smuggled_into_label", "169.254.169.254:80/pad.attacker.example"),+ ("port", "e.example.com:8080"),+ ("path", "e.example.com/i/v0/e/"),+ ("scheme", "https://e.example.com"),+ ("userinfo", "[email protected]"),+ ("backslash", "e.example.com\\@attacker.example"),+ ("whitespace", "e.example.com "),+ ("ipv4_literal", "169.254.169.254"),+ ("ipv6_literal", "[::1]"),+ ("single_label", "localhost"),+ ("trailing_dot", "e.example.com."),+ ("empty_label", "e..example.com"),+ ("leading_hyphen_label", "-e.example.com"),+ ("underscore", "_dmarc.example.com"),+ ("wildcard", "*.example.com"),+ ("empty", ""),+ ("oversized_label", f"{'a' * 64}.example.com"),+ ("oversized_total", ".".join(["a" * 63] * 4) + ".com"),+ ]+ )+ def test_rejects_non_hostname_shapes(self, _name, domain):+ self.assertFalse(is_valid_proxy_domain(domain))+CF_TARGET = "abc.cf-prod-eu-proxy.europehog.com."LEGACY_TARGET = "abc.proxy-us.posthog.com."@@ -290,7 +389,7 @@ class TestDiagnoseOrchestrator(TestCase):@parameterized.expand([("cloudflare_path", CF_TARGET), ("legacy_path", LEGACY_TARGET)])@patch("posthog.api.proxy_record_diagnostics._check_cert_expiry")- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_live_pass_short_circuits_to_healthy(self, _name, target, ResolverMock, get_mock, post_mock, cert_mock):@@ -311,7 +410,7 @@ class TestDiagnoseOrchestrator(TestCase):self.assertEqual([c.id for c in report.checks], ["cname", "live_event", "cert_expiry"])get_mock.assert_not_called()- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_cname_failure_skips_live_probe(self, ResolverMock, get_mock, post_mock):@@ -335,7 +434,7 @@ class TestDiagnoseOrchestrator(TestCase):self.assertEqual(live_check.status, "skipped")self.assertEqual(report.summary.primary_issue, "cname")- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_legacy_not_serving_skips_cloudflare_and_offers_no_retry(self, ResolverMock, get_mock, post_mock):@@ -360,7 +459,7 @@ class TestDiagnoseOrchestrator(TestCase):self.assertFalse(any(c.remediation and c.remediation.type == "retry" for c in report.checks))self.assertEqual(report.summary.primary_issue, "live_event")- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_cloudflare_missing_hostname_still_offers_retry(self, ResolverMock, get_mock, post_mock):@@ -384,7 +483,7 @@ class TestDiagnoseOrchestrator(TestCase):assert cf_check.remediation is not Noneself.assertEqual(cf_check.remediation.type, "retry")- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_cloudflare_unprovisioned_skips_hostname_check_when_dns_absent(self, ResolverMock, get_mock, post_mock):@@ -410,7 +509,7 @@ class TestDiagnoseOrchestrator(TestCase):self.assertEqual(report.summary.primary_issue, "cname")@patch("posthog.api.proxy_record_diagnostics.requests.get")- @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_cloudflare_not_serving_caa_blocking_is_primary(self, ResolverMock, get_mock, post_mock, http_get_mock):@@ -436,3 +535,35 @@ class TestDiagnoseOrchestrator(TestCase):self.assertEqual(report.summary.primary_issue, "caa")# next_action is the fix (authorize pki.goog), not the causeself.assertIn("pki.goog", report.summary.next_action or "")++ @patch("posthog.api.proxy_record_diagnostics.ssl_module.create_default_context")+ @patch("posthog.api.proxy_record_diagnostics.socket.create_connection")+ @patch("posthog.api.proxy_record_diagnostics.requests.get")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")+ def test_stored_domain_that_is_not_a_hostname_never_reaches_the_network(+ self, ResolverMock, get_mock, post_mock, http_get_mock, socket_mock, _ctx_mock+ ):+ # `domain` predates write-time validation, and passing the CNAME check does not+ # constrain it: dnspython reads this as the DNS name `169.254.169.254:80/pad`+ # `.attacker.example`, so a nameserver the attacker controls can answer it with the+ # expected target, while `requests` reads the same string as the authority+ # `169.254.169.254:80`. The two grammars disagree, so the record must fail closed+ # before any check queries DNS or opens a connection.+ cname = MagicMock()+ cname.target.to_text.return_value = CF_TARGET+ ResolverMock.return_value.resolve.return_value = [cname]+ # A probe that fires would succeed, so the assertions below turn on whether it+ # fired at all rather than on how a half-configured mock happens to fail.+ post_mock.return_value = MagicMock(status_code=200)++ report = diagnostics.diagnose(_record(domain="169.254.169.254:80/pad.attacker.example", target=CF_TARGET))++ post_mock.assert_not_called()+ http_get_mock.assert_not_called()+ socket_mock.assert_not_called()+ get_mock.assert_not_called()+ ResolverMock.return_value.resolve.assert_not_called()+ self.assertEqual(report.summary.status, "fail")+ self.assertFalse(any(c.status == "passed" for c in report.checks))diff --git a/posthog/models/proxy_record.py b/posthog/models/proxy_record.pyindex a3e8a727de33..24c249be66f1 100644--- a/posthog/models/proxy_record.py+++ b/posthog/models/proxy_record.py@@ -1,8 +1,46 @@+import re+from django.db import modelsfrom posthog.models import Organizationfrom posthog.models.utils import UUIDTModel+MAX_PROXY_DOMAIN_LENGTH = 253+MAX_PROXY_DOMAIN_LABEL_LENGTH = 63++_LABEL = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"+_PROXY_DOMAIN_RE = re.compile(rf"{_LABEL}(?:\.{_LABEL})*")+++def is_valid_proxy_domain(domain: str) -> bool:+ """Whether `domain` is a bare hostname that means the same thing to a DNS resolver+ and to a URL parser.++ `domain` reaches two grammars: dnspython parses it as a DNS query name, and+ `requests`/`urlparse` parse it as a URL authority. Those grammars disagree, and the+ disagreement is exploitable. dnspython's all-ASCII path copies every byte except `.`+ and `\\` into a label, so `169.254.169.254:80/pad.attacker.example` is a legal query+ name that a nameserver can answer however it likes, while `urlparse` reads the same+ string as the authority `169.254.169.254:80` with the rest demoted to the path. A+ check that resolves the name therefore says nothing about where a request built from+ it will connect.++ Restricting the value to letter-digit-hyphen labels removes every byte the two+ grammars read differently, so passing here means both parse it identically. A final+ label of only digits is rejected because that is an IPv4 literal rather than a+ hostname, which keeps address literals out of the DNS path entirely.+ """+ if not domain or len(domain) > MAX_PROXY_DOMAIN_LENGTH:+ return False+ if not _PROXY_DOMAIN_RE.fullmatch(domain):+ return False+ labels = domain.split(".")+ if len(labels) < 2:+ return False+ if any(len(label) > MAX_PROXY_DOMAIN_LABEL_LENGTH for label in labels):+ return False+ return not labels[-1].isdigit()+class ProxyRecord(UUIDTModel):organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="proxy_records")diff --git a/posthog/temporal/proxy_service/monitor.py b/posthog/temporal/proxy_service/monitor.pyindex ee922a9f14e3..fb87bdaaa32f 100644--- a/posthog/temporal/proxy_service/monitor.py+++ b/posthog/temporal/proxy_service/monitor.py@@ -18,6 +18,9 @@ from temporalio.exceptions import ActivityError, ApplicationErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import ProxyRecord+from posthog.models.proxy_record import is_valid_proxy_domain+from posthog.security.pinned_requests import select_pinned_ip+from posthog.security.url_validation import validate_url_and_pin_ipsfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.client import async_connectfrom posthog.temporal.common.logger import get_logger@@ -289,6 +292,16 @@ async def check_proxy_is_live(inputs: CheckActivityInput) -> CheckActivityOutputdef _probe_proxy(proxy_record: ProxyRecord) -> CheckActivityOutput:+ # Records created before the serializer validated this field can hold a value that a DNS+ # resolver and a URL parser read as two different hosts, so the probes below would report on a+ # host nobody configured. The check runs unattended and its outcome is visible on the record.+ if not is_valid_proxy_domain(proxy_record.domain):+ return CheckActivityOutput(+ errors=["Proxy domain is not a plain hostname; recreate this proxy record"],+ warnings=[],+ )+ probe_base = f"https://{proxy_record.domain}"+# send dummy event to check the proxy is workingtry:# allow_redirects=False is a security boundary: the domain is attacker-controllable@@ -298,7 +311,7 @@ def _probe_proxy(proxy_record: ProxyRecord) -> CheckActivityOutput:# as the on-demand diagnostics probe in posthog/api/proxy_record_diagnostics.py# (_check_live_event).response = requests.post(- f"https://{proxy_record.domain}/i/v0/e/",+ f"{probe_base}/i/v0/e/",headers={"Content-Type": "application/json"},data=json.dumps({"event": "test", "api_key": "test", "distinct_id": "test"}),timeout=PROXY_LIVE_CHECK_TIMEOUT_S,@@ -321,9 +334,25 @@ def _probe_proxy(proxy_record: ProxyRecord) -> CheckActivityOutput:# create_connection carries PROXY_LIVE_CHECK_TIMEOUT_S into the connect and the TLS handshake so# an attacker-controlled domain can't stall this raw socket the way it could the POST above -# same guard, same reason. Mirrors _check_cert_expiry in proxy_record_diagnostics.py.+ #+ # A raw socket carries no proxy settings, so the egress proxy that covers the POST above+ # does not see this connection. Validate and pin the address here instead: this resolution+ # is its own, separate from whatever the POST resolved, so the domain can answer the first+ # lookup correctly and point somewhere internal by this one. SNI stays on the hostname so+ # certificate verification still checks the name the customer configured.+ allowed, _reason, pinned_ips = validate_url_and_pin_ips(f"{probe_base}/")+ if not allowed:+ return CheckActivityOutput(+ errors=["Proxy domain does not resolve to a public address"],+ warnings=[],+ )+ chosen_ip = select_pinned_ip(pinned_ips)+ # An empty set means validation was bypassed (dev mode), so fall back to the hostname.+ connect_host = str(chosen_ip) if chosen_ip is not None else proxy_record.domain+ctx = ssl.create_default_context()ctx.minimum_version = ssl.TLSVersion.TLSv1_2- with socket.create_connection((proxy_record.domain, 443), timeout=PROXY_LIVE_CHECK_TIMEOUT_S) as sock:+ with socket.create_connection((connect_host, 443), timeout=PROXY_LIVE_CHECK_TIMEOUT_S) as sock:with ctx.wrap_socket(sock, server_hostname=proxy_record.domain) as s:cert = s.getpeercert()if cert is None:diff --git a/posthog/temporal/proxy_service/test/monitor_test.py b/posthog/temporal/proxy_service/test/monitor_test.pyindex 8a915b545db7..25a6c4ae2f06 100644--- a/posthog/temporal/proxy_service/test/monitor_test.py+++ b/posthog/temporal/proxy_service/test/monitor_test.py@@ -1,4 +1,5 @@import json+import ipaddressimport pytestfrom freezegun import freeze_time@@ -121,6 +122,78 @@ class TestCheckProxyIsLive(TestCase):result = await check_proxy_is_live(self.input)self.assertEqual(result.errors, expected_errors)++ @parameterized.expand(+ [+ ("url_authority_polyglot", "169.254.169.254:80/pad.example.com"),+ ("scheme_and_path", "https://example.com/x"),+ ("address_literal", "169.254.169.254"),+ ]+ )+ @pytest.mark.asyncio+ @patch("posthog.temporal.proxy_service.monitor.socket.create_connection")+ @patch("posthog.temporal.proxy_service.monitor.requests.post")+ @patch("posthog.temporal.proxy_service.monitor.get_record")+ async def test_check_proxy_is_live_refuses_a_stored_domain_that_is_not_a_hostname(+ self, _name, domain, mock_get_record, mock_post, mock_create_connection+ ):+ self.proxy_record.domain = domain+ mock_get_record.return_value = self.proxy_record++ result = await check_proxy_is_live(self.input)++ self.assertEqual(result.errors, ["Proxy domain is not a plain hostname; recreate this proxy record"])+ mock_post.assert_not_called()+ mock_create_connection.assert_not_called()++ @pytest.mark.asyncio+ @freeze_time("2024-01-16 10:00:00")+ @patch("posthog.temporal.proxy_service.monitor.validate_url_and_pin_ips")+ @patch("posthog.temporal.proxy_service.monitor.socket.create_connection")+ @patch("posthog.temporal.proxy_service.monitor.ssl.create_default_context")+ @patch("posthog.temporal.proxy_service.monitor.requests.post")+ @patch("posthog.temporal.proxy_service.monitor.get_record")+ async def test_cert_check_connects_to_the_validated_address(+ self, mock_get_record, mock_post, mock_ssl_context, mock_create_connection, mock_validate+ ):+ mock_get_record.return_value = self.proxy_record+ mock_post.return_value = Mock(status_code=200, raise_for_status=Mock(return_value=None))+ mock_validate.return_value = (True, None, {ipaddress.ip_address("203.0.113.7")})+ mock_create_connection.return_value = MagicMock()++ mock_socket = Mock()+ mock_socket.getpeercert.return_value = {"notAfter": "Feb 5 10:00:00 2024 GMT"}+ mock_wrapped_socket = Mock()+ mock_wrapped_socket.__enter__ = Mock(return_value=mock_socket)+ mock_wrapped_socket.__exit__ = Mock(return_value=None)+ mock_context = Mock()+ mock_context.wrap_socket.return_value = mock_wrapped_socket+ mock_ssl_context.return_value = mock_context++ result = await check_proxy_is_live(self.input)++ self.assertEqual(result.errors, [])+ # The socket carries no proxy settings, so the address it opens is the whole control. SNI+ # stays on the hostname so certificate verification still checks the configured name.+ mock_create_connection.assert_called_once_with(("203.0.113.7", 443), timeout=PROXY_LIVE_CHECK_TIMEOUT_S)+ self.assertEqual(mock_context.wrap_socket.call_args.kwargs["server_hostname"], self.proxy_record.domain)++ @pytest.mark.asyncio+ @patch("posthog.temporal.proxy_service.monitor.validate_url_and_pin_ips")+ @patch("posthog.temporal.proxy_service.monitor.socket.create_connection")+ @patch("posthog.temporal.proxy_service.monitor.requests.post")+ @patch("posthog.temporal.proxy_service.monitor.get_record")+ async def test_cert_check_does_not_connect_to_a_private_address(+ self, mock_get_record, mock_post, mock_create_connection, mock_validate+ ):+ mock_get_record.return_value = self.proxy_record+ mock_post.return_value = Mock(status_code=200, raise_for_status=Mock(return_value=None))+ mock_validate.return_value = (False, "private address", set())++ result = await check_proxy_is_live(self.input)++ self.assertEqual(result.errors, ["Proxy domain does not resolve to a public address"])+ mock_create_connection.assert_not_called()self.assertEqual(result.warnings, [])@pytest.mark.asyncio