harden response handling and packaging; make cookies fully RFC 9018-compliant
test / test (pull_request) Successful in 35s
test / test (pull_request) Successful in 35s
Response handling: - Clear the DNSSEC AD bit in all responses (RFC 6840 section 5.8): rdns forwards but does not validate, so it must not relay the upstream AD bit - Truncate UDP responses exceeding the client's advertised payload size (RFC 6891 section 6.2.5): set TC and let clients retry over TCP; the COOKIE option survives truncation. Server UDP buffer raised to 4096 - Decrement TTLs of cached responses by the time spent in the cache (positive and negative answers); -t remains the cache lifetime source of truth. OPT pseudo-records are left untouched - Reject upstream responses whose question section does not match the query, then try the next nameserver (anti-spoofing) - Echo the current query's question section on cache hits and forwarded responses (0x20 case), and stop mutating the client's message when adding EDNS for the upstream exchange - Advertise 1232 bytes to upstream when the client sends no EDNS, and gate DoT connection error logging behind -l Cookies: - Make server cookies fully RFC 9018-compliant, pinned against the RFC Appendix A test vectors: version 1, second-granularity timestamps, little-endian hash sub-field, RFC 1982 serial-number skew checks, reserved sub-field hashed as received on validation - Strip COOKIE options before caching instead of on every cache hit - Count server cookies presented by clients in the rdns_cookie_checks_total metric (valid/invalid/absent), wiring validateServerCookie into the serving path - Response OPT advertises the responder's payload size (RFC 6891) Packaging and CI: - package.yml: fix the deb Description/Homepage copy-paste errors, install the binary to /usr/local/bin (matching the systemd unit), register /etc/rdns conffiles, ship the systemd unit and the logrotate/rsyslog configs, add Installed-Size - New test.yml workflow running go vet and go test -race on pull requests; image/release pushes stay tied to main/tags - Stop tracking the generated conf/blocklist.txt (gitignore it, generate with utils/blocklist_update) - README: fix the project description, document cookie handling, the AD-bit and truncation behavior, TTL decrementing, and utils/ Tests: - Mock-upstream integration tests: end-to-end cookie rewrite and AD clearing, question-mismatch rejection, TCP retry on truncation, TC truncation per client buffer, TTL decrement on cache serve, question case echo, cache entry stored without COOKIE - Unit tests: all 64 SipHash-2-4 reference vectors, RFC 9018 Appendix A cookie vectors, cookie validation metric Upstream ports are overridable (upstreamDNSPort/upstreamDoTPort) so tests can point the resolver at a mock nameserver.
This commit is contained in:
10 files changed
+834
-775317
No files matched your search
@@ -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: |
|
||||
|
||||
@@ -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 ./...
|
||||
@@ -1,2 +1,4 @@
|
||||
/rdns.log
|
||||
/rdns
|
||||
# Generated by utils/blocklist_update, not stored in git
|
||||
/conf/blocklist.txt
|
||||
@@ -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 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
|
||||
- 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)
|
||||
|
||||
## 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
File diff suppressed because it is too large.
Load diff
@@ -12,28 +12,36 @@ import (
|
||||
"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
|
||||
// server cookie bound to the client address and the current time.
|
||||
// Responses served from cache (including negative ones) get their
|
||||
// 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 = 0
|
||||
clientCookieLen = 8
|
||||
serverCookieLen = 16 // 128-bit server cookie (RFC 9018 section 4.3)
|
||||
timestampUnitSecs = 60 // server cookie timestamp granularity: minutes
|
||||
cookieVersion = 1 // RFC 9018 section 4.1
|
||||
clientCookieLen = 8
|
||||
serverCookieLen = 16 // 128-bit server cookie (RFC 9018 section 4)
|
||||
|
||||
secretRotateEvery = time.Hour
|
||||
// RFC 9018 section 4.3: a server cookie timestamp up to one hour in
|
||||
// the past must be accepted; allow a few minutes of future skew.
|
||||
// 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
|
||||
)
|
||||
@@ -76,8 +84,8 @@ func startCookieSecretRotation() {
|
||||
}()
|
||||
}
|
||||
|
||||
// siphash24 is SipHash-2-4 with a 128-bit key, as required by RFC 9018
|
||||
// section 4.3 for the server cookie hash.
|
||||
// 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])
|
||||
@@ -140,12 +148,15 @@ func clientIPBytes(ip string) []byte {
|
||||
return []byte(ip)
|
||||
}
|
||||
|
||||
// cookieHashInput builds the RFC 9018 section 4.3 hash input:
|
||||
// cookieHashInput builds the RFC 9018 section 4.4 SipHash-2-4 input:
|
||||
// Client Cookie || Version || Reserved || Timestamp || Client IP.
|
||||
func cookieHashInput(clientCookie []byte, timestamp uint32, clientIP string) []byte {
|
||||
// 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, cookieVersion, 0, 0, 0)
|
||||
in = append(in, version, reserved[0], reserved[1], reserved[2])
|
||||
var ts [4]byte
|
||||
binary.BigEndian.PutUint32(ts[:], timestamp)
|
||||
in = append(in, ts[:]...)
|
||||
@@ -153,29 +164,35 @@ func cookieHashInput(clientCookie []byte, timestamp uint32, clientIP string) []b
|
||||
return in
|
||||
}
|
||||
|
||||
// makeServerCookie computes an RFC 9018-style 128-bit server cookie:
|
||||
// version (8 bits) || reserved (24 bits) || timestamp (32 bits, minutes
|
||||
// since 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.
|
||||
// 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() / timestampUnitSecs)
|
||||
h := siphash24(secret[:], cookieHashInput(clientCookie, timestamp, clientIP))
|
||||
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)
|
||||
binary.BigEndian.PutUint64(cookie[8:16], h)
|
||||
// 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 against the current and
|
||||
// previous server secrets, honouring the RFC 9018 timestamp skew policy.
|
||||
// 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
|
||||
}
|
||||
@@ -183,20 +200,25 @@ func validateServerCookie(clientIP string, clientCookie, serverCookie []byte, no
|
||||
return false
|
||||
}
|
||||
timestamp := binary.BigEndian.Uint32(serverCookie[4:8])
|
||||
cookieTime := time.Unix(int64(timestamp)*timestampUnitSecs, 0)
|
||||
if cookieTime.Before(now.Add(-cookieMaxPastSkew)) || cookieTime.After(now.Add(cookieMaxFutureSkew)) {
|
||||
// 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, timestamp, clientIP)
|
||||
in := cookieHashInput(clientCookie, serverCookie[0], reserved, timestamp, clientIP)
|
||||
for _, secret := range secrets {
|
||||
h := siphash24(secret[:], in)
|
||||
var want [8]byte
|
||||
binary.BigEndian.PutUint64(want[:], h)
|
||||
binary.LittleEndian.PutUint64(want[:], h)
|
||||
if subtle.ConstantTimeCompare(want[:], serverCookie[8:16]) == 1 {
|
||||
return true
|
||||
}
|
||||
@@ -204,23 +226,23 @@ func validateServerCookie(clientIP string, clientCookie, serverCookie []byte, no
|
||||
return false
|
||||
}
|
||||
|
||||
// getClientCookie extracts the 8-byte client cookie from the COOKIE
|
||||
// option of a query, if present and well-formed.
|
||||
func getClientCookie(q *dns.Msg) ([]byte, bool) {
|
||||
// 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) {
|
||||
opt := q.IsEdns0()
|
||||
if opt == nil {
|
||||
return nil, false
|
||||
return nil, nil, false
|
||||
}
|
||||
for _, o := range opt.Option {
|
||||
if c, ok := o.(*dns.EDNS0_COOKIE); ok {
|
||||
if c, isCookie := o.(*dns.EDNS0_COOKIE); isCookie {
|
||||
raw, err := hex.DecodeString(c.Cookie)
|
||||
if err != nil || len(raw) < clientCookieLen {
|
||||
return nil, false
|
||||
return nil, nil, false
|
||||
}
|
||||
return raw[:clientCookieLen], true
|
||||
return raw[:clientCookieLen], raw[clientCookieLen:], true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// stripCookies removes any COOKIE option from a response, e.g. one
|
||||
@@ -232,7 +254,7 @@ func stripCookies(r *dns.Msg) {
|
||||
}
|
||||
kept := opt.Option[:0]
|
||||
for _, o := range opt.Option {
|
||||
if _, ok := o.(*dns.EDNS0_COOKIE); !ok {
|
||||
if _, isCookie := o.(*dns.EDNS0_COOKIE); !isCookie {
|
||||
kept = append(kept, o)
|
||||
}
|
||||
}
|
||||
@@ -243,22 +265,30 @@ func stripCookies(r *dns.Msg) {
|
||||
// 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.
|
||||
// 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) {
|
||||
stripCookies(r)
|
||||
clientCookie, ok := getClientCookie(q)
|
||||
clientCookie, serverCookie, ok := getQueryCookie(q)
|
||||
if !ok {
|
||||
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()
|
||||
}
|
||||
opt := r.IsEdns0()
|
||||
if opt == nil {
|
||||
size := uint16(dns.DefaultMsgSize)
|
||||
if qo := q.IsEdns0(); qo != nil && qo.UDPSize() > 0 {
|
||||
size = qo.UDPSize()
|
||||
}
|
||||
r.SetEdns0(size, false)
|
||||
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())...)
|
||||
@@ -268,10 +298,23 @@ func applyCookie(q, r *dns.Msg, clientIP string) {
|
||||
})
|
||||
}
|
||||
|
||||
// writeResponse applies per-client COOKIE handling to r and writes it to
|
||||
// the client.
|
||||
// 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).
|
||||
func writeResponse(w dns.ResponseWriter, q, r *dns.Msg, clientIP string) {
|
||||
applyCookie(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)
|
||||
}
|
||||
|
||||
+189
-7
@@ -9,6 +9,8 @@ import (
|
||||
"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 {
|
||||
@@ -73,6 +75,54 @@ var siphashRefVectors = [][]byte{
|
||||
{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) {
|
||||
@@ -103,8 +153,11 @@ func TestMakeServerCookie(t *testing.T) {
|
||||
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()/timestampUnitSecs) {
|
||||
t.Errorf("server cookie timestamp = %d, want %d", ts, now.Unix()/timestampUnitSecs)
|
||||
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.
|
||||
@@ -139,6 +192,9 @@ func TestValidateServerCookie(t *testing.T) {
|
||||
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))
|
||||
@@ -149,11 +205,15 @@ func TestValidateServerCookie(t *testing.T) {
|
||||
if validateServerCookie("192.0.2.10", clientCookie, tooOld, now) {
|
||||
t.Error("server cookie 2 hours old must not validate")
|
||||
}
|
||||
// Small future skew is tolerated.
|
||||
// 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.
|
||||
@@ -168,6 +228,81 @@ func TestValidateServerCookie(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 TestApplyCookieEchoesClientCookie(t *testing.T) {
|
||||
clientCookie := []byte{0x6d, 0x36, 0x72, 0xdf, 0xf3, 0xc4, 0x63, 0x75}
|
||||
q := newCookieQuery("example.test", dns.TypeA, clientCookie)
|
||||
@@ -189,8 +324,8 @@ func TestApplyCookieEchoesClientCookie(t *testing.T) {
|
||||
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() != 1232 {
|
||||
t.Errorf("response OPT UDP size = %d, want 1232 (from query)", r.IsEdns0().UDPSize())
|
||||
if r.IsEdns0().UDPSize() != serverUDPSize {
|
||||
t.Errorf("response OPT UDP size = %d, want %d (responder's payload size)", r.IsEdns0().UDPSize(), serverUDPSize)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,6 +397,53 @@ func TestApplyCookieNoCookieInQuery(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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 TestApplyCookieCountsServerCookieValidation(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)
|
||||
applyCookie(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)
|
||||
applyCookie(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)
|
||||
applyCookie(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()
|
||||
@@ -355,7 +537,7 @@ func TestHandleQueryCookieCacheHitNXDOMAIN(t *testing.T) {
|
||||
Code: dns.EDNS0COOKIE,
|
||||
Cookie: hex.EncodeToString(cachedCookie),
|
||||
})
|
||||
qcache.SetDefault(cacheKey("nx.cookie.test", "IN", "TXT"), cached)
|
||||
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.
|
||||
@@ -414,7 +596,7 @@ func TestHandleQueryCookieAbsentOnCacheHit(t *testing.T) {
|
||||
Code: dns.EDNS0COOKIE,
|
||||
Cookie: hex.EncodeToString(append(append([]byte{}, clientCookie...), makeServerCookie("192.0.2.10", clientCookie, time.Now())...)),
|
||||
})
|
||||
qcache.SetDefault(cacheKey("plain.test", "IN", "A"), cached)
|
||||
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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,6 +320,7 @@ 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
|
||||
}
|
||||
|
||||
@@ -272,7 +357,7 @@ 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.Copy())
|
||||
qcache.Set(key, r.Copy(), cacheTTL())
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode))
|
||||
}
|
||||
@@ -309,7 +394,7 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
|
||||
AAAA: ip,
|
||||
})
|
||||
}
|
||||
qcache.SetDefault(key, r.Copy())
|
||||
qcache.Set(key, r.Copy(), cacheTTL())
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode))
|
||||
}
|
||||
@@ -324,7 +409,7 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
|
||||
rcode = dns.RcodeRefused
|
||||
r.SetRcode(q, rcode)
|
||||
r.MsgHdr.RecursionAvailable = true
|
||||
qcache.SetDefault(key, r.Copy())
|
||||
qcache.Set(key, r.Copy(), cacheTTL())
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode))
|
||||
}
|
||||
@@ -347,7 +432,10 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
|
||||
} else {
|
||||
rcode = r.Rcode
|
||||
r.MsgHdr.RecursionAvailable = true
|
||||
qcache.SetDefault(key, r.Copy())
|
||||
// Never cache upstream COOKIE options: they are stripped here and
|
||||
// rebuilt per client when the entry is served.
|
||||
stripCookies(r)
|
||||
qcache.Set(key, r.Copy(), cacheTTL())
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode), proto)
|
||||
}
|
||||
@@ -361,7 +449,7 @@ func serve(addr string, port string, network string, started func()) *dns.Server
|
||||
Addr: net.JoinHostPort(addr, port),
|
||||
Net: network,
|
||||
ReusePort: true,
|
||||
UDPSize: dns.DefaultMsgSize,
|
||||
UDPSize: serverUDPSize,
|
||||
NotifyStartedFunc: started,
|
||||
}
|
||||
go func() {
|
||||
@@ -461,7 +549,7 @@ 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()
|
||||
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
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 a
|
||||
// COOKIE option, and cache hits rebuild 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(4096, false)
|
||||
if clientCookie, _, ok := getQueryCookie(q); ok {
|
||||
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 COOKIE option.
|
||||
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)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user