#!/usr/bin/env python3 """Count the DNS-lookup terms of an SPF record recursively (RFC 7208 section 4.6.4). Counts: include, a, mx, ptr, exists, redirect (each term = 1). Does not count ip4/ip6/all. The A/AAAA lookups done for the hosts returned by an mx term are NOT counted (RFC 7208 limits those separately to 10 names). Also counts "void" lookups (queries that return nothing); more than 2 is also a permerror. Backends: live DNS-over-HTTPS (Cloudflare JSON API, via curl) or a JSON fixture {"name|TYPE": ["value", ...]}.""" import json, subprocess, sys, re class Fixture: def __init__(self, path): self.z = json.load(open(path)) def txt(self, name): return self.z.get(f"{name}|TXT", []) def has(self, name, t): return bool(self.z.get(f"{name}|{t}")) def mx(self, name): return self.z.get(f"{name}|MX", []) class DoH: def _q(self, name, t): out = subprocess.run(["curl", "-s", "--max-time", "10", "-H", "accept: application/dns-json", f"https://cloudflare-dns.com/dns-query?name={name}&type={t}"], capture_output=True, text=True).stdout return json.loads(out) if out else {} def txt(self, name): j = self._q(name, "TXT") return [a["data"].replace('" "', '').strip('"') for a in j.get("Answer", []) if a.get("type") == 16] def has(self, name, t): j = self._q(name, t); return any(a.get("type") in (1, 28) for a in j.get("Answer", [])) def mx(self, name): j = self._q(name, "MX"); return [a["data"].split()[1].rstrip(".") for a in j.get("Answer", []) if a.get("type") == 15] def spf_record(res, domain): recs = [t for t in res.txt(domain) if re.match(r"^v=spf1(\s|$)", t, re.I)] return recs def count(res, domain, depth=0, state=None, trail=None): state = state if state is not None else {"lookups": 0, "void": 0, "trail": []} if depth > 10: return state recs = spf_record(res, domain) if len(recs) != 1: state["void"] += 1 state["trail"].append(f"{' '*depth}{domain}: {len(recs)} SPF records (void)") return state for term in recs[0].split()[1:]: t = term.lower().lstrip("+-~?") name, _, arg = t.partition(":") if t.startswith("redirect="): state["lookups"] += 1; state["trail"].append(f"{' '*depth}redirect={t[9:]} [lookup {state['lookups']}]") count(res, t[9:], depth + 1, state) elif name == "include": state["lookups"] += 1; state["trail"].append(f"{' '*depth}include:{arg} [lookup {state['lookups']}]") count(res, arg, depth + 1, state) elif name in ("a", "mx", "ptr", "exists") or t.startswith(("a/", "mx/")): target = arg.split("/")[0] or domain state["lookups"] += 1; state["trail"].append(f"{' '*depth}{term} [lookup {state['lookups']}]") if name == "mx" or t.startswith("mx/"): if not res.mx(target): state["void"] += 1 elif name in ("a",) or t.startswith("a/"): if not (res.has(target, "A") or res.has(target, "AAAA")): state["void"] += 1 return state if __name__ == "__main__": backend = Fixture(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].endswith(".json") else DoH() s = count(backend, sys.argv[1].lower()) print("\n".join(s["trail"])) verdict = "OVER THE LIMIT (permerror)" if s["lookups"] > 10 or s["void"] > 2 else "within limits" print(f"TOTAL: {s['lookups']} DNS-lookup terms, {s['void']} void lookups -> {verdict}")