forked from mehrdadrad/mylg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ns.go
401 lines (359 loc) · 7.89 KB
/
ns.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 ns provides name server methods for selected name server(s)
package ns
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"sort"
"strings"
"time"
"github.com/miekg/dns"
"github.com/mehrdadrad/mylg/cli"
"github.com/mehrdadrad/mylg/data"
)
const (
publicDNSHost = "http://public-dns.info"
publicDNSNodesPath = "/nameservers.csv"
)
// A Host represents a name server host
type Host struct {
IP string
Alpha2 string
Country string
City string
}
// A Request represents a name server request
type Request struct {
Country string
City string
Target string
Type uint16
Host string
Hosts []Host
TraceEnabled bool
}
// NewRequest creates a new dns request object
func NewRequest() *Request {
return &Request{Host: ""}
}
// SetOptions passes arguments to appropriate variable
func (d *Request) SetOptions(args, prompt string) bool {
d.Host = ""
d.TraceEnabled = false
d.Type = dns.TypeANY
nArgs, flag := cli.Flag(args)
// show help
if _, ok := flag["help"]; ok || len(nArgs) < 1 {
help()
return false
}
for _, a := range strings.Fields(nArgs) {
if a[0] == '@' {
d.Host = a[1:]
d.City = ""
continue
}
if t, ok := dns.StringToType[strings.ToUpper(a)]; ok {
d.Type = t
continue
}
if a == "+trace" {
d.TraceEnabled = true
continue
}
d.Target = a
}
p := strings.Split(prompt, "/")
if d.Host == "" {
if p[0] == "local" || len(p) < 3 {
config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
d.Host = config.Servers[0]
d.City = "your local dns server"
} else {
d.ChkNode(p[2])
}
}
return true
}
// Init configure dns command and fetch name servers
func (d *Request) Init() {
if !d.cache("validate") {
d.Hosts = fetchNSHosts()
d.cache("write")
} else {
d.cache("read")
}
}
// CountryList init the connect contry items
func (d *Request) CountryList() []string {
var countries []string
for _, host := range d.Hosts {
countries = append(countries, host.Country)
}
countries = uniqStrSlice(countries)
sort.Strings(countries)
return countries
}
// NodeList gets the node city items
func (d *Request) NodeList() []string {
var node []string
for _, host := range d.Hosts {
if host.Country == d.Country {
node = append(node, host.City)
}
}
sort.Strings(node)
return node
}
// ChkCountry validates and set requested country
func (d *Request) ChkCountry(country string) bool {
country = strings.ToLower(country)
for _, h := range d.Hosts {
if country == h.Country {
d.Country = country
return true
}
}
return false
}
// ChkNode set requested country
func (d *Request) ChkNode(city string) bool {
city = strings.ToLower(city)
for _, h := range d.Hosts {
if d.Country == h.Country && city == h.City {
d.Host = h.IP
d.City = h.City
return true
}
}
return false
}
// Local set host to nothing means local
func (d *Request) Local() {
d.Host = ""
d.Country = ""
}
// Dig looks up name server w/ trace feature
func (d *Request) Dig() {
if !d.TraceEnabled {
d.RunDig()
} else {
d.RunDigTrace()
}
}
// RunDig looks up name server
func (d *Request) RunDig() {
var (
r *dns.Msg
err error
rtt time.Duration
)
c := new(dns.Client)
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(d.Target), d.Type)
m.RecursionDesired = true
m.RecursionAvailable = true
c.Net = "udp"
for i := 0; i < 3; i++ {
fmt.Printf("Trying to query server (%s): %s %s %s\n", c.Net, d.Host, d.Country, d.City)
r, rtt, err = c.Exchange(m, net.JoinHostPort(d.Host, "53"))
// fall back to tcp
if err == dns.ErrTruncated && i == 0 {
c.Net = "tcp"
}
// last chance: udp + A records instead of any records
if err != nil && i == 1 {
c.Net = "udp"
d.Type = dns.TypeA
m.SetQuestion(dns.Fqdn(d.Target), d.Type)
}
if err != nil {
println(err.Error())
continue
} else {
break
}
}
if err != nil {
return
}
// Answer
println(r.MsgHdr.String())
for _, a := range r.Answer {
fmt.Println(a)
}
// Extra info
if len(r.Extra) > 0 {
println("\n;; ADDITIONAL SECTION:")
for _, a := range r.Extra {
fmt.Println(a)
}
}
fmt.Printf(";; Query time: %d ms\n", rtt/1e6)
// CHAOS
c.Timeout = ((rtt / 1e6) + 100) * time.Millisecond
fmt.Printf("\n;; CHAOS CLASS BIND\n")
for _, q := range []string{"version.bind.", "hostname.bind."} {
m.Question[0] = dns.Question{q, dns.TypeTXT, dns.ClassCHAOS}
r, _, err = c.Exchange(m, d.Host+":53")
if err != nil {
continue
}
for _, a := range r.Answer {
fmt.Println(a)
}
}
}
// RunDigTrace handles dig trace
func (d *Request) RunDigTrace() {
var (
nss = []string{d.Host}
err error
host string
rtt time.Duration
r *dns.Msg
)
c := new(dns.Client)
m := new(dns.Msg)
m.RecursionDesired = true
q := ""
domain := []string{""}
domain = append(domain, strings.Split(dns.Fqdn(d.Target), ".")...)
for i := range domain {
if i != 1 && i != len(domain)-1 {
q = domain[len(domain)-i-1] + "." + q
} else {
q = domain[len(domain)-i-1] + q
}
if i != len(domain)-1 {
m.SetQuestion(q, dns.TypeNS)
} else {
m.SetQuestion(q, dns.TypeA)
}
for _, host = range nss {
r, rtt, err = c.Exchange(m, net.JoinHostPort(host, "53"))
if err != nil {
println(err.Error())
} else {
break
}
}
nss = nss[:0]
for _, a := range r.Answer {
println(a.String())
if a.Header().Rrtype == dns.TypeNS {
nss = append(nss, strings.Fields(a.String())[4])
}
}
for _, a := range r.Ns {
println(a.String())
nss = append(nss, strings.Fields(a.String())[4])
}
fmt.Printf("from: %s#53 in %d ms\n", host, rtt/1e6)
}
}
// cache provides caching for name servers
func (d *Request) cache(r string) bool {
switch r {
case "read":
b, err := ioutil.ReadFile("/tmp/mylg.ns")
if err != nil {
panic(err.Error())
}
d.Hosts = d.Hosts[:0]
r := bytes.NewBuffer(b)
s := bufio.NewScanner(r)
for s.Scan() {
csv := strings.Split(s.Text(), ";")
if len(csv) != 4 {
continue
}
d.Hosts = append(d.Hosts, Host{Alpha2: csv[0], Country: csv[1], City: csv[2], IP: csv[3]})
}
case "write":
var data []string
for _, h := range d.Hosts {
data = append(data, fmt.Sprintf("%s;%s;%s;%s", h.Alpha2, h.Country, h.City, h.IP))
}
err := ioutil.WriteFile("/tmp/mylg.ns", []byte(strings.Join(data, "\n")), 0644)
if err != nil {
panic(err.Error())
}
case "validate":
f, err := os.Stat("/tmp/mylg.ns")
if err != nil {
return false
}
d := time.Since(f.ModTime())
if d.Hours() > 48 {
return false
}
}
return true
}
// Fetch name servers from public-dns.info
func fetchNSHosts() []Host {
var (
hosts []Host
city string
counter = make(map[string]int)
chkDup = make(map[string]int)
)
resp, err := http.Get(publicDNSHost + publicDNSNodesPath)
if err != nil {
println(err.Error())
return []Host{}
}
if resp.StatusCode != 200 {
println("error: public dns is not available")
return []Host{}
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
csv := strings.Split(scanner.Text(), ",")
if csv[3] != "\"\"" {
if name, ok := data.Country[csv[2]]; ok && counter[csv[2]] < 5 {
name = strings.ToLower(name)
city = strings.ToLower(csv[3])
chkDup[name+city] += 1
if chkDup[name+city] > 1 {
city = fmt.Sprintf("%s0%d", city, chkDup[name+city]-1)
}
hosts = append(hosts, Host{IP: csv[0], Alpha2: csv[2], Country: name, City: city})
counter[csv[2]]++
}
}
}
return hosts
}
// uniqStrSlice return unique slice
func uniqStrSlice(src []string) []string {
var rst []string
tmp := make(map[string]struct{})
for _, s := range src {
tmp[s] = struct{}{}
}
for s := range tmp {
rst = append(rst, s)
}
return rst
}
// help
func help() {
fmt.Println(`
usage:
dig [@local-server] host [options]
options:
+trace
Example:
dig google.com
dig @8.8.8.8 yahoo.com
dig google.com +trace
dig google.com MX
`)
}