DKIM / SPF / DMARC Builder & Checker — Python source
Build the three email-authentication DNS records — SPF, DKIM, and DMARC — as ready-to-paste TXT values, or look up a domain's live records over DNS-over-HTTPS. Import existing records, catch publishing mistakes, share via URL. Entirely client-side.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""dkim-spf-dmarc — Email authentication (SPF / DKIM / DMARC) record parsing and lookup.
Language: Python 3 (standard library only — urllib.request + json for the
DNS-over-HTTPS lookup, base64 for the DKIM key; the parsers
themselves need nothing).
CosmoDev polyglot showcase port of the `dkim-spf-dmarc` tool, ported from
src/lib/dkim-spf-dmarc.ts (the canonical TypeScript implementation).
Two layers, mirroring the TypeScript reference:
- Pure parsers (parse_spf / parse_dkim / parse_dmarc) — deterministic, never
raise, testable without network.
- Check functions (check_spf / check_dkim / check_dmarc) — one
DNS-over-HTTPS request to Cloudflare's public resolver, then a pure parse.
CosmoDev runs no backend for this tool.
Specs: SPF RFC 7208, DKIM RFC 6376, DMARC RFC 7489.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import base64
import binascii
import json
import re
import urllib.parse
import urllib.request
DOMAIN_RE = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$")
SELECTOR_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$", re.IGNORECASE)
SPF_KINDS = ("all", "include", "a", "mx", "ip4", "ip6", "exists", "ptr")
SPF_LOOKUP_KINDS = frozenset(("include", "a", "mx", "exists", "ptr"))
DMARC_POLICIES = ("none", "quarantine", "reject")
DOH_ENDPOINT = "https://cloudflare-dns.com/dns-query"
def normalize_domain(raw: str) -> str:
"""Strip a leading scheme, userinfo, path, query, port, and trailing dot."""
s = (raw or "").strip()
s = re.sub(r"^[a-z][a-z0-9+.-]*://", "", s, flags=re.IGNORECASE) # scheme://
s = re.sub(r"^mailto:", "", s, flags=re.IGNORECASE) # mailto:user@domain
if "@" in s: # keep host of user@host
s = s[s.rindex("@") + 1:]
s = s.split("/")[0].split("?")[0].split(":")[0] # drop path, query, port
s = re.sub(r"\.+$", "", s) # trailing dot(s)
return s.lower()
def is_domain_like(domain: str) -> bool:
"""True when the string looks like a plausible multi-label domain."""
return bool(DOMAIN_RE.match(domain)) and len(domain) <= 253
def is_valid_selector(selector: str) -> bool:
"""True when the selector is a safe DNS label chain (no traversal)."""
s = selector.strip()
return 0 < len(s) <= 100 and bool(SELECTOR_RE.match(s)) and ".." not in s
def _unquote(value: str) -> str:
"""Strip one layer of surrounding double quotes, as TXT records carry."""
return re.sub(r'^"(.*)"$', r"\1", value, flags=re.DOTALL)
def _parse_tag_list(txt: str, warnings: list[str]) -> dict[str, str]:
"""Split a `k=v; k=v` tag list into a dict, recording malformed terms."""
tags: dict[str, str] = {}
for part in txt.split(";"):
term = _unquote(part.strip()).strip()
if not term:
continue
eq = term.find("=")
if eq <= 0:
warnings.append(f'Malformed tag "{term}" ignored.')
continue
tags[term[:eq].strip().lower()] = term[eq + 1:].strip()
return tags
def _colon_list(value: str | None) -> list[str]:
return [p.strip() for p in (value or "").split(":") if p.strip()]
def _comma_list(value: str | None) -> list[str]:
return [p.strip() for p in (value or "").split(",") if p.strip()]
def parse_spf(txt: str) -> dict:
"""Parse one or more (newline-joined) TXT record strings for SPF. Pure."""
lines = [_unquote(line.strip()) for line in (txt or "").split("\n")]
spf_lines = [line for line in lines if line and re.match(r"^v=spf1(\s|$)", line, re.IGNORECASE)]
warnings: list[str] = []
if not spf_lines:
return {"valid": False, "mechanisms": [], "lookup_count": 0, "record_count": 0,
"warnings": ["No v=spf1 record found in the supplied text."]}
if len(spf_lines) > 1:
warnings.append(f"{len(spf_lines)} SPF records found — RFC 7208 allows exactly one. "
"Receivers treat this as a permanent error and ignore SPF for the whole domain.")
terms = spf_lines[0].split()
mechanisms: list[dict] = []
redirect = exp = None
for term in terms[1:]:
modifier = re.match(r"^([a-z][a-z0-9-]*)=(.*)$", term, re.IGNORECASE)
if modifier:
name = modifier.group(1).lower()
if name == "redirect":
redirect = modifier.group(2)
elif name == "exp":
exp = modifier.group(2)
else:
warnings.append(f'Unknown modifier "{term}" ignored.')
continue
m = re.match(r"^([+\-~?])?([a-z0-9]+)(?::(.*))?$", term, re.IGNORECASE | re.DOTALL)
if not m:
warnings.append(f'Unrecognized term "{term}" ignored.')
continue
qualifier, kind, value = m.group(1) or "+", m.group(2).lower(), m.group(3)
if kind not in SPF_KINDS:
warnings.append(f'Unknown mechanism "{term}" ignored.')
continue
if not value and kind in ("include", "exists"):
warnings.append(f'Mechanism "{term}" is missing its required value.')
continue
mechanisms.append({"qualifier": qualifier, "kind": kind, "value": value})
lookup_count = sum(1 for mech in mechanisms if mech["kind"] in SPF_LOOKUP_KINDS) + (1 if redirect else 0)
all_mech = next((mech for mech in mechanisms if mech["kind"] == "all"), None)
if not all_mech and not redirect:
warnings.append('No "all" mechanism and no "redirect=" — unmatched senders get a Neutral '
"result, so anyone can still send mail that looks like this domain.")
if all_mech and all_mech["qualifier"] == "+":
warnings.append('"+all" explicitly allows every host on the internet to send mail as this '
"domain — this defeats SPF entirely.")
elif all_mech and all_mech["qualifier"] == "?":
warnings.append('"?all" (Neutral) lets unmatched senders through with no protection. '
'Prefer "~all" or "-all".')
if any(mech["kind"] == "ptr" for mech in mechanisms):
warnings.append('The "ptr" mechanism is deprecated (RFC 7208 §5.5) and should not be used.')
if redirect and all_mech:
warnings.append('A "redirect=" modifier is ignored when an "all" mechanism is present.')
if lookup_count > 10:
warnings.append(f"{lookup_count} DNS-lookup mechanisms — RFC 7208 §4.6.4 caps SPF at 10. "
"Receivers that hit the cap return permerror and ignore the record.")
return {"valid": True, "version": terms[0], "mechanisms": mechanisms, "redirect": redirect,
"exp": exp, "lookup_count": lookup_count, "record_count": len(spf_lines),
"warnings": warnings}
def _decode_base64_lenient(b64: str) -> bytes | None:
"""Decode base64 without raising on bad input; missing padding is added."""
clean = re.sub(r"\s+", "", b64)
try:
return base64.b64decode(clean + "=" * ((4 - len(clean) % 4) % 4), validate=True)
except (binascii.Error, ValueError):
return None
def parse_dkim(txt: str) -> dict:
"""Parse a `<selector>._domainkey` TXT record. Pure."""
warnings: list[str] = []
tags = _parse_tag_list(txt or "", warnings)
version = tags.get("v")
if version and version.upper() != "DKIM1":
warnings.append(f"Unusual version tag v={version} (expected DKIM1).")
key_type = tags.get("k", "rsa")
p = tags.get("p")
hashes, services, flags = _colon_list(tags.get("h")), _colon_list(tags.get("s")), _colon_list(tags.get("t"))
record: dict = {"valid": True, "key_type": key_type, "hashes": hashes,
"services": services, "flags": flags, "warnings": warnings}
if version:
record["version"] = version.upper()
if p is None:
record["valid"] = False
warnings.append("No p= tag — this record is not a usable DKIM key.")
return record
if p == "":
warnings.append("p= is empty — the key is revoked. Receivers will treat mail signed "
"with this selector as unsigned.")
return record
decoded = _decode_base64_lenient(p)
if decoded is None:
warnings.append("The p= value is not valid base64 — the key could not be read.")
return record
record["public_key"] = re.sub(r"\s+", "", p)
if key_type == "rsa":
# SubjectPublicKeyInfo DER ≈ modulus bits/8 + ~24 bytes of ASN.1 overhead.
bits = max(0, len(decoded) - 24) * 8
record["key_bits"] = bits
if bits < 1024:
warnings.append(f"Weak RSA key (~{bits} bits). Keys under 1024 bits are considered "
"breakable; RFC 8301 discourages short keys.")
elif bits < 2048:
warnings.append(f"RSA key of ~{bits} bits works today but is below the recommended "
"2048 bits (RFC 8301).")
if "y" in flags:
warnings.append("t=y — the key is in test mode: receivers must treat signatures as if unsigned.")
if "s" in flags:
warnings.append("t=s — strict domain matching: the key cannot be used for subdomain "
"signatures (informational).")
return record
def parse_dmarc(txt: str) -> dict:
"""Parse a `_dmarc` TXT record. Pure."""
warnings: list[str] = []
tags = _parse_tag_list(txt or "", warnings)
record: dict = {"valid": True, "aggregate_uris": [], "forensic_uris": [], "warnings": warnings}
version = tags.get("v")
if not version:
record["valid"] = False
warnings.append("No v= tag — this is not a DMARC record.")
return record
if version.upper() != "DMARC1":
record["valid"] = False
warnings.append(f"Unknown version v={version} (expected DMARC1).")
return record
policy = (tags.get("p") or "").lower()
if not policy:
record["valid"] = False
warnings.append("No p= policy tag — DMARC requires it.")
return record
if policy not in DMARC_POLICIES:
record["valid"] = False
warnings.append(f"Invalid policy p={policy} (expected none, quarantine, or reject).")
return record
record["policy"] = policy
sp = (tags.get("sp") or "").lower()
if sp:
if sp in DMARC_POLICIES:
record["subdomain_policy"] = sp
else:
warnings.append(f"Invalid sp={sp} ignored (expected none, quarantine, or reject).")
record["aggregate_uris"] = _comma_list(tags.get("rua"))
record["forensic_uris"] = _comma_list(tags.get("ruf"))
pct = tags.get("pct")
if pct is not None:
if re.fullmatch(r"\d+", pct) and 0 <= int(pct) <= 100:
record["percent"] = int(pct)
else:
warnings.append(f"Invalid pct={pct} ignored (must be 0-100).")
for tag, key in (("adkim", "dkim_alignment"), ("aspf", "spf_alignment")):
value = tags.get(tag)
if value:
if value in ("r", "s"):
record[key] = value
else:
warnings.append(f"Invalid {tag}={value} ignored (expected r or s).")
if record["policy"] == "none":
warnings.append("p=none is monitor-only — no mail is quarantined or rejected, but you "
"still need SPF/DKIM to pass for reports to be useful.")
if not record["aggregate_uris"]:
warnings.append("No rua= address — without aggregate reports you cannot see who is "
"failing authentication. Add rua=mailto:reports@example.com.")
elif record["forensic_uris"]:
warnings.append("ruf= (forensic reports) is supported by few receivers and may leak "
"message content to the report address (informational).")
percent = record.get("percent")
if percent is not None and percent < 100 and record["policy"] != "none":
warnings.append(f"pct={percent} applies the policy to only {percent}% of mail — "
f"the other {100 - percent}% is unaffected.")
return record
def _query_txt(name: str) -> list[str]:
"""Query TXT records via Cloudflare's DoH JSON API. Returns unquoted strings."""
url = f"{DOH_ENDPOINT}?name={urllib.parse.quote(name, safe='')}&type=TXT"
request = urllib.request.Request(url, headers={"Accept": "application/dns-json"})
with urllib.request.urlopen(request, timeout=10) as response:
if response.status != 200:
raise RuntimeError(f"DNS resolver responded with HTTP {response.status}.")
body = json.loads(response.read().decode("utf-8"))
if body.get("Status") == 3:
return [] # NXDOMAIN — no such domain
if body.get("Status") != 0:
raise RuntimeError(f"DNS query failed with status {body.get('Status')}.")
return [_unquote(str(answer["data"])).replace('" "', "") # multi-chunk TXT
for answer in body.get("Answer", []) if answer.get("type") == 16]
def _fail(message: str) -> dict:
return {"status": "fail", "found": False, "message": message}
def check_spf(domain: str) -> dict:
"""Look up and evaluate a domain's SPF record."""
host = normalize_domain(domain)
if not is_domain_like(host):
return _fail("Enter a valid domain, e.g. example.com.")
try:
record = parse_spf("\n".join(_query_txt(host)))
except Exception as exc: # network/JSON errors degrade to a fail result
return _fail(str(exc) or "DNS lookup failed.")
if not record["valid"]:
return _fail(f"No SPF record found for {host}. Receivers cannot verify which "
"servers may send mail for it.")
status = "warn" if record["warnings"] else "pass"
message = "SPF record found and looks healthy." if status == "pass" else None
return {"status": status, "found": True, "record": record, "message": message}
def check_dkim(domain: str, selector: str) -> dict:
"""Look up and evaluate a domain's DKIM public key for one selector."""
host = normalize_domain(domain)
if not is_domain_like(host):
return _fail("Enter a valid domain, e.g. example.com.")
sel = selector.strip().lower()
if not is_valid_selector(sel):
return _fail("Enter a valid selector (letters, digits, dots, hyphens, underscores).")
try:
record = parse_dkim("\n".join(_query_txt(f"{sel}._domainkey.{host}")))
except Exception as exc:
return _fail(str(exc) or "DNS lookup failed.")
if not record["valid"]:
return _fail(f"No DKIM record found at {sel}._domainkey.{host}. Try another "
"selector — only one is checked per lookup.")
revoked = any("revoked" in w for w in record["warnings"])
status = "fail" if revoked else ("warn" if record["warnings"] else "pass")
return {"status": status, "found": True, "record": record}
def check_dmarc(domain: str) -> dict:
"""Look up and evaluate a domain's DMARC policy."""
host = normalize_domain(domain)
if not is_domain_like(host):
return _fail("Enter a valid domain, e.g. example.com.")
try:
record = parse_dmarc("\n".join(_query_txt(f"_dmarc.{host}")))
except Exception as exc:
return _fail(str(exc) or "DNS lookup failed.")
if not record["valid"]:
return _fail(f"No DMARC record found at _dmarc.{host}. Receivers have no policy "
"to apply when SPF or DKIM fails.")
status = "warn" if record["warnings"] else "pass"
return {"status": status, "found": True, "record": record}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →