Files
tchivert 2a3e20d8d7
test / test (pull_request) Successful in 10s
close remaining RFC 7873/6891 spec gaps from review
Malformed COOKIE options (RFC 7873 section 5.2.2): option lengths other
than 8 and 16-40 are now answered with FORMERR and never get a COOKIE
in the response; getQueryCookie classifies absent/valid/malformed.

Server-cookie learning probes (RFC 7873 section 5.4): question-less
queries carrying a COOKIE option are answered NOERROR with a freshly
minted server cookie, or BADCOOKIE when re-establishing an invalid
server cookie. miekg's ServeMux refuses question-less queries, so the
servers now use handleQuery directly as their handler, and
msgAcceptFunc lets QDCOUNT=0 QUERY requests through.

EDNS/OPT handling (RFC 6891): the upstream OPT record is no longer
cached or forwarded (sections 6.1.1 and 6.2.1) — it is removed before
caching and rebuilt per query. Responses to EDNS queries always carry
an OPT record advertising the responder's payload size and echoing
the query's DO bit (sections 6.1.1 and 6.2.4); responses to non-EDNS
queries never carry one (section 7). applyCookie is now applyEDNS.

Tests: malformed-COOKIE FORMERR for lengths 4/12/41 and normal
answers for 8/16/40, cookie probe (NOERROR/BADCOOKIE) at the handler
level and through a real miekg server over UDP (independent raw-socket
verification included), msgAcceptFunc unit test, OPT-never-cached and
OPT-rebuild assertions, non-EDNS responses carry no OPT.

README documents the new EDNS and COOKIE behaviors.
2026-10-11 19:22:04 +02:00

373 lines
12 KiB
Go

package main
import (
"crypto/rand"
"crypto/subtle"
"encoding/binary"
"encoding/hex"
"log"
"math/bits"
"net"
"sync"
"time"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
// cookieChecks counts server cookies presented by clients (echoed back in
// later queries per RFC 7873 section 5.2.2), by validation result.
var cookieChecks = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "rdns_cookie_checks_total",
Help: "Server cookies presented by clients, by validation result",
}, []string{"result"})
// EDNS COOKIE (RFC 7873, updated by RFC 9018) handling.
//
// The resolver is a middlebox: it terminates COOKIE processing towards
// downstream clients instead of relaying the upstream server's cookie.
// For every query carrying a COOKIE option, the response echoes the
// client cookie of that query unchanged and carries a freshly computed
// RFC 9018 server cookie bound to the client address and the current
// time. Responses served from cache (including negative ones) get their
// cached COOKIE option stripped and rebuilt for the current query, so a
// cached response is never replayed verbatim to a different client.
const (
cookieVersion = 1 // RFC 9018 section 4.1
clientCookieLen = 8
maxServerCookieLen = 32 // RFC 7873 section 4.2
serverCookieLen = 16 // 128-bit server cookie (RFC 9018 section 4)
secretRotateEvery = time.Hour
// RFC 9018 section 4.3: accept server cookie timestamps up to one
// hour in the past and a few minutes into the future.
cookieMaxPastSkew = time.Hour
cookieMaxFutureSkew = 5 * time.Minute
)
// cookieState classifies the COOKIE option of a query.
type cookieState int
const (
cookieAbsent cookieState = iota
cookieValid
cookieMalformed
)
// cookieSecrets holds the current and previous server secrets. The
// previous secret is kept after rotation so cookies minted before a
// rotation remain valid for the skew tolerance window.
var cookieSecrets = struct {
sync.RWMutex
current [16]byte
previous [16]byte
}{}
func init() {
cookieSecrets.current = randomSecret()
cookieSecrets.previous = randomSecret()
}
func randomSecret() (s [16]byte) {
if _, err := rand.Read(s[:]); err != nil {
panic("rdns: cannot read randomness for cookie secret: " + err.Error())
}
return s
}
func rotateCookieSecrets() {
cookieSecrets.Lock()
defer cookieSecrets.Unlock()
cookieSecrets.previous = cookieSecrets.current
cookieSecrets.current = randomSecret()
}
func startCookieSecretRotation() {
go func() {
ticker := time.NewTicker(secretRotateEvery)
defer ticker.Stop()
for range ticker.C {
rotateCookieSecrets()
}
}()
}
// siphash24 is SipHash-2-4 with a 128-bit key, the pseudorandom function
// mandated for RFC 9018 server cookies (sections 4.4 and 6).
func siphash24(key []byte, msg []byte) uint64 {
k0 := binary.LittleEndian.Uint64(key[:8])
k1 := binary.LittleEndian.Uint64(key[8:16])
v0 := k0 ^ 0x736f6d6570736575
v1 := k1 ^ 0x646f72616e646f6d
v2 := k0 ^ 0x6c7967656e657261
v3 := k1 ^ 0x7465646279746573
round := func() {
v0 += v1
v1 = bits.RotateLeft64(v1, 13)
v1 ^= v0
v0 = bits.RotateLeft64(v0, 32)
v2 += v3
v3 = bits.RotateLeft64(v3, 16)
v3 ^= v2
v0 += v3
v3 = bits.RotateLeft64(v3, 21)
v3 ^= v0
v2 += v1
v1 = bits.RotateLeft64(v1, 17)
v1 ^= v2
v2 = bits.RotateLeft64(v2, 32)
}
n := len(msg)
for len(msg) >= 8 {
m := binary.LittleEndian.Uint64(msg)
v3 ^= m
round()
round()
v0 ^= m
msg = msg[8:]
}
var last [8]byte
copy(last[:], msg)
last[7] = byte(n)
m := binary.LittleEndian.Uint64(last[:])
v3 ^= m
round()
round()
v0 ^= m
v2 ^= 0xff
round()
round()
round()
round()
return v0 ^ v1 ^ v2 ^ v3
}
func clientIPBytes(ip string) []byte {
if parsed := net.ParseIP(ip); parsed != nil {
if v4 := parsed.To4(); v4 != nil {
return v4
}
return parsed.To16()
}
return []byte(ip)
}
// cookieHashInput builds the RFC 9018 section 4.4 SipHash-2-4 input:
// Client Cookie || Version || Reserved || Timestamp || Client IP.
// The Version, Reserved and Timestamp sub-fields are taken as received
// when validating (RFC 9018 section 4.2: the Reserved sub-field MUST NOT
// be enforced to be zero on verification).
func cookieHashInput(clientCookie []byte, version byte, reserved [3]byte, timestamp uint32, clientIP string) []byte {
in := make([]byte, 0, clientCookieLen+4+4+net.IPv6len)
in = append(in, clientCookie...)
in = append(in, version, reserved[0], reserved[1], reserved[2])
var ts [4]byte
binary.BigEndian.PutUint32(ts[:], timestamp)
in = append(in, ts[:]...)
in = append(in, clientIPBytes(clientIP)...)
return in
}
// makeServerCookie computes an RFC 9018 version 1 server cookie:
// version (8 bits) || reserved (24 bits, zero) || timestamp (32 bits,
// seconds since the epoch, network order) || SipHash-2-4 hash (64 bits)
// over the client cookie, version, reserved, timestamp and client IP,
// keyed with the current server secret.
func makeServerCookie(clientIP string, clientCookie []byte, now time.Time) []byte {
cookieSecrets.RLock()
secret := cookieSecrets.current
cookieSecrets.RUnlock()
timestamp := uint32(now.Unix())
h := siphash24(secret[:], cookieHashInput(clientCookie, cookieVersion, [3]byte{}, timestamp, clientIP))
cookie := make([]byte, serverCookieLen)
cookie[0] = cookieVersion
binary.BigEndian.PutUint32(cookie[4:8], timestamp)
// The Hash sub-field is the SipHash-2-4 output in little-endian byte
// order, as shown by the test vectors of RFC 9018 Appendix A.
binary.LittleEndian.PutUint64(cookie[8:16], h)
return cookie
}
// validateServerCookie checks a server cookie presented by a client
// against the current and previous server secrets (RFC 9018 section 5),
// honouring the timestamp skew policy of RFC 9018 section 4.3 with
// RFC 1982 serial number arithmetic.
func validateServerCookie(clientIP string, clientCookie, serverCookie []byte, now time.Time) bool {
// RFC 9018 section 4.4: a version 1 COOKIE option must be precisely
// 24 bytes: 8 bytes of client cookie plus a 16-byte server cookie.
if len(serverCookie) != serverCookieLen || len(clientCookie) != clientCookieLen {
return false
}
if serverCookie[0] != cookieVersion {
return false
}
timestamp := binary.BigEndian.Uint32(serverCookie[4:8])
// RFC 1982 serial number arithmetic on (now - timestamp): the cookie
// is too old when the difference exceeds the past tolerance, and too
// far in the future when it is below minus the future tolerance.
diff := int32(uint32(now.Unix()) - timestamp)
if diff > int32(cookieMaxPastSkew/time.Second) || diff < -int32(cookieMaxFutureSkew/time.Second) {
return false
}
var reserved [3]byte
copy(reserved[:], serverCookie[1:4])
cookieSecrets.RLock()
secrets := [][16]byte{cookieSecrets.current, cookieSecrets.previous}
cookieSecrets.RUnlock()
in := cookieHashInput(clientCookie, serverCookie[0], reserved, timestamp, clientIP)
for _, secret := range secrets {
h := siphash24(secret[:], in)
var want [8]byte
binary.LittleEndian.PutUint64(want[:], h)
if subtle.ConstantTimeCompare(want[:], serverCookie[8:16]) == 1 {
return true
}
}
return false
}
// getQueryCookie extracts the client cookie and the optional server
// cookie from the first COOKIE option of a query (RFC 7873 section 5.2:
// only the first COOKIE option is considered). The state reports whether
// the option is absent, valid, or malformed. Valid COOKIE option lengths
// are 8 bytes (client cookie only) and 16 to 40 bytes (client cookie plus
// an 8 to 32 byte server cookie), per RFC 7873 section 5.2.2.
func getQueryCookie(q *dns.Msg) (clientCookie, serverCookie []byte, state cookieState) {
opt := q.IsEdns0()
if opt == nil {
return nil, nil, cookieAbsent
}
for _, o := range opt.Option {
c, isCookie := o.(*dns.EDNS0_COOKIE)
if !isCookie {
continue
}
raw, err := hex.DecodeString(c.Cookie)
if err != nil {
return nil, nil, cookieMalformed
}
if len(raw) != clientCookieLen && (len(raw) < 2*clientCookieLen || len(raw) > clientCookieLen+maxServerCookieLen) {
return nil, nil, cookieMalformed
}
return raw[:clientCookieLen], raw[clientCookieLen:], cookieValid
}
return nil, nil, cookieAbsent
}
// stripCookies removes any COOKIE option from a response, e.g. one
// relayed from upstream or replayed from cache.
func stripCookies(r *dns.Msg) {
opt := r.IsEdns0()
if opt == nil {
return
}
kept := opt.Option[:0]
for _, o := range opt.Option {
if _, isCookie := o.(*dns.EDNS0_COOKIE); !isCookie {
kept = append(kept, o)
}
}
opt.Option = kept
}
// removeOPT removes the OPT pseudo-record from a response. OPT records
// carry per-transaction control information and MUST NOT be cached or
// forwarded (RFC 6891 section 6.1.1).
func removeOPT(r *dns.Msg) {
kept := r.Extra[:0]
for _, rr := range r.Extra {
if rr.Header().Rrtype != dns.TypeOPT {
kept = append(kept, rr)
}
}
r.Extra = kept
}
// applyEDNS finalizes the EDNS state of response r for query q:
// - a query without EDNS gets a response without an OPT record
// (RFC 6891 section 7: the responder MUST NOT include an OPT
// record in its response)
// - a query with EDNS gets an OPT record (RFC 6891 section 6.1.1:
// compliant responders MUST include an OPT record) advertising the
// responder's payload size (RFC 6891 section 6.2.4) and echoing the
// query's DO bit
// - a query with a valid COOKIE option gets the client cookie echoed
// unchanged and a freshly minted server cookie (RFC 7873/9018), and
// server cookies presented by clients are validated and counted in
// the rdns_cookie_checks metric. A malformed COOKIE option never
// gets a cookie in the response (such queries are answered FORMERR
// by the caller, RFC 7873 section 5.2.2).
//
// OPT records are never cached (RFC 6891 section 6.2.1): the OPT of an
// upstream response is removed before caching and rebuilt here from the
// current query.
func applyEDNS(q, r *dns.Msg, clientIP string) {
stripCookies(r)
clientCookie, serverCookie, state := getQueryCookie(q)
qo := q.IsEdns0()
if qo == nil {
removeOPT(r)
return
}
opt := r.IsEdns0()
if opt == nil {
r.SetEdns0(serverUDPSize, false)
opt = r.IsEdns0()
}
// The OPT in a response advertises the responder's payload size
// (RFC 6891 section 6.2.4), not the client's, and echoes the query's
// DO bit.
opt.SetUDPSize(serverUDPSize)
opt.SetDo(qo.Do())
if state != cookieValid {
return
}
switch {
case len(serverCookie) == 0:
cookieChecks.WithLabelValues("absent").Inc()
case validateServerCookie(clientIP, clientCookie, serverCookie, time.Now()):
cookieChecks.WithLabelValues("valid").Inc()
default:
cookieChecks.WithLabelValues("invalid").Inc()
}
cookie := make([]byte, 0, clientCookieLen+serverCookieLen)
cookie = append(cookie, clientCookie...)
cookie = append(cookie, makeServerCookie(clientIP, clientCookie, time.Now())...)
opt.Option = append(opt.Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString(cookie),
})
}
// writeResponse finalizes r for the client and writes it out: it applies
// per-client EDNS/COOKIE handling, clears the DNSSEC AD bit (rdns
// forwards but does not validate, so it MUST NOT relay the upstream AD
// bit, RFC 6840 section 5.8) and truncates UDP responses exceeding the
// client's advertised payload size (RFC 6891 section 6.2.5).
func writeResponse(w dns.ResponseWriter, q, r *dns.Msg, clientIP string) {
applyEDNS(q, r, clientIP)
r.MsgHdr.AuthenticatedData = false
if _, udp := w.LocalAddr().(*net.UDPAddr); udp {
limit := dns.MinMsgSize
if opt := q.IsEdns0(); opt != nil && int(opt.UDPSize()) > limit {
limit = int(opt.UDPSize())
}
if r.Len() > limit {
r.Truncate(limit)
}
}
if err := w.WriteMsg(r); err != nil && *logs {
log.Println("ERROR: Failed to write response:", err)
}
}