DEV Community

developer
developer

Posted on

Automating SPF & DMARC DNS Health Audits with dnspython

Why a DNS health audit matters

When you ship cold‑email at scale—like the 2,305 messages sent from our production stack—every rejected envelope costs reputation and revenue. SPF and DMARC are the first line of defense; a missing or malformed TXT record can cause a 550 rejection before the message even reaches the recipient's spam filter. Automating the audit lets you catch misconfigurations during domain onboarding (the OutboundOS platform supports bulk onboarding of 1‑100+ domains) and prevents silent bounce spikes that would otherwise inflate the 219 suppressed addresses we see in the wild.

Core audit requirements

  • Fetch the domain’s MX, SPF (v=spf1) and DMARC (v=DMARC1) TXT records.
  • Validate syntax against RFC 7208 (SPF) and RFC 7489 (DMARC).
  • Cross‑check that the SPF policy authorizes the outbound IP ranges you actually use.
  • Report a health score that downstream services (e.g., GET /api/accounts/dns-health) can consume.

Minimal dnspython wrapper

The dnspython library gives us low‑level DNS resolution without external binaries. Below is a production‑ready helper that returns a dictionary of raw TXT values and a list of validation warnings.

import dns.resolver
import re
from typing import Dict, List, Tuple

# RFC‑compliant regexes – trimmed for readability
SPF_RE = re.compile(r"^v=spf1(?:\s+(?:\+|\-)?[a-z]+(?:[:=][^\s]+)?)*)\s+~?all$")
DMARC_RE = re.compile(r"^v=DMARC1;\s*(?:p=none|p=quarantine|p=reject);.*$")

def fetch_txt(name: str) -> List[str]:
    """Return all TXT strings for *name* or an empty list on NXDOMAIN."""
    try:
        answers = dns.resolver.resolve(name, "TXT", raise_on_no_answer=False)
        return [b"".join(r.strings).decode() for r in answers]
    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.exception.Timeout):
        return []

def audit_spf(domain: str) -> Tuple[str, List[str]]:
    txts = fetch_txt(domain)
    spf_records = [t for t in txts if t.lower().startswith("v=spf1")]
    warnings = []
    if not spf_records:
        warnings.append("No SPF record found.")
        return "none", warnings
    # Prefer the first record – multiple SPF records are a configuration error.
    spf = spf_records[0]
    if not SPF_RE.match(spf):
        warnings.append("SPF syntax invalid.")
    # Simple IP check – replace with your actual outbound CIDR list.
    allowed_ips = {"192.0.2.0/24", "198.51.100.0/24"}
    ip_mechs = re.findall(r"ip4:([0-9.]+/[0-9]+)", spf)
    if not set(ip_mechs) & allowed_ips:
        warnings.append("SPF does not include any authorized outbound IPs.")
    return spf, warnings

def audit_dmarc(domain: str) -> Tuple[str, List[str]]:
    txts = fetch_txt(f"_dmarc.{domain}")
    dmarc_records = [t for t in txts if t.lower().startswith("v=dmarc1")]
    warnings = []
    if not dmarc_records:
        warnings.append("No DMARC record found.")
        return "none", warnings
    dmarc = dmarc_records[0]
    if not DMARC_RE.match(dmarc):
        warnings.append("DMARC syntax invalid.")
    # Ensure a policy is set (reject is strongest).
    if "p=reject" not in dmarc:
        warnings.append("DMARC policy is not set to 'reject'.")
    return dmarc, warnings

def audit_domain(domain: str) -> Dict:
    spf, spf_warn = audit_spf(domain)
    dmarc, dmarc_warn = audit_dmarc(domain)
    mx = fetch_txt(domain)  # MX records are fetched elsewhere; placeholder.
    health = {
        "domain": domain,
        "spf": spf,
        "spf_warnings": spf_warn,
        "dmarc": dmarc,
        "dmarc_warnings": dmarc_warn,
        "overall_score": 100 - 20 * (len(spf_warn) + len(dmarc_warn)),
    }
    return health
Enter fullscreen mode Exit fullscreen mode

Storing audit results – a tiny SQLite schema

OutboundOS persists per‑domain health so the UI can surface a red‑flag badge. The following snippet shows a pragmatic schema and an upsert helper.

import sqlite3
from datetime import datetime

SCHEMA = """
CREATE TABLE IF NOT EXISTS dns_audit (
    domain TEXT PRIMARY KEY,
    spf TEXT,
    spf_warnings TEXT,
    dmarc TEXT,
    dmarc_warnings TEXT,
    score INTEGER,
    last_checked TIMESTAMP
);
"""

def init_db(path: str = "dns_audit.db") -> sqlite3.Connection:
    conn = sqlite3.connect(path)
    conn.executescript(SCHEMA)
    return conn

def upsert_audit(conn: sqlite3.Connection, audit: dict) -> None:
    sql = """
    INSERT INTO dns_audit (domain, spf, spf_warnings, dmarc, dmarc_warnings, score, last_checked)
    VALUES (:domain, :spf, :spf_warnings, :dmarc, :dmarc_warnings, :overall_score, :ts)
    ON CONFLICT(domain) DO UPDATE SET
        spf = excluded.spf,
        spf_warnings = excluded.spf_warnings,
        dmarc = excluded.dmarc,
        dmarc_warnings = excluded.dmarc_warnings,
        score = excluded.score,
        last_checked = excluded.last_checked;
    """
    audit["ts"] = datetime.utcnow().isoformat()
    conn.execute(sql, audit)
    conn.commit()
Enter fullscreen mode Exit fullscreen mode

Integrating with the OutboundOS API surface

The platform already exposes GET /api/accounts/dns-health, which expects a JSON payload matching the audit_domain output. A thin Flask view can wire the helper directly:

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route("/api/accounts/dns-health", methods=["POST"])
def dns_health():
    domains = request.json.get("domains", [])
    results = [audit_domain(d) for d in domains]
    conn = init_db()
    for r in results:
        upsert_audit(conn, r)
    return jsonify({"audits": results})
Enter fullscreen mode Exit fullscreen mode

Common pitfalls and how we mitigated them

Pitfall Symptom Fix
Multiple SPF TXT records SPF validation passes but mail servers reject with "multiple SPF records" The audit stops after the first record and adds a warning if len(spf_records) > 1.
DNS timeout on large provider lists Audits stall for >30 s, causing API timeouts Use dns.resolver.Resolver(lifetime=5) and fall back to cached results.
Null MX (.) handling MX lookup returns a single dot, which is valid per RFC 7505 but our code treats it as missing Treat a single . as a legitimate MX entry and skip MX‑related warnings.
Internationalized domain names (IDN) dns.resolver raises UnicodeError Encode with idna (domain.encode('idna').decode()) before lookup.

Running the audit at scale

OutboundOS can onboard up to 100 domains in a single request. To keep the 2.5‑minute IMAP poller responsive, we parallelise DNS queries with a thread pool:

from concurrent.futures import ThreadPoolExecutor, as_completed

def bulk_audit(domains: List[str]) -> List[dict]:
    with ThreadPoolExecutor(max_workers=20) as pool:
        future_map = {pool.submit(audit_domain, d): d for d in domains}
        results = []
        for fut in as_completed(future_map):
            try:
                results.append(fut.result())
            except Exception as exc:
                results.append({"domain": future_map[fut], "error": str(exc)})
    return results
Enter fullscreen mode Exit fullscreen mode

The thread count of 20 balances the typical 100‑domain batch against the 1‑second average DNS response time observed on Oracle Cloud's Always Free ARM64 instance.

Putting the health score to work

The overall_score (0‑100) feeds two downstream controls:

  1. Domain gating – any domain below 60 is automatically excluded from the daily 30‑35 cold‑email cap.
  2. RevOps dashboard – the GET /api/revops/executive-summary endpoint aggregates scores to surface a deliverability health KPI for the executive team.

Because the audit runs nightly, a sudden dip (e.g., after a DNS provider change) surfaces in the same 14‑day aged‑domain ramp that already limits volume, preventing a spike in the 219 bounced‑address suppression metric.

TL;DR checklist

  • Use dnspython to pull SPF and DMARC TXT records.
  • Validate against RFC regexes; warn on multiple records.
  • Cross‑reference SPF IP mechanisms with your outbound CIDR blocks.
  • Persist results in a lightweight SQLite table (or your preferred store).
  • Parallelise for bulk onboarding; respect DNS timeouts.
  • Feed the health score into domain gating and RevOps reporting.

If you want to inspect or fork the full production implementation, it lives inside OutboundOS on GitHub: https://github.com/ansh1325/OutboundOS


⭐ If this helped, please star the open-source repo on GitHub: ansh1325/OutboundOS (MIT Licensed — PRs & feedback welcome!)

Top comments (0)