close remaining RFC 7873/6891 spec gaps from review
test / test (pull_request) Successful in 10s

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.
This commit is contained in:
tchivert committed 2026-10-11 19:22:04 +02:00
1 parent 8628de05d0
commit 2a3e20d8d7
5 files changed
+398 -73

No files matched your search

+2 -2
View File
@@ -5,9 +5,9 @@ rdns is a caching, forwarding DNS resolver written in Go. It acts as a DNS serve
## Features
- Caching of positive and negative (NXDOMAIN/NODATA) responses; the cache lifetime is controlled by `-t` and the TTLs of cached responses are decremented by the time spent in the cache
- EDNS COOKIE support (RFC 7873, RFC 9018): rdns terminates cookie processing towards clients — it echoes the client cookie of each query, mints its own RFC 9018 server cookies (SipHash-2-4 over client cookie, version, timestamp and client IP, keyed with an hourly-rotated server secret), and never relays upstream server cookies. Cached responses get a fresh cookie built for the current client. Queries without a COOKIE option get responses without one
- EDNS handling per RFC 6891: responses to EDNS queries always carry an OPT record advertising the responder's payload size and echoing the query's DO bit; responses to non-EDNS queries never carry an OPT record; OPT records (including their options) are never cached or forwarded, and UDP responses exceeding the client's advertised payload size are truncated with the TC bit set so clients retry over TCP
- EDNS COOKIE support (RFC 7873, RFC 9018): rdns terminates cookie processing towards clients — it echoes the client cookie of each query, mints its own RFC 9018 server cookies (SipHash-2-4 over client cookie, version, timestamp and client IP, keyed with an hourly-rotated server secret), and never relays upstream server cookies. Cached responses get a fresh cookie built for the current client. Queries without a COOKIE option get responses without one; malformed COOKIE options are answered with FORMERR (RFC 7873 section 5.2.2), and question-less COOKIE queries are answered as server-cookie learning probes (RFC 7873 section 5.4, BADCOOKIE when re-establishing an invalid server cookie)
- No DNSSEC validation: the AD bit is always cleared in responses (RFC 6840 section 5.8)
- UDP responses larger than the client's advertised EDNS payload size are truncated with the TC bit set, so clients retry over TCP (RFC 6891)
- Blocklist, custom zones and hosts files
- Prometheus metrics (optional)
+86 -35
View File
@@ -35,9 +35,10 @@ var cookieChecks = promauto.NewCounterVec(prometheus.CounterOpts{
// cached response is never replayed verbatim to a different client.
const (
cookieVersion = 1 // RFC 9018 section 4.1
clientCookieLen = 8
serverCookieLen = 16 // 128-bit server cookie (RFC 9018 section 4)
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
@@ -46,6 +47,15 @@ const (
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.
@@ -227,22 +237,31 @@ func validateServerCookie(clientIP string, clientCookie, serverCookie []byte, no
}
// getQueryCookie extracts the client cookie and the optional server
// cookie from the COOKIE option of a query, if present and well-formed.
func getQueryCookie(q *dns.Msg) (clientCookie, serverCookie []byte, ok bool) {
// 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, false
return nil, nil, cookieAbsent
}
for _, o := range opt.Option {
if c, isCookie := o.(*dns.EDNS0_COOKIE); isCookie {
raw, err := hex.DecodeString(c.Cookie)
if err != nil || len(raw) < clientCookieLen {
return nil, nil, false
}
return raw[:clientCookieLen], raw[clientCookieLen:], true
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, false
return nil, nil, cookieAbsent
}
// stripCookies removes any COOKIE option from a response, e.g. one
@@ -261,16 +280,56 @@ func stripCookies(r *dns.Msg) {
opt.Option = kept
}
// applyCookie rewrites the COOKIE option of response r for query q:
// the client cookie of q is echoed unchanged and any existing (upstream
// or cached) server cookie is replaced with a freshly computed one bound
// to the current client. If q carries no COOKIE option, any COOKIE
// option is stripped from r. Server cookies presented by the client are
// validated and counted in the rdns_cookie_checks metric.
func applyCookie(q, r *dns.Msg, clientIP string) {
// 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, ok := getQueryCookie(q)
if !ok {
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 {
@@ -281,14 +340,6 @@ func applyCookie(q, r *dns.Msg, clientIP string) {
default:
cookieChecks.WithLabelValues("invalid").Inc()
}
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.5), not the client's.
opt.SetUDPSize(serverUDPSize)
cookie := make([]byte, 0, clientCookieLen+serverCookieLen)
cookie = append(cookie, clientCookie...)
cookie = append(cookie, makeServerCookie(clientIP, clientCookie, time.Now())...)
@@ -299,12 +350,12 @@ func applyCookie(q, r *dns.Msg, clientIP string) {
}
// writeResponse finalizes r for the client and writes it out: it applies
// per-client 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).
// 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) {
applyCookie(q, r, clientIP)
applyEDNS(q, r, clientIP)
r.MsgHdr.AuthenticatedData = false
if _, udp := w.LocalAddr().(*net.UDPAddr); udp {
limit := dns.MinMsgSize
+152 -21
View File
@@ -303,14 +303,14 @@ func TestRFC9018Vectors(t *testing.T) {
}
}
func TestApplyCookieEchoesClientCookie(t *testing.T) {
func TestApplyEDNSEchoesClientCookie(t *testing.T) {
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
q := newCookieQuery("example.test", dns.TypeA, clientCookie)
// Response without any OPT record.
r := new(dns.Msg)
r.SetReply(q)
applyCookie(q, r, "192.0.2.10")
applyEDNS(q, r, "192.0.2.10")
c := responseCookie(r)
if c == nil {
@@ -329,7 +329,7 @@ func TestApplyCookieEchoesClientCookie(t *testing.T) {
}
}
func TestApplyCookieReplacesUpstreamServerCookie(t *testing.T) {
func TestApplyEDNSReplacesUpstreamServerCookie(t *testing.T) {
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
upstreamServer := []byte{0x01, 0x00, 0x00, 0x00, 0x6a, 0xcb, 0x73, 0x63, 0xa3, 0x6c, 0x6a, 0x41, 0x62, 0xa3, 0x69, 0x6b}
q := newCookieQuery("example.test", dns.TypeA, clientCookie)
@@ -345,7 +345,7 @@ func TestApplyCookieReplacesUpstreamServerCookie(t *testing.T) {
Cookie: hex.EncodeToString(upstreamCookie),
})
applyCookie(q, r, "192.0.2.10")
applyEDNS(q, r, "192.0.2.10")
c := responseCookie(r)
if c == nil {
@@ -364,25 +364,38 @@ func TestApplyCookieReplacesUpstreamServerCookie(t *testing.T) {
}
}
func TestApplyCookieNoCookieInQuery(t *testing.T) {
// Query without a COOKIE option: any COOKIE option must be stripped
// from the response, even one present in a cached/upstream response.
func TestApplyEDNSNoCookieInQuery(t *testing.T) {
// Query with EDNS but without a COOKIE option: any COOKIE option must
// be stripped from the response, and the OPT record must be rebuilt
// for the responder (RFC 6891 sections 6.1.1 and 6.2.4).
q := newQuery("example.test", dns.TypeA, dns.ClassINET)
q.SetEdns0(1232, false)
q.IsEdns0().SetDo(true)
r := new(dns.Msg)
r.SetReply(q)
r.SetEdns0(1232, false)
r.SetEdns0(512, false)
r.IsEdns0().Option = append(r.IsEdns0().Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}),
Cookie: hex.EncodeToString([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}),
})
applyCookie(q, r, "192.0.2.10")
applyEDNS(q, r, "192.0.2.10")
if c := responseCookie(r); c != nil {
t.Errorf("response must not carry a COOKIE option, got %s", c.Cookie)
}
if r.IsEdns0() == nil {
t.Fatal("response to an EDNS query must carry an OPT record (RFC 6891 section 6.1.1)")
}
if size := r.IsEdns0().UDPSize(); size != serverUDPSize {
t.Errorf("response OPT UDP size = %d, want %d (responder's payload size)", size, serverUDPSize)
}
if !r.IsEdns0().Do() {
t.Error("response OPT must echo the query's DO bit")
}
// Query without EDNS at all.
// Query without EDNS at all: the response must not carry an OPT
// record (RFC 6891 section 7), even one present in a cached or
// upstream response.
q2 := newQuery("example.test", dns.TypeA, dns.ClassINET)
r2 := new(dns.Msg)
r2.SetReply(q2)
@@ -391,9 +404,9 @@ func TestApplyCookieNoCookieInQuery(t *testing.T) {
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString([]byte{1, 2, 3, 4, 5, 6, 7, 8}),
})
applyCookie(q2, r2, "192.0.2.10")
if c := responseCookie(r2); c != nil {
t.Errorf("response must not carry a COOKIE option, got %s", c.Cookie)
applyEDNS(q2, r2, "192.0.2.10")
if r2.IsEdns0() != nil {
t.Errorf("response to a non-EDNS query must not carry an OPT record, got udp: %d", r2.IsEdns0().UDPSize())
}
}
@@ -406,7 +419,7 @@ func counterValue(t *testing.T, c prometheus.Counter) float64 {
return m.GetCounter().GetValue()
}
func TestApplyCookieCountsServerCookieValidation(t *testing.T) {
func TestApplyEDNSCountsServerCookieValidation(t *testing.T) {
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
serverCookie := makeServerCookie("192.0.2.10", clientCookie, time.Now())
@@ -419,7 +432,7 @@ func TestApplyCookieCountsServerCookieValidation(t *testing.T) {
q := newCookieQuery("metric.test", dns.TypeA, append(append([]byte{}, clientCookie...), serverCookie...))
r := new(dns.Msg)
r.SetReply(q)
applyCookie(q, r, "192.0.2.10")
applyEDNS(q, r, "192.0.2.10")
if got := counterValue(t, cookieChecks.WithLabelValues("valid")); got != validBefore+1 {
t.Errorf("valid cookie checks = %v, want %v", got, validBefore+1)
}
@@ -429,7 +442,7 @@ func TestApplyCookieCountsServerCookieValidation(t *testing.T) {
q = newCookieQuery("metric.test", dns.TypeA, bogus)
r = new(dns.Msg)
r.SetReply(q)
applyCookie(q, r, "192.0.2.10")
applyEDNS(q, r, "192.0.2.10")
if got := counterValue(t, cookieChecks.WithLabelValues("invalid")); got != invalidBefore+1 {
t.Errorf("invalid cookie checks = %v, want %v", got, invalidBefore+1)
}
@@ -438,7 +451,7 @@ func TestApplyCookieCountsServerCookieValidation(t *testing.T) {
q = newCookieQuery("metric.test", dns.TypeA, clientCookie)
r = new(dns.Msg)
r.SetReply(q)
applyCookie(q, r, "192.0.2.10")
applyEDNS(q, r, "192.0.2.10")
if got := counterValue(t, cookieChecks.WithLabelValues("absent")); got != absentBefore+1 {
t.Errorf("absent cookie checks = %v, want %v", got, absentBefore+1)
}
@@ -598,8 +611,8 @@ func TestHandleQueryCookieAbsentOnCacheHit(t *testing.T) {
})
qcache.Set(cacheKey("plain.test", "IN", "A"), cached, cacheTTL())
// A client sending no COOKIE option must get no COOKIE option back,
// even on a cache hit.
// A client sending no EDNS/COOKIE at all must get no OPT record back,
// even on a cache hit whose entry carries one.
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
handleQuery(w, newQuery("plain.test", dns.TypeA, dns.ClassINET))
if w.msg == nil {
@@ -608,6 +621,9 @@ func TestHandleQueryCookieAbsentOnCacheHit(t *testing.T) {
if c := responseCookie(w.msg); c != nil {
t.Errorf("response to cookie-less query carries COOKIE option %s", c.Cookie)
}
if w.msg.IsEdns0() != nil {
t.Error("response to a non-EDNS query must not carry an OPT record (RFC 6891 section 7)")
}
if len(w.msg.Answer) != 1 {
t.Errorf("answers = %d, want 1", len(w.msg.Answer))
}
@@ -643,7 +659,7 @@ func TestHandleQueryCookieBlocklistAndServfail(t *testing.T) {
q := newCookieQuery("error.cookie.test", dns.TypeA, clientCookie)
r := new(dns.Msg)
r.SetRcode(q, dns.RcodeServerFailure)
applyCookie(q, r, "192.0.2.10")
applyEDNS(q, r, "192.0.2.10")
c = responseCookie(r)
if c == nil {
t.Fatal("SERVFAIL response has no COOKIE option")
@@ -651,3 +667,118 @@ func TestHandleQueryCookieBlocklistAndServfail(t *testing.T) {
gotClient, _ = decodeCookie(t, c)
mustEqual(t, "SERVFAIL response client cookie", gotClient, clientCookie)
}
// newProbeQuery builds a question-less query (QDCOUNT=0) carrying a
// COOKIE option, as used for the RFC 7873 section 5.4 server-cookie
// learning probe.
func newProbeQuery(clientCookie, serverCookie []byte) *dns.Msg {
q := new(dns.Msg)
q.RecursionDesired = true
q.SetEdns0(1232, false)
cookie := append(append([]byte{}, clientCookie...), serverCookie...)
q.IsEdns0().Option = append(q.IsEdns0().Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString(cookie),
})
return q
}
func TestHandleQueryMalformedCookie(t *testing.T) {
resetMaps()
qcache.Flush()
hostsMap["cookie.test"] = "192.0.2.10"
// RFC 7873 section 5.2.2: valid COOKIE option lengths are 8 and 16 to
// 40 inclusive; anything else must be answered with FORMERR.
for _, length := range []int{4, 12, 41} {
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
handleQuery(w, newCookieQuery("cookie.test", dns.TypeA, make([]byte, length)))
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Rcode != dns.RcodeFormatError {
t.Errorf("COOKIE option of %d bytes: rcode = %d, want FORMERR", length, w.msg.Rcode)
}
if c := responseCookie(w.msg); c != nil {
t.Errorf("COOKIE option of %d bytes: FORMERR response carries a COOKIE option (%s)", length, c.Cookie)
}
}
// Valid lengths are answered normally, with the client cookie echoed
// and a fresh server cookie minted.
for _, length := range []int{8, 16, 40} {
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
handleQuery(w, newCookieQuery("cookie.test", dns.TypeA, make([]byte, length)))
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Rcode != dns.RcodeSuccess {
t.Errorf("COOKIE option of %d bytes: rcode = %d, want NOERROR", length, w.msg.Rcode)
}
if len(w.msg.Answer) != 1 {
t.Errorf("COOKIE option of %d bytes: answers = %d, want 1", length, len(w.msg.Answer))
}
if c := responseCookie(w.msg); c == nil {
t.Errorf("COOKIE option of %d bytes: response has no COOKIE option", length)
}
}
}
func TestHandleQueryCookieProbe(t *testing.T) {
resetMaps()
qcache.Flush()
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
serverCookie := makeServerCookie("192.0.2.10", clientCookie, time.Now())
// Probe with a client cookie only: NOERROR with a fresh server
// cookie (RFC 7873 section 5.4).
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
handleQuery(w, newProbeQuery(clientCookie, nil))
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Rcode != dns.RcodeSuccess {
t.Errorf("rcode = %d, want NOERROR for a client-cookie-only probe", w.msg.Rcode)
}
if len(w.msg.Question) != 0 || len(w.msg.Answer) != 0 {
t.Error("probe response must have an empty question and answer section")
}
c := responseCookie(w.msg)
if c == nil {
t.Fatal("probe response has no COOKIE option")
}
gotClient, gotServer := decodeCookie(t, c)
mustEqual(t, "probe response client cookie", gotClient, clientCookie)
if !validateServerCookie("192.0.2.10", clientCookie, gotServer, time.Now()) {
t.Error("probe response server cookie does not validate")
}
// Probe re-establishing a valid server cookie: NOERROR.
w = &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
handleQuery(w, newProbeQuery(clientCookie, serverCookie))
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Rcode != dns.RcodeSuccess {
t.Errorf("rcode = %d, want NOERROR for a probe with a valid server cookie", w.msg.Rcode)
}
// Probe re-establishing an invalid server cookie: BADCOOKIE, with a
// fresh server cookie so the client can retry (RFC 7873 sections 5.4
// and 5.3).
w = &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
handleQuery(w, newProbeQuery(clientCookie, make([]byte, serverCookieLen)))
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Rcode != dns.RcodeBadCookie {
t.Errorf("rcode = %d, want BADCOOKIE for a probe with an invalid server cookie", w.msg.Rcode)
}
c = responseCookie(w.msg)
if c == nil {
t.Fatal("BADCOOKIE response has no COOKIE option")
}
gotClient, _ = decodeCookie(t, c)
mustEqual(t, "BADCOOKIE response client cookie", gotClient, clientCookie)
}
+48 -8
View File
@@ -328,13 +328,37 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
queries.Inc()
client := clientIP(w)
if len(q.Question) == 0 {
// RFC 7873 section 5.2.2: a COOKIE option whose length is not 8 or in
// the 16 to 40 range is malformed and must be answered with FORMERR.
if _, _, state := getQueryCookie(q); state == cookieMalformed {
r := new(dns.Msg)
r.SetRcode(q, dns.RcodeFormatError)
writeResponse(w, q, r, client)
return
}
if len(q.Question) == 0 {
r := new(dns.Msg)
clientCookie, serverCookie, state := getQueryCookie(q)
switch {
case state != cookieValid:
// A question-less query without a valid COOKIE option is a
// format error.
r.SetRcode(q, dns.RcodeFormatError)
case len(serverCookie) > 0 && !validateServerCookie(client, clientCookie, serverCookie, time.Now()):
// RFC 7873 section 5.4: re-establishing an invalid server
// cookie is answered with BADCOOKIE.
r.SetRcode(q, dns.RcodeBadCookie)
default:
// RFC 7873 section 5.4: a question-less query with a COOKIE
// option is a server-cookie learning probe; answer NOERROR
// with a fresh cookie (added by writeResponse).
r.SetRcode(q, dns.RcodeSuccess)
}
writeResponse(w, q, r, client)
return
}
var (
r *dns.Msg
err error
@@ -432,9 +456,10 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
} else {
rcode = r.Rcode
r.MsgHdr.RecursionAvailable = true
// Never cache upstream COOKIE options: they are stripped here and
// rebuilt per client when the entry is served.
stripCookies(r)
// Never cache the upstream OPT record (RFC 6891 section 6.2.1:
// OPT records MUST NOT be cached); it is rebuilt per client when
// the entry is served.
removeOPT(r)
qcache.Set(key, r.Copy(), cacheTTL())
if *logs {
log.Println(client, qname, qclass, qtype, getRcode(rcode), proto)
@@ -444,13 +469,30 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
responses.WithLabelValues(qtype, getRcode(rcode)).Inc()
}
// msgAcceptFunc accepts question-less QUERY requests so that RFC 7873
// section 5.4 server-cookie learning probes reach the handler; all other
// messages are judged by miekg/dns' default rules.
func msgAcceptFunc(dh dns.Header) dns.MsgAcceptAction {
opcode := int(dh.Bits>>11) & 0xF
if dh.Qdcount == 0 && opcode == dns.OpcodeQuery {
return dns.MsgAccept
}
return dns.DefaultMsgAcceptFunc(dh)
}
func serve(addr string, port string, network string, started func()) *dns.Server {
server := &dns.Server{
Addr: net.JoinHostPort(addr, port),
Net: network,
Addr: net.JoinHostPort(addr, port),
Net: network,
Handler: dns.HandlerFunc(handleQuery),
// The handler is set directly instead of going through the
// default ServeMux: the mux answers question-less queries with
// REFUSED, but those must reach handleQuery as RFC 7873
// section 5.4 server-cookie learning probes.
ReusePort: true,
UDPSize: serverUDPSize,
NotifyStartedFunc: started,
MsgAcceptFunc: msgAcceptFunc,
}
go func() {
if err := server.ListenAndServe(); err != nil {
@@ -608,8 +650,6 @@ func main() {
}()
}
dns.HandleFunc(".", handleQuery)
var readyOnce sync.Once
ready := func() { readyOnce.Do(func() { up.Set(1) }) }
servers := []*dns.Server{
+110 -7
View File
@@ -56,8 +56,9 @@ func mockUDPWriter(t *testing.T) *mockWriter {
// TestHandleQueryUpstreamCookieAndAD exercises the full forwarding path:
// the upstream response's COOKIE is replaced with a freshly minted one,
// the upstream AD bit is cleared, the cache entry is stored without a
// COOKIE option, and cache hits rebuild the cookie for the new client.
// the upstream AD bit is cleared, the cache entry is stored without the
// upstream OPT record (RFC 6891 section 6.2.1), and cache hits rebuild
// both the OPT record and the cookie for the new client.
func TestHandleQueryUpstreamCookieAndAD(t *testing.T) {
resetMaps()
qcache.Flush()
@@ -71,8 +72,15 @@ func TestHandleQueryUpstreamCookieAndAD(t *testing.T) {
Hdr: dns.RR_Header{Name: q.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300},
A: net.ParseIP("192.0.2.1"),
})
r.SetEdns0(4096, false)
if clientCookie, _, ok := getQueryCookie(q); ok {
r.SetEdns0(512, false)
// An upstream EDE option (info code 0, "Other Error"), which must
// not survive into the cache or the client response (OPT records
// are never cached or forwarded, RFC 6891 section 6.1.1).
r.IsEdns0().Option = append(r.IsEdns0().Option, &dns.EDNS0_EDE{
InfoCode: 0, // RFC 8914: Other Error
ExtraText: "upstream ede",
})
if clientCookie, _, state := getQueryCookie(q); state == cookieValid {
cookie := append(append([]byte{}, clientCookie...), upstreamServerCookie...)
r.IsEdns0().Option = append(r.IsEdns0().Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
@@ -120,14 +128,28 @@ func TestHandleQueryUpstreamCookieAndAD(t *testing.T) {
t.Error("response server cookie does not validate for the querying client")
}
// The cache entry must be stored without the upstream COOKIE option.
// The cache entry must be stored without the upstream OPT record:
// OPT records MUST NOT be cached (RFC 6891 section 6.2.1).
key := cacheKey("upstream.test", "IN", "A")
cached, found := qcache.Get(key)
if !found {
t.Fatal("response was not cached")
}
if c := responseCookie(cached.(*dns.Msg)); c != nil {
t.Errorf("cached entry carries a COOKIE option (%s), want none", c.Cookie)
if cached.(*dns.Msg).IsEdns0() != nil {
t.Error("cached entry carries an OPT record, want none (RFC 6891 section 6.2.1)")
}
// The client response carries a freshly built OPT record: the
// responder's payload size, the query's DO bit, and our COOKIE —
// but not the upstream's EDE option.
if w1.msg.IsEdns0() == nil {
t.Fatal("response has no OPT record")
}
if size := w1.msg.IsEdns0().UDPSize(); size != serverUDPSize {
t.Errorf("response OPT UDP size = %d, want %d (responder's payload size)", size, serverUDPSize)
}
if len(w1.msg.IsEdns0().Option) != 1 {
t.Errorf("response OPT options = %d, want 1 (COOKIE only, upstream options not forwarded)", len(w1.msg.IsEdns0().Option))
}
// Second query from a different client (different cookie, different
@@ -374,3 +396,84 @@ func TestHandleCacheDecrementsTTL(t *testing.T) {
t.Errorf("NXDOMAIN SOA TTL = %d, want 90 (120 decremented by 30s)", ttl)
}
}
func TestMsgAcceptFunc(t *testing.T) {
header := func(qdcount uint16, opcode int) dns.Header {
return dns.Header{Bits: uint16(opcode)<<11 | 0x0100, Qdcount: qdcount} // RD set
}
// Question-less QUERY requests are accepted so that RFC 7873
// section 5.4 server-cookie learning probes reach the handler.
if got := msgAcceptFunc(header(0, dns.OpcodeQuery)); got != dns.MsgAccept {
t.Errorf("msgAcceptFunc(QDCOUNT=0 QUERY) = %v, want MsgAccept", got)
}
// Everything else follows the default rules.
if got := msgAcceptFunc(header(1, dns.OpcodeQuery)); got != dns.MsgAccept {
t.Errorf("msgAcceptFunc(QDCOUNT=1 QUERY) = %v, want MsgAccept", got)
}
if got := msgAcceptFunc(header(2, dns.OpcodeQuery)); got != dns.MsgReject {
t.Errorf("msgAcceptFunc(QDCOUNT=2 QUERY) = %v, want MsgReject", got)
}
if got := msgAcceptFunc(header(0, dns.OpcodeUpdate)); got != dns.MsgRejectNotImplemented {
t.Errorf("msgAcceptFunc(QDCOUNT=0 UPDATE) = %v, want MsgRejectNotImplemented", got)
}
}
// TestServerCookieProbe runs the real server stack (miekg/dns server with
// msgAcceptFunc and handleQuery) over UDP and exercises the RFC 7873
// section 5.4 server-cookie learning probe and the malformed-COOKIE FORMERR
// end to end.
func TestServerCookieProbe(t *testing.T) {
resetMaps()
qcache.Flush()
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := &dns.Server{
PacketConn: pc,
Handler: dns.HandlerFunc(handleQuery),
MsgAcceptFunc: msgAcceptFunc,
UDPSize: serverUDPSize,
}
go func() { _ = srv.ActivateAndServe() }()
t.Cleanup(func() { _ = srv.Shutdown() })
addr := pc.LocalAddr().String()
client := &dns.Client{Net: "udp", UDPSize: dns.MaxMsgSize}
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
// QDCOUNT=0 probe with a client cookie: NOERROR, empty answer
// section, fresh server cookie.
r, _, err := client.Exchange(newProbeQuery(clientCookie, nil), addr)
if err != nil {
t.Fatal(err)
}
if r.Rcode != dns.RcodeSuccess {
t.Errorf("probe rcode = %d, want NOERROR", r.Rcode)
}
if len(r.Answer) != 0 {
t.Errorf("probe answer count = %d, want 0", len(r.Answer))
}
c := responseCookie(r)
if c == nil {
t.Fatal("probe response has no COOKIE option")
}
gotClient, gotServer := decodeCookie(t, c)
mustEqual(t, "probe response client cookie", gotClient, clientCookie)
if !validateServerCookie("127.0.0.1", clientCookie, gotServer, time.Now()) {
t.Error("probe response server cookie does not validate for the client address")
}
// A query with a malformed COOKIE option gets FORMERR.
r2, _, err := client.Exchange(newCookieQuery("malformed.test", dns.TypeA, []byte{1, 2, 3, 4}), addr)
if err != nil {
t.Fatal(err)
}
if r2.Rcode != dns.RcodeFormatError {
t.Errorf("malformed COOKIE rcode = %d, want FORMERR", r2.Rcode)
}
if c := responseCookie(r2); c != nil {
t.Error("FORMERR response to a malformed COOKIE option carries a COOKIE option")
}
}