Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <stdio.h>
- #include <shlwapi.h>
- #include <tchar.h>
- #include <stdio.h>
- #pragma comment ( lib, "shlwapi.lib" )
- #define NT_SUCCESS(x) ((x) >= 0)
- //#define STATUS_INFO_LENGTH_MISMATCH 0xc0000004
- #define SystemHandleInformation 16
- #define ObjectBasicInformation 0
- #define ObjectNameInformation 1
- #define ObjectTypeInformation 2
- #define STATUS_SUCCESS ((NTSTATUS)0x00000000L) //getprocid
- #define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L) //getprocid
- typedef NTSTATUS ( NTAPI *_NtQuerySystemInformation )
- (
- ULONG SystemInformationClass,
- PVOID SystemInformation,
- ULONG SystemInformationLength,
- PULONG ReturnLength
- );
- typedef NTSTATUS ( NTAPI *_NtDuplicateObject )
- (
- HANDLE SourceProcessHandle,
- HANDLE SourceHandle,
- HANDLE TargetProcessHandle,
- PHANDLE TargetHandle,
- ACCESS_MASK DesiredAccess,
- ULONG Attributes,
- ULONG Options
- );
- typedef NTSTATUS ( NTAPI *_NtQueryObject )
- (
- HANDLE ObjectHandle,
- ULONG ObjectInformationClass,
- PVOID ObjectInformation,
- ULONG ObjectInformationLength,
- PULONG ReturnLength
- );
- typedef struct _UNICODE_STRING
- {
- USHORT Length;
- USHORT MaximumLength;
- PWSTR Buffer;
- } UNICODE_STRING, *PUNICODE_STRING;
- typedef struct _SYSTEM_HANDLE
- {
- ULONG ProcessId;
- BYTE ObjectTypeNumber;
- BYTE Flags;
- USHORT Handle;
- PVOID Object;
- ACCESS_MASK GrantedAccess;
- } SYSTEM_HANDLE, *PSYSTEM_HANDLE;
- typedef struct _SYSTEM_HANDLE_INFORMATION
- {
- ULONG HandleCount;
- SYSTEM_HANDLE Handles[ 1 ];
- } SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
- typedef enum _POOL_TYPE
- {
- NonPagedPool,
- PagedPool,
- NonPagedPoolMustSucceed,
- DontUseThisType,
- NonPagedPoolCacheAligned,
- PagedPoolCacheAligned,
- NonPagedPoolCacheAlignedMustS
- } POOL_TYPE, *PPOOL_TYPE;
- typedef struct _OBJECT_TYPE_INFORMATION
- {
- UNICODE_STRING Name;
- ULONG TotalNumberOfObjects;
- ULONG TotalNumberOfHandles;
- ULONG TotalPagedPoolUsage;
- ULONG TotalNonPagedPoolUsage;
- ULONG TotalNamePoolUsage;
- ULONG TotalHandleTableUsage;
- ULONG HighWaterNumberOfObjects;
- ULONG HighWaterNumberOfHandles;
- ULONG HighWaterPagedPoolUsage;
- ULONG HighWaterNonPagedPoolUsage;
- ULONG HighWaterNamePoolUsage;
- ULONG HighWaterHandleTableUsage;
- ULONG InvalidAttributes;
- GENERIC_MAPPING GenericMapping;
- ULONG ValidAccess;
- BOOLEAN SecurityRequired;
- BOOLEAN MaintainHandleCount;
- USHORT MaintainTypeList;
- POOL_TYPE PoolType;
- ULONG PagedPoolUsage;
- ULONG NonPagedPoolUsage;
- } OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;
- //getprocid
- typedef enum _SYSTEM_INFORMATION_CLASS
- {
- SystemProcessInformation = 5
- } SYSTEM_INFORMATION_CLASS;
- typedef LONG KPRIORITY; // Thread priority
- typedef struct _SYSTEM_PROCESS_INFORMATION_DETAILD
- {
- ULONG NextEntryOffset;
- ULONG NumberOfThreads;
- LARGE_INTEGER SpareLi1;
- LARGE_INTEGER SpareLi2;
- LARGE_INTEGER SpareLi3;
- LARGE_INTEGER CreateTime;
- LARGE_INTEGER UserTime;
- LARGE_INTEGER KernelTime;
- UNICODE_STRING ImageName;
- KPRIORITY BasePriority;
- HANDLE UniqueProcessId;
- ULONG InheritedFromUniqueProcessId;
- ULONG HandleCount;
- BYTE Reserved4[4];
- PVOID Reserved5[11];
- SIZE_T PeakPagefileUsage;
- SIZE_T PrivatePageCount;
- LARGE_INTEGER Reserved6[6];
- } SYSTEM_PROCESS_INFORMATION_DETAILD, *PSYSTEM_PROCESS_INFORMATION_DETAILD;
- typedef NTSTATUS( WINAPI *PFN_NT_QUERY_SYSTEM_INFORMATION )
- (
- IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
- IN OUT PVOID SystemInformation,
- IN ULONG SystemInformationLength,
- OUT OPTIONAL PULONG ReturnLength
- );
- typedef struct {
- HANDLE handle;
- PVOID NameInfo;
- ULONG retVal;
- } SFileNameInfo;
- int Counter = 0;
- PVOID GetLibraryProcAddress( PSTR LibraryName, PSTR ProcName );
- int GetHandle( ULONG pid );
- static _NtQuerySystemInformation NtQuerySystemInformation;
- static _NtDuplicateObject NtDuplicateObject;
- static _NtQueryObject NtQueryObject;
- int test( HANDLE handli );
- void EnableDebugPriv( void );
- int GetProcessList();
- static bool InitNTDLL()
- {
- NtQuerySystemInformation = ( _NtQuerySystemInformation ) GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "NtQuerySystemInformation" );
- NtDuplicateObject = ( _NtDuplicateObject ) GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "NtDuplicateObject" );
- NtQueryObject =( _NtQueryObject ) GetProcAddress(GetModuleHandleA( "ntdll.dll" ), "NtQueryObject" );
- return NtQuerySystemInformation != NULL &&
- NtDuplicateObject != NULL &&
- NtQueryObject != NULL;
- }
- NTSTATUS status;
- PSYSTEM_HANDLE_INFORMATION handleInfo;
- ULONG handleInfoSize = 0x10000;
- int __cdecl wmain( int argc, PWSTR argv[] )
- {
- if ( !InitNTDLL() )
- {
- printf( "\nFailed to bind to ntdll.dll!" );
- return 1;
- }
- handleInfo = ( PSYSTEM_HANDLE_INFORMATION )malloc( handleInfoSize );
- while ( ( status = NtQuerySystemInformation( SystemHandleInformation, handleInfo, handleInfoSize, NULL ) ) == STATUS_INFO_LENGTH_MISMATCH )
- handleInfo = ( PSYSTEM_HANDLE_INFORMATION )realloc( handleInfo, handleInfoSize *= 2 );
- EnableDebugPriv();
- GetProcessList();
- free( handleInfo );
- NtQueryObject = NULL;
- NtDuplicateObject = NULL;
- NtQuerySystemInformation = NULL;
- }
- int test( HANDLE HandleToTest )
- {
- HANDLE Job( CreateJobObject( NULL, NULL ) );
- if( !Job )
- {
- wprintf( L"Could not create job object, error %d\n", GetLastError() );
- return 0;
- }
- HANDLE IOPort( CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, 0, 1 ) );
- if( !IOPort )
- {
- wprintf( L"Could not create IO completion port, error %d\n", GetLastError() );
- return 0;
- }
- JOBOBJECT_ASSOCIATE_COMPLETION_PORT Port;
- Port.CompletionKey = HandleToTest;
- Port.CompletionPort = IOPort;
- if( !SetInformationJobObject( HandleToTest, JobObjectAssociateCompletionPortInformation, &Port, sizeof( Port ) ) )
- {
- wprintf( L"Could not associate job with IO completion port, error %d\n", GetLastError() );
- return 0;
- }
- PROCESS_INFORMATION ProcessInformation;
- STARTUPINFO StartupInfo = { sizeof(StartupInfo) };
- PWSTR CommandLine = PathGetArgs(GetCommandLine());
- if( !CreateProcess( NULL, CommandLine, NULL, NULL, FALSE, CREATE_NEW_CONSOLE | CREATE_SUSPENDED, NULL, NULL, &StartupInfo, &ProcessInformation ) )
- {
- wprintf( L"Could not run process, error %d\n", GetLastError() );
- return 0;
- }
- if( !AssignProcessToJobObject( HandleToTest, ProcessInformation.hProcess ) )
- {
- wprintf( L"Could not assign process to job, error %d\n", GetLastError() );
- return 0;
- }
- printf( "\nHandle : [%#x]", HandleToTest );
- system( "pause" );
- ResumeThread( ProcessInformation.hThread );
- CloseHandle( ProcessInformation.hThread );
- CloseHandle( ProcessInformation.hProcess );
- DWORD CompletionCode;
- ULONG_PTR CompletionKey;
- LPOVERLAPPED Overlapped;
- int ProcessCount = 0;
- while ( GetQueuedCompletionStatus( IOPort, &CompletionCode, &CompletionKey, &Overlapped, INFINITE ) && CompletionCode != JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO )
- {
- if ( CompletionCode == JOB_OBJECT_MSG_NEW_PROCESS ) ProcessCount++;
- if ( ( CompletionCode == JOB_OBJECT_MSG_EXIT_PROCESS ) || ( CompletionCode == JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS) ) ProcessCount--;
- wprintf( L"Waiting for %d processes to finish...\n", ProcessCount );
- }
- wprintf( L"All done\n" );
- return 0;
- }
- void EnableDebugPriv( void )
- {
- HANDLE hToken;
- LUID sedebugnameValue;
- TOKEN_PRIVILEGES tkp;
- // enable the SeDebugPrivilege
- if ( ! OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
- {
- _tprintf( _T( "OpenProcessToken() failed, Error = %d SeDebugPrivilege is not available.\n" ) , GetLastError() );
- return;
- }
- if ( ! LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &sedebugnameValue ) )
- {
- _tprintf( _T( "LookupPrivilegeValue() failed, Error = %d SeDebugPrivilege is not available.\n" ), GetLastError() );
- CloseHandle( hToken );
- return;
- }
- tkp.PrivilegeCount = 1;
- tkp.Privileges[ 0 ].Luid = sedebugnameValue;
- tkp.Privileges[ 0 ].Attributes = SE_PRIVILEGE_ENABLED;
- if ( ! AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof tkp, NULL, NULL ) )
- _tprintf( _T( "AdjustTokenPrivileges() failed, Error = %d SeDebugPrivilege is not available.\n" ), GetLastError() );
- CloseHandle( hToken );
- }//EnableDebugPriv
- PVOID GetLibraryProcAddress( PSTR LibraryName, PSTR ProcName )
- {
- return GetProcAddress( GetModuleHandleA( LibraryName ), ProcName );
- }
- int GetHandle( ULONG pid )
- {
- HANDLE processHandle;
- ULONG i;
- wchar_t tmp[ 64 ] = { 0 };
- HANDLE duplicated;
- if ( !( processHandle = OpenProcess( PROCESS_DUP_HANDLE, FALSE, pid ) ) )
- {
- printf( "\n\tCould not open PID %d! (Don't try to open a system process.)\n", pid );
- return 1;
- }
- /* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */
- if ( !NT_SUCCESS( status ) )
- {
- printf( "NtQuerySystemInformation failed!\n" );
- return NULL;
- }
- int Count = 0;
- for ( i = 0; i < handleInfo->HandleCount; i++ )
- {
- SYSTEM_HANDLE handle = handleInfo->Handles[ i ];
- HANDLE dupHandle = NULL;
- POBJECT_TYPE_INFORMATION objectTypeInfo;
- PVOID objectNameInfo;
- UNICODE_STRING objectName;
- ULONG returnLength;
- /* Check if this handle belongs to the PID the user specified. */
- if ( handle.ProcessId != pid ) continue;
- //--------------------------------------------------------------
- Count++;
- //--------------------------------------------------------------
- /* Duplicate the handle so we can query it. */
- if ( !NT_SUCCESS( NtDuplicateObject( processHandle, ( HANDLE )handle.Handle, GetCurrentProcess(), &dupHandle, 0, 0, 0 ) ) )
- {
- // printf( "%3d - [%#x] Error!\n", Count, handle.Handle );
- continue;
- }
- /* Query the object type. */
- objectTypeInfo = ( POBJECT_TYPE_INFORMATION )malloc( 0x1000 );
- if ( !NT_SUCCESS( NtQueryObject( dupHandle, ObjectTypeInformation, objectTypeInfo, 0x1000, NULL ) ) )
- {
- printf( "%3d - [%#x] Error!\n", Count, handle.Handle );
- CloseHandle( dupHandle );
- continue;
- }
- /* Query the object name (unless it has an access of
- 0x0012019f, on which NtQueryObject could hang. */
- if ( handle.GrantedAccess == 0x0012019f )
- {
- /* We have the type, so display that. */
- if ( wcscmp( tmp , L"Job" ) != 0 ) ;//do nothing
- else
- {
- printf( "%3d - [%#x] %.*S: (did not get name)\n", Count, handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );
- if ( !DuplicateHandle( OpenProcess( PROCESS_ALL_ACCESS, FALSE, pid ), ( HANDLE )handle.Handle, GetCurrentProcess(), &duplicated, 0, FALSE, DUPLICATE_SAME_ACCESS ) )
- printf( "\nDuplicateHandle Failed!" );
- else
- {
- BOOL res;
- IsProcessInJob( duplicated, NULL, &res );
- printf( "IsProcessInJob: %s\n", res ? "True" : "False" );
- if ( res ) test( duplicated );
- }
- }
- free( objectTypeInfo );
- CloseHandle( dupHandle );
- continue;
- }
- objectNameInfo = malloc( 0x1000 );
- if ( !NT_SUCCESS( NtQueryObject( dupHandle, ObjectNameInformation, objectNameInfo, 0x1000, &returnLength ) ) )
- {
- /* Reallocate the buffer and try again. */
- objectNameInfo = realloc( objectNameInfo, returnLength );
- if ( !NT_SUCCESS( NtQueryObject( dupHandle, ObjectNameInformation, objectNameInfo, returnLength, NULL ) ) )
- {
- /* We have the type name, so just display that. */
- if ( wcscmp( tmp , L"Job" ) != 0 ) ;//do nothing
- else
- {
- printf( "\n\t%3d - [%#x] %.*S: (could not get name)\n", Count, handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );
- if ( !DuplicateHandle( OpenProcess( PROCESS_ALL_ACCESS, FALSE, pid ), ( HANDLE )handle.Handle, GetCurrentProcess(), &duplicated, 0, FALSE, DUPLICATE_SAME_ACCESS ) )
- printf( "\nDuplicateHandle Failed!" );
- else
- {
- BOOL res;
- IsProcessInJob( duplicated, NULL, &res );
- printf( "IsProcessInJob: %s\n", res ? "True" : "False" );
- if ( res ) test( duplicated );
- }
- }
- free( objectTypeInfo );
- free( objectNameInfo );
- CloseHandle( dupHandle );
- continue;
- }
- }
- /* Cast our buffer into an UNICODE_STRING. */
- objectName = *( PUNICODE_STRING )objectNameInfo;
- /* Print the information! */
- if ( objectName.Length )
- {
- /* The object has a name. */
- wsprintf( tmp, L"%ls", objectTypeInfo->Name.Buffer );
- if ( wcscmp( tmp , L"Job" ) != 0 ) ;//do nothing
- else
- {
- //printf( "\n\t%3d - [%#x] %.*S: %.*S\n", Count, handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer, objectName.Length / 2, objectName.Buffer );
- printf( "\n\t%3d - [%#x] \t%d - %ls \t\n", Count, handle.Handle, handle.ObjectTypeNumber, objectName.Buffer );
- if ( !DuplicateHandle( OpenProcess( PROCESS_ALL_ACCESS, FALSE, pid ), ( HANDLE )handle.Handle, GetCurrentProcess(), &duplicated, 0, FALSE, DUPLICATE_SAME_ACCESS ) )
- printf( "\nDuplicateHandle Failed!" );
- else
- {
- BOOL res;
- IsProcessInJob( duplicated, NULL, &res );
- printf( "IsProcessInJob: %s\n", res ? "True" : "False" );
- if ( res ) test( duplicated );
- }
- }
- }
- else
- {
- /* Print something else. */
- wsprintf( tmp, L"%ls", objectTypeInfo->Name.Buffer );
- if ( wcscmp( tmp , L"Job" ) != 0 ) ;//do nothing
- else
- {
- //printf( "\n\t%3d - [%#x] %.*S: (unnamed)\n", Count, handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer );
- printf( "\n\t%3d - [%#x] \t%d - %ls \t\n", Count, handle.Handle, handle.ObjectTypeNumber, objectName.Buffer );
- if ( !DuplicateHandle( OpenProcess( PROCESS_ALL_ACCESS, FALSE, pid ), ( HANDLE )handle.Handle, GetCurrentProcess(), &duplicated, 0, FALSE, DUPLICATE_SAME_ACCESS ) )
- printf( "\nDuplicateHandle Failed!" );
- else
- {
- BOOL res;
- IsProcessInJob( duplicated, NULL, &res );
- printf( "IsProcessInJob: %s\n", res ? "True" : "False" );
- if ( res ) test( duplicated );
- }
- }
- }
- free( objectTypeInfo );
- free( objectNameInfo );
- CloseHandle( dupHandle );
- }
- CloseHandle( processHandle );
- return 0;
- }
- int GetProcessList()
- {
- size_t bufferSize = 102400;
- PSYSTEM_PROCESS_INFORMATION_DETAILD pspid = ( PSYSTEM_PROCESS_INFORMATION_DETAILD )malloc( bufferSize );
- ULONG ReturnLength;
- PFN_NT_QUERY_SYSTEM_INFORMATION pfnNtQuerySystemInformation = ( PFN_NT_QUERY_SYSTEM_INFORMATION )
- GetProcAddress( GetModuleHandle( TEXT( "ntdll.dll" ) ), "NtQuerySystemInformation" );
- NTSTATUS status;
- while( TRUE )
- {
- status = pfnNtQuerySystemInformation( SystemProcessInformation, ( PVOID )pspid, bufferSize, &ReturnLength );
- if ( status == STATUS_SUCCESS )
- break;
- else if ( status != STATUS_INFO_LENGTH_MISMATCH )
- { // 0xC0000004L
- _tprintf( TEXT( "ERROR 0x%X\n" ), status );
- return 1; // error
- }
- bufferSize *= 2;
- pspid = ( PSYSTEM_PROCESS_INFORMATION_DETAILD )realloc( ( PVOID )pspid, bufferSize );
- }
- int Counter = 1;
- for ( ; ; pspid = ( PSYSTEM_PROCESS_INFORMATION_DETAILD )( pspid->NextEntryOffset + ( PBYTE )pspid ) )
- {
- _tprintf( TEXT( "%4d.\tPID: %d, \tProcess: %ls\n" ), Counter++, pspid->UniqueProcessId,
- ( pspid->ImageName.Length && pspid->ImageName.Buffer ) ? pspid->ImageName.Buffer: L"" );
- wchar_t test[64] = {0};
- wsprintf( test, L"%ls",pspid->ImageName.Buffer );
- GetHandle( ( DWORD )pspid->UniqueProcessId );
- if ( pspid->NextEntryOffset == 0 ) break;
- }
- return 0;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement