cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2021.1.2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

edgediscovery/allregions/discovery.go

130lines · modecode

1package allregions
2
3import (
4 "context"
5 "crypto/tls"
6 "fmt"
7 "net"
8 "time"
9
10 "github.com/pkg/errors"
11 "github.com/rs/zerolog"
12)
13
14const (
15 // Used to discover HA origintunneld servers
16 srvService = "origintunneld"
17 srvProto = "tcp"
18 srvName = "argotunnel.com"
19
20 // Used to fallback to DoT when we can't use the default resolver to
21 // discover HA origintunneld servers (GitHub issue #75).
22 dotServerName = "cloudflare-dns.com"
23 dotServerAddr = "1.1.1.1:853"
24 dotTimeout = 15 * time.Second
25)
26
27// Redeclare network functions so they can be overridden in tests.
28var (
29 netLookupSRV = net.LookupSRV
30 netLookupIP = net.LookupIP
31)
32
33// If the call to net.LookupSRV fails, try to fall back to DoT from Cloudflare directly.
34//
35// Note: Instead of DoT, we could also have used DoH. Either of these:
36// - directly via the JSON API (https://1.1.1.1/dns-query?ct=application/dns-json&name=_origintunneld._tcp.argotunnel.com&type=srv)
37// - indirectly via `tunneldns.NewUpstreamHTTPS()`
38// But both of these cases miss out on a key feature from the stdlib:
39// "The returned records are sorted by priority and randomized by weight within a priority."
40// (https://golang.org/pkg/net/#Resolver.LookupSRV)
41// Does this matter? I don't know. It may someday. Let's use DoT so we don't need to worry about it.
42// See also: Go feature request for stdlib-supported DoH: https://github.com/golang/go/issues/27552
43var fallbackLookupSRV = lookupSRVWithDOT
44
45var friendlyDNSErrorLines = []string{
46 `Please try the following things to diagnose this issue:`,
47 ` 1. ensure that argotunnel.com is returning "origintunneld" service records.`,
48 ` Run your system's equivalent of: dig srv _origintunneld._tcp.argotunnel.com`,
49 ` 2. ensure that your DNS resolver is not returning compressed SRV records.`,
50 ` See GitHub issue https://github.com/golang/go/issues/27546`,
51 ` For example, you could use Cloudflare's 1.1.1.1 as your resolver:`,
52 ` https://developers.cloudflare.com/1.1.1.1/setting-up-1.1.1.1/`,
53}
54
55// EdgeDiscovery implements HA service discovery lookup.
56func edgeDiscovery(log *zerolog.Logger) ([][]*net.TCPAddr, error) {
57 _, addrs, err := netLookupSRV(srvService, srvProto, srvName)
58 if err != nil {
59 _, fallbackAddrs, fallbackErr := fallbackLookupSRV(srvService, srvProto, srvName)
60 if fallbackErr != nil || len(fallbackAddrs) == 0 {
61 // use the original DNS error `err` in messages, not `fallbackErr`
62 log.Err(err).Msg("Error looking up Cloudflare edge IPs: the DNS query failed")
63 for _, s := range friendlyDNSErrorLines {
64 log.Error().Msg(s)
65 }
66 return nil, errors.Wrapf(err, "Could not lookup srv records on _%v._%v.%v", srvService, srvProto, srvName)
67 }
68 // Accept the fallback results and keep going
69 addrs = fallbackAddrs
70 }
71
72 var resolvedIPsPerCNAME [][]*net.TCPAddr
73 for _, addr := range addrs {
74 ips, err := resolveSRVToTCP(addr)
75 if err != nil {
76 return nil, err
77 }
78 resolvedIPsPerCNAME = append(resolvedIPsPerCNAME, ips)
79 }
80
81 return resolvedIPsPerCNAME, nil
82}
83
84func lookupSRVWithDOT(service, proto, name string) (cname string, addrs []*net.SRV, err error) {
85 // Inspiration: https://github.com/artyom/dot/blob/master/dot.go
86 r := &net.Resolver{
87 PreferGo: true,
88 Dial: func(ctx context.Context, _ string, _ string) (net.Conn, error) {
89 var dialer net.Dialer
90 conn, err := dialer.DialContext(ctx, "tcp", dotServerAddr)
91 if err != nil {
92 return nil, err
93 }
94 tlsConfig := &tls.Config{ServerName: dotServerName}
95 return tls.Client(conn, tlsConfig), nil
96 },
97 }
98 ctx, cancel := context.WithTimeout(context.Background(), dotTimeout)
99 defer cancel()
100 return r.LookupSRV(ctx, srvService, srvProto, srvName)
101}
102
103func resolveSRVToTCP(srv *net.SRV) ([]*net.TCPAddr, error) {
104 ips, err := netLookupIP(srv.Target)
105 if err != nil {
106 return nil, errors.Wrapf(err, "Couldn't resolve SRV record %v", srv)
107 }
108 if len(ips) == 0 {
109 return nil, fmt.Errorf("SRV record %v had no IPs", srv)
110 }
111 addrs := make([]*net.TCPAddr, len(ips))
112 for i, ip := range ips {
113 addrs[i] = &net.TCPAddr{IP: ip, Port: int(srv.Port)}
114 }
115 return addrs, nil
116}
117
118// ResolveAddrs resolves TCP address given a list of addresses. Address can be a hostname, however, it will return at most one
119// of the hostname's IP addresses.
120func ResolveAddrs(addrs []string, log *zerolog.Logger) (resolved []*net.TCPAddr) {
121 for _, addr := range addrs {
122 tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
123 if err != nil {
124 log.Err(err).Msgf("Failed to resolve %s", addr)
125 } else {
126 resolved = append(resolved, tcpAddr)
127 }
128 }
129 return
130}
131