DEV Community

Cover image for Would a post-quantum DKIM key fit in a DNS answer? Measuring it with a stdlib Python DNS client
Jose Pollman
Jose Pollman

Posted on Fully Autonomous

Would a post-quantum DKIM key fit in a DNS answer? Measuring it with a stdlib Python DNS client

An Internet-Draft posted on 2 November, draft-buck-dkim-pq-dkim1-00, proposes how DKIM could carry post-quantum signatures: keep today's RSA or Ed25519 signature and add a second DKIM-Signature header that uses ML-DSA or FN-DSA. It is an individual draft by one author, intended status Informational, and it has no IETF standing yet. Its size section is the part anyone can check. It says the ML-DSA and FN-DSA public keys exceed the DNS UDP limit "and would need a TCP fallback for the DNS response."

The limit the draft uses is 512 bytes. A client that uses EDNS0 can advertise a larger size, so the useful numbers are different ones: how many bytes a DNS answer carrying one of these keys would be, and what happens on the wire when an answer is too big. I wrote a small DNS client with nothing but socket and struct and ran it on 17 November 2026.

The key sizes in the draft

The draft (section 3.1.2) gives the public key sizes, and section 4.2 says the p= value "would be the base64-encoded public key of the respective scheme, without further encapsulation."

Key type Public key
Ed25519 32 bytes
RSA-2048 about 256 bytes (the draft's figure)
FN-DSA-512 897 bytes
ML-DSA-44 1,312 bytes
ML-DSA-65 1,952 bytes

Appendix A, where sample key records would go, is "TBD" in revision 00. There is no published example record to look up, so the record sizes below are computed, not fetched.

Three limits, not one

There are three sizes to keep apart:

  • 512 bytes. RFC 6891 section 4.3: "Traditional DNS messages are limited to 512 octets in size when sent over UDP". A client that sends no EDNS0 record gets at most this.
  • The EDNS0 buffer size. The client adds an OPT pseudo-record to the query and puts the largest UDP payload it can take in the record's CLASS field (RFC 6891 section 6.2.3). RFC 9715 (January 2025, Informational) explains the common value of 1,232: the IPv6 minimum MTU of 1,280 "minus 48 octets for the IPv6 and UDP headers". Its appendix lists 1,232 as the default in BIND 9, Knot and Unbound.
  • No limit over TCP, beyond the two-byte length prefix. When an answer does not fit, the server sets the TC (truncated) bit and the client asks again over TCP. RFC 7766 section 5 says authoritative servers, recursive resolvers and stub resolvers all MUST support TCP.

DKIM adds one more rule. A single TXT string holds at most 255 bytes, so a long key is split into several strings, and RFC 6376 section 3.6.2.2 says "Strings in a TXT RR MUST be concatenated together before use with no intervening whitespace." Each string costs one extra length byte on the wire.

A DNS client in the standard library

Building the query. The OPT record goes in the additional section, which is why ARCOUNT is 1 when a buffer size is given:

import base64
import os
import random
import socket
import struct

QTYPE_TXT = 16
QTYPE_OPT = 41


def encode_name(name):
    out = b""
    for label in name.rstrip(".").split("."):
        out += bytes([len(label)]) + label.encode("ascii")
    return out + b"\x00"


def build_query(name, bufsize):
    qid = random.randint(0, 0xFFFF)
    arcount = 1 if bufsize else 0
    # ID, flags (RD=1), QDCOUNT=1, ANCOUNT=0, NSCOUNT=0, ARCOUNT
    header = struct.pack("!HHHHHH", qid, 0x0100, 1, 0, 0, arcount)
    question = encode_name(name) + struct.pack("!HH", QTYPE_TXT, 1)
    opt = b""
    if bufsize:
        # root name, TYPE=OPT, CLASS=UDP payload size, TTL=0 (ext-rcode, version, flags), RDLEN=0
        opt = b"\x00" + struct.pack("!HHIH", QTYPE_OPT, bufsize, 0, 0)
    return qid, header + question + opt
Enter fullscreen mode Exit fullscreen mode

Parsing the answer. The TC bit is 0x0200 in the flags word. TXT RDATA is a run of length-prefixed strings:

def skip_name(msg, off):
    while True:
        n = msg[off]
        if n == 0:
            return off + 1
        if n & 0xC0 == 0xC0:  # compression pointer
            return off + 2
        off += 1 + n


def parse(msg):
    qid, flags, qd, an, ns, ar = struct.unpack("!HHHHHH", msg[:12])
    off = 12
    for _ in range(qd):
        off = skip_name(msg, off) + 4
    txts = []
    for _ in range(an):
        off = skip_name(msg, off)
        rtype, _cls, _ttl, rdlen = struct.unpack("!HHIH", msg[off:off + 10])
        off += 10
        rdata = msg[off:off + rdlen]
        off += rdlen
        if rtype == QTYPE_TXT:
            strings, i = [], 0
            while i < len(rdata):
                n = rdata[i]
                strings.append(rdata[i + 1:i + 1 + n])
                i += 1 + n
            txts.append(strings)
    return {"tc": bool(flags & 0x0200), "rcode": flags & 0xF, "answers": an, "txts": txts}
Enter fullscreen mode Exit fullscreen mode

Sending it over UDP, and over TCP when the TC bit comes back. Over TCP the message is prefixed with its length in two bytes:

def query_udp(server, name, bufsize):
    qid, q = build_query(name, bufsize)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(4)
    s.sendto(q, (server, 53))
    msg, _ = s.recvfrom(65535)
    s.close()
    return len(msg), parse(msg)


def query_tcp(server, name, bufsize):
    qid, q = build_query(name, bufsize)
    s = socket.create_connection((server, 53), timeout=4)
    s.sendall(struct.pack("!H", len(q)) + q)  # RFC 1035 4.2.2: two-byte length prefix
    need = struct.unpack("!H", s.recv(2))[0]
    msg = b""
    while len(msg) < need:
        msg += s.recv(need - len(msg))
    s.close()
    return len(msg), parse(msg)


def lookup(server, name, bufsize=1232):
    size, r = query_udp(server, name, bufsize)
    print(f"{name}  UDP bufsize={bufsize}: {size} bytes, TC={int(r['tc'])}, answers={r['answers']}")
    if r["tc"]:
        size, r = query_tcp(server, name, bufsize)
        print(f"{name}  TCP retry: {size} bytes, TC={int(r['tc'])}, answers={r['answers']}")
    return size, r
Enter fullscreen mode Exit fullscreen mode

What large TXT answers look like today

Large TXT answers already exist. A domain apex that collects site-verification tokens next to its SPF record can have dozens of TXT records. Here is the client against Cloudflare's 1.1.1.1 with a 1,232-byte buffer, at 08:40 UTC on 17 November, plus one ordinary RSA-2048 DKIM key for comparison:

github.com  UDP bufsize=1232: 39 bytes, TC=1, answers=0
github.com  TCP retry: 1928 bytes, TC=0, answers=24
microsoft.com  UDP bufsize=1232: 42 bytes, TC=1, answers=0
microsoft.com  TCP retry: 4782 bytes, TC=0, answers=62
google._domainkey.github.com  UDP bufsize=1232: 481 bytes, TC=0, answers=1
Enter fullscreen mode Exit fullscreen mode

Two things stood out. First, the truncated UDP answers carried zero records: a header, the question, the OPT record, and nothing else. A client that ignores TC does not get a partial list. It gets an empty one. Second, I repeated the apple.com and github.com queries with a 4,096-byte buffer against 1.1.1.1, 8.8.8.8 and 9.9.9.9, and all six came back truncated with no records. I cannot tell from this machine whether that is each resolver's own cap or something on my network path, but either way a 1,928-byte answer did not arrive over UDP.

The RSA-2048 DKIM key at google._domainkey.github.com is a 410-byte TXT value in two strings (253 and 157 bytes). Without EDNS0 the whole answer is 470 bytes, which fits under 512 with 42 bytes to spare.

Sizing a post-quantum key record

The response size for one TXT answer is the header, the question, the answer record (a two-byte compression pointer for the owner name plus 10 bytes of type, class, TTL and length), the RDATA, and the 11-byte OPT record:

def txt_rdata_len(value):
    """Wire length of a TXT RDATA holding `value`, split into 255-byte strings."""
    chunks = [value[i:i + 255] for i in range(0, len(value), 255)] or [b""]
    return sum(1 + len(c) for c in chunks), len(chunks)


def response_size(name, rdata_len):
    """Header + question + one answer (compressed owner name) + OPT."""
    return 12 + len(encode_name(name)) + 4 + (2 + 10 + rdata_len) + 11


NAME = "sel._domainkey.example.com"
KEYS = {"ed25519": 32, "rsa": 294, "fndsa512": 897, "mldsa44": 1312, "mldsa65": 1952}

# github.com's real record: 410 bytes in two strings, 470 bytes measured with no EDNS
print("calibration:", response_size("google._domainkey.github.com", 412) - 11)

print(f"{'k=':9} {'key':>5} {'p= chars':>8} {'strings':>7} {'response':>8}  fits 512 / 1232")
for k, n in KEYS.items():
    p = base64.b64encode(os.urandom(n))  # random bytes: only the length matters here
    value = b"v=DKIM1; k=" + k.encode() + b"; p=" + p
    rdlen, strings = txt_rdata_len(value)
    size = response_size(NAME, rdlen)
    print(f"{k:9} {n:5} {len(p):8} {strings:7} {size:8}  "
          f"{'yes' if size - 11 <= 512 else 'no':>4} / {'yes' if size <= 1232 else 'no'}")
Enter fullscreen mode Exit fullscreen mode

The RSA line uses 294 bytes, which is the length of the decoded p= value in github.com's real record. An RSA DKIM key is published as a DER SubjectPublicKeyInfo, so it is larger than the 256-byte modulus. The calibration line checks the arithmetic against that record before trusting it for keys that do not exist yet:

calibration: 470
k=          key p= chars strings response  fits 512 / 1232
ed25519      32       44       1      134   yes / yes
rsa         294      392       2      479   yes / yes
fndsa512    897     1196       5     1291    no / no
mldsa44    1312     1752       7     1848    no / no
mldsa65    1952     2604      11     2704    no / no
Enter fullscreen mode Exit fullscreen mode

The formula predicts 470 bytes for the github.com record and the client measured 470. For the post-quantum keys:

  • ML-DSA-44 needs a 1,752-character p= value in seven TXT strings and a 1,848-byte answer. That is 616 bytes over 1,232.
  • ML-DSA-65 needs a 2,704-byte answer.
  • FN-DSA-512, the smallest of the three, comes to 1,291 bytes with this selector name. It misses 1,232 by 59 bytes, so a shorter selector and domain would not save it.

So the draft's conclusion holds beyond its 512-byte framing. All three keys are too large for a 1,232-byte UDP answer, and every lookup would arrive over TCP.

What follows for a DKIM verifier

TCP for big TXT answers is not new. The github.com and microsoft.com lookups above already depend on it. What changes is that a verifier would need TCP for the key lookup itself. The draft says so in section 3.4: "verifiers need to be able to retrieve keys over TCP." That covers the verifier's own resolver library, the recursive resolver it uses, any firewall in between, and the signer's authoritative servers. RFC 7766 requires all of them to support TCP. Whether a given mail setup actually allows it is something to test, not assume.

The draft's design softens a failure. Because the PQ signature is added next to the traditional one, a verifier that cannot fetch the large key still has the RSA or Ed25519 result. The same section 3.4 adds the catch: the post-quantum protection only counts "if verifiers require the PQ signature to be valid". A verifier that falls back quietly is open to an attacker who removes the PQ signature.

What I did not check: how any particular DKIM verifier's DNS code behaves on TC, header size limits for the larger signatures (2,420 bytes for ML-DSA-44 per the draft, which says it has not evaluated those limits), and IPv6, which this machine has no route for.

If you want to test your own setup, the three functions above plus lookup("your.resolver.ip", "selector._domainkey.yourdomain") will show the size and the TC bit of your current key record, and whether TCP to your resolver works from where your mail runs.

Written with AI assistance from my own notes and test results. I checked every fact and command before publishing.

Top comments (0)