-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathupstream_ddr.go
More file actions
374 lines (330 loc) · 12.1 KB
/
upstream_ddr.go
File metadata and controls
374 lines (330 loc) · 12.1 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
File: upstream_ddr.go
Version: 2.42.0
Updated: 11-May-2026 14:12 CEST
Description:
Discovery of Designated Resolvers (DDR), Encrypted Client Hello (ECH), and
Application-Layer Protocol Negotiation (ALPN) extraction mechanics. Interrogates
upstream resolvers directly to autonomously secure encrypted TLS channels,
map topological dependencies, and upgrade transports natively.
Extracted from upstream.go to isolate network probing and bootstrap capabilities
away from the primary structural configurations.
Changes:
2.42.0 - [REFACTOR] Unified redundant `limitReader` HTTP payload extraction
logic for `doh` and `doh3` DDR probes natively, optimizing stream
verification securely.
2.41.0 - [LOGGING] Confined detailed Discovery traces seamlessly into the
`logDDR` evaluation bound dynamically.
2.40.0 - [SECURITY/FIX] Addressed ECS (EDNS0 Client Subnet) leakage vulnerabilities
during bootstrap querying natively. Discovery packets are now strictly
isolated from localized subnets by seeding `prepareForwardQuery` with null
`netip.Addr` architectures, guaranteeing payload purity organically.
*/
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/netip"
"strings"
"time"
"github.com/miekg/dns"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
)
// ---------------------------------------------------------------------------
// SVCB / DDR Upstream Probing
// ---------------------------------------------------------------------------
// readDDRPayload cleanly extracts and unpacks the upstream HTTP payload securely natively.
func readDDRPayload(body io.ReadCloser) (*dns.Msg, error) {
// [SECURITY/FIX] CWE-400 Memory Exhaustion Prevention
// Prevent malicious upstreams from flooding the router RAM via infinite streams natively
limitReader := io.LimitReader(body, 65536 + 1)
bodyBytes, _ := io.ReadAll(limitReader)
if len(bodyBytes) > 65536 {
return nil, fmt.Errorf("security constraint: DDR payload exceeded 64KB maximum buffer capacity")
}
resp := new(dns.Msg)
return resp, resp.Unpack(bodyBytes)
}
// fetchDDRParams performs a one-off Discovery of Designated Resolvers (DDR) query
// directly against the upstream using its native encrypted protocol (DoT, DoH, DoQ).
// It requests _dns.resolver.arpa (SVCB) to extract ECH keys and ALPN parameters dynamically.
// Validates target constraints according to the cfg.Server.HostnameECH strictness setting natively.
func fetchDDRParams(u *Upstream, expectedHost string) ([]byte, bool) {
// [SECURITY/FIX] Expand global timeout envelope to guarantee all targets have time
// to successfully iterate natively before abrupt termination.
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if logDDR {
log.Printf("[DDR] Initiating extended bootstrap for upstream %s via %s", expectedHost, u.Proto)
}
req := new(dns.Msg)
req.SetQuestion("_dns.resolver.arpa.", dns.TypeSVCB)
req.RecursionDesired = true
opt := &dns.OPT{
Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT, Class: dns.ClassINET},
}
opt.SetUDPSize(4096)
req.Extra = append(req.Extra, opt)
// Suppress ECS mappings forcefully during external bootstrap probes
fwd := prepareForwardQuery(req, true, nil, netip.Addr{})
var resp *dns.Msg
var err error
targetURL := u.RawURL
if u.hasClientNameTemplate {
targetURL = strings.ReplaceAll(targetURL, "{client-name}", "bootstrap")
expectedHost = strings.ReplaceAll(expectedHost, "{client-name}", "bootstrap")
}
var targets []string
if len(u.dialAddrs) > 0 {
targets = append(targets, u.dialAddrs...)
} else if len(u.BootstrapIPs) > 0 {
_, port := parseHostPort(u.RawURL, u.Proto)
for _, ip := range u.BootstrapIPs {
targets = append(targets, net.JoinHostPort(ip, port))
}
} else {
_, port := parseHostPort(u.RawURL, u.Proto)
targets = []string{net.JoinHostPort(expectedHost, port)}
}
if logDDR {
log.Printf("[DDR] Executing _dns.resolver.arpa SVCB query against %s using native protocol %s", expectedHost, u.Proto)
}
// Isolate the DDR fetch to completely ephemeral transports.
// Iterate through all identified target boundaries until successful.
for _, dialAddr := range targets {
err = nil
resp = nil
// [SECURITY/FIX] Dynamically inject strict boundary contexts per dial
// to ensure tarpitted connections do not instantly sever parallel targets.
dialCtx, dialCancel := context.WithTimeout(ctx, 5*time.Second)
switch u.Proto {
case "dot":
tlsConf := getHardenedTLSConfig()
tlsConf.ServerName = expectedHost
tlsConf.NextProtos = []string{"dot"}
var conn *dns.Conn
conn, err = dns.DialTimeoutWithTLS("tcp-tls", dialAddr, tlsConf, 5*time.Second)
if err == nil {
if err = conn.WriteMsg(fwd); err == nil {
resp, err = conn.ReadMsg()
}
conn.Close()
}
case "doh":
tlsConf := getHardenedTLSConfig()
tlsConf.ServerName = expectedHost
tr := &http.Transport{
TLSClientConfig: tlsConf,
ForceAttemptHTTP2: true,
// [SECURITY/FIX] Explicitly disable keep-alives since this is a one-shot probe.
// This natively prevents ephemeral Go network pollers from leaking idle sockets globally.
DisableKeepAlives: true,
}
dialer := &net.Dialer{Timeout: 3 * time.Second}
tr.DialContext = func(dCtx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(dCtx, network, dialAddr)
}
client := &http.Client{Timeout: 5 * time.Second, Transport: tr}
buf, _ := fwd.Pack()
hReq, reqErr := http.NewRequestWithContext(dialCtx, http.MethodPost, targetURL, bytes.NewReader(buf))
if reqErr != nil {
err = reqErr
dialCancel()
continue
}
hReq.Header.Set("Content-Type", "application/dns-message")
hReq.Header.Set("Accept", "application/dns-message")
var httpResp *http.Response
httpResp, err = client.Do(hReq)
if err == nil {
if httpResp.StatusCode == http.StatusOK {
resp, err = readDDRPayload(httpResp.Body)
} else {
err = fmt.Errorf("http status %d", httpResp.StatusCode)
}
httpResp.Body.Close()
}
case "doh3":
tlsConf := getHardenedTLSConfig()
tlsConf.ServerName = expectedHost
tr := &http3.Transport{
TLSClientConfig: tlsConf,
QUICConfig: &quic.Config{
HandshakeIdleTimeout: 3 * time.Second,
},
Dial: func(dCtx context.Context, addr string, tlsCfg *tls.Config, qCfg *quic.Config) (*quic.Conn, error) {
return quic.DialAddrEarly(dCtx, dialAddr, tlsCfg, qCfg)
},
}
client := &http.Client{Timeout: 5 * time.Second, Transport: tr}
buf, _ := fwd.Pack()
hReq, reqErr := http.NewRequestWithContext(dialCtx, http.MethodPost, targetURL, bytes.NewReader(buf))
if reqErr != nil {
err = reqErr
tr.Close() // [SECURITY/FIX] Clean up HTTP/3 transport
dialCancel()
continue
}
hReq.Header.Set("Content-Type", "application/dns-message")
hReq.Header.Set("Accept", "application/dns-message")
var httpResp *http.Response
httpResp, err = client.Do(hReq)
if err == nil {
if httpResp.StatusCode == http.StatusOK {
resp, err = readDDRPayload(httpResp.Body)
} else {
err = fmt.Errorf("http status %d", httpResp.StatusCode)
}
httpResp.Body.Close()
}
// [SECURITY/FIX] Explicitly terminate underlying QUIC connections
// natively bounding UDP socket allocations safely on the hot path.
tr.Close()
case "doq":
tlsConf := getHardenedTLSConfig()
tlsConf.ServerName = expectedHost
tlsConf.NextProtos = []string{"doq"}
var conn *quic.Conn
conn, err = quic.DialAddrEarly(dialCtx, dialAddr, tlsConf, &quic.Config{})
if err == nil {
var stream *quic.Stream
stream, err = conn.OpenStreamSync(dialCtx)
if err == nil {
buf, _ := fwd.Pack()
lenBuf := make([]byte, 2)
binary.BigEndian.PutUint16(lenBuf, uint16(len(buf)))
stream.Write(lenBuf)
stream.Write(buf)
stream.Close() // Send FIN to prevent strict QUIC servers from stalling
if _, readErr := io.ReadFull(stream, lenBuf); readErr == nil {
respLen := binary.BigEndian.Uint16(lenBuf)
if respLen > 0 {
respBuf := make([]byte, respLen)
// [SECURITY/FIX] Catch ignored ReadFull payload errors to prevent
// unpacking poisoned or incomplete zero-byte arrays natively.
if _, rErr := io.ReadFull(stream, respBuf); rErr == nil {
resp = new(dns.Msg)
err = resp.Unpack(respBuf)
} else {
err = fmt.Errorf("read payload: %v", rErr)
}
} else {
err = errors.New("zero length response")
}
} else {
err = fmt.Errorf("read length: %v", readErr)
}
}
conn.CloseWithError(0, "ddr complete")
}
}
dialCancel() // Terminate inner ephemeral context
if err == nil && resp != nil {
break
}
}
if err != nil {
if logDDR {
log.Printf("[DDR] Failed to query upstream %s for DDR parameters: %v", expectedHost, err)
}
return nil, false
}
if resp == nil {
if logDDR {
log.Printf("[DDR] Received empty response from upstream %s", expectedHost)
}
return nil, false
}
if logDDR {
log.Printf("[DDR] Received response (RCODE: %s) with %d Answer records from %s", dns.RcodeToString[resp.Rcode], len(resp.Answer), expectedHost)
}
expectedHostFqdn := dns.Fqdn(expectedHost)
// Deep-inspect the answer payload for structural DDR parameters.
for _, rr := range resp.Answer {
if svcb, ok := rr.(*dns.SVCB); ok {
if logDDR {
log.Printf("[DDR] Found SVCB record for Target: %s (Expected: %s)", svcb.Target, expectedHostFqdn)
}
// Validate target constraints natively against strict/loose/apex/any mode
isMatch := false
targetClean := strings.TrimSuffix(svcb.Target, ".")
expectedClean := strings.TrimSuffix(expectedHostFqdn, ".")
switch cfg.Server.HostnameECH {
case "any":
// [SECURITY] "any" universally accepts the returned SVCB target, including "."
// Use with caution as it bypasses strict hostname identity validation.
isMatch = true
case "apex":
// [SECURITY] "apex" validates that both the expected host and the discovered
// target share the exact same eTLD+1 domain boundary (e.g., dns.google and 8.8.8.8.dns.google).
// Safely permits "." as a valid fallback if the apex matched originally.
if svcb.Target == "." {
isMatch = true
} else {
targetApex, _ := extractETLDPlusOne(targetClean)
expectedApex, _ := extractETLDPlusOne(expectedClean)
if targetApex != "" && targetApex == expectedApex {
isMatch = true
}
}
case "loose":
// [SECURITY] "loose" accepts an exact hostname match or the standard "." fallback.
if svcb.Target == expectedHostFqdn || svcb.Target == "." {
isMatch = true
}
default: // "strict"
// [SECURITY] "strict" mandates an exact FQDN match. Fallback targets (".") are rejected.
if svcb.Target == expectedHostFqdn && svcb.Target != "." {
isMatch = true
}
}
if isMatch {
var extractedECH []byte
var supportsH3 bool
for _, v := range svcb.Value {
if e, ok := v.(*dns.SVCBECHConfig); ok {
extractedECH = e.ECH
}
if alpn, ok := v.(*dns.SVCBAlpn); ok {
for _, a := range alpn.Alpn {
if a == "h3" {
supportsH3 = true
}
}
}
}
if logDDR {
if len(extractedECH) > 0 {
log.Printf("[DDR] Successfully extracted ECH Config payload (%d bytes) for %s", len(extractedECH), expectedHost)
}
if supportsH3 {
log.Printf("[DDR] Successfully discovered HTTP/3 (ALPN: h3) support for %s", expectedHost)
}
}
if len(extractedECH) > 0 || supportsH3 {
return extractedECH, supportsH3
}
if logDDR {
log.Printf("[DDR] SVCB record matched target, but no useful parameters (ECH/ALPN) were found")
}
} else {
if logDDR {
log.Printf("[DDR] Skipping SVCB record: Target mismatch (Target: %s, Expected: %s, Mode: %s)", svcb.Target, expectedHostFqdn, cfg.Server.HostnameECH)
}
}
}
}
if logDDR {
log.Printf("[DDR] No valid ECH/ALPN configurations discovered for upstream %s", expectedHost)
}
return nil, false
}