-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubhunter.go
More file actions
715 lines (605 loc) · 22.9 KB
/
Copy pathsubhunter.go
File metadata and controls
715 lines (605 loc) · 22.9 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
package main
import (
"bufio"
"crypto/rand"
"encoding/json"
"flag"
"fmt"
"io"
"math/big"
"net"
"net/http"
"os"
"os/exec"
"regexp"
"sort"
"strings"
"sync"
"time"
)
const (
Reset = "\033[0m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Purple = "\033[35m"
Cyan = "\033[36m"
Bold = "\033[1m"
)
// httpClient is a shared HTTP client for all requests to reuse connections.
var httpClient *http.Client
// init function to initialize package level variables
func init() {
httpClient = &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
},
}
}
type Config struct {
Domain string
Output string
Verbose bool
Check bool
CompareFile string
Timeout int
Threads int
UserAgents []string
Stats bool
Install bool
}
type SourceResult struct {
Source string
Subdomains []string
Error error
}
type CrtResponse struct {
NameValue string `json:"name_value"`
}
type BufferOverResponse struct {
FDNSA []string `json:"FDNS_A"`
}
func printBanner() {
banner := `
███████╗██╗ ██╗██████╗ ██╗ ██╗██╗ ██╗███╗ ██╗████████╗███████╗██████╗
██╔════╝██║ ██║██╔══██╗██║ ██║██║ ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗
███████╗██║ ██║██████╔╝███████║██║ ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝
╚════██║██║ ██║██╔══██╗██╔══██║██║ ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗
███████║╚██████╔╝██████╔╝██║ ██║╚██████╔╝██║ ╚████║ ██║ ███████╗██║ ██║
╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
` + Cyan + `Advanced Subdomain Enumeration Tool` + Reset + `
` + Yellow + `by: toprak_pt1` + Reset + `
`
fmt.Print(banner)
}
func log(config *Config, message string) {
if config.Verbose {
fmt.Printf("%s[*]%s %s\n", Blue+Bold, Reset, message)
}
}
// makeRequest performs an HTTP GET request and returns the body as a string.
func makeRequest(url string, config *Config) (string, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", fmt.Errorf("error creating request: %v", err)
}
// Set a random user agent
n, _ := rand.Int(rand.Reader, big.NewInt(int64(len(config.UserAgents))))
userAgent := config.UserAgents[n.Int64()]
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept", "*/*")
req.Header.Set("Connection", "keep-alive")
// Create a new HTTP client with timeout from config
client := &http.Client{
Timeout: time.Duration(config.Timeout) * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error reading response: %v", err)
}
return string(body), nil
}
// extractSubdomains uses regex to find subdomains in a given text body.
func extractSubdomains(body, domain string) []string {
re := regexp.MustCompile(`([a-zA-Z0-9.-]+\.` + regexp.QuoteMeta(domain) + `)`)
return re.FindAllString(body, -1)
}
func rapidDNS(domain string, config *Config) SourceResult {
log(config, "Scanning RapidDNS...")
url := fmt.Sprintf("https://rapiddns.io/subdomain/%s?full=1#result", domain)
resp, err := makeRequest(url, config)
if err != nil {
log(config, fmt.Sprintf("RapidDNS error: %v", err))
return SourceResult{Source: "RapidDNS", Error: err}
}
return SourceResult{Source: "RapidDNS", Subdomains: extractSubdomains(resp, domain)}
}
func riddler(domain string, config *Config) SourceResult {
log(config, "Scanning Riddler...")
url := fmt.Sprintf("https://riddler.io/search/exportcsv?q=pld:%s", domain)
resp, err := makeRequest(url, config)
if err != nil {
log(config, fmt.Sprintf("Riddler error: %v", err))
return SourceResult{Source: "Riddler", Error: err}
}
return SourceResult{Source: "Riddler", Subdomains: extractSubdomains(resp, domain)}
}
func jldcAnubis(domain string, config *Config) SourceResult {
log(config, "Scanning JLDC Anubis...")
url := fmt.Sprintf("https://jldc.me/anubis/subdomains/%s", domain)
resp, err := makeRequest(url, config)
if err != nil {
log(config, fmt.Sprintf("JLDC Anubis error: %v", err))
return SourceResult{Source: "JLDC Anubis", Error: err}
}
return SourceResult{Source: "JLDC Anubis", Subdomains: extractSubdomains(resp, domain)}
}
func crtSh(domain string, config *Config) SourceResult {
log(config, "Scanning crt.sh...")
url := fmt.Sprintf("https://crt.sh/?q=%%.%s&output=json", domain)
resp, err := makeRequest(url, config)
if err != nil {
log(config, fmt.Sprintf("crt.sh error: %v", err))
return SourceResult{Source: "crt.sh", Error: err}
}
var crtData []CrtResponse
// crt.sh can return a single object on error, so we handle that by ignoring unmarshal errors.
// The cleanAndFilter function will discard invalid entries anyway.
_ = json.Unmarshal([]byte(resp), &crtData)
var result []string
for _, entry := range crtData {
nameValue := strings.ReplaceAll(entry.NameValue, "*.", "")
lines := strings.Split(nameValue, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasSuffix(line, "."+domain) || line == domain {
result = append(result, line)
}
}
}
return SourceResult{Source: "crt.sh", Subdomains: result}
}
func bufferOver(domain string, config *Config) SourceResult {
log(config, "Scanning BufferOver...")
url := fmt.Sprintf("https://dns.bufferover.run/dns?q=.%s", domain)
resp, err := makeRequest(url, config)
if err != nil {
log(config, fmt.Sprintf("BufferOver error: %v", err))
return SourceResult{Source: "BufferOver", Error: err}
}
var bufferData BufferOverResponse
// Similar to crt.sh, ignore JSON parsing errors for now.
_ = json.Unmarshal([]byte(resp), &bufferData)
var result []string
for _, entry := range bufferData.FDNSA {
// The entry can be "ip,hostname"
parts := strings.Split(entry, ",")
if len(parts) == 2 {
result = append(result, strings.TrimSpace(parts[1]))
}
}
return SourceResult{Source: "BufferOver", Subdomains: result}
}
func urlScan(domain string, config *Config) SourceResult {
log(config, "Scanning URLScan...")
url := fmt.Sprintf("https://urlscan.io/domain/%s", domain)
resp, err := makeRequest(url, config)
if err != nil {
log(config, fmt.Sprintf("URLScan error: %v", err))
return SourceResult{Source: "URLScan", Error: err}
}
return SourceResult{Source: "URLScan", Subdomains: extractSubdomains(resp, domain)}
}
func runSubfinder(domain string, config *Config) SourceResult {
log(config, "Scanning with Subfinder...")
outFile := fmt.Sprintf("subfinder_%s.txt", domain)
cmd := exec.Command("subfinder", "-d", domain, "-all", "-silent", "-o", outFile)
err := cmd.Run()
if err != nil {
log(config, fmt.Sprintf("Subfinder error: %v", err))
return SourceResult{Source: "Subfinder", Error: err}
}
subs, err := readSubdomainsFromFile(outFile)
if err != nil {
return SourceResult{Source: "Subfinder", Error: err}
}
// Clean up after reading
os.Remove(outFile)
return SourceResult{Source: "Subfinder", Subdomains: subs}
}
func runSamoscout(domain string, config *Config) SourceResult {
log(config, "Scanning with Samoscout...")
outFile := fmt.Sprintf("samoscout_%s.txt", domain)
cmd := exec.Command("samoscout", "-d", domain, "-o", outFile)
err := cmd.Run()
if err != nil {
log(config, fmt.Sprintf("Samoscout error: %v", err))
// If samoscout isn't found or fails, don't crash, just log error
return SourceResult{Source: "Samoscout", Error: err}
}
subs, err := readSubdomainsFromFile(outFile)
if err != nil {
return SourceResult{Source: "Samoscout", Error: err}
}
// Clean up after reading
os.Remove(outFile)
return SourceResult{Source: "Samoscout", Subdomains: subs}
}
func cleanAndFilter(subdomains []string, domain string) []string {
unique := make(map[string]bool)
var result []string
// Regex to match valid hostnames for the given domain.
// This is a bit more strict than the original.
domainRegex := regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*` + regexp.QuoteMeta(domain) + `$`)
for _, sub := range subdomains {
cleaned := strings.TrimSpace(sub)
cleaned = strings.ToLower(cleaned)
cleaned = strings.TrimPrefix(cleaned, "*.")
cleaned = strings.TrimSuffix(cleaned, ".")
if domainRegex.MatchString(cleaned) && !unique[cleaned] {
unique[cleaned] = true
result = append(result, cleaned)
}
}
sort.Strings(result)
return result
}
func readSubdomainsFromFile(filename string) ([]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
var subdomains []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
sub := strings.TrimSpace(scanner.Text())
if sub != "" {
subdomains = append(subdomains, sub)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return subdomains, nil
}
func compareSubdomains(ours, theirs []string) (onlyOurs, onlyTheirs, common []string) {
ourSet := make(map[string]bool)
theirSet := make(map[string]bool)
for _, sub := range ours {
ourSet[strings.ToLower(sub)] = true
}
for _, sub := range theirs {
sub = strings.ToLower(sub)
theirSet[sub] = true
if ourSet[sub] {
common = append(common, sub)
} else {
onlyTheirs = append(onlyTheirs, sub)
}
}
for _, sub := range ours {
sub = strings.ToLower(sub)
if !theirSet[sub] {
onlyOurs = append(onlyOurs, sub)
}
}
sort.Strings(onlyOurs)
sort.Strings(onlyTheirs)
sort.Strings(common)
return onlyOurs, onlyTheirs, common
}
func writeComparisonResults(ours, theirs, common []string, domain string, config *Config) error {
// Write our unique subdomains to the main output file
if err := writeResults(ours, config.Output); err != nil {
return fmt.Errorf("error writing our subdomains: %v", err)
}
timestamp := time.Now().Format("20060102_150405")
summaryFile := fmt.Sprintf("%s_%s_summary.txt", strings.TrimSuffix(config.Output, ".txt"), timestamp)
summary := fmt.Sprintf(`Subdomain Comparison Summary
==========================
Date: %s
Domain: %s
SubHunter found: %d subdomains
Other tool found: %d subdomains
Unique to SubHunter: %d
Unique to other tool: %d
Common subdomains: %d
`,
time.Now().Format("2006-01-02 15:04:05"),
domain,
len(ours)+len(common),
len(theirs)+len(common),
len(ours),
len(theirs),
len(common),
)
if err := os.WriteFile(summaryFile, []byte(summary), 0644); err != nil {
return fmt.Errorf("error writing summary: %v", err)
}
return nil
}
func writeResults(results []string, filename string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, result := range results {
if _, err := writer.WriteString(result + "\n"); err != nil {
return err
}
}
return writer.Flush()
}
func checkRequiredTools() error {
tools := []string{"curl", "wget", "subfinder"}
var missing []string
for _, tool := range tools {
_, err := exec.LookPath(tool)
if err != nil {
missing = append(missing, tool)
}
}
// Samoscout might not be in path, it's optional but good to check
_, err := exec.LookPath("samoscout")
if err != nil {
fmt.Printf("%s[*]%s Note: samoscout is missing but optional\n", Blue+Bold, Reset)
}
if len(missing) > 0 {
return fmt.Errorf("required tools not found: %v", missing)
}
return nil
}
func runCheck() {
fmt.Printf("%s[+]%s Running system check...\n", Green+Bold, Reset)
// Check required tools
err := checkRequiredTools()
if err != nil {
fmt.Printf("%s[-]%s %v\n", Red+Bold, Reset, err)
} else {
fmt.Printf("%s[+]%s All required tools are installed\n", Green+Bold, Reset)
}
// Check internet connection
tr := &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
client := &http.Client{Transport: tr}
_, err = client.Get("https://www.google.com")
if err != nil {
fmt.Printf("%s[-]%s No internet connection: %v\n", Red+Bold, Reset, err)
} else {
fmt.Printf("%s[+]%s Internet connection OK\n", Green+Bold, Reset)
}
// Check DNS resolution
_, err = net.LookupHost("google.com")
if err != nil {
fmt.Printf("%s[-]%s DNS resolution failed: %v\n", Red+Bold, Reset, err)
} else {
fmt.Printf("%s[+]%s DNS resolution OK\n", Green+Bold, Reset)
}
fmt.Printf("\n%s[+]%s System check completed!\n", Green+Bold, Reset)
}
func main() {
var config Config
var help bool
// Initialize default configuration
config.UserAgents = []string{
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
}
// Define flags
flag.StringVar(&config.Domain, "d", "", "Target domain")
flag.StringVar(&config.Domain, "domain", "", "Target domain")
flag.StringVar(&config.Output, "o", "", "Output file")
flag.StringVar(&config.Output, "output", "", "Output file")
flag.BoolVar(&config.Verbose, "v", false, "Verbose output")
flag.BoolVar(&config.Verbose, "verbose", false, "Verbose output")
flag.BoolVar(&config.Check, "check", false, "Run system check")
flag.BoolVar(&config.Check, "c", false, "Run system check (shorthand)")
flag.StringVar(&config.CompareFile, "compare", "", "Compare with subdomains from file")
flag.IntVar(&config.Timeout, "timeout", 30, "HTTP request timeout in seconds")
flag.IntVar(&config.Threads, "t", 5, "Number of concurrent threads")
flag.BoolVar(&config.Stats, "stats", false, "Print stats of subdomains found per source")
flag.BoolVar(&config.Install, "install", false, "Install required external tools (subfinder, samoscout)")
flag.BoolVar(&help, "h", false, "Show this help message")
flag.BoolVar(&help, "help", false, "Show this help message")
// Custom usage message
flag.Usage = func() {
printBanner()
fmt.Fprintf(os.Stdout, "\n%sA fast and simple subdomain enumeration tool by toprak_pt1.%s\n", Cyan, Reset)
fmt.Fprintf(os.Stdout, "\n%sUsage:%s\n %s -d <domain> [flags]\n", Yellow, Reset, os.Args[0])
fmt.Fprintf(os.Stdout, "\n%sRequired Flags:%s\n", Yellow, Reset)
fmt.Fprintf(os.Stdout, " -d, --domain string Target domain to scan\n")
fmt.Fprintf(os.Stdout, "\n%sOptional Flags:%s\n", Yellow, Reset)
fmt.Fprintf(os.Stdout, " -o, --output string Output file (default: <domain>_<timestamp>.txt)\n")
fmt.Fprintf(os.Stdout, " -v, --verbose Enable verbose output\n")
fmt.Fprintf(os.Stdout, " -t, --threads int Number of concurrent threads (default 5)\n")
fmt.Fprintf(os.Stdout, " --timeout int HTTP request timeout in seconds (default 30)\n")
fmt.Fprintf(os.Stdout, " -c, --check Run system check before scanning\n")
fmt.Fprintf(os.Stdout, " --compare string Compare with subdomains from file\n")
fmt.Fprintf(os.Stdout, " --stats Show subdomains found by each source\n")
fmt.Fprintf(os.Stdout, " --install Install requisite external tools (subfinder, samoscout)\n")
fmt.Fprintf(os.Stdout, " -h, --help Show this help message\n")
fmt.Fprintf(os.Stdout, "\n%sExamples:%s\n", Yellow, Reset)
fmt.Fprintf(os.Stdout, " %s -d example.com -o subs.txt -v\n", os.Args[0])
fmt.Fprintf(os.Stdout, " %s -d example.com -t 10 --timeout 60\n", os.Args[0])
fmt.Fprintf(os.Stdout, " %s --check\n\n", os.Args[0])
}
flag.Parse()
if help {
flag.Usage()
os.Exit(0)
}
if config.Install {
fmt.Printf("%s[+]%s Installing required external tools...\n", Green+Bold, Reset)
fmt.Printf("%s[*]%s Installing Samoscout...\n", Blue+Bold, Reset)
cmdSamo := exec.Command("go", "install", "github.com/samogod/samoscout@latest")
cmdSamo.Stdout = os.Stdout
cmdSamo.Stderr = os.Stderr
if err := cmdSamo.Run(); err != nil {
fmt.Printf("%s[-]%s Failed to install Samoscout: %v\n", Red+Bold, Reset, err)
} else {
fmt.Printf("%s[+]%s Samoscout installed successfully.\n", Green+Bold, Reset)
}
fmt.Printf("%s[*]%s Installing Subfinder...\n", Blue+Bold, Reset)
cmdSubf := exec.Command("go", "install", "-v", "github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest")
cmdSubf.Stdout = os.Stdout
cmdSubf.Stderr = os.Stderr
if err := cmdSubf.Run(); err != nil {
fmt.Printf("%s[-]%s Failed to install Subfinder: %v\n", Red+Bold, Reset, err)
} else {
fmt.Printf("%s[+]%s Subfinder installed successfully.\n", Green+Bold, Reset)
}
fmt.Printf("\n%s[+]%s Make sure your Go bin directory is in your PATH: export PATH=$PATH:$(go env GOPATH)/bin\n", Green+Bold, Reset)
os.Exit(0)
}
// Run system check if requested
if config.Check {
runCheck()
os.Exit(0)
}
printBanner()
// Set default output filename if not provided
if config.Output == "" {
config.Output = fmt.Sprintf("subhunter_%s.txt", config.Domain)
}
// Normalize domain (remove http://, https://, and trailing slashes)
config.Domain = strings.TrimPrefix(strings.TrimPrefix(config.Domain, "http://"), "https://")
config.Domain = strings.TrimRight(config.Domain, "/")
fmt.Printf("%s[+]%s Target: %s%s%s\n", Green+Bold, Reset, Yellow, config.Domain, Reset)
fmt.Printf("%s[+]%s Output: %s%s%s\n", Green+Bold, Reset, Yellow, config.Output, Reset)
fmt.Printf("%s[+]%s Threads: %s%d%s\n", Green+Bold, Reset, Yellow, config.Threads, Reset)
fmt.Printf("%s[+]%s Timeout: %s%d seconds%s\n", Green+Bold, Reset, Yellow, config.Timeout, Reset)
fmt.Printf("%s[+]%s Stats Mode: %s%t%s\n", Green+Bold, Reset, Yellow, config.Stats, Reset)
fmt.Printf("%s[+]%s Start Time: %s%s%s\n", Green+Bold, Reset, Yellow, time.Now().Format("2006-01-02 15:04:05"), Reset)
fmt.Println()
startTime := time.Now()
sources := []func(string, *Config) SourceResult{
rapidDNS,
riddler,
jldcAnubis,
crtSh,
bufferOver,
urlScan,
runSubfinder,
runSamoscout,
}
var wg sync.WaitGroup
resultsChan := make(chan SourceResult, len(sources))
for _, source := range sources {
wg.Add(1)
go func(src func(string, *Config) SourceResult) {
defer wg.Done()
resultsChan <- src(config.Domain, &config)
}(source)
}
// This goroutine waits for all workers to finish and then closes the channel.
go func() {
wg.Wait()
close(resultsChan)
}()
var allSubdomains []string
statsMap := make(map[string]int)
for res := range resultsChan {
if res.Error == nil {
statsMap[res.Source] = len(res.Subdomains)
allSubdomains = append(allSubdomains, res.Subdomains...)
} else {
statsMap[res.Source] = 0
}
}
log(&config, "Merging and cleaning results...")
cleanResults := cleanAndFilter(allSubdomains, config.Domain)
// If compare file is provided, compare the results
if config.CompareFile != "" {
log(&config, fmt.Sprintf("Comparing with subdomains from: %s", config.CompareFile))
// Read subdomains from the comparison file
otherSubdomains, err := readSubdomainsFromFile(config.CompareFile)
if err != nil {
fmt.Printf("%s[!]%s Error reading comparison file: %v%s\n", Red+Bold, Reset, err, Reset)
os.Exit(1)
}
// Compare the subdomains
onlyOurs, onlyTheirs, common := compareSubdomains(cleanResults, otherSubdomains)
// Write comparison results
if err := writeComparisonResults(onlyOurs, onlyTheirs, common, config.Domain, &config); err != nil {
fmt.Printf("%s[!]%s Error writing comparison results: %v%s\n", Red+Bold, Reset, err, Reset)
os.Exit(1)
}
// Print comparison summary
fmt.Printf("\n%s[+]%s Comparison Results:%s\n", Green+Bold, Reset, Reset)
fmt.Printf("%s[+]%s SubHunter found: %s%d%s subdomains\n", Green+Bold, Reset, Yellow, len(cleanResults), Reset)
fmt.Printf("%s[+]%s Other tool found: %s%d%s subdomains\n", Green+Bold, Reset, Yellow, len(otherSubdomains), Reset)
fmt.Printf("%s[+]%s Unique to SubHunter: %s%d%s\n", Green+Bold, Reset, Yellow, len(onlyOurs), Reset)
fmt.Printf("%s[+]%s Unique to other tool: %s%d%s\n", Green+Bold, Reset, Yellow, len(onlyTheirs), Reset)
fmt.Printf("%s[+]%s Common subdomains: %s%d%s\n", Green+Bold, Reset, Yellow, len(common), Reset)
if config.Verbose {
if len(onlyOurs) > 0 {
fmt.Printf("\n%s[*]%s Subdomains only found by SubHunter:%s\n", Blue+Bold, Reset, Reset)
for i, sub := range onlyOurs {
fmt.Printf("%s%3d%s %s\n", Cyan, i+1, Reset, sub)
}
}
if len(onlyTheirs) > 0 {
fmt.Printf("\n%s[*]%s Subdomains only found in %s:%s\n", Blue+Bold, Reset, config.CompareFile, Reset)
for i, sub := range onlyTheirs {
fmt.Printf("%s%3d%s %s\n", Cyan, i+1, Reset, sub)
}
}
if len(common) > 0 {
fmt.Printf("\n%s[*]%s Common subdomains:%s\n", Blue+Bold, Reset, Reset)
for i, sub := range common {
fmt.Printf("%s%3d%s %s\n", Cyan, i+1, Reset, sub)
}
}
}
fmt.Printf("\n%s[+]%s Comparison results saved to files with timestamp: %s\n",
Green+Bold, Reset, time.Now().Format("20060102_150405"))
}
// Write results to file
if err := writeResults(cleanResults, config.Output); err != nil {
fmt.Printf("%s[!]%s Error writing results: %v%s\n", Red+Bold, Reset, err, Reset)
os.Exit(1)
}
elapsed := time.Since(startTime)
fmt.Printf("\n%s[+]%s Scan completed in %s%.2f seconds%s\n", Green+Bold, Reset, Yellow, elapsed.Seconds(), Reset)
fmt.Printf("%s[+]%s Found %s%d%s unique subdomains\n", Green+Bold, Reset, Yellow, len(cleanResults), Reset)
fmt.Printf("%s[+]%s Results saved to: %s%s%s\n", Green+Bold, Reset, Yellow, config.Output, Reset)
// Calculate and show the rate
if elapsed.Seconds() > 0 {
rate := float64(len(cleanResults)) / elapsed.Seconds()
fmt.Printf("%s[+]%s Processing rate: %s%.2f subdomains/second%s\n",
Green+Bold, Reset, Yellow, rate, Reset)
}
if config.Stats {
fmt.Printf("\n%s[+]%s Sources Statistics:%s\n", Green+Bold, Reset, Reset)
for source, count := range statsMap {
fmt.Printf("%s[*]%s %s%20s%s : %s%d%s subdomains\n",
Blue+Bold, Reset, Cyan, source, Reset, Yellow, count, Reset)
}
}
if config.Verbose {
fmt.Printf("\n%s[*]%s Results:%s\n", Blue+Bold, Reset, Reset)
for i, subdomain := range cleanResults {
fmt.Printf("%s%3d%s %s\n", Cyan, i+1, Reset, subdomain)
}
}
}