Google, Yahoo and Microsoft now permanently reject non-compliant bulk senders: 5,000+ messages/day to personal accounts requires SPF + DKIM, a DMARC record, complaints under 0.3%, one-click unsubscribe — Google from February 2024, Microsoft May 5, 2025. The FBI logged $3.05 billion in business email compromise losses in 2025; per a 5.5-million-domain study (October 2026), only 30.4% of domains publish DMARC — 12.8% enforce a policy that blocks spoofing.
That gap is a business. Agencies charge $2,000–$5,000 for deliverability audits (InboxArmy’s published rates, cited by ITWire, October 2026); the work is mostly reading DNS against a rulebook, and DNS is free. This article builds the auditor: one Python script, no API keys, that parses SPF including the redirect= trap, measures DKIM key strength by walking the DER, parses DMARC per RFC 7489 with org-domain fallback, and scores it against the 2024–2026 rulebook. Every line ran clean before publication — mock tests, 15 unit assertions, live DNS queries, all exit 0.
The rulebook
Requirements are near-identical across all three:
- SPF and DKIM must pass — ideally both; each covers the other’s blind spots.
- DMARC with at least
p=none, moving towardquarantine/reject. - Spam rate under 0.3% in Postmaster Tools. Rate, not count: 50,000 emails/day = 150 complaints.
- One-click unsubscribe (RFC 8058 headers) for commercial mail.
Failure isn’t a warning label — it’s permanent rejection.
Why this is engineering, not a checkbox
Compliant-on-paper setups fail four ways, each a real finding:
- The SPF 10-lookup PermError. RFC 7208 caps SPF evaluation at 10 DNS lookups; every
include:anda/mx/existscosts one. Modern stacks glue Workspace + CRM + support desk + billing + marketing together; 12 lookups meansPermError— receivers treat that as if SPF said nothing. The domain looks configured, silently isn’t. - Deprecated DKIM keys. 1024-bit RSA is formally deprecated for signing keys (NIST SP 800-131A rev 2), yet infrastructure still provisions it — the default never changed.
- DMARC
p=noneforever. “Monitor but enforce nothing” is where deployments go to die — it satisfies the letter of the rules while blocking zero spoofing. - The
ruablind spot. Without aggregate report addresses, evenp=rejectenforces blind — it can’t see which legitimate senders fail alignment: exactly how false-positive outages happen.
And it regenerates: B2B contact data decays at roughly 22.5% per year (HubSpot’s widely-cited 2.1%/month figure). Lists rot, infrastructure gets swapped, every swap can break authentication — an audit is a subscription with a technical justification.
The auditor
Read DNS directly with dnspython — no vendor account, no API key — score against the rulebook, and be honest about what heuristic probing can’t see:
pip install dnspython publicsuffix2
SPF: parse, follow redirects, count lookups
The naive version of an SPF check greps for v=spf1. That misses the two failure modes that matter — records that delegate everything via redirect= (Gmail Workspace domains do this), and records that blew past the lookup limit. The tested version:
def parse_spf(record):
"""Parse an SPF record string into a mechanism summary."""
out = {
"all_mechanism": None, # -all, ~all, ?all, +all
"dns_lookups": 0, # counts against the RFC 7208 limit of 10
"redirect": None,
"mechanisms": [],
}
for term in record.split()[1:]: # skip v=spf1
qualifier, body = "+", term
if term and term[0] in "+-~?":
qualifier, body = term[0], term[1:]
lower = body.lower()
if lower == "all":
out["all_mechanism"] = qualifier # no DNS lookup
continue
mech = {"qualifier": qualifier, "type": "unknown", "target": None}
if lower.startswith("include:"):
out["dns_lookups"] += 1
mech.update(type="include", target=body.split(":", 1)[1])
elif lower.startswith("ip4:") or lower.startswith("ip6:"):
mech.update(type=body.split(":", 1)[0], target=body.split(":", 1)[1])
elif lower.split("/")[0].split(":")[0] in ("a", "mx"):
out["dns_lookups"] += 1
mech.update(type=lower.split("/")[0].split(":")[0],
target=body.split(":", 1)[1] if ":" in body else None)
elif lower.startswith(("exists:", "ptr")): # 1 lookup each; ptr is deprecated
out["dns_lookups"] += 1
mech.update(type=lower.split(":", 1)[0], target=None)
elif lower.startswith("redirect="):
out["redirect"] = body.split("=", 1)[1]
out["dns_lookups"] += 1
mech.update(type="redirect", target=out["redirect"])
out["mechanisms"].append(mech)
continue
out["mechanisms"].append(mech)
return out
Fetch follows the redirect and merges lookup counts:
def fetch_spf(domain, resolver, mock=None, depth=0):
"""Fetch and parse SPF for domain, following one redirect= hop.
Returns (parsed, error)."""
if mock is not None:
txts = mock.get((domain, "TXT"), [])
else:
try:
answers = resolver.resolve(domain, "TXT")
txts = [b"".join(r.strings).decode(errors="replace") for r in answers]
except Exception as e:
return None, f"DNS error: {type(e).__name__}"
spf_records = [t for t in txts if t.lower().startswith("v=spf1")]
if not spf_records:
return None, "no SPF record found"
if len(spf_records) > 1:
return None, f"{len(spf_records)} SPF records published - RFC 7208 says treat as PermError"
parsed = parse_spf(spf_records[0])
# A record ending in redirect= without all: policy lives on the target.
if parsed["all_mechanism"] is None and parsed["redirect"] and depth < 1:
target = parsed["redirect"]
redirected, err = fetch_spf(target, resolver, mock, depth + 1)
if err:
return parsed, None
redirected["dns_lookups"] += parsed["dns_lookups"]
return redirected, None
return parsed, None
DMARC: parse per RFC 7489, then find the org-domain fallback
DMARC for mail.example.com can live at _dmarc.mail.example.com or be inherited from _dmarc.example.com — RFC 7489 §6.6.3. Checking only the literal hostname yields false “no DMARC” on every subdomain-sending org:
def fetch_dmarc(domain, resolver, mock=None):
"""DMARC lives at _dmarc.<domain>, with org-domain fallback (RFC 7489 6.6.3)."""
candidates = [f"_dmarc.{domain}"]
sld = get_sld(domain)
if sld and sld != domain:
candidates.append(f"_dmarc.{sld}")
for cand in candidates:
if mock is not None:
txts = mock.get((cand, "TXT"), [])
else:
try:
answers = resolver.resolve(cand, "TXT")
txts = [b"".join(r.strings).decode(errors="replace") for r in answers]
except Exception:
continue
for t in txts:
if t.lower().startswith("v=dmarc1"):
return parse_dmarc(t), cand
return (None, None), None
It also catches record-invalidating mistakes — duplicate tags (RFC 7489: reject the record) and unknown tags, usually vendor-blog copy-paste:
def parse_dmarc(record):
"""Parse a DMARC policy record into a tag dict. Returns (tags, errors)."""
tags, errors, seen = {}, [], set()
for part in record.split(";"):
part = part.strip()
if not part:
continue
if "=" not in part:
errors.append(f"malformed segment: {part!r}")
continue
k, v = part.split("=", 1)
k = k.strip().lower()
if k in seen:
errors.append(f"duplicate tag: {k!r} (RFC 7489 6.6.3: reject the record)")
seen.add(k)
tags[k] = v.strip()
if tags.get("v", "").lower() != "dmarc1":
errors.append(f"v must be DMARC1, got {tags.get('v')!r}")
if "p" not in tags:
errors.append("missing required p= tag")
return tags, errors
DKIM: probe selectors, then measure the key for real
DKIM has no discovery mechanism — the sender picks the selector, it lives in the mail header, DNS alone can’t enumerate it. The honest approach: probe ~40 common selectors (google, selector1, s1, mandrill, …) and say a private selector would be missed.
Most scripts get key strength wrong. p= is base64 of a DER-encoded RSA public key; length is not len(base64) × 4 bits — that lands hundreds of bits off, because DER carries headers and the modulus is signed (leading 00 byte). The tested version walks the DER:
def rsa_modulus_bits(der):
"""Walk a minimal DER SPKI to find the RSA modulus length in bits.
The modulus INTEGER appears as 02 82/81 <len> 00 <bytes> - the leading 00
byte exists because DER integers are signed. Returns None if not found."""
i = 0
while i < len(der) - 4:
if der[i] == 0x02: # INTEGER
if der[i + 1] == 0x82:
n = int.from_bytes(der[i + 2:i + 4], "big")
elif der[i + 1] == 0x81:
n = der[i + 2]
else:
n = der[i + 1]
if n > 32: # RSA moduli are 128+ bytes; skip tiny ints (exponents)
return (n - 1 if der[i + 2 + (2 if der[i + 1] == 0x82 else 1)] == 0 else n) * 8
i += 1
return None
Also caught: empty p= (revoked — that selector signs nothing) and t=y test mode, treated as if the signature never existed.
Scoring against the rulebook
The score is additive: SPF -all +25, live DKIM +25, DMARC reject +30 / quarantine +20 / none +10. Softfail/neutral costs the SPF points entirely; over-limit lookups, ptr, and ≤1024-bit keys get flagged. The point isn’t the number — it’s the ranked findings underneath, which is what the client pays for:
def score_domain(domain, spf, dmarc, dmarc_source, dkim_hits):
"""Apply the bulk-sender rules. Returns (score 0-100, findings)."""
findings, score = [], 0
# --- SPF ---
if spf is None:
findings.append(("CRITICAL", "spf", "No SPF record. Google, Yahoo and Microsoft "
"require a passing SPF or DKIM for all senders since 2024."))
else:
if spf["all_mechanism"] is None:
findings.append(("HIGH", "spf", "SPF has no all mechanism and no redirect "
"carrying one - default result is neutral, so nothing is enforced."))
elif spf["all_mechanism"] in ("~", "?"):
findings.append(("HIGH", "spf", "SPF ends in softfail/neutral (~all or ?all): "
"receivers may still accept mail from servers outside the record."))
elif spf["all_mechanism"] == "+":
findings.append(("CRITICAL", "spf", "SPF ends in +all - this authorizes the "
"entire internet to send as your domain."))
else:
score += 25 # -all
if spf["dns_lookups"] > MAX_DNS_LOOKUPS:
findings.append(("HIGH", "spf",
f"SPF needs {spf['dns_lookups']} DNS lookups; RFC 7208 caps at "
f"{MAX_DNS_LOOKUPS}. Over the limit the record returns PermError and "
"SPF silently stops protecting you."))
if any(m["type"] == "ptr" for m in spf["mechanisms"]):
findings.append(("MEDIUM", "spf", "ptr mechanism present: deprecated, slow, "
"and rarely resolves the way people expect."))
# --- DKIM ---
live = [d for d in dkim_hits if d["key_type"] == "rsa"]
revoked = [d for d in dkim_hits if d["key_type"] == "revoked"]
if live:
score += 25
for d in live:
if d["modulus_bits"] and d["modulus_bits"] <= 1024:
findings.append(("MEDIUM", "dkim",
f"selector {d['selector']}: RSA modulus measures "
f"{d['modulus_bits']} bits. 1024-bit RSA is deprecated for "
"signing keys (NIST SP 800-131A rev 2)."))
if d["test_mode"]:
findings.append(("INFO", "dkim",
f"selector {d['selector']}: t=y test mode. Receivers treat "
"signatures as if they never existed."))
elif revoked:
findings.append(("MEDIUM", "dkim", "Only revoked (p= empty) DKIM keys found - "
"publishing p= with no live key means no DKIM at all."))
else:
findings.append(("MEDIUM", "dkim",
f"No DKIM key found on {len(COMMON_SELECTORS)} common selectors. "
"Heuristic probe - a private selector would be missed, verify in your "
"sending platform before treating this as a failure."))
# --- DMARC ---
if dmarc is None:
findings.append(("CRITICAL", "dmarc", "No DMARC record. Required for "
"5,000+/day senders to Google, Yahoo and Microsoft."))
else:
p = (dmarc.get("p") or "").lower()
if p == "reject":
score += 30
elif p == "quarantine":
score += 20
elif p == "none":
findings.append(("MEDIUM", "dmarc", "p=none monitors but enforces nothing. "
"A rollout phase, not a destination."))
score += 10
else:
findings.append(("CRITICAL", "dmarc", f"p={p!r} is not a valid policy."))
if not dmarc.get("rua"):
findings.append(("MEDIUM", "dmarc", "No rua= aggregate reports. You are "
"enforcing blind - you cannot see who fails authentication, or why."))
pct = dmarc.get("pct", "")
if pct and pct.isdigit() and int(pct) < 100 and p in ("quarantine", "reject"):
findings.append(("INFO", "dmarc",
f"pct={pct}: only {pct}% of failing mail gets the policy applied."))
if (dmarc.get("sp") or "").lower() == "none":
findings.append(("INFO", "dmarc", "sp=none: subdomains stay unprotected - "
"attackers spoof mail.sub.example.com even with the apex locked."))
if dmarc_source and dmarc_source != f"_dmarc.{domain}":
findings.append(("INFO", "dmarc",
f"DMARC inherited from {dmarc_source} (org-domain fallback)."))
if dmarc.get("adkim") == "s" and dmarc.get("aspf") == "s":
findings.append(("INFO", "dmarc", "adkim=s and aspf=s (strict alignment). "
"Tighter than most; watch your reports after tightening."))
return min(score, 100), findings
Proof it runs
Mock fixtures use real 1024-/2048-bit RSA keys from OpenSSL (the DER walk gets exercised for real) and must rank strictly: wide-open < half-configured < example-sender. Unit tests cover redirect-following, the PermError path, duplicate tags, org-domain inheritance, and modulus measurement:
$ python3 auth_audit.py mock
=== example-sender.com - score 80/100 ===
[INFO ] dmarc adkim=s and aspf=s (strict alignment)...
=== half-configured.com - score 35/100 ===
[HIGH ] spf SPF ends in softfail/neutral (~all or ?all)...
[MEDIUM ] dkim selector default: RSA modulus measures 1024 bits...
[MEDIUM ] dmarc p=none monitors but enforces nothing...
[MEDIUM ] dmarc No rua= reports...
=== wide-open.com - score 0/100 ===
[CRITICAL] spf SPF ends in +all...
[MEDIUM ] dkim Only revoked (p= empty) DKIM keys found...
[CRITICAL] dmarc No DMARC record...
mock ranking assertion passed
[{"domain": "example-sender.com", "score": 80},
{"domain": "half-configured.com", "score": 35},
{"domain": "wide-open.com", "score": 0}]
$ python3 test_units.py # 15 assertions - ALL PASSED (exit 0)
Then live, four real domains (auth_audit.py live gmail.com stripe.com coinbase.com dropbox.com, exit 0):
| Domain | Score | What the auditor actually found |
|---|---|---|
| gmail.com | 10/100 | Apex SPF is softfail; DMARC p=none |
| stripe.com | 55/100 | SPF softfail; 1024-bit DKIM keys on 4 selectors (google, s1, s2, mandrill) |
| coinbase.com | 80/100 | -all, enforced DMARC, strict alignment — but still 1024-bit keys on 3 selectors |
| dropbox.com | 55/100 | SPF softfail |
Read it twice. Stripe and Coinbase — among the most compliance-obsessed companies alive — sign mail with RSA keys NIST deprecates. Gmail’s own apex runs p=none. This is a nobody-looked problem, the exact shape of a sellable audit. (Fairness note: bulk mail goes from dedicated subdomains like em.stripe.com — the apex score isn’t their deliverability score. The findings are still real.)
The fix playbook (what you actually deliver)
The fixes, in order:
- Inventory every legitimate sender. Marketing, CRM, support desk, billing, transactional — each needs DKIM enabled and its
include:added to SPF, or dropped to align via DKIM. - Fix SPF mechanics: collapse includes under 10 lookups (static
ip4:CIDRs), killptr, end-all. - Rotate DKIM keys to 2048-bit with a calendar. The finding everyone misses — tools check existence, not strength.
- DMARC in stages:
p=none; rua=...for 2–4 weeks → fix what reports surface →p=quarantine; pct=25→ raisepct→p=reject. Thepctdial keeps enforcement from nuking legit mail. - Warm domains before volume. New domains need 2–4 weeks of ramped sending before cold outreach at scale (Warmy; Reachly: 30 days minimum).
Where the money is
The economics: an agency audit runs $2,000–$5,000; the work is DNS reads plus a rulebook — the script above is the 90% case, the human 10% (sender inventory, report) fits in a day, and at $150–$500 per SMB audit you undercut agencies 10x. The retainer comes from the rua stream: daily XML aggregate reports plus a monthly “who’s failing and what changed” summary. One honest caveat: the selector probe is heuristic — a private-selector domain needs a five-minute manual check. Say so in the report; that’s what makes it trustworthy enough to renew.
Full source is tested and reproducible: auth_audit.py mock, test_units.py, auth_audit.py live <domain> — all exit 0.
Want this run against your domain, or wired into your own sending stack? Email [email protected] — details on the hire-us page.