Build a Django app that watches Certificate Transparency for names under your own domains, resolves them with dnspython, diffs against a stored inventory, flags dangling CNAMEs and e-mails the security team, with retries, rate limiting, a daily timer and mocked tests.
Every organisation has more internet-facing hostnames than its inventory admits. This tutorial builds a small Django app that watches Certificate Transparency for names under your own domains, resolves them, compares the result with a stored inventory, and e-mails the security team when something new or different appears. It is passive monitoring of assets you own, run once a day.
An asset inventory is accurate on the day it is written. After that, several forces pull it away from reality:
Attackers enumerate your names from public sources as a matter of routine. You should see the same picture first, and see it continuously rather than once a year during an audit.
Before you build anything, make sure monitoring is covered by a written scope that lists the domains you are authorised to monitor, the permitted sources and the rate limits. The code below enforces that list.
Certificate Transparency (CT, RFC 6962 and its successor RFC 9162) requires publicly trusted certificate authorities to submit every certificate, or a precertificate, to append-only logs. Each log is a Merkle tree: entries can be added but not removed or rewritten without detection, and monitors can verify consistency between tree heads. Browsers require proof of logging (a signed certificate timestamp) before they trust a certificate, so in practice every publicly trusted certificate for your domains is in some log within minutes of issuance.
For defenders this has two consequences:
CT shows names that were certified, not hosts that exist. A name can sit in a certificate long after its DNS record was removed. That is why the monitor resolves every name it learns.
Running your own CT log monitor means tailing dozens of logs and parsing X.509 structures. For a single organisation the public crt.sh aggregator is a pragmatic start. It offers JSON output:
https://crt.sh/?q=%.example.com&output=json&exclude=expired
% is a SQL-style wildcard, so %.example.com matches every subdomain and also certificates that list the apex alongside a subdomain. exclude=expired limits results to certificates that are still valid, which keeps responses small and the inventory current. Each element looks like this (real response, shortened):
{
"issuer_ca_id": 413868,
"issuer_name": "C=US, O=..., CN=...",
"common_name": "example.com",
"name_value": "*.example.com\nexample.com",
"id": 29581274041,
"not_before": "2026-09-26T22:49:11",
"not_after": "2026-12-25T22:56:35",
"serial_number": "01eee6aabb521d5e14fc315fd9985690",
"result_count": 3
}
name_value contains all subject alternative names and the common name, separated by newlines. In a real query for example.com it also contained strings such as user@example.com and a certificate authority test label with spaces, and a broader query returned m.testexample.com, which is a different registrable domain. Parsing must therefore filter, not just split.
Treat crt.sh as a source of grade B at best. It is a free community service that is often slow and sometimes returns partial results or errors under load. In our test runs a query took close to two minutes, and two consecutive queries for the same domain returned 6 and then 10 entries. Design for that: generous timeouts, retries with backoff, at most one request every few seconds, and never treat a missing name in one response as proof that the name is gone.
The code was tested on Python 3.13 with Django 5.2.20 (the current LTS line), dnspython 2.9.2, requests 2.34.2 and urllib3 2.8.0, the latest stable releases at the time of writing. Python 3.12 or later is required.
python -m venv .venv
. .venv/bin/activate
pip install "Django>=5.2,<6.0" "dnspython>=2.9,<3.0" "requests>=2.34,<3.0"
django-admin startproject myproject .
python manage.py startapp exposure
Add the app and the scope to myproject/settings.py:
INSTALLED_APPS += ["exposure"]
# Scope: only domains listed here may be monitored (see the scope document).
EXPOSURE_DOMAINS = ["example.com", "example.org"]
EXPOSURE_ALERT_RECIPIENTS = ["security@example.com"]
DEFAULT_FROM_EMAIL = "monitor@example.com"
Configure a real EMAIL_BACKEND for production; the console backend is convenient during development.
Two models are enough. Asset is one DNS name with its current state. Observation records a DNS state and is written only when the state differs from the previous one, so the table holds a compact change history rather than one row per name per day.
from django.db import models
from django.utils import timezone
class Status(models.TextChoices):
ACTIVE = "active"
NXDOMAIN = "nxdomain"
DANGLING = "dangling_cname"
ERROR = "error"
WILDCARD = "wildcard"
class Asset(models.Model):
name = models.CharField(max_length=253, unique=True)
domain = models.CharField(max_length=253, db_index=True)
is_wildcard = models.BooleanField(default=False)
status = models.CharField(max_length=20, choices=Status, default=Status.ACTIVE)
first_seen = models.DateTimeField(default=timezone.now)
last_seen = models.DateTimeField(default=timezone.now)
acknowledged = models.BooleanField(default=False) # an owner confirmed it
def __str__(self):
return self.name
class Observation(models.Model):
"""DNS state of an asset, stored only when it differs from the previous one."""
asset = models.ForeignKey(Asset, on_delete=models.CASCADE,
related_name="observations")
observed_at = models.DateTimeField(default=timezone.now, db_index=True)
status = models.CharField(max_length=20, choices=Status)
addresses = models.JSONField(default=list)
cname = models.CharField(max_length=253, blank=True)
class Meta:
ordering = ["-observed_at", "-id"]
The acknowledged flag lets an owner confirm that a host is known and wanted. A dashboard can then focus on unacknowledged assets. No personal data is stored: names that look like e-mail addresses are dropped before they reach the database.
Retries belong in the transport layer. urllib3's Retry retries connection errors and the listed status codes with exponential backoff, and honours a Retry-After header on 429 and 503 responses. A small rate limiter guarantees a minimum gap between requests within one run, regardless of how many domains are configured.
import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
CRT_SH_URL = "https://crt.sh/"
USER_AGENT = "myproject-asm/1.0 (+mailto:security@example.com)"
def build_session() -> requests.Session:
retry = Retry(
total=4,
backoff_factor=2,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET"}),
respect_retry_after_header=True,
)
session = requests.Session()
session.headers["User-Agent"] = USER_AGENT
session.mount("https://", HTTPAdapter(max_retries=retry))
return session
class RateLimiter:
"""Enforce a minimum interval between requests within one run."""
def __init__(self, min_interval, clock=time.monotonic, sleep=time.sleep):
self.min_interval = min_interval
self.clock, self.sleep = clock, sleep
self._last = None
def wait(self) -> None:
if self._last is not None:
remaining = self.min_interval - (self.clock() - self._last)
if remaining > 0:
self.sleep(remaining)
self._last = self.clock()
def fetch_ct_entries(domain, session, limiter) -> list[dict]:
limiter.wait()
resp = session.get(
CRT_SH_URL,
params={"q": f"%.{domain}", "output": "json", "exclude": "expired"},
timeout=(10, 120),
)
resp.raise_for_status()
return resp.json()
The timeout tuple separates the connect timeout from the read timeout, because crt.sh accepts connections quickly but can take a long time to answer. The User-Agent identifies the tool and gives a contact address, which is the polite thing to do towards a free service. The limiter takes injectable clock and sleep functions so it can be tested without waiting.
Normalisation lowercases names, strips trailing dots, splits on newlines and deduplicates through a dictionary key. Two filters keep the data in scope: the name must equal the monitored domain or end with a dot followed by it (a plain endswith("example.com") would accept testexample.com), and every label must be a valid hostname label. Internationalised names appear in their xn-- form and pass the label check.
import re
LABEL = re.compile(r"^(?!-)[a-z0-9-]{1,63}(?<!-)$")
def extract_names(entries: list[dict], domain: str) -> dict[str, bool]:
"""Map each in-scope DNS name to True if it is a wildcard name."""
domain = domain.lower().rstrip(".")
names: dict[str, bool] = {}
for entry in entries:
for raw in entry.get("name_value", "").splitlines():
name = raw.strip().lower().rstrip(".")
wildcard = name.startswith("*.")
base = name[2:] if wildcard else name
if base != domain and not base.endswith("." + domain):
continue # look-alike or unrelated name
if not all(LABEL.match(label) for label in base.split(".")):
continue # e-mail address, CA test string, other noise
names[name] = wildcard
return names
Wildcard names such as *.example.com are kept as assets with is_wildcard=True but are not resolved, because the literal name has no meaning in DNS. A wildcard certificate is still worth tracking: it tells you that some system holds a private key valid for every first-level subdomain, and that system is worth knowing about. Whether the zone also has a wildcard DNS record is a separate question you can answer from your own zone file.
dnspython resolves A and AAAA records and follows CNAME chains. The answer exposes both the queried name and the canonical name, which tells us whether the name is an alias.
import dns.exception
import dns.resolver
from .models import Status
def resolve(name: str, resolver: dns.resolver.Resolver | None = None) -> dict:
resolver = resolver or dns.resolver.Resolver()
result = {"status": Status.ACTIVE, "addresses": [], "cname": ""}
for rtype in ("A", "AAAA"):
try:
answer = resolver.resolve(name, rtype, lifetime=5.0)
except dns.resolver.NXDOMAIN:
return _nxdomain(name, resolver, result)
except dns.resolver.NoAnswer:
continue
except (dns.resolver.NoNameservers, dns.resolver.LifetimeTimeout):
result["status"] = Status.ERROR
continue
result["addresses"] += [rr.to_text() for rr in answer]
if answer.canonical_name != answer.qname:
result["cname"] = answer.canonical_name.to_text().rstrip(".")
result["addresses"].sort()
return result
def _nxdomain(name, resolver, result) -> dict:
"""Is the name itself missing, or only the target of its CNAME?"""
try:
answer = resolver.resolve(name, "CNAME", lifetime=5.0)
except dns.exception.DNSException:
result["status"] = Status.NXDOMAIN
return result
result["cname"] = answer[0].target.to_text().rstrip(".")
result["status"] = Status.DANGLING
return result
If a query returns NXDOMAIN, the helper asks for the CNAME record of the name itself. If one exists, the alias is present but its target does not resolve. That is a dangling CNAME, a known precursor to subdomain takeover when the target is a third-party service where someone else could claim the name. This tutorial only flags it; the separate subdomain takeover tutorial covers verification and remediation in depth.
Resolution sends queries through your resolver to your own authoritative name servers. That is low-impact active collection against your own infrastructure; list it in the scope document. Use the organisation's resolver so the results match what your users see.
The core of the monitor compares the state just observed with the most recent observation per asset. A new asset, a changed address set, a changed CNAME target and a status change are all reported. The whole update runs in one transaction, so a crash halfway through does not leave a half-updated inventory.
from dataclasses import dataclass, field
from django.conf import settings
from django.core.mail import send_mail
from django.db import transaction
from django.utils import timezone
from .dnscheck import resolve
from .models import Asset, Observation, Status
from .names import extract_names
@dataclass
class Report:
domain: str
seen: int = 0
new: list = field(default_factory=list)
changed: list = field(default_factory=list) # (asset, previous, current)
dangling: list = field(default_factory=list)
@transaction.atomic
def update_inventory(domain, entries, resolve_fn=None) -> Report:
resolve_fn = resolve_fn or resolve
report, now = Report(domain), timezone.now()
for name, wildcard in sorted(extract_names(entries, domain).items()):
report.seen += 1
asset, created = Asset.objects.get_or_create(
name=name,
defaults={"domain": domain, "is_wildcard": wildcard, "first_seen": now})
if wildcard:
state = {"status": Status.WILDCARD, "addresses": [], "cname": ""}
else:
state = resolve_fn(name)
previous = asset.observations.first()
key = (state["status"], state["addresses"], state["cname"])
if previous is None or (previous.status, previous.addresses,
previous.cname) != key:
current = Observation.objects.create(asset=asset, observed_at=now, **state)
if not created:
report.changed.append((asset, previous, current))
asset.status, asset.last_seen = state["status"], now
asset.save(update_fields=["status", "last_seen"])
if created:
report.new.append(asset)
if state["status"] == Status.DANGLING:
report.dangling.append(asset)
return report
def send_alert(report: Report) -> int:
if not (report.new or report.changed or report.dangling):
return 0
lines = [f"External asset monitor for {report.domain}", ""]
lines += [f"NEW {a.name} ({a.status})" for a in report.new]
for asset, old, new in report.changed:
before = f"{old.status} {old.addresses} {old.cname}".strip() if old else "none"
after = f"{new.status} {new.addresses} {new.cname}".strip()
lines.append(f"CHANGED {asset.name}: {before} -> {after}")
lines += [f"DANGLING {a.name}: CNAME target does not resolve"
for a in report.dangling]
subject = (f"[myproject ASM] {report.domain}: {len(report.new)} new, "
f"{len(report.changed)} changed, {len(report.dangling)} dangling")
return send_mail(subject, "\n".join(lines), settings.DEFAULT_FROM_EMAIL,
settings.EXPOSURE_ALERT_RECIPIENTS)
Addresses are sorted before comparison, so a round-robin record that returns the same addresses in a different order does not produce a false change. Assets that disappear from CT are not deleted. Since the query excludes expired certificates, a name that has not been seen for longer than your longest certificate lifetime is a good candidate for review; that is a simple query on last_seen.
The resolver is looked up at call time (resolve_fn or resolve) rather than bound as a default argument. That keeps it patchable in tests.
The command ties everything together. It refuses any domain that is not in EXPOSURE_DOMAINS, continues with the next domain when one query fails, and exits with an error afterwards so the scheduler records the failure.
import requests
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from exposure.ct import RateLimiter, build_session, fetch_ct_entries
from exposure.monitor import send_alert, update_inventory
class Command(BaseCommand):
help = "Refresh the inventory of our own domains from Certificate Transparency."
def add_arguments(self, parser):
parser.add_argument("domains", nargs="*")
parser.add_argument("--min-interval", type=float, default=10.0)
parser.add_argument("--no-mail", action="store_true")
def handle(self, *args, domains, min_interval, no_mail, **options):
in_scope = set(settings.EXPOSURE_DOMAINS)
domains = domains or sorted(in_scope)
if not_allowed := set(domains) - in_scope:
raise CommandError(f"Not in scope: {', '.join(sorted(not_allowed))}")
session, limiter, failures = build_session(), RateLimiter(min_interval), 0
for domain in domains:
try:
entries = fetch_ct_entries(domain, session, limiter)
except (requests.RequestException, ValueError) as exc:
failures += 1
self.stderr.write(f"{domain}: CT query failed: {exc}")
continue
report = update_inventory(domain, entries)
if not no_mail:
send_alert(report)
self.stdout.write(
f"{domain}: {len(entries)} CT entries, {report.seen} names, "
f"{len(report.new)} new, {len(report.changed)} changed, "
f"{len(report.dangling)} dangling")
if failures:
raise CommandError(f"{failures} domain(s) not refreshed")
A failed fetch leaves the inventory for that domain untouched. Doing nothing is the right response to an aggregator error: an empty or truncated response must never be interpreted as "all hosts were removed".
Real runs against example.com, a few minutes apart, followed by an attempt outside the scope:
$ python manage.py makemigrations exposure && python manage.py migrate
...
$ python manage.py monitor_exposure example.com --no-mail
example.com: 6 CT entries, 2 names, 2 new, 0 changed, 0 dangling
$ python manage.py monitor_exposure example.com --no-mail
example.com: 10 CT entries, 3 names, 1 new, 0 changed, 0 dangling
$ python manage.py monitor_exposure example.net
CommandError: Not in scope: example.net
The second run found a name that the first response did not include. That is aggregator variance, not a new certificate, and a good reason to read alerts with the source grade in mind.
With the console backend, a run that discovers a new staging host and an alias pointing to a removed CDN endpoint produces this message (headers shortened):
Subject: [myproject ASM] example.com: 2 new, 0 changed, 1 dangling
From: monitor@example.com
To: security@example.com
...
External asset monitor for example.com
NEW assets.example.com (dangling_cname)
NEW staging.example.com (active)
DANGLING assets.example.com: CNAME target does not resolve
Keep alerts terse and actionable. A daily message that says "nothing changed" trains people to ignore the channel, so the monitor stays silent when there is nothing to report. Monitor the job itself separately, as described next.
A systemd timer is the more robust option on Linux, because it logs to the journal, catches up after downtime and lets you add a random delay so the request does not hit crt.sh at the same second as everybody else's cron job.
# /etc/systemd/system/myproject-asm.service
[Unit]
Description=myproject external asset monitor
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=myproject
WorkingDirectory=/srv/myproject
ExecStart=/srv/myproject/.venv/bin/python manage.py monitor_exposure
TimeoutStartSec=30min
# /etc/systemd/system/myproject-asm.timer
[Unit]
Description=Run the myproject external asset monitor daily
[Timer]
OnCalendar=*-*-* 06:00:00
RandomizedDelaySec=45min
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now myproject-asm.timer
systemctl list-timers myproject-asm.timer
journalctl -u myproject-asm.service --since today
With cron, the equivalent is one line in the service user's crontab. Add flock so a slow run cannot overlap the next one:
17 6 * * * cd /srv/myproject && flock -n /tmp/myproject-asm.lock .venv/bin/python manage.py monitor_exposure >> /var/log/myproject/asm.log 2>&1
Whichever you choose, alert on failure. A monitor that has silently not run for three weeks is worse than none, because people believe it is working. OnFailure= in the service unit, or a dead man's switch that expects a ping after each successful run, closes that gap.
Tests must never touch crt.sh or real DNS. requests.Session.get is patched to return a fake response, and the resolver function is replaced with one that reads from a dictionary of documentation addresses. The dangling CNAME case uses a fake resolver object that raises NXDOMAIN for address queries and returns a CNAME record.
from unittest import mock
import dns.resolver
from django.core import mail
from django.core.management import CommandError, call_command
from django.test import TestCase
from exposure.ct import RateLimiter
from exposure.dnscheck import resolve
from exposure.models import Asset, Status
from exposure.names import extract_names
CT_ENTRIES = [
{"name_value": "*.example.com\nexample.com"},
{"name_value": "www.example.com\nWWW.EXAMPLE.COM."},
{"name_value": "shop.example.com\nuser@example.com"},
{"name_value": "login.example.com.example.net"}, # not ours
{"name_value": "m.testexample.com"}, # look-alike
]
DNS = {
"example.com": ["192.0.2.10"],
"www.example.com": ["192.0.2.10"],
"shop.example.com": ["198.51.100.7"],
}
def fake_resolve(name):
return {"status": Status.ACTIVE, "addresses": list(DNS[name]), "cname": ""}
def fake_response(payload, status=200):
resp = mock.Mock(status_code=status)
resp.json.return_value = payload
resp.raise_for_status.return_value = None
return resp
@mock.patch("exposure.monitor.resolve", side_effect=fake_resolve)
@mock.patch("requests.Session.get")
class MonitorCommandTests(TestCase):
def run_command(self):
call_command("monitor_exposure", "example.com", "--min-interval", "0",
stdout=mock.Mock())
def test_first_run_creates_assets_and_alerts(self, get, _resolve):
get.return_value = fake_response(CT_ENTRIES)
self.run_command()
self.assertEqual(
sorted(Asset.objects.values_list("name", flat=True)),
["*.example.com", "example.com", "shop.example.com", "www.example.com"])
self.assertEqual(len(mail.outbox), 1)
self.assertIn("4 new", mail.outbox[0].subject)
_, kwargs = get.call_args
self.assertEqual(kwargs["params"]["q"], "%.example.com")
def test_unchanged_second_run_is_silent(self, get, _resolve):
get.return_value = fake_response(CT_ENTRIES)
self.run_command()
self.run_command()
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(Asset.objects.get(name="www.example.com").observations.count(), 1)
def test_address_change_is_reported(self, get, _resolve):
get.return_value = fake_response(CT_ENTRIES)
self.run_command()
with mock.patch.dict(DNS, {"shop.example.com": ["203.0.113.50"]}):
self.run_command()
self.assertEqual(len(mail.outbox), 2)
self.assertIn("CHANGED shop.example.com", mail.outbox[1].body)
self.assertIn("203.0.113.50", mail.outbox[1].body)
def test_out_of_scope_domain_is_refused(self, get, _resolve):
with self.assertRaisesMessage(CommandError, "Not in scope: example.net"):
call_command("monitor_exposure", "example.net")
get.assert_not_called()
def test_http_failure_leaves_inventory_untouched(self, get, _resolve):
import requests
get.side_effect = requests.ConnectionError("boom")
with self.assertRaises(CommandError):
call_command("monitor_exposure", "example.com", "--min-interval", "0",
stderr=mock.Mock())
self.assertFalse(Asset.objects.exists())
class NameAndDnsTests(TestCase):
def test_extract_names_filters_noise(self):
names = extract_names(CT_ENTRIES, "example.com")
self.assertEqual(names["*.example.com"], True)
self.assertNotIn("user@example.com", names)
self.assertNotIn("m.testexample.com", names)
def test_dangling_cname_detected(self):
resolver = mock.Mock()
cname = mock.Mock()
cname.target.to_text.return_value = "myproject.cdn.example.net."
def answer(name, rtype, lifetime):
if rtype == "CNAME":
return [cname]
raise dns.resolver.NXDOMAIN()
resolver.resolve.side_effect = answer
result = resolve("assets.example.com", resolver)
self.assertEqual(result["status"], Status.DANGLING)
self.assertEqual(result["cname"], "myproject.cdn.example.net")
def test_rate_limiter_sleeps_for_remaining_interval(self):
now = [100.0]
sleeps = []
limiter = RateLimiter(10, clock=lambda: now[0], sleep=sleeps.append)
limiter.wait()
now[0] = 103.0
limiter.wait()
self.assertEqual(sleeps, [7.0])
$ python manage.py test exposure
Found 8 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
........
----------------------------------------------------------------------
Ran 8 tests in 0.041s
OK
Destroying test database for alias 'default'...
The scope test asserts that no HTTP call is made for an out-of-scope domain, and the failure test asserts that a connection error leaves the database empty. Those two properties matter more than any parsing detail, so they deserve explicit tests.
acknowledged, and add it to the formal inventory. Unknown hosts with no owner are the most important finding the monitor can produce.issuer_name against that list.Asset and Observation models do not need to change; only fetch_ct_entries does.stale report section listing assets whose last_seen is older than 120 days, and a test for it.issuer_name against an allowlist of certificate authorities in settings and report certificates from any other issuer as a separate alert category.Asset in the Django admin with filters on status, acknowledged and domain, and make acknowledged editable from the list view.Found a mistake in this tutorial? Let us know and we will fix it.