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.

feat(security): validate domain DNSSEC (#84593)

Reece Jonesdaad68bed66f
diff --git a/posthog/api/test/test_organization_domain.py b/posthog/api/test/test_organization_domain.py
index ce6c3be2bd1f..6efe28da9363 100644
--- a/posthog/api/test/test_organization_domain.py
+++ b/posthog/api/test/test_organization_domain.py
@@ -191,12 +191,12 @@ class TestOrganizationDomainsAPI(APIBaseTest):
self.assertEqual(OrganizationDomain.objects.count(), count)
- @patch("posthog.models.organization_domain.dns.resolver.resolve")
+ @patch("posthog.models.organization_domain.dnssec_resolver")
def test_can_request_verification_for_unverified_domains(self, mock_dns_query):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
- mock_dns_query.return_value = FakeDNSResponse(
+ mock_dns_query.return_value.resolve.return_value = FakeDNSResponse(
[
dns.rrset.from_text(
"_posthog-challenge.myposthog.com.",
@@ -227,12 +227,12 @@ class TestOrganizationDomainsAPI(APIBaseTest):
)
self.assertEqual(self.domain.is_verified, True)
- @patch("posthog.models.organization_domain.dns.resolver.resolve")
+ @patch("posthog.models.organization_domain.dnssec_resolver")
def test_domain_is_not_verified_with_missing_challenge(self, mock_dns_query):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
- mock_dns_query.side_effect = dns.resolver.NoAnswer()
+ mock_dns_query.return_value.resolve.side_effect = dns.resolver.NoAnswer()
with freeze_time("2021-10-10T10:10:10Z"):
with self.is_cloud(True):
@@ -248,12 +248,12 @@ class TestOrganizationDomainsAPI(APIBaseTest):
datetime.datetime(2021, 10, 10, 10, 10, 10, tzinfo=ZoneInfo("UTC")),
)
- @patch("posthog.models.organization_domain.dns.resolver.resolve")
+ @patch("posthog.models.organization_domain.dnssec_resolver")
def test_domain_is_not_verified_with_missing_domain(self, mock_dns_query):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
- mock_dns_query.side_effect = dns.resolver.NXDOMAIN()
+ mock_dns_query.return_value.resolve.side_effect = dns.resolver.NXDOMAIN()
with freeze_time("2021-10-10T10:10:10Z"):
with self.is_cloud(True):
@@ -269,12 +269,12 @@ class TestOrganizationDomainsAPI(APIBaseTest):
datetime.datetime(2021, 10, 10, 10, 10, 10, tzinfo=ZoneInfo("UTC")),
)
- @patch("posthog.models.organization_domain.dns.resolver.resolve")
+ @patch("posthog.models.organization_domain.dnssec_resolver")
def test_domain_is_not_verified_with_incorrect_challenge(self, mock_dns_query):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
- mock_dns_query.return_value = FakeDNSResponse(
+ mock_dns_query.return_value.resolve.return_value = FakeDNSResponse(
[
dns.rrset.from_text(
"_posthog-challenge.myposthog.com.",
diff --git a/posthog/dns_utils.py b/posthog/dns_utils.py
new file mode 100644
index 000000000000..99c8ac222877
--- /dev/null
+++ b/posthog/dns_utils.py
@@ -0,0 +1,23 @@
+import dns.flags
+import dns.resolver
+import dns.nameserver
+import dns.asyncresolver
+
+DNSSEC_VALIDATING_NAMESERVERS = (
+ dns.nameserver.DoHNameserver("https://cloudflare-dns.com/dns-query", bootstrap_address="1.1.1.1"),
+ dns.nameserver.DoHNameserver("https://cloudflare-dns.com/dns-query", bootstrap_address="1.0.0.1"),
+)
+
+
+def dnssec_resolver() -> dns.resolver.Resolver:
+ resolver = dns.resolver.Resolver(configure=False)
+ resolver.nameservers = list(DNSSEC_VALIDATING_NAMESERVERS)
+ resolver.use_edns(edns=0, ednsflags=dns.flags.DO)
+ return resolver
+
+
+def async_dnssec_resolver() -> dns.asyncresolver.Resolver:
+ resolver = dns.asyncresolver.Resolver(configure=False)
+ resolver.nameservers = list(DNSSEC_VALIDATING_NAMESERVERS)
+ resolver.use_edns(edns=0, ednsflags=dns.flags.DO)
+ return resolver
diff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.py
index cbadb4c87ee0..3c56e98bed0a 100644
--- a/posthog/models/organization_domain.py
+++ b/posthog/models/organization_domain.py
@@ -12,6 +12,7 @@ import structlog
import dns.resolver
from posthog.constants import AvailableFeature
+from posthog.dns_utils import dnssec_resolver
from posthog.models import Organization
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.identity_provider_config import IdentityProviderConfig
@@ -379,9 +380,8 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):
Performs a DNS verification for a specific domain.
"""
try:
- # TODO: Should we manually validate DNSSEC?
- dns_response = dns.resolver.resolve(f"_posthog-challenge.{self.domain}", "TXT")
- except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
+ dns_response = dnssec_resolver().resolve(f"_posthog-challenge.{self.domain}", "TXT")
+ except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, dns.resolver.NoNameservers):
pass
else:
for item in list(dns_response.response.answer[0]):
diff --git a/posthog/temporal/proxy_service/create.py b/posthog/temporal/proxy_service/create.py
index 9223c47ea3de..d8e67ef7e0c0 100644
--- a/posthog/temporal/proxy_service/create.py
+++ b/posthog/temporal/proxy_service/create.py
@@ -13,7 +13,6 @@ from django.conf import settings
import grpc.aio
import requests
import dns.resolver
-import dns.asyncresolver
import temporalio.common
from structlog import get_logger
from temporalio import activity, workflow
@@ -26,6 +25,7 @@ from temporalio.client import (
)
from temporalio.exceptions import ActivityError, ApplicationError, RetryState
+from posthog.dns_utils import async_dnssec_resolver
from posthog.models import ProxyRecord
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.client import async_connect
@@ -122,7 +122,8 @@ async def wait_for_dns_records(inputs: WaitForDNSRecordsInputs):
raise RecordDeletedException("proxy record was deleted while waiting for DNS records")
try:
- cnames = await dns.asyncresolver.resolve(inputs.domain, "CNAME")
+ resolver = async_dnssec_resolver()
+ cnames = await resolver.resolve(inputs.domain, "CNAME")
value = cnames[0].target.canonicalize().to_text()
if cnames[0].target == dns.name.from_text(inputs.target_cname):
@@ -140,7 +141,7 @@ async def wait_for_dns_records(inputs: WaitForDNSRecordsInputs):
# It means there is a record set, but it's not a CNAME record
# A likely reason for this is that they have set Cloudflare proxying on.
# Check for this explicitly to create a nice message for the user.
- arecords = await dns.asyncresolver.resolve(inputs.domain, "A")
+ arecords = await resolver.resolve(inputs.domain, "A")
if len(arecords) == 0:
raise
ip = arecords[0].to_text()
@@ -155,7 +156,7 @@ async def wait_for_dns_records(inputs: WaitForDNSRecordsInputs):
# off (grey cloud). If the IPs match our target, the setup is
# correct — the CNAME is just being flattened.
try:
- target_arecords = await dns.asyncresolver.resolve(inputs.target_cname, "A")
+ target_arecords = await resolver.resolve(inputs.target_cname, "A")
target_ips = {r.to_text() for r in target_arecords}
customer_ips = {r.to_text() for r in arecords}
if customer_ips == target_ips:
diff --git a/posthog/temporal/proxy_service/monitor.py b/posthog/temporal/proxy_service/monitor.py
index d384c36294e6..6607a10f6442 100644
--- a/posthog/temporal/proxy_service/monitor.py
+++ b/posthog/temporal/proxy_service/monitor.py
@@ -16,6 +16,7 @@ from structlog.contextvars import bind_contextvars
from temporalio import activity, workflow
from temporalio.exceptions import ActivityError, ApplicationError
+from posthog.dns_utils import dnssec_resolver
from posthog.exceptions_capture import capture_exception
from posthog.models import ProxyRecord
from posthog.models.proxy_record import is_valid_proxy_domain
@@ -127,8 +128,9 @@ async def check_dns(inputs: CheckActivityInput) -> CheckActivityOutput:
def _resolve_dns(proxy_record: ProxyRecord) -> CheckActivityOutput:
+ resolver = dnssec_resolver()
try:
- cnames = dns.resolver.resolve(proxy_record.domain, "CNAME", lifetime=DNS_LOOKUP_LIFETIME_S)
+ cnames = resolver.resolve(proxy_record.domain, "CNAME", lifetime=DNS_LOOKUP_LIFETIME_S)
value = cnames[0].target.canonicalize().to_text()
if cnames[0].target == dns.name.from_text(proxy_record.target_cname):
return CheckActivityOutput(
@@ -148,7 +150,7 @@ def _resolve_dns(proxy_record: ProxyRecord) -> CheckActivityOutput:
# A likely reason for this is that they have set Cloudflare proxying on.
# Check for this explicitly to create a nice message for the user.
try:
- arecords = dns.resolver.resolve(proxy_record.domain, "A", lifetime=DNS_LOOKUP_LIFETIME_S)
+ arecords = resolver.resolve(proxy_record.domain, "A", lifetime=DNS_LOOKUP_LIFETIME_S)
except DNS_LOOKUP_FAILURES:
return CheckActivityOutput(
errors=["No CNAME or A record DNS records found"],
diff --git a/posthog/temporal/proxy_service/test/dns_test.py b/posthog/temporal/proxy_service/test/dns_test.py
index bad285a9d904..7f9b334cf586 100644
--- a/posthog/temporal/proxy_service/test/dns_test.py
+++ b/posthog/temporal/proxy_service/test/dns_test.py
@@ -67,7 +67,8 @@ class TestProxyChecksDoNotFailOnHandledConditions(SimpleTestCase):
raise dns.resolver.NoAnswer()
raise exc
- with patch("dns.resolver.resolve", side_effect=resolve):
+ with patch("posthog.temporal.proxy_service.monitor.dnssec_resolver") as resolver:
+ resolver.return_value.resolve.side_effect = resolve
out = await check_dns(CheckActivityInput(proxy_record_id=RECORD_ID))
assert out.errors == ["No CNAME or A record DNS records found"]
@@ -77,7 +78,8 @@ class TestProxyChecksDoNotFailOnHandledConditions(SimpleTestCase):
async def test_a_cname_failure_is_reported_not_raised(self, _name, exc, mock_get_record):
mock_get_record.return_value = _record()
- with patch("dns.resolver.resolve", side_effect=exc):
+ with patch("posthog.temporal.proxy_service.monitor.dnssec_resolver") as resolver:
+ resolver.return_value.resolve.side_effect = exc
out = await check_dns(CheckActivityInput(proxy_record_id=RECORD_ID))
assert out.errors == ["Domain name not found"]
@@ -93,7 +95,8 @@ class TestProxyChecksDoNotFailOnHandledConditions(SimpleTestCase):
raise dns.resolver.NoAnswer()
return [a_rec]
- with patch("dns.resolver.resolve", side_effect=resolve):
+ with patch("posthog.temporal.proxy_service.monitor.dnssec_resolver") as resolver:
+ resolver.return_value.resolve.side_effect = resolve
with patch(
"posthog.temporal.proxy_service.monitor.requests.get",
side_effect=requests.exceptions.Timeout(),
@@ -112,7 +115,8 @@ class TestProxyChecksKeepTheEventLoopFree(SimpleTestCase):
time.sleep(1.0)
raise dns.resolver.NXDOMAIN()
- with patch("dns.resolver.resolve", side_effect=slow):
+ with patch("posthog.temporal.proxy_service.monitor.dnssec_resolver") as resolver:
+ resolver.return_value.resolve.side_effect = slow
baseline, contended = await _time_a_co_tenant(
lambda: check_dns(CheckActivityInput(proxy_record_id=RECORD_ID))
)
diff --git a/posthog/test/activity_logging/test_organization_domain_activity_logging.py b/posthog/test/activity_logging/test_organization_domain_activity_logging.py
index e1e2a7f4bd0c..5f39816ac05f 100644
--- a/posthog/test/activity_logging/test_organization_domain_activity_logging.py
+++ b/posthog/test/activity_logging/test_organization_domain_activity_logging.py
@@ -127,7 +127,7 @@ class TestOrganizationDomainActivityLogging(APIBaseTest):
assert field_change is not None, f"Expected change for '{expected_field_name}' not found in {changes}"
self.assertEqual(field_change["after"], expected_logged_value)
- @patch("posthog.models.organization_domain.dns.resolver.resolve")
+ @patch("posthog.models.organization_domain.dnssec_resolver")
def test_domain_verification_activity_logging(self, mock_dns_query):
response = self.client.post(
"/api/organizations/@current/domains/",
@@ -140,7 +140,7 @@ class TestOrganizationDomainActivityLogging(APIBaseTest):
scope="OrganizationDomain",
).delete()
- mock_dns_query.return_value = FakeDNSResponse(
+ mock_dns_query.return_value.resolve.return_value = FakeDNSResponse(
[
dns.rrset.from_text(
"_posthog-challenge.verify.example.com.",
@@ -169,7 +169,7 @@ class TestOrganizationDomainActivityLogging(APIBaseTest):
verified_change = next((c for c in changes if c["field"] == "domain verification"), None)
assert verified_change is not None, f"Expected 'domain verification' change not found in {changes}"
- @patch("posthog.models.organization_domain.dns.resolver.resolve")
+ @patch("posthog.models.organization_domain.dnssec_resolver")
def test_failed_verification_excludes_last_verification_retry(self, mock_dns_query):
response = self.client.post(
"/api/organizations/@current/domains/",
@@ -182,7 +182,7 @@ class TestOrganizationDomainActivityLogging(APIBaseTest):
scope="OrganizationDomain",
).delete()
- mock_dns_query.side_effect = dns.resolver.NoAnswer()
+ mock_dns_query.return_value.resolve.side_effect = dns.resolver.NoAnswer()
response = self.client.post(f"/api/organizations/@current/domains/{domain.id}/verify")
self.assertEqual(response.status_code, 200)
diff --git a/posthog/test/test_dns_utils.py b/posthog/test/test_dns_utils.py
new file mode 100644
index 000000000000..7691e3cb1288
--- /dev/null
+++ b/posthog/test/test_dns_utils.py
@@ -0,0 +1,17 @@
+from django.test import SimpleTestCase
+
+import dns.flags
+import dns.nameserver
+
+from posthog.dns_utils import DNSSEC_VALIDATING_NAMESERVERS, async_dnssec_resolver, dnssec_resolver
+
+
+class TestDNSSECResolvers(SimpleTestCase):
+ def test_resolvers_request_opportunistic_dnssec_validation(self) -> None:
+ for resolver in (dnssec_resolver(), async_dnssec_resolver()):
+ assert tuple(resolver.nameservers) == DNSSEC_VALIDATING_NAMESERVERS
+ for nameserver in resolver.nameservers:
+ assert isinstance(nameserver, dns.nameserver.DoHNameserver)
+ assert nameserver.verify is True
+ assert resolver.edns == 0
+ assert resolver.ednsflags & dns.flags.DO