-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
2425 lines (2171 loc) · 103 KB
/
sw.js
File metadata and controls
2425 lines (2171 loc) · 103 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
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
// Configuration constants - More generous timeouts for robustness
const CONFIG = {
TIMEOUTS: {
FETCH_DEFAULT: 8000, // Increased from 3000
FETCH_HEADERS: 5000, // Increased from 2500
FETCH_TEXT: 6000, // Increased from 2500
FETCH_JSON: 8000, // Increased from 3500
FETCH_FAVICON: 4000, // Increased from 2000
DOH_RESOLVE: 5000, // Increased from 2500
SECURITY_TXT: 4000, // Increased from 2000
VT_REQUEST: 8000, // Increased from 3000
CVE_NVD: 10000, // Increased from 4000
SUBDOMAIN_PASSIVE: 8000, // New
IP_ENRICHMENT: 8000 // New
},
LIMITS: {
MAX_IPS: 20,
MAX_EXTERNAL_SCRIPTS: 12,
MAX_INLINE_SCRIPTS: 16,
MAX_SECRETS_RESULTS: 20,
MAX_SUBDOMAINS: 200,
MAX_SUBDOMAINS_LIVE: 80,
MAX_SUBDOMAINS_QUEUE: 120,
MAX_PARALLEL_WORKERS: 6,
MAX_CPES_PER_IP: 5,
MAX_CVE_RESULTS: 60,
MAX_SOURCE_MAPS: 6,
MAX_DKIM_SELECTORS: 6,
MAX_DOM_PATHS: 200,
MAX_PAGES_TRACKED: 100,
MAX_REQUESTS_LOGGED: 200,
MAX_DOMAIN_STORE_SIZE: 500000 // ~500KB per domain
},
RETRY: {
MAX_ATTEMPTS: 3,
INITIAL_DELAY: 500,
MAX_DELAY: 4000
},
CACHE: {
DOH_MS: 5 * 60 * 1000,
SUBDOMAIN_MS: 10 * 60 * 1000,
MAX_ENTRIES: 128
}
};
function log(...a){ try{ console.log("[SnailSploit Recon]", ...a);}catch{} }
function logError(...a){ try{ console.error("[SnailSploit Recon ERROR]", ...a);}catch{} }
function merge(a, b) {
const result = Object.assign({}, a || {});
for (const [key, val] of Object.entries(b || {})) {
if (val !== null && typeof val === 'object' && !Array.isArray(val) &&
result[key] !== null && typeof result[key] === 'object' && !Array.isArray(result[key])) {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
return result;
}
const dohCache = new Map();
const subdomainCache = new Map();
const highlightTimers = new Map();
// ============ DOMAIN-LEVEL PERSISTENT STORE ============
// Accumulates findings across pages, tabs, and sessions for a target domain.
// While tab state (session storage) shows the current page, domain state
// (local storage) builds a complete picture as the user browses.
const domainStoreKey = (domain) => `domain:${domain}`;
async function getDomainData(domain) {
try {
const key = domainStoreKey(domain);
return (await chrome.storage.local.get(key))[key] || null;
} catch (e) { logError("getDomainData failed:", e); return null; }
}
async function setDomainData(domain, data) {
try {
const key = domainStoreKey(domain);
data._lastUpdated = Date.now();
await chrome.storage.local.set({ [key]: data });
} catch (e) {
if (String(e).includes('QUOTA') || String(e).includes('quota')) {
// Prune oldest domain stores to make room
const all = await chrome.storage.local.get(null);
const domains = Object.entries(all)
.filter(([k]) => k.startsWith("domain:"))
.sort(([,a],[,b]) => (a._lastUpdated||0) - (b._lastUpdated||0));
if (domains.length > 5) {
await chrome.storage.local.remove(domains.slice(0, 3).map(([k]) => k));
log("Pruned 3 oldest domain stores for quota");
try { await chrome.storage.local.set({ [domainStoreKey(domain)]: data }); } catch {}
}
} else { logError("setDomainData failed:", e); }
}
}
// Merge new findings into the domain's persistent store.
// Arrays are union-merged (deduplicated), objects are deep-merged.
function mergeUnique(existing, incoming, keyFn) {
if (!existing || !existing.length) return incoming || [];
if (!incoming || !incoming.length) return existing;
const seen = new Set(existing.map(keyFn).filter(Boolean));
const merged = [...existing];
for (const item of incoming) {
const k = keyFn(item);
if (k && !seen.has(k)) { seen.add(k); merged.push(item); }
}
return merged;
}
async function accumulateToDomain(domain, tabState) {
if (!domain || !tabState) return;
const existing = await getDomainData(domain) || {
domain,
firstSeen: Date.now(),
pagesVisited: [],
requestLog: [],
allEndpoints: [],
allParams: [],
allSecrets: [],
allEmails: [],
allForms: [],
allTech: [],
allCookies: [],
jsEndpoints: [],
authSurfaces: [],
jsConfigs: [],
subdomainTakeovers: [],
waybackUrls: [],
waybackAll: [],
discoveredParams: [],
leads: []
};
// Track page visit
const page = tabState.url;
if (page && !existing.pagesVisited.some(p => p.url === page)) {
existing.pagesVisited.push({
url: page,
ts: Date.now(),
title: tabState.pageTitle || null
});
if (existing.pagesVisited.length > CONFIG.LIMITS.MAX_PAGES_TRACKED) {
existing.pagesVisited = existing.pagesVisited.slice(-CONFIG.LIMITS.MAX_PAGES_TRACKED);
}
}
// Accumulate secrets (deduplicate by source)
existing.allSecrets = mergeUnique(existing.allSecrets, tabState.secrets, s => s.source);
// Accumulate subdomains
existing.quickSubs = mergeUnique(existing.quickSubs, tabState.quickSubs, s => s?.subdomain);
// Accumulate JS endpoints
if (tabState.jsEndpoints?.length) {
const epSet = new Set(existing.jsEndpoints || []);
for (const ep of tabState.jsEndpoints) epSet.add(ep);
existing.jsEndpoints = [...epSet].slice(0, 500);
}
// Accumulate auth surfaces
existing.authSurfaces = mergeUnique(existing.authSurfaces, tabState.authSurfaces, a => `${a.type}:${a.detail}`);
// Accumulate JS configs
existing.jsConfigs = mergeUnique(existing.jsConfigs, tabState.jsConfigs, c => c.match);
// Accumulate emails
if (tabState.intel?.emails?.length) {
const emailSet = new Set(existing.allEmails || []);
for (const e of tabState.intel.emails) emailSet.add(e);
existing.allEmails = [...emailSet];
}
// Accumulate forms (deduplicate by action+method)
existing.allForms = mergeUnique(existing.allForms, tabState.forms, f => `${f.method}:${f.action}`);
// Accumulate tech tags
if (tabState.tech?.tags) {
const techSet = new Set(existing.allTech || []);
for (const t of tabState.tech.tags) techSet.add(t);
existing.allTech = [...techSet];
}
// Accumulate cookies
existing.allCookies = mergeUnique(existing.allCookies, tabState.cookieSecurity, c => c.name);
// Accumulate takeovers
existing.subdomainTakeovers = mergeUnique(
existing.subdomainTakeovers, tabState.subdomainTakeovers, t => t.subdomain
);
// Accumulate wayback URLs
if (tabState.waybackUrls?.length) {
const wbSet = new Set(existing.waybackUrls || []);
for (const u of tabState.waybackUrls) wbSet.add(u);
existing.waybackUrls = [...wbSet].slice(0, 200);
}
// Accumulate discovered params
existing.discoveredParams = mergeUnique(
existing.discoveredParams, tabState.discoveredParams, p => p.name
);
// Copy over one-time fields (latest wins)
if (tabState.headers) existing.headers = tabState.headers;
if (tabState.ips) existing.ips = tabState.ips;
if (tabState.perIp) existing.perIp = merge(existing.perIp || {}, tabState.perIp);
if (tabState.tlsInfo) existing.tlsInfo = tabState.tlsInfo;
if (tabState.corsFindings) existing.corsFindings = tabState.corsFindings;
if (tabState.sensitiveFiles) existing.sensitiveFiles = tabState.sensitiveFiles;
if (tabState.httpMethods) existing.httpMethods = tabState.httpMethods;
if (tabState.dmarc) existing.dmarc = tabState.dmarc;
if (tabState.spf) existing.spf = tabState.spf;
if (tabState.waf) existing.waf = tabState.waf;
// Re-generate leads from accumulated data
existing.leads = generateLeads(existing);
// Stats
existing.totalPages = existing.pagesVisited.length;
existing.totalEndpoints = (existing.jsEndpoints || []).length;
existing.totalSecrets = (existing.allSecrets || []).length;
await setDomainData(domain, existing);
return existing;
}
// Track tab → domain mapping so we know which domain each tab is on
const tabDomainMap = new Map();
function setBoundedCache(map, key, value){
map.set(key, value);
if (map.size > CONFIG.CACHE.MAX_ENTRIES) {
const first = map.keys().next().value;
if (first !== undefined) map.delete(first);
}
}
// Exponential backoff retry helper
async function retryWithBackoff(fn, maxAttempts = CONFIG.RETRY.MAX_ATTEMPTS, operation = "operation") {
let lastError;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt === maxAttempts) {
logError(`${operation} failed after ${maxAttempts} attempts:`, error);
throw error;
}
const delay = Math.min(CONFIG.RETRY.INITIAL_DELAY * Math.pow(2, attempt - 1), CONFIG.RETRY.MAX_DELAY);
log(`${operation} attempt ${attempt}/${maxAttempts} failed, retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
async function fetchWithTimeout(resource, options={}, ms=3000){
const c = new AbortController(); const id = setTimeout(()=>c.abort(), ms);
try { return await fetch(resource, { ...options, signal: c.signal, cache: "no-store" }); }
finally { clearTimeout(id); }
}
async function jsonWithTimeout(url, opts={}, ms=3000){ const r=await fetchWithTimeout(url,opts,ms); if(!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }
// headers
const headersByTab = new Map();
chrome.webRequest.onHeadersReceived.addListener((d)=>{
if (d.type !== "main_frame") return;
headersByTab.set(d.tabId, { url: d.url, responseHeaders: d.responseHeaders || [] });
}, { urls: ["<all_urls>"] }, ["responseHeaders","extraHeaders"]);
// Passive request logger - captures API calls, XHR, fetches as user browses
const requestLogByDomain = new Map();
chrome.webRequest.onCompleted.addListener((d) => {
if (d.tabId < 0) return; // Ignore non-tab requests
const domain = tabDomainMap.get(d.tabId);
if (!domain) return;
// Only log interesting request types (skip images, fonts, CSS)
const dominated = ["xmlhttprequest", "script", "sub_frame", "other"];
if (!dominated.includes(d.type)) return;
try {
const urlObj = new URL(d.url);
const entry = {
url: d.url,
path: urlObj.pathname,
method: d.method || "GET",
type: d.type,
status: d.statusCode,
ts: Date.now()
};
// Extract query parameters
if (urlObj.search) {
entry.params = [...urlObj.searchParams.keys()].slice(0, 20);
}
if (!requestLogByDomain.has(domain)) requestLogByDomain.set(domain, []);
const log_arr = requestLogByDomain.get(domain);
// Deduplicate by path+method
if (!log_arr.some(e => e.path === entry.path && e.method === entry.method)) {
log_arr.push(entry);
if (log_arr.length > CONFIG.LIMITS.MAX_REQUESTS_LOGGED) log_arr.shift();
}
} catch {}
}, { urls: ["<all_urls>"] });
// Also capture redirects passively
chrome.webRequest.onBeforeRedirect.addListener((d) => {
if (d.tabId < 0) return;
const domain = tabDomainMap.get(d.tabId);
if (!domain) return;
try {
if (!requestLogByDomain.has(domain)) requestLogByDomain.set(domain, []);
const log_arr = requestLogByDomain.get(domain);
log_arr.push({
url: d.url,
redirectUrl: d.redirectUrl,
method: d.method || "GET",
type: "redirect",
status: d.statusCode,
ts: Date.now()
});
if (log_arr.length > CONFIG.LIMITS.MAX_REQUESTS_LOGGED) log_arr.shift();
} catch {}
}, { urls: ["<all_urls>"] });
function pickSecurityHeaders(tabId){
const rec = headersByTab.get(tabId); if (!rec) return null;
const h = {}; const setCookies = [];
for (const {name,value} of rec.responseHeaders||[]) {
const lc = name.toLowerCase();
if (lc === "set-cookie") { setCookies.push(value || ""); }
else { h[lc] = value || ""; }
}
// Preserve all Set-Cookie headers as an array
if (setCookies.length) h["set-cookie"] = setCookies;
const get = k => h[k] || null;
return { url: rec.url, headers: {
"content-security-policy": get("content-security-policy"),
"strict-transport-security": get("strict-transport-security"),
"x-frame-options": get("x-frame-options"),
"x-content-type-options": get("x-content-type-options"),
"referrer-policy": get("referrer-policy"),
"permissions-policy": get("permissions-policy"),
"server": get("server"),
"alt-svc": get("alt-svc"),
"x-powered-by": get("x-powered-by"),
"via": get("via"),
"set-cookie": setCookies.length ? setCookies : null
}};
}
async function fetchHeadersFallback(url){
try{ const r=await fetchWithTimeout(url,{method:"HEAD"},2500); const o={}; for(const [k,v] of r.headers.entries()) o[k.toLowerCase()]=v; return o; }catch(e){ log(`HEAD fallback failed for ${url}:`, e.message); }
try{ const r=await fetchWithTimeout(url,{method:"GET",headers:{"Range":"bytes=0-0"}},2500); const o={}; for(const [k,v] of r.headers.entries()) o[k.toLowerCase()]=v; return o; }catch(e){ log(`GET-Range fallback failed for ${url}:`, e.message); }
return null;
}
// DNS resolution via DNS-over-HTTPS (DoH) - Uses Google and Cloudflare public resolvers
// Avoids chrome.dns API requirement, making extension work on Chrome Stable
async function dohResolve(name, type){
const key = `${name}|${type}`;
const now = Date.now();
const cached = dohCache.get(key);
if (cached && (now - cached.ts) < CONFIG.CACHE.DOH_MS) return cached.ans;
const enc = encodeURIComponent(name);
const urls = [
`https://dns.google/resolve?name=${enc}&type=${type}`,
`https://cloudflare-dns.com/dns-query?name=${enc}&type=${type}`
];
for (const u of urls) {
try {
const r = await fetchWithTimeout(u, { headers:{accept:"application/dns-json"} }, 2500);
if (!r.ok) continue;
const j=await r.json();
if (j.Answer && j.Answer.length) {
setBoundedCache(dohCache, key, { ts: now, ans: j.Answer });
return j.Answer;
}
} catch (e) { log(`DoH resolver failed (${u}):`, e.message); }
}
setBoundedCache(dohCache, key, { ts: now, ans: [] });
return [];
}
async function dohTXT(name){ const ans=await dohResolve(name,"TXT"); const out=[]; for(const a of ans){ if(a.type!==16) continue; let d=a.data||""; d=d.replace(/^\"|\"$/g,"").replace(/\"\\s+\"?/g,""); out.push(d);} return out; }
async function dohMX(name){ const ans=await dohResolve(name,"MX"); return (ans||[]).filter(a=>a.type===15).map(a=>a.data); }
function isIPv4(ip){ return /^(\d{1,3}\.){3}\d{1,3}$/.test(ip); }
function isIPv6(ip){ return ip.includes(":"); }
function ipv4ToPtr(ip){ return ip.split(".").reverse().join(".") + ".in-addr.arpa"; }
function expandIPv6Blocks(ip){ const [h,t]=ip.split("::"); const H=(h?h.split(":"):[]).filter(Boolean); const T=(t?t.split(":"):[]).filter(Boolean); const miss=Math.max(0,8-(H.length+T.length)); return [...H,...Array(miss).fill("0"),...T].map(x=>("0000"+x).slice(-4)); }
function ipv6ToPtr(ip){ try{ const parts=expandIPv6Blocks(ip).join(""); return parts.split("").reverse().join(".") + ".ip6.arpa"; }catch{ return null; } }
async function reverseDNS(ip){ let name=null; if(isIPv4(ip)) name=ipv4ToPtr(ip); else if(isIPv6(ip)) name=ipv6ToPtr(ip); if(!name) return null; const ans=await dohResolve(name,"PTR"); const a=(ans||[]).find(x=>x.type===12); return a ? (a.data||"").replace(/\.$/,"") : null; }
async function resolveIPs(hostname){
const ips = new Set();
const q = encodeURIComponent(hostname);
const urls = [
`https://dns.google/resolve?name=${q}&type=A`,
`https://dns.google/resolve?name=${q}&type=AAAA`,
`https://cloudflare-dns.com/dns-query?name=${q}&type=A`,
`https://cloudflare-dns.com/dns-query?name=${q}&type=AAAA`
];
const all = await Promise.all(urls.map(u => fetchWithTimeout(u, { headers:{accept:"application/dns-json"} }, CONFIG.TIMEOUTS.DOH_RESOLVE).then(r=>r.json()).catch(()=>({}))));
for (const j of all) for (const a of (j.Answer||[])) if (a.type===1||a.type===28) ips.add(a.data);
return [...ips].slice(0, CONFIG.LIMITS.MAX_IPS);
}
// Enrichers with robust error handling and retry logic
async function fetchJSON(url, opts = {}, timeout = CONFIG.TIMEOUTS.FETCH_JSON) {
return retryWithBackoff(async () => {
const r = await fetchWithTimeout(url, { ...opts }, timeout);
if (r.status === 429) {
const retryAfter = parseInt(r.headers.get('retry-after') || '5', 10);
log(`Rate limited (429) on ${url}, waiting ${retryAfter}s`);
await new Promise(res => setTimeout(res, retryAfter * 1000));
throw new Error(`Rate limited (429) for ${url}`);
}
if (!r.ok) throw new Error(`HTTP ${r.status} for ${url}`);
return r.json();
}, 2, `fetchJSON(${url})`);
}
async function shodanInternetDB(ip) {
try {
return await fetchJSON(`https://internetdb.shodan.io/${ip}`, {}, CONFIG.TIMEOUTS.IP_ENRICHMENT);
} catch (e) {
logError(`Shodan InternetDB failed for ${ip}:`, e);
return {};
}
}
async function ipWhoIs(ip) {
try {
return await fetchJSON(`https://ipwho.is/${ip}`, {}, CONFIG.TIMEOUTS.IP_ENRICHMENT);
} catch (e) {
log(`ipwho.is failed for ${ip}, trying ipapi.co...`);
try {
return await fetchJSON(`https://ipapi.co/${ip}/json/`, {}, CONFIG.TIMEOUTS.IP_ENRICHMENT);
} catch (e2) {
logError(`Both IP whois services failed for ${ip}`);
return {};
}
}
}
async function rdapDomain(domain) {
try {
return await fetchJSON(`https://rdap.org/domain/${domain}`, {}, CONFIG.TIMEOUTS.FETCH_JSON);
} catch (e) {
logError(`RDAP domain lookup failed for ${domain}:`, e);
return null;
}
}
async function rdapIP(ip) {
try {
return await fetchJSON(`https://rdap.org/ip/${ip}`, {}, CONFIG.TIMEOUTS.IP_ENRICHMENT);
} catch (e) {
logError(`RDAP IP lookup failed for ${ip}:`, e);
return null;
}
}
async function getSecurityTxt(origin) {
try {
const u1 = new URL("/.well-known/security.txt", origin).href;
const r1 = await fetchWithTimeout(u1, {}, CONFIG.TIMEOUTS.SECURITY_TXT);
if (r1.ok) return { url: u1 };
} catch (e) {
log(`security.txt not found at /.well-known/, trying root...`);
}
try {
const u2 = new URL("/security.txt", origin).href;
const r2 = await fetchWithTimeout(u2, {}, CONFIG.TIMEOUTS.SECURITY_TXT);
if (r2.ok) return { url: u2 };
} catch (e) {
log(`security.txt not found at root either`);
}
return null;
}
async function getRobots(origin) {
try {
const u = new URL("/robots.txt", origin).href;
const r = await fetchWithTimeout(u, {}, CONFIG.TIMEOUTS.SECURITY_TXT);
if (r.ok) return { url: u };
} catch (e) {
log(`robots.txt not found for ${origin}`);
}
return null;
}
async function checkDMARC(d){ try{ const recs=await dohTXT(`_dmarc.${d}`); const m=recs.find(r=>String(r).toUpperCase().includes("V=DMARC1")); return {present:!!m, record:m||null}; }catch{ return {present:false, record:null}; } }
async function checkSPF(d){ try{ const recs=await dohTXT(d); const m=recs.find(r=>String(r).toLowerCase().startsWith("v=spf1")); return {present:!!m, record:m||null}; }catch{ return {present:false, record:null}; } }
const COMMON_DKIM=["default","google","mail","mandrill","dkim","selector","selector1","selector2","s1","s2","k1","mx","smtp"];
async function checkDKIM(d){ const found=[]; for(const sel of COMMON_DKIM){ try{ const txts=await dohTXT(`${sel}._domainkey.${d}`); const rec=(txts||[]).find(r=>String(r).toLowerCase().includes("v=dkim1")); if(rec) found.push({selector:sel,record:rec}); if(found.length>=6) break; }catch{} } return {selectors:found}; }
// Subdomain enumeration - OPTIMIZED: Parallel API calls to all sources
// Combines passive sources (crt.sh, BufferOver, Anubis) concurrently
async function subdomainsPassive(domain){
const set = new Set(); const q = domain.replace(/^\*\./, "");
const cached = subdomainCache.get(q);
if (cached && (Date.now() - cached.ts) < CONFIG.CACHE.SUBDOMAIN_MS) {
log(`Using cached subdomains for ${q}`);
return cached.data.slice(0, CONFIG.LIMITS.MAX_SUBDOMAINS);
}
// Fetch from all sources in parallel for maximum speed
const sources = await Promise.allSettled([
// crt.sh - certificate transparency logs (uses shared cache)
(async () => {
try {
log(`Fetching subdomains from crt.sh for ${q}...`);
const arr = await fetchCrtshData(q);
const results = [];
for (const row of arr) {
const names = String(row.name_value || "").split(/\n+/);
for (const n of names) {
if (n && n.endsWith(q)) results.push(n.replace(/^\*\./, ""));
}
}
log(`crt.sh found ${results.length} subdomains`);
return results;
} catch (e) {
logError(`crt.sh lookup failed for ${q}:`, e);
}
return [];
})(),
// BufferOver - DNS aggregator
(async () => {
try {
log(`Fetching subdomains from BufferOver for ${q}...`);
const r = await fetchWithTimeout(`https://dns.bufferover.run/dns?q=.${encodeURIComponent(q)}`, {}, CONFIG.TIMEOUTS.SUBDOMAIN_PASSIVE);
if (r.ok) {
const j = await r.json();
const results = [];
for (const line of (j.FDNS_A || [])) {
const d = (line.split(",")[1] || "").trim();
if (d && d.endsWith(q)) results.push(d);
}
for (const line of (j.FDNS_AAAA || [])) {
const d = (line.split(",")[1] || "").trim();
if (d && d.endsWith(q)) results.push(d);
}
log(`BufferOver found ${results.length} subdomains`);
return results;
}
} catch (e) {
logError(`BufferOver lookup failed for ${q}:`, e);
}
return [];
})(),
// Anubis - subdomain aggregator
(async () => {
try {
log(`Fetching subdomains from Anubis for ${q}...`);
const r = await fetchWithTimeout(`https://jldc.me/anubis/subdomains/${encodeURIComponent(q)}`, {}, CONFIG.TIMEOUTS.SUBDOMAIN_PASSIVE);
if (r.ok) {
const arr = await r.json();
const results = [];
for (const d of arr) {
if (typeof d === "string" && d.endsWith(q)) results.push(d);
}
log(`Anubis found ${results.length} subdomains`);
return results;
}
} catch (e) {
logError(`Anubis lookup failed for ${q}:`, e);
}
return [];
})(),
// AlienVault OTX - passive DNS aggregator (4th source)
(async () => {
try {
log(`Fetching subdomains from AlienVault OTX for ${q}...`);
const r = await fetchWithTimeout(`https://otx.alienvault.com/api/v1/indicators/domain/${encodeURIComponent(q)}/passive_dns`, {}, CONFIG.TIMEOUTS.SUBDOMAIN_PASSIVE);
if (r.ok) {
const j = await r.json();
const results = [];
for (const entry of (j.passive_dns || [])) {
const h = (entry.hostname || "").trim();
if (h && h.endsWith(q) && h !== q) results.push(h);
}
log(`AlienVault OTX found ${results.length} subdomains`);
return results;
}
} catch (e) {
logError(`AlienVault OTX lookup failed for ${q}:`, e);
}
return [];
})()
]);
// Merge all results
for (const result of sources) {
if (result.status === 'fulfilled' && Array.isArray(result.value)) {
result.value.forEach(sub => set.add(sub));
}
}
log(`Total ${set.size} unique subdomains found for ${q} (parallel fetch)`);
const list = [...set].slice(0, CONFIG.LIMITS.MAX_SUBDOMAINS);
setBoundedCache(subdomainCache, q, { ts: Date.now(), data: list });
return list;
}
async function subdomainsLive(domain){
const passive=await subdomainsPassive(domain); const out=[]; const queue=passive.slice(0,CONFIG.LIMITS.MAX_SUBDOMAINS_QUEUE); const limit=CONFIG.LIMITS.MAX_PARALLEL_WORKERS;
async function worker(){ while(queue.length){ const s=queue.shift(); try{ const a4=(await dohResolve(s,"A")).filter(x=>x.type===1).map(x=>x.data); const a6=(await dohResolve(s,"AAAA")).filter(x=>x.type===28).map(x=>x.data); const cnames=(await dohResolve(s,"A")).filter(x=>x.type===5).map(x=>x.data?.replace(/\.$/,"")); if(a4.length||a6.length) out.push({subdomain:s,a:a4,aaaa:a6,cnames}); }catch(e){ log(`DNS resolve failed for ${s}:`, e.message); } } }
await Promise.all(Array.from({length:limit},worker)); return out.slice(0,CONFIG.LIMITS.MAX_SUBDOMAINS_LIVE);
}
// Favicon hash - Computes MurmurHash3 (32-bit) of favicon for fingerprinting
// Used by Shodan and other tools to identify web technologies by favicon signature
function mmh3_32_from_b64(b64){
function rotl32(x,r){ return (x<<r)|(x>>> (32-r)); }
const bin=atob(b64); const arr=new Uint8Array(bin.length); for(let i=0;i<bin.length;i++) arr[i]=bin.charCodeAt(i);
let h1=0x811c9dc5; const c1=0xcc9e2d51, c2=0x1b873593; const view=new DataView(arr.buffer,arr.byteOffset,arr.byteLength);
const nblocks=Math.floor(arr.byteLength/4);
// Process 4-byte blocks
for(let i=0;i<nblocks;i++){ let k1=view.getUint32(i*4,true); k1=Math.imul(k1,c1); k1=rotl32(k1,15); k1=Math.imul(k1,c2); h1^=k1; h1=rotl32(h1,13); h1=(Math.imul(h1,5)+0xe6546b64)|0; }
// Process remaining bytes
let k1=0; const tail=arr.byteLength & 3; const p=nblocks*4;
if(tail===3) k1^=arr[p+2]<<16; if(tail>=2) k1^=arr[p+1]<<8; if(tail>=1){ k1^=arr[p]; k1=Math.imul(k1,c1); k1=rotl32(k1,15); k1=Math.imul(k1,c2); h1^=k1; }
// Finalization
h1^=arr.byteLength; h1^=h1>>>16; h1=Math.imul(h1,0x85ebca6b); h1^=h1>>>13; h1=Math.imul(h1,0xc2b2ae35); h1^=h1>>>16; return (h1|0);
}
// Fetches favicon and computes its mmh3 hash for fingerprinting
async function faviconHash(url){ try{ const r=await fetchWithTimeout(url,{},CONFIG.TIMEOUTS.FETCH_FAVICON); if(!r.ok) return null; const buf=await r.arrayBuffer(); const b64=btoa(String.fromCharCode(...new Uint8Array(buf))); return mmh3_32_from_b64(b64);}catch{ return null; }}
// Shared crt.sh data cache to avoid duplicate API calls
const crtshCache = new Map();
async function fetchCrtshData(hostname) {
const q = hostname.replace(/^\*\./, "");
if (crtshCache.has(q)) return crtshCache.get(q);
try {
log(`Fetching crt.sh data for ${q}...`);
const r = await fetchWithTimeout(`https://crt.sh/?q=%25.${encodeURIComponent(q)}&output=json`, {}, CONFIG.TIMEOUTS.SUBDOMAIN_PASSIVE);
if (!r.ok) { crtshCache.set(q, []); return []; }
const t = await r.text();
let arr = [];
try {
arr = JSON.parse(t);
} catch {
arr = t.trim().split("\n").map(x => {
try { return JSON.parse(x); } catch { return null; }
}).filter(Boolean);
}
crtshCache.set(q, arr);
return arr;
} catch (e) {
logError(`crt.sh fetch failed for ${q}:`, e);
crtshCache.set(q, []);
return [];
}
}
// TLS/SSL Certificate Analysis - Extract certificate details from shared crt.sh data
async function getTLSInfo(hostname) {
try {
log(`Extracting TLS certificate info for ${hostname}...`);
const certs = await fetchCrtshData(hostname);
if (!Array.isArray(certs) || certs.length === 0) return null;
// Get the most recent cert for the exact hostname (not wildcard subdomains)
const relevant = certs.filter(c => {
const names = String(c.name_value || "").split(/\n+/);
return names.some(n => n.trim() === hostname || n.trim() === `*.${hostname}`);
});
const pool = relevant.length ? relevant : certs;
const latest = pool.sort((a, b) => new Date(b.entry_timestamp) - new Date(a.entry_timestamp))[0];
// Parse SANs (Subject Alternative Names) for subdomain intel
const sans = new Set();
if (latest.name_value) {
latest.name_value.split('\n').forEach(n => {
const clean = n.trim().replace(/^\*\./, '');
if (clean && clean.includes('.')) sans.add(clean);
});
}
return {
issuer: latest.issuer_name || 'Unknown',
notBefore: latest.not_before,
notAfter: latest.not_after,
serialNumber: latest.serial_number,
sans: Array.from(sans).slice(0, 100),
commonName: latest.common_name
};
} catch (e) {
logError(`TLS info extraction failed for ${hostname}:`, e);
return null;
}
}
// Wayback Machine URL Discovery - Finds historical URLs for the target domain
// Reveals old endpoints, forgotten admin panels, API routes, and URL parameters
async function waybackUrls(domain) {
try {
log(`Fetching Wayback Machine URLs for ${domain}...`);
const r = await fetchWithTimeout(
`https://web.archive.org/cdx/search/cdx?url=*.${encodeURIComponent(domain)}/*&output=json&fl=original&collapse=urlkey&limit=200`,
{}, CONFIG.TIMEOUTS.SUBDOMAIN_PASSIVE
);
if (!r.ok) return [];
const rows = await r.json();
// First row is header ["original"], skip it
const urls = new Set();
for (let i = 1; i < rows.length; i++) {
const u = rows[i]?.[0];
if (u && typeof u === "string") urls.add(u);
}
// Deduplicate by path (strip query string for grouping, but keep full URL)
const unique = [...urls].slice(0, 150);
log(`Wayback Machine found ${unique.length} unique URLs for ${domain}`);
// Extract interesting patterns: admin, api, config, backup, login, upload
const interesting = unique.filter(u =>
/\b(admin|api|login|upload|config|backup|dashboard|debug|internal|console|panel|phpinfo|wp-admin|.env|graphql|swagger)\b/i.test(u)
);
return { all: unique, interesting: interesting.slice(0, 50) };
} catch (e) {
logError(`Wayback Machine lookup failed for ${domain}:`, e);
return { all: [], interesting: [] };
}
}
// CORS Misconfiguration Detection - Test for overly permissive CORS policies
async function checkCORS(url) {
try {
log(`Checking CORS policy for ${url}...`);
const testOrigins = [
'https://evil.com',
'null',
url.replace(/^https?:\/\//, 'https://attacker.')
];
const findings = [];
for (const origin of testOrigins) {
try {
const r = await fetchWithTimeout(url, {
method: 'GET',
headers: { 'Origin': origin }
}, 3000);
const acao = r.headers.get('access-control-allow-origin');
const acac = r.headers.get('access-control-allow-credentials');
if (acao === '*') {
findings.push({ type: 'wildcard', detail: 'ACAO: * (allows any origin)' });
} else if (acao === origin) {
findings.push({ type: 'reflected', detail: `ACAO reflects: ${origin}`, credentials: acac === 'true' });
} else if (acao === 'null') {
findings.push({ type: 'null_origin', detail: 'ACAO: null (sandbox bypass risk)' });
}
} catch (e) { log(`CORS probe failed for origin ${origin}:`, e.message); }
}
return findings.length > 0 ? findings : null;
} catch (e) {
logError(`CORS check failed for ${url}:`, e);
return null;
}
}
// HTTP Methods Enumeration - Discover allowed HTTP methods
async function probeHTTPMethods(url) {
try {
log(`Probing HTTP methods for ${url}...`);
const r = await fetchWithTimeout(url, { method: 'OPTIONS' }, 3000);
const allow = r.headers.get('allow');
const acao = r.headers.get('access-control-allow-methods');
const methods = new Set();
if (allow) allow.split(',').forEach(m => methods.add(m.trim().toUpperCase()));
if (acao) acao.split(',').forEach(m => methods.add(m.trim().toUpperCase()));
const dangerous = ['PUT', 'DELETE', 'TRACE', 'CONNECT', 'PATCH'].filter(m => methods.has(m));
return {
all: Array.from(methods),
dangerous: dangerous,
risky: dangerous.length > 0
};
} catch (e) {
logError(`HTTP methods probe failed for ${url}:`, e);
return null;
}
}
// Sensitive File/Directory Probing - Check for exposed sensitive files
// Uses content-type validation and soft-404 detection to reduce false positives
async function probeSensitiveFiles(origin) {
const sensitiveFiles = [
{ path: '/.git/config', expectedType: /text|octet-stream/, marker: '[core]' },
{ path: '/.git/HEAD', expectedType: /text|octet-stream/, marker: 'ref:' },
{ path: '/.env', expectedType: /text|octet-stream/, marker: '=' },
{ path: '/.env.local', expectedType: /text|octet-stream/, marker: '=' },
{ path: '/.env.production', expectedType: /text|octet-stream/, marker: '=' },
{ path: '/package.json', expectedType: /json/, marker: '"name"' },
{ path: '/composer.json', expectedType: /json/, marker: '"require"' },
{ path: '/web.config', expectedType: /xml|text/, marker: '<configuration' },
{ path: '/.htaccess', expectedType: /text|octet-stream/, marker: null },
{ path: '/phpinfo.php', expectedType: /html/, marker: 'phpinfo' },
{ path: '/server-status', expectedType: /html|text/, marker: 'Apache' },
{ path: '/backup.zip', expectedType: /zip|octet-stream/, marker: null },
{ path: '/database.sql', expectedType: /sql|text|octet-stream/, marker: null },
{ path: '/.DS_Store', expectedType: /octet-stream/, marker: null },
{ path: '/Dockerfile', expectedType: /text|octet-stream/, marker: 'FROM' },
{ path: '/docker-compose.yml', expectedType: /yaml|text|octet-stream/, marker: 'services' },
{ path: '/swagger.json', expectedType: /json/, marker: '"swagger"' },
{ path: '/graphql', expectedType: /json|html/, marker: null },
{ path: '/.svn/entries', expectedType: /text|xml|octet-stream/, marker: null }
];
const found = [];
// Rate-limited: batch in groups of 5 with small delay to avoid WAF triggers
for (let i = 0; i < sensitiveFiles.length; i += 5) {
const batch = sensitiveFiles.slice(i, i + 5);
const checks = batch.map(async ({ path, expectedType, marker }) => {
try {
const url = new URL(path, origin).href;
// Use GET with small range to validate content, not just HEAD (which can lie)
const r = await fetchWithTimeout(url, { method: 'GET' }, 2500);
if (!r.ok) return;
const ct = r.headers.get('content-type') || '';
const size = r.headers.get('content-length');
// Skip if content-type is HTML for non-HTML expected files (likely a custom 404 page)
if (expectedType && !expectedType.test(ct) && /text\/html/i.test(ct)) return;
// Read a small sample for marker validation
const body = await r.text();
const sample = body.slice(0, 2000);
// Soft-404 detection: skip if response looks like a generic error page
if (/text\/html/i.test(ct) && /(?:404|not found|page not found|error|does not exist)/i.test(sample) && !marker) return;
// If a marker is specified, verify it exists in the response
if (marker && !sample.includes(marker)) return;
found.push({
path: path,
status: r.status,
size: size ? parseInt(size) : body.length,
contentType: ct
});
log(`Confirmed exposed file: ${path} (${r.status}, ct: ${ct})`);
} catch (e) { log(`Probe ${path} failed:`, e.message); }
});
await Promise.all(checks);
// Small delay between batches to avoid aggressive scanning detection
if (i + 5 < sensitiveFiles.length) await new Promise(r => setTimeout(r, 200));
}
return found.length > 0 ? found : null;
}
// Extract emails, phone numbers, and other intel from page content
function extractIntelFromText(html) {
const intel = {
emails: new Set(),
phones: new Set(),
socialLinks: new Set(),
comments: []
};
// Email extraction
const emailRx = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
const emails = html.match(emailRx);
if (emails) emails.forEach(e => intel.emails.add(e.toLowerCase()));
// Phone number extraction (international formats: US, UK, EU, intl prefix)
const phoneRx = /(?:\+\d{1,3}[-.\s]?)?\(?([0-9]{2,4})\)?[-.\s]?([0-9]{3,4})[-.\s]?([0-9]{3,4})/g;
const phones = html.match(phoneRx);
if (phones) phones.filter(p => p.replace(/\D/g, '').length >= 7).forEach(p => intel.phones.add(p));
// Social media links (updated: includes x.com, tiktok, mastodon, threads)
const socialRx = /https?:\/\/(?:www\.)?(?:twitter\.com|x\.com|linkedin\.com|facebook\.com|github\.com|instagram\.com|youtube\.com|tiktok\.com|mastodon\.social|threads\.net)\/[@A-Za-z0-9_\-\.\/]+/gi;
const social = html.match(socialRx);
if (social) social.forEach(s => intel.socialLinks.add(s));
// HTML comments (often contain sensitive info)
const commentRx = /<!--([\s\S]*?)-->/g;
let match;
while ((match = commentRx.exec(html)) !== null) {
const comment = match[1].trim();
if (comment.length > 5 && comment.length < 500) {
intel.comments.push(comment);
}
}
return {
emails: Array.from(intel.emails).slice(0, 50),
phones: Array.from(intel.phones).slice(0, 20),
socialLinks: Array.from(intel.socialLinks).slice(0, 30),
comments: intel.comments.slice(0, 20)
};
}
// Subdomain Takeover Detection - Check if subdomains point to unclaimed services
async function checkSubdomainTakeover(subdomain, cnames) {
const vulnerableServices = [
{ pattern: /\.herokuapp\.com$/i, service: 'Heroku', message: 'No such app' },
{ pattern: /\.github\.io$/i, service: 'GitHub Pages', message: "There isn't a GitHub Pages site here" },
{ pattern: /\.azurewebsites\.net$/i, service: 'Azure', message: 'Error 404' },
{ pattern: /\.s3\.amazonaws\.com$/i, service: 'AWS S3', message: 'NoSuchBucket' },
{ pattern: /\.cloudfront\.net$/i, service: 'AWS CloudFront', message: 'The request could not be satisfied' },
{ pattern: /\.wordpress\.com$/i, service: 'WordPress.com', message: "Do you want to register" },
{ pattern: /\.pantheonsite\.io$/i, service: 'Pantheon', message: '404 error unknown site' },
{ pattern: /\.zendesk\.com$/i, service: 'Zendesk', message: 'Help Center Closed' },
{ pattern: /\.fastly\.net$/i, service: 'Fastly', message: 'Fastly error: unknown domain' },
{ pattern: /\.ghost\.io$/i, service: 'Ghost', message: 'The thing you were looking for is no longer here' }
];
if (!Array.isArray(cnames) || cnames.length === 0) return null;
for (const cname of cnames) {
for (const vuln of vulnerableServices) {
if (vuln.pattern.test(cname)) {
// Found potential takeover - try to verify
try {
const r = await fetchWithTimeout(`https://${subdomain}`, {}, 3000);
const text = await r.text();
if (text.includes(vuln.message) || r.status === 404) {
return {
subdomain: subdomain,
cname: cname,
service: vuln.service,
vulnerable: true,
confidence: 'high'
};
}
} catch {}
}
}
}
return null;
}
// ============ LEAD GENERATION ENGINE ============
// Extracts actionable intelligence that tells pentesters WHERE to look
// Extract API endpoints, routes, and interesting URLs from JavaScript source
function extractJSEndpoints(jsText) {
if (!jsText) return [];
const endpoints = new Set();
const apiPatterns = [
// Fetch/XHR calls: fetch("/api/users"), axios.get("/v1/data")
/(?:fetch|axios\.(?:get|post|put|delete|patch)|\.ajax|\.open)\s*\(\s*["'`](\/[^"'`\s]{3,})/gi,
// Route definitions: router.get("/users/:id"), app.post("/api")
/(?:router|app|server)\.(?:get|post|put|delete|patch|all|use)\s*\(\s*["'`](\/[^"'`\s]{3,})/gi,
// String assignments that look like API paths
/(?:url|endpoint|path|route|api|href|action|src)\s*[:=]\s*["'`](\/(?:api|v\d|graphql|auth|admin|user|account|dashboard|internal|ws|socket)[^"'`\s]*)/gi,
// Full URL patterns pointing to APIs
/["'`](https?:\/\/[^"'`\s]*\/(?:api|v\d|graphql|auth|admin|internal|ws)[^"'`\s]*)/gi,
// GraphQL operations
/(?:query|mutation|subscription)\s+(\w+)\s*[\({]/g,
// Webpack/build config API base URLs
/(?:BASE_URL|API_URL|BACKEND|SERVER_URL|API_HOST|API_BASE)\s*[:=]\s*["'`]([^"'`\s]+)/gi,
];
for (const rx of apiPatterns) {
rx.lastIndex = 0;
let m;
while ((m = rx.exec(jsText)) !== null) {
const ep = m[1];
if (ep && ep.length > 2 && ep.length < 200) endpoints.add(ep);
}
}
return [...endpoints];
}
// Extract URL parameters for injection testing
function extractParameters(urls) {
const params = new Map(); // param name → Set of example values
for (const url of urls) {
try {
const u = new URL(url, "https://placeholder.test");
for (const [k, v] of u.searchParams) {
if (!params.has(k)) params.set(k, new Set());
if (v && v.length < 100) params.get(k).add(v);
}
} catch {}
}
// Convert to array sorted by frequency (most-seen params first)
return [...params.entries()]
.map(([name, values]) => ({ name, examples: [...values].slice(0, 3), count: values.size }))
.sort((a, b) => b.count - a.count)
.slice(0, 40);