fix cache races, cross-class cache poisoning, TCP retry on truncation, blocklist_update separators; add singleflight, graceful shutdown, hardening and tests
This commit is contained in:
7 files changed
+521
-117
No files matched your search
+2
-2
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.26 AS build
|
||||
FROM golang:1.27 AS build
|
||||
|
||||
WORKDIR /
|
||||
|
||||
@@ -8,7 +8,7 @@ COPY go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY *.go ./
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o rdns .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o rdns .
|
||||
|
||||
FROM alpine:latest
|
||||
|
||||
|
||||
@@ -35,14 +35,17 @@ This command will start the rdns-go container in the background.
|
||||
|
||||
The rdns-go project can be configured using the following command arguments:
|
||||
|
||||
- `-b` (default: /etc/rdns/blocklist.txt): The path to the blocklist file. This file contains a list of domain names to block.
|
||||
- `-z` (default: /etc/rdns/rdns.zones): The path to the zones file. This file contains custom zone information.
|
||||
- `-h` (default: /etc/rdns/hosts): The path to the hosts file. This file contains custom hosts and can be used as a network wide /etc/hosts file.
|
||||
- `-n` (default: 9.9.9.9:1.1.1.1): The nameservers to use for DNS resolution.
|
||||
- `-t` (default: 60): The time-to-live value for cached queries (in minutes).
|
||||
- `-s` (default: true): Whether to use TLS to contact the resolver.
|
||||
- `-l` (default: false): Whether to enable query logging.
|
||||
- `-m` (default: false): Whether to enable Prometheus metrics.
|
||||
- `-a` (default: `0.0.0.0`): The address to listen on.
|
||||
- `-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.
|
||||
- `-h` (default: none): The path to the hosts file. This file contains custom hosts and can be used as a network wide /etc/hosts file.
|
||||
- `-n` (default: `9.9.9.9`): The nameservers to use for DNS resolution, separated by `:` or `,`.
|
||||
- `-c` (default: all CPUs): The number of CPUs to use.
|
||||
- `-t` (default: `10`): The cache TTL for queries, in minutes.
|
||||
- `-s` (default: `false`): Whether to use TLS (DoT, port 853) to contact the resolver.
|
||||
- `-l` (default: `false`): Whether to enable query logging.
|
||||
- `-m` (default: `false`): Whether to enable Prometheus metrics on port 9153.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
module rdns
|
||||
|
||||
go 1.26.0
|
||||
go 1.27.0
|
||||
|
||||
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
|
||||
golang.org/x/sync v0.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -18,7 +19,6 @@ require (
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
golang.org/x/mod v0.22.0 // indirect
|
||||
golang.org/x/net v0.32.0 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/tools v0.28.0 // indirect
|
||||
google.golang.org/protobuf v1.36.0 // indirect
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -21,23 +23,24 @@ import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
var (
|
||||
addr = flag.String("a", "0.0.0.0", "address to use")
|
||||
port = flag.String("p", "53", "port to run on")
|
||||
ns = flag.String("n", "9.9.9.9", "nameservers to use")
|
||||
ns = flag.String("n", "9.9.9.9", "nameservers to use, separated by ':' or ','")
|
||||
blocklistPath = flag.String("b", "", "blocklist path")
|
||||
zonesPath = flag.String("z", "", "add a custom zone file")
|
||||
hostsPath = flag.String("h", "", "add a custom hosts file")
|
||||
cpu = flag.Int("c", 0, "number of cpu to use")
|
||||
ttl = flag.Int("t", 10, "force queries TTL")
|
||||
ttl = flag.Int("t", 10, "cache TTL for queries, in minutes")
|
||||
dot = flag.Bool("s", false, "use tls to contact the resolver")
|
||||
logs = flag.Bool("l", false, "log queries")
|
||||
metrics = flag.Bool("m", false, "enable prometheus metrics")
|
||||
qcache *cache.Cache
|
||||
inflight singleflight.Group
|
||||
|
||||
// Optimized data structures for O(1) lookups
|
||||
blocklistMap = make(map[string]bool)
|
||||
zonesMap = make(map[string]string)
|
||||
hostsMap = make(map[string]string)
|
||||
@@ -60,7 +63,7 @@ var (
|
||||
})
|
||||
slowAnswers = promauto.NewSummary(prometheus.SummaryOpts{
|
||||
Name: "rdns_answers_slow",
|
||||
Help: "Number of queries answered within 100 millisecond",
|
||||
Help: "Latency of upstream responses exceeding 100 milliseconds",
|
||||
})
|
||||
cacheHits = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "rdns_cache_hits",
|
||||
@@ -85,30 +88,10 @@ var (
|
||||
)
|
||||
|
||||
func getRcode(rcode int) string {
|
||||
switch rcode {
|
||||
case 0:
|
||||
return "NOERROR"
|
||||
case 1:
|
||||
return "FORMERR"
|
||||
case 2:
|
||||
return "SERVFAIL"
|
||||
case 3:
|
||||
return "NXDOMAIN"
|
||||
case 4:
|
||||
return "NOTIMP"
|
||||
case 5:
|
||||
return "REFUSED"
|
||||
case 6:
|
||||
return "YXDOMAIN"
|
||||
case 7:
|
||||
return "XRRSET"
|
||||
case 8:
|
||||
return "NOTAUTH"
|
||||
case 9:
|
||||
return "NOTZONE"
|
||||
default:
|
||||
return "SERVFAIL"
|
||||
if name, ok := dns.RcodeToString[rcode]; ok {
|
||||
return name
|
||||
}
|
||||
return "SERVFAIL"
|
||||
}
|
||||
|
||||
func getDomain(qn string) string {
|
||||
@@ -143,14 +126,33 @@ func doDot(s string) string {
|
||||
return s + "."
|
||||
}
|
||||
|
||||
func handleCache(q *dns.Msg, qname string, qtype string) (*dns.Msg, int) {
|
||||
var qnt = qname + "." + qtype
|
||||
if cached, found := qcache.Get(qnt); found {
|
||||
cached.(*dns.Msg).MsgHdr.Id = q.MsgHdr.Id
|
||||
rcode := cached.(*dns.Msg).MsgHdr.Rcode
|
||||
return cached.(*dns.Msg), rcode
|
||||
func clientIP(w dns.ResponseWriter) string {
|
||||
addr := w.RemoteAddr()
|
||||
if addr == nil {
|
||||
return "unknown"
|
||||
}
|
||||
return q, 2
|
||||
if host, _, err := net.SplitHostPort(addr.String()); err == nil {
|
||||
return host
|
||||
}
|
||||
return addr.String()
|
||||
}
|
||||
|
||||
func cacheKey(qname, qclass, qtype string) string {
|
||||
return qname + "." + qclass + "." + qtype
|
||||
}
|
||||
|
||||
func handleCache(q *dns.Msg, key string) (*dns.Msg, int, bool) {
|
||||
if cached, found := qcache.Get(key); found {
|
||||
msg := cached.(*dns.Msg).Copy()
|
||||
msg.Id = q.Id
|
||||
return msg, msg.Rcode, true
|
||||
}
|
||||
return nil, 0, false
|
||||
}
|
||||
|
||||
type lookupResult struct {
|
||||
msg *dns.Msg
|
||||
proto string
|
||||
}
|
||||
|
||||
func lookup(q *dns.Msg, qname string) (*dns.Msg, string, error) {
|
||||
@@ -159,15 +161,16 @@ func lookup(q *dns.Msg, qname string) (*dns.Msg, string, error) {
|
||||
rtt time.Duration
|
||||
err error
|
||||
n []string
|
||||
notls bool = false
|
||||
qdomain = getDomain(qname)
|
||||
notls bool = false
|
||||
proto string = "udp"
|
||||
qdomain = getDomain(qname)
|
||||
)
|
||||
|
||||
if zoneNS := getZoneNS(qdomain); zoneNS != "." {
|
||||
n = []string{zoneNS}
|
||||
notls = true
|
||||
} else {
|
||||
n = strings.Split(*ns, ":")
|
||||
n = strings.FieldsFunc(*ns, func(r rune) bool { return r == ':' || r == ',' })
|
||||
if len(n) > 1 {
|
||||
rand.Shuffle(len(n), func(i, j int) {
|
||||
n[i], n[j] = n[j], n[i]
|
||||
@@ -175,25 +178,36 @@ func lookup(q *dns.Msg, qname string) (*dns.Msg, string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
c := new(dns.Client)
|
||||
// Advertise an EDNS0 buffer to avoid truncated UDP responses
|
||||
if q.IsEdns0() == nil {
|
||||
q.SetEdns0(dns.DefaultMsgSize, false)
|
||||
}
|
||||
|
||||
c := &dns.Client{UDPSize: dns.MaxMsgSize}
|
||||
for i := 0; i < len(n); i++ {
|
||||
if *dot && !notls {
|
||||
c.Net = "tcp-tls"
|
||||
// Use proper TLS configuration with certificate verification
|
||||
c.TLSConfig = &tls.Config{
|
||||
ServerName: n[i],
|
||||
}
|
||||
proto = "tcp-tls"
|
||||
r, rtt, err = c.Exchange(q, net.JoinHostPort(n[i], "853"))
|
||||
if err != nil {
|
||||
// Always log TLS connection failures to stderr (security-critical)
|
||||
fmt.Fprintf(os.Stderr, "TLS connection failed to %s: %v\n", n[i], err)
|
||||
}
|
||||
} else {
|
||||
c.Net = "udp"
|
||||
proto = "udp"
|
||||
r, rtt, err = c.Exchange(q, net.JoinHostPort(n[i], "53"))
|
||||
if err != nil && *logs {
|
||||
log.Println("WARN:", err)
|
||||
}
|
||||
if err == nil && r.Truncated {
|
||||
// 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"))
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
nameservers.WithLabelValues(n[i]).Inc()
|
||||
@@ -205,10 +219,38 @@ func lookup(q *dns.Msg, qname string) (*dns.Msg, string, error) {
|
||||
slowAnswers.Observe(float64(rtt / time.Millisecond))
|
||||
}
|
||||
|
||||
return r, c.Net, err
|
||||
return r, proto, err
|
||||
}
|
||||
|
||||
func resolve(q *dns.Msg, qname, key string) (*dns.Msg, string, error) {
|
||||
v, err, _ := inflight.Do(key, func() (any, error) {
|
||||
msg, proto, err := lookup(q, qname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &lookupResult{msg: msg, proto: proto}, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
res := v.(*lookupResult)
|
||||
msg := res.msg.Copy()
|
||||
msg.Id = q.Id
|
||||
return msg, res.proto, nil
|
||||
}
|
||||
|
||||
func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
|
||||
queries.Inc()
|
||||
|
||||
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)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
r *dns.Msg
|
||||
err error
|
||||
@@ -217,27 +259,25 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
|
||||
qname = strings.ToLower(q.Question[0].Name[:len(q.Question[0].Name)-1])
|
||||
qclass = dns.Class(q.Question[0].Qclass).String()
|
||||
qtype = dns.Type(q.Question[0].Qtype).String()
|
||||
qnt = qname + "." + qtype
|
||||
client = strings.Split(w.RemoteAddr().String(), ":")[0]
|
||||
key = cacheKey(qname, qclass, qtype)
|
||||
client = clientIP(w)
|
||||
)
|
||||
|
||||
queries.Inc()
|
||||
qtypes.WithLabelValues(qtype).Inc()
|
||||
|
||||
if qclass == "CH" && qname == "version.bind" {
|
||||
qname = "version.bind."
|
||||
r = new(dns.Msg)
|
||||
rcode = 0
|
||||
r.SetReply(q)
|
||||
rcode = dns.RcodeSuccess
|
||||
r.SetRcode(q, rcode)
|
||||
r.MsgHdr.RecursionAvailable = true
|
||||
r.Answer = append(r.Answer, &dns.TXT{
|
||||
Hdr: dns.RR_Header{Name: qname, Rrtype: 16, Class: 3, Ttl: 86400},
|
||||
Hdr: dns.RR_Header{Name: "version.bind.", Rrtype: dns.TypeTXT, Class: dns.ClassCHAOS, Ttl: 86400},
|
||||
Txt: []string{"rdns"},
|
||||
})
|
||||
qcache.SetDefault(key, r)
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode))
|
||||
}
|
||||
qcache.SetDefault(qnt, r)
|
||||
if err := w.WriteMsg(r); err != nil && *logs {
|
||||
log.Println("ERROR: Failed to write response:", err)
|
||||
}
|
||||
@@ -245,7 +285,7 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
|
||||
return
|
||||
}
|
||||
|
||||
if r, rcode = handleCache(q, qname, qtype); rcode != 2 {
|
||||
if r, rcode, ok := handleCache(q, key); ok {
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode), "cache")
|
||||
}
|
||||
@@ -257,41 +297,42 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
|
||||
return
|
||||
}
|
||||
|
||||
if hostIP := getHost(qname); hostIP != "" && (qtype == "A" || qtype == "AAAA") {
|
||||
r = new(dns.Msg)
|
||||
rcode = 0
|
||||
r.SetReply(q)
|
||||
r.SetRcode(q, rcode)
|
||||
r.MsgHdr.RecursionAvailable = true
|
||||
if qtype == "A" {
|
||||
r.Answer = append(r.Answer, &dns.A{
|
||||
Hdr: dns.RR_Header{Name: doDot(qname), Rrtype: 1, Class: 1, Ttl: 300},
|
||||
A: net.ParseIP(hostIP),
|
||||
})
|
||||
if hostIP := getHost(qname); hostIP != "" {
|
||||
ip := net.ParseIP(hostIP)
|
||||
if (qtype == "A" && ip != nil && ip.To4() != nil) || (qtype == "AAAA" && ip != nil && ip.To4() == nil) {
|
||||
r = new(dns.Msg)
|
||||
rcode = dns.RcodeSuccess
|
||||
r.SetRcode(q, rcode)
|
||||
r.MsgHdr.RecursionAvailable = true
|
||||
if qtype == "A" {
|
||||
r.Answer = append(r.Answer, &dns.A{
|
||||
Hdr: dns.RR_Header{Name: doDot(qname), Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300},
|
||||
A: ip,
|
||||
})
|
||||
} else {
|
||||
r.Answer = append(r.Answer, &dns.AAAA{
|
||||
Hdr: dns.RR_Header{Name: doDot(qname), Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: 300},
|
||||
AAAA: ip,
|
||||
})
|
||||
}
|
||||
qcache.SetDefault(key, r)
|
||||
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)
|
||||
}
|
||||
responses.WithLabelValues(qtype, getRcode(rcode)).Inc()
|
||||
return
|
||||
}
|
||||
if qtype == "AAAA" {
|
||||
r.Answer = append(r.Answer, &dns.AAAA{
|
||||
Hdr: dns.RR_Header{Name: doDot(qname), Rrtype: 28, Class: 1, Ttl: 300},
|
||||
AAAA: net.ParseIP(hostIP),
|
||||
})
|
||||
}
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode))
|
||||
}
|
||||
qcache.SetDefault(qnt, r)
|
||||
if err := w.WriteMsg(r); err != nil && *logs {
|
||||
log.Println("ERROR: Failed to write response:", err)
|
||||
}
|
||||
responses.WithLabelValues(qtype, getRcode(rcode)).Inc()
|
||||
return
|
||||
}
|
||||
|
||||
if blocklistMap[qname] {
|
||||
r = new(dns.Msg)
|
||||
rcode = 5
|
||||
r.SetReply(q)
|
||||
rcode = dns.RcodeRefused
|
||||
r.SetRcode(q, rcode)
|
||||
qcache.SetDefault(qnt, r)
|
||||
r.MsgHdr.RecursionAvailable = true
|
||||
qcache.SetDefault(key, r)
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode))
|
||||
}
|
||||
@@ -302,37 +343,46 @@ func handleQuery(w dns.ResponseWriter, q *dns.Msg) {
|
||||
return
|
||||
}
|
||||
|
||||
r, proto, err = lookup(q, qname)
|
||||
r, proto, err = resolve(q, qname, key)
|
||||
if err != nil {
|
||||
if *logs {
|
||||
log.Println("ERROR:", err)
|
||||
}
|
||||
r = new(dns.Msg)
|
||||
rcode = 2
|
||||
r.SetReply(q)
|
||||
r.SetRcode(r, rcode)
|
||||
rcode = dns.RcodeServerFailure
|
||||
r.SetRcode(q, rcode)
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode))
|
||||
}
|
||||
} else {
|
||||
rcode = r.MsgHdr.Rcode
|
||||
rcode = r.Rcode
|
||||
r.MsgHdr.RecursionAvailable = true
|
||||
qcache.SetDefault(key, r)
|
||||
if *logs {
|
||||
log.Println(client, qname, qclass, qtype, getRcode(rcode), proto)
|
||||
}
|
||||
}
|
||||
qcache.SetDefault(qnt, r)
|
||||
if err := w.WriteMsg(r); err != nil && *logs {
|
||||
log.Println("ERROR: Failed to write response:", err)
|
||||
}
|
||||
responses.WithLabelValues(qtype, getRcode(rcode)).Inc()
|
||||
}
|
||||
|
||||
func serve(addr string, port string, net string) {
|
||||
server := &dns.Server{Addr: addr + ":" + port, Net: net, ReusePort: true}
|
||||
if err := server.ListenAndServe(); err != nil {
|
||||
fmt.Printf("Failed to setup the "+net+" server: %s\n", err.Error())
|
||||
func serve(addr string, port string, network string, started func()) *dns.Server {
|
||||
server := &dns.Server{
|
||||
Addr: net.JoinHostPort(addr, port),
|
||||
Net: network,
|
||||
ReusePort: true,
|
||||
UDPSize: dns.DefaultMsgSize,
|
||||
NotifyStartedFunc: started,
|
||||
}
|
||||
go func() {
|
||||
if err := server.ListenAndServe(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Failed to setup the %s server on %s: %v\n", network, server.Addr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
return server
|
||||
}
|
||||
|
||||
func loadBlocklist(path string) {
|
||||
@@ -345,7 +395,7 @@ func loadBlocklist(path string) {
|
||||
lines := strings.Split(string(data), "\n")
|
||||
count := 0
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
line = strings.ToLower(strings.TrimSpace(line))
|
||||
if line != "" && !strings.HasPrefix(line, "#") {
|
||||
blocklistMap[line] = true
|
||||
count++
|
||||
@@ -376,7 +426,7 @@ func loadZones(path string) int {
|
||||
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) >= 2 {
|
||||
zonesMap[parts[0]] = parts[1]
|
||||
zonesMap[strings.ToLower(parts[0])] = parts[1]
|
||||
count++
|
||||
}
|
||||
}
|
||||
@@ -403,10 +453,9 @@ func loadHosts(path string) int {
|
||||
}
|
||||
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) >= 2 {
|
||||
// Map all hostnames to the IP (first field)
|
||||
if len(parts) >= 2 && net.ParseIP(parts[0]) != nil {
|
||||
for i := 1; i < len(parts); i++ {
|
||||
hostsMap[parts[i]] = parts[0]
|
||||
hostsMap[strings.ToLower(parts[i])] = parts[0]
|
||||
count++
|
||||
}
|
||||
}
|
||||
@@ -456,20 +505,54 @@ func main() {
|
||||
fmt.Println("Hosts loaded:", count, "entries")
|
||||
}
|
||||
}
|
||||
|
||||
var metricsServer *http.Server
|
||||
if *metrics {
|
||||
fmt.Println("Starting prometheus exporter on port 9153")
|
||||
http.Handle("/metrics", promhttp.Handler())
|
||||
go http.ListenAndServe(":9153", nil)
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/metrics", promhttp.Handler())
|
||||
metricsServer = &http.Server{
|
||||
Addr: ":9153",
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
if err := metricsServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
fmt.Fprintf(os.Stderr, "Metrics server error: %v\n", err)
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(10 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
cacheItems.Set(float64(qcache.ItemCount()))
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
dns.HandleFunc(".", handleQuery)
|
||||
go serve(*addr, *port, "tcp")
|
||||
go serve(*addr, *port, "udp")
|
||||
|
||||
up.Set(float64(1))
|
||||
var readyOnce sync.Once
|
||||
ready := func() { readyOnce.Do(func() { up.Set(1) }) }
|
||||
servers := []*dns.Server{
|
||||
serve(*addr, *port, "tcp", ready),
|
||||
serve(*addr, *port, "udp", ready),
|
||||
}
|
||||
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-sig
|
||||
fmt.Printf("\033[2K\rTime to sleep, goodbye\n")
|
||||
|
||||
for _, s := range servers {
|
||||
if err := s.Shutdown(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error shutting down server: %v\n", err)
|
||||
}
|
||||
}
|
||||
if metricsServer != nil {
|
||||
if err := metricsServer.Close(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
fmt.Fprintf(os.Stderr, "Error shutting down metrics server: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
"github.com/patrickmn/go-cache"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
qcache = cache.New(time.Minute, time.Minute)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
type mockWriter struct {
|
||||
msg *dns.Msg
|
||||
addr net.Addr
|
||||
}
|
||||
|
||||
func (m *mockWriter) WriteMsg(msg *dns.Msg) error { m.msg = msg; return nil }
|
||||
func (m *mockWriter) LocalAddr() net.Addr { return m.addr }
|
||||
func (m *mockWriter) RemoteAddr() net.Addr { return m.addr }
|
||||
func (m *mockWriter) Write(b []byte) (int, error) { return len(b), nil }
|
||||
func (m *mockWriter) Close() error { return nil }
|
||||
func (m *mockWriter) TsigStatus() error { return nil }
|
||||
func (m *mockWriter) TsigTimersOnly(bool) {}
|
||||
func (m *mockWriter) Hijack() {}
|
||||
|
||||
func resetMaps() {
|
||||
clear(hostsMap)
|
||||
clear(blocklistMap)
|
||||
clear(zonesMap)
|
||||
}
|
||||
|
||||
func newQuery(name string, qtype uint16, qclass uint16) *dns.Msg {
|
||||
q := new(dns.Msg)
|
||||
q.SetQuestion(dns.Fqdn(name), qtype)
|
||||
q.Question[0].Qclass = qclass
|
||||
return q
|
||||
}
|
||||
|
||||
func TestGetDomain(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"example.test": "example.test",
|
||||
"a.example.test": "example.test",
|
||||
"long.a.example.test": "example.test",
|
||||
"localhost": "localhost",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := getDomain(in); got != want {
|
||||
t.Errorf("getDomain(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoDot(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"": ".",
|
||||
".": ".",
|
||||
"example.test": "example.test.",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := doDot(in); got != want {
|
||||
t.Errorf("doDot(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRcode(t *testing.T) {
|
||||
if got := getRcode(dns.RcodeSuccess); got != "NOERROR" {
|
||||
t.Errorf("getRcode(0) = %q, want NOERROR", got)
|
||||
}
|
||||
if got := getRcode(dns.RcodeRefused); got != "REFUSED" {
|
||||
t.Errorf("getRcode(5) = %q, want REFUSED", got)
|
||||
}
|
||||
if got := getRcode(250); got != "SERVFAIL" {
|
||||
t.Errorf("getRcode(250) = %q, want SERVFAIL", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheKeyIncludesClass(t *testing.T) {
|
||||
a := cacheKey("version.bind", "CH", "TXT")
|
||||
b := cacheKey("version.bind", "IN", "TXT")
|
||||
if a == b {
|
||||
t.Error("cache key must differ between qclasses")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCacheReturnsCopy(t *testing.T) {
|
||||
qcache.Flush()
|
||||
cached := new(dns.Msg)
|
||||
cached.SetReply(newQuery("example.test", dns.TypeA, dns.ClassINET))
|
||||
cached.Id = 4321
|
||||
qcache.SetDefault(cacheKey("example.test", "IN", "A"), cached)
|
||||
|
||||
req := newQuery("example.test", dns.TypeA, dns.ClassINET)
|
||||
req.Id = 1234
|
||||
msg, rcode, ok := handleCache(req, cacheKey("example.test", "IN", "A"))
|
||||
if !ok {
|
||||
t.Fatal("expected cache hit")
|
||||
}
|
||||
if rcode != dns.RcodeSuccess {
|
||||
t.Errorf("rcode = %d, want 0", rcode)
|
||||
}
|
||||
if msg.Id != 1234 {
|
||||
t.Errorf("returned message ID = %d, want 1234 (caller ID)", msg.Id)
|
||||
}
|
||||
if cached.Id != 4321 {
|
||||
t.Errorf("cached entry ID mutated: %d, want 4321", cached.Id)
|
||||
}
|
||||
if msg == cached {
|
||||
t.Error("handleCache must return a copy, not the shared cached entry")
|
||||
}
|
||||
|
||||
if _, _, ok := handleCache(req, cacheKey("other.test", "IN", "A")); ok {
|
||||
t.Error("expected cache miss for unknown key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBlocklist(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "blocklist.txt")
|
||||
content := "# comment\n\nExample.TEST\n spaced.test \nblocked.test\n# trailing comment\n"
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
resetMaps()
|
||||
loadBlocklist(path)
|
||||
|
||||
want := map[string]bool{"example.test": true, "spaced.test": true, "blocked.test": true}
|
||||
for name := range want {
|
||||
if !blocklistMap[name] {
|
||||
t.Errorf("blocklist missing %q", name)
|
||||
}
|
||||
}
|
||||
if len(blocklistMap) != len(want) {
|
||||
t.Errorf("blocklist size = %d, want %d", len(blocklistMap), len(want))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadZones(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "zones")
|
||||
content := "# comment\nExample.TEST 192.168.1.102\nplain.test 10.0.0.1 # inline comment\nbroken-line\n"
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
resetMaps()
|
||||
count := loadZones(path)
|
||||
|
||||
if count != 2 {
|
||||
t.Errorf("count = %d, want 2", count)
|
||||
}
|
||||
if ns := getZoneNS("example.test"); ns != "192.168.1.102" {
|
||||
t.Errorf("getZoneNS(example.test) = %q, want 192.168.1.102", ns)
|
||||
}
|
||||
if ns := getZoneNS("unknown.test"); ns != "." {
|
||||
t.Errorf("getZoneNS(unknown.test) = %q, want \".\"", ns)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadHosts(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
content := "# comment\n192.168.1.10 Example.TEST other.test\nnot-an-ip broken.test\n2001:db8::1 v6.test\n"
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
resetMaps()
|
||||
count := loadHosts(path)
|
||||
|
||||
if count != 3 {
|
||||
t.Errorf("count = %d, want 3", count)
|
||||
}
|
||||
if ip := getHost("example.test"); ip != "192.168.1.10" {
|
||||
t.Errorf("getHost(example.test) = %q, want 192.168.1.10", ip)
|
||||
}
|
||||
if ip := getHost("broken.test"); ip != "" {
|
||||
t.Errorf("getHost(broken.test) = %q, want empty (invalid IP must be skipped)", ip)
|
||||
}
|
||||
if ip := getHost("v6.test"); ip != "2001:db8::1" {
|
||||
t.Errorf("getHost(v6.test) = %q, want 2001:db8::1", ip)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientIP(t *testing.T) {
|
||||
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
|
||||
if got := clientIP(w); got != "192.0.2.10" {
|
||||
t.Errorf("clientIP = %q, want 192.0.2.10", got)
|
||||
}
|
||||
w = &mockWriter{addr: &net.TCPAddr{IP: net.ParseIP("2001:db8::1"), Port: 5300}}
|
||||
if got := clientIP(w); got != "2001:db8::1" {
|
||||
t.Errorf("clientIP = %q, want 2001:db8::1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryHostsAnswer(t *testing.T) {
|
||||
resetMaps()
|
||||
qcache.Flush()
|
||||
hostsMap["example.test"] = "192.168.1.10"
|
||||
blocklistMap["example.test"] = true // ensures a fallthrough is observable
|
||||
|
||||
// A query matches the IPv4 entry
|
||||
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
|
||||
handleQuery(w, newQuery("example.test", dns.TypeA, dns.ClassINET))
|
||||
|
||||
if w.msg == nil {
|
||||
t.Fatal("no response written")
|
||||
}
|
||||
if len(w.msg.Answer) != 1 {
|
||||
t.Fatalf("answers = %d, want 1", len(w.msg.Answer))
|
||||
}
|
||||
a, ok := w.msg.Answer[0].(*dns.A)
|
||||
if !ok {
|
||||
t.Fatalf("answer type = %T, want *dns.A", w.msg.Answer[0])
|
||||
}
|
||||
if !a.A.Equal(net.ParseIP("192.168.1.10")) {
|
||||
t.Errorf("A = %v, want 192.168.1.10", a.A)
|
||||
}
|
||||
|
||||
// AAAA query does not match an IPv4 entry and must fall through (blocked here)
|
||||
w = &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
|
||||
handleQuery(w, newQuery("example.test", dns.TypeAAAA, dns.ClassINET))
|
||||
if w.msg == nil {
|
||||
t.Fatal("no response written")
|
||||
}
|
||||
if w.msg.Rcode != dns.RcodeRefused {
|
||||
t.Errorf("rcode = %d, want REFUSED (fallthrough to blocklist)", w.msg.Rcode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryBlocked(t *testing.T) {
|
||||
resetMaps()
|
||||
qcache.Flush()
|
||||
blocklistMap["ads.example.test"] = true
|
||||
|
||||
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
|
||||
handleQuery(w, newQuery("ads.example.test", dns.TypeA, dns.ClassINET))
|
||||
|
||||
if w.msg == nil {
|
||||
t.Fatal("no response written")
|
||||
}
|
||||
if w.msg.Rcode != dns.RcodeRefused {
|
||||
t.Errorf("rcode = %d, want REFUSED", w.msg.Rcode)
|
||||
}
|
||||
if !w.msg.RecursionAvailable {
|
||||
t.Error("RecursionAvailable not set on REFUSED reply")
|
||||
}
|
||||
|
||||
// Second identical query must be served from cache
|
||||
w2 := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
|
||||
q2 := newQuery("ads.example.test", dns.TypeA, dns.ClassINET)
|
||||
q2.Id = 7777
|
||||
handleQuery(w2, q2)
|
||||
if w2.msg == nil || w2.msg.Rcode != dns.RcodeRefused {
|
||||
t.Fatalf("cached response rcode = %v, want REFUSED", w2.msg)
|
||||
}
|
||||
if w2.msg.Id != 7777 {
|
||||
t.Errorf("cached response ID = %d, want 7777", w2.msg.Id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryVersionBind(t *testing.T) {
|
||||
resetMaps()
|
||||
qcache.Flush()
|
||||
|
||||
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
|
||||
handleQuery(w, newQuery("version.bind", dns.TypeTXT, dns.ClassCHAOS))
|
||||
|
||||
if w.msg == nil {
|
||||
t.Fatal("no response written")
|
||||
}
|
||||
if len(w.msg.Answer) != 1 {
|
||||
t.Fatalf("answers = %d, want 1", len(w.msg.Answer))
|
||||
}
|
||||
txt, ok := w.msg.Answer[0].(*dns.TXT)
|
||||
if !ok {
|
||||
t.Fatalf("answer type = %T, want *dns.TXT", w.msg.Answer[0])
|
||||
}
|
||||
if len(txt.Txt) != 1 || txt.Txt[0] != "rdns" {
|
||||
t.Errorf("TXT = %v, want [rdns]", txt.Txt)
|
||||
}
|
||||
|
||||
// An IN-class version.bind query must not be served from the CH cache entry
|
||||
if _, _, ok := handleCache(newQuery("version.bind", dns.TypeTXT, dns.ClassINET), cacheKey("version.bind", "IN", "TXT")); ok {
|
||||
t.Error("IN class query must not hit the CH class cache entry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryMalformed(t *testing.T) {
|
||||
w := &mockWriter{addr: &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 5300}}
|
||||
handleQuery(w, &dns.Msg{MsgHdr: dns.MsgHdr{Id: 42}})
|
||||
|
||||
if w.msg == nil {
|
||||
t.Fatal("no response written for question-less query")
|
||||
}
|
||||
if w.msg.Rcode != dns.RcodeFormatError {
|
||||
t.Errorf("rcode = %d, want FORMERR", w.msg.Rcode)
|
||||
}
|
||||
}
|
||||
+12
-6
@@ -1,13 +1,19 @@
|
||||
#!/bin/bash
|
||||
# Usage ./blocklist_update | sort | uniq | sed $'s/[^[:print:]\t]//g'
|
||||
|
||||
list=$(curl -s https://v.firebog.net/hosts/lists.php?type=tick)
|
||||
list+=https://raw.githubusercontent.com/AdAway/adaway.github.io/master/hosts.txt
|
||||
list+=https://hblock.molinero.dev/hosts_domains.txt
|
||||
set -euo pipefail
|
||||
|
||||
for i in $list;
|
||||
do
|
||||
curl -s $i | grep -v "#" | sed '/^$/d' | sed 's/127\.0\.0\.1\|0\.0\.0\.0//g' | sed '/^[^a-zA-Z0-9\ ]/d' | sed 's/[^a-zA-Z0-9\.\-]//g' | awk '{ print $NF }'
|
||||
list=(
|
||||
https://raw.githubusercontent.com/AdAway/adaway.github.io/master/hosts.txt
|
||||
https://hblock.molinero.dev/hosts_domains.txt
|
||||
)
|
||||
|
||||
while IFS= read -r url; do
|
||||
list+=("$url")
|
||||
done < <(curl -fsSL https://v.firebog.net/hosts/lists.php?type=tick)
|
||||
|
||||
for i in "${list[@]}"; do
|
||||
curl -fsSL "$i" | grep -v '#' | sed '/^$/d' | sed 's/127\.0\.0\.1\|0\.0\.0\.0//g' | sed '/^[^a-zA-Z0-9\ ]/d' | sed 's/[^a-zA-Z0-9\.\-]//g' | awk '{ print $NF }' || true
|
||||
done
|
||||
|
||||
echo "msn.com"
|
||||
|
||||
@@ -8,5 +8,13 @@ ExecStart=/usr/local/bin/rdns -b /etc/rdns/blocklist.txt -z /etc/rdns/rdns.zones
|
||||
# optional args: -l -m
|
||||
Restart=on-failure
|
||||
|
||||
# Hardening
|
||||
NoNewPrivileges=true
|
||||
ProtectHome=true
|
||||
ProtectSystem=full
|
||||
ProtectKernelTunables=true
|
||||
ProtectControlGroups=true
|
||||
RestrictSUIDSGID=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Reference in new issue
Block a user