Code example of detecting open process handles to our process (C/C++, Windows usermode)
- All handles on the system are retrieved via
NtQuerySystemInformation
- Handles are then filtered based on not being from of the current process (all handles except our current process handles are looked at)
DuplicateHandle
is used afterOpenProcess(PROCESS_DUP_HANDLE, FALSE, handle.ProcessId)
to obtain a handle contextGetProcessId
on the duplicated handle is then compared to the current process ID, and a match tells us this handle is an open process handle to our process
- Calls to
OpenProcess
from external applications to our application can be detected
- Expensive CPU-wise to constantly fetch all system handles
- SERVICE or SYSTEM processes cannot have their handles queried from usermode
Thanks for reading, happy coding!