Repository navigation
Expand file tree
/
Copy pathflowoosint.py
More file actions
4029 lines (3571 loc) · 163 KB
/
Copy pathflowoosint.py
File metadata and controls
4029 lines (3571 loc) · 163 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
import sys, os, time, random, threading, queue, re, json, socket
from datetime import datetime
from urllib.parse import urljoin, urlparse
def _check():
need = []
for pkg, imp in [
("requests", "requests"),
("beautifulsoup4","bs4"),
("colorama", "colorama"),
("dnspython", "dns"),
("httpx[http2]", "httpx"),
("lxml", "lxml"),
("selectolax", "selectolax"),
("rich", "rich"),
("tldextract", "tldextract"),
("pydantic", "pydantic"),
("duckdb", "duckdb"),
("trafilatura", "trafilatura"),
]:
try: __import__(imp)
except ImportError: need.append(pkg)
if need:
print(f"\n [!] Missing packages: {', '.join(need)}")
print(f" Run: pip install {' '.join(need)}")
ans = input("\n Auto-install now? [Y/n]: ").strip().lower()
if ans in ("","y","yes"):
import subprocess
subprocess.check_call([sys.executable,"-m","pip","install"]+need)
print("\n [+] Done — restarting...\n"); time.sleep(1)
os.execv(sys.executable,[sys.executable]+sys.argv)
sys.exit(0)
_check()
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import httpx
from bs4 import BeautifulSoup, Comment
from lxml import etree as _lxml_etree
from selectolax.parser import HTMLParser
from colorama import Fore, Style, init
init(autoreset=True)
from rich.console import Console as _RConsole
from rich.table import Table as _RTable
from rich.progress import (Progress as _RProgress, SpinnerColumn,
TextColumn, BarColumn, TaskProgressColumn,
TimeElapsedColumn)
from rich.panel import Panel as _RPanel
from rich import box as _rbox
_rc = _RConsole()
import tldextract as _tldex
from pydantic import BaseModel, field_validator
from typing import Optional, List
import duckdb as _duckdb
try:
import trafilatura as _trafilatura
TRAFILATURA_OK = True
except ImportError:
TRAFILATURA_OK = False
try:
import dns.resolver as _dns
DNS_OK = True
except ImportError:
DNS_OK = False
PLAYWRIGHT_OK = False
try:
from playwright.sync_api import sync_playwright as _sync_pw
PLAYWRIGHT_OK = True
except ImportError:
pass
R=Fore.RED; BR=Fore.LIGHTRED_EX; Y=Fore.YELLOW; W=Fore.WHITE
G=Fore.GREEN; C=Fore.CYAN; M=Fore.MAGENTA; DIM=Style.DIM
BOLD=Style.BRIGHT; RE=Style.RESET_ALL
class Finding(BaseModel):
severity: str
confidence: str
category: str
title: str
detail: Optional[str] = ""
remediation: Optional[str] = ""
caveats: Optional[List[str]] = []
@field_validator("severity")
@classmethod
def valid_sev(cls, v):
allowed = {"CRITICAL","HIGH","MEDIUM","LOW","INFO"}
v = v.upper()
if v not in allowed:
v = "INFO"
return v
@field_validator("confidence")
@classmethod
def valid_conf(cls, v):
allowed = {"CONFIRMED","LIKELY","POSSIBLE","UNVERIFIED"}
v = v.upper()
if v not in allowed:
v = "UNVERIFIED"
return v
def to_dict(self):
return self.model_dump()
def tw():
try: return os.get_terminal_size().columns
except: return 100
def ctr(text, fill=" "):
"""Centre a raw string (strip ANSI for width calc)."""
ansi = re.compile(r'\x1b\[[0-9;]*m')
visible = len(ansi.sub("", text))
pad = max(0, (tw() - visible) // 2)
return fill*pad + text
def rule(char="─", color=R):
return color + char * tw() + RE
def sep(char="▓", color=R):
print(color + char * tw() + RE)
_log_lock = threading.Lock()
_LOG_FILE: str = ""
def _set_log_file(path: str):
global _LOG_FILE
_LOG_FILE = path
with open(path, "w", encoding="utf-8") as f:
f.write(f"FlowOsint v2.01 — Live Log\nStarted: {datetime.now()}\n{'='*60}\n\n")
def _write_log(raw: str):
"""Strip ANSI codes and append to live log file."""
if not _LOG_FILE:
return
clean = re.sub(r'\x1b\[[0-9;]*m', '', raw)
try:
with open(_LOG_FILE, "a", encoding="utf-8") as f:
f.write(clean + "\n")
except Exception:
pass
_ANSI_RE = re.compile(r'\x1b\[[0-9;]*m')
def _log(tag, col, msg):
ts = datetime.now().strftime("%H:%M:%S")
raw = f"[{ts}] [{tag}] {_ANSI_RE.sub('', str(msg))}"
with _log_lock:
print(f"{DIM}{W}[{ts}]{RE} {col}{BOLD}[{tag}]{RE} {W}{msg}{RE}")
_write_log(raw)
def hit(m): _log("FOUND", BR, m)
def info(m): _log(" INFO", C, m)
def warn(m): _log(" WARN", Y, m)
def err(m): _log("ERROR", R, m)
def sect(m):
bar = "─" * tw()
lbl = f"[ {m.upper()} ]"
with _log_lock:
print(f"\n{R}{bar}{RE}\n{ctr(f'{BR}{BOLD}{lbl}{RE}')}\n{R}{bar}{RE}\n")
_write_log(f"\n{bar}\n{lbl}\n{bar}\n")
class Spinner:
"""Wraps rich Progress so we get a proper spinner + elapsed time."""
def __init__(self, msg="Working"):
self.msg = msg
self._prog = _RProgress(
SpinnerColumn(style="bold red"),
TextColumn("[bold white]{task.description}"),
TimeElapsedColumn(),
transient=True,
console=_rc,
)
self._task = None
def start(self):
self._prog.start()
self._task = self._prog.add_task(f"{self.msg}", total=None)
return self
def stop(self, done="Done"):
self._prog.stop()
_rc.print(f" [bold green]✔[/] [white]{done}[/]")
LOGO_LINES = [
f"{BR} █████▒ ██▓ ▒█████ █ █░ ▒█████ ██████ ██▓ ███▄ █ ▄▄▄█████▓{RE}",
f"{R} ▓██ ▒ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░▒██▒ ██▒▒██ ▒ ▓██▒ ██ ▀█ █ ▓ ██▒ ▓▒{RE}",
f"{BR} ▒████ ░ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▒██░ ██▒░ ▓██▄ ▒██▒ ▓██ ▀█ ██▒ ▒ ▓██░ ▒░{RE}",
f"{R} ░▓█▒ ░ ▒██░ ▒██ ██░░█░ █ ░█ ▒██ ██░ ▒ ██▒░██░ ▓██▒ ▐▌██▒ ░ ▓██▓ ░ {RE}",
f"{BR} ░▒█░ ░██████░ ████▓▒░░░██▒██▓ ░ ████▓▒░▒██████▒▒░██░ ▒██░ ▓██░ ▒██▒ ░ {RE}",
f"{R} ▒ ░ ░ ▒░▓ ░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░▒░▒░ ▒ ▒▓▒ ▒ ░░▓ ░ ▒░ ▒ ▒ ▒ ░░ {RE}",
f"{BR} ░ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ▒ ▒░ ░ ░▒ ░ ░ ▒ ░ ░ ░░ ░ ▒░ ░ {RE}",
f"{R} ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ▒ ░ ░ ░ ░ ░ {RE}",
f"{BR} ░ ░ ░ ░ ░ ░ ░ ░ ░ {RE}",
]
def banner():
os.system("cls" if os.name=="nt" else "clear")
for line in LOGO_LINES:
print(ctr(line))
time.sleep(0.04)
print(ctr(f"{DIM}{W}v2.01 · Advanced Web Recon & OSINT · github.com/FlowThingy/FlowOsint{RE}"))
print()
MENU_PAGES = {
1: {
"cols": [
("Web Recon", [
("01","Full Recon (All Modules)"),
("02","Dir & File Bruteforce"),
("03","Subdomain Probe"),
("04","Link & Form Crawler"),
("05","JS File Analysis"),
("06","HTML Comment Dump"),
("07","CSS Asset Extractor"),
]),
("OSINT", [
("08","Robots & Sitemap"),
("09","Tech Fingerprint"),
("10","WAF / CDN Detect"),
("11","Header Inspector"),
("12","Cookie Auditor"),
("13","DNS Record Lookup"),
("14","WHOIS Lookup"),
]),
("Deep Analysis", [
("15","JS Secret Hunter"),
("16","Hidden Field Dump"),
("17","Form Harvester"),
("18","Email Harvester"),
("19","Open Redirect Probe"),
("20","Open Ports Scan"),
("21","Full Report Export"),
]),
]
},
2: {
"cols": [
("Vulnerability", [
("22","SQLi Error Probe"),
("23","XSS Reflection Test"),
("24","LFI Path Test"),
("25","SSL/TLS Inspector"),
("26","HTTP Methods Test"),
("27","Clickjack / CSP Check"),
("28","CORS Policy Check"),
]),
("Network / Intel", [
("29","IP Geolocation"),
("30","Reverse IP Lookup"),
("31","SPF / DMARC Check"),
("32","Security Headers"),
("33","Google Dork Generator"),
("34","Shodan InternetDB"),
("35","VirusTotal Domain"),
]),
("Threat / OSINT APIs", [
("36","Wayback Machine"),
("37","GreyNoise IP Check"),
("38","urlscan.io Analysis"),
("40","HaveIBeenPwned"),
("41","crt.sh CT Logs"),
("42","Email Security Audit"),
("43","CMS Context JSON Probe"),
]),
]
},
3: {
"cols": [
("Utilities", [
("44","Doc Metadata Harvest"),
("45","Risk Score Report"),
("46","Playwright JS Scan"),
("47","JS-Rendered Crawl"),
("48","DuckDB Query"),
("49","Trafilatura Extract"),
("50","Batch URL Scanner"),
]),
("Tools", [
("51","Hash a String"),
("52","Encode / Decode Base64"),
("53","Extract All URLs"),
]),
("", []),
]
},
4: {
"cols": [
("Social OSINT", [
("60","Username Search"),
("61","Email OSINT"),
("62","GitHub User OSINT"),
]),
("", []),
("System", [
("98","Settings"),
("00","Exit"),
]),
]
},
}
_current_page = [1]
_COMPACT_REMAP = {
"34": "50",
"35": "51",
"36": "52",
"37": "53",
"38": "54",
"40": "55",
"50": "40",
"51": "36",
"52": "37",
"53": "38",
}
def draw_menu():
W_term = tw()
page = MENU_PAGES[_current_page[0]]
cols = page["cols"]
col_w = 28
n = len(cols)
total = n * col_w + (n-1) * 5
left = max(0, (W_term - total) // 2)
pad = " " * left
pg = _current_page[0]
nav = f"{R}[{W}I{R}] Info [{W}S{R}] Settings [{W}00{R}] Exit"
nav_r = f"Page {pg}/4 [{W}N{R}] Next ▶{RE}"
total_nav = len(_ANSI_RE.sub("", nav + nav_r))
gap = max(1, W_term - total_nav - 2)
print(f" {nav}{' '*gap}{nav_r}")
header_line = pad
for i,(title,_) in enumerate(cols):
box = f"{R}┌{'─'*(col_w-2)}┐{RE}"
header_line += box + (" " if i < n-1 else "")
print(header_line)
title_line = pad
for i,(title,_) in enumerate(cols):
inner = f" {BR}{BOLD}{title:<{col_w-4}}{RE} "
box = f"{R}│{RE}{inner}{R}│{RE}"
title_line += box + (" " if i < n-1 else "")
print(title_line)
bottom_line = pad
for i,_ in enumerate(cols):
box = f"{R}└{'─'*(col_w-2)}┘{RE}"
bottom_line += box + (" " if i < n-1 else "")
print(bottom_line)
max_rows = max(len(items) for _,items in cols)
for r_idx in range(max_rows):
row_line = pad
for c_idx,(_,items) in enumerate(cols):
if r_idx < len(items):
num, label = items[r_idx]
cell = f"{R}─{RE} {R}[{W}{num}{R}]{RE} {W}{label:<{col_w-7}}{RE}"
else:
cell = " " * col_w
row_line += cell + (" " if c_idx < n-1 else "")
print(row_line)
print()
sep()
UAS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64; rv:115.0) Gecko/20100101 Firefox/115.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Edg/124.0",
]
def mk_session(proxy=None, cookies=None, extra_headers=None, timeout=12):
"""
Build an httpx client (HTTP/2 capable) with requests fallback stored.
Returns an httpx.Client that also has ._fo_timeout and ._requests_session.
"""
headers = {
"User-Agent": random.choice(UAS),
"Accept": "text/html,application/xhtml+xml,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
}
if extra_headers:
headers.update(extra_headers)
httpx_proxy_kwargs = {"proxy": proxy} if proxy else {}
try:
import h2 # noqa: F401
_http2 = True
except ImportError:
_http2 = False
client = httpx.Client(
http2=_http2,
verify=False,
timeout=timeout,
headers=headers,
cookies=cookies or {},
follow_redirects=True,
**httpx_proxy_kwargs,
)
client._fo_timeout = timeout
rs = requests.Session()
rs.verify = False
rs.headers.update(headers)
if cookies:
for k,v in cookies.items(): rs.cookies.set(k,v)
if proxy: rs.proxies = {"http":proxy,"https":proxy}
rs._fo_timeout=timeout
client._requests_session = rs
return client
def get(session, url):
"""
Fetch url via httpx (HTTP/2).
Falls back to requests on httpx failure.
"""
try:
r = session.get(url)
return r
except Exception:
pass
try:
rs = getattr(session, "_requests_session", None)
if rs:
return rs.get(url, timeout=getattr(session,"_fo_timeout",12),
verify=False, allow_redirects=True)
except Exception:
pass
return None
def extract_domain(url: str) -> str:
"""
Return registered domain (e.g. 'example.co.uk' not just 'co.uk').
tldextract uses the Public Suffix List — handles .co.uk, .github.io etc.
"""
ext = _tldex.extract(url)
return f"{ext.domain}.{ext.suffix}" if ext.suffix else ext.domain
def extract_subdomain(url: str) -> str:
return _tldex.extract(url).subdomain
_DB_PATH = ""
_DB_LOCK = threading.Lock() # BUG FIX: concurrent DuckDB writes from threaded scans
def _init_db(domain: str):
"""Create/open a per-scan DuckDB file and set up the findings table."""
global _DB_PATH
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
_DB_PATH = f"flowoosint_{domain.replace('.','_')}_{ts}.duckdb"
con = _duckdb.connect(_DB_PATH)
con.execute("""
CREATE TABLE IF NOT EXISTS findings (
id INTEGER PRIMARY KEY,
severity VARCHAR,
confidence VARCHAR,
category VARCHAR,
title VARCHAR,
detail VARCHAR,
remediation VARCHAR,
caveats VARCHAR,
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
con.execute("""
CREATE TABLE IF NOT EXISTS assets (
id INTEGER PRIMARY KEY,
type VARCHAR,
value VARCHAR,
source VARCHAR,
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
con.close()
info(f"Scan DB: {BR}{_DB_PATH}{RE} (query with duckdb or DBeaver)")
def _db_insert_finding(f: dict):
if not _DB_PATH: return
with _DB_LOCK: # BUG FIX: serialize concurrent inserts from threaded modules
try:
con = _duckdb.connect(_DB_PATH)
con.execute("""
INSERT INTO findings (severity,confidence,category,title,detail,remediation,caveats)
VALUES (?,?,?,?,?,?,?)
""", [f.get("severity"), f.get("confidence"), f.get("category"),
f.get("title"), f.get("detail","")[:500],
f.get("remediation","")[:500],
json.dumps(f.get("caveats",[]))])
con.close()
except Exception: pass
def _db_insert_asset(asset_type: str, value: str, source: str = ""):
if not _DB_PATH: return
with _DB_LOCK: # BUG FIX: serialize concurrent inserts from threaded modules
try:
con = _duckdb.connect(_DB_PATH)
con.execute(
"INSERT INTO assets (type,value,source) VALUES (?,?,?)",
[asset_type, str(value)[:500], source]
)
con.close()
except Exception: pass
def db_query(sql: str):
"""Run any SQL against the current scan DB and print a rich table."""
if not _DB_PATH:
warn("No scan database yet — run a scan first"); return
try:
con = _duckdb.connect(_DB_PATH)
rel = con.execute(sql)
rows = rel.fetchall()
cols = [d[0] for d in rel.description]
con.close()
t = _RTable(box=_rbox.SIMPLE, style="dim", header_style="bold red")
for c in cols: t.add_column(c, style="white")
for row in rows: t.add_row(*[str(v) if v is not None else "" for v in row])
_rc.print(t)
info(f"{len(rows)} row(s) returned")
except Exception as e:
err(f"DB query error: {e}")
DIRS = [
"admin","administrator","login","dashboard","panel","cpanel","wp-admin",
"phpmyadmin","api","api/v1","api/v2","v1","v2","v3","swagger","swagger-ui",
"docs","doc","backup","backups","bak","db","database","config","conf",
".git",".svn",".env","env","secret","secrets","private","uploads","upload",
"files","media","static","assets","js","css","images","img","vendor","src",
"app","server","data","dev","staging","test","beta","old","temp","tmp",
"cache","log","logs","error","debug","trace","help","support","faq","about",
"profile","user","users","account","accounts","member","register","signup",
"signin","logout","auth","oauth","token","session","reset","forgot","password",
"key","keys","cert","ssl","manage","management","settings","setup","install",
"update","download","export","import","report","search","sitemap","robots",
"robots.txt","sitemap.xml",".htaccess",".htpasswd","web.config",
"crossdomain.xml","phpinfo.php","info.php","test.php","debug.php",
"wp-content","wp-includes","wp-login.php","xmlrpc.php","readme.html",
"license.txt","composer.json","package.json",".gitignore","Dockerfile",
"docker-compose.yml","console","terminal","health","healthcheck","status",
"monitor","metrics","stats","analytics","graphql","websocket","socket",
"jenkins","gitlab","grafana","kibana","elasticsearch","redis",
".well-known","well-known","security.txt",".well-known/security.txt",
"actuator","actuator/env","actuator/mappings","actuator/health",
"trace","dump","heapdump","threaddump","beans","autoconfig",
]
EXTS = ["",".php",".html",".htm",".txt",".bak",".zip",".env",
".json",".xml",".conf",".log",".sql",".yml",".yaml",".old",".orig"]
def mod_dirbust(base, session, threads=25, wordlist=None):
sect("Directory & File Discovery")
# bro if this finds admin panel its over for them fr
# this function just brute forces paths like /admin /backup /.env etc
words = wordlist or DIRS
q = queue.Queue()
for w in words:
for e in EXTS:
q.put(w+e)
total = q.qsize()
found_list = []
with _RProgress(
SpinnerColumn(style="bold red"),
TextColumn("[bold white]{task.description}"),
BarColumn(bar_width=30, style="red", complete_style="bright_red"),
TaskProgressColumn(),
TimeElapsedColumn(),
console=_rc, transient=True,
) as progress:
task = progress.add_task(f"Probing {total} paths", total=total)
def worker():
while True:
try: path = q.get_nowait()
except queue.Empty: break
url = base.rstrip("/")+"/"+path.lstrip("/")
r = get(session, url)
if r and r.status_code not in (404,400,410,406):
code, size = r.status_code, len(r.content)
clr = BR if code==200 else (Y if code in (301,302,307,308) else C)
hit(f"{clr}[{code}]{RE} {W}{url} {DIM}({size} B)")
found_list.append({"url":url,"status":code,"size":size})
_db_insert_asset("path", url, f"dirbust:{code}")
progress.advance(task)
q.task_done()
pool = [threading.Thread(target=worker,daemon=True) for _ in range(min(threads,50))]
for t in pool: t.start()
for t in pool: t.join()
info(f"Directory scan done — {BR}{len(found_list)} paths discovered")
return found_list
SUBS = [
"www","mail","ftp","smtp","pop","imap","ns1","ns2","dns","vpn","dev",
"staging","test","beta","api","app","portal","admin","dashboard","git",
"repo","cdn","static","assets","media","img","upload","blog","shop",
"store","pay","payment","secure","ssl","login","auth","sso","oauth",
"id","identity","internal","intranet","corp","hr","crm","erp","support",
"help","docs","wiki","forum","community","news","webmail","mx","mx1","mx2",
"email","newsletter","analytics","track","monitor","status","health",
"metrics","grafana","kibana","jenkins","gitlab","ci","cd","build","deploy",
"prod","production","qa","uat","sandbox","demo","mobile","m","wap","preview",
"old","new","legacy","backup","db","database","mysql","pgsql","mongo",
"redis","elastic","search","img2","images","files","download","uploads",
"cloud","s3","bucket","storage","video","stream","live","chat","ws",
"socket","api2","api3","v2","v3","dev2","test2","stg","preprod",
]
def mod_subdomains(domain, session):
sect("Subdomain Probe")
# staging.target.com hits different ngl
reg = extract_domain(domain)
found_list = []
q = queue.Queue()
for s in SUBS: q.put(s+"."+reg)
total = q.qsize()
with _RProgress(
SpinnerColumn(style="bold red"),
TextColumn("[bold white]{task.description}"),
BarColumn(bar_width=30, style="red", complete_style="bright_red"),
TaskProgressColumn(),
TimeElapsedColumn(),
console=_rc, transient=True,
) as progress:
task = progress.add_task(f"Probing {total} subdomains", total=total)
def probe():
while True:
try: host = q.get_nowait()
except queue.Empty: break
for scheme in ('https','http'):
try:
r = get(session, f"{scheme}://{host}")
if r and r.status_code not in (400,None):
clr = BR if r.status_code==200 else Y
hit(f"{clr}[{r.status_code}]{RE} {scheme}://{host}")
found_list.append({"host":host,"scheme":scheme,"status":r.status_code})
_db_insert_asset("subdomain", host, f"{scheme}:{r.status_code}")
break
except Exception: continue
progress.advance(task)
q.task_done()
pool = [threading.Thread(target=probe,daemon=True) for _ in range(40)]
for t in pool: t.start()
for t in pool: t.join()
info(f"Subdomain probe done — {BR}{len(found_list)} responded")
return found_list
def _parse_page_selectolax(html: str, base_url: str, parsed_base):
"""
Fast extraction using selectolax (Gumbo/Lexbor C parser).
Returns links, scripts, styles, forms found on this page.
"""
links, scripts, styles, forms = [], [], [], []
try:
tree = HTMLParser(html)
except Exception:
return links, scripts, styles, forms
def _attr(node, key, fallback=""):
v = node.attributes.get(key, fallback)
return (v or fallback).strip()
for node in tree.css("a[href]"):
href = _attr(node, "href")
if href:
full = urljoin(base_url, href)
links.append(full)
for node in tree.css("script[src]"):
src = _attr(node, "src")
if src:
scripts.append(urljoin(base_url, src))
for node in tree.css("link[rel]"):
rel = _attr(node, "rel")
if "stylesheet" in rel:
href = _attr(node, "href")
if href:
styles.append(urljoin(base_url, href))
for form in tree.css("form"):
action_raw = _attr(form, "action") or base_url
action = urljoin(base_url, action_raw)
method = (_attr(form, "method") or "GET").upper()
fields = [_attr(n, "name")
for n in form.css("input,textarea,select")
if _attr(n, "name")]
forms.append({"page":base_url,"action":action,"method":method,"fields":fields})
return links, scripts, styles, forms
def _parse_page_lxml(html: str, base_url: str):
"""
Deep extraction using lxml XPath — catches things selectolax misses
in malformed or complex HTML (data-src lazy-load, noscript blocks, etc.)
"""
extra = []
try:
parser = _lxml_etree.HTMLParser(recover=True)
tree = _lxml_etree.fromstring(html.encode("utf-8","replace"), parser)
if tree is None:
return extra
for el in tree.xpath("//*[@data-src]"):
src = el.get("data-src","").strip()
if src and not src.startswith("data:"):
extra.append(urljoin(base_url, src))
for el in tree.xpath("//noscript//a[@href]"):
href = el.get("href","").strip()
if href:
extra.append(urljoin(base_url, href))
for tag in ("iframe","embed","object","frame"):
for el in tree.xpath(f"//{tag}[@src]"):
src = el.get("src","").strip()
if src and not src.startswith("data:"):
extra.append(urljoin(base_url, src))
for el in tree.xpath("//meta[@http-equiv]"):
if "refresh" in el.get("http-equiv","").lower():
content = el.get("content","")
m = re.search(r'url=(.+)', content, re.I)
if m:
extra.append(urljoin(base_url, m.group(1).strip().strip("'\"")))
except Exception:
pass
return extra
def _render_with_playwright(url: str, timeout_ms: int = 15000) -> str:
"""
Launch headless Chromium, navigate to url, wait for network idle,
return the fully rendered HTML. Only called when PLAYWRIGHT_OK=True.
"""
if not PLAYWRIGHT_OK:
return ""
try:
with _sync_pw() as pw:
browser = pw.chromium.launch(headless=True)
page = browser.new_page()
page.goto(url, wait_until="networkidle", timeout=timeout_ms)
html = page.content()
browser.close()
return html
except Exception as e:
warn(f"Playwright render failed: {e}")
return ""
def mod_crawler(base, session, depth=2, js_render=False):
sect("Link, Script & Form Crawler")
if js_render and PLAYWRIGHT_OK:
info(f"{G}JS rendering mode ON{RE} (Playwright — full SPA support)")
elif js_render and not PLAYWRIGHT_OK:
warn("Playwright not installed — JS rendering disabled. "
"Install: pip install playwright && playwright install chromium")
parsed_base = urlparse(base)
visited, to_visit = set(), {base}
links,scripts,styles,forms = [],[],[],[]
lxml_extras = []
for _ in range(depth):
nxt = set()
for url in list(to_visit):
if url in visited: continue
visited.add(url)
r = get(session, url)
if not r: continue
ct = r.headers.get("content-type","") if hasattr(r.headers,"get") \
else dict(r.headers).get("content-type","")
if "text/html" not in ct: continue
html = r.text
if js_render and PLAYWRIGHT_OK and len(html.strip()) < 3000:
rendered = _render_with_playwright(url)
if rendered:
html = rendered
info(f"{G}[JS-rendered]{RE} {url}")
pg_links, pg_scripts, pg_styles, pg_forms = \
_parse_page_selectolax(html, url, parsed_base)
extras = _parse_page_lxml(html, url)
for full in pg_links:
if full not in links:
links.append(full)
info(f"{C}Link{RE} {W}{full}")
p = urlparse(full)
if p.netloc == parsed_base.netloc and full not in visited:
nxt.add(full)
for src in pg_scripts:
if src not in scripts:
scripts.append(src)
hit(f"{Y}Script{RE} {W}{src}")
for href in pg_styles:
if href not in styles:
styles.append(href)
hit(f"{M}Style{RE} {W}{href}")
for entry in pg_forms:
forms.append(entry)
hit(f"{BR}Form{RE} {W}{entry['action']} "
f"{DIM}[{entry['method']}] {entry['fields']}")
for ex in extras:
if ex not in lxml_extras:
lxml_extras.append(ex)
info(f"{C}[lxml]{RE} {W}{ex}")
to_visit = nxt
info(f"Crawl done — {len(links)} links | {len(scripts)} scripts | "
f"{len(styles)} styles | {len(forms)} forms | "
f"{len(lxml_extras)} lxml extras")
return {"links":links,"scripts":scripts,"styles":styles,
"forms":forms,"lxml_extras":lxml_extras}
import math as _math
def _shannon_entropy(s: str) -> float:
"""
Calculate Shannon entropy (bits per character) of a string.
Real API keys generated by cryptographic RNGs typically score >= 3.5.
Placeholder / test keys (e.g. 'xxxxxxxx', 'A9A9A9A9', '1234567890') score < 3.0.
"""
if not s:
return 0.0
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
length = len(s)
return -sum((c / length) * _math.log2(c / length) for c in freq.values())
def _char_diversity(s: str) -> float:
"""
Ratio of unique characters to total length.
A repeating pattern like 'A9A9A9A9' has very low diversity.
Real keys generally have diversity > 0.4 for strings of length 16+.
"""
if not s:
return 0.0
return len(set(s)) / len(s)
_ENTROPY_SKIP = {
"Private Key", "Database URL", "Hidden Endpoint",
"GraphQL", "Relative API", "Internal IP", "Email",
}
_THRESHOLDS = {
"AWS Access Key": (3.8, 0.50),
"AWS Secret": (4.0, 0.55),
"Google API Key": (3.6, 0.50),
"Stripe Key": (3.8, 0.50),
"GitHub Token": (3.8, 0.50),
"Slack Token": (3.5, 0.45),
"SendGrid Key": (3.8, 0.50),
"JWT": (3.5, 0.40),
"Bearer Token": (3.5, 0.40),
"_default": (3.2, 0.40),
}
def _is_real_secret(label: str, value: str) -> tuple[bool, float, float]:
"""
Returns (passes, entropy, diversity).
Strings that fail either threshold are considered placeholder / fake.
"""
if label in _ENTROPY_SKIP:
return True, 0.0, 0.0
ent = _shannon_entropy(value)
div = _char_diversity(value)
min_ent, min_div = _THRESHOLDS.get(label, _THRESHOLDS["_default"])
passes = (ent >= min_ent) and (div >= min_div)
return passes, ent, div
_PLACEHOLDER_RE = re.compile(
r'^(?:'
r'x{6,}|0{6,}|1{6,}|a{6,}|' # xxxxxxxx, 000000
r'(?:test|demo|fake|sample|example|placeholder|your[_\-]?api|changeme|replace|insert)'
r')',
re.IGNORECASE
)
JS_PATTERNS = {
"API Key/Token": r'(?:api[_\-]?key|apikey|api[_\-]?token|access[_\-]?token)\s*[=:]\s*["\']([A-Za-z0-9_\-]{16,})["\']',
"AWS Access Key": r'(AKIA[0-9A-Z]{16})',
"AWS Secret": r'(?:aws[_\-]?secret|secret[_\-]?key)\s*[=:]\s*["\']([A-Za-z0-9/+=]{40})["\']',
"Google API Key": r'(AIza[0-9A-Za-z\-_]{35})',
"Private Key": r'(-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----)',
"Password": r'(?:password|passwd|pwd)\s*[=:]\s*["\']([^"\']{6,})["\']',
"Bearer Token": r'[Bb]earer\s+([A-Za-z0-9\-_=]{20,}\.[A-Za-z0-9\-_=]{20,}\.?[A-Za-z0-9\-_.+/=]*)',
"JWT": r'(eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,})',
"Internal IP": r'(\b(?:10\.|172\.(?:1[6-9]|2\d|3[01])\.|192\.168\.)\d{1,3}\.\d{1,3}\b)',
"Email": r'([a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,})',
"Hidden Endpoint": r'(?:fetch|axios\.(?:get|post|put|delete)|http\.get)\s*\(\s*["\']([/][^"\']{3,})["\']',
"GraphQL": r'(?:graphql|gql)["\s:=(]+([/][^"\')\s]{3,})',
"Database URL": r'((?:mongodb|mysql|postgres|redis|mssql)://[^\s"\'<>]+)',
"S3 Bucket": r's3\.amazonaws\.com/([a-z0-9\-\.]{3,})',
"Secret Key": r'(?:secret[_\-]?key|secretkey)\s*[=:]\s*["\']([^"\']{8,})["\']',
"Relative API": r'(["\'](?:\/api\/|\/rest\/|\/v\d\/)[a-zA-Z0-9/_\-?=&]{4,}["\'])',
"Slack Token": r'(xox[baprs]-[0-9A-Za-z\-]{10,})',
"Stripe Key": r'((?:sk|pk)_(?:live|test)_[0-9A-Za-z]{24,})',
"GitHub Token": r'(gh[pousr]_[A-Za-z0-9]{36,})',
"Twilio SID": r'(AC[a-z0-9]{32})',
"SendGrid Key": r'(SG\.[A-Za-z0-9\-_]{22}\.[A-Za-z0-9\-_]{43})',
}
def mod_js(scripts, session):
sect("JavaScript Intelligence — Secrets & Endpoints")
# devs really just leave aws keys in prod js files 💀
result = []
rejected = 0
for url in scripts:
resp = get(session, url)
if not resp:
continue
found_here = False
for label, pat in JS_PATTERNS.items():
for m in re.findall(pat, resp.text, re.IGNORECASE):
val = m if isinstance(m, str) else (m[0] if m else "")
val = val.strip().strip('"\'')
if not val:
continue
if _PLACEHOLDER_RE.match(val):
info(f"{DIM}[placeholder] {label}: {val[:60]}")
rejected += 1
continue
passes, ent, div = _is_real_secret(label, val)
if not passes:
info(
f"{DIM}[low-entropy] {label}: {val[:60]}"
f" entropy={ent:.2f} diversity={div:.2f}"
)
rejected += 1
continue
ent_tag = f"{DIM}[H:{ent:.2f} D:{div:.2f}]{RE}" if ent > 0 else ""
hit(
f"{BR}{label}{RE}: {W}{val[:120]}{RE}"
f" {ent_tag} {DIM}← {url}"
)
result.append({
"script": url,
"type": label,
"value": val[:120],
"entropy": round(ent, 3),
"diversity": round(div, 3),
})
found_here = True
if not found_here:
info(f"Clean: {DIM}{url}")
info(
f"JS scan done — {BR}{len(result)} real findings{RE} "
f"{DIM}({rejected} low-entropy / placeholder strings discarded)"
)
return result