-
Notifications
You must be signed in to change notification settings - Fork 240
/
upstream.go
401 lines (342 loc) · 11.9 KB
/
upstream.go
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
package upstream
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"golang.org/x/net/http2"
"github.com/AdguardTeam/golibs/log"
"github.com/ameshkov/dnscrypt"
"github.com/ameshkov/dnsstamps"
"github.com/joomcode/errorx"
"github.com/miekg/dns"
)
// DohMaxConnsPerHost controls the maximum number of connections per host
// nolint
var DohMaxConnsPerHost = 0
// Upstream is an interface for a DNS resolver
type Upstream interface {
Exchange(m *dns.Msg) (*dns.Msg, error)
Address() string
}
//
// plain DNS
//
type plainDNS struct {
address string
timeout time.Duration
preferTCP bool
}
// Address returns the original address that we've put in initially, not resolved one
func (p *plainDNS) Address() string { return p.address }
func (p *plainDNS) Exchange(m *dns.Msg) (*dns.Msg, error) {
if p.preferTCP {
tcpClient := dns.Client{Net: "tcp", Timeout: p.timeout}
reply, _, tcpErr := tcpClient.Exchange(m, p.address)
return reply, tcpErr
}
client := dns.Client{Timeout: p.timeout, UDPSize: dns.MaxMsgSize}
reply, _, err := client.Exchange(m, p.address)
if reply != nil && reply.Truncated {
log.Tracef("Truncated message was received, retrying over TCP, question: %s", m.Question[0].String())
tcpClient := dns.Client{Net: "tcp", Timeout: p.timeout}
reply, _, err = tcpClient.Exchange(m, p.address)
}
return reply, err
}
//
// DNS-over-TLS
//
type dnsOverTLS struct {
boot bootstrapper
pool *TLSPool
sync.RWMutex // protects pool
}
func (p *dnsOverTLS) Address() string { return p.boot.address }
func (p *dnsOverTLS) Exchange(m *dns.Msg) (*dns.Msg, error) {
var pool *TLSPool
p.RLock()
pool = p.pool
p.RUnlock()
if pool == nil {
p.Lock()
// lazy initialize it
p.pool = &TLSPool{boot: &p.boot}
p.Unlock()
}
p.RLock()
poolConn, err := p.pool.Get()
p.RUnlock()
if err != nil {
return nil, errorx.Decorate(err, "Failed to get a connection from TLSPool to %s", p.Address())
}
reply, err := p.exchangeConn(poolConn, m)
if err != nil {
// The pooled connection might have been closed already (see https://github.com/AdguardTeam/dnsproxy/issues/3)
// So we're trying to re-connect right away here.
// We are forcing creation of a new connection instead of calling Get() again
// as there's no guarantee that other pooled connections are intact
p.RLock()
poolConn, err = p.pool.Create()
p.RUnlock()
if err != nil {
return nil, errorx.Decorate(err, "Failed to create a new connection from TLSPool to %s", p.Address())
}
// Retry sending the DNS request
reply, err = p.exchangeConn(poolConn, m)
}
if err == nil {
p.RLock()
p.pool.Put(poolConn)
p.RUnlock()
}
return reply, err
}
func (p *dnsOverTLS) exchangeConn(poolConn net.Conn, m *dns.Msg) (*dns.Msg, error) {
c := dns.Conn{Conn: poolConn}
err := c.WriteMsg(m)
if err != nil {
poolConn.Close()
return nil, errorx.Decorate(err, "Failed to send a request to %s", p.Address())
}
reply, err := c.ReadMsg()
if err != nil {
poolConn.Close()
return nil, errorx.Decorate(err, "Failed to read a request from %s", p.Address())
}
return reply, err
}
//
// DNS-over-https
//
type dnsOverHTTPS struct {
boot bootstrapper
// The Client's Transport typically has internal state (cached TCP
// connections), so Clients should be reused instead of created as
// needed. Clients are safe for concurrent use by multiple goroutines.
client *http.Client
sync.RWMutex // protects transport
}
func (p *dnsOverHTTPS) Address() string { return p.boot.address }
func (p *dnsOverHTTPS) Exchange(m *dns.Msg) (*dns.Msg, error) {
client, err := p.getClient()
if err != nil {
return nil, errorx.Decorate(err, "couldn't initialize HTTP client or transport")
}
return p.exchangeHTTPSClient(m, client)
}
// exchangeHTTPSClient sends the DNS query to a DOH resolver using the specified http.Client instance
func (p *dnsOverHTTPS) exchangeHTTPSClient(m *dns.Msg, client *http.Client) (*dns.Msg, error) {
buf, err := m.Pack()
if err != nil {
return nil, errorx.Decorate(err, "couldn't pack request msg")
}
// It appears, that GET requests are more memory-efficient with Golang implementation of HTTP/2.
requestURL := p.boot.address + "?dns=" + base64.RawURLEncoding.EncodeToString(buf)
req, err := http.NewRequest("GET", requestURL, nil)
if err != nil {
return nil, errorx.Decorate(err, "couldn't create a HTTP request to %s", p.boot.address)
}
req.Header.Set("Accept", "application/dns-message")
resp, err := client.Do(req)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
return nil, errorx.Decorate(err, "couldn't do a POST request to '%s'", p.boot.address)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errorx.Decorate(err, "couldn't read body contents for '%s'", p.boot.address)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("got an unexpected HTTP status code %d from '%s'", resp.StatusCode, p.boot.address)
}
response := dns.Msg{}
err = response.Unpack(body)
if err != nil {
return nil, errorx.Decorate(err, "couldn't unpack DNS response from '%s': body is %s", p.boot.address, string(body))
}
return &response, nil
}
// getClient gets or lazily initializes an HTTP client (and transport) that will be used for this DOH resolver.
func (p *dnsOverHTTPS) getClient() (*http.Client, error) {
p.Lock()
defer p.Unlock()
if p.client != nil {
return p.client, nil
}
transport, err := p.createTransport()
if err != nil {
return nil, errorx.Decorate(err, "couldn't initialize HTTP transport")
}
client := &http.Client{
Transport: transport,
Timeout: p.boot.timeout,
Jar: nil,
}
// Warming up the HTTP client.
// This is actually important -- if there is no warmup, there's a race condition on the very first DNS query:
// http.Client will create numerous connections. During this warmup it'll create a new connection that will be used
// for processing further DNS queries.
req := dns.Msg{}
req.Id = dns.Id()
req.RecursionDesired = true
req.Question = []dns.Question{{Name: "ipv4only.arpa.", Qtype: dns.TypeA, Qclass: dns.ClassINET}}
_, err = p.exchangeHTTPSClient(&req, client)
if err != nil {
return nil, err
}
p.client = client
return p.client, nil
}
// createTransport initializes an HTTP transport that will be used specifically for this DOH resolver
// This HTTP transport ensures that the HTTP requests will be sent exactly to the IP address got from the bootstrap resolver
func (p *dnsOverHTTPS) createTransport() (*http.Transport, error) {
tlsConfig, dialContext, err := p.boot.get()
if err != nil {
return nil, errorx.Decorate(err, "couldn't bootstrap %s", p.boot.address)
}
transport := &http.Transport{
TLSClientConfig: tlsConfig,
DisableCompression: true,
DialContext: dialContext,
MaxConnsPerHost: DohMaxConnsPerHost,
MaxIdleConns: 1,
}
// It appears that this is important to explicitly configure transport to use HTTP2
// Relevant issue: https://github.com/AdguardTeam/dnsproxy/issues/11
http2.ConfigureTransport(transport) // nolint
return transport, nil
}
//
// DNSCrypt
//
type dnsCrypt struct {
boot bootstrapper
client *dnscrypt.Client // DNSCrypt client properties
serverInfo *dnscrypt.ServerInfo // DNSCrypt server info
sync.RWMutex // protects DNSCrypt client
}
func (p *dnsCrypt) Address() string { return p.boot.address }
func (p *dnsCrypt) Exchange(m *dns.Msg) (*dns.Msg, error) {
var client *dnscrypt.Client
var serverInfo *dnscrypt.ServerInfo
p.RLock()
client = p.client
serverInfo = p.serverInfo
p.RUnlock()
now := uint32(time.Now().Unix())
if client == nil || serverInfo == nil || (serverInfo != nil && serverInfo.ServerCert.NotAfter < now) {
p.Lock()
// Using "udp" for DNSCrypt upstreams by default
client = &dnscrypt.Client{Timeout: p.boot.timeout, AdjustPayloadSize: true}
si, _, err := client.Dial(p.boot.address)
if err != nil {
p.Unlock()
return nil, errorx.Decorate(err, "failed to fetch certificate info from %s", p.Address())
}
p.client = client
p.serverInfo = si
serverInfo = si
p.Unlock()
}
reply, _, err := client.Exchange(m, serverInfo)
if reply != nil && reply.Truncated {
log.Tracef("Truncated message was received, retrying over TCP, question: %s", m.Question[0].String())
tcpClient := dnscrypt.Client{Timeout: p.boot.timeout, Proto: "tcp"}
reply, _, err = tcpClient.Exchange(m, serverInfo)
}
if os.IsTimeout(err) {
// If request times out, it is possible that the server configuration has been changed.
// It is safe to assume that the key was rotated (for instance, as it is described here: https://dnscrypt.pl/2017/02/26/how-key-rotation-is-automated/).
// We should re-fetch the server certificate info so that the new requests were not failing.
p.Lock()
p.client = nil
p.serverInfo = nil
p.Unlock()
}
return reply, err
}
// Options for AddressToUpstream func
// bootstrap is a plain DNS list to be used to resolve DoH/DoT hostnames (if any)
// timeout is a default upstream timeout. Also, it is used as a timeout for bootstrap DNS requests.
// timeout=0 means infinite timeout
type Options struct {
Bootstrap []string
Timeout time.Duration
}
// AddressToUpstream converts the specified address to an Upstream instance
// * 8.8.8.8:53 -- plain DNS
// * tcp://8.8.8.8:53 -- plain DNS over TCP
// * tls://1.1.1.1 -- DNS-over-TLS
// * https://dns.adguard.com/dns-query -- DNS-over-HTTPS
// * sdns://... -- DNS stamp (see https://dnscrypt.info/stamps-specifications)
func AddressToUpstream(address string, opts Options) (Upstream, error) {
if strings.Contains(address, "://") {
upstreamURL, err := url.Parse(address)
if err != nil {
return nil, errorx.Decorate(err, "failed to parse %s", address)
}
return urlToUpstream(upstreamURL, opts)
}
// we don't have scheme in the url, so it's just a plain DNS host:port
_, _, err := net.SplitHostPort(address)
if err != nil {
// doesn't have port, default to 53
address = net.JoinHostPort(address, "53")
}
return &plainDNS{address: address, timeout: opts.Timeout}, nil
}
// urlToUpstream converts a URL to an Upstream
func urlToUpstream(upstreamURL *url.URL, opts Options) (Upstream, error) {
switch upstreamURL.Scheme {
case "sdns":
return stampToUpstream(upstreamURL.String(), opts)
case "dns":
return &plainDNS{address: getHostWithPort(upstreamURL, "53"), timeout: opts.Timeout}, nil
case "tcp":
return &plainDNS{address: getHostWithPort(upstreamURL, "53"), timeout: opts.Timeout, preferTCP: true}, nil
case "tls":
return &dnsOverTLS{boot: toBoot(getHostWithPort(upstreamURL, "853"), opts.Bootstrap, opts.Timeout)}, nil
case "https":
if upstreamURL.Port() == "" {
upstreamURL.Host += ":443"
}
return &dnsOverHTTPS{boot: toBoot(upstreamURL.String(), opts.Bootstrap, opts.Timeout)}, nil
default:
// assume it's plain DNS
return &plainDNS{address: getHostWithPort(upstreamURL, "53"), timeout: opts.Timeout}, nil
}
}
// stampToUpstream converts a DNS stamp to an Upstream
func stampToUpstream(address string, opts Options) (Upstream, error) {
stamp, err := dnsstamps.NewServerStampFromString(address)
if err != nil {
return nil, errorx.Decorate(err, "failed to parse %s", address)
}
switch stamp.Proto {
case dnsstamps.StampProtoTypePlain:
return &plainDNS{address: stamp.ServerAddrStr, timeout: opts.Timeout}, nil
case dnsstamps.StampProtoTypeDNSCrypt:
return &dnsCrypt{boot: toBoot(address, opts.Bootstrap, opts.Timeout)}, nil
case dnsstamps.StampProtoTypeDoH:
return AddressToUpstream(fmt.Sprintf("https://%s%s", stamp.ProviderName, stamp.Path), opts)
case dnsstamps.StampProtoTypeTLS:
return AddressToUpstream(fmt.Sprintf("tls://%s", stamp.ProviderName), opts)
}
return nil, fmt.Errorf("unsupported protocol %v in %s", stamp.Proto, address)
}
// getHostWithPort is a helper function that appends port if needed
func getHostWithPort(upstreamURL *url.URL, defaultPort string) string {
if upstreamURL.Port() == "" {
return upstreamURL.Host + ":" + defaultPort
}
return upstreamURL.Host
}