-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenedFiles.cpp
More file actions
422 lines (393 loc) · 11.4 KB
/
OpenedFiles.cpp
File metadata and controls
422 lines (393 loc) · 11.4 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
// Based on https://www.codeproject.com/Articles/18975/Listing-Used-Files
#include "StdAfx.h"
#include "OpenedFiles.h"
#include <Tlhelp32.h>
#include <Psapi.h>
#include "Utils.h"
struct PROCESS_INFO_t
{
CString csProcess;
DWORD dwImageListIndex;
};
void EnumerateLoadedModules( CString& csPath, OF_CALLBACK CallBackProc, UINT_PTR pUserContext );
int EnumerateOpenedFiles( CString& csPath, OF_CALLBACK CallBackProc, UINT_PTR pUserContext, HANDLE hDriver, GetFinalPathNameByHandleDef pGetFinalPathNameByHandle );
extern "C" __declspec(dllexport) int GetOpenedFiles( LPCWSTR lpPath, OF_TYPE Filter, OF_CALLBACK CallBackProc,
UINT_PTR pUserContext )
{
int cnt = 0;
CString csPath = lpPath;
csPath.MakeLower();
EnableTokenPrivilege( SE_DEBUG_NAME );
if( Filter& MODULES_ONLY )
{
EnumerateLoadedModules( csPath, CallBackProc, pUserContext );
}
if( Filter& FILES_ONLY )
{
GetFinalPathNameByHandleDef pGetFinalPathNameByHandle = 0;
pGetFinalPathNameByHandle = (GetFinalPathNameByHandleDef)GetProcAddress( GetModuleHandle(_T("kernel32.dll")), "GetFinalPathNameByHandleW" );
// Now walk all handles
cnt = EnumerateOpenedFiles( csPath, CallBackProc, pUserContext, NULL, pGetFinalPathNameByHandle );
}
return cnt;
}
UINT g_CurrentIndex = 0;
struct THREAD_PARAMS
{
PSYSTEM_HANDLE_INFORMATION pSysHandleInformation;
GetFinalPathNameByHandleDef pGetFinalPathNameByHandle;
LPTSTR lpPath;
int nFileType;
HANDLE hStartEvent;
HANDLE hFinishedEvent;
bool bStatus;
};
DWORD WINAPI ThreadProc( LPVOID lParam )
{
THREAD_PARAMS* pThreadParam = (THREAD_PARAMS*)lParam;
GetFinalPathNameByHandleDef pGetFinalPathNameByHandle = pThreadParam->pGetFinalPathNameByHandle;
for( g_CurrentIndex; g_CurrentIndex < pThreadParam->pSysHandleInformation->dwCount; )
{
WaitForSingleObject( pThreadParam->hStartEvent, INFINITE );
ResetEvent( pThreadParam->hStartEvent );
pThreadParam->bStatus = false;
SYSTEM_HANDLE& sh = pThreadParam->pSysHandleInformation->Handles[g_CurrentIndex];
g_CurrentIndex++;
HANDLE hDup = (HANDLE)sh.wValue;
HANDLE hProcess = OpenProcess( PROCESS_DUP_HANDLE , FALSE, sh.dwProcessId );
if( hProcess )
{
BOOL b = DuplicateHandle( hProcess, (HANDLE)sh.wValue, GetCurrentProcess(), &hDup, 0, FALSE, DUPLICATE_SAME_ACCESS );
if( !b )
{
hDup = (HANDLE)sh.wValue;
}
CloseHandle( hProcess );
}
DWORD dwRet = pGetFinalPathNameByHandle( hDup, pThreadParam->lpPath, MAX_PATH, 0 );
if( hDup && (hDup != (HANDLE)sh.wValue))
{
CloseHandle( hDup );
}
if(dwRet)
{
pThreadParam->bStatus = true;
}
SetEvent( pThreadParam->hFinishedEvent );
}
return 0;
}
int EnumerateOpenedFiles( CString& csPath, OF_CALLBACK CallBackProc, UINT_PTR pUserContext, HANDLE hDriver,
GetFinalPathNameByHandleDef pGetFinalPathNameByHandle )
{
int nFileType = XP_FILETYPE;
int cnt = 0;
OSVERSIONINFO info = { 0 };
info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&info);
if( info.dwMajorVersion == 6 &&
info.dwMinorVersion == 0 )
{
nFileType = VISTA_FILETYPE;
}
LPCTSTR lpPath = csPath;
CString csShortName;
GetShortPathName( csPath, csShortName.GetBuffer( MAX_PATH), MAX_PATH );
csShortName.ReleaseBuffer();
csShortName.MakeLower();
bool bShortPath = false;
LPCTSTR lpShortPath = csShortName;
if( csShortName != csPath && FALSE == csShortName.IsEmpty())
{
bShortPath = true;
}
HMODULE hModule = GetModuleHandle(_T("ntdll.dll"));
PNtQuerySystemInformation NtQuerySystemInformation = (PNtQuerySystemInformation)GetProcAddress( hModule, "NtQuerySystemInformation" );
if( 0 == NtQuerySystemInformation )
{
OutputDebugString( L"Getting proc of NtQuerySystemInformation failed" );
return cnt;
}
// Get the list of all handles in the system
PSYSTEM_HANDLE_INFORMATION pSysHandleInformation = new SYSTEM_HANDLE_INFORMATION;
DWORD size = sizeof(SYSTEM_HANDLE_INFORMATION);
DWORD needed = 0;
NTSTATUS status = NtQuerySystemInformation( SystemHandleInformation, pSysHandleInformation, size, &needed );
if( !NT_SUCCESS(status))
{
if( 0 == needed )
{
return cnt;// some other error
}
// The previously supplied buffer wasn't enough.
delete pSysHandleInformation;
size = needed + 1024;
pSysHandleInformation = (PSYSTEM_HANDLE_INFORMATION)new BYTE[size];
status = NtQuerySystemInformation( SystemHandleInformation, pSysHandleInformation, size, &needed );
if( !NT_SUCCESS(status))
{
// some other error so quit.
delete pSysHandleInformation;
return cnt;
}
}
if( pGetFinalPathNameByHandle )// there is no driver, we have do it ugly way
{
g_CurrentIndex = 0;
TCHAR tcFileName[MAX_PATH+1];
THREAD_PARAMS ThreadParams;
ThreadParams.lpPath = tcFileName;
ThreadParams.nFileType = nFileType;
ThreadParams.pGetFinalPathNameByHandle = pGetFinalPathNameByHandle;
ThreadParams.pSysHandleInformation = pSysHandleInformation;
ThreadParams.hStartEvent = ::CreateEvent( 0, TRUE, FALSE, 0 );
ThreadParams.hFinishedEvent = ::CreateEvent( 0, TRUE, FALSE, 0 );
HANDLE ThreadHandle = 0;
while( g_CurrentIndex < pSysHandleInformation->dwCount )
{
if( !ThreadHandle )
{
ThreadHandle = CreateThread( 0, 0, ThreadProc, &ThreadParams, 0, 0 );
}
ResetEvent( ThreadParams.hFinishedEvent );
SetEvent( ThreadParams.hStartEvent );
if( WAIT_TIMEOUT == WaitForSingleObject( ThreadParams.hFinishedEvent, 100 ))
{
CString csError;
csError.Format(L"Query hang for handle %d", (int)pSysHandleInformation->Handles[g_CurrentIndex - 1].wValue);
OutputDebugString(csError );
TerminateThread( ThreadHandle, 0 );
CloseHandle( ThreadHandle );
ThreadHandle = 0;
continue;
}
if( !ThreadParams.bStatus )
{
continue;
}
int nCmpStart = 4;
CString csFileName( &ThreadParams.lpPath[nCmpStart] );
csFileName.MakeLower();
if( 0 != _tcsncmp( lpPath, csFileName , csPath.GetLength()))
{
continue;
}
OF_INFO_t stOFInfo;
stOFInfo.dwPID = pSysHandleInformation->Handles[g_CurrentIndex - 1].dwProcessId;
stOFInfo.lpFile = csFileName;
stOFInfo.hFile = (HANDLE)pSysHandleInformation->Handles[g_CurrentIndex - 1].wValue;
CallBackProc( stOFInfo, pUserContext );
cnt++;
}
if( ThreadHandle )
{
if( WAIT_TIMEOUT == WaitForSingleObject( ThreadHandle, 1000 ))
{
TerminateThread( ThreadHandle, 0 );
}
CloseHandle( ThreadHandle );
}
CloseHandle( ThreadParams.hStartEvent );
CloseHandle( ThreadParams.hFinishedEvent );
return cnt;
}
// Walk through the handle list
for ( DWORD i = 0; i < pSysHandleInformation->dwCount; i++ )
{
SYSTEM_HANDLE& sh = pSysHandleInformation->Handles[i];
if( sh.bObjectType != nFileType )// Under windows XP file handle is of type 28
{
continue;
}
CString csFileName;
CString csDir;
if( hDriver )
{
HANDLE_INFO stHandle = {0};
ADDRESS_INFO stAddress;
stAddress.pAddress = sh.pAddress;
DWORD dwReturn = 0;
BOOL bSuccess = DeviceIoControl( hDriver, IOCTL_LISTDRV_BUFFERED_IO, &stAddress, sizeof(ADDRESS_INFO),
&stHandle, sizeof(HANDLE_INFO), &dwReturn, NULL );
if( bSuccess && stHandle.tcFileName[0] != 0 &&
stHandle.uType != FILE_DEVICE_SOUND &&
stHandle.uType != FILE_DEVICE_NAMED_PIPE )
{
if( stHandle.uType != FILE_DEVICE_NETWORK_FILE_SYSTEM )
{
// Get the drive name from the dos device name
if( !GetDrive( (LPCTSTR)stHandle.tcDeviceName, csFileName, true ))
{
OutputDebugString( L"GetDrive failed" );
}
csFileName += (LPCTSTR)stHandle.tcFileName;
}
else
{
csFileName = _T("\\");
csFileName += (LPCTSTR)stHandle.tcFileName;
}
}
else
{
continue;
}
}
else
{
return cnt;
}
csFileName.MakeLower();
// Check whether the file belongs to the specified folder
// if( -1 == csFileName.Find( csPath ))
// {
// if( bShortPath )
// {
// // Some times the file name may be in short path form.
// if( -1 == csFileName.Find( csShortName ))
// {
// continue;
// }
// }
// else
// {
// continue;
// }
// }
if( 0 != _tcsncmp( lpPath, csFileName, csPath.GetLength()))
{
if( bShortPath )
{
// Some times the file name may be in short path form.
if( 0 != _tcsncmp( lpShortPath, csFileName, csShortName.GetLength()))
{
continue;
}
}
else
{
continue;
}
}
OF_INFO_t stOFInfo;
stOFInfo.dwPID = sh.dwProcessId;
stOFInfo.lpFile = csFileName;
stOFInfo.hFile = (HANDLE)sh.wValue;
CallBackProc( stOFInfo, pUserContext );
cnt++;
}
delete pSysHandleInformation;
return cnt;
}
void EnumerateLoadedModules( CString& csPath, OF_CALLBACK CallBackProc, UINT_PTR pUserContext )
{
CString csShortName;
GetShortPathName( csPath, csShortName.GetBuffer( MAX_PATH), MAX_PATH );
csShortName.ReleaseBuffer();
csShortName.MakeLower();
bool bShortPath = false;
if( csShortName != csPath && FALSE == csShortName.IsEmpty())
{
bShortPath = true;
}
DWORD dwsize = 300;
PDWORD pDwId = (PDWORD)new BYTE[dwsize];
DWORD dwRetruned = dwsize;
// Enum all the process first
while( 1 )
{
EnumProcesses( pDwId, dwsize, &dwRetruned );
if( dwsize > dwRetruned )
{
break;
}
delete pDwId;
dwsize += 50;
pDwId = (PDWORD)new BYTE[dwsize];
}
int nCount = dwRetruned / sizeof(DWORD);
// int nItemCount = -1;
// Enumerate modules of the above process
for( int nIdx = 0; nIdx < nCount;nIdx++ )
{
if( 0 != pDwId[nIdx] )
{
HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
MODULEENTRY32 me32;
// Take a snapshot of all modules in the specified process.
hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, pDwId[nIdx] );
if( hModuleSnap == INVALID_HANDLE_VALUE )
{
continue;
}
me32.dwSize = sizeof( MODULEENTRY32 );
if( !Module32First( hModuleSnap, &me32 ) )
{
CloseHandle( hModuleSnap );
continue;
}
bool bFirst = true;
PROCESS_INFO_t stInfo;
do
{
CString csModule;
if( bFirst )
{
// First module is always the exe name
bFirst = false;
if( !PathFileExists( me32.szExePath ))
{
TCHAR tcFileName[MAX_PATH];
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, TRUE, pDwId[nIdx] );
if( GetProcessImageFileName( hProcess, tcFileName, MAX_PATH ))
{
GetDrive( tcFileName, csModule, false );
}
CloseHandle( hProcess );
}
else
{
csModule = me32.szExePath;
}
csModule.MakeLower();
}
else
{
csModule = me32.szExePath;
csModule.MakeLower();
}
if( -1 == csModule.Find( csPath ))
{
if( bShortPath )
{
if( -1 == csModule.Find( csShortName ))
{
continue;
}
}
else
{
continue;
}
}
OF_INFO_t stOFInfo;
stOFInfo.dwPID = pDwId[nIdx];
stOFInfo.lpFile = csModule;
CallBackProc( stOFInfo, pUserContext );
}
while( Module32Next( hModuleSnap, &me32 ) );
CloseHandle( hModuleSnap );
}
}
delete pDwId;
}
#ifdef _TEST_LSOF_WIN32
void CALLBACK CallBackFunc( OF_INFO_t OpenedFileInfo, UINT_PTR pUserContext )
{
printf("%p %i %ls\n", OpenedFileInfo.hFile, OpenedFileInfo.dwPID, OpenedFileInfo.lpFile);
}
int main() {
GetFinalPathNameByHandleDef pGetFinalPathNameByHandle = (GetFinalPathNameByHandleDef)GetProcAddress( GetModuleHandle(_T("kernel32.dll")), "GetFinalPathNameByHandleW" );
EnumerateOpenedFiles( CString(L""), CallBackFunc, NULL, NULL, pGetFinalPathNameByHandle );
}
#endif