-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathdohclient.go
More file actions
446 lines (389 loc) · 11.9 KB
/
dohclient.go
File metadata and controls
446 lines (389 loc) · 11.9 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package rdns
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"time"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"log/slog"
"github.com/jtacoma/uritemplates"
"github.com/miekg/dns"
"golang.org/x/net/http2"
)
// defaultDoHIdleTimeout is the default idle connection timeout for DoH TCP transport.
const defaultDoHIdleTimeout = 30 * time.Second
// DoHClientOptions contains options used by the DNS-over-HTTP resolver.
type DoHClientOptions struct {
// Query method, either GET or POST. If empty, POST is used.
Method string
// Bootstrap address - IP to use for the service instead of looking up
// the service's hostname with potentially plain DNS.
BootstrapAddr string
// Transport protocol to run HTTPS over. "quic" or "tcp", defaults to "tcp".
Transport string
// Local IP to use for outbound connections. If nil, a local address is chosen.
LocalAddr net.IP
LocalAddrV4 net.IP
LocalAddrV6 net.IP
TLSConfig *tls.Config
QueryTimeout time.Duration
// IdleTimeout is the maximum amount of time an idle connection will remain
// open before being closed. For TCP transport, defaults to 30 seconds if not set.
// For QUIC transport, defaults to the quic-go library default if not set. Note
// that for QUIC, the actual timeout is the minimum of client and server values.
IdleTimeout time.Duration
// Optional dialer, e.g. proxy
Dialer Dialer
Use0RTT bool
// Linux network namespace for outbound connections.
NetNS *NetNS
// Linux socket options for fwmark and interface binding.
SocketOptions SocketOptions
}
// DoHClient is a DNS-over-HTTP resolver with support for HTTP/2.
type DoHClient struct {
id string
endpoint string
template *uritemplates.UriTemplate
client *http.Client
opt DoHClientOptions
metrics *ListenerMetrics
}
var _ Resolver = &DoHClient{}
func NewDoHClient(id, endpoint string, opt DoHClientOptions) (*DoHClient, error) {
// Validate options
if opt.IdleTimeout < 0 {
return nil, fmt.Errorf("idle-timeout must not be negative")
}
// Parse the URL template
template, err := uritemplates.Parse(endpoint)
if err != nil {
return nil, err
}
// Configure the HTTP Client and Transport based on connection options
var client *http.Client
switch opt.Transport {
case "tcp", "":
tr, err := dohTcpTransport(opt)
if err != nil {
return nil, err
}
client = &http.Client{Transport: tr}
case "quic":
tr, err := dohQuicTransport(endpoint, opt)
if err != nil {
return nil, err
}
client = &http.Client{Transport: tr}
default:
return nil, fmt.Errorf("unknown protocol: '%s'", opt.Transport)
}
if opt.Method == "" {
opt.Method = "POST"
}
if opt.Method != "POST" && opt.Method != "GET" {
return nil, fmt.Errorf("unsupported method '%s'", opt.Method)
}
if opt.QueryTimeout == 0 {
opt.QueryTimeout = defaultQueryTimeout
}
return &DoHClient{
id: id,
endpoint: endpoint,
template: template,
client: client,
opt: opt,
metrics: NewListenerMetrics("client", id),
}, nil
}
// Resolve a DNS query.
func (d *DoHClient) Resolve(q *dns.Msg, ci ClientInfo) (*dns.Msg, error) {
// Packing a message is not always a read-only operation, make a copy
q = q.Copy()
log := logger(d.id, q, ci)
log.Debug("querying upstream resolver",
slog.String("resolver", d.endpoint),
slog.String("protocol", "doh"),
slog.String("method", d.opt.Method),
)
// Add padding before sending the query over HTTPS
padQuery(q)
// Pack the DNS query into wire format
msg, err := q.Pack()
if err != nil {
d.metrics.err.Add("pack", 1)
return nil, err
}
d.metrics.query.Add(1)
ctx, cancel := context.WithTimeout(context.Background(), d.opt.QueryTimeout)
defer cancel()
// Build a DoH request and execute it
req, err := d.buildRequest(ctx, msg)
if err != nil {
return nil, err
}
resp, err := d.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Extract the DNS response from the HTTP response
return d.responseFromHTTP(resp)
}
func (d *DoHClient) buildRequest(ctx context.Context, msg []byte) (*http.Request, error) {
switch d.opt.Method {
case "POST":
return d.buildPostRequest(ctx, msg)
case "GET":
return d.buildGetRequest(ctx, msg)
default:
return nil, errors.New("unsupported method")
}
}
func (d *DoHClient) do(req *http.Request) (*http.Response, error) {
resp, err := d.client.Do(req)
if err != nil {
d.metrics.err.Add(req.Method, 1)
return nil, err
}
return resp, err
}
func (d *DoHClient) buildPostRequest(ctx context.Context, msg []byte) (*http.Request, error) {
// The URL could be a template. Process it without values since POST doesn't use variables in the URL.
u, err := d.template.Expand(map[string]any{})
if err != nil {
d.metrics.err.Add("template", 1)
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", u, bytes.NewReader(msg))
if err != nil {
d.metrics.err.Add("http", 1)
return nil, err
}
req.Header.Add("accept", "application/dns-message")
req.Header.Add("content-type", "application/dns-message")
return req, nil
}
func (d *DoHClient) buildGetRequest(ctx context.Context, msg []byte) (*http.Request, error) {
// Encode the query as base64url
b64 := base64.RawURLEncoding.EncodeToString(msg)
// The URL must be a template. Process it with the "dns" param containing the encoded query.
u, err := d.template.Expand(map[string]any{"dns": b64})
if err != nil {
d.metrics.err.Add("template", 1)
return nil, err
}
method := http.MethodGet
if d.opt.Use0RTT && d.opt.Transport == "quic" {
method = http3.MethodGet0RTT
}
req, err := http.NewRequestWithContext(ctx, method, u, nil)
if err != nil {
d.metrics.err.Add("http", 1)
return nil, err
}
req.Header.Add("accept", "application/dns-message")
return req, nil
}
func (d *DoHClient) String() string {
return d.id
}
// Check the HTTP response status code and parse out the response DNS message.
func (d *DoHClient) responseFromHTTP(resp *http.Response) (*dns.Msg, error) {
if resp.StatusCode < 200 || resp.StatusCode > 299 {
d.metrics.err.Add(fmt.Sprintf("http%d", resp.StatusCode), 1)
return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
rb, err := io.ReadAll(resp.Body)
if err != nil {
d.metrics.err.Add("read", 1)
return nil, err
}
a := new(dns.Msg)
err = a.Unpack(rb)
if err != nil {
d.metrics.err.Add("unpack", 1)
} else {
d.metrics.response.Add(rCode(a), 1)
}
return a, err
}
func dohTcpTransport(opt DoHClientOptions) (http.RoundTripper, error) {
idleTimeout := opt.IdleTimeout
if idleTimeout == 0 {
idleTimeout = defaultDoHIdleTimeout
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: opt.TLSConfig,
DisableCompression: true,
ResponseHeaderTimeout: 10 * time.Second,
IdleConnTimeout: idleTimeout,
}
// If we're using a custom tls.Config, HTTP2 isn't enabled by default in
// the HTTP library. Turn it on for this transport.
if tr.TLSClientConfig != nil {
if err := http2.ConfigureTransport(tr); err != nil {
return nil, err
}
}
// Use a custom dialer if a bootstrap address, local address, proxy, netns, or socket options were provided
if opt.BootstrapAddr != "" || opt.LocalAddr != nil || opt.LocalAddrV4 != nil || opt.LocalAddrV6 != nil || opt.Dialer != nil || (opt.NetNS != nil && opt.NetNS.Name != "") || opt.SocketOptions.active() {
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
if opt.BootstrapAddr != "" {
_, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
addr = net.JoinHostPort(opt.BootstrapAddr, port)
}
if opt.Dialer != nil {
var conn net.Conn
err := RunInNetNS(opt.NetNS, func() error {
var e error
conn, e = opt.Dialer.Dial(network, addr)
return e
})
if err != nil {
return nil, err
}
if err := opt.SocketOptions.applyToConn(conn); err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
addr = resolveEndpointAddr(addr)
localAddr := selectLocalAddr(addr, opt.LocalAddr, opt.LocalAddrV4, opt.LocalAddrV6)
d := net.Dialer{LocalAddr: &net.TCPAddr{IP: localAddr}, Control: opt.SocketOptions.dialerControl()}
var conn net.Conn
err := RunInNetNS(opt.NetNS, func() error {
var e error
conn, e = d.DialContext(ctx, network, addr)
return e
})
return conn, err
}
}
return tr, nil
}
func dohQuicTransport(endpoint string, opt DoHClientOptions) (http.RoundTripper, error) {
var tlsConfig *tls.Config
if opt.TLSConfig == nil {
tlsConfig = new(tls.Config)
} else {
tlsConfig = opt.TLSConfig.Clone()
}
u, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
// enable TLS session caching for session resumption and 0-RTT
tlsConfig.ClientSessionCache = tls.NewLRUClientSessionCache(100)
tlsConfig.ServerName = u.Hostname()
quicConfig := &quic.Config{
TokenStore: quic.NewLRUTokenStore(10, 10),
}
if opt.IdleTimeout > 0 {
quicConfig.MaxIdleTimeout = opt.IdleTimeout
}
// When both V4 and V6 local addresses are specified, create two QUIC transports
// since a UDP socket bound to an IPv4 address cannot reach IPv6 endpoints and vice versa.
if opt.LocalAddrV4 != nil && opt.LocalAddrV6 != nil {
return dohDualStackQuicTransport(opt, tlsConfig, quicConfig)
}
lAddr := net.IPv4zero
if opt.LocalAddr != nil {
lAddr = opt.LocalAddr
}
if opt.LocalAddrV4 != nil {
lAddr = opt.LocalAddrV4
}
if opt.LocalAddrV6 != nil {
lAddr = opt.LocalAddrV6
}
// Initialize the local UDP connection, it'll be re-used for all connections
udpConn, err := ListenUDPInNetNS(context.Background(), opt.NetNS, "udp", &net.UDPAddr{IP: lAddr, Port: 0}, opt.SocketOptions)
if err != nil {
Log.Error("couldn't listen on UDP socket on local address", "error", err, "local", lAddr.String())
return nil, err
}
quicTransport := &quic.Transport{Conn: udpConn}
dialFunc := quicTransport.Dial
if opt.Use0RTT {
dialFunc = quicTransport.DialEarly
}
dialer := func(ctx context.Context, addr string, tlsConfig *tls.Config, config *quic.Config) (*quic.Conn, error) {
if opt.BootstrapAddr != "" {
_, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
addr = net.JoinHostPort(opt.BootstrapAddr, port)
}
rAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return nil, err
}
return dialFunc(ctx, rAddr, tlsConfig, config)
}
tr := &http3.Transport{
TLSClientConfig: tlsConfig,
QUICConfig: quicConfig,
Dial: dialer,
}
return tr, nil
}
// dohDualStackQuicTransport creates a dual-stack QUIC transport with separate
// UDP sockets for IPv4 and IPv6, selecting the appropriate one based on the
// resolved remote address family.
func dohDualStackQuicTransport(opt DoHClientOptions, tlsConfig *tls.Config, quicConfig *quic.Config) (http.RoundTripper, error) {
udpConn4, err := ListenUDPInNetNS(context.Background(), opt.NetNS, "udp4", &net.UDPAddr{IP: opt.LocalAddrV4, Port: 0}, opt.SocketOptions)
if err != nil {
return nil, err
}
qt4 := &quic.Transport{Conn: udpConn4}
udpConn6, err := ListenUDPInNetNS(context.Background(), opt.NetNS, "udp6", &net.UDPAddr{IP: opt.LocalAddrV6, Port: 0}, opt.SocketOptions)
if err != nil {
return nil, err
}
qt6 := &quic.Transport{Conn: udpConn6}
dialFunc4 := qt4.Dial
dialFunc6 := qt6.Dial
if opt.Use0RTT {
dialFunc4 = qt4.DialEarly
dialFunc6 = qt6.DialEarly
}
dialer := func(ctx context.Context, addr string, tlsConfig *tls.Config, config *quic.Config) (*quic.Conn, error) {
if opt.BootstrapAddr != "" {
_, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
addr = net.JoinHostPort(opt.BootstrapAddr, port)
}
rAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return nil, err
}
dialFunc := dialFunc4
if rAddr.IP.To4() == nil {
dialFunc = dialFunc6
}
return dialFunc(ctx, rAddr, tlsConfig, config)
}
tr := &http3.Transport{
TLSClientConfig: tlsConfig,
QUICConfig: quicConfig,
Dial: dialer,
}
return tr, nil
}