-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpolicy.go
More file actions
314 lines (280 loc) · 10 KB
/
policy.go
File metadata and controls
314 lines (280 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*
File: policy.go
Version: 1.6.0
Updated: 2026-04-13 13:52 CEST
Description:
DNS query policy enforcement and domain-map lookup for sdproxy.
Contains five distinct but tightly related responsibilities:
1. Policy response generation — dynamically constructs policy exits
(REFUSED, NOTIMP, NXDOMAIN, NOERROR, NULL-IP, or Silent Drops) ensuring
the response Question matches the query perfectly.
2. walkDomainMaps — single label-by-label suffix walk that checks both
domainPolicy and domainRoutes in one pass. Bounded by pre-computed
min/max label depths so a pure eTLD+1 list costs exactly one map probe.
3. Routing helper — getRouteIdx.
4. Name normalisation — lowerTrimDot, isValidReversePTR, extractIPFromPTR,
countDomainLabels.
5. TTL capping — CapResponseTTL, used by the parental control path in
process.go to enforce a heartbeat TTL on categorised domains.
Changes:
1.6.0 - [FEAT] Replaced `writePolicyResp` with `writePolicyAction` to support
dynamic "DROP" and "BLOCK" commands (Null-IP for A/AAAA/NXDOMAIN for others)
alongside standard DNS RCODE responses. Upgraded Cache Synthesizer to
mirror Null-IP Block architectures and safely ignore DROP operations.
1.5.0 - [FEAT] Added extractIPFromPTR to parse and rebuild underlying IPv4
and IPv6 address strings from .in-addr.arpa and .ip6.arpa domains,
enabling PTR queries to be evaluated against IP/CIDR blocklists.
*/
package main
import (
"net"
"net/netip"
"strings"
"github.com/miekg/dns"
)
// ---------------------------------------------------------------------------
// Policy response generation
// ---------------------------------------------------------------------------
// writePolicyAction executes a dynamically constructed policy response for the given
// action or RCODE. If the action is PolicyActionDrop, it silently drops the query.
// Returns true if the query was dropped (no response sent), false otherwise.
func writePolicyAction(w dns.ResponseWriter, r *dns.Msg, action int) bool {
IncrPolicyBlock() // stats counter — single atomic Add, zero DNS-path cost
if action == PolicyActionDrop {
return true // Silently drop, do not write a response
}
// Pull from the shared message pool to avoid allocation overhead.
msg := msgPool.Get().(*dns.Msg)
*msg = dns.Msg{}
msg.SetReply(r) // Automatically mirrors the client's Question (Name, Class, Type)
msg.RecursionAvailable = true
q := r.Question[0]
if action == PolicyActionBlock {
if q.Qtype == dns.TypeA {
msg.Rcode = dns.RcodeSuccess
msg.Answer = append(msg.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: syntheticTTL},
A: net.IPv4zero,
})
} else if q.Qtype == dns.TypeAAAA {
msg.Rcode = dns.RcodeSuccess
msg.Answer = append(msg.Answer, &dns.AAAA{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: syntheticTTL},
AAAA: net.IPv6unspecified,
})
} else {
msg.Rcode = dns.RcodeNameError
// Inject fake SOA into the Authority section for negative caching
msg.Ns = []dns.RR{&dns.SOA{
Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: syntheticTTL},
Ns: "ns.sdproxy.",
Mbox: "hostmaster.sdproxy.",
Serial: 1,
Refresh: 3600,
Retry: 600,
Expire: 86400,
Minttl: syntheticTTL,
}}
}
} else {
// Standard RCODE
msg.Rcode = action
// For NXDOMAIN (RcodeNameError), inject a fake SOA into the Authority section.
// This ensures stub resolvers cache the negative response for syntheticTTL
// seconds (RFC 2308 §3).
if action == dns.RcodeNameError {
msg.Ns = []dns.RR{&dns.SOA{
Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: syntheticTTL},
Ns: "ns.sdproxy.",
Mbox: "hostmaster.sdproxy.",
Serial: 1,
Refresh: 3600,
Retry: 600,
Expire: 86400,
Minttl: syntheticTTL,
}}
}
}
_ = w.WriteMsg(msg)
msgPool.Put(msg)
return false
}
// ---------------------------------------------------------------------------
// Domain-map walk
// ---------------------------------------------------------------------------
// domainPolicyMinLabels / domainPolicyMaxLabels bound the suffix walk for
// domainPolicy. Set by computeDomainLabelBounds() in main.go after the maps
// are fully populated.
var (
domainPolicyMinLabels = 1
domainPolicyMaxLabels = 128
domainRoutesMinLabels = 1
domainRoutesMaxLabels = 128
)
// countDomainLabels returns the number of dot-separated labels in s.
func countDomainLabels(s string) int {
if s == "" {
return 0
}
return strings.Count(s, ".") + 1
}
// walkDomainMaps performs a single label-by-label suffix walk over qname,
// checking domainPolicy and domainRoutes simultaneously in one pass.
//
// Pre-skip: leading labels are stripped until search depth ≤ max ceiling so
// sub-domain levels deeper than any configured entry are never probed.
// Floor: the walk stops before a bare TLD when no entry lives that shallow.
//
// For a pure eTLD+1 block-list (min=max=2) this results in exactly one map
// probe per query regardless of how many sub-domain labels the query has.
func walkDomainMaps(qname string) (policyAction int, policyBlocked bool, policyMatched string, routeUpstream string, routeBypassLocal bool, routeMatched bool) {
search := qname
labels := countDomainLabels(qname)
ceiling := domainPolicyMaxLabels
if domainRoutesMaxLabels > ceiling {
ceiling = domainRoutesMaxLabels
}
for labels > ceiling {
idx := strings.IndexByte(search, '.')
if idx < 0 {
break
}
search = search[idx+1:]
labels--
}
for {
if hasDomainPolicy && !policyBlocked {
if action, ok := domainPolicy[search]; ok {
policyAction = action
policyBlocked = true
policyMatched = search
}
}
if hasDomainRoutes && !routeMatched {
if entry, ok := domainRoutes[search]; ok {
routeUpstream = entry.upstream
routeBypassLocal = entry.bypassLocal
routeMatched = true
}
}
if policyBlocked && routeMatched {
return
}
idx := strings.IndexByte(search, '.')
if idx < 0 {
break
}
search = search[idx+1:]
labels--
policyDone := !hasDomainPolicy || policyBlocked || labels < domainPolicyMinLabels
routesDone := !hasDomainRoutes || routeMatched || labels < domainRoutesMinLabels
if policyDone && routesDone {
break
}
}
return
}
// ---------------------------------------------------------------------------
// Route index helper
// ---------------------------------------------------------------------------
// getRouteIdx returns the uint8 route index for the named upstream group.
// Falls back to routeIdxDefault when the name is not in the map.
// routeIdxDefault and routeIdxMap are declared in globals.go.
func getRouteIdx(name string) uint8 {
if idx, ok := routeIdxByName[name]; ok {
return idx
}
return routeIdxDefault
}
// ---------------------------------------------------------------------------
// Domain label bounds (populated by main.computeDomainLabelBounds)
// ---------------------------------------------------------------------------
// minDomainLabels, maxDomainLabels, hasDomainPolicy, hasDomainRoutes,
// rtypePolicy, domainPolicy, hasRtypePolicy, and blockUnknownQtypes are all
// declared in globals.go — do not redeclare here.
// ---------------------------------------------------------------------------
// Name normalisation & extraction
// ---------------------------------------------------------------------------
// lowerTrimDot returns s lowercased with any trailing dot removed.
// Zero allocations when the input is already lowercase.
func lowerTrimDot(s string) string {
clean := true
for i := 0; i < len(s); i++ {
if c := s[i]; c >= 'A' && c <= 'Z' {
clean = false
break
}
}
if clean {
return strings.TrimSuffix(s, ".")
}
b := []byte(s)
for i, c := range b {
if c >= 'A' && c <= 'Z' {
b[i] = c + 32
}
}
return strings.TrimSuffix(string(b), ".")
}
// isValidReversePTR reports whether name is a well-formed reverse-lookup
// PTR label (in-addr.arpa or ip6.arpa).
func isValidReversePTR(name string) bool {
return strings.HasSuffix(name, ".in-addr.arpa") ||
strings.HasSuffix(name, ".ip6.arpa")
}
// extractIPFromPTR parses an in-addr.arpa or ip6.arpa reverse-lookup name
// and returns the underlying IP address as a string. Returns "" if invalid.
// Expects a lowercase, dot-trimmed qname.
func extractIPFromPTR(name string) string {
if strings.HasSuffix(name, ".in-addr.arpa") {
p := strings.TrimSuffix(name, ".in-addr.arpa")
parts := strings.Split(p, ".")
if len(parts) == 4 {
return parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0]
}
} else if strings.HasSuffix(name, ".ip6.arpa") {
p := strings.TrimSuffix(name, ".ip6.arpa")
parts := strings.Split(p, ".")
if len(parts) == 32 {
var sb strings.Builder
sb.Grow(39) // 32 hex chars + 7 colons
for i := 31; i >= 0; i-- {
if len(parts[i]) != 1 {
return "" // Safety guard against misformed segments
}
sb.WriteString(parts[i])
if i%4 == 0 && i != 0 {
sb.WriteByte(':')
}
}
if addr, err := netip.ParseAddr(sb.String()); err == nil {
return addr.String() // Compresses it securely
}
}
}
return ""
}
// ---------------------------------------------------------------------------
// TTL capping
// ---------------------------------------------------------------------------
// CapResponseTTL sets the TTL of every RR in msg (Answer, Ns, Extra) to
// min(rr.Ttl, cap). Used by the parental control path to enforce a heartbeat
// TTL on categorised domains so TTL-compliant clients re-query frequently.
// OPT records (EDNS0) carry flags, not a TTL — always skipped.
func CapResponseTTL(msg *dns.Msg, cap uint32) {
for _, rr := range msg.Answer {
if rr.Header().Ttl > cap {
rr.Header().Ttl = cap
}
}
for _, rr := range msg.Ns {
if rr.Header().Ttl > cap {
rr.Header().Ttl = cap
}
}
for _, rr := range msg.Extra {
if rr.Header().Rrtype != dns.TypeOPT && rr.Header().Ttl > cap {
rr.Header().Ttl = cap
}
}
}