C# - Get PID or name of the process handle

841 Views Asked by At

I enumerate all handles of a process. I have process handle and now I want to know the PID of the process the handle is for. Here is the stuct I am using:

public struct SYSTEM_HANDLE_INFORMATION
{
public int ProcessID;
public byte ObjectTypeNumber;
public byte Flags; // 0x01 = PROTECT_FROM_CLOSE, 0x02 = INHERIT
public ushort Handle;
public int Object_Pointer;
public UInt32 GrantedAccess;
}

The ProcessID sadly of all my handles is the same as the PID of the program I am running (host). It should be the Object_Pointer, but I am not sure how to use it. Now the Object_Pointer together with GrantedAccess matches the object address of the process the handle is for - picture

It is weird though, since the GrantedAccess should be the level of access for the process and not part of the address.

1

There are 1 best solutions below

3
RbMm On

if we have process handle with PROCESS_QUERY_LIMITED_INFORMATION or PROCESS_QUERY_INFORMATION access right we can got it PID by GetProcessId function

and your definition of SYSTEM_HANDLE_INFORMATION is wrong. obviously that Object_Pointer can not be int (4 bytes) when it must be void* (8 bytes on 64-bit system). correct definition of this structure is

struct SYSTEM_HANDLE_TABLE_ENTRY_INFO
{
    USHORT UniqueProcessId;
    USHORT CreatorBackTraceIndex;
    UCHAR ObjectTypeIndex;
    UCHAR HandleAttributes;
    USHORT HandleValue;
    PVOID Object;
    ULONG GrantedAccess;
};

but however much better use SystemExtendedHandleInformation instead SystemHandleInformation and work with SYSTEM_HANDLE_INFORMATION_EX