"""spf-dkim-dmarc-explained-rfc-9989.py — read the SPF, DKIM and DMARC records of a domain you run. What it does, for one domain: SPF finds the v=spf1 record, follows include: and redirect= through DNS, and counts the terms that cost a DNS lookup (include, a, mx, ptr, exists, redirect). RFC 7208 Sec. 4.6.4 caps that count at 10; a check that reaches an 11th such term ends in "permerror", and a sender that matches nothing in the record always gets that far. It also flags more than one SPF record, "+all", "ptr", a missing "all", and a redirect that "all" makes dead. DMARC finds the policy record the way RFC 9989 (May 2026) says a receiver does: _dmarc. first, then the "DNS Tree Walk" (Sec. 4.10) up the parent names, at most eight queries. It parses the record against the RFC 9989 tag list and flags the tags RFC 9989 retired (pct, rf, ri), a missing p=, missing rua=, and what t=y does to the policy. DKIM for each selector you name, reads ._domainkey., decodes the public key and reports its size: RFC 8301 says verifiers MUST NOT accept RSA keys under 1024 bits and signers SHOULD use at least 2048. It only sends DNS TXT queries (UDP port 53, TCP if the answer is truncated) to the resolver you choose. It does not send mail, connect to mail servers, or contact anything else. Run it against domains you own or administer. DKIM selectors are not discoverable from DNS; find yours in the DKIM-Signature header (the s= tag) of a message your domain sent. Inputs: domain the domain to check --selector NAME a DKIM selector (repeat for several) --resolver IP a recursive resolver (default 1.1.1.1; use your own if you prefer) --selftest run the offline checks built from the RFC examples; no network --demo print the report for a made-up domain with common faults; no network Run: python spf-dkim-dmarc-explained-rfc-9989.py --selftest python spf-dkim-dmarc-explained-rfc-9989.py --demo python spf-dkim-dmarc-explained-rfc-9989.py your-domain.example --selector s1 Standard library only. Tested with Python 3.13. """ import argparse import base64 import binascii import ipaddress import random import re import socket import struct import sys # ----------------------------------------------------------------------------- DNS (TXT only) --- NOERROR, NXDOMAIN = 0, 3 def _encode_name(name): out = b"" for label in name.rstrip(".").split("."): raw = label.encode("idna") if label else b"" if not raw or len(raw) > 63: raise ValueError(f"bad DNS label in {name!r}") out += bytes([len(raw)]) + raw return out + b"\x00" def _skip_name(msg, pos): while True: n = msg[pos] if n == 0: return pos + 1 if n & 0xC0 == 0xC0: # compression pointer: two bytes, ends the name return pos + 2 pos += 1 + n def dns_txt(name, resolver="1.1.1.1", timeout=5.0): """Return (rcode, [txt, ...]) for the TXT records at name. Each record's character-strings are joined with no separator (RFC 7208 Sec. 3.3; RFC 6376 Sec. 3.6.2.2).""" qid = random.randrange(65536) query = struct.pack(">HHHHHH", qid, 0x0100, 1, 0, 0, 0) + _encode_name(name) + struct.pack(">HH", 16, 1) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.settimeout(timeout) s.sendto(query, (resolver, 53)) msg = s.recv(4096) if struct.unpack(">H", msg[2:4])[0] & 0x0200: # TC bit: answer truncated, ask again over TCP with socket.create_connection((resolver, 53), timeout=timeout) as s: s.sendall(struct.pack(">H", len(query)) + query) need = struct.unpack(">H", _recv_exact(s, 2))[0] msg = _recv_exact(s, need) rid, flags, qd, an = struct.unpack(">HHHH", msg[:8]) if rid != qid: raise RuntimeError("DNS reply id mismatch") pos = 12 for _ in range(qd): pos = _skip_name(msg, pos) + 4 txts = [] for _ in range(an): pos = _skip_name(msg, pos) rtype, _rclass, _ttl, rdlen = struct.unpack(">HHIH", msg[pos:pos + 10]) pos += 10 rdata = msg[pos:pos + rdlen] pos += rdlen if rtype != 16: continue # e.g. the CNAME a provider-hosted _dmarc name points through parts, i = [], 0 while i < len(rdata): ln = rdata[i] parts.append(rdata[i + 1:i + 1 + ln]) i += 1 + ln txts.append(b"".join(parts).decode("utf-8", "replace")) return flags & 0x000F, txts def _recv_exact(s, n): buf = b"" while len(buf) < n: chunk = s.recv(n - len(buf)) if not chunk: raise RuntimeError("DNS TCP connection closed early") buf += chunk return buf # ------------------------------------------------------------------------------------- SPF --- SPF_MECHANISMS = {"all", "include", "a", "mx", "ptr", "ip4", "ip6", "exists"} LOOKUP_TERMS = {"include", "a", "mx", "ptr", "exists", "redirect"} # RFC 7208 Sec. 4.6.4 def spf_records(txts): return [t for t in txts if t.lower() == "v=spf1" or t.lower().startswith("v=spf1 ")] def parse_spf(record): """Split a v=spf1 record into (qualifier, name, argument, is_modifier) terms; raise ValueError on syntax the RFC 7208 grammar does not allow (which makes the whole check a permerror).""" terms = [] for raw in record.split()[1:]: m = re.fullmatch(r"([A-Za-z][A-Za-z0-9._-]*)=(.*)", raw) if m: terms.append(("", m.group(1).lower(), m.group(2), True)) continue q = raw[0] if raw[0] in "+-~?" else "" body = raw[1:] if q else raw m = re.fullmatch(r"([A-Za-z0-9]+)([:/].*)?", body) if not m or m.group(1).lower() not in SPF_MECHANISMS: raise ValueError(f"unknown or malformed term {raw!r}") name, arg = m.group(1).lower(), (m.group(2) or "") if name in ("ip4", "ip6"): try: net = ipaddress.ip_network(arg[1:], strict=False) except ValueError: raise ValueError(f"bad address in {raw!r}") from None if (name == "ip4") != (net.version == 4): raise ValueError(f"{name} with a version-{net.version} address in {raw!r}") if name in ("include", "exists") and not arg.startswith(":"): raise ValueError(f"{name} needs a domain: {raw!r}") terms.append((q or "+", name, arg[1:] if arg.startswith(":") else arg, False)) return terms def check_spf(domain, lookup, _seen=None, _depth=0): """Walk the SPF record at domain and everything it includes or redirects to. Returns dict(lookups, void, lines, problems). lookups counts every DNS-lookup term in the worst case (all terms evaluated), which is how the 10-term limit is exceeded in practice.""" seen = _seen if _seen is not None else set() out = {"lookups": 0, "void": 0, "lines": [], "problems": []} pad = " " * _depth if domain.lower() in seen: out["problems"].append(f"{domain}: loop, already visited") return out seen.add(domain.lower()) rcode, txts = lookup(domain) recs = spf_records(txts) if rcode == NXDOMAIN or not recs: out["void"] += 1 if (rcode == NXDOMAIN or not txts) else 0 out["lines"].append(f"{pad}{domain}: no SPF record") out["problems"].append(f"{domain}: no SPF record (as an include or redirect target this is a permerror)" if _depth else f"{domain}: no SPF record, so SPF returns 'none'") return out if len(recs) > 1: out["problems"].append(f"{domain}: {len(recs)} SPF records; RFC 7208 Sec. 4.5 makes that a permerror") rec = recs[0] out["lines"].append(f"{pad}{domain}: {rec}") try: terms = parse_spf(rec) except ValueError as e: out["problems"].append(f"{domain}: syntax error, permerror ({e})") return out names = [t[1] for t in terms] has_all = "all" in names if has_all: cut = names.index("all") if any(not t[3] for t in terms[cut + 1:]): out["problems"].append(f"{domain}: mechanisms after 'all' are never tested") qual = terms[cut][0] if _depth == 0: out["all"] = qual + "all" if qual == "+": out["problems"].append(f"{domain}: '+all' authorises every host on the internet") elif qual == "?": out["problems"].append(f"{domain}: '?all' makes unlisted senders 'neutral', not a failure") for q, name, arg, is_mod in terms: if is_mod and name == "redirect" and has_all: out["problems"].append(f"{domain}: redirect={arg} is ignored because the record has 'all' (Sec. 5.1)") continue if name not in LOOKUP_TERMS: continue if name == "ptr": out["problems"].append(f"{domain}: 'ptr' SHOULD NOT be published (RFC 7208 Sec. 5.5)") out["lookups"] += 1 if name in ("include", "redirect"): if "%" in arg: out["lines"].append(f"{pad} {name}:{arg} (macro, needs a live connection to expand; counted once)") continue sub = check_spf(arg, lookup, seen, _depth + 1) for k in ("lookups", "void"): out[k] += sub[k] out["lines"] += sub["lines"] out["problems"] += sub["problems"] if _depth == 0: if not has_all and "redirect" not in names: out["all"] = None out["problems"].append(f"{domain}: no 'all' and no redirect, so unlisted senders get 'neutral' (Sec. 4.7)") if out["lookups"] > 10: out["problems"].append(f"{domain}: {out['lookups']} DNS-lookup terms (limit 10, RFC 7208 Sec. 4.6.4): " "a check that gets past the 10th ends in permerror, as does every unlisted sender") if out["void"] > 2: out["problems"].append(f"{domain}: {out['void']} void lookups (RFC 7208 recommends a limit of 2)") return out # ----------------------------------------------------------------------------------- DMARC --- DMARC_VALUES = {"p": {"none", "quarantine", "reject"}, "sp": {"none", "quarantine", "reject"}, "np": {"none", "quarantine", "reject"}, "t": {"y", "n"}, "psd": {"y", "n", "u"}, "adkim": {"r", "s"}, "aspf": {"r", "s"}} DMARC_ACTIVE = set(DMARC_VALUES) | {"rua", "ruf", "fo", "v"} DMARC_HISTORIC = {"pct": "sampling rate", "rf": "failure report format", "ri": "aggregate report interval"} def parse_dmarc(record): """Return dict of tags for a valid DMARC Policy Record (RFC 9989 Sec. 4.7-4.8), or None if the record is not one (v=DMARC1 must be the first tag, case-sensitive).""" parts = [p.strip(" \t") for p in record.split(";")] m = re.fullmatch(r"v[ \t]*=[ \t]*(\S+)", parts[0]) if parts else None if not m or m.group(1) != "DMARC1": return None tags = {"v": "DMARC1"} for p in parts[1:]: m = re.fullmatch(r"([A-Za-z]+)[ \t]*=[ \t]*(.+)", p) if m and m.group(1).lower() not in tags: tags[m.group(1).lower()] = m.group(2).strip(" \t") return tags def dmarc_uris(value): return [u.strip(" \t") for u in (value or "").split(",") if u.strip(" \t")] def review_dmarc(tags): """Plain-language findings for one parsed DMARC record.""" notes = [] for k, allowed in DMARC_VALUES.items(): if k in tags and tags[k].lower() not in allowed: notes.append(f"{k}={tags[k]} is not a valid value (allowed: {', '.join(sorted(allowed))})") rua = [u for u in dmarc_uris(tags.get("rua")) if re.match(r"[A-Za-z][A-Za-z0-9+.-]*:", u)] p = tags.get("p", "").lower() if p not in DMARC_VALUES["p"]: notes.append("no valid p= tag: receivers treat it as p=none because rua= is present (Sec. 4.10.1)" if rua else "no valid p= tag and no valid rua=: receivers apply no DMARC processing (Sec. 4.10.1)") p = "none" if rua else "" if p == "none": notes.append("p=none is monitoring mode: failing mail is not quarantined or rejected because of this record") if tags.get("t", "n").lower() == "y" and p in ("quarantine", "reject"): notes.append(f"t=y: receivers are asked to apply one level below p={p}, i.e. " f"{'none' if p == 'quarantine' else 'quarantine'} (Sec. 4.7)") if not rua: notes.append("no rua=: receivers MUST NOT send aggregate reports, so you cannot see what fails") for u in dmarc_uris(tags.get("rua")) + dmarc_uris(tags.get("ruf")): if "!" in u: notes.append(f"{u}: the '!size' suffix is obsolete in RFC 9989 and ignored") for k, what in DMARC_HISTORIC.items(): if k in tags: extra = "" if k == "pct": extra = (" pct=0 -> publish t=y instead." if tags[k] == "0" else " pct=100 was the default; delete it." if tags[k] == "100" else " RFC 9989 has no sampling; RFC 7489-era receivers may still sample.") notes.append(f"{k}= ({what}) is historic in RFC 9989.{extra}") for k in tags: if k not in DMARC_ACTIVE and k not in DMARC_HISTORIC: notes.append(f"unknown tag {k}= is ignored") return notes def walk_names(domain): """The names a DNS Tree Walk queries, RFC 9989 Sec. 4.10: the start, then one label shorter each time, except that a name of eight or more labels jumps straight to its last seven.""" labels = domain.rstrip(".").lower().split(".") names = [".".join(labels)] while len(labels) > 1: labels = labels[-7:] if len(labels) >= 8 else labels[1:] names.append(".".join(labels)) return names def dmarc_lookup(name, lookup): rcode, txts = lookup("_dmarc." + name) recs = [r for r in (parse_dmarc(t) for t in txts) if r is not None] return recs[0] if len(recs) == 1 else None # zero, or several (all discarded), means none def tree_walk(domain, lookup): """Query every name in walk_names(domain), stopping at a record with psd=y or psd=n. Returns [(name, tags), ...] for the names that had exactly one valid record, plus the query list.""" found, queried = [], [] for name in walk_names(domain): queried.append("_dmarc." + name) tags = dmarc_lookup(name, lookup) if tags: found.append((name, tags)) if tags.get("psd", "u").lower() in ("y", "n"): break return found, queried def organizational_domain(domain, lookup): """RFC 9989 Sec. 4.10.2 selection rules over the Tree Walk results.""" domain = domain.rstrip(".").lower() found, _ = tree_walk(domain, lookup) for name, tags in found: # longest to shortest if tags.get("psd", "u").lower() == "n": return name if tags.get("psd", "u").lower() == "y" and name != domain: labels = domain.split(".") return ".".join(labels[-(len(name.split(".")) + 1):]) return found[-1][0] if found else domain def discover_policy(domain, lookup): """RFC 9989 Sec. 4.10.1: which record applies to mail From: domain, and which tag sets the policy.""" domain = domain.rstrip(".").lower() own = dmarc_lookup(domain, lookup) if own: return {"policy_domain": domain, "tags": own, "tag_used": "p", "org": organizational_domain(domain, lookup)} org = organizational_domain(domain, lookup) found, _ = tree_walk(domain, lookup) by_name = dict(found) psd = [n for n, t in found if t.get("psd", "u").lower() == "y"] pol = org if org in by_name else (psd[0] if psd else None) if pol is None: return {"policy_domain": None, "tags": None, "tag_used": None, "org": org} tags = by_name[pol] rcode, _ = lookup(domain) exists = rcode != NXDOMAIN tag = "sp" if exists and "sp" in tags else "np" if not exists and "np" in tags else \ "sp" if not exists and "sp" in tags else "p" return {"policy_domain": pol, "tags": tags, "tag_used": tag, "org": org, "exists": exists} # ------------------------------------------------------------------------------------ DKIM --- def _der(buf, pos): tag, ln = buf[pos], buf[pos + 1] pos += 2 if ln & 0x80: n = ln & 0x7F ln = int.from_bytes(buf[pos:pos + n], "big") pos += n return tag, buf[pos:pos + ln], pos + ln def rsa_bits(der): """Modulus size of an RSA public key given as SubjectPublicKeyInfo or bare RSAPublicKey DER.""" tag, seq, _ = _der(der, 0) if tag != 0x30: raise ValueError("not a DER SEQUENCE") t1, v1, nxt = _der(seq, 0) if t1 == 0x30: # SubjectPublicKeyInfo: AlgorithmIdentifier, BIT STRING t2, bits, _ = _der(seq, nxt) if t2 != 0x03: raise ValueError("no BIT STRING after the algorithm identifier") return rsa_bits(bits[1:]) # skip the unused-bits byte if t1 != 0x02: raise ValueError("expected INTEGER modulus") return int.from_bytes(v1, "big").bit_length() def parse_tag_list(txt): tags = {} for p in txt.split(";"): if "=" in p: k, v = p.split("=", 1) tags.setdefault(k.strip().lower(), re.sub(r"\s+", "", v)) return tags def review_dkim_key(txt): """Findings for one DKIM key record (RFC 6376 Sec. 3.6.1, RFC 8301, RFC 8463).""" tags = parse_tag_list(txt) first_key = txt.split(";")[0].split("=", 1)[0].strip().lower() if first_key == "v" and tags["v"] != "DKIM1": return {"bits": None, "notes": ["v= is not DKIM1 as the first tag: verifiers discard this record"]} if "v" in tags and first_key != "v": return {"bits": None, "notes": ["v= is present but not the first tag: the record is invalid"]} k = tags.get("k", "rsa").lower() p = tags.get("p") notes, bits = [], None if p is None: return {"bits": None, "notes": ["no p= tag: not a usable key record"]} if p == "": return {"bits": None, "notes": ["p= is empty: this key is revoked, signatures with it fail"]} try: raw = base64.b64decode(p, validate=True) except (binascii.Error, ValueError): return {"bits": None, "notes": ["p= is not valid base64"]} if k == "rsa": try: bits = rsa_bits(raw) except (ValueError, IndexError) as e: return {"bits": None, "notes": [f"p= does not decode as an RSA public key ({e})"]} if bits < 1024: notes.append(f"RSA {bits} bits: RFC 8301 says verifiers MUST NOT accept keys under 1024 bits") elif bits < 2048: notes.append(f"RSA {bits} bits: valid, but RFC 8301 says signers SHOULD use at least 2048") else: notes.append(f"RSA {bits} bits") elif k == "ed25519": bits = len(raw) * 8 notes.append(f"Ed25519 key ({len(raw)} bytes; RFC 8463). Pair it with an RSA signature: not every " "verifier supports Ed25519") else: notes.append(f"k={k}: unknown key type, ignored by verifiers") if "h" in tags and "sha256" not in tags["h"].lower().split(":"): notes.append(f"h={tags['h']} excludes sha256; RFC 8301 forbids rsa-sha1, so nothing can verify") flags = tags.get("t", "").lower().split(":") if "y" in flags: notes.append("t=y: the domain says it is testing DKIM; verifiers may treat signatures as unsigned") return {"bits": bits, "notes": notes} # -------------------------------------------------------------------------------- reports --- def report(domain, selectors, lookup): print(f"== {domain}") spf = check_spf(domain, lookup) print(f"\nSPF ({spf['lookups']} of 10 DNS-lookup terms used)") for line in spf["lines"]: print(" " + line) for p in spf["problems"]: print(" ! " + p) found, queried = tree_walk(domain, lookup) pol = discover_policy(domain, lookup) print("\nDMARC") print(" tree walk queried: " + ", ".join(queried)) if not pol["tags"]: print(" ! no DMARC policy record found for this domain or any parent: DMARC does not apply") else: t = pol["tags"] print(f" policy record at _dmarc.{pol['policy_domain']}: " + "; ".join(f"{k}={v}" for k, v in t.items())) print(f" organizational domain: {pol['org']}; policy taken from the {pol['tag_used']}= tag " f"(= {t.get(pol['tag_used'], 'none')})") for n in review_dmarc(t): print(" ! " + n) for sel in selectors: name = f"{sel}._domainkey.{domain}" rcode, txts = lookup(name) print(f"\nDKIM {name}") if not txts: print(" ! no key record (wrong selector, or not published)") continue for n in review_dkim_key(txts[0])["notes"]: print(" - " + n) # ------------------------------------------------------------------------------- self-test --- def _fake(zone): def lookup(name): key = name.rstrip(".").lower() if key in zone: return NOERROR, list(zone[key]) exists = any(z == key or z.endswith("." + key) for z in zone) return (NOERROR if exists else NXDOMAIN), [] return lookup def _rsa_der(bits, spki): n = (1 << (bits - 1)) | 1 # any odd integer of exactly `bits` bits def tlv(tag, body): ln = len(body) enc = bytes([ln]) if ln < 128 else bytes([0x80 | ((ln.bit_length() + 7) // 8)]) + ln.to_bytes((ln.bit_length() + 7) // 8, "big") return bytes([tag]) + enc + body nb = n.to_bytes((bits + 7) // 8, "big") rsapub = tlv(0x30, tlv(0x02, (b"\x00" + nb) if nb[0] & 0x80 else nb) + tlv(0x02, b"\x01\x00\x01")) if not spki: return rsapub algo = tlv(0x30, tlv(0x06, bytes.fromhex("2a864886f70d010101")) + b"\x05\x00") return tlv(0x30, algo + tlv(0x03, b"\x00" + rsapub)) def selftest(): ok = 0 def check(cond, what): nonlocal ok if not cond: raise AssertionError(what) ok += 1 # RFC 9989 Sec. 4.10: the eight names for a 13-label Author Domain check(walk_names("a.b.c.d.e.f.g.h.i.j.mail.example.com") == [ "a.b.c.d.e.f.g.h.i.j.mail.example.com", "g.h.i.j.mail.example.com", "h.i.j.mail.example.com", "i.j.mail.example.com", "j.mail.example.com", "mail.example.com", "example.com", "com"], "walk 4.10") rec = "v=DMARC1; p=none; rua=mailto:dmarc-feedback@example.com" # RFC 9989 Appendix B.4.1 and B.4.2: example.com and signing.example.com publish, com does not z = _fake({"_dmarc.example.com": [rec], "_dmarc.signing.example.com": [rec]}) check(organizational_domain("example.com", z) == "example.com", "B.4.1 author") check(organizational_domain("signing.example.com", z) == "example.com", "B.4.1 dkim") check(organizational_domain("a.b.c.d.e.f.g.h.i.j.k.example.com", z) == "example.com", "B.4.2") check(len(tree_walk("a.b.c.d.e.f.g.h.i.j.k.example.com", z)[1]) == 8, "B.4.2 eight queries") # RFC 9989 Appendix B.4.3: bank.example publishes psd=y z = _fake({"_dmarc.bank.example": ["v=DMARC1; p=reject; psd=y"], "_dmarc.giant.bank.example": [rec]}) check(organizational_domain("giant.bank.example", z) == "giant.bank.example", "B.4.3 author") check(organizational_domain("mail.giant.bank.example", z) == "giant.bank.example", "B.4.3 spf") check(organizational_domain("mail.mega.bank.example", z) == "mega.bank.example", "B.4.3 dkim") # Sec. 4.10.2 second example: psd=n on mail.example.com stops the walk there z = _fake({"_dmarc.mail.example.com": ["v=DMARC1; p=none; psd=n"], "_dmarc.example.com": [rec]}) check(organizational_domain("a.mail.example.com", z) == "mail.example.com", "psd=n") # RFC 9989 Appendix B.2.5, TXT strings joined: quarantine under test mode b25 = "".join(["v=DMARC1; p=quarantine; ", "rua=mailto:dmarc-feedback@example.com,", "mailto:tld-test@thirdparty.example.net; ", "t=y"]) t = parse_dmarc(b25) check(t["p"] == "quarantine" and t["t"] == "y" and len(dmarc_uris(t["rua"])) == 2, "B.2.5 parse") check(any("i.e. none" in n for n in review_dmarc(t)), "B.2.5 t=y one level down") check(parse_dmarc("v=dmarc1; p=reject") is None, "v value is case-sensitive") check(parse_dmarc("p=reject; v=DMARC1") is None, "v must be first") check(any("monitoring" in n for n in review_dmarc(parse_dmarc(rec))), "p=none monitoring") old = review_dmarc(parse_dmarc("v=DMARC1; p=reject; pct=0; ri=86400")) check(any("t=y instead" in n for n in old) and any(n.startswith("ri=") for n in old), "historic tags") check(any("treat it as p=none" in n for n in review_dmarc(parse_dmarc("v=DMARC1; rua=mailto:a@example.com"))), "no p, rua") check(any("no DMARC processing" in n for n in review_dmarc(parse_dmarc("v=DMARC1; sp=reject"))), "no p, no rua") # policy discovery: subdomain that exists uses sp, a non-existent one uses np z = _fake({"_dmarc.example.com": ["v=DMARC1; p=reject; sp=quarantine; np=reject; rua=mailto:a@example.com"], "news.example.com": ["v=spf1 -all"]}) check(discover_policy("news.example.com", z)["tag_used"] == "sp", "sp for existing subdomain") check(discover_policy("nosuch.example.com", z)["tag_used"] == "np", "np for NXDOMAIN subdomain") check(discover_policy("example.com", z)["tag_used"] == "p", "p for the domain itself") # SPF: RFC 7208 Sec. 5.2 vanity-domain example, then the limits z = _fake({"example.net": ["v=spf1 include:example.com include:example.org -all"], "example.com": ["v=spf1 mx a -all"], "example.org": ["v=spf1 ip4:192.0.2.0/24 -all"]}) r = check_spf("example.net", z) check(r["lookups"] == 4 and not r["problems"] and r["all"] == "-all", "7208 vanity example") chain = {f"s{i}.example": [f"v=spf1 include:s{i + 1}.example a -all"] for i in range(5)} chain["s5.example"] = ["v=spf1 a mx -all"] r = check_spf("s0.example", _fake(chain)) check(r["lookups"] == 12 and any("limit 10" in p for p in r["problems"]), "over 10 lookups") r = check_spf("d.example", _fake({"d.example": ["v=spf1 -all", "v=spf1 a -all"]})) check(any("permerror" in p for p in r["problems"]), "two SPF records") r = check_spf("p.example", _fake({"p.example": ["v=spf1 ptr +all redirect=x.example"]})) check(sum(("+all" in p) or ("ptr" in p) or ("ignored" in p) for p in r["problems"]) == 3, "+all, ptr, dead redirect") r = check_spf("m.example", _fake({"m.example": ["v=spf1 ip4:300.1.1.1 -all"]})) check(any("syntax error" in p for p in r["problems"]), "bad ip4") r = check_spf("n.example", _fake({"n.example": ["v=spf1 include:gone.example ~all"]})) check(any("gone.example: no SPF record" in p for p in r["problems"]) and r["void"] == 1, "include target missing") # DKIM key sizes, both DER layouts for bits, spki in ((2048, True), (1024, True), (2048, False), (512, True), (4096, True)): k = "v=DKIM1; k=rsa; p=" + base64.b64encode(_rsa_der(bits, spki)).decode() check(review_dkim_key(k)["bits"] == bits, f"rsa {bits} spki={spki}") check("MUST NOT" in review_dkim_key("k=rsa; p=" + base64.b64encode(_rsa_der(512, True)).decode())["notes"][0], "512") check("SHOULD" in review_dkim_key("p=" + base64.b64encode(_rsa_der(1024, True)).decode())["notes"][0], "1024") check("revoked" in review_dkim_key("v=DKIM1; p=")["notes"][0], "revoked") check("discard" in review_dkim_key("v=DKIM2; p=AAAA")["notes"][0], "v=DKIM2") print(f"selftest: {ok} checks passed") return ok def demo(): """Offline: the report for a made-up domain (documentation names, RFC 2606) with common faults.""" leaf = "v=spf1 a mx ip4:198.51.100.0/24 ~all" zone = { "example.net": ["v=spf1 mx include:_spf.example.net include:esp.example.org ~all"], "_spf.example.net": ["v=spf1 ip4:192.0.2.0/24 include:_spf2.example.net -all"], "_spf2.example.net": ["v=spf1 a mx exists:%{i}._ip.example.net -all"], "esp.example.org": ["v=spf1 include:a.esp.example.org include:b.esp.example.org " "include:c.esp.example.org ~all"], "a.esp.example.org": [leaf], "b.esp.example.org": [leaf], "c.esp.example.org": [leaf], "_dmarc.example.net": ["v=DMARC1; p=quarantine; pct=0; rf=afrf; rua=mailto:dmarc-reports@example.net"], "s2019._domainkey.example.net": ["v=DKIM1; k=rsa; p=" + base64.b64encode(_rsa_der(1024, True)).decode()], "s2026._domainkey.example.net": ["v=DKIM1; k=rsa; p=" + base64.b64encode(_rsa_der(2048, True)).decode()], } report("example.net", ["s2019", "s2026"], _fake(zone)) def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("domain", nargs="?") ap.add_argument("--selector", action="append", default=[]) ap.add_argument("--resolver", default="1.1.1.1") ap.add_argument("--selftest", action="store_true") ap.add_argument("--demo", action="store_true") a = ap.parse_args() if a.selftest: selftest() return if a.demo: demo() return if not a.domain: ap.error("give a domain, or --selftest") report(a.domain.rstrip(".").lower(), a.selector, lambda n: dns_txt(n, a.resolver)) if __name__ == "__main__": sys.stdout.reconfigure(encoding="utf-8") main()