This repository has been archived by the owner on Feb 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathnodesub.js
1700 lines (1474 loc) · 65.1 KB
/
nodesub.js
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const dns = require('dns');
const fs = require('fs');
const axios = require('axios');
const cheerio = require('cheerio');
const fastGlob = require('fast-glob');
const Bottleneck = require('bottleneck');
const Spinner = require('cli-spinner').Spinner;
const figlet = require('figlet');
const cloudscraper = require('cloudscraper');
const subquest = require('subquest');
const net = require('net');
const forge = require('node-forge');
const https = require('https');
const http = require('http');
const DnsSocket = require('dns-socket');
const {
promisify
} = require('util');
const FormData = require('form-data');
const resolve4 = promisify(dns.resolve4);
const os = require('os');
const {
v4: uuidv4
} = require('uuid');
const {
exec
} = require('child_process');
const {
createObjectCsvWriter
} = require('csv-writer');
const PDFDocument = require('pdfkit');
const {
program
} = require('commander');
const clc = require('cli-color');
const URL = require('url').URL;
const path = require('path');
const rateLimit = require('axios-rate-limit');
// Proxy
const HttpProxyAgent = require('http-proxy-agent');
const HttpsProxyAgent = require('https-proxy-agent');
const SocksProxyAgent = require('socks-proxy-agent');
const version = '0.1.2';
const codename = 'pikpikcu';
program
.description('Nodesub is a command-line tool for finding subdomains in bug bounty programs.')
.option('-u, --url <domain>', 'Main domain')
.option('-l, --list <file>', 'File with list of domains')
.option('-c, --cidr <cidr/file>', 'Perform subdomain enumeration using CIDR')
.option('-a, --asn <asn/file>', 'Perform subdomain enumeration using ASN')
.option('-dns, --dnsenum', 'Enable DNS Enumeration (if you enable this the enumeration process will be slow)')
.option('-rl, --rate-limit <limit>', 'Rate limit for DNS requests (requests per second)', '0')
.option('-ip, --ips', 'Ekstrak IPs in Subdomain Resolved')
.option('-wl, --wildcard', 'Filter subdomains by wildcard DNS resolution Default:(False)')
.option('-r, --recursive', 'Enable recursive subdomain enumeration')
.option('-P, --permutations', 'Enable subdomain permutations')
.option('-re,--resolver <file>', 'File with list of resolvers')
.option('-w, --wordlist <file>', 'Wordlist file')
.option('-p, --proxy <proxy>', 'Proxy URL')
.option('-pa, --proxy-auth <username:password>', 'Proxy authentication credentials')
.option('-s, --size <size>', 'Max old space size heap Default:(10048 MB)')
.option('-d, --debug', 'Show DNS resolution details')
.option('-v, --verbose', 'Enable verbose output')
.option('-o, --output <file>', 'Output file')
.option('-f, --format <format>', 'Output file format (txt, json, csv, pdf)', 'txt');
program.parse(process.argv);
const argv = program.opts();
const spinner = new Spinner();
spinner.setSpinnerString('|/-\\');
// Set max old space size for JavaScript heap
const defaultMaxOldSpaceSize = 10048; // Default heap size in MB
// Create an instance of axios with rate limiting
const axiosWithRateLimit = rateLimit(axios.create(), {
maxRequests: 10, // Set the maximum number of requests per second
perMilliseconds: 10000, // Set the time window in milliseconds
});
// Set Limit Shodan
let lastShodanCallTime = null;
let shodanCallCount = 0;
const shodanRateLimit = 2; // Limit on the number of summons per second
const shodanRateLimitInterval = 1000; // Time range in milliseconds (for example, 1000 ms = 1 second)
// Function to execute shell command and get the output
function runCommand(command) {
return new Promise((resolve, reject) => {
exec(command, (error, stdout) => {
if (error) {
reject(error);
} else {
resolve(stdout.trim());
}
});
});
}
function isSubfinderInstalled() {
try {
runCommand('subfinder -h');
return true;
} catch (error) {
return false;
}
}
function isAmassInstalled() {
try {
runCommand('amass -h');
return true;
} catch (error) {
return false;
}
}
function isAlteryxInstalled() {
try {
runCommand('alterx --version');
return true;
} catch (error) {
return false;
}
}
function installAlteryx() {
try {
runCommand('go install github.com/projectdiscovery/alterx/cmd/alterx@latest');
console.log(`${clc.green('[V]')} Alteryx installed successfully`);
} catch (error) {
console.error(`${clc.red('[!]')} Error installing Alteryx:`, error);
}
}
// Function to set the delay (delay)
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// Function to create directory
function createDirectory(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, {
recursive: true
});
}
}
// Function to read wordlist file
function readWordlistFile(wordlist) {
try {
const data = fs.readFileSync(wordlist, 'utf8');
const lines = data.split('\n').filter(Boolean); // Filter out empty lines
return lines;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error reading wordlist file:`, error);
return [];
}
}
// Function to filter subdomains by wildcard DNS resolution
function filterWildcardSubdomains(subdomains) {
if (argv.wildcard) {
return subdomains;
}
return subdomains.filter(({
isActive
}) => isActive);
}
// Function to Extension Output file
function getOutputFileExtension(format) {
if (format === 'txt') {
return 'txt';
} else if (format === 'json') {
return 'json';
} else if (format === 'csv') {
return 'csv';
} else if (format === 'pdf') {
return 'pdf';
} else {
throw new Error('Invalid output file format');
}
}
// Function to get the current user's home directory
async function getHomeDirectory() {
let homeDirectory = '';
if (process.platform === 'win32') {
homeDirectory = await runCommand('echo %USERPROFILE%');
} else {
homeDirectory = await runCommand('echo $HOME');
}
return homeDirectory;
}
// Function to download file
async function downloadFile(url, filePath) {
const response = await axios.get(url, {
responseType: 'stream'
});
const writer = fs.createWriteStream(filePath);
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}
// Fungsi untuk membuat HttpsProxyAgent berdasarkan URL proxy
function createProxyAgent(proxyUrl) {
const proxy = url.parse(proxyUrl);
const agent = new HttpsProxyAgent(proxy);
return agent;
}
// Fungsi untuk mengeksekusi permintaan HTTP dengan proxy
async function executeRequest(subdomain, proxy, agent) {
try {
const requestOptions = {
method: 'GET',
url: `https://${subdomain}`,
httpsAgent: agent,
};
if (proxy) {
requestOptions.headers = { 'X-Custom-Proxy': proxy };
}
const response = await axios(requestOptions);
console.log(`Requests to domain: ${subdomain}`);
// Proses respons
if (proxy) {
const proxyHost = new url.URL(proxy).hostname;
const proxyPort = new url.URL(proxy).port || (new url.URL(proxy).protocol === 'http:' ? 80 : 443);
const subdomainWithoutProxy = subdomain.replace(`.${proxyHost}`, '');
const proxyHistoryUrl = `http://${proxyHost}:${proxyPort}/subdomain/${subdomainWithoutProxy}`;
// Kirim permintaan GET ke URL proxyHistoryUrl menggunakan agent HTTP
const proxyAgent = new http.Agent({ keepAlive: true });
const proxyRequestOptions = {
method: 'GET',
url: proxyHistoryUrl,
agent: proxyAgent,
};
await axios(proxyRequestOptions);
}
} catch (error) {
console.error(`Failed to execute HTTP request with proxy: ${error.message}`);
}
}
// Function to read API keys from config.ini file
function readApiKeys() {
const configPath = path.join(process.env.HOME, '.config', 'nodesub', 'config.ini');
const configData = fs.readFileSync(configPath, 'utf8');
const lines = configData.split('\n').filter(Boolean);
const apiKeys = {};
for (const line of lines) {
const [key, value] = line.split('=');
apiKeys[key] = value.replace(/"/g, '').trim();
}
return apiKeys;
}
// Function to check if dnsrecon is installed
async function isDnsreconInstalled() {
try {
await runCommand('dnsrecon -h');
return true;
} catch (error) {
return false;
}
}
// Function to install dnsrecon
async function installDnsrecon() {
try {
console.log('Installing dnsrecon...');
await runCommand('pip3 install dnsrecon');
console.log('dnsrecon installed successfully.');
} catch (error) {
console.error('Error installing dnsrecon:', error);
}
}
// Function to run dnsrecon and get the list of subdomains
async function runDnsrecon(domain) {
try {
const isInstalled = await isDnsreconInstalled();
if (!isInstalled) {
await installDnsrecon();
if (!await isDnsreconInstalled()) {
console.error('Failed to install dnsrecon. Please make sure dnsrecon is installed manually.');
return [];
}
}
const commands = [
`dnsrecon -d ${domain} -t zonewalk 2>&1`,
`dnsrecon -d ${domain} -k 2>&1`,
`dnsrecon -d ${domain} -y -k -b --lifetime 10 --threads 15 -w 2>&1`,
];
const subdomains = [];
for (const command of commands) {
const output = await runCommand(command);
const lines = output.split('\n');
const extractedSubdomains = lines.map(line => {
const match = line.match(/(^|\s)([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}(\s|$)/g);
if (match) {
return match[0].trim();
}
}).filter(Boolean);
subdomains.push(...extractedSubdomains);
}
return subdomains;
} catch (error) {
console.error(clc.red('\n[!] Error running dnsrecon:'), error.response ? error.response.statusText : error.message);
return [];
}
}
// generateCombinations
function generateCombinations(chars, length) {
const combinations = [];
function generateCombination(currentCombination) {
if (currentCombination.length === length) {
combinations.push(currentCombination);
return;
}
for (let i = 0; i < chars.length; i++) {
const newCombination = currentCombination + chars[i];
generateCombination(newCombination);
}
}
generateCombination('');
return combinations;
}
// DnsServers
async function getDnsServers() {
const resolveFilePath = path.join(os.homedir(), '.config', 'nodesub', 'resolvers.txt');
const resolvConf = await fs.promises.readFile(resolveFilePath, 'utf-8');
const dnsServers = [];
const lines = resolvConf.split('\n');
for (const line of lines) {
if (line.startsWith('nameserver')) {
const parts = line.split(' ');
const dnsServer = parts[1].trim();
dnsServers.push(dnsServer);
}
}
return dnsServers;
}
// subquest
async function getSubDomains(domain) {
try {
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789.-_';
const dictionary = generateCombinations(chars, 3);
fs.writeFileSync('dictionary.txt', dictionary.join('\n'));
const dnsServers = await getDnsServers();
const enumOptions = {
host: domain,
rateLimit: 500,
port: Array.from({
length: 65535
}, (_, index) => (index + 1).toString()),
dnsServer: dnsServers,
recursive: false,
dictionary: 'dictionary.txt',
};
const subdomains = await subquest.getSubDomains(enumOptions);
return subdomains || [];
} finally {
fs.unlinkSync('dictionary.txt');
}
}
// Subdomain enumeration with SecurityTrails
async function runSecurityTrails(domain, securityTrailsApiKey) {
try {
const curlCommand = `curl "https://api.securitytrails.com/v1/domain/${domain}/subdomains" -H 'apikey: ${securityTrailsApiKey}'`;
const response = await runCommand(curlCommand);
const data = JSON.parse(response);
const subdomains = data.subdomains.map(subdomain => `${subdomain}.${domain}`);
const uniqueSubdomains = Array.from(new Set(subdomains));
uniqueSubdomains.sort();
return uniqueSubdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running SecurityTrails:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Anubis DB Subdomain Enumerations
async function runAnubisDB(domain) {
try {
const apiUrl = `https://jonlu.ca/anubis/subdomains/${domain}`;
const response = await axiosWithRateLimit.get(apiUrl);
const subdomains = response.data;
subdomains.sort();
return subdomains;
} catch (error) {
console.error(clc.red('\n[!] Error running anubis:'), error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to run dnsenum and get the list of subdomains
async function runDnsenum(domain) {
try {
const commands = [
`dnsenum ${domain} --enum --threads 5 -s 15 -w --zonewalk`,
`dnsenum ${domain} --recursion --noreverse`,
//`dnsenum ${domain} --dnsserver NS`,
];
const outputs = await Promise.all(commands.map(command => runCommand(command)));
const subdomains = outputs.flatMap(output => {
const lines = output.split('\n');
return lines.map(line => {
const match = line.match(/^(\*\.)?([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/g);
if (match) {
return match[0];
}
}).filter(Boolean);
});
return subdomains;
} catch (error) {
console.error(clc.red('\n[!] Error running dnsenum:'), error.response ? error.response.statusText : error.message);
return [];
}
}
// runBaiduSearch
async function runBaiduSearch(domain, page = 1) {
try {
const url = new URL(`https://www.baidu.com/s?wd=site%3A*.${domain}&pn=${(page - 1) * 10}`);
//const response = await axios.get(url.href);
const response = await axiosWithRateLimit.get(url.href);
const $ = cheerio.load(response.data);
const subdomains = new Set();
// Get all search results
$('.c-container').each((index, element) => {
const mu = $(element).attr('mu=');
if (mu) {
const subdomainMatches = mu.match(/\/\/([^/]+)\./);
if (subdomainMatches && subdomainMatches.length > 1) {
const subdomain = subdomainMatches[1];
subdomains.add(subdomain);
}
}
});
// Sort subdomains
const sortedSubdomains = Array.from(subdomains).sort();
return sortedSubdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running Baidu search:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to run Bing search and get the list of subdomains
async function runBing(domain, first) {
try {
const url = `https://www.bing.com/search?q=${domain}+-www&sp=-1&ghc=1&lq=0&pq=${domain}+-www&sc=0-25&qs=n&sk=&cvid=10BD11349D554525AB05E3626258B00E&ghsh=0&ghacc=0&ghpl=&FPIG=955CADBBFF1D4009AF95D073654A5BFA%2c9CE86F91D3BE436C983233A8216C0F50&first=${first}&FORM=PERE1`;
//const response = await axios.get(url);
const response = await axiosWithRateLimit.get(url);
const $ = cheerio.load(response.data);
const subdomains = [];
const subdomainRegex = /(?:https?:\/\/)?(([^/]+))\//;
$('.b_algo').each((index, element) => {
const link = $(element).find('a').attr('href');
const subdomainMatch = link.match(subdomainRegex);
if (subdomainMatch && subdomainMatch[0].includes(domain)) {
const subdomain = subdomainMatch[1];
subdomains.push(subdomain);
}
});
// Remove duplicates and sort subdomains
const uniqueSubdomains = Array.from(new Set(subdomains));
uniqueSubdomains.sort();
// Check if there are more pages and fetch them recursively
const nextLink = $('.sb_pagN').find('a').attr('href');
if (nextLink) {
const nextPage = nextLink.split('&first=')[1];
const nextPageSubdomains = await runBing(domain, nextPage);
uniqueSubdomains.push(...nextPageSubdomains);
}
return uniqueSubdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running Bing search:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to run crt.sh and fetch subdomains
async function runCrtsh(domain) {
try {
const urls = [
`https://crt.sh/?q=%.${domain}`,
`https://crt.sh/?q=%.%.${domain}`,
`https://crt.sh/?q=%.%.%.${domain}`,
`https://crt.sh/?q=%.%.%.%.${domain}`,
`https://crt.sh/?q=%.%.%.%.%.${domain}`,
`https://crt.sh/?q=%.%.%.%.%.%.${domain}`,
];
const subdomains = [];
for (const url of urls) {
const response = await axiosWithRateLimit.get(url, {
maxRedirects: 0,
timeout: 70000 // Set the timeout value according to your needs
});
const $ = cheerio.load(response.data);
// Get all subdomains
$('table tr').each((index, element) => {
const subdomainText = $(element).find('td:nth-child(5)').text().trim();
const subdomainMatches = subdomainText.match(/([a-zA-Z0-9][a-zA-Z0-9-]{1,61}\.[a-zA-Z\.]{2,})/);
if (subdomainMatches && subdomainMatches.length > 0) {
const subdomain = subdomainMatches[0];
if (subdomain.endsWith(domain)) { // ensure the subdomain belongs to the main domain
subdomains.push(subdomain);
}
}
});
}
// Sort and remove duplicates from subdomains
const uniqueSubdomains = Array.from(new Set(subdomains));
uniqueSubdomains.sort();
return uniqueSubdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running crt.sh:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to fetch subdomains from AlienVault OTX API
async function fetchAlienVaultSubdomains(domain) {
try {
const url = `https://otx.alienvault.com/api/v1/indicators/domain/${domain}/passive_dns`;
const response = await axios.get(url);
const {
data
} = response;
// Extract subdomains from the response
const subdomains = data.passive_dns.map((record) => record.hostname);
// Sort and remove duplicates from subdomains
const uniqueSubdomains = Array.from(new Set(subdomains));
uniqueSubdomains.sort();
return uniqueSubdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error fetching subdomains from AlienVault OTX:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Subdomain enumeration with Shodan
async function runShodan(domain, shodanApiKey) {
try {
// Rate limit Shodan requests
if (lastShodanCallTime) {
const elapsedTime = Date.now() - lastShodanCallTime;
if (elapsedTime < shodanRateLimitInterval) {
await delay(shodanRateLimitInterval - elapsedTime);
}
}
const url = `https://api.shodan.io/dns/domain/${domain}?key=${shodanApiKey}`;
const response = await axios.get(url);
const data = response.data;
lastShodanCallTime = Date.now();
shodanCallCount++;
const subdomains = data.subdomains.map(subdomain => `${subdomain}."${domain}"`);
// Sort and remove duplicates from subdomains
const uniqueSubdomains = Array.from(new Set(subdomains));
uniqueSubdomains.sort();
return uniqueSubdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running Shodan:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to run Amass and get the list of subdomains
async function runAmass(domain) {
try {
const isInstalled = isAmassInstalled();
if (!isInstalled) {
console.log(`${clc.red('\n[!]')} Amass is not installed. Installing Amass...`);
await runCommand('go install -v github.com/owasp-amass/amass/v3/...@master');
}
const commands = [
`amass enum -d "${domain}" -passive`,
//`amass enum -d "${domain}" -active`,
];
const output = await Promise.all(commands.map(runCommand));
const subdomains = output.join('\n').split('\n');
return subdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running Amass:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to run Subfinder and get the list of subdomains
async function runSubfinder(domain) {
try {
const isInstalled = isSubfinderInstalled();
if (!isInstalled) {
console.log(`${clc.red('\n[!]')} Subfinder is not installed. Installing Subfinder...`);
await runCommand('go install -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest');
}
const commands = [
`subfinder -all -d "${domain}" -rl 100 -recursive`,
`subfinder -all -d "${domain}" -rl 1000 -active`,
//`echo "${domain}" | subfinder -silent -all -recursive | subfinder -rl 1000 `,
];
const output = await Promise.all(commands.map(runCommand));
const subdomains = output.join('\n').split('\n');
return subdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running Subfinder:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to perform subdomain permutations using AlterX
async function generatePermutations(domain) {
try {
const subdomains = [];
if (!isAlteryxInstalled()) {
console.log(`${clc.red('\n[!]')} Alteryx is not installed. Installing Alteryx...`);
installAlteryx();
}
const commands = [
`echo "${domain}" | alterx`,
`echo "${domain}" | alterx -enrich -p '{{word}}.{{suffix}}'`,
`echo "${domain}" | alterx -enrich -p '{{word}}-{{year}}.{{suffix}}'`,
`echo "${domain}" | alterx -enrich`,
`echo "${domain}" | alterx -enrich -p '{{number}}.{{suffix}}'`,
`echo "${domain}" | alterx -enrich -p '{{number}}-{{word}}.{{suffix}}'`
];
const output = await Promise.all(commands.map(runCommand));
output.forEach(result => {
subdomains.push(...result.trim().split('\n'));
});
return subdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running AlterX:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to execute DNS query and get the IP address
async function resolveDomain(subdomain) {
try {
if (!argv.resolver) {
// If argv.resolver is not provided, directly pass empty resolver
const addresses = await dns.promises.resolve(subdomain, 'A');
if (addresses && addresses.length > 0) {
if (argv.debug) {
console.log(`${clc.green('[V]')} Resolved subdomain ${subdomain}:`, addresses);
}
return subdomain; // Return the original subdomain
}
} else {
// Load custom resolvers from file
const resolvers = fs.readFileSync(argv.resolver, 'utf8').split('\n').filter(Boolean);
const addresses = await dns.promises.resolve(subdomain, 'A', {
resolver: resolvers, // Use custom resolvers
});
if (addresses && addresses.length > 0) {
if (argv.debug) {
console.log(`${clc.green('[V]')} Resolved subdomain ${subdomain}:`, addresses);
}
return subdomain; // Return the original subdomain
}
}
} catch (error) {
if (argv.verbose && argv.debug) {
console.error(`${clc.red('\n[!]')} Error resolving subdomain ${subdomain}:`, error.response ? error.response.statusText : error.message);
}
}
return null; // Mark resolution as failed
}
// Function to perform subdomain enumeration
async function enumerateSubdomains(domain, subdomains) {
const resolvedSubdomains = [];
const failedSubdomains = [];
// Loop through each subdomain and resolve them in parallel
const resolvedPromises = subdomains.map(async (subdomain) => {
try {
let isActive;
if (argv.rateLimit > 0) {
const [result] = await rateLimitDNSRequests([subdomain]);
isActive = result.isActive;
} else {
isActive = await resolveDomain(subdomain);
}
if (isActive) {
resolvedSubdomains.push({
subdomain,
isActive
});
} else {
failedSubdomains.push({
subdomain,
isActive
});
}
} catch (error) {
console.error(`${clc.red('\n[!]')} Error resolving subdomain ${subdomain}:`, error.response ? error.response.statusText : error.message);
failedSubdomains.push({
subdomain,
isActive: false
});
}
});
await Promise.all(resolvedPromises);
return {
resolvedSubdomains,
failedSubdomains
}; // Return both resolved and subdomains
}
// Function to rate limit DNS requests
async function rateLimitDNSRequests(subdomains) {
const rateLimit = parseInt(argv.rateLimit);
if (rateLimit <= 0) {
return subdomains;
}
const limiter = new Bottleneck({
maxConcurrent: rateLimit,
minTime: 10000 / rateLimit,
});
const rateLimitedSubdomains = subdomains.map((subdomain) => {
return limiter.schedule(async () => {
try {
let isActive;
if (argv.rateLimit > 0) {
const [result] = await rateLimitDNSRequests([subdomain]);
isActive = result.isActive;
} else {
isActive = await resolveDomain(subdomain);
}
return {
subdomain,
isActive
};
} catch (error) {
console.error(`${clc.red('\n[!]')} Error resolving domain ${subdomain}:`, error.response ? error.response.statusText : error.message);
return {
subdomain,
isActive: false
};
}
});
});
await Promise.all(rateLimitedSubdomains); // Await the resolution of DNS requests
return rateLimitedSubdomains;
}
// Function to perform recursive subdomain enumeration with a specified level of recursion
async function performRecursiveEnumeration(domain, defaultWordlistContent, maxLevel) {
const discoveredSubdomains = [];
const resolvedSubdomains = [];
const failedSubdomains = [];
// Function to recursively enumerate subdomains
async function enumerateSubdomainsRecursive(subdomain, defaultWordlistContent, currentLevel) {
if (currentLevel > maxLevel) return;
try {
const fullSubdomain = `${subdomain}.${domain}`;
const isActive = await resolveDomain(fullSubdomain);
if (isActive) {
resolvedSubdomains.push({
subdomain: fullSubdomain,
isActive
});
discoveredSubdomains.push(fullSubdomain);
} else {
failedSubdomains.push({
subdomain: fullSubdomain,
isActive
});
}
// Recursive call to enumerate subdomains
for (const word of defaultWordlistContent) {
const newSubdomain = `${word}.${fullSubdomain}`;
await enumerateSubdomainsRecursive(newSubdomain, defaultWordlistContent, currentLevel + 1);
}
} catch (error) {
console.error(`${clc.red('\n[!]')} Error running performing recursive enumeration:`, error.response ? error.response.statusText : error.message);
}
}
// Start the recursive enumeration
for (const word of defaultWordlistContent) {
const subdomain = `${word}.${domain}`;
await enumerateSubdomainsRecursive(subdomain, defaultWordlistContent, 1);
}
return {
discoveredSubdomains,
resolvedSubdomains,
failedSubdomains
};
}
// Function to perform subdomain brute force using wordlist with early exit
async function bruteForceSubdomains(domain, wordlist) {
const CHUNK_SIZE = 10000; // Set the chunk size for wordlist processing
const subdomains = [];
const accuracy = 0.5; // Desired accuracy (50%)
// Chunk the wordlist into smaller arrays
const chunks = [];
for (let i = 0; i < wordlist.length; i += CHUNK_SIZE) {
chunks.push(wordlist.slice(i, i + CHUNK_SIZE));
}
// Loop through each chunk of the wordlist
for (const chunk of chunks) {
// Loop through each word in the chunk
for (const word of chunk) {
const subdomain = `${word}.${domain}`;
// Perform early exit check
if (await earlyExitCheck(subdomain, accuracy)) {
subdomains.push(subdomain);
}
}
}
return subdomains;
}
// Function to perform early exit check for subdomain
async function earlyExitCheck(subdomain, accuracy) {
const maxAttempts = Math.ceil(subdomain.length * (1 - accuracy));
// Loop through each character of the subdomain
for (let i = 0; i < subdomain.length; i++) {
const prefix = subdomain.slice(0, i + 1);
const isActive = await resolveDomain(prefix);
// If the prefix does not resolve, return false
if (!isActive) {
return true;
}
// If the maximum number of attempts is reached, return true
if (i + 100 >= maxAttempts) {
return true;
}
}
// If all characters are resolved, return true
return true;
}
async function getSubdomainsFromCIDR(cidr1) {
try {
const subdomains = [];
// Perform subdomain enumeration using CIDR
// Replace the following code with your own implementation to extract subdomains from CIDR
// Example implementation using 'amass', 'mapcidr' command line tool
const commands = [
`amass intel -cidr ${cidr1} ; echo ${cidr1} | mapcidr -silent | tlsx -cn -silent -nc | tr -d '[]' | awk '{print $2}'`
];
const output = await Promise.all(commands.map(runCommand));
output.forEach((cmdOutput) => {
const lines = cmdOutput.split('\n');
lines.forEach((line) => {
const matches = line.match(/\b([a-zA-Z0-9.-]+)\b/g);
if (matches) {
subdomains.push(...matches);
}
});
});
return subdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error getting subdomains from CIDR:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to get subdomains from ASN using whois
async function getSubdomainsFromASN(asn1) {
try {
const subdomains = [];
// Perform subdomain enumeration using ASN
// Replace the following code with your own implementation to extract subdomains from ASN
// Example implementation using 'amass', 'asnmap', and 'whois' command line tools
const commands = [
`amass intel -asn ${asn1} ; asnmap -a ${asn1} -silent | mapcidr -silent | tlsx -cn -silent -nc | tr -d '[]' | awk '{print $2}'`,
`whois -h whois.radb.net -- '-i origin ${asn1}' | grep -Eo "([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}"`
];
const output = await Promise.all(commands.map(runCommand));
output.forEach((cmdOutput) => {
const lines = cmdOutput.split('\n');
lines.forEach((line) => {
const matches = line.match(/\b([a-zA-Z0-9.-]+)\b/g);
if (matches) {
subdomains.push(...matches);
}
});
});
return subdomains;
} catch (error) {
console.error(`${clc.red('\n[!]')} Error getting subdomains from ASN:`, error.response ? error.response.statusText : error.message);
return [];
}
}
// Function to get subdomains using DNS Dumpster Diving technique
async function getSubdomainsFromDnsDumpster(domain) {
try {
const socket = new DnsSocket();