-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver_init.go
More file actions
368 lines (324 loc) · 11.7 KB
/
Copy pathserver_init.go
File metadata and controls
368 lines (324 loc) · 11.7 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
/*
File: server_init.go
Version: 1.18.0 (Split)
Updated: 06-Jun-2026 11:40 CEST
Description:
Listener initialization and OS binding orchestration.
Extracted from server.go to cleanly separate the setup of network listeners
(UDP, TCP, TLS, DoH, DoQ) from the runtime protocol payload handlers.
Changes:
1.18.0 - [FEAT] Registered `/.well-known/origin-svcb` L7 discovery endpoint natively
for DoH and DoH3 listeners to comply with `draft-ietf-tls-wkech-11`.
Seamlessly generates compliant JSON payloads mapping active ECH configurations organically.
1.17.0 - [FEAT] Registered `/.well-known/ech` L7 discovery endpoint natively
for DoH and DoH3 encrypted listeners. Allows clients to bypass DNS
tampering and fetch the router's `ECHConfigList` directly over HTTPS.
1.16.0 - [SECURITY/FIX] Resolved a severe concurrency discrepancy dynamically.
Shifted the atomic `activeDoQConns` counter inherently inside the
Listener iteration loop natively. Ensures that DoQ protocol bounds
safely respect precise per-listener connection limits exactly like
their `netutil.LimitListener` TCP/DoT equivalents.
1.15.0 - [BUG/FIX] Resolved a compilation error natively within the DoQ listener loop.
Eliminated an invalid interface type assertion since `quic.Conn` is inherently
a concrete pointer structure, bypassing the assertion bounds seamlessly.
1.14.0 - [SECURITY/FIX] Addressed a severe Resource Exhaustion (DoS) vulnerability
within the DoQ (DNS-over-QUIC) listener loop natively. Deployed a strict
atomic admission gate to enforce `MaxTCPConnections` limits against QUIC
transports, matching TCP/DoT/DoH parity. Prevents malicious actors from
spamming unfulfilled handshakes to permanently exhaust the router's
file descriptors and memory capacity.
*/
package main
import (
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"log"
"net"
"net/http"
"net/netip"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/miekg/dns"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"golang.org/x/net/netutil"
)
var (
shutdownCh = make(chan struct{})
shutdownOnce sync.Once
)
// Shutdown cleanly signals all active listeners and pools to terminate.
func Shutdown() {
shutdownOnce.Do(func() {
close(shutdownCh)
})
}
// filterListeners returns a subset of addresses that match the global support_ip_version.
func filterListeners(addrs []string) []string {
if ipVersionSupport == "both" {
return addrs
}
var out []string
for _, a := range addrs {
host, _, err := net.SplitHostPort(a)
if err != nil {
host = a
}
if addr, err := netip.ParseAddr(host); err == nil {
if ipVersionSupport == "ipv4" && !addr.Is4() {
if logSystem {
log.Printf("[LISTEN] Skipping %s: support_ip_version is 'ipv4' only", a)
}
continue
}
if ipVersionSupport == "ipv6" && !addr.Is6() {
if logSystem {
log.Printf("[LISTEN] Skipping %s: support_ip_version is 'ipv6' only", a)
}
continue
}
}
out = append(out, a)
}
return out
}
// StartServers spins up all configured DNS protocol listeners independently.
// This function establishes the underlying net.Listeners and maps them to
// their appropriate protocol payload handlers inside server.go.
func StartServers(tlsConf *tls.Config) {
// Extract MaxTCPConnections to protect against FD exhaustion natively
maxTCP := cfg.Server.MaxTCPConnections
if maxTCP <= 0 {
maxTCP = 250 // Conservative default for tiny routers
}
tcpReadTimeout := 5 * time.Second
// Dynamically calculate WriteTimeout based on Upstream execution deadlines
// to prevent terminating the socket prematurely on cache-misses.
var tcpWriteTimeout time.Duration
if cfg.Server.UpstreamTimeoutMs > 0 {
tcpWriteTimeout = time.Duration(cfg.Server.UpstreamTimeoutMs)*time.Millisecond + (2 * time.Second)
} else {
tcpWriteTimeout = 30 * time.Second // Robust default for unbounded upstream dials
}
tcpIdleTimeout := 15 * time.Second
// 1. Classic UDP (Dispatches to Linux SO_REUSEPORT or fallback workers)
startUDPServers(filterListeners(cfg.Server.ListenUDP), cfg.Server.UDPWorkers)
// 2. DNS over TCP
for _, addr := range filterListeners(cfg.Server.ListenTCP) {
addr := addr
go func() {
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("[FATAL] TCP listen failed on %s: %v", addr, err)
}
// Apply LimitListener to cap concurrent TCP sessions natively
l = netutil.LimitListener(l, maxTCP)
server := &dns.Server{
Listener: l,
Handler: dns.HandlerFunc(handleTCP),
ReadTimeout: tcpReadTimeout,
WriteTimeout: tcpWriteTimeout,
}
if logSystem {
log.Printf("[LISTEN] TCP on %s (Max Conns: %d)", addr, maxTCP)
}
if err := server.ActivateAndServe(); err != nil {
log.Fatalf("[FATAL] TCP failed on %s: %v", addr, err)
}
}()
}
// 3. DNS over TLS (DoT)
for _, addr := range filterListeners(cfg.Server.ListenDoT) {
addr := addr
go func() {
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("[FATAL] DoT listen failed on %s: %v", addr, err)
}
// Apply LimitListener to cap concurrent DoT sessions natively
l = netutil.LimitListener(l, maxTCP)
tlsL := tls.NewListener(l, tlsConf)
server := &dns.Server{
Listener: tlsL,
Handler: dns.HandlerFunc(handleDoT),
ReadTimeout: tcpReadTimeout,
WriteTimeout: tcpWriteTimeout,
}
if logSystem {
log.Printf("[LISTEN] DoT on %s (Max Conns: %d)", addr, maxTCP)
}
if err := server.ActivateAndServe(); err != nil {
log.Fatalf("[FATAL] DoT failed on %s: %v", addr, err)
}
}()
}
// 4. DNS over HTTPS (DoH/HTTP1.1 + HTTP/2) + DNS over HTTP/3 (DoH3/QUIC)
for _, addr := range filterListeners(cfg.Server.ListenDoH) {
addr := addr
mux := http.NewServeMux()
altSvc := buildAltSvc(addr)
mux.HandleFunc("/dns-query", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Alt-Svc", altSvc)
handleDoH(w, r)
})
// [FEAT] Serve ECHConfigList via Well-Known URI natively (L7 Discovery - draft-ietf-tls-wkech-11)
// Provides the standard JSON format containing Encrypted Client Hello keys dynamically.
mux.HandleFunc("/.well-known/origin-svcb", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Alt-Svc", altSvc)
if len(ddrECHConfig) > 0 {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "public, max-age=86400")
// Encode ECH config to base64 for the JSON response
b64Ech := base64.StdEncoding.EncodeToString(ddrECHConfig)
jsonPayload := fmt.Sprintf(`{"endpoints":[{"ech":"%s"}]}`, b64Ech)
w.Write([]byte(jsonPayload))
} else {
http.Error(w, "Not Found", http.StatusNotFound)
}
})
// [FEAT] Serve ECHConfigList via Well-Known URI natively (Legacy L7 Discovery)
// Protects ECH parameter distribution from DNS-layer manipulation natively.
mux.HandleFunc("/.well-known/ech", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Alt-Svc", altSvc)
if len(ddrECHConfig) > 0 {
w.Header().Set("Content-Type", "application/echconfig-list")
w.Header().Set("Cache-Control", "public, max-age=86400")
w.Write(ddrECHConfig)
} else {
http.Error(w, "Not Found", http.StatusNotFound)
}
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Alt-Svc", altSvc)
// Always treat any request that accepts DNS Message structure as DoH
// Uses strings.Contains to absorb complex headers securely without failing
accept := r.Header.Get("Accept")
contentType := r.Header.Get("Content-Type")
if strings.Contains(accept, "application/dns-message") ||
strings.Contains(contentType, "application/dns-message") ||
r.URL.Query().Get("dns") != "" {
handleDoH(w, r)
return
}
if WebUIMux != nil {
WebUIMux.ServeHTTP(w, r)
} else {
http.Error(w, "Not Found", http.StatusNotFound)
}
})
dohTLS := tlsConf.Clone()
dohTLS.NextProtos = []string{"h2", "http/1.1"}
h2Server := &http.Server{
Handler: mux,
ReadTimeout: tcpReadTimeout,
ReadHeaderTimeout: 3 * time.Second, // Hardened against Slowloris attacks
WriteTimeout: tcpWriteTimeout, // [SECURITY/FIX] Re-enabled to prevent Slow-Read DoS
IdleTimeout: tcpIdleTimeout,
MaxHeaderBytes: 8192,
ErrorLog: log.New(io.Discard, "", 0), // Suppress scanner/handshake EOF spam natively
}
go func() {
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("[FATAL] DoH listen failed on %s: %v", addr, err)
}
// Apply LimitListener to cap concurrent DoH sessions natively
l = netutil.LimitListener(l, maxTCP)
tlsL := tls.NewListener(l, dohTLS)
if logSystem {
log.Printf("[LISTEN] DoH (HTTP/1.1 + HTTP/2) on %s (Max Conns: %d)", addr, maxTCP)
if len(ddrECHConfig) > 0 {
log.Printf("[LISTEN] Registered /.well-known/origin-svcb & /.well-known/ech L7 discovery endpoints natively on %s", addr)
}
}
if err := h2Server.Serve(tlsL); err != nil && err != http.ErrServerClosed {
log.Fatalf("[FATAL] DoH failed on %s: %v", addr, err)
}
}()
h3Server := &http3.Server{
Addr: addr,
Handler: mux,
TLSConfig: tlsConf,
QUICConfig: &quic.Config{
Allow0RTT: true,
MaxIdleTimeout: tcpIdleTimeout,
KeepAlivePeriod: 15 * time.Second, // [PERF/FIX] Prevent strict NAT timeouts natively
MaxIncomingStreams: 1000, // [PERFORMANCE] Raised from 50 to 1000 to support heavy multiplexing from modern browsers
},
}
go func() {
if logSystem {
log.Printf("[LISTEN] DoH3 (QUIC) on %s", addr)
}
if err := h3Server.ListenAndServe(); err != nil {
log.Fatalf("[FATAL] DoH3 failed on %s: %v", addr, err)
}
}()
}
// 5. DNS over QUIC (DoQ) — RFC 9250
for _, addr := range filterListeners(cfg.Server.ListenDoQ) {
addr := addr
go func() {
var activeDoQConns atomic.Int32
doqTLS := tlsConf.Clone()
doqTLS.NextProtos = []string{"doq"}
listener, err := quic.ListenAddr(addr, doqTLS, &quic.Config{
Allow0RTT: true,
MaxIdleTimeout: tcpIdleTimeout,
KeepAlivePeriod: 15 * time.Second,
MaxIncomingStreams: 1000,
})
if err != nil {
log.Fatalf("[FATAL] DoQ failed on %s: %v", addr, err)
}
if logSystem {
log.Printf("[LISTEN] DoQ on %s (Max Conns: %d)", addr, maxTCP)
}
// [SECURITY/FIX] Close the listener when Shutdown() fires so Accept()
// unblocks with a clean, expected error instead of this goroutine
// running forever and blocking process termination.
go func() {
<-shutdownCh
listener.Close()
}()
for {
conn, err := listener.Accept(context.Background())
if err != nil {
select {
case <-shutdownCh:
// Expected: listener was closed intentionally during shutdown.
return
default:
}
// [SECURITY/FIX] Persistent Accept() errors (e.g. FD exhaustion, a
// listener killed out-of-band) previously caused an unbounded
// busy-loop pinning a full CPU core at 100% — especially bad on
// the low-power routers this project targets. Back off instead.
if logSystem {
log.Printf("[DOQ] Accept error on %s: %v", addr, err)
}
time.Sleep(250 * time.Millisecond)
continue
}
if activeDoQConns.Add(1) > int32(maxTCP) {
activeDoQConns.Add(-1)
conn.CloseWithError(0x0, "server busy")
if logSystem {
log.Printf("[SECURITY] DoQ connection rejected on %s: Max Connections (%d) reached", addr, maxTCP)
}
continue
}
currentConn := conn
go func() {
defer activeDoQConns.Add(-1)
handleDoQConnection(currentConn)
}()
}
}()
}
}