-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprocess_helpers.go
More file actions
254 lines (217 loc) · 8.43 KB
/
process_helpers.go
File metadata and controls
254 lines (217 loc) · 8.43 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
/*
File: process_helpers.go
Version: 1.8.0
Updated: 11-May-2026 14:31 CEST
Description:
Synchronization pools, string builders, and high-performance global
utilities for the sdproxy DNS processing pipeline.
Extracted from process.go to isolate memory pools and string manipulation
away from the primary hot-path logic.
Changes:
1.8.0 - [REFACTOR] Introduced global, zero-allocation DNS and IP utility helpers
(`SetNegativeSOA`, `PreserveEDNS0`, `RcodeStr`, and `ParsePrefixUnmapped`).
Consolidates protocol compliance and network mapping logic, eliminating
severe code duplication natively across 15+ sub-systems.
1.7.0 - [SECURITY/FIX] Resolved a severe cache coalescing vulnerability within
`buildSFKey`. The SingleFlight execution group now strictly incorporates
`DoBit` (DNSSEC OK) and `CdBit` (Checking Disabled) flags into the hashing
signature. This securely neutralizes a regression where non-validating clients
could accidentally hijack and corrupt DNSSEC payload responses for strict resolvers.
1.6.0 - [LOGGING] Fixed a telemetry regression where `cleanUpstreamHost` inadvertently
stripped the `+ECH` protocol marker from upstream connection logs. The helper
now natively detects and prepends `[ECH]` to the output string to ensure
Encrypted Client Hello statuses are visible in the Web UI and console.
1.5.0 - [FIX] Expanded `buildSFKey` buffer capacity and bitwise shifting
to accommodate the new uint16 route index structure seamlessly,
resolving silent routing overflows on extreme configurations.
1.4.0 - [LOGGING] Suppressed `[UNKNOWN-ASN]` tags for private, loopback, and link-local IP addresses in telemetry.
1.3.0 - [LOGGING] Appended `[UNKNOWN-ASN]` to the buildClientID builder for
private/LAN IPs that cannot be mapped to the IPinfo public databases.
*/
package main
import (
"fmt"
"net"
"net/netip"
"strings"
"sync"
"sync/atomic"
"github.com/miekg/dns"
"golang.org/x/sync/singleflight"
)
// ---------------------------------------------------------------------------
// Global Synchronization Pools & Trackers
// ---------------------------------------------------------------------------
// clientIDPool reuses string builders for generating Client ID log lines,
// ensuring zero-allocation string concatenations on the hot path.
var clientIDPool = sync.Pool{New: func() any { return new(strings.Builder) }}
// sfGroup deduplicates identical concurrent upstream queries (Thundering Herd prevention).
var sfGroup singleflight.Group
// sfResult is the internal payload passed back by the singleflight execution group.
type sfResult struct {
msg *dns.Msg
addr string
}
// coalescedTotal tracks how many redundant upstream queries were successfully
// suppressed by the singleflight group.
var coalescedTotal atomic.Int64
// revalSem bounds the maximum number of background cache-revalidation routines
// that can execute simultaneously to prevent goroutine explosion.
const revalSemCap = 32
var revalSem = make(chan struct{}, revalSemCap)
// msgPool provides highly-recyclable dns.Msg structures to heavily reduce
// Garbage Collection (GC) pressure during intense query floods.
var msgPool = sync.Pool{New: func() any { return new(dns.Msg) }}
// ---------------------------------------------------------------------------
// Key Builders & Formatters
// ---------------------------------------------------------------------------
// buildClientID generates the descriptive client identity string used throughout
// the logging architecture (e.g., "192.168.1.10 (alice-ipad)").
func buildClientID(ip, name string, addr netip.Addr) string {
if name == "" && !logASNDetails {
return ip
}
sb := clientIDPool.Get().(*strings.Builder)
sb.Reset()
sb.WriteString(ip)
if name != "" {
sb.WriteString(" (" + name + ")")
}
if logASNDetails {
asn, asnName, asnCountry := LookupASNDetails(addr)
if asn != "" {
sb.WriteString(" [")
sb.WriteString(asn)
if asnName != "" {
sb.WriteString(" ")
sb.WriteString(asnName)
}
if asnCountry != "" {
sb.WriteString(", ")
sb.WriteString(asnCountry)
}
sb.WriteString("]")
} else if addr.IsValid() && !addr.IsPrivate() && !addr.IsLoopback() && !addr.IsLinkLocalUnicast() {
sb.WriteString(" [UNKNOWN-ASN]")
}
}
s := sb.String()
clientIDPool.Put(sb)
return s
}
// buildSFKey constructs a highly specific cache key for the SingleFlight
// execution group, ensuring only identical questions intended for the exact
// same upstream route index and DNSSEC constraints are coalesced.
// [PERF] Uses strings.Builder with exact capacity sizing for zero-allocation
// string conversion on return.
func buildSFKey(name string, qtype uint16, routeIdx uint16, doBit bool, cdBit bool, clientName string) string {
var sb strings.Builder
// Pre-allocate exact buffer size: name length + 6 control bytes + clientName length
// (1 for name terminator, 2 for qtype, 2 for uint16 routeIdx, 1 for flags).
capSize := len(name) + 6
if clientName != "" {
capSize += 1 + len(clientName)
}
sb.Grow(capSize)
sb.WriteString(name)
sb.WriteByte(0)
sb.WriteByte(byte(qtype >> 8))
sb.WriteByte(byte(qtype))
sb.WriteByte(byte(routeIdx >> 8))
sb.WriteByte(byte(routeIdx))
// Pack cryptographic constraints into a single byte payload to prevent execution drift
var flags byte
if doBit {
flags |= 1
}
if cdBit {
flags |= 2
}
sb.WriteByte(flags)
if clientName != "" {
sb.WriteByte(0)
sb.WriteString(clientName)
}
return sb.String()
}
// cleanUpstreamHost extracts a clean "Hostname (IP)" or just "IP" from the
// upstream connection log, stripping redundant schemas or HTTP path data
// while preserving the ECH status indicator if successfully negotiated.
func cleanUpstreamHost(s string) string {
if s == "" {
return ""
}
echMarker := ""
if strings.Contains(s, "+ECH://") {
echMarker = "[ECH] "
}
// Remove scheme "proto://"
if idx := strings.Index(s, "://"); idx >= 0 {
s = s[idx+3:]
}
parts := strings.SplitN(s, " (", 2)
hostPart := parts[0]
// Remove path or query strings (e.g., HTTP paths)
if slashIdx := strings.IndexByte(hostPart, '/'); slashIdx >= 0 {
hostPart = hostPart[:slashIdx]
}
if len(parts) > 1 {
ipPart := parts[1]
ipPart = strings.TrimSuffix(ipPart, ")")
// Strip port from IP
if host, _, err := net.SplitHostPort(ipPart); err == nil {
ipPart = host
}
return echMarker + hostPart + " (" + ipPart + ")"
}
// Strip port if it's just a raw host/IP
if host, _, err := net.SplitHostPort(hostPart); err == nil {
hostPart = host
}
return echMarker + hostPart
}
// ---------------------------------------------------------------------------
// DNS Message & IP Utilities
// ---------------------------------------------------------------------------
// SetNegativeSOA natively synthesizes an SOA record for negative caching proofs (RFC 2308).
// Binds strictly to the requested QNAME to prevent stub resolvers from aggressively
// retrying missing or intercepted records.
func SetNegativeSOA(msg *dns.Msg, name string, ttl uint32) {
msg.Ns = []dns.RR{&dns.SOA{
Hdr: dns.RR_Header{Name: name, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: ttl},
Ns: "ns.sdproxy.", Mbox: "hostmaster.sdproxy.",
Serial: 1, Refresh: 3600, Retry: 600, Expire: 86400, Minttl: ttl,
}}
}
// PreserveEDNS0 extracts and deeply clones the client's EDNS0 payload natively.
// Crucial for satisfying RFC 6891 requirements; strict resolvers often reject
// synthesized block responses if their initial OPT limits are ignored.
func PreserveEDNS0(req *dns.Msg, resp *dns.Msg) {
if opt := req.IsEdns0(); opt != nil {
resp.Extra = append(resp.Extra, dns.Copy(opt))
}
}
// RcodeStr returns a string representation of a DNS return code dynamically.
func RcodeStr(rcode int) string {
if str, ok := dns.RcodeToString[rcode]; ok {
return str
}
return fmt.Sprintf("RCODE:%d", rcode)
}
// ParsePrefixUnmapped parses a CIDR string and structurally unmaps IPv4-in-IPv6 boundaries natively.
// Eliminates an evasion vector where malicious clients attempt to bypass IPv4 ACLs
// and Domain blocks by shrouding payloads in IPv6 translation mechanics.
func ParsePrefixUnmapped(s string) (netip.Prefix, error) {
prefix, err := netip.ParsePrefix(s)
if err != nil {
return prefix, err
}
if prefix.Addr().Is4In6() {
bits := prefix.Bits() - 96
if bits < 0 {
bits = 0
}
prefix = netip.PrefixFrom(prefix.Addr().Unmap(), bits)
}
return prefix, nil
}