-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
473 lines (433 loc) · 12.7 KB
/
main.go
File metadata and controls
473 lines (433 loc) · 12.7 KB
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// main.go
package main
import (
"bufio"
"bytes"
"context"
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"log"
"net"
"os"
"regexp"
"strings"
"github.com/alecthomas/chroma/quick"
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
"gopkg.in/yaml.v2"
)
// DomainTXT holds the full DNS TXT record result for a domain.
type DomainTXT struct {
Domain string `json:"domain" yaml:"domain"`
TXT string `json:"txt" yaml:"txt"`
Key string `json:"key" yaml:"key"`
Value string `json:"value" yaml:"value"`
}
// SimpleResult holds the simplified output for a domain.
type SimpleResult struct {
Domain string `json:"domain" yaml:"domain"`
Key string `json:"key" yaml:"key"`
}
// simplifyKey returns the substring of key before the first "-" (if present).
func simplifyKey(key string) string {
if idx := strings.Index(key, "-"); idx != -1 {
return key[:idx]
}
return key
}
// printFlagDefaults prints all defined flags with a double-dash (--)
// before each flag name. It prints a type hint ("string") for non-bool flags
// and includes the default value when appropriate.
func printFlagDefaults() {
flag.VisitAll(func(f *flag.Flag) {
// Determine if the flag is a bool flag by checking its default value.
isBool := f.DefValue == "true" || f.DefValue == "false"
if isBool {
fmt.Fprintf(os.Stderr, " --%s\n", f.Name)
} else {
fmt.Fprintf(os.Stderr, " --%s string\n", f.Name)
}
fmt.Fprintf(os.Stderr, " %s", f.Usage)
if !isBool && f.DefValue != "" {
fmt.Fprintf(os.Stderr, " (default %q)", f.DefValue)
}
fmt.Fprintf(os.Stderr, "\n")
})
}
var (
verbose bool
dnsServer string
)
func init() {
flag.BoolVar(&verbose, "verbose", false, "Enable verbose logging")
flag.StringVar(&dnsServer, "dns", "", "Specify DNS server to use")
}
func main() {
// Define command-line flags.
filePath := flag.String("file", "", "Path to a text file containing domain names (one domain per line).")
outputFormat := flag.String("format", "pretty", "Output format. Options: pretty (default), json, yaml, csv.")
noColor := flag.Bool("no-color", false, "Disable colored output and syntax highlighting.")
allRecords := flag.Bool("all", false, "Include all TXT records, even those without a valid key/value pair.")
// By default, SPF records are ignored unless --include-spf is set.
includeSPF := flag.Bool("include-spf", false, "Include SPF TXT records (records starting with 'v=spf1'). By default, SPF records are ignored.")
// New --simple flag: output a simplified view.
simple := flag.Bool("simple", false, "Output simplified results: only the domain and a simplified key (deduplicated).")
// Override the default Usage function with a Typer-inspired help interface.
flag.Usage = func() {
if *noColor {
color.NoColor = true
}
header := color.New(color.FgCyan, color.Bold)
example := color.New(color.FgYellow)
fmt.Fprintf(os.Stderr, "\n")
header.Fprintf(os.Stderr, "dnxty - A DNS TXT Record Extraction Utility\n\n")
fmt.Fprintf(os.Stderr, "Usage:\n %s [options] domain1 [domain2 ...]\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Options:\n")
printFlagDefaults()
fmt.Fprintf(os.Stderr, "\nExamples:\n")
example.Fprintf(os.Stderr, " %s google.com facebook.com\n", os.Args[0])
example.Fprintf(os.Stderr, " %s --file domains.txt --format json\n", os.Args[0])
example.Fprintf(os.Stderr, " %s --all google.com\n", os.Args[0])
example.Fprintf(os.Stderr, " %s --include-spf google.com\n", os.Args[0])
example.Fprintf(os.Stderr, " %s --simple google.com\n\n", os.Args[0])
}
flag.Parse()
color.NoColor = *noColor
if len(flag.Args()) == 0 {
fmt.Println("Usage: main.go [options] <domain>")
flag.PrintDefaults()
os.Exit(1)
}
domain := flag.Args()[0]
if verbose {
log.Printf("Looking up domain: %s", domain)
if dnsServer != "" {
log.Printf("Using DNS server: %s", dnsServer)
}
}
ips, err := lookupDomain(domain)
if err != nil {
log.Fatalf("Failed to lookup domain: %v", err)
}
for _, ip := range ips {
fmt.Println(ip)
}
txts, err := lookupTXTRecords(domain)
if err != nil {
log.Printf("Error looking up TXT records for %s: %v", domain, err)
} else {
for _, txt := range txts {
fmt.Println(txt)
}
}
// Gather domains from file (if provided) and from positional arguments.
var domains []string
if *filePath != "" {
f, err := os.Open(*filePath)
if err != nil {
color.Red("Error opening file %s: %v", *filePath, err)
os.Exit(1)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line != "" {
domains = append(domains, line)
}
}
if err := scanner.Err(); err != nil {
color.Red("Error reading file %s: %v", *filePath, err)
os.Exit(1)
}
}
// Append any domains provided as positional arguments.
domains = append(domains, flag.Args()...)
if len(domains) == 0 {
color.Yellow("No domains provided. Please supply domains as arguments or via the --file flag.\n")
flag.Usage()
os.Exit(1)
}
// Prepare to store full results.
var results []DomainTXT
// Compile a regex to capture key=value pairs (commonly used for domain verification).
re := regexp.MustCompile(`([\w\.\-]+)=([A-Za-z0-9\+\/=]+)`)
// For each domain, perform a DNS TXT lookup.
for _, domain := range domains {
txtRecords, err := net.LookupTXT(domain)
if err != nil {
color.Red("Error looking up TXT records for %s: %v", domain, err)
continue
}
// Process each TXT record.
for _, txt := range txtRecords {
// By default, ignore SPF records (those starting with "v=spf1") unless --include-spf is set.
if !*includeSPF && strings.HasPrefix(strings.ToLower(txt), "v=spf1") {
continue
}
key := ""
value := ""
match := re.FindStringSubmatch(txt)
if len(match) == 3 {
key = match[1]
value = match[2]
} else if *simple {
// If no key=value pattern is found and in simple mode,
// if the TXT record is a single word (no spaces or "="), use the entire record as the key.
if !strings.Contains(txt, " ") && !strings.Contains(txt, "=") {
key = txt
}
}
// If not in allRecords mode and key is empty, skip this record.
if !*allRecords && key == "" {
continue
}
results = append(results, DomainTXT{
Domain: domain,
TXT: txt,
Key: key,
Value: value,
})
}
}
// If the --simple flag is enabled, produce simplified output.
if *simple {
// Create a map to deduplicate simplified keys per domain.
simpleMap := make(map[string]map[string]bool)
for _, res := range results {
if res.Key == "" {
continue
}
simpleKey := simplifyKey(res.Key)
if simpleMap[res.Domain] == nil {
simpleMap[res.Domain] = make(map[string]bool)
}
simpleMap[res.Domain][simpleKey] = true
}
// Build a slice of SimpleResult.
var simpleResults []SimpleResult
for domain, keys := range simpleMap {
for key := range keys {
simpleResults = append(simpleResults, SimpleResult{
Domain: domain,
Key: key,
})
}
}
// Output the simplified results in the chosen format.
switch strings.ToLower(*outputFormat) {
case "pretty":
printSimplePretty(simpleResults)
case "json":
printSimpleJSON(simpleResults)
case "yaml":
printSimpleYAML(simpleResults)
case "csv":
printSimpleCSV(simpleResults)
default:
color.Yellow("Unknown output format '%s'. Defaulting to pretty.", *outputFormat)
printSimplePretty(simpleResults)
}
return
}
// Otherwise, output the full results.
switch strings.ToLower(*outputFormat) {
case "pretty":
printPretty(results)
case "json":
printJSON(results)
case "yaml":
printYAML(results)
case "csv":
printCSV(results)
default:
color.Yellow("Unknown output format '%s'. Defaulting to pretty.", *outputFormat)
printPretty(results)
}
}
// printPretty outputs the full results as a formatted table.
func printPretty(results []DomainTXT) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Domain", "TXT Record", "Key", "Value"})
headerColors := []tablewriter.Colors{
{tablewriter.FgHiBlueColor, tablewriter.Bold},
{tablewriter.FgHiBlueColor, tablewriter.Bold},
{tablewriter.FgHiBlueColor, tablewriter.Bold},
{tablewriter.FgHiBlueColor, tablewriter.Bold},
}
table.SetHeaderColor(headerColors...)
for _, r := range results {
table.Append([]string{r.Domain, r.TXT, r.Key, r.Value})
}
table.Render()
}
// printJSON outputs the full results in JSON format with syntax highlighting.
func printJSON(results []DomainTXT) {
b, err := json.MarshalIndent(results, "", " ")
if err != nil {
color.Red("Error marshalling JSON: %v", err)
return
}
jsonStr := string(b)
if !color.NoColor {
if err := quick.Highlight(os.Stdout, jsonStr, "json", "terminal", "monokai"); err != nil {
fmt.Println(jsonStr)
}
} else {
fmt.Println(jsonStr)
}
}
// printYAML outputs the full results in YAML format with syntax highlighting.
func printYAML(results []DomainTXT) {
b, err := yaml.Marshal(results)
if err != nil {
color.Red("Error marshalling YAML: %v", err)
return
}
yamlStr := string(b)
if !color.NoColor {
if err := quick.Highlight(os.Stdout, yamlStr, "yaml", "terminal", "monokai"); err != nil {
fmt.Println(yamlStr)
}
} else {
fmt.Println(yamlStr)
}
}
// printCSV outputs the full results in CSV format with optional syntax highlighting.
func printCSV(results []DomainTXT) {
var buf bytes.Buffer
writer := csv.NewWriter(&buf)
if err := writer.Write([]string{"Domain", "TXT Record", "Key", "Value"}); err != nil {
color.Red("Error writing CSV header: %v", err)
return
}
for _, r := range results {
if err := writer.Write([]string{r.Domain, r.TXT, r.Key, r.Value}); err != nil {
color.Red("Error writing CSV row: %v", err)
return
}
}
writer.Flush()
if err := writer.Error(); err != nil {
color.Red("Error flushing CSV: %v", err)
return
}
csvStr := buf.String()
if !color.NoColor {
if err := quick.Highlight(os.Stdout, csvStr, "csv", "terminal", "monokai"); err != nil {
fmt.Println(csvStr)
}
} else {
fmt.Println(csvStr)
}
}
// The following functions output simplified results.
func printSimplePretty(simpleResults []SimpleResult) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Domain", "Key"})
headerColors := []tablewriter.Colors{
{tablewriter.FgHiBlueColor, tablewriter.Bold},
{tablewriter.FgHiBlueColor, tablewriter.Bold},
}
table.SetHeaderColor(headerColors...)
for _, r := range simpleResults {
table.Append([]string{r.Domain, r.Key})
}
table.Render()
}
func printSimpleJSON(simpleResults []SimpleResult) {
b, err := json.MarshalIndent(simpleResults, "", " ")
if err != nil {
color.Red("Error marshalling JSON: %v", err)
return
}
jsonStr := string(b)
if !color.NoColor {
if err := quick.Highlight(os.Stdout, jsonStr, "json", "terminal", "monokai"); err != nil {
fmt.Println(jsonStr)
}
} else {
fmt.Println(jsonStr)
}
}
func printSimpleYAML(simpleResults []SimpleResult) {
b, err := yaml.Marshal(simpleResults)
if err != nil {
color.Red("Error marshalling YAML: %v", err)
return
}
yamlStr := string(b)
if !color.NoColor {
if err := quick.Highlight(os.Stdout, yamlStr, "yaml", "terminal", "monokai"); err != nil {
fmt.Println(yamlStr)
}
} else {
fmt.Println(yamlStr)
}
}
func printSimpleCSV(simpleResults []SimpleResult) {
var buf bytes.Buffer
writer := csv.NewWriter(&buf)
if err := writer.Write([]string{"Domain", "Key"}); err != nil {
color.Red("Error writing CSV header: %v", err)
return
}
for _, r := range simpleResults {
if err := writer.Write([]string{r.Domain, r.Key}); err != nil {
color.Red("Error writing CSV row: %v", err)
return
}
}
writer.Flush()
if err := writer.Error(); err != nil {
color.Red("Error flushing CSV: %v", err)
return
}
csvStr := buf.String()
if !color.NoColor {
if err := quick.Highlight(os.Stdout, csvStr, "csv", "terminal", "monokai"); err != nil {
fmt.Println(csvStr)
}
} else {
fmt.Println(csvStr)
}
}
func lookupDomain(domain string) ([]string, error) {
resolver := createResolver()
ips, err := resolver.LookupHost(context.Background(), domain)
if err != nil {
return nil, err
}
if verbose {
log.Printf("Resolved IPs: %v", ips)
}
return ips, nil
}
func lookupTXTRecords(domain string) ([]string, error) {
resolver := createResolver()
txts, err := resolver.LookupTXT(context.Background(), domain)
if err != nil {
return nil, err
}
if verbose {
log.Printf("Resolved TXT records: %v", txts)
}
return txts, nil
}
func createResolver() *net.Resolver {
if dnsServer != "" {
if !strings.Contains(dnsServer, ":") {
dnsServer += ":53"
}
return &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
d := net.Dialer{}
return d.DialContext(ctx, "udp", dnsServer)
},
}
}
return net.DefaultResolver
}