forked from naksyn/PythonMemoryModule
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.py
More file actions
1557 lines (1245 loc) · 55.3 KB
/
process.py
File metadata and controls
1557 lines (1245 loc) · 55.3 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
import sys
import ctypes
import os
import copy
import time
import struct
import itertools
from contextlib import contextmanager
from collections import namedtuple
import windows
import windows.native_exec.simple_x86 as x86
import windows.native_exec.simple_x64 as x64
import windows.remotectypes as rctypes
import windows.generated_def as gdef
from windows import injection
from windows import native_exec
from windows import pe_parse
from windows import winproxy
from windows import utils
from windows.dbgprint import dbgprint
from windows.generated_def.winstructs import *
from windows.generated_def.ntstatus import NtStatusException
from windows.winobject import exception
from windows.winobject import apisetmap
from windows.winobject import token
from windows import security
from windows.pycompat import raw_encode, raw_decode, basestring
TimeInfo = namedtuple("TimeInfo", ["creation", "exit", "kernel", "user"])
"""Time information about a process"""
class DeadThread(utils.AutoHandle):
"""An already dead thread (returned only by API returning a new thread if thread die before being returned)"""
def __init__(self, handle, tid=None):
if tid is None:
tid = WinThread._get_thread_id(handle)
self.tid = tid
# set AutoHandle _handle
self._handle = handle
@property
def is_exit(self):
"""``True`` if the thread is terminated
:type: :class:`bool`
"""
return self.exit_code != STILL_ACTIVE
@property
def exit_code(self):
"""The exit code of the thread : ``STILL_ACTIVE`` means the process is not dead
:type: :class:`int`
"""
res = DWORD()
winproxy.GetExitCodeThread(self.handle, byref(res))
return res.value
class Process(utils.AutoHandle):
@utils.fixedpropety
def is_wow_64(self):
"""``True`` if the process is a SysWow64 process (32bit process on 64bits system).
:type: :class:`bool`
"""
# return utils.is_wow_64(self.handle)
return utils.is_wow_64(self.limited_handle)
@utils.fixedpropety
def bitness(self):
"""The bitness of the process
:returns: :class:`int` -- 32 or 64
"""
if windows.system.bitness == 32:
return 32
if self.is_wow_64:
return 32
return 64
@utils.fixedpropety
def limited_handle(self):
if windows.system.version[0] <= 5:
# Windows XP | Serveur 2003
return winproxy.OpenProcess(PROCESS_QUERY_INFORMATION, dwProcessId=self.pid)
return winproxy.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, dwProcessId=self.pid)
@utils.fixedpropety
def ppid(self):
"""Parent Process ID
:type: :class:`int`
"""
if windows.current_process.bitness == 32 and self.bitness == 64:
xtype = windows.remotectypes.transform_type_to_remote64bits(PROCESS_BASIC_INFORMATION)
# Fuck-it <3
data = (ctypes.c_char * ctypes.sizeof(xtype))()
windows.syswow64.NtQueryInformationProcess_32_to_64(self.limited_handle, ProcessInformation=data, ProcessInformationLength=ctypes.sizeof(xtype))
# Map a remote64bits(PROCESS_BASIC_INFORMATION) at the address of 'data'
x = xtype(ctypes.addressof(data), windows.current_process)
else:
information_type = 0
x = PROCESS_BASIC_INFORMATION()
winproxy.NtQueryInformationProcess(self.limited_handle, information_type, x)
return x.InheritedFromUniqueProcessId
@property
def threads(self):
"""The threads of the process
:type: [:class:`WinThread`] -- A list of Thread
"""
owner_pid = self.pid
return [WinThread._from_THREADENTRY32(th, owner=self) for th in windows.system.enumerate_threads_generator() if th.th32OwnerProcessID == owner_pid]
def virtual_alloc(self, size):
raise NotImplementedError("virtual_alloc")
def virtual_free(self):
raise NotImplementedError("virtual_free")
@property
def exit_code(self):
"""The exit code of the process : ``STILL_ACTIVE`` means the process is not dead
:type: :class:`int`
"""
res = DWORD()
winproxy.GetExitCodeProcess(self.handle, byref(res))
return res.value
@property
def is_exit(self):
"""``True`` if the process is terminated
:type: :class:`bool`
"""
return self.exit_code != STILL_ACTIVE
@contextmanager
def allocated_memory(self, size, prot=PAGE_EXECUTE_READWRITE):
"""ContextManager to allocate memory and free it
:type: :class:`int` -- the address of the allocated memory
"""
addr = self.virtual_alloc(size, prot=prot)
try:
yield addr
finally:
winproxy.VirtualFreeEx(self.handle, addr)
@contextmanager
def virtual_protected(self, addr, size, protect):
"""A context manager for local virtual_protect (old Protection are restored at exit)"""
old_protect = DWORD()
self.virtual_protect(addr, size, protect, old_protect)
try:
yield addr
finally:
self.virtual_protect(addr, size, old_protect.value, old_protect)
def virtual_protect(self, addr, size, protect, old_protect=None):
"""Change the access right of one or more page of the process"""
if windows.current_process.bitness == 32 and self.bitness == 64:
if size & 0x0fff:
size = ((size >> 12) + 1) << 12
if old_protect is None:
old_protect = gdef.DWORD()
xold_protect = ctypes.addressof(old_protect)
xaddr = ULONG64(addr)
addr = ctypes.addressof(xaddr)
xsize = ULONG(size)
size = ctypes.addressof(xsize)
return windows.syswow64.NtProtectVirtualMemory_32_to_64(self.handle, addr, size, protect, xold_protect)
else:
winproxy.VirtualProtectEx(self.handle, addr, size, protect, old_protect)
def execute(self, code, parameter=0):
"""Execute some native code in the context of the process
:return: The thread executing the code
:rtype: :class:`WinThread` or :class:`DeadThread`
"""
x = self.virtual_alloc(len(code)) #Todo: free this ? when ? how ? reuse ?
self.write_memory(x, code)
return self.create_thread(x, parameter)
def query_memory(self, addr):
"""Query the memory informations about page at ``addr``
:rtype: :class:`~windows.generated_def.winstructs.MEMORY_BASIC_INFORMATION`
"""
if windows.current_process.bitness == 32 and self.bitness == 64:
res = MEMORY_BASIC_INFORMATION64()
try:
v = windows.syswow64.NtQueryVirtualMemory_32_to_64(ProcessHandle=self.handle, BaseAddress=addr, MemoryInformationClass=MemoryBasicInformation, MemoryInformation=res)
except NtStatusException as e:
if e.code & 0xffffffff == 0XC000000D:
raise winproxy.WinproxyError("NtQueryVirtualMemory_32_to_64")
raise
return res
info_type = {32 : MEMORY_BASIC_INFORMATION32, 64 : MEMORY_BASIC_INFORMATION64}
res = info_type[windows.current_process.bitness]()
ptr = ctypes.cast(byref(res), POINTER(MEMORY_BASIC_INFORMATION))
winproxy.VirtualQueryEx(self.handle, addr, ptr, sizeof(res))
return res
def memory_state(self):
"""Yield the memory information for the whole address space of the process
:yield: :class:`~windows.generated_def.winstructs.MEMORY_BASIC_INFORMATION`
"""
addr = 0
res = []
while True:
try:
x = self.query_memory(addr)
yield x
except winproxy.WinproxyError:
return
addr += x.RegionSize
def query_working_set(self):
if self.bitness == 64 or windows.current_process.bitness == 64:
WSET_BLOCK = EPSAPI_WORKING_SET_BLOCK64
dummy = PSAPI_WORKING_SET_INFORMATION64()
else:
WSET_BLOCK = EPSAPI_WORKING_SET_BLOCK32
dummy = PSAPI_WORKING_SET_INFORMATION32()
try:
windows.winproxy.QueryWorkingSet(self.handle, ctypes.byref(dummy), ctypes.sizeof(dummy))
except WindowsError as e:
if e.winerror != 24:
raise
NumberOfEntriesType = [f for f in WSET_BLOCK._fields_ if f[0] == "Flags"][0][1]
for i in range(10):
# use the same type as WSET_BLOCK.Flags
class GENERATED_PSAPI_WORKING_SET_INFORMATION(ctypes.Structure):
_fields_ = [
("NumberOfEntries", NumberOfEntriesType),
("WorkingSetInfo", WSET_BLOCK * dummy.NumberOfEntries),
]
res = GENERATED_PSAPI_WORKING_SET_INFORMATION()
try:
if windows.current_process.bitness == 32 and self.bitness == 64:
windows.syswow64.NtQueryVirtualMemory_32_to_64(self.handle, 0, MemoryWorkingSetList, res)
else:
windows.winproxy.QueryWorkingSet(self.handle, ctypes.byref(res), ctypes.sizeof(res))
except WindowsError as e:
if e.winerror != 24:
raise
dummy.NumberOfEntries = res.NumberOfEntries
continue
except windows.generated_def.ntstatus.NtStatusException as e:
if e.code != STATUS_INFO_LENGTH_MISMATCH:
raise
dummy.NumberOfEntries = res.NumberOfEntries
continue
return res.WorkingSetInfo
# Raise ?
return None
def query_working_setex(self, addresses):
if self.bitness == 64 or windows.current_process.bitness == 64:
info_type = EPSAPI_WORKING_SET_EX_INFORMATION64
else:
info_type = EPSAPI_WORKING_SET_EX_INFORMATION32
info_array = (info_type * len(addresses))()
for i, data in enumerate(info_array):
info_array[i].VirtualAddress = addresses[i]
if windows.current_process.bitness == 32 and self.bitness == 64:
windows.syswow64.NtQueryVirtualMemory_32_to_64(self.handle, 0, MemoryWorkingSetListEx, info_array)
else:
winproxy.QueryWorkingSetEx(self.handle, ctypes.byref(info_array), ctypes.sizeof(info_array))
return info_array
def get_mapped_filename(self, addr):
"""The filename mapped at address ``addr`` or ``None``
:rtype: :class:`unicode` or ``None``
"""
buffer_size = 0x1000
buffer = ctypes.c_buffer(buffer_size)
if windows.current_process.bitness == 32 and self.bitness == 64:
target_size = ctypes.c_buffer(buffer_size)
try:
windows.syswow64.NtQueryVirtualMemory_32_to_64(self.handle, addr, MemorySectionName, buffer, buffer_size, target_size)
except NtStatusException as e:
if e.code not in (STATUS_FILE_INVALID, STATUS_INVALID_ADDRESS):
raise
return None
remote_winstring = rctypes.transform_type_to_remote64bits(gdef.LSA_UNICODE_STRING)
mapped_filename = remote_winstring(ctypes.addressof(buffer), windows.current_process)
return mapped_filename.str
try:
size = winproxy.GetMappedFileNameW(self.handle, addr, buffer, buffer_size)
except winproxy.WinproxyError as e:
if e.winerror not in (gdef.ERROR_UNEXP_NET_ERR, gdef.ERROR_FILE_INVALID):
raise # Raise if error type is not expected: detect mapped aborted transaction
return None
return buffer[: size * 2].decode("utf16")
def read_byte(self, addr):
"""Read a ``CHAR`` at ``addr``"""
sizeof_char = sizeof(CHAR)
return struct.unpack("<B", self.read_memory(addr, sizeof_char))[0]
def read_short(self, addr):
"""Read a ``SHORT`` at ``addr``"""
sizeof_short = sizeof(ctypes.c_short)
return struct.unpack("<H", self.read_memory(addr, sizeof_short))[0]
def read_dword(self, addr):
"""Read a ``DWORD`` at ``addr``"""
sizeof_dword = sizeof(DWORD)
return struct.unpack("<I", self.read_memory(addr, sizeof_dword))[0]
def read_qword(self, addr):
"""Read a ``ULONG64`` at ``addr``"""
sizeof_qword = sizeof(ULONG64)
return struct.unpack("<Q", self.read_memory(addr, sizeof_qword))[0]
def read_ptr(self, addr):
"""Read a ``PTR`` at ``addr``"""
if self.bitness == 32:
return self.read_dword(addr)
return self.read_qword(addr)
def read_string(self, addr):
"""Read an ascii string at ``addr``"""
res = []
read_size = 0x100
readden = 0
for i in itertools.count():
try:
x = self.read_memory(addr + readden, read_size)
except WindowsError as e:
if read_size == 2:
raise
# handle read_wstring at end of page
# Of read failed: read only the half of size
# read_size must remain a multiple of 2
read_size = read_size // 2
continue
readden += read_size
if b"\x00" in x:
res.append(x.split(b"\x00", 1)[0])
break
res.append(x)
return b"".join(res).decode("ascii")
def read_wstring(self, addr):
"""Read a windows UTF16 string at ``addr``"""
res = []
read_size = 0x100
readden = 0
# I am trying to do something smart here..
while True:
try:
x = self.read_memory(addr + readden, read_size)
except WindowsError as e:
if read_size == 2:
raise
# handle read_wstring at end of page
# Of read failed: read only the half of size
# read_size must remain a multiple of 2
read_size = read_size // 2
continue
readden += read_size
# Bytearray will work on py2 & py3
# Py2: bytearray((0, 0)) == b"\x00\x00"
# Py2: bytearray((0, 0)) == b"\x00\x00"
utf16_chars = [bytearray(c) for c in zip(*[iter(x)] * 2)]
if b"\x00\x00" in utf16_chars:
# Translate bytearray to str/bytes for both py2 & py3
res.extend(x[:utf16_chars.index(b"\x00\x00") * 2])
break
res.extend(x)
return bytearray(res).decode("utf-16")
def write_byte(self, addr, byte):
"""write a byte at ``addr``"""
return self.write_memory(addr, struct.pack("<B", byte))
def write_short(self, addr, word):
"""write a word at ``addr``"""
return self.write_memory(addr, struct.pack("<H", word))
def write_dword(self, addr, dword):
"""write a dword at ``addr``"""
return self.write_memory(addr, struct.pack("<I", dword))
def write_qword(self, addr, qword):
"""write a qword at ``addr``"""
return self.write_memory(addr, struct.pack("<Q", qword))
def write_ptr(self, addr, value):
"""Write a ``PTR`` at ``addr``"""
if self.bitness == 32:
return self.write_dword(addr, value)
return self.write_qword(addr, value)
@property
def time_info(self):
"""The time information of the process (creation, kernel/user time, exit time)
:type: :class:`TimeInfo`"""
CreationTime = FILETIME()
ExitTime = FILETIME()
KernelTime = FILETIME()
UserTime = FILETIME()
winproxy.GetProcessTimes(self.limited_handle, CreationTime, ExitTime, KernelTime, UserTime)
creation = (CreationTime.dwHighDateTime << 32) + CreationTime.dwLowDateTime
exit = (ExitTime.dwHighDateTime << 32) + ExitTime.dwLowDateTime
kernel = (KernelTime.dwHighDateTime << 32) + KernelTime.dwLowDateTime
user = (UserTime.dwHighDateTime << 32) + UserTime.dwLowDateTime
return TimeInfo(creation, exit, kernel, user)
PRIORITY_CLASS_MAPPER = gdef.FlagMapper(
ABOVE_NORMAL_PRIORITY_CLASS,
BELOW_NORMAL_PRIORITY_CLASS,
HIGH_PRIORITY_CLASS,
IDLE_PRIORITY_CLASS,
NORMAL_PRIORITY_CLASS,
PROCESS_MODE_BACKGROUND_BEGIN,
PROCESS_MODE_BACKGROUND_END,
REALTIME_PRIORITY_CLASS)
@property
def memory_info(self):
result = gdef.PROCESS_MEMORY_COUNTERS_EX()
result.cb = sizeof(gdef.PROCESS_MEMORY_COUNTERS_EX)
cast_result = cast(pointer(result), gdef.PPROCESS_MEMORY_COUNTERS)
windows.winproxy.GetProcessMemoryInfo(self.limited_handle, cast_result, result.cb)
return result
def query_info(self, information_class, data=None):
winproxy.NtQueryInformationProcess(self.handle, information_class, byref(data), sizeof(data))
return data
def set_info(self, information_class, data):
winproxy.NtSetInformationProcess(self.handle, information_class, byref(data), sizeof(data))
def get_priority(self):
return self.PRIORITY_CLASS_MAPPER[winproxy.GetPriorityClass(self.handle)]
def set_priority(self, priority):
return winproxy.SetPriorityClass(self.handle, priority)
priority = property(get_priority, set_priority)
"""The priority of the process"""
def open_token(self, flags=MAXIMUM_ALLOWED):
"""Open the process Token
:returns: :class:`~windows.winobject.token.Token`
"""
token_handle = HANDLE()
winproxy.OpenProcessToken(self.limited_handle, flags, byref(token_handle))
return token.Token(token_handle.value)
token = property(open_token, doc="The process :class:`~windows.winobject.token.Token`")
def get_security_descriptor(self, query_sacl=False, flags=security.SecurityDescriptor.DEFAULT_SECURITY_INFORMATION):
open_flags = gdef.READ_CONTROL
if query_sacl:
open_flags |= gdef.ACCESS_SYSTEM_SECURITY
tmp_handle = windows.winproxy.OpenProcess(open_flags, 0, self.pid)
try:
return security.SecurityDescriptor.from_handle(tmp_handle, query_sacl=query_sacl, flags=flags, obj_type="process")
finally:
windows.winproxy.CloseHandle(tmp_handle)
def set_security_descriptor(self, sd):
if isinstance(sd, basestring):
sd = security.SecurityDescriptor.from_string(sd)
open_flags = gdef.WRITE_OWNER | gdef.WRITE_DAC
if (sd.sacl and
any(ace.Header.AceType != gdef.SYSTEM_MANDATORY_LABEL_ACE_TYPE for ace in sd.sacl)):
# Print error if requested but no SecurityPrivilege ?
open_flags |= gdef.ACCESS_SYSTEM_SECURITY
tmp_handle = windows.winproxy.OpenProcess(open_flags, 0, self.pid)
try:
sd._apply_to_handle_and_type(tmp_handle, gdef.SE_KERNEL_OBJECT)
finally:
windows.winproxy.CloseHandle(tmp_handle)
security_descriptor = property(get_security_descriptor, set_security_descriptor)
@property # Document ?
def handles(self):
pid = self.pid
return [h for h in windows.system.handles if h.dwProcessId == pid]
def __del__(self):
super(Process, self).__del__()
# Same logic that AutoHandle.__del__ for Process.limited_handle
# Assert that Process inherit AutoHandle
# sys.path is not None -> check if python shutdown
if sys.path is not None and hasattr(self, "_limited_handle") and self._limited_handle:
# Prevent some bug where dbgprint might be None when __del__ is called in a closing process
# This line is bad -> it reopens a handle closed by 'super(Process, self).__del__()' ._.
dbgprint("Closing limited handle {0} for {1}".format(hex(self._limited_handle), self), "HANDLE") if dbgprint is not None else None
self._close_function(self._limited_handle)
class Thread(utils.AutoHandle):
def open_token(self, flags=MAXIMUM_ALLOWED, as_self=False):
"""Open the Thread token if any (Impersonation) else return None.
``as_self`` tells which security context should be used
:returns: :class:`~windows.winobject.token.Token`
.. note::
see https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openthreadtoken
"""
token_handle = HANDLE()
try:
winproxy.OpenThreadToken(self.handle, flags, as_self, byref(token_handle))
except WindowsError as e:
if e.winerror == gdef.ERROR_NO_TOKEN:
# No token to open: return None
return None
raise
return token.Token(token_handle.value)
def set_token(self, token):
"""Set the token for the thread (impersonation). Setting the token to None revert the impersonation"""
thandle = getattr(token, "handle", token) # Accept raw handle & token object
return winproxy.SetThreadToken(self.handle, thandle)
_TOKEN_PROPERTY_DOC = """The thread :class:`~windows.winobject.token.Token`
:getter: :func:`open_token`
:setter: :func:`set_token`
"""
token = property(open_token, set_token, doc=_TOKEN_PROPERTY_DOC)
class CurrentThread(Thread):
"""The current thread"""
@property #It's not a fixedpropety because executing thread might change
def tid(self):
"""Thread ID
:type: :class:`int`
"""
return winproxy.GetCurrentThreadId()
@property
def owner(self):
"""The current process
:type: :class:`CurrentProcess`
"""
return windows.current_process
def _get_handle(self):
return winproxy.GetCurrentThread()
def __del__(self):
pass
def exit(self, code=0):
"""Exit the thread"""
return winproxy.ExitThread(code)
def wait(self, timeout=INFINITE):
"""Raise :class:`ValueError` to prevent deadlock :D"""
raise ValueError("wait() on current thread")
class CurrentProcess(Process):
"""The current process"""
get_peb = None
get_peb_32_code = x86.MultipleInstr()
get_peb_32_code += x86.Mov('EAX', x86.mem('fs:[0x30]'))
get_peb_32_code += x86.Ret()
get_peb_32_code = get_peb_32_code.get_code()
get_peb_64_code = x64.MultipleInstr()
get_peb_64_code += x64.Mov('RAX', x64.mem('gs:[0x60]'))
get_peb_64_code += x64.Ret()
get_peb_64_code = get_peb_64_code.get_code()
allocator = native_exec.native_function.allocator
name = "CurrentProcess" # Used by Winthread for __repr__
# Use RtlGetCurrentPeb ?
def get_peb_builtin(self):
if self.get_peb is not None:
return self.get_peb
if self.bitness == 32:
get_peb = native_exec.create_function(self.get_peb_32_code, [PVOID])
else:
get_peb = native_exec.create_function(self.get_peb_64_code, [PVOID])
self.get_peb = get_peb
return get_peb
def _get_handle(self):
return winproxy.GetCurrentProcess()
@utils.fixedpropety
def limited_handle(self):
return winproxy.GetCurrentProcess()
def __del__(self):
pass
@property
def pid(self):
"""Process ID
:type: :class:`int`
"""
return os.getpid()
@utils.fixedpropety # leave it has fixed property as we don't care if CurrentProcess is never collected
def peb(self):
"""The Process Environment Block of the current process
:type: :class:`PEB`
"""
return PEB.from_address(self.get_peb_builtin()())
@utils.fixedpropety
def bitness(self):
"""The bitness of the process
:type: :class:`int` -- 32 or 64
"""
import platform
bits = platform.architecture()[0]
return int(bits[:2])
def virtual_alloc(self, size, prot=PAGE_EXECUTE_READWRITE):
"""Allocate memory in the process
:return: The address of the allocated memory
:rtype: :class:`int`
"""
return winproxy.VirtualAlloc(dwSize=size, flProtect=prot)
def virtual_free(self, addr):
"""Free memory in the process by virtual_alloc"""
return winproxy.VirtualFree(addr)
def write_memory(self, addr, data):
"""Write data at addr"""
data = raw_encode(data)
# buffertype = (c_char * len(data)).from_address(addr)
# buffertype[:len(data)] = data
ctypes.memmove(addr, data, len(data))
return True
def read_memory(self, addr, size):
"""Read ``size`` from ``addr``
:return: The data read
:rtype: :class:`str`
"""
dbgprint('Read CurrentProcess Memory', 'READMEM')
buffer = ctypes.c_buffer(size)
ctypes.memmove(buffer, addr, size)
return buffer[:]
def create_thread(self, lpStartAddress, lpParameter, dwCreationFlags=0):
"""Create a new thread
:rtype: :class:`WinThread` or :class:`DeadThread`
"""
handle = winproxy.CreateThread(lpStartAddress=lpStartAddress, lpParameter=lpParameter, dwCreationFlags=dwCreationFlags)
return WinThread._from_handle(handle)
def load_library(self, dll_path):
"""Load the library in current process
:rtype: :class:`LoadedModule`
"""
dllbase = winproxy.LoadLibraryA(dll_path)
return [m for m in self.peb.modules if m.baseaddr == dllbase][0]
def execute(self, code, parameter=0):
"""Execute native code ``code`` in the current thread.
:rtype: :class:`int` the return value of the native code"""
f = windows.native_exec.create_function(code, [PVOID, PVOID])
return f(parameter)
def exit(self, code=0):
"""Exit the process"""
return winproxy.ExitProcess(code)
def wait(self, timeout=INFINITE):
"""Raise :class:`ValueError` to prevent deadlock :D"""
raise ValueError("wait() on current thread")
@utils.fixedpropety
def peb_syswow(self):
"""The 64bits PEB of a SysWow64 process
:type: :class:`PEB`
"""
if not self.is_wow_64:
raise ValueError("Not a syswow process")
return windows.syswow64.get_current_process_syswow_peb()
# TODO: use ctypes.string_at / ctypes.wstring_at for read_string / read_wstring ?
def read_string(self, addr):
return ctypes.string_at(addr) # Raises WindowsError on fail
def read_wstring(self, addr):
return ctypes.wstring_at(addr) # Raises WindowsError on fail
class WinThread(Thread):
"""Represent a thread """
def __init__(self, tid=None, handle=None, owner_pid=None, owner=None):
if tid is None and handle is None:
raise ValueError("Need at least <pid> or <handle> to create a {0}".format(type(self).__name__))
if tid is not None: self._tid = tid
if handle is not None: self._handle = handle
if owner is not None: self._owner = owner
if owner_pid is not None: self._owner_pid = owner_pid
if owner_pid is None and owner:
self._owner_pid = owner.pid
@classmethod
def _from_THREADENTRY32(cls, entry, owner=None):
tid = entry.th32ThreadID
owner_pid = entry.th32OwnerProcessID
return cls(tid=tid, owner_pid=owner_pid, owner=owner)
@classmethod
def _from_handle(cls, handle):
# Create a DeadThread if thread is already dead ?
return WinThread(handle=handle)
@utils.fixedpropety
def tid(self):
"""Thread ID
:type: :class:`int`"""
return self._get_thread_id(self.handle)
@utils.fixedpropety
def owner_pid(self):
res = THREAD_BASIC_INFORMATION()
windows.winproxy.NtQueryInformationThread(self.handle, ThreadBasicInformation, byref(res), ctypes.sizeof(res))
owner_id = res.ClientId.UniqueProcess
return owner_id
@utils.fixedpropety
def owner(self):
"""The Process owning the thread
:type: :class:`WinProcess`
"""
return WinProcess(pid=self.owner_pid)
@property
def context(self):
"""The context of the thread, type depend of the target process.
:type: :class:`windows.exception.ECONTEXT32` or :class:`windows.exception.ECONTEXT64` or :class:`windows.exception.ECONTEXTWOW64`
"""
if self.owner.bitness == 32 and windows.current_process.bitness == 64:
# Wow64
x = exception.ECONTEXTWOW64()
x.ContextFlags = CONTEXT_ALL
winproxy.Wow64GetThreadContext(self.handle, x)
return x
if self.owner.bitness == 64 and windows.current_process.bitness == 32:
x = exception.ECONTEXT64.new_aligned()
x.ContextFlags = CONTEXT_ALL
windows.syswow64.NtGetContextThread_32_to_64(self.handle, x)
return x
if self.owner.bitness == 32:
x = exception.ECONTEXT32()
else:
x = exception.ECONTEXT64.new_aligned()
x.ContextFlags = CONTEXT_ALL
winproxy.GetThreadContext(self.handle, x)
return x
@property
def context_syswow(self):
"""The 64 bits context of a syswow thread.
:type: :class:`windows.exception.ECONTEXT64`
"""
if not self.owner.is_wow_64:
raise ValueError("Not a syswow process")
x = exception.ECONTEXT64.new_aligned()
x.ContextFlags = CONTEXT_ALL
if windows.current_process.bitness == 64:
winproxy.GetThreadContext(self.handle, x)
else:
windows.syswow64.NtGetContextThread_32_to_64(self.handle, x)
return x
def set_context(self, context):
"""Set the thread's context to ``context``"""
if self.owner.bitness == windows.current_process.bitness:
return winproxy.SetThreadContext(self.handle, context)
if windows.current_process.bitness == 64 and self.owner.bitness == 32:
return winproxy.Wow64SetThreadContext(self.handle, context)
return windows.syswow64.NtSetContextThread_32_to_64(self.handle, ctypes.byref(context))
def set_syswow_context(self, context):
"""Set a syswow thread's 64 context to ``context``"""
if not self.owner.is_wow_64:
raise ValueError("Not a syswow process")
if windows.current_process.bitness == 64:
return winproxy.SetThreadContext(self.handle, context)
return windows.syswow64.NtSetContextThread_32_to_64(self.handle, ctypes.byref(context))
@property
def start_address(self):
"""The start address of the thread
:type: :class:`int`
"""
if windows.current_process.bitness == 32 and self.owner.bitness == 64:
res = ULONGLONG()
windows.syswow64.NtQueryInformationThread_32_to_64(self.handle, ThreadQuerySetWin32StartAddress, byref(res), ctypes.sizeof(res))
return res.value
res_size = max(self.owner.bitness, windows.current_process.bitness)
if res_size == 32:
res = ULONG()
else:
res = ULONGLONG()
winproxy.NtQueryInformationThread(self.handle, ThreadQuerySetWin32StartAddress, byref(res), ctypes.sizeof(res))
return res.value
def _get_principal_teb_addr(self):
# Returns the 64bits TEB on a 64bits computer (syswow process or not)
# Returns the 32bits TEB on a 32bits computer
# If we are wow64 process its means we either
# - Want the TEB of a 64b process
# - Want the TEB64 of a Wowprocess
# It's the same code for both
if windows.current_process.is_wow_64:
restype = rctypes.transform_type_to_remote64bits(THREAD_BASIC_INFORMATION)
ressize = (ctypes.sizeof(restype))
# Manual aligned allocation :DDDD
nb_qword = (ressize + 8) / ctypes.sizeof(ULONGLONG)
buffer = (nb_qword * ULONGLONG)()
struct_address = ctypes.addressof(buffer)
if (struct_address & 0xf) not in [0, 8]:
raise ValueError("ULONGLONG array not aligned on 8")
windows.syswow64.NtQueryInformationThread_32_to_64(self.handle, ThreadBasicInformation, struct_address, ressize)
return restype(struct_address, windows.current_process).TebBaseAddress
res = THREAD_BASIC_INFORMATION()
windows.winproxy.NtQueryInformationThread(self.handle, ThreadBasicInformation, byref(res), ctypes.sizeof(res))
return res.TebBaseAddress
@property
def teb_base(self):
"""The address of the thread's TEB. If the owner is a SysWow64 process, return the TEB32.
:type: :class:`int`
"""
main_teb_addr = self._get_principal_teb_addr()
if not self.owner.is_wow_64:
return main_teb_addr
# import pdb; pdb.set_trace()
# TEB32 is pointed at the begining of the TEB64
return self.owner.read_dword(main_teb_addr)
@property
def teb_syswow_base(self):
"""The address of the thread's TEB64 for a SysWow64 process
:type: :class:`int`
"""
if not self.owner.is_wow_64:
raise ValueError("Not a syswow process")
# just return the main TEB
return self._get_principal_teb_addr()
def exit(self, code=0):
"""Exit the thread"""
return winproxy.TerminateThread(self.handle, code)
def resume(self):
"""Resume the thread"""
return winproxy.ResumeThread(self.handle)
def suspend(self):
"""Suspend the thread"""
return winproxy.SuspendThread(self.handle)
def _get_handle(self):
return winproxy.OpenThread(dwThreadId=self.tid)
@property
def is_exit(self):
"""``True`` if the thread is terminated
:type: :class:`bool`
"""
return self.exit_code != STILL_ACTIVE
@property
def exit_code(self):
"""The exit code of the thread : ``STILL_ACTIVE`` means the process is not dead
:type: :class:`int`
"""
res = DWORD()
winproxy.GetExitCodeThread(self.handle, byref(res))
return res.value
def __repr__(self):
owner = self.owner
if owner is None:
owner_name = "<Dead process with pid {0}>".format(hex(self.th32OwnerProcessID))
else:
try:
owner_name = owner.name
except EnvironmentError:
owner_name = "!cannot-retrieve-owner-name"
return '<{0} {1} owner "{2}" at {3}>'.format(self.__class__.__name__, self.tid, owner_name, hex(id(self)))
@staticmethod
def _get_thread_id_by_api(handle):
return winproxy.GetThreadId(handle)
@staticmethod
def _get_thread_id_manual(handle):
if windows.current_process.bitness == 32 and self.owner.bitness == 64:
raise NotImplementedError("[_get_thread_id_manual] 32 -> 64 (XP64 bits + Syswow process ?)")
res = THREAD_BASIC_INFORMATION()
windows.winproxy.NtQueryInformationThread(handle, ThreadBasicInformation, byref(res), ctypes.sizeof(res))
id2 = res.ClientId.UniqueThread
return id2
if winproxy.is_implemented(winproxy.GetThreadId):
_get_thread_id = _get_thread_id_by_api
else:
_get_thread_id = _get_thread_id_manual
class WinProcess(Process):
"""A Process on the system"""
def __init__(self, pid=None, handle=None, name=None, ppid=None):
if pid is None and handle is None:
raise ValueError("Need at least <pid> or <handle> to create a {0}".format(type(self).__name__))
if pid is not None: self._pid = pid
if handle is not None: self._handle = handle
if name is not None: self._name = name
if ppid is not None: self._ppid = ppid
@staticmethod
def _from_handle(handle):
#pid = winproxy.GetProcessId(handle)
#proc = [p for p in windows.system.processes if p.pid == pid][0]
#proc._handle = handle
#dbgprint("Process {0} from handle {1}".format(proc, hex(handle)), "HANDLE")