用 Python 標準庫解析 DKIM 金鑰記錄,並檢視 DKIM2 草案擬棄用的四個標籤
Parsing DKIM key records in stdlib Python, and the four tags a DKIM2 draft would deprecate
作者以 Python 標準庫編寫 DKIM 金鑰記錄解析器,並指出 draft-ietf-dkim-dkim2-dns-03 建議不再在 DKIM1 記錄中使用 h=、n=、s=、t= 四個標籤,DKIM2 則會忽略它們。解析器處理分段 TXT 記錄、重複標籤及兩種 RSA 公鑰格式;DKIM1 現階段尚未改變。
A DKIM key record is a TXT record at <selector>._domainkey.<domain>, and it looks simple enough to parse with a split on ;. It mostly is. The parts that are not simple are the ones a checker gets wrong: two legal shapes for an RSA key, a record split across several strings, a revoked key that is still a valid record, and four tags that a new draft says should no longer be used.
That last group is why I wrote this now. draft-ietf-dkim-dkim2-dns-03, a DKIM working group draft dated 2 November 2026 and still the current revision this morning, says:
The h=, n=, s= and t= tags are deprecated: they SHOULD NOT be used in
DKIM1 key records, and DKIM2 ignores them if they are present.
It is an Internet-Draft, intended for Standards Track, "Updates: 6376 (if approved)". Nothing has changed for DKIM1 yet. But it is a good excuse to write a parser that reports what a record actually contains, then run it against live DNS. Everything below is Python's standard library, run on 26 November 2026.
Step 1: get the TXT strings, not a joined string
A TXT record is a list of strings of up to 255 bytes each. An RSA-2048 key does not fit in one, so the record arrives as two or more. RFC 6376 §3.6.2.2 is explicit: "Strings in a TXT RR MUST be concatenated together before use with no intervening whitespace." Google's DNS-over-HTTPS JSON API does the joining for you. A raw DNS answer does not, and a script that joins the strings with a space puts a space in the middle of the key.
The lookup below sends a plain UDP query with EDNS0 and retries over TCP if the answer is truncated. It returns each TXT record as its list of strings so the caller does the joining.
txt_lookup(): a TXT query over UDP, TCP if truncated
import base64, random, re, socket, struct
RESOLVER = "1.1.1.1"
def _qname(name):
return b"".join(bytes([len(p)]) + p.encode() for p in name.rstrip(".").split(".")) + b"\0"
def _skip(msg, off):
while msg[off]:
if msg[off] & 0xC0 == 0xC0:
return off + 2
off += 1 + msg[off]
return off + 1
def txt_lookup(name, server=RESOLVER):
"""Return (rcode, [list of strings per TXT record])."""
q = struct.pack("!HHHHHH", random.getrandbits(16), 0x0100, 1, 0, 0, 1)
q += _qname(name) + struct.pack("!HH", 16, 1)
q += b"\0" + struct.pack("!HHIH", 41, 1232, 0, 0) # EDNS0, 1232-byte buffer
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(4)
s.sendto(q, (server, 53))
msg = s.recv(65535)
s.close()
if msg[2] & 0x02: # TC bit: ask again over TCP
t = socket.create_connection((server, 53), timeout=4)
t.sendall(struct.pack("!H", len(q)) + q)
need = struct.unpack("!H", t.recv(2))[0]
msg = b""
while len(msg) < need:
msg += t.recv(need - len(msg))
t.close()
flags, qd, an = struct.unpack("!HHH", msg[2:8])
off = 12
for _ in range(qd):
off = _skip(msg, off) + 4
records = []
for _ in range(an):
off = _skip(msg, off)
rtype, _, _, rdlen = struct.unpack("!HHIH", msg[off:off + 10])
off += 10
rdata, off = msg[off:off + rdlen], off + rdlen
if rtype == 16:
strings, i = [], 0
while i < len(rdata):
strings.append(rdata[i + 1:i + 1 + rdata[i]].decode("latin-1"))
i += 1 + rdata[i]
records.append(strings)
return flags & 0xF, records
Step 2: the tag-list
The record body is a tag-list, defined once in RFC 6376 §3.2 and reused by the signature header. Three rules matter for a parser: whitespace is allowed around tags and around =, a trailing ; is fine, and a duplicate tag name makes "the entire tag-list" invalid, not just the second copy.
TAG_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]*$")
def parse_tag_list(text):
tags = {}
for spec in text.split(";"):
if not spec.strip():
continue # a trailing ";" is allowed
name, eq, value = spec.partition("=")
name, value = name.strip(), value.strip()
if not eq or not TAG_NAME.match(name):
raise ValueError(f"bad tag-spec {spec.strip()!r}")
if name in tags:
raise ValueError(f"duplicate tag {name}=") # whole list invalid
tags[name] = value
return tags
Splitting on ; is safe here because the grammar's VALCHAR excludes the semicolon, so no value can contain one.
Step 3: two shapes of RSA key
RFC 6376 §3.6.1 says an rsa key in p= is a DER-encoded RSAPublicKey. But the same RFC's Appendix C tells you to make the key with openssl rsa -pubout, which writes a SubjectPublicKeyInfo: the RSAPublicKey wrapped in an algorithm identifier and a BIT STRING. Erratum 3017 has pointed this out since 2011 ("most current implementations will accept such keys"), and dkim2-dns-03 settles it by allowing both.
Telling them apart takes one look at the first element inside the outer SEQUENCE. An RSAPublicKey starts with the modulus, an INTEGER. A SubjectPublicKeyInfo starts with the algorithm identifier, another SEQUENCE.
def _der(buf, off):
tag, n = buf[off], buf[off + 1]
off += 2
if n & 0x80:
k = n & 0x7F
n, off = int.from_bytes(buf[off:off + k], "big"), off + k
return tag, buf[off:off + n], off + n
def rsa_modulus_bits(der):
"""Accept an RSAPublicKey or a SubjectPublicKeyInfo holding one."""
tag, body, _ = _der(der, 0)
first, _, _ = _der(body, 0)
form = "RSAPublicKey"
if first == 0x30: # AlgorithmIdentifier first: this is an SPKI
_, _, off = _der(body, 0)
_, bitstring, _ = _der(body, off)
tag, body, _ = _der(bitstring[1:], 0) # skip the unused-bits byte
form = "SubjectPublicKeyInfo"
_, modulus, _ = _der(body, 0)
return int.from_bytes(modulus, "big").bit_length(), form
Ed25519 keys (RFC 8463) need no DER at all. p= is the raw 32-byte public key in base64, 44 characters, so the whole record fits in one TXT string.
Step 4: the record checker
DRAFT_DEPRECATES = ("h", "n", "s", "t")
def check_key_record(text):
tags = parse_tag_list(text)
out = []
if "v" in tags:
if tags["v"] != "DKIM1":
return [f"DISCARD v={tags['v']} (not DKIM1)"]
if next(iter(tags)) != "v":
out.append("ERROR v= present but not the first tag")
if "p" not in tags:
return out + ["ERROR no p= tag"]
k = tags.get("k", "rsa")
key = base64.b64decode(re.sub(r"\s+", "", tags["p"]), validate=True)
if not key:
out.append(f"k={k} REVOKED (empty p=)")
elif k == "rsa":
try:
bits, form = rsa_modulus_bits(key)
out.append(f"k=rsa {bits}-bit, p= is a {form}")
except IndexError:
out.append(f"k=rsa MALFORMED ({len(key)} bytes of p= are not DER)")
elif k == "ed25519":
ok = "ok" if len(key) == 32 else "MALFORMED, must be 32"
out.append(f"k=ed25519 {len(key)}-byte key ({ok})")
else:
out.append(f"k={k} unknown key type, a DKIM1 verifier ignores it")
if "y" in [f.strip() for f in tags.get("t", "").split(":")]:
out.append("t=y testing flag set")
used = [t for t in DRAFT_DEPRECATES if t in tags]
if used:
out.append("tags dkim2-dns-03 would deprecate: " + ", ".join(f"{t}={tags[t]}" for t in used))
unknown = [t for t in tags if t not in ("v", "k", "p", *DRAFT_DEPRECATES)]
if unknown:
out.append("unknown tags (ignored): " + ", ".join(unknown))
return out
An empty p= is not an error. RFC 6376 defines it as a revoked key: the signer is saying it knows the selector and every signature made with it should fail. A checker that reports "invalid key" there is wrong.
Before touching the network, the test record from RFC 8463 Appendix A.2 and a few broken ones:
tests = [
"v=DKIM1; k=ed25519; p=11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=",
"v=DKIM1 ; k = ed25519 ; p = 11qYAYKxCrfVS/7TyWQH Og7hcvPapiMlrwIaaPcHURo= ;",
"v=DKIM1; k=rsa; p=",
"k=rsa; v=DKIM1; p=AAAA",
"v=DKIM1; p=abc; p=def",
"v=DKIM1; k=mldsa44; p=AAAA",
]
for t in tests:
try:
print(check_key_record(t))
except ValueError as e:
print("INVALID:", e)
print(base64.b64decode("11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=").hex())
['k=ed25519 32-byte key (ok)']
['k=ed25519 32-byte key (ok)']
['k=rsa REVOKED (empty p=)']
['ERROR v= present but not the first tag', 'k=rsa MALFORMED (3 bytes of p= are not DER)']
INVALID: duplicate tag p=
['k=mldsa44 unknown key type, a DKIM1 verifier ignores it']
d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a
The second line is the same record with spaces everywhere the grammar allows them, and the decoded key is the public key from RFC 8032 §7.1 Test 1, which is where RFC 8463 says it came from. mldsa44 is a key type dkim2-dns-03 defines for DKIM2 only; to a DKIM1 verifier it is an unrecognized type, which RFC 6376 says MUST be ignored.
Step 5: live records
Stalwart, the open-source mail server, generates one RSA and one Ed25519 key per domain by default. Its domain settings reference (last updated 23 November) gives the current selector template as v{version}-{algorithm}-{date-%Y%m%d}. The project's own domain has an older pair, named by year and month:
def probe(domain, selector):
name = f"{selector}._domainkey.{domain}"
rcode, records = txt_lookup(name)
if not records:
return f"{name}: rcode={rcode}, no TXT"
lines = [f"{name}: {len(records)} TXT record(s)"]
for strings in records:
text = "".join(strings) # concatenate, no whitespace in between
lines.append(f" {len(strings)} string(s), {len(text)} chars")
try:
lines += [" " + x for x in check_key_record(text)]
except ValueError as e:
lines.append(f" INVALID: {e}")
return "\n".join(lines)
for sel in ["202404r", "202404e"]:
print(probe("stalw.art", sel))
202404r._domainkey.stalw.art: 1 TXT record(s)
2 string(s), 420 chars
k=rsa 2048-bit, p= is a SubjectPublicKeyInfo
tags dkim2-dns-03 would deprecate: h=sha256
202404e._domainkey.stalw.art: 1 TXT record(s)
1 string(s), 76 chars
k=ed25519 32-byte key (ok)
tags dkim2-dns-03 would deprecate: h=sha256
Both keys carry h=sha256. That tag limits which hash a key may be used with, and since RFC 8301 already forbids SHA-1 for DKIM, it no longer narrows anything. The draft's abstract calls the four "key record features that have not turned out to be useful". A second domain, belonging to a mail service that opened a public beta this week, publishes the same pair (YYYYMMr and YYYYMMe, one RSA-2048 and one Ed25519) with the same h=sha256.
Then I ran the same checker in a loop over 24 well-known tech domains and 14 common selector names (google, selector1, selector2, k1, s1, s2, default, mail and a few date-named ones). It found 44 key records:
records 44 revoked 1
tag counts {'k': 44, 'n': 3, 'p': 44, 't': 15, 'v': 21}
t=y on []
key forms {'k=rsa 2048-bit, p= is a SubjectPublicKeyInfo': 13, 'k=rsa 1024-bit, p= is a SubjectPublicKeyInfo': 30, 'k=rsa REVOKED': 1}
Three things in that tally:
- Every live RSA key is a
SubjectPublicKeyInfo. Not one uses theRSAPublicKeyform RFC 6376's text describes. A parser that only accepts what §3.6.1 says would reject all 43. - Of the four tags the draft would deprecate,
t=sappears 15 times, every time on ans1ors2selector, andn=three times. The revoked record usesn=as a note to humans:n=Intentionally_Left_Blank_As_Per_DKIM_Rotation_BCP; p=. Nobody publishest=yon a key here, andh=ands=do not appear at all. - 30 of 43 keys are 1024-bit. RFC 8301 allows that (signers "MUST use RSA keys of at least 1024 bits" and "SHOULD use RSA keys of at least 2048 bits"). A published key is not proof it still signs anything; plenty of these selectors may belong to old senders.
Step 6: the name the draft wants back
dkim2-dns-03 also defines a Domain Policy Record for DKIM2 at the bare _domainkey.<domain> name, a tag-list that starts with v=DKIM1 and carries an optional f=strict flag. So I asked that name too:
domains = ["github.com", "gitlab.com", "mozilla.org", "python.org", "ietf.org", "debian.org",
"ubuntu.com", "wikimedia.org", "stackoverflow.com", "npmjs.com", "docker.com",
"cloudflare.com", "fastmail.com", "proton.me", "dev.to", "stripe.com", "slack.com",
"atlassian.com", "zoom.us", "dropbox.com", "microsoft.com", "apple.com",
"amazon.com", "netflix.com", "stalw.art"]
found = {d: ["".join(r) for r in txt_lookup("_domainkey." + d)[1]] for d in domains}
found = {d: r for d, r in found.items() if r}
print(len(found), "of", len(domains))
for records in sorted(found.values()):
print(records)
10 of 25
['o=-']
['o=~']
['o=~; r=dkimfeedback@netflix.com']
['o=~; r=postmaster@wikimedia.org;']
['o=~; r=team@stackoverflow.com']
['t=y; o=~;']
['t=y; o=~;']
['t=y; o=~; r=abuse@amazon.com']
['t=y;o=~;']
['v=spf1 -all']
None of them is a DKIM2 policy record. Nine are DomainKeys sending-policy records from RFC 4870 (May 2007, now Historic): o=~ meant "this domain may sign some email", o=- "signs all email", r= a reporting address, and t=y testing mode. The tenth is an SPF record, v=spf1 -all, published at that name.
They are harmless. DKIM1 never queries this name, and the draft says "TXT records at that name that do not begin with v=DKIM1 are ignored". But they are a trap for anyone writing a DKIM2 checker: four of these records say t=y, and a parser that reads the bare name without checking v=DKIM1 first would report testing mode on domains that are not testing anything. The v= check goes first, then everything else.
What I'd take from this
- Keep the TXT strings separate until you join them yourself, with nothing in between.
- Accept both RSA shapes, and report a revoked key as revoked, not broken.
- Report
h=,n=,s=andt=as present, and say a draft would deprecate them; do not call them errors. RFC 6376 still defines them. - If you add DKIM2's policy record, check
v=DKIM1before reading any other tag at that name. There are 2007 records sitting there.
Written with AI assistance from my own notes and test results. I checked every fact and command before publishing.
來源:DEV Community · dev.to