-
Notifications
You must be signed in to change notification settings - Fork 240
/
upstream.go
367 lines (318 loc) · 10.8 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
package upstream
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/ameshkov/dnscrypt"
"github.com/ameshkov/dnsstamps"
"github.com/hmage/golibs/log"
"github.com/joomcode/errorx"
"github.com/miekg/dns"
)
// 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 {
boot bootstrapper
preferTCP bool
}
// Address returns the original address that we've put in initially, not resolved one
func (p *plainDNS) Address() string { return p.boot.address }
func (p *plainDNS) Exchange(m *dns.Msg) (*dns.Msg, error) {
addr, _, err := p.boot.get()
if err != nil {
return nil, err
}
if p.preferTCP {
tcpClient := dns.Client{Net: "tcp", Timeout: p.boot.timeout}
reply, _, tcpErr := tcpClient.Exchange(m, addr)
return reply, tcpErr
}
client := dns.Client{Timeout: p.boot.timeout, UDPSize: dns.MaxMsgSize}
reply, _, err := client.Exchange(m, addr)
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.boot.timeout}
reply, _, err = tcpClient.Exchange(m, addr)
}
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
// transport is an http.Transport configured to use the bootstrapped IP address
// Transports should be reused instead of created as needed.
// Transports are safe for concurrent use by multiple goroutines.
transport *http.Transport
sync.RWMutex // protects transport
}
func (p *dnsOverHTTPS) Address() string { return p.boot.address }
func (p *dnsOverHTTPS) Exchange(m *dns.Msg) (*dns.Msg, error) {
transport, err := p.getTransport()
if err != nil {
return nil, errorx.Decorate(err, "couldn't initialize HTTP transport")
}
buf, err := m.Pack()
if err != nil {
return nil, errorx.Decorate(err, "couldn't pack request msg")
}
bb := bytes.NewBuffer(buf)
req, err := http.NewRequest("POST", p.boot.address, bb)
if err != nil {
return nil, errorx.Decorate(err, "couldn't create a HTTP request to %s", p.boot.address)
}
req.Header.Set("Content-Type", "application/dns-message")
req.Header.Set("Accept", "application/dns-message")
client := http.Client{
Transport: transport,
Timeout: p.boot.timeout,
}
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
}
// getTransport gets or lazily 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) getTransport() (*http.Transport, error) {
p.Lock()
defer p.Unlock()
if p.transport != nil {
return p.transport, nil
}
resolverAddr, tlsConfig, err := p.boot.get()
if err != nil {
return nil, errorx.Decorate(err, "couldn't bootstrap %s", p.boot.address)
}
dialer := &net.Dialer{
Timeout: p.boot.timeout,
DualStack: true,
}
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
// Note that we're using bootstrapped resolverAddr instead of what's passed to the function
return dialer.DialContext(ctx, network, resolverAddr)
}
transport := &http.Transport{
TLSClientConfig: tlsConfig,
DisableCompression: true,
DialContext: dialContext,
}
// Uncomment to reproduce the conditions for https://github.com/AdguardTeam/dnsproxy/issues/5
// http2.ConfigureTransport(transport)
// Save the transport for the future use
p.transport = transport
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
}
// 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)
// bootstrap is a plain DNS which is 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
func AddressToUpstream(address string, bootstrap string, timeout time.Duration) (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, bootstrap, timeout)
}
// 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{boot: toBoot(address, bootstrap, timeout)}, nil
}
// urlToUpstream converts a URL to an Upstream
func urlToUpstream(upstreamURL *url.URL, bootstrap string, timeout time.Duration) (Upstream, error) {
switch upstreamURL.Scheme {
case "sdns":
return stampToUpstream(upstreamURL.String(), bootstrap, timeout)
case "dns":
return &plainDNS{boot: toBoot(getHostWithPort(upstreamURL, "53"), bootstrap, timeout)}, nil
case "tcp":
return &plainDNS{boot: toBoot(getHostWithPort(upstreamURL, "53"), bootstrap, timeout), preferTCP: true}, nil
case "tls":
return &dnsOverTLS{boot: toBoot(getHostWithPort(upstreamURL, "853"), bootstrap, timeout)}, nil
case "https":
if upstreamURL.Port() == "" {
upstreamURL.Host += ":443"
}
return &dnsOverHTTPS{boot: toBoot(upstreamURL.String(), bootstrap, timeout)}, nil
default:
// assume it's plain DNS
return &plainDNS{boot: toBoot(getHostWithPort(upstreamURL, "53"), bootstrap, timeout)}, nil
}
}
// stampToUpstream converts a DNS stamp to an Upstream
func stampToUpstream(address string, bootstrap string, timeout time.Duration) (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{boot: toBoot(stamp.ServerAddrStr, bootstrap, timeout)}, nil
case dnsstamps.StampProtoTypeDNSCrypt:
return &dnsCrypt{boot: toBoot(address, bootstrap, timeout)}, nil
case dnsstamps.StampProtoTypeDoH:
return AddressToUpstream(fmt.Sprintf("https://%s%s", stamp.ProviderName, stamp.Path), bootstrap, timeout)
case dnsstamps.StampProtoTypeTLS:
return AddressToUpstream(fmt.Sprintf("tls://%s", stamp.ProviderName), bootstrap, timeout)
}
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
}