Guest User

Untitled

a guest
Nov 20th, 2022
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. unsafe static IntPtr[] GetOpenedProcessHandles(Process targetProcess)
  2. {
  3.     NtStatus status;
  4.     IntPtr hProcess;
  5.  
  6.     var selfProc = Process.GetCurrentProcess();
  7.  
  8.     if (Kernel32.DuplicateHandle(Kernel32.CurrentProcess, Kernel32.CurrentProcess, Kernel32.CurrentProcess, out hProcess, 0, false, DuplicateOptions.DuplicateSameAccess)) {
  9.         uint cb = 0x10000;
  10.         do {
  11.             byte[] buf;
  12.             SystemHandleInformationEx* pshie;
  13.             //union {
  14.             //    PVOID buf;
  15.             //    PSYSTEM_HANDLE_INFORMATION_EX pshie;
  16.             //};
  17.  
  18.             buf = new byte[cb + 0x1000];
  19.                    
  20.             fixed(byte* bufPtr = buf) {
  21.                 pshie = (SystemHandleInformationEx*)bufPtr;
  22.  
  23.                 if (0 <= (status = NtDll.NtQuerySystemInformation(SystemInformationClass.SystemExtendedHandleInformation, bufPtr, cb, out cb))) {
  24.                     ulong NumberOfHandles = pshie->NumberOfHandles;
  25.  
  26.                     if (NumberOfHandles != 0)
  27.                     {
  28.                         uint UniqueProcessId = (uint)selfProc.Id;
  29.                         SystemHandleInformationExEntry* Entry = pshie->Handles;
  30.                         do {
  31.                             if (Entry->HandleValue == (ulong)hProcess && Entry->UniqueProcessId == UniqueProcessId) {
  32.                                 void* Object = Entry->Object;
  33.  
  34.                                 Entry = pshie->Handles;
  35.                                 NumberOfHandles = pshie->NumberOfHandles;
  36.  
  37.                                 do {
  38.                                     if (Object == Entry->Object && Entry->UniqueProcessId != UniqueProcessId) {
  39.                                         Console.WriteLine(Entry->UniqueProcessId);
  40.                                     }
  41.  
  42.                                     Entry++;
  43.                                 } while ((--NumberOfHandles) != 0);
  44.  
  45.                                 break;
  46.                             }
  47.  
  48.                             Entry++;
  49.                         } while ((--NumberOfHandles) != 0);
  50.                     }
  51.                 }
  52.             }
  53.         } while (status == NtStatus.INFO_LENGTH_MISMATCH);
  54.  
  55.         Kernel32.CloseHandle(hProcess);
  56.     }
  57.  
  58.     return null;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment