1// Package dnsbl implements DNS block lists (RFC 5782), for checking incoming messages from sources without reputation.
2//
3// A DNS block list contains IP addresses that should be blocked. The DNSBL is
4// queried using DNS "A" lookups. The DNSBL starts at a "zone", e.g.
5// "dnsbl.example". To look up whether an IP address is listed, a DNS name is
6// composed: For 10.11.12.13, that name would be "13.12.11.10.dnsbl.example". If
7// the lookup returns "record does not exist", the IP is not listed. If an IP
8// address is returned, the IP is listed. If an IP is listed, an additional TXT
9// lookup is done for more information about the block. IPv6 addresses are also
10// looked up with an DNS "A" lookup of a name similar to an IPv4 address, but with
11// 4-bit hexadecimal dot-separated characters, in reverse.
12//
13// The health of a DNSBL "zone" can be check through a lookup of 127.0.0.1
14// (must not be present) and 127.0.0.2 (must be present).
15package dnsbl
16
17import (
18 "context"
19 "errors"
20 "fmt"
21 "log/slog"
22 "net"
23 "strconv"
24 "strings"
25 "time"
26
27 "github.com/mjl-/mox/dns"
28 "github.com/mjl-/mox/mlog"
29 "github.com/mjl-/mox/stub"
30)
31
32var (
33 MetricLookup stub.HistogramVec = stub.HistogramVecIgnore{}
34)
35
36var ErrDNS = errors.New("dnsbl: dns error") // Temporary error.
37
38// Status is the result of a DNSBL lookup.
39type Status string
40
41var (
42 StatusTemperr Status = "temperror" // Temporary failure.
43 StatusPass Status = "pass" // Not present in block list.
44 StatusFail Status = "fail" // Present in block list.
45)
46
47// Lookup checks if "ip" occurs in the DNS block list "zone" (e.g. dnsbl.example.org).
48func Lookup(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, zone dns.Domain, ip net.IP) (rstatus Status, rexplanation string, rerr error) {
49 log := mlog.New("dnsbl", elog)
50 start := time.Now()
51 defer func() {
52 MetricLookup.ObserveLabels(float64(time.Since(start))/float64(time.Second), zone.Name(), string(rstatus))
53 log.Debugx("dnsbl lookup result", rerr,
54 slog.Any("zone", zone),
55 slog.Any("ip", ip),
56 slog.Any("status", rstatus),
57 slog.String("explanation", rexplanation),
58 slog.Duration("duration", time.Since(start)))
59 }()
60
61 b := &strings.Builder{}
62 v4 := ip.To4()
63 if v4 != nil {
64 // ../rfc/5782:148
65 s := len(v4) - 1
66 for i := s; i >= 0; i-- {
67 if i < s {
68 b.WriteByte('.')
69 }
70 b.WriteString(strconv.Itoa(int(v4[i])))
71 }
72 } else {
73 // ../rfc/5782:270
74 s := len(ip) - 1
75 const chars = "0123456789abcdef"
76 for i := s; i >= 0; i-- {
77 if i < s {
78 b.WriteByte('.')
79 }
80 v := ip[i]
81 b.WriteByte(chars[v>>0&0xf])
82 b.WriteByte('.')
83 b.WriteByte(chars[v>>4&0xf])
84 }
85 }
86 b.WriteString("." + zone.ASCII + ".")
87 addr := b.String()
88
89 // ../rfc/5782:175
90 _, _, err := dns.WithPackage(resolver, "dnsbl").LookupIP(ctx, "ip4", addr)
91 if dns.IsNotFound(err) {
92 return StatusPass, "", nil
93 } else if err != nil {
94 return StatusTemperr, "", fmt.Errorf("%w: %s", ErrDNS, err)
95 }
96
97 txts, _, err := dns.WithPackage(resolver, "dnsbl").LookupTXT(ctx, addr)
98 if dns.IsNotFound(err) {
99 return StatusFail, "", nil
100 } else if err != nil {
101 log.Debugx("looking up txt record from dnsbl", err, slog.String("addr", addr))
102 return StatusFail, "", nil
103 }
104 return StatusFail, strings.Join(txts, "; "), nil
105}
106
107// CheckHealth checks whether the DNSBL "zone" is operating correctly by
108// querying for 127.0.0.2 (must be present) and 127.0.0.1 (must not be present).
109// Users of a DNSBL should periodically check if the DNSBL is still operating
110// properly.
111// For temporary errors, ErrDNS is returned.
112func CheckHealth(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, zone dns.Domain) (rerr error) {
113 log := mlog.New("dnsbl", elog)
114 start := time.Now()
115 defer func() {
116 log.Debugx("dnsbl healthcheck result", rerr, slog.Any("zone", zone), slog.Duration("duration", time.Since(start)))
117 }()
118
119 // ../rfc/5782:355
120 status1, _, err1 := Lookup(ctx, log.Logger, resolver, zone, net.IPv4(127, 0, 0, 1))
121 status2, _, err2 := Lookup(ctx, log.Logger, resolver, zone, net.IPv4(127, 0, 0, 2))
122 if status1 == StatusPass && status2 == StatusFail {
123 return nil
124 } else if status1 == StatusFail {
125 return fmt.Errorf("dnsbl contains unwanted test address 127.0.0.1")
126 } else if status2 == StatusPass {
127 return fmt.Errorf("dnsbl does not contain required test address 127.0.0.2")
128 }
129 if err1 != nil {
130 return err1
131 } else if err2 != nil {
132 return err2
133 }
134 return ErrDNS
135}
136