-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprocess_exchange.go
More file actions
348 lines (302 loc) · 13 KB
/
process_exchange.go
File metadata and controls
348 lines (302 loc) · 13 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
File: process_exchange.go
Version: 2.42.0
Updated: 11-May-2026 14:31 CEST
Description:
Upstream Exchange and Payload Transformation for sdproxy.
Executes the final phase of the core processing pipeline natively:
- QNAME Label Bounds Constraint Inspection
- SingleFlight Connection Coalescing
- Answer Sorting & Payload Optimization
- Target Name Policy Inspection
- Response IP Filtering and Rebinding Defenses
- Buffer capacity & Telemetry execution
Extracted from process.go to promote advanced modularity.
Changes:
2.42.0 - [REFACTOR] Instantiated the `RcodeStr` helper to gracefully construct
logging parameters organically across the network dialect strings.
2.41.0 - [REFACTOR] Adopted the centralized `RecordBlockEvent` telemetry function,
ensuring cached upstream payloads accurately record analytics naturally.
2.40.0 - [SECURITY/FIX] Clarified the `QNAME Label Bounds` telemetry reason text.
If an oversized, natively spoofed alias target (e.g., `forcesafesearch...`)
violates upstream constraints on behalf of a standard user query, the
resulting block log natively appends the Target context organically.
Prevents administrative confusion over seemingly legal requests.
2.39.0 - [SECURITY] Incorporated the `QNAME Label Bounds` evaluation explicitly
into the upstream pipeline. Identifies and safely terminates malformed
or massive domain strings dynamically before executing exterior resolvers,
while robustly accommodating grouped exemptions natively (`ignore_qname_labels`).
*/
package main
import (
"fmt"
"log"
"net/netip"
"github.com/miekg/dns"
)
// executeUpstreamExchange performs the outbound network dial, validates the payload responses,
// executes modifications, and replies to the client natively.
func executeUpstreamExchange(
w dns.ResponseWriter, r *dns.Msg, q dns.Question, qNameTrimmed string,
doBit bool, originalID uint16, cacheKey DNSCacheKey,
routeName string, routeIdx uint16, routeOriginType string,
clientID, clientName, clientMAC, clientIP string, clientAddr netip.Addr,
protocol, sni, path string,
parentalForcedTTL uint32, parentalReason, parentalCategory, parentalMatchedApex string,
bypassPolicies bool,
originalQName, originalQNameTrimmed, spoofedAlias string,
) {
// ── 1. Upstream selection + pre-validation ────────────────────────────
group, exists := routeUpstreams[routeName]
if !exists || len(group.Servers) == 0 {
group = routeUpstreams["default"]
}
if group == nil || len(group.Servers) == 0 {
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE: %s (%s) | NO UPSTREAMS CONFIGURED",
protocol, clientID, originalQName, dns.TypeToString[q.Qtype],
routeName, routeOriginType)
dns.HandleFailed(w, r)
return
}
// ── 1.5 EDNS0 Client Subnet (ECS) Log Inspection ──────────────────────
var clientSentECS bool
if opt := r.IsEdns0(); opt != nil {
for _, o := range opt.Option {
if _, ok := o.(*dns.EDNS0_SUBNET); ok {
clientSentECS = true
break
}
}
}
ecsMark := ""
if group.ECSAction == "add" && clientAddr.IsValid() {
var m int
if clientAddr.Is4() {
m = group.ECSV4Mask
} else {
m = group.ECSV6Mask
}
ecsMark = fmt.Sprintf(" [ECS: ADD /%d]", m)
} else if group.ECSAction == "pass" && clientSentECS {
ecsMark = " [ECS: PASS]"
}
// ── 1.8 QNAME Label Bounds Validation ─────────────────────────────────
if !group.IgnoreQnameLabels {
labels := countDomainLabels(qNameTrimmed)
if labels < cfg.Server.QnameMinLabels || labels > cfg.Server.QnameMaxLabels {
IncrPolicyBlock()
// [SECURITY/FIX] Append the Target evaluation structure transparently
// if the bounds violation originated from a CNAME Spoofed Alias natively.
reason := fmt.Sprintf("QNAME Label Bounds (%d labels)", labels)
if originalQNameTrimmed != qNameTrimmed {
reason += fmt.Sprintf(" (Target: %s)", qNameTrimmed)
}
RecordBlockEvent(clientIP, originalQNameTrimmed, reason)
dropped := writePolicyAction(w, r, PolicyActionBlock)
if cacheSynthFlag && !dropped && globalBlockAction != BlockActionDrop {
synthMsg := buildSynthCacheMsg(q, PolicyActionBlock)
CacheSetSynth(cacheKey, synthMsg)
msgPool.Put(synthMsg) // [PERF] Zero-allocation memory recycling
}
if logQueries {
var actionLogStr string
if globalBlockAction == BlockActionLog {
actionLogStr = "LOG ONLY"
} else if globalBlockAction == BlockActionDrop {
actionLogStr = "DROP"
} else {
actionLogStr = getBlockActionLogStr(q.Qtype)
}
statusMark := "POLICY BLOCK"
if dropped {
statusMark = "POLICY DROP"
}
if spoofedAlias != "" {
statusMark = fmt.Sprintf("SPOOFED ALIAS (%s) | %s", spoofedAlias, statusMark)
}
log.Printf("[DNS] [%s] %s -> %s %s | %s (Label Bounds) | %s",
protocol, clientID, originalQName, dns.TypeToString[q.Qtype], statusMark, actionLogStr)
}
return
}
}
// ── 2. Upstream forwarding — coalesced via singleflight ───────────────
sfClientName := ""
if hasClientNameUpstream {
sfClientName = clientName
}
// Note: The RouteIdx inherently isolates Cache keys, so specific subnets
// utilizing distinct upstream groups will securely partition the cache seamlessly.
sfKey := buildSFKey(qNameTrimmed, q.Qtype, routeIdx, doBit, r.CheckingDisabled, sfClientName)
didUpstream := false
v, sfErr, shared := sfGroup.Do(sfKey, func() (any, error) {
didUpstream = true
IncrUpstreamCall()
ctx, cancel := newUpstreamCtx()
defer cancel()
// The active routing pipeline transmits the underlying subnet to intelligently populate ECS
msg, addr, err := group.Exchange(ctx, r, clientID, clientName, clientAddr)
if err != nil || msg == nil {
// [FEAT] Infinite Serve-Stale Fallback
// Intercept upstream outages and connection timeouts natively by
// probing the cache arrays for expired records as an absolute last resort.
if cfg.Cache.ServeStaleInfinite {
fallbackMsg := msgPool.Get().(*dns.Msg)
*fallbackMsg = dns.Msg{}
if CacheGetExpired(cacheKey, fallbackMsg) {
return sfResult{msg: fallbackMsg, addr: "stale-fallback"}, nil
}
msgPool.Put(fallbackMsg)
}
return sfResult{msg: msg, addr: addr}, err
}
isNeg := msg.Rcode == dns.RcodeNameError || (msg.Rcode == dns.RcodeSuccess && len(msg.Answer) == 0)
if !isNeg || cacheUpstreamNeg {
CacheSet(cacheKey, msg, routeName)
}
return sfResult{msg: msg, addr: addr}, nil
})
if shared && !didUpstream {
coalescedTotal.Add(1)
}
var finalResp *dns.Msg
var upstreamUsed string
if v != nil {
if res, ok := v.(sfResult); ok {
upstreamUsed = res.addr
if res.msg != nil && sfErr == nil {
if shared {
finalResp = res.msg.Copy()
} else {
finalResp = res.msg
}
}
}
}
// ── 3. Error Handle ───────────────────────────────────────────────────
if finalResp == nil {
if sfErr != nil && sfErr.Error() == "silent_drop" {
if logQueries {
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE: %s (%s) | CONSENSUS DROP | DROP",
protocol, clientID, originalQName, dns.TypeToString[q.Qtype],
routeName, routeOriginType)
}
return // Natively shed the load without responding
}
upstreamLog := ""
if upstreamUsed != "" {
upstreamLog = " | UPSTREAM: " + cleanUpstreamHost(upstreamUsed)
}
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE: %s (%s)%s | FAILED: %v",
protocol, clientID, originalQName, dns.TypeToString[q.Qtype],
routeName, routeOriginType, upstreamLog, sfErr)
dns.HandleFailed(w, r)
return
}
// ── 4. Answer Sorting ─────────────────────────────────────────────────
// MUST execute BEFORE any client-specific payload mutations (like TTL Caps
// or DNSSEC stripping) to prevent corrupting the global cache byte arrays.
if cfg.Cache.AnswerSort != "none" {
if applyAnswerSort(finalResp, cfg.Cache.AnswerSort) {
// [PERFORMANCE] Prevent severe CPU starvation and lock contention.
// 'random' sorting shuffles records ephemerally for the client.
// If 'shared' is true, this is a coalesced SingleFlight cache-miss.
// Only the primary worker executes CacheUpdateOrder to prevent parallel goroutines from thrashing.
if cfg.Cache.AnswerSort != "random" && !shared {
CacheUpdateOrder(cacheKey, finalResp)
}
}
}
// ── 5. Target Name Policy Check (Cache Miss) ──────────────────────────
if checkTargetNames(w, r, finalResp, clientMAC, clientIP, clientAddr, clientName, clientID, protocol, sni, path, bypassPolicies, originalQName) {
return
}
// ── 6. Response transforms ────────────────────────────────────────────
finalResp = transformResponse(finalResp, q.Qtype, doBit, true)
// ── 7. IP Filter Policy Check (Cache Miss) ────────────────────────────
if filterResponseIPs(w, r, finalResp, clientMAC, clientIP, clientAddr, clientName, clientID, protocol, sni, path, bypassPolicies, originalQName, originalQNameTrimmed) {
return
}
// ── 8. DNS Rebinding Protection (Cache Miss) ──────────────────────────
if filterRebinding(w, r, finalResp, clientIP, clientAddr, clientName, clientID, protocol, originalQName, originalQNameTrimmed) {
return
}
// ── 9. NULL-IP Detection (Pre-Truncation) ─────────────────────────────
// Evaluate NULL-IPs natively BEFORE UDP Fragmentation defense executes.
// This guarantees that artificially truncated payloads (where Answer == nil)
// do not silently evade telemetry trackers.
isNullIP := responseContainsNullIP(finalResp)
if isNullIP {
IncrPolicyBlock()
RecordBlockEvent(clientIP, originalQNameTrimmed, "Upstream NULL-IP ("+routeName+")")
}
// ── 10. UDP Amplification & Fragmentation Defense ──────────────────────
upstreamSize, clientAdvertised := enforceUDPDefenses(r, finalResp, protocol)
// ── 11. Final reply ───────────────────────────────────────────────────
if parentalForcedTTL > 0 {
CapResponseTTL(finalResp, parentalForcedTTL)
}
finalResp.Id = originalID
IncrReturnCode(finalResp.Rcode, isNullIP)
if finalResp.Rcode == dns.RcodeNameError {
IncrNXDomain(originalQNameTrimmed)
}
if upstreamUsed != "" {
IncrUpstreamHost(cleanUpstreamHost(upstreamUsed))
}
w.WriteMsg(finalResp)
// [MEMORY LIFECYCLE & GC]
// Note: `finalResp` is inherently generated via a network `Unpack()` allocation
// from the upstream dialer (or cloned during a SingleFlight coalescing event).
// It is intentionally NOT placed back into the `msgPool` to be safely garbage-collected.
// This natively prevents pool pollution from external, variable-sized network arrays
// and guarantees pristine baseline capacities for local synthetic messages.
if logQueries {
rcodeStr := RcodeStr(finalResp.Rcode)
if isNullIP {
rcodeStr += " (NULL-IP)"
}
var status string
switch {
case shared && !didUpstream:
status = "COALESCED | " + rcodeStr
case isNullIP:
status = rcodeStr + " (NULL-IP)"
case finalResp.Truncated:
status = fmt.Sprintf("TRUNCATED (TC=1, Upstream:%dB, Client:%dB) | %s", upstreamSize, clientAdvertised, rcodeStr)
}
if parentalReason == "FREE" {
if parentalCategory != "" {
status += fmt.Sprintf(" (PARENTAL FREE: %s, apex: %s)", parentalCategory, parentalMatchedApex)
} else {
status += " (PARENTAL FREE)"
}
} else if parentalReason == "ALLOW" {
if parentalCategory != "" {
status += fmt.Sprintf(" (PARENTAL ALLOW: %s, apex: %s)", parentalCategory, parentalMatchedApex)
} else {
status += " (PARENTAL ALLOW)"
}
} else if parentalReason == "LOG" {
if parentalCategory != "" {
status += fmt.Sprintf(" (PARENTAL LOG: %s, apex: %s)", parentalCategory, parentalMatchedApex)
} else {
status += " (PARENTAL LOG)"
}
} else if parentalCategory != "" {
status += fmt.Sprintf(" (CATEGORY: %s, apex: %s)", parentalCategory, parentalMatchedApex)
}
if upstreamUsed == "stale-fallback" {
status = "INFINITE STALE FALLBACK | " + status
}
if spoofedAlias != "" {
status = fmt.Sprintf("SPOOFED ALIAS (%s) | %s", spoofedAlias, status)
}
if ecsMark != "" {
status += ecsMark
}
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE: %s (%s) | UPSTREAM: %s (%s) | %s",
protocol, clientID, originalQName, dns.TypeToString[q.Qtype],
routeName, routeOriginType, upstreamUsed, routeName, status)
}
}