-
Notifications
You must be signed in to change notification settings - Fork 221
/
dig.go
273 lines (220 loc) · 6.34 KB
/
dig.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
// Package dig implements the dig command chain.
package dig
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"net"
"regexp"
"strings"
"github.com/miekg/dns"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/agent"
"github.com/superfly/flyctl/iostreams"
"github.com/superfly/flyctl/client"
"github.com/superfly/flyctl/internal/appconfig"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/flag"
)
var nameErrorRx = regexp.MustCompile(`\[.*?\]:53`)
func New() *cobra.Command {
const (
long = `Make DNS requests against Fly.io's internal DNS server. Valid types include
AAAA and TXT (the two types our servers answer authoritatively), AAAA-NATIVE
and TXT-NATIVE, which resolve with Go's resolver (they're slower,
but may be useful if diagnosing a DNS bug) and A and CNAME
(if you're using the server to test recursive lookups.)
Note that this resolves names against the server for the current organization. You can
set the organization with -o <org-slug>; otherwise, the command uses the organization
attached to the current app (you can pass an app in with -a <appname>).`
short = "Make DNS requests against Fly.io's internal DNS server"
)
cmd := command.New("dig [type] <name> [flags]", short, long, run,
command.RequireSession,
command.LoadAppNameIfPresent,
)
cmd.Args = cobra.RangeArgs(1, 2)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.Org(),
flag.Bool{
Name: "short",
Shorthand: "s",
Default: false,
Description: "Just print the answers, not DNS record details",
},
)
return cmd
}
func run(ctx context.Context) error {
var (
client = client.FromContext(ctx).API()
io = iostreams.FromContext(ctx)
err error
)
orgSlug := flag.GetOrg(ctx)
if orgSlug == "" {
appName := appconfig.NameFromContext(ctx)
app, err := client.GetAppBasic(ctx, appName)
if err != nil {
return fmt.Errorf("get app: %w", err)
}
orgSlug = app.Organization.Slug
}
agentclient, err := agent.Establish(ctx, client)
if err != nil {
return err
}
r, ns, err := ResolverForOrg(ctx, agentclient, orgSlug)
if err != nil {
return err
}
d, err := agentclient.Dialer(ctx, orgSlug)
if err != nil {
return err
}
conn, err := d.DialContext(ctx, "tcp", net.JoinHostPort(ns, "53"))
if err != nil {
return err
}
msg := &dns.Msg{}
dtype := "AAAA"
name := flag.FirstArg(ctx)
if len(flag.Args(ctx)) > 1 {
dtype = strings.ToUpper(flag.FirstArg(ctx))
name = flag.Args(ctx)[1]
}
// add the trailing dot
name = dns.Fqdn(name)
if strings.HasSuffix(name, ".internal.") {
msg.RecursionDesired = false
} else {
msg.RecursionDesired = true
}
// put this switch block in its own function to reduce the footprint of the main function
// e.g: func resolve(ctx context.Context, r *net.Resolver, msg *dns.Msg, name string, dtype string)
switch dtype {
case "A", "CNAME", "TXT", "AAAA":
msg.SetQuestion(name, dns.StringToType[dtype])
reply, err := roundTrip(conn, msg)
if err != nil {
return err
}
if flag.GetBool(ctx, "short") {
if reply.MsgHdr.Rcode != dns.RcodeSuccess {
return fmt.Errorf("lookup failed: %s", dns.RcodeToString[reply.MsgHdr.Rcode])
}
switch dtype {
case "AAAA":
for _, rr := range reply.Answer {
if aaaa, ok := rr.(*dns.AAAA); ok {
fmt.Fprintf(io.Out, "%s\n", aaaa.AAAA)
}
}
case "TXT":
buf := &bytes.Buffer{}
for _, rr := range reply.Answer {
if txt, ok := rr.(*dns.TXT); ok {
for _, s := range txt.Txt {
buf.WriteString(s)
}
}
}
fmt.Fprintf(io.Out, "%s\n", buf.String())
}
} else {
fmt.Fprintf(io.Out, "%+v\n", reply)
}
case "AAAA-NATIVE":
hosts, err := r.LookupHost(ctx, name)
if err != nil {
return fixNameError(err, ns)
}
for _, h := range hosts {
fmt.Fprintf(io.Out, "%s\n", h)
}
case "TXT-NATIVE":
txts, err := r.LookupTXT(ctx, name)
if err != nil {
return fixNameError(err, ns)
}
fmt.Fprintf(io.Out, "%s\n", strings.Join(txts, ""))
default:
return fmt.Errorf("don't understand DNS type %s", dtype)
}
return nil
}
// roundTrip a DNS request across a "TCP" socket; we'd just use miekg/dns's Client, but I don't think it promises to
// work over our weird UDS TCP proxy.
func roundTrip(conn net.Conn, m *dns.Msg) (*dns.Msg, error) {
m.Id = dns.Id()
m.Compress = true
buf, err := m.Pack()
if err != nil {
return nil, err
}
var lenbuf [2]byte
binary.BigEndian.PutUint16(lenbuf[:], uint16(len(buf)))
if _, err = conn.Write(lenbuf[:]); err != nil {
return nil, err
}
if _, err = conn.Write(buf); err != nil {
return nil, err
}
if _, err = conn.Read(lenbuf[:]); err != nil {
return nil, err
}
l := int(binary.BigEndian.Uint16(lenbuf[:]))
buf = make([]byte, l)
if _, err = conn.Read(buf); err != nil {
return nil, err
}
ret := &dns.Msg{}
if err = ret.Unpack(buf); err != nil {
return nil, err
}
return ret, nil
}
// ResolverForOrg takes a connection to the wireguard agent and an organization
// and returns a working net.Resolver for DNS for that organization, along with the
// address of the nameserver.
func ResolverForOrg(ctx context.Context, c *agent.Client, orgSlug string) (*net.Resolver, string, error) {
// do this explicitly so we can get the DNS server address
ts, err := c.Establish(ctx, orgSlug)
if err != nil {
return nil, "", err
}
return &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d, err := c.Dialer(ctx, orgSlug)
if err != nil {
return nil, err
}
server := net.JoinHostPort(ts.TunnelConfig.DNS.String(), "53")
// the connections we get from the agent are over a unix domain socket proxy,
// which implements the PacketConn interface, so Go's janky DNS library thinks
// we want UDP DNS. Trip it up.
type fakeConn struct {
net.Conn
}
c, err := d.DialContext(ctx, "tcp", server)
if err != nil {
return nil, err
}
return &fakeConn{c}, nil
},
}, ts.TunnelConfig.DNS.String(), nil
}
// FixNameOrError cleans up resolver errors; the Go stdlib doesn't notice when
// you swap out the host its resolver connects to, and prints the resolv.conf
// resolver in error messages, which is super confusing for users.
func fixNameError(err error, ns string) error {
if err == nil {
return err
}
return errors.New(nameErrorRx.ReplaceAllString(err.Error(), fmt.Sprintf("[%s]:53", ns)))
}