-
Notifications
You must be signed in to change notification settings - Fork 12
/
file_handles.py
246 lines (217 loc) · 6.85 KB
/
file_handles.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
import os, sys
from ctypes import *
from ctypes.wintypes import *
import Queue
import re
import struct
import threading
import ntsecuritycon
import pywintypes
import win32api
import win32con
import win32event
import win32file
import win32security
import winerror
UCHAR = c_ubyte
PVOID = c_void_p
ntdll = windll.ntdll
SystemHandleInformation = 16
STATUS_INFO_LENGTH_MISMATCH = 0xC0000004
STATUS_BUFFER_OVERFLOW = 0x80000005L
STATUS_INVALID_HANDLE = 0xC0000008L
STATUS_BUFFER_TOO_SMALL = 0xC0000023L
STATUS_SUCCESS = 0
CURRENT_PROCESS = win32api.GetCurrentProcess ()
DEVICE_DRIVES = {}
for d in "abcdefghijklmnopqrstuvwxyz":
try:
DEVICE_DRIVES[win32file.QueryDosDevice (d + ":").strip ("\x00").lower ()] = d + ":"
except win32file.error, (errno, errctx, errmsg):
if errno == 2:
pass
else:
raise
class x_file_handles (Exception):
pass
def signed_to_unsigned (signed):
unsigned, = struct.unpack ("L", struct.pack ("l", signed))
return unsigned
class SYSTEM_HANDLE_TABLE_ENTRY_INFO (Structure):
_fields_ = [
("UniqueProcessId", USHORT),
("CreatorBackTraceIndex", USHORT),
("ObjectTypeIndex", UCHAR),
("HandleAttributes", UCHAR),
("HandleValue", USHORT),
("Object", PVOID),
("GrantedAccess", ULONG),
]
class SYSTEM_HANDLE_INFORMATION (Structure):
_fields_ = [
("NumberOfHandles", ULONG),
("Handles", SYSTEM_HANDLE_TABLE_ENTRY_INFO * 1),
]
class LSA_UNICODE_STRING (Structure):
_fields_ = [
("Length", USHORT),
("MaximumLength", USHORT),
("Buffer", LPWSTR),
]
class PUBLIC_OBJECT_TYPE_INFORMATION (Structure):
_fields_ = [
("Name", LSA_UNICODE_STRING),
("Reserved", ULONG * 22),
]
class OBJECT_NAME_INFORMATION (Structure):
_fields_ = [
("Name", LSA_UNICODE_STRING),
]
class IO_STATUS_BLOCK_UNION (Union):
_fields_ = [
("Status", LONG),
("Pointer", PVOID),
]
class IO_STATUS_BLOCK (Structure):
_anonymous_ = ("u",)
_fields_ = [
("u", IO_STATUS_BLOCK_UNION),
("Information", POINTER (ULONG)),
]
class FILE_NAME_INFORMATION (Structure):
filename_size = 4096
_fields_ = [
("FilenameLength", ULONG),
("FileName", WCHAR * filename_size),
]
def get_handles ():
system_handle_information = SYSTEM_HANDLE_INFORMATION ()
size = DWORD (sizeof (system_handle_information))
while True:
result = ntdll.ZwQuerySystemInformation (
SystemHandleInformation,
byref (system_handle_information),
size,
byref (size)
)
result = signed_to_unsigned (result)
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 ("ZwQuerySystemInformation", hex (result))
pHandles = cast (
system_handle_information.Handles,
POINTER (SYSTEM_HANDLE_TABLE_ENTRY_INFO * system_handle_information.NumberOfHandles)
)
for handle in pHandles.contents:
yield handle.UniqueProcessId, handle.HandleValue
def get_process_handle (pid, handle):
try:
hProcess = win32api.OpenProcess (win32con.PROCESS_DUP_HANDLE, 0, pid)
return win32api.DuplicateHandle (hProcess, handle, CURRENT_PROCESS, 0, 0, win32con.DUPLICATE_SAME_ACCESS)
except win32api.error, (errno, errctx, errmsg):
if errno in (
winerror.ERROR_ACCESS_DENIED,
winerror.ERROR_INVALID_PARAMETER,
winerror.ERROR_INVALID_HANDLE,
winerror.ERROR_NOT_SUPPORTED
):
return None
else:
raise
def get_type_info (handle):
public_object_type_information = PUBLIC_OBJECT_TYPE_INFORMATION ()
size = DWORD (sizeof (public_object_type_information))
while True:
result = signed_to_unsigned (
ntdll.ZwQueryObject (
handle, 2, 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:
return None
else:
raise x_file_handles ("ZwQueryObject.2", hex (result))
def get_name_info (handle):
object_name_information = OBJECT_NAME_INFORMATION ()
size = DWORD (sizeof (object_name_information))
while True:
result = signed_to_unsigned (
ntdll.ZwQueryObject (
handle, 1, byref (object_name_information), size, None
)
)
if result == STATUS_SUCCESS:
return object_name_information.Name.Buffer
elif result in (STATUS_BUFFER_OVERFLOW, STATUS_BUFFER_TOO_SMALL, STATUS_INFO_LENGTH_MISMATCH):
size = DWORD (size.value * 4)
resize (object_name_information, size.value)
else:
return None
def can_access (handle):
try:
return win32event.WaitForSingleObject (handle, 10) not in (win32event.WAIT_TIMEOUT, win32event.WAIT_ABANDONED)
except win32event.error, (errno, errctx, errmsg):
if errno in (winerror.ERROR_ACCESS_DENIED,):
return False
else:
raise
def get_object_info (requests, results):
while True:
pid, handle = requests.get ()
type = get_type_info (handle)
name = get_name_info (handle)
results.put ((pid, type, name))
def main ():
requests = Queue.Queue ()
results = Queue.Queue ()
for i in range (20):
t = threading.Thread (target=get_object_info, args=(requests, results))
t.setDaemon (True)
t.start ()
public_object_type_information = PUBLIC_OBJECT_TYPE_INFORMATION ()
object_name_information = OBJECT_NAME_INFORMATION ()
this_pid = os.getpid ()
for pid, handle in get_handles ():
if pid == this_pid:
continue
hDuplicate = get_process_handle (pid, handle)
if hDuplicate is None:
continue
else:
requests.put ((pid, int (hDuplicate)))
while True:
try:
yield results.get (True, 2)
except Queue.Empty:
break
def filepath_from_devicepath (devicepath):
if devicepath is None: return None
devicepath = devicepath.lower ()
for device, drive in DEVICE_DRIVES.items ():
if devicepath.startswith (device):
return drive + devicepath[len (device):]
else:
return devicepath
if __name__ == '__main__':
se_debug = win32security.LookupPrivilegeValue (u"", win32security.SE_DEBUG_NAME)
hToken = win32security.OpenProcessToken (
CURRENT_PROCESS,
ntsecuritycon.MAXIMUM_ALLOWED
)
#~ win32security.AdjustTokenPrivileges (
#~ hToken, False, [(se_debug, win32security.SE_PRIVILEGE_ENABLED)]
#~ )
try:
for pid, type, devicepath in main ():
print pid, type, filepath_from_devicepath (devicepath)
except x_file_handles, (context, errno):
print "Error in", context, "with errno", errno