fix EDNS COOKIE (RFC 7873/9018) handling: terminate cookies at the resolver #2

Merged
marvin merged 3 commits from fix/edns-cookie-handling into main 2026-10-11 19:20:44 +00:00
10 changed files with 1868 additions and 775288 deletions

No files matched your search

+35 -12
View File
@@ -41,23 +41,33 @@ jobs:
- name: Create deb dir tree
run: |
mkdir -p rdns-amd64/usr/bin
mkdir -p rdns-amd64/etc/rdns
mkdir -p rdns-amd64/DEBIAN
mkdir -p rdns-arm64/usr/bin
mkdir -p rdns-arm64/etc/rdns
mkdir -p rdns-arm64/DEBIAN
for arch in amd64 arm64; do
mkdir -p rdns-$arch/usr/local/bin
mkdir -p rdns-$arch/etc/rdns
mkdir -p rdns-$arch/DEBIAN
mkdir -p rdns-$arch/lib/systemd/system
mkdir -p rdns-$arch/etc/logrotate.d
mkdir -p rdns-$arch/etc/rsyslog.d
done
- name: Copy binaries
run: |
cp bin/rdns-linux-amd64 rdns-amd64/usr/bin/rdns
cp bin/rdns-linux-arm64 rdns-arm64/usr/bin/rdns
cp bin/rdns-linux-amd64 rdns-amd64/usr/local/bin/rdns
cp bin/rdns-linux-arm64 rdns-arm64/usr/local/bin/rdns
- name: Copy configuration example
run: |
cp -r conf/* rdns-amd64/etc/rdns/
cp -r conf/* rdns-arm64/etc/rdns/
- name: Copy service and log configs
run: |
for arch in amd64 arm64; do
cp utils/services/rdns.service rdns-$arch/lib/systemd/system/
cp utils/logrotate.d/rdns rdns-$arch/etc/logrotate.d/
cp utils/rsyslog.d/56-rdns.conf rdns-$arch/etc/rsyslog.d/
done
- name: Get version
run: |
TAG=${{ gitea.ref_name }}
@@ -67,19 +77,32 @@ jobs:
run: |
echo "Package: rdns" > rdns-amd64/DEBIAN/control
echo "Version: $VERSION" >> rdns-amd64/DEBIAN/control
echo "Installed-Size: $(du -sk rdns-amd64 | cut -f1)" >> rdns-amd64/DEBIAN/control
echo "Maintainer: tchivert <me@tchv.fr>" >> rdns-amd64/DEBIAN/control
echo "Architecture: amd64" >> rdns-amd64/DEBIAN/control
echo "Homepage: https://git.rznet.fr/tchivert/rdns" >> rdns-amd64/DEBIAN/control
echo "Description: another disk usage utility" >> rdns-amd64/DEBIAN/control
echo "Homepage: https://git.rznet.fr/tchivert/rdns-go" >> rdns-amd64/DEBIAN/control
echo "Description: caching and forwarding DNS resolver" >> rdns-amd64/DEBIAN/control
echo " Acts as a local recursive DNS resolver: forwards queries to" >> rdns-amd64/DEBIAN/control
echo " configured upstream nameservers and caches the responses." >> rdns-amd64/DEBIAN/control
- name: Prepare arm64 control file
run: |
echo "Package: rdns" > rdns-arm64/DEBIAN/control
echo "Version: $VERSION" >> rdns-arm64/DEBIAN/control
echo "Installed-Size: $(du -sk rdns-arm64 | cut -f1)" >> rdns-arm64/DEBIAN/control
echo "Maintainer: tchivert <me@tchv.fr>" >> rdns-arm64/DEBIAN/control
echo "Architecture: arm64" >> rdns-arm64/DEBIAN/control
echo "Homepage: https://git.rznet.fr/tchivert/rdns" >> rdns-arm64/DEBIAN/control
echo "Description: another disk usage utility" >> rdns-arm64/DEBIAN/control
echo "Homepage: https://git.rznet.fr/tchivert/rdns-go" >> rdns-arm64/DEBIAN/control
echo "Description: caching and forwarding DNS resolver" >> rdns-arm64/DEBIAN/control
echo " Acts as a local recursive DNS resolver: forwards queries to" >> rdns-arm64/DEBIAN/control
echo " configured upstream nameservers and caches the responses." >> rdns-arm64/DEBIAN/control
- name: Register conffiles
run: |
for arch in amd64 arm64; do
echo "/etc/rdns/hosts" > rdns-$arch/DEBIAN/conffiles
echo "/etc/rdns/rdns.zones" >> rdns-$arch/DEBIAN/conffiles
done
- name: Build deb files
run: |
+21
View File
@@ -0,0 +1,21 @@
name: test
on:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup go
uses: actions/setup-go@v4
with:
go-version: '>=1.26'
- name: Run tests
run: |
go vet ./...
go test -race ./...
+2
View File
@@ -1,2 +1,4 @@
/rdns.log
/rdns
# Generated by utils/blocklist_update, not stored in git
/conf/blocklist.txt
+21 -2
View File
@@ -1,6 +1,15 @@
# rdns-go
rdns is a reverse DNS proxy resolver written in Go. It acts as a DNS server, forwarding DNS queries to configured nameservers and returning the corresponding reverse DNS records.
rdns is a caching, forwarding DNS resolver written in Go. It acts as a DNS server, forwarding DNS queries to configured upstream nameservers and caching the responses (including negative ones).
## 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 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)
- Blocklist, custom zones and hosts files
- Prometheus metrics (optional)
## Building
@@ -31,11 +40,13 @@ docker-compose up -d
This command will start the rdns-go container in the background.
On a host, install the packaged binary (see the release assets) or copy the binary and use the provided systemd unit in `utils/services/rdns.service`.
## Configuration
The rdns-go project can be configured using the following command arguments:
- `-a` (default: `0.0.0.0`): The address to listen on.
- `-a` (default: `0.0.0.0`): The address to listen on. Use `127.0.0.1` for a machine-local resolver.
- `-p` (default: `53`): The port to listen on.
- `-b` (default: none): The path to the blocklist file. This file contains a list of domain names to block.
- `-z` (default: none): The path to the zones file. This file contains custom zone information.
@@ -47,6 +58,14 @@ The rdns-go project can be configured using the following command arguments:
- `-l` (default: `false`): Whether to enable query logging.
- `-m` (default: `false`): Whether to enable Prometheus metrics on port 9153.
## Utilities
The `utils/` directory contains deployment helpers:
- `utils/blocklist_update`: downloads and merges public blocklists into a single domain list. Generate the blocklist with `utils/blocklist_update > conf/blocklist.txt` (`conf/blocklist.txt` is generated data and is not stored in git).
- `utils/services/rdns.service`: systemd unit running rdns as a local caching resolver.
- `utils/logrotate.d/rdns` and `utils/rsyslog.d/56-rdns.conf`: log rotation and routing for the query log.
## Acknowledgments
This project uses code from [miekg/dns](https://github.com/miekg/dns) and [patrickmn/go-cache](https://github.com/patrickmn/go-cache).
-775237
View File
File diff suppressed because it is too large. Load diff
+372
View File
@@ -0,0 +1,372 @@
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)
}
}
+784
View File
@@ -0,0 +1,784 @@
package main
import (
"bytes"
"encoding/binary"
"encoding/hex"
"net"
"testing"
"time"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
)
func newCookieQuery(name string, qtype uint16, clientCookie []byte) *dns.Msg {
q := newQuery(name, qtype, dns.ClassINET)
q.SetEdns0(1232, false)
opt := q.IsEdns0()
opt.Option = append(opt.Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString(clientCookie),
})
return q
}
func responseCookie(m *dns.Msg) *dns.EDNS0_COOKIE {
opt := m.IsEdns0()
if opt == nil {
return nil
}
for _, o := range opt.Option {
if c, ok := o.(*dns.EDNS0_COOKIE); ok {
return c
}
}
return nil
}
func decodeCookie(t *testing.T, c *dns.EDNS0_COOKIE) (client, server []byte) {
t.Helper()
raw, err := hex.DecodeString(c.Cookie)
if err != nil {
t.Fatalf("COOKIE option is not valid hex: %v", err)
}
if len(raw) < clientCookieLen {
t.Fatalf("COOKIE option too short: %d bytes", len(raw))
}
return raw[:clientCookieLen], raw[clientCookieLen:]
}
func mustEqual(t *testing.T, what string, got, want []byte) {
t.Helper()
if !bytes.Equal(got, want) {
t.Errorf("%s = %x, want %x", what, got, want)
}
}
// Official SipHash-2-4 reference vectors (key 00 01 02 ... 0f, inputs
// of increasing length), from the reference implementation test suite.
var siphashRefVectors = [][]byte{
{0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72},
{0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74},
{0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d},
{0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85},
{0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf},
{0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18},
{0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb},
{0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab},
{0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93},
{0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e},
{0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a},
{0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4},
{0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75},
{0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14},
{0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7},
{0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1},
{0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f},
{0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69},
{0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b},
{0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb},
{0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe},
{0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0},
{0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93},
{0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8},
{0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8},
{0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc},
{0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17},
{0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f},
{0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde},
{0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6},
{0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad},
{0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32},
{0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71},
{0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7},
{0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12},
{0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15},
{0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31},
{0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02},
{0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca},
{0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a},
{0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e},
{0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad},
{0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18},
{0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4},
{0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9},
{0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9},
{0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb},
{0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0},
{0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6},
{0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7},
{0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee},
{0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1},
{0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a},
{0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81},
{0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f},
{0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24},
{0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7},
{0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea},
{0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60},
{0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66},
{0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c},
{0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f},
{0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5},
{0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95},
}
func TestSipHash24ReferenceVectors(t *testing.T) {
var key [16]byte
for i := range key {
key[i] = byte(i)
}
var in [64]byte
for i := range in {
in[i] = byte(i)
}
for i, want := range siphashRefVectors {
got := siphash24(key[:], in[:i])
if got != binary.LittleEndian.Uint64(want) {
t.Errorf("siphash24(key, in[:%d]) = %016x, want %016x", i, got, binary.LittleEndian.Uint64(want))
}
}
}
func TestMakeServerCookie(t *testing.T) {
now := time.Unix(1700000000, 0)
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
sc := makeServerCookie("192.0.2.10", clientCookie, now)
if len(sc) != serverCookieLen {
t.Fatalf("server cookie length = %d, want %d", len(sc), serverCookieLen)
}
if sc[0] != cookieVersion {
t.Errorf("server cookie version = %d, want %d", sc[0], cookieVersion)
}
if ts := binary.BigEndian.Uint32(sc[4:8]); ts != uint32(now.Unix()) {
t.Errorf("server cookie timestamp = %d, want %d (seconds since epoch)", ts, now.Unix())
}
if sc[1] != 0 || sc[2] != 0 || sc[3] != 0 {
t.Errorf("server cookie reserved bytes = %x, want 000000", sc[1:4])
}
// Bound to the client address.
if other := makeServerCookie("192.0.2.11", clientCookie, now); bytes.Equal(sc, other) {
t.Error("server cookie must differ for different client IPs")
}
// Bound to the client cookie.
if other := makeServerCookie("192.0.2.10", []byte{1, 2, 3, 4, 5, 6, 7, 8}, now); bytes.Equal(sc, other) {
t.Error("server cookie must differ for different client cookies")
}
// Changes over time.
if other := makeServerCookie("192.0.2.10", clientCookie, now.Add(2*time.Minute)); bytes.Equal(sc, other) {
t.Error("server cookie must change over time")
}
// Works for IPv6 clients too.
if other := makeServerCookie("2001:db8::1", clientCookie, now); len(other) != serverCookieLen {
t.Errorf("IPv6 server cookie length = %d, want %d", len(other), serverCookieLen)
}
}
func TestValidateServerCookie(t *testing.T) {
now := time.Now()
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
sc := makeServerCookie("192.0.2.10", clientCookie, now)
if !validateServerCookie("192.0.2.10", clientCookie, sc, now) {
t.Error("freshly minted server cookie must validate")
}
if validateServerCookie("192.0.2.11", clientCookie, sc, now) {
t.Error("server cookie must not validate for a different client IP")
}
if validateServerCookie("192.0.2.10", []byte{1, 2, 3, 4, 5, 6, 7, 8}, sc, now) {
t.Error("server cookie must not validate for a different client cookie")
}
if validateServerCookie("192.0.2.10", clientCookie, sc[:15], now) {
t.Error("server cookie with wrong length must not validate")
}
// Skew tolerance: up to one hour in the past is accepted.
old := makeServerCookie("192.0.2.10", clientCookie, now.Add(-30*time.Minute))
if !validateServerCookie("192.0.2.10", clientCookie, old, now) {
t.Error("server cookie 30 minutes old must validate (skew tolerance)")
}
tooOld := makeServerCookie("192.0.2.10", clientCookie, now.Add(-2*time.Hour))
if validateServerCookie("192.0.2.10", clientCookie, tooOld, now) {
t.Error("server cookie 2 hours old must not validate")
}
// Small future skew is tolerated, larger future skew is not.
future := makeServerCookie("192.0.2.10", clientCookie, now.Add(2*time.Minute))
if !validateServerCookie("192.0.2.10", clientCookie, future, now) {
t.Error("server cookie 2 minutes in the future must validate (skew tolerance)")
}
tooFarFuture := makeServerCookie("192.0.2.10", clientCookie, now.Add(10*time.Minute))
if validateServerCookie("192.0.2.10", clientCookie, tooFarFuture, now) {
t.Error("server cookie 10 minutes in the future must not validate")
}
// Rotation: cookies minted before a rotation stay valid (previous
// secret is retained), cookies from two rotations ago do not.
preRotation := makeServerCookie("192.0.2.10", clientCookie, now)
rotateCookieSecrets()
if !validateServerCookie("192.0.2.10", clientCookie, preRotation, now) {
t.Error("server cookie minted before secret rotation must still validate")
}
rotateCookieSecrets()
if validateServerCookie("192.0.2.10", clientCookie, preRotation, now) {
t.Error("server cookie minted two rotations ago must not validate")
}
}
// TestRFC9018Vectors pins the server cookie construction against the test
// vectors of RFC 9018 Appendix A.
func TestRFC9018Vectors(t *testing.T) {
setSecrets := func(current, previous [16]byte) (restore func()) {
cookieSecrets.Lock()
oldCurrent, oldPrevious := cookieSecrets.current, cookieSecrets.previous
cookieSecrets.current, cookieSecrets.previous = current, previous
cookieSecrets.Unlock()
return func() {
cookieSecrets.Lock()
cookieSecrets.current, cookieSecrets.previous = oldCurrent, oldPrevious
cookieSecrets.Unlock()
}
}
secret := func(hexSecret string) [16]byte {
raw, err := hex.DecodeString(hexSecret)
if err != nil {
t.Fatal(err)
}
var s [16]byte
copy(s[:], raw)
return s
}
cookie := func(hexCookie string) []byte {
raw, err := hex.DecodeString(hexCookie)
if err != nil {
t.Fatal(err)
}
return raw
}
// A.1 / A.2: IPv4 client 198.51.100.100.
restore := setSecrets(secret("e5e973e5a6b2a43f48e7dc849e37bfcf"), secret("0000000000000000000000000000000000"))
defer restore()
clientCookie := cookie("2464c4abcf10c957")
sc := makeServerCookie("198.51.100.100", clientCookie, time.Unix(1559731985, 0))
if want := cookie("010000005cf79f111f8130c3eee29480"); !bytes.Equal(sc, want) {
t.Errorf("A.1 server cookie = %x, want %x", sc, want)
}
if !validateServerCookie("198.51.100.100", clientCookie, sc, time.Unix(1559731985, 0)) {
t.Error("A.1 server cookie must validate")
}
sc = makeServerCookie("198.51.100.100", clientCookie, time.Unix(1559734385, 0))
if want := cookie("010000005cf7a871d4a564a1442aca77"); !bytes.Equal(sc, want) {
t.Errorf("A.2 server cookie = %x, want %x", sc, want)
}
// A.3: another IPv4 client, 203.0.113.203.
clientCookie = cookie("fc93fc62807ddb86")
sc = makeServerCookie("203.0.113.203", clientCookie, time.Unix(1559734700, 0))
if want := cookie("010000005cf7a9acf73a7810aca2381e"); !bytes.Equal(sc, want) {
t.Errorf("A.3 server cookie = %x, want %x", sc, want)
}
// A.4: IPv6 client with a rolled-over secret: the previous secret
// still validates the cookie the client presents, the new secret is
// used for minting.
restore()
restore = setSecrets(secret("445536bcd2513298075a5d379663c962"), secret("dd3bdf9344b678b185a6f5cb60fca715"))
defer restore()
clientCookie = cookie("22681ab97d52c298")
presented := cookie("010000005cf7c57926556bd0934c72f8")
now := time.Unix(1559741961, 0)
if !validateServerCookie("2001:db8:220:1:59de:d0f4:8769:82b8", clientCookie, presented, now) {
t.Error("A.4 server cookie minted with the previous secret must still validate")
}
sc = makeServerCookie("2001:db8:220:1:59de:d0f4:8769:82b8", clientCookie, now)
if want := cookie("010000005cf7c609a6bb79d16625507a"); !bytes.Equal(sc, want) {
t.Errorf("A.4 server cookie = %x, want %x", sc, want)
}
}
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)
applyEDNS(q, r, "192.0.2.10")
c := responseCookie(r)
if c == nil {
t.Fatal("response has no COOKIE option")
}
gotClient, gotServer := decodeCookie(t, c)
mustEqual(t, "echoed client cookie", gotClient, clientCookie)
if len(gotServer) != serverCookieLen {
t.Errorf("server cookie length = %d, want %d", len(gotServer), serverCookieLen)
}
if !validateServerCookie("192.0.2.10", clientCookie, gotServer, time.Now()) {
t.Error("response server cookie does not validate for the querying client")
}
if r.IsEdns0().UDPSize() != serverUDPSize {
t.Errorf("response OPT UDP size = %d, want %d (responder's payload size)", r.IsEdns0().UDPSize(), serverUDPSize)
}
}
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)
// Response as relayed from upstream: echoes our client cookie and
// carries the upstream server cookie, which must not be relayed.
r := new(dns.Msg)
r.SetReply(q)
r.SetEdns0(1232, false)
upstreamCookie := append(append([]byte{}, clientCookie...), upstreamServer...)
r.IsEdns0().Option = append(r.IsEdns0().Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString(upstreamCookie),
})
applyEDNS(q, r, "192.0.2.10")
c := responseCookie(r)
if c == nil {
t.Fatal("response has no COOKIE option")
}
gotClient, gotServer := decodeCookie(t, c)
mustEqual(t, "echoed client cookie", gotClient, clientCookie)
if bytes.Equal(gotServer, upstreamServer) {
t.Error("upstream server cookie must not be relayed to the client")
}
if len(gotServer) != serverCookieLen {
t.Errorf("server cookie length = %d, want %d", len(gotServer), serverCookieLen)
}
if !validateServerCookie("192.0.2.10", clientCookie, gotServer, time.Now()) {
t.Error("response server cookie does not validate for the querying client")
}
}
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(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}),
})
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: 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)
r2.SetEdns0(1232, false)
r2.IsEdns0().Option = append(r2.IsEdns0().Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString([]byte{1, 2, 3, 4, 5, 6, 7, 8}),
})
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())
}
}
func counterValue(t *testing.T, c prometheus.Counter) float64 {
t.Helper()
var m dto.Metric
if err := c.Write(&m); err != nil {
t.Fatal(err)
}
return m.GetCounter().GetValue()
}
func TestApplyEDNSCountsServerCookieValidation(t *testing.T) {
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
serverCookie := makeServerCookie("192.0.2.10", clientCookie, time.Now())
validBefore := counterValue(t, cookieChecks.WithLabelValues("valid"))
invalidBefore := counterValue(t, cookieChecks.WithLabelValues("invalid"))
absentBefore := counterValue(t, cookieChecks.WithLabelValues("absent"))
// A client presenting a valid server cookie (echoed back per RFC 7873
// section 5.2.2).
q := newCookieQuery("metric.test", dns.TypeA, append(append([]byte{}, clientCookie...), serverCookie...))
r := new(dns.Msg)
r.SetReply(q)
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)
}
// A client presenting a bogus server cookie.
bogus := append(append([]byte{}, clientCookie...), make([]byte, serverCookieLen)...)
q = newCookieQuery("metric.test", dns.TypeA, bogus)
r = new(dns.Msg)
r.SetReply(q)
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)
}
// A client sending a client cookie only.
q = newCookieQuery("metric.test", dns.TypeA, clientCookie)
r = new(dns.Msg)
r.SetReply(q)
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)
}
}
func TestHandleQueryCookieFirstAndRepeat(t *testing.T) {
resetMaps()
qcache.Flush()
hostsMap["cookie.test"] = "192.0.2.10"
clientCookie1 := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
clientCookie2 := []byte{0xde, 0xad, 0xbe, 0xef, 0x00, 0x11, 0x22, 0x33}
// First query from client 1 (cache miss, answered locally).
w1 := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
q1 := newCookieQuery("cookie.test", dns.TypeA, clientCookie1)
handleQuery(w1, q1)
if w1.msg == nil {
t.Fatal("no response written")
}
c1 := responseCookie(w1.msg)
if c1 == nil {
t.Fatal("first response has no COOKIE option")
}
gotClient, gotServer := decodeCookie(t, c1)
mustEqual(t, "first response client cookie", gotClient, clientCookie1)
if len(gotServer) != serverCookieLen {
t.Fatalf("first response server cookie length = %d, want %d", len(gotServer), serverCookieLen)
}
if len(w1.msg.Answer) != 1 {
t.Fatalf("first response answers = %d, want 1", len(w1.msg.Answer))
}
// The cached entry must not have been polluted with client 1's cookie.
if cached, found := qcache.Get(cacheKey("cookie.test", "IN", "A")); found {
if c := responseCookie(cached.(*dns.Msg)); c != nil {
t.Errorf("cached entry carries a COOKIE option (%s), want none", c.Cookie)
}
} else {
t.Fatal("response was not cached")
}
// Repeat query from a different client (different address and
// different client cookie): cache hit, cookie must be rewritten.
w2 := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.99"), Port: 5300}}
q2 := newCookieQuery("cookie.test", dns.TypeA, clientCookie2)
q2.Id = 4321
handleQuery(w2, q2)
if w2.msg == nil {
t.Fatal("no response written")
}
if w2.msg.Id != 4321 {
t.Errorf("cached response ID = %d, want 4321", w2.msg.Id)
}
c2 := responseCookie(w2.msg)
if c2 == nil {
t.Fatal("cached response has no COOKIE option")
}
gotClient2, gotServer2 := decodeCookie(t, c2)
mustEqual(t, "cached response client cookie", gotClient2, clientCookie2)
if bytes.Equal(gotServer2, gotServer) {
t.Error("cached response must carry a fresh server cookie for the new client")
}
if !validateServerCookie("192.0.2.99", clientCookie2, gotServer2, time.Now()) {
t.Error("cached response server cookie does not validate for the new client")
}
if len(w2.msg.Answer) != 1 {
t.Errorf("cached response answers = %d, want 1", len(w2.msg.Answer))
}
}
func TestHandleQueryCookieCacheHitNXDOMAIN(t *testing.T) {
resetMaps()
qcache.Flush()
// Simulate a cached negative response that still carries the COOKIE
// option of the original upstream exchange.
oldClientCookie := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}
upstreamServer := []byte{0x01, 0x00, 0x00, 0x00, 0x6a, 0xcb, 0x73, 0x63, 0xa3, 0x6c, 0x6a, 0x41, 0x62, 0xa3, 0x69, 0x6b}
cached := new(dns.Msg)
cached.SetReply(newQuery("nx.cookie.test", dns.TypeTXT, dns.ClassINET))
cached.Rcode = dns.RcodeNameError
cached.Ns = []dns.RR{&dns.SOA{
Hdr: dns.RR_Header{Name: "cookie.test.", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 300},
Ns: "ns.cookie.test.",
Mbox: "hostmaster.cookie.test.",
Serial: 1,
Refresh: 3600,
Retry: 600,
Expire: 86400,
Minttl: 300,
}}
cached.SetEdns0(1232, false)
cachedCookie := append(append([]byte{}, oldClientCookie...), upstreamServer...)
cached.IsEdns0().Option = append(cached.IsEdns0().Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString(cachedCookie),
})
qcache.Set(cacheKey("nx.cookie.test", "IN", "TXT"), cached, cacheTTL())
// New client, new client cookie: the cached NXDOMAIN must be served
// with a cookie rebuilt for this query.
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
q := newCookieQuery("nx.cookie.test", dns.TypeTXT, clientCookie)
q.Id = 777
handleQuery(w, q)
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Rcode != dns.RcodeNameError {
t.Errorf("rcode = %d, want NXDOMAIN", w.msg.Rcode)
}
if w.msg.Id != 777 {
t.Errorf("response ID = %d, want 777", w.msg.Id)
}
if len(w.msg.Ns) != 1 {
t.Errorf("authority records = %d, want 1 (SOA preserved)", len(w.msg.Ns))
}
c := responseCookie(w.msg)
if c == nil {
t.Fatal("cached NXDOMAIN response has no COOKIE option")
}
gotClient, gotServer := decodeCookie(t, c)
mustEqual(t, "cached NXDOMAIN client cookie", gotClient, clientCookie)
if bytes.Equal(gotServer, upstreamServer) {
t.Error("cached NXDOMAIN response must not relay the upstream server cookie")
}
if !validateServerCookie("192.0.2.10", clientCookie, gotServer, time.Now()) {
t.Error("cached NXDOMAIN server cookie does not validate for the current client")
}
// The cached entry itself must be untouched.
if c := responseCookie(cached); c == nil || c.Cookie != hex.EncodeToString(cachedCookie) {
t.Errorf("cached entry COOKIE mutated: %v", c)
}
}
func TestHandleQueryCookieAbsentOnCacheHit(t *testing.T) {
resetMaps()
qcache.Flush()
hostsMap["plain.test"] = "192.0.2.10"
// Prime the cache with a cookie-carrying entry.
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
cached := new(dns.Msg)
cached.SetReply(newQuery("plain.test", dns.TypeA, dns.ClassINET))
cached.Answer = []dns.RR{&dns.A{
Hdr: dns.RR_Header{Name: "plain.test.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300},
A: net.ParseIP("192.0.2.10"),
}}
cached.SetEdns0(1232, false)
cached.IsEdns0().Option = append(cached.IsEdns0().Option, &dns.EDNS0_COOKIE{
Code: dns.EDNS0COOKIE,
Cookie: hex.EncodeToString(append(append([]byte{}, clientCookie...), makeServerCookie("192.0.2.10", clientCookie, time.Now())...)),
})
qcache.Set(cacheKey("plain.test", "IN", "A"), cached, cacheTTL())
// 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 {
t.Fatal("no response written")
}
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))
}
}
func TestHandleQueryCookieBlocklistAndServfail(t *testing.T) {
resetMaps()
qcache.Flush()
blocklistMap["blocked.cookie.test"] = true
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
// Locally generated REFUSED answer.
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
handleQuery(w, newCookieQuery("blocked.cookie.test", dns.TypeA, clientCookie))
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Rcode != dns.RcodeRefused {
t.Errorf("rcode = %d, want REFUSED", w.msg.Rcode)
}
c := responseCookie(w.msg)
if c == nil {
t.Fatal("REFUSED response has no COOKIE option")
}
gotClient, gotServer := decodeCookie(t, c)
mustEqual(t, "REFUSED response client cookie", gotClient, clientCookie)
if !validateServerCookie("192.0.2.10", clientCookie, gotServer, time.Now()) {
t.Error("REFUSED response server cookie does not validate")
}
// Locally generated SERVFAIL answer (writeResponse path on error).
q := newCookieQuery("error.cookie.test", dns.TypeA, clientCookie)
r := new(dns.Msg)
r.SetRcode(q, dns.RcodeServerFailure)
applyEDNS(q, r, "192.0.2.10")
c = responseCookie(r)
if c == nil {
t.Fatal("SERVFAIL response has no COOKIE option")
}
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)
}
+1 -1
View File
@@ -6,6 +6,7 @@ require (
github.com/miekg/dns v1.1.62
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/prometheus/client_golang v1.20.5
github.com/prometheus/client_model v0.6.1
golang.org/x/sync v0.10.0
)
@@ -14,7 +15,6 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.61.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
golang.org/x/mod v0.22.0 // indirect
+153 -36
View File
@@ -26,6 +26,23 @@ import (
"golang.org/x/sync/singleflight"
)
// serverUDPSize is the UDP payload size rdns advertises to clients
// (RFC 6891) and uses as its inbound UDP buffer.
const serverUDPSize = 4096
// upstreamAdvertisedSize is the EDNS buffer size advertised to upstream
// resolvers when the client sends no EDNS: large enough for typical
// answers, small enough to avoid IP fragmentation.
const upstreamAdvertisedSize = 1232
// Upstream ports, overridable by tests to point at a mock nameserver.
var (
upstreamDNSPort = "53"
upstreamDoTPort = "853"
errQuestionMismatch = errors.New("response question section does not match the query")
)
var (
addr = flag.String("a", "0.0.0.0", "address to use")
port = flag.String("p", "53", "port to run on")
@@ -141,10 +158,65 @@ func cacheKey(qname, qclass, qtype string) string {
return qname + "." + qclass + "." + qtype
}
// cacheTTL is how long responses are kept in the cache. The -t flag is the
// source of truth for cache lifetime; TTLs of cached responses are
// decremented by the time spent in the cache when served.
func cacheTTL() time.Duration {
return time.Duration(*ttl) * time.Minute
}
// decrementTTLs reduces the TTL of every record in msg by age, so that
// responses served from cache reflect the time already spent there. The
// OPT pseudo-record is skipped: its TTL field carries the extended rcode
// and flags, not a TTL.
func decrementTTLs(msg *dns.Msg, age time.Duration) {
dec := uint32(age.Seconds())
if dec == 0 {
return
}
for _, section := range [][]dns.RR{msg.Answer, msg.Ns, msg.Extra} {
for _, rr := range section {
if rr == nil || rr.Header().Rrtype == dns.TypeOPT {
continue
}
h := rr.Header()
if h.Ttl > dec {
h.Ttl -= dec
} else {
h.Ttl = 0
}
}
}
}
// questionMatches reports whether the question section of an upstream
// response matches the query that was sent, guarding against spoofed or
// mismatched replies (name comparison is case-insensitive, RFC 1035
// section 2.3.3).
func questionMatches(q, r *dns.Msg) bool {
if len(q.Question) == 0 || len(r.Question) != len(q.Question) {
return false
}
for i := range q.Question {
if !strings.EqualFold(q.Question[i].Name, r.Question[i].Name) ||
q.Question[i].Qtype != r.Question[i].Qtype ||
q.Question[i].Qclass != r.Question[i].Qclass {
return false
}
}
return true
}
func handleCache(q *dns.Msg, key string) (*dns.Msg, int, bool) {
if cached, found := qcache.Get(key); found {
if cached, expiration, found := qcache.GetWithExpiration(key); found {
msg := cached.(*dns.Msg).Copy()
msg.Id = q.Id
msg.Question = q.Question
if !expiration.IsZero() {
if age := cacheTTL() - time.Until(expiration); age > 0 {
decrementTTLs(msg, age)
}
}
return msg, msg.Rcode, true
}
return nil, 0, false
@@ -178,9 +250,13 @@ func lookup(q *dns.Msg, qname string) (*dns.Msg, string, error) {
}
}
// Advertise an EDNS0 buffer to avoid truncated UDP responses
// Advertise an EDNS0 buffer to upstream to avoid truncated UDP
// responses. Exchange a copy when adding EDNS, so the client's
// original message keeps the payload size it advertised.
uq := q
if q.IsEdns0() == nil {
q.SetEdns0(dns.DefaultMsgSize, false)
uq = q.Copy()
uq.SetEdns0(upstreamAdvertisedSize, false)
}
c := &dns.Client{UDPSize: dns.MaxMsgSize}
@@ -191,14 +267,14 @@ func lookup(q *dns.Msg, qname string) (*dns.Msg, string, error) {
ServerName: n[i],
}
proto = "tcp-tls"
r, rtt, err = c.Exchange(q, net.JoinHostPort(n[i], "853"))
r, rtt, err = c.Exchange(uq, net.JoinHostPort(n[i], upstreamDoTPort))
if err != nil {
fmt.Fprintf(os.Stderr, "TLS connection failed to %s: %v\n", n[i], err)
log.Println("WARN: TLS connection failed to", n[i], err)
}
} else {
c.Net = "udp"
proto = "udp"
r, rtt, err = c.Exchange(q, net.JoinHostPort(n[i], "53"))
r, rtt, err = c.Exchange(uq, net.JoinHostPort(n[i], upstreamDNSPort))
if err != nil && *logs {
log.Println("WARN:", err)
}
@@ -206,9 +282,17 @@ func lookup(q *dns.Msg, qname string) (*dns.Msg, string, error) {
// Response was truncated: retry over TCP to get the full answer
tc := &dns.Client{Net: "tcp"}
proto = "tcp"
r, rtt, err = tc.Exchange(q, net.JoinHostPort(n[i], "53"))
r, rtt, err = tc.Exchange(uq, net.JoinHostPort(n[i], upstreamDNSPort))
}
}
if err == nil && !questionMatches(q, r) {
// Reject responses whose question section does not match the
// query, then try the next nameserver.
if *logs {
log.Println("WARN: question mismatch in response from", n[i])
}
err = errQuestionMismatch
}
if err == nil {
nameservers.WithLabelValues(n[i]).Inc()
break
@@ -236,18 +320,42 @@ func resolve(q *dns.Msg, qname, key string) (*dns.Msg, string, error) {
res := v.(*lookupResult)
msg := res.msg.Copy()
msg.Id = q.Id
msg.Question = q.Question
return msg, res.proto, nil
}
func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
queries.Inc()
client := clientIP(w)
// 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)
r.SetRcode(q, dns.RcodeFormatError)
if err := w.WriteMsg(r); err != nil && *logs {
log.Println("ERROR: Failed to write response:", err)
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
}
@@ -260,7 +368,6 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
qclass = dns.Class(q.Question[0].Qclass).String()
qtype = dns.Type(q.Question[0].Qtype).String()
key = cacheKey(qname, qclass, qtype)
client = clientIP(w)
)
qtypes.WithLabelValues(qtype).Inc()
@@ -274,13 +381,11 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
Hdr: dns.RR_Header{Name: "version.bind.", Rrtype: dns.TypeTXT, Class: dns.ClassCHAOS, Ttl: 86400},
Txt: []string{"rdns"},
})
qcache.SetDefault(key, r)
qcache.Set(key, r.Copy(), cacheTTL())
if *logs {
log.Println(client, qname, qclass, qtype, getRcode(rcode))
}
if err := w.WriteMsg(r); err != nil && *logs {
log.Println("ERROR: Failed to write response:", err)
}
writeResponse(w, q, r, client)
responses.WithLabelValues(qtype, getRcode(rcode)).Inc()
return
}
@@ -291,9 +396,7 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
}
responses.WithLabelValues(qtype, getRcode(rcode)).Inc()
cacheHits.Inc()
if err := w.WriteMsg(r); err != nil && *logs {
log.Println("ERROR: Failed to write response:", err)
}
writeResponse(w, q, r, client)
return
}
@@ -315,13 +418,11 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
AAAA: ip,
})
}
qcache.SetDefault(key, r)
qcache.Set(key, r.Copy(), cacheTTL())
if *logs {
log.Println(client, qname, qclass, qtype, getRcode(rcode))
}
if err := w.WriteMsg(r); err != nil && *logs {
log.Println("ERROR: Failed to write response:", err)
}
writeResponse(w, q, r, client)
responses.WithLabelValues(qtype, getRcode(rcode)).Inc()
return
}
@@ -332,13 +433,11 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
rcode = dns.RcodeRefused
r.SetRcode(q, rcode)
r.MsgHdr.RecursionAvailable = true
qcache.SetDefault(key, r)
qcache.Set(key, r.Copy(), cacheTTL())
if *logs {
log.Println(client, qname, qclass, qtype, getRcode(rcode))
}
if err := w.WriteMsg(r); err != nil && *logs {
log.Println("ERROR: Failed to write response:", err)
}
writeResponse(w, q, r, client)
responses.WithLabelValues(qtype, getRcode(rcode)).Inc()
return
}
@@ -357,24 +456,43 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
} else {
rcode = r.Rcode
r.MsgHdr.RecursionAvailable = true
qcache.SetDefault(key, 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)
}
}
if err := w.WriteMsg(r); err != nil && *logs {
log.Println("ERROR: Failed to write response:", err)
}
writeResponse(w, q, r, client)
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: dns.DefaultMsgSize,
UDPSize: serverUDPSize,
NotifyStartedFunc: started,
MsgAcceptFunc: msgAcceptFunc,
}
go func() {
if err := server.ListenAndServe(); err != nil {
@@ -473,8 +591,9 @@ func cacheEviction(key string, value any) {
func main() {
flag.Parse()
qcache = cache.New(time.Duration(*ttl)*time.Minute, 5*time.Minute)
qcache = cache.New(cacheTTL(), 5*time.Minute)
qcache.OnEvicted(cacheEviction)
startCookieSecretRotation()
fmt.Println("Starting Proxy Resolver:", net.JoinHostPort(*addr, *port), "->", *ns, "[UDP/TCP]")
fmt.Println("Cache TTL:", *ttl, "minutes\nTLS enabled:", *dot)
@@ -531,8 +650,6 @@ func main() {
}()
}
dns.HandleFunc(".", handleQuery)
var readyOnce sync.Once
ready := func() { readyOnce.Do(func() { up.Set(1) }) }
servers := []*dns.Server{
+479
View File
@@ -0,0 +1,479 @@
package main
import (
"bytes"
"encoding/hex"
"fmt"
"net"
"strconv"
"testing"
"time"
"github.com/miekg/dns"
)
// startMockUpstream runs a mock nameserver on 127.0.0.1 with a shared
// UDP/TCP port, returning its address.
func startMockUpstream(t *testing.T, udpHandler, tcpHandler dns.HandlerFunc) string {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := ln.Addr().(*net.TCPAddr).Port
pc, err := net.ListenPacket("udp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
if err != nil {
t.Fatal(err)
}
udpSrv := &dns.Server{PacketConn: pc, Handler: udpHandler}
tcpSrv := &dns.Server{Listener: ln, Handler: tcpHandler}
go func() { _ = udpSrv.ActivateAndServe() }()
go func() { _ = tcpSrv.ActivateAndServe() }()
t.Cleanup(func() {
_ = udpSrv.Shutdown()
_ = tcpSrv.Shutdown()
})
return net.JoinHostPort("127.0.0.1", strconv.Itoa(port))
}
// useUpstream points the resolver at a mock nameserver address and
// restores the configuration afterwards.
func useUpstream(t *testing.T, addr string) {
t.Helper()
oldNS, oldPort := *ns, upstreamDNSPort
host, port, err := net.SplitHostPort(addr)
if err != nil {
t.Fatal(err)
}
*ns = host
upstreamDNSPort = port
t.Cleanup(func() { *ns, upstreamDNSPort = oldNS, oldPort })
}
func mockUDPWriter(t *testing.T) *mockWriter {
return &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
}
// 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 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()
upstreamServerCookie := []byte{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}
handler := func(w dns.ResponseWriter, q *dns.Msg) {
r := new(dns.Msg)
r.SetReply(q)
r.MsgHdr.AuthenticatedData = true // upstream claims validation
r.Answer = append(r.Answer, &dns.A{
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(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,
Cookie: hex.EncodeToString(cookie),
})
}
if err := w.WriteMsg(r); err != nil {
t.Error(err)
}
}
useUpstream(t, startMockUpstream(t, handler, handler))
clientCookie1 := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
clientCookie2 := []byte{0xde, 0xad, 0xbe, 0xef, 0x00, 0x11, 0x22, 0x33}
// First query: forwarded upstream.
w1 := mockUDPWriter(t)
q1 := newCookieQuery("upstream.test", dns.TypeA, clientCookie1)
handleQuery(w1, q1)
if w1.msg == nil {
t.Fatal("no response written")
}
if len(w1.msg.Answer) != 1 {
t.Fatalf("answers = %d, want 1", len(w1.msg.Answer))
}
if !w1.msg.RecursionAvailable {
t.Error("RecursionAvailable not set")
}
if w1.msg.AuthenticatedData {
t.Error("AD bit must be cleared: rdns does not validate DNSSEC (RFC 6840 section 5.8)")
}
if w1.msg.Answer[0].Header().Ttl != 300 {
t.Errorf("fresh response TTL = %d, want 300", w1.msg.Answer[0].Header().Ttl)
}
c1 := responseCookie(w1.msg)
if c1 == nil {
t.Fatal("response has no COOKIE option")
}
gotClient, gotServer := decodeCookie(t, c1)
mustEqual(t, "upstream response client cookie", gotClient, clientCookie1)
if bytes.Equal(gotServer, upstreamServerCookie) {
t.Error("upstream server cookie must not be relayed to the client")
}
if !validateServerCookie("192.0.2.10", clientCookie1, gotServer, time.Now()) {
t.Error("response server cookie does not validate for the querying client")
}
// 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 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
// question case): cache hit with a rebuilt cookie.
w2 := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.99"), Port: 5300}}
q2 := newCookieQuery("UPSTREAM.test", dns.TypeA, clientCookie2)
q2.Id = 999
handleQuery(w2, q2)
if w2.msg == nil {
t.Fatal("no response written")
}
if w2.msg.Id != 999 {
t.Errorf("cached response ID = %d, want 999", w2.msg.Id)
}
if w2.msg.Question[0].Name != "UPSTREAM.test." {
t.Errorf("cached response question = %q, want the current query's question", w2.msg.Question[0].Name)
}
if w2.msg.AuthenticatedData {
t.Error("AD bit must be cleared on cache hits too")
}
c2 := responseCookie(w2.msg)
if c2 == nil {
t.Fatal("cached response has no COOKIE option")
}
gotClient2, gotServer2 := decodeCookie(t, c2)
mustEqual(t, "cached response client cookie", gotClient2, clientCookie2)
if bytes.Equal(gotServer2, gotServer) {
t.Error("cached response must carry a fresh server cookie for the new client")
}
if !validateServerCookie("192.0.2.99", clientCookie2, gotServer2, time.Now()) {
t.Error("cached response server cookie does not validate for the new client")
}
if len(w2.msg.Answer) != 1 {
t.Errorf("cached response answers = %d, want 1", len(w2.msg.Answer))
}
}
// TestHandleQueryUpstreamQuestionMismatch verifies that an upstream
// response whose question section does not match the query is rejected.
func TestHandleQueryUpstreamQuestionMismatch(t *testing.T) {
resetMaps()
qcache.Flush()
handler := func(w dns.ResponseWriter, q *dns.Msg) {
r := new(dns.Msg)
r.SetReply(q)
r.Question[0].Name = "evil.example."
r.Answer = append(r.Answer, &dns.A{
Hdr: dns.RR_Header{Name: "evil.example.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300},
A: net.ParseIP("192.0.2.1"),
})
if err := w.WriteMsg(r); err != nil {
t.Error(err)
}
}
useUpstream(t, startMockUpstream(t, handler, handler))
w := mockUDPWriter(t)
handleQuery(w, newQuery("mismatch.test", dns.TypeA, dns.ClassINET))
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Rcode != dns.RcodeServerFailure {
t.Errorf("rcode = %d, want SERVFAIL for question-mismatched upstream response", w.msg.Rcode)
}
}
// TestHandleQueryTruncatedRetryTCP verifies that a truncated UDP response
// from upstream is retried over TCP to get the full answer.
func TestHandleQueryTruncatedRetryTCP(t *testing.T) {
resetMaps()
qcache.Flush()
fullAnswer := func(q *dns.Msg) *dns.Msg {
r := new(dns.Msg)
r.SetReply(q)
r.Answer = append(r.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300},
A: net.ParseIP("192.0.2.1"),
})
return r
}
udpHandler := func(w dns.ResponseWriter, q *dns.Msg) {
r := fullAnswer(q)
r.Truncated = true
if err := w.WriteMsg(r); err != nil {
t.Error(err)
}
}
tcpHandler := func(w dns.ResponseWriter, q *dns.Msg) {
if err := w.WriteMsg(fullAnswer(q)); err != nil {
t.Error(err)
}
}
useUpstream(t, startMockUpstream(t, udpHandler, tcpHandler))
w := mockUDPWriter(t)
handleQuery(w, newQuery("truncated.test", dns.TypeA, dns.ClassINET))
if w.msg == nil {
t.Fatal("no response written")
}
if w.msg.Truncated {
t.Error("response must not be truncated after the TCP retry")
}
if len(w.msg.Answer) != 1 {
t.Fatalf("answers = %d, want 1 (full answer over TCP)", len(w.msg.Answer))
}
}
// TestHandleQueryUDPTruncation verifies that UDP responses exceeding the
// client's advertised payload size are truncated with the TC bit set, and
// that a client with a larger buffer gets the full cached answer.
func TestHandleQueryUDPTruncation(t *testing.T) {
resetMaps()
qcache.Flush()
handler := func(w dns.ResponseWriter, q *dns.Msg) {
r := new(dns.Msg)
r.SetReply(q)
for i := 0; i < 40; i++ {
r.Answer = append(r.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300},
A: net.ParseIP(fmt.Sprintf("192.0.2.%d", i+1)),
})
}
if err := w.WriteMsg(r); err != nil {
t.Error(err)
}
}
useUpstream(t, startMockUpstream(t, handler, handler))
// Client without EDNS: responses are limited to 512 bytes.
w1 := mockUDPWriter(t)
handleQuery(w1, newQuery("big.test", dns.TypeA, dns.ClassINET))
if w1.msg == nil {
t.Fatal("no response written")
}
if !w1.msg.Truncated {
t.Error("oversized UDP response must be truncated (TC bit set) for a non-EDNS client")
}
if len(w1.msg.Answer) == 0 || len(w1.msg.Answer) == 40 {
t.Errorf("answers = %d, want a partial answer", len(w1.msg.Answer))
}
// Client with a large EDNS buffer: full answer from the cache.
w2 := mockUDPWriter(t)
q2 := newQuery("big.test", dns.TypeA, dns.ClassINET)
q2.SetEdns0(4096, false)
handleQuery(w2, q2)
if w2.msg == nil {
t.Fatal("no response written")
}
if w2.msg.Truncated {
t.Error("response within the client's buffer must not be truncated")
}
if len(w2.msg.Answer) != 40 {
t.Errorf("answers = %d, want 40 (full cached answer)", len(w2.msg.Answer))
}
}
// TestHandleCacheDecrementsTTL verifies that TTLs of cached responses are
// decremented by the time the entry spent in the cache, for both positive
// and negative answers, and that the OPT pseudo-record is left untouched.
func TestHandleCacheDecrementsTTL(t *testing.T) {
qcache.Flush()
cached := new(dns.Msg)
cached.SetReply(newQuery("ttl.test", dns.TypeA, dns.ClassINET))
cached.Answer = []dns.RR{&dns.A{
Hdr: dns.RR_Header{Name: "ttl.test.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300},
A: net.ParseIP("192.0.2.1"),
}}
cached.Ns = []dns.RR{&dns.SOA{
Hdr: dns.RR_Header{Name: "ttl.test.", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 120},
Ns: "ns.ttl.test.",
Mbox: "hostmaster.ttl.test.",
Serial: 1,
Refresh: 3600,
Retry: 600,
Expire: 86400,
Minttl: 60,
}}
cached.SetEdns0(4096, false)
cached.IsEdns0().Hdr.Ttl = 0x00008000 // DO bit: must survive untouched
key := cacheKey("ttl.test", "IN", "A")
// Store the entry as if it had been cached 30 seconds ago.
qcache.Set(key, cached, cacheTTL()-30*time.Second)
req := newQuery("TTL.test", dns.TypeA, dns.ClassINET)
req.Id = 4242
msg, rcode, ok := handleCache(req, key)
if !ok {
t.Fatal("expected cache hit")
}
if rcode != dns.RcodeSuccess {
t.Errorf("rcode = %d, want NOERROR", rcode)
}
if msg.Id != 4242 {
t.Errorf("response ID = %d, want 4242", msg.Id)
}
if msg.Question[0].Name != "TTL.test." {
t.Errorf("question = %q, want the current query's question", msg.Question[0].Name)
}
if ttl := msg.Answer[0].Header().Ttl; ttl != 270 {
t.Errorf("answer TTL = %d, want 270 (300 decremented by 30s)", ttl)
}
if ttl := msg.Ns[0].Header().Ttl; ttl != 90 {
t.Errorf("authority TTL = %d, want 90 (120 decremented by 30s)", ttl)
}
if msg.IsEdns0().Hdr.Ttl != 0x00008000 {
t.Errorf("OPT TTL/flags = %#x, want 0x8000 (untouched)", msg.IsEdns0().Hdr.Ttl)
}
// The cached entry itself must not be mutated.
if ttl := cached.Answer[0].Header().Ttl; ttl != 300 {
t.Errorf("cached entry answer TTL = %d, want 300 (unmutated)", ttl)
}
// A negative (NXDOMAIN) entry is decremented too.
nxKey := cacheKey("nx.ttl.test", "IN", "A")
nx := new(dns.Msg)
nx.SetReply(newQuery("nx.ttl.test", dns.TypeA, dns.ClassINET))
nx.Rcode = dns.RcodeNameError
nx.Ns = []dns.RR{&dns.SOA{
Hdr: dns.RR_Header{Name: "ttl.test.", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 120},
Ns: "ns.ttl.test.",
Mbox: "hostmaster.ttl.test.",
Serial: 1,
Refresh: 3600,
Retry: 600,
Expire: 86400,
Minttl: 60,
}}
qcache.Set(nxKey, nx, cacheTTL()-30*time.Second)
nxMsg, nxRcode, ok := handleCache(newQuery("nx.ttl.test", dns.TypeA, dns.ClassINET), nxKey)
if !ok {
t.Fatal("expected cache hit for NXDOMAIN entry")
}
if nxRcode != dns.RcodeNameError {
t.Errorf("rcode = %d, want NXDOMAIN", nxRcode)
}
if ttl := nxMsg.Ns[0].Header().Ttl; ttl != 90 {
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")
}
}