findhandle.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #include <windows.h>
  2. #include <stdio.h>
  3. #include <shlwapi.h>
  4. #include <Psapi.h>
  5. #include "findhandle.h"
  6. #include "beacon.h"
  7. #pragma comment(lib, "shlwapi")
  8. //Code from: https://github.com/outflanknl/C2-Tool-Collection/blob/main/BOF/Psx/SOURCE/Psx.c
  9. HRESULT BeaconPrintToStreamW(_In_z_ LPCWSTR lpwFormat, ...) {
  10. HRESULT hr = S_FALSE;
  11. va_list argList;
  12. DWORD dwWritten = 0;
  13. if (g_lpStream <= (LPSTREAM)1) {
  14. hr = OLE32$CreateStreamOnHGlobal(NULL, TRUE, &g_lpStream);
  15. if (FAILED(hr)) {
  16. return hr;
  17. }
  18. }
  19. // For BOF we need to avoid large stack buffers, so put print buffer on heap.
  20. if (g_lpwPrintBuffer <= (LPWSTR)1) { // Allocate once and free in BeaconOutputStreamW.
  21. g_lpwPrintBuffer = (LPWSTR)MSVCRT$calloc(MAX_STRING, sizeof(WCHAR));
  22. if (g_lpwPrintBuffer == NULL) {
  23. hr = E_FAIL;
  24. goto CleanUp;
  25. }
  26. }
  27. va_start(argList, lpwFormat);
  28. if (!MSVCRT$_vsnwprintf_s(g_lpwPrintBuffer, MAX_STRING, MAX_STRING -1, lpwFormat, argList)) {
  29. hr = E_FAIL;
  30. goto CleanUp;
  31. }
  32. if (g_lpStream != NULL) {
  33. if (FAILED(hr = g_lpStream->lpVtbl->Write(g_lpStream, g_lpwPrintBuffer, (ULONG)MSVCRT$wcslen(g_lpwPrintBuffer) * sizeof(WCHAR), &dwWritten))) {
  34. goto CleanUp;
  35. }
  36. }
  37. hr = S_OK;
  38. CleanUp:
  39. if (g_lpwPrintBuffer != NULL) {
  40. MSVCRT$memset(g_lpwPrintBuffer, 0, MAX_STRING * sizeof(WCHAR)); // Clear print buffer.
  41. }
  42. va_end(argList);
  43. return hr;
  44. }
  45. //Code from: https://github.com/outflanknl/C2-Tool-Collection/blob/main/BOF/Psx/SOURCE/Psx.c
  46. VOID BeaconOutputStreamW() {
  47. STATSTG ssStreamData = { 0 };
  48. SIZE_T cbSize = 0;
  49. ULONG cbRead = 0;
  50. LARGE_INTEGER pos;
  51. LPWSTR lpwOutput = NULL;
  52. if (FAILED(g_lpStream->lpVtbl->Stat(g_lpStream, &ssStreamData, STATFLAG_NONAME))) {
  53. return;
  54. }
  55. cbSize = ssStreamData.cbSize.LowPart;
  56. lpwOutput = KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, cbSize + 1);
  57. if (lpwOutput != NULL) {
  58. pos.QuadPart = 0;
  59. if (FAILED(g_lpStream->lpVtbl->Seek(g_lpStream, pos, STREAM_SEEK_SET, NULL))) {
  60. goto CleanUp;
  61. }
  62. if (FAILED(g_lpStream->lpVtbl->Read(g_lpStream, lpwOutput, (ULONG)cbSize, &cbRead))) {
  63. goto CleanUp;
  64. }
  65. BeaconPrintf(CALLBACK_OUTPUT, "%ls", lpwOutput);
  66. }
  67. CleanUp:
  68. if (g_lpStream != NULL) {
  69. g_lpStream->lpVtbl->Release(g_lpStream);
  70. g_lpStream = NULL;
  71. }
  72. if (g_lpwPrintBuffer != NULL) {
  73. MSVCRT$free(g_lpwPrintBuffer); // Free print buffer.
  74. g_lpwPrintBuffer = NULL;
  75. }
  76. if (lpwOutput != NULL) {
  77. KERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, lpwOutput);
  78. }
  79. return;
  80. }
  81. BOOL GetHandles(int basePid, const BYTE flags, int targetPid) {
  82. NTSTATUS status;
  83. PSYSTEM_HANDLE_INFORMATION handleInfo;
  84. ULONG handleInfoSize = 0x10000;
  85. HANDLE processHandle;
  86. ULONG i;
  87. char procHostName[MAX_PATH];
  88. BOOL foundHandle = FALSE;
  89. if (flags == QUERY_PROC) BeaconPrintToStreamW(L"[+] PROCESS HANDLE RESULTS\n==========================================");
  90. else BeaconPrintToStreamW(L"[+] THREAD HANDLE RESULTS\n==========================================");
  91. NtQuerySystemInformation_t pNtQuerySystemInformation = (NtQuerySystemInformation_t) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation");
  92. NtDuplicateObject_t pNtDuplicateObject = (NtDuplicateObject_t) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtDuplicateObject");
  93. NtQueryObject_t pNtQueryObject = (NtQueryObject_t) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQueryObject");
  94. // parse which handle types extract
  95. WCHAR Filter[100];
  96. switch(flags) {
  97. case QUERY_PROC: MSVCRT$swprintf_s(Filter, 50, L"%s", L"Process"); break;
  98. default: MSVCRT$swprintf_s(Filter, 50, L"%s", L"Thread"); break;
  99. }
  100. handleInfo = (PSYSTEM_HANDLE_INFORMATION) MSVCRT$malloc(handleInfoSize);
  101. while ((status = pNtQuerySystemInformation(SystemHandleInformation, handleInfo, handleInfoSize, NULL)) == STATUS_INFO_LENGTH_MISMATCH)
  102. handleInfo = (PSYSTEM_HANDLE_INFORMATION)MSVCRT$realloc(handleInfo, handleInfoSize *= 2);
  103. if (status != 0) {
  104. BeaconPrintf(CALLBACK_ERROR, "Failed to retrieve process information!\n");
  105. return 1;
  106. }
  107. for (i = 0 ; i < handleInfo->NumberOfHandles ; i++) {
  108. SYSTEM_HANDLE_TABLE_ENTRY_INFO objHandle = handleInfo->Handles[i];
  109. HANDLE dupHandle = NULL;
  110. POBJECT_TYPE_INFORMATION objectTypeInfo;
  111. PVOID objectNameInfo;
  112. UNICODE_STRING objectName;
  113. ULONG returnLength;
  114. //Skip system processes
  115. if(objHandle.UniqueProcessId == 4) continue;
  116. //p2h: if the process doens't match the basePid, go to the next
  117. if ((basePid != 0) && (objHandle.UniqueProcessId != basePid)) continue;
  118. //all: for some reason handles dont fully close if the tool is finshed in COFF. This will skip all the handles from the previous enumeration task
  119. if (objHandle.UniqueProcessId == KERNEL32$GetCurrentProcessId()) continue;
  120. if (!(processHandle = KERNEL32$OpenProcess(PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION, FALSE, objHandle.UniqueProcessId))) {
  121. continue;
  122. }
  123. KERNEL32$K32GetProcessImageFileNameA(processHandle, procHostName, MAX_PATH);
  124. if (!NT_SUCCESS(pNtDuplicateObject(processHandle, (void *) objHandle.HandleValue, KERNEL32$GetCurrentProcess(), &dupHandle, 0, 0, DUPLICATE_SAME_ACCESS))) {
  125. continue;
  126. }
  127. objectTypeInfo = (POBJECT_TYPE_INFORMATION) MSVCRT$malloc(0x1000);
  128. if (!NT_SUCCESS(pNtQueryObject(dupHandle, ObjectTypeInformation, objectTypeInfo, 0x1000, NULL))) {
  129. KERNEL32$CloseHandle(dupHandle);
  130. continue;
  131. }
  132. if (!SHLWAPI$StrStrIW(Filter, objectTypeInfo->Name.Buffer)) {
  133. MSVCRT$free(objectTypeInfo);
  134. KERNEL32$CloseHandle(dupHandle);
  135. continue;
  136. }
  137. objectNameInfo = MSVCRT$malloc(0x1000);
  138. objectName = *(PUNICODE_STRING) objectNameInfo;
  139. int procID = 0;
  140. if (flags == QUERY_PROC) procID = KERNEL32$GetProcessId(dupHandle);
  141. if (flags == QUERY_THREAD) procID = KERNEL32$GetProcessIdOfThread(dupHandle);
  142. char procNameTemp[MAX_PATH];
  143. if (procID != 0) {
  144. if (flags == QUERY_THREAD) {
  145. HANDLE pH = KERNEL32$OpenProcess(PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION, FALSE, procID);
  146. if (pH) KERNEL32$K32GetProcessImageFileNameA(pH, procNameTemp, MAX_PATH);
  147. else MSVCRT$sprintf_s(procNameTemp, MAX_PATH, "%s", "non existent?");
  148. KERNEL32$CloseHandle(pH);
  149. }
  150. else {
  151. KERNEL32$K32GetProcessImageFileNameA(dupHandle, procNameTemp, MAX_PATH);
  152. }
  153. }
  154. //h2p: if the process doens't match the targetPid, go to the next
  155. if (targetPid != 0 && targetPid != procID) {
  156. MSVCRT$free(objectTypeInfo);
  157. MSVCRT$free(objectNameInfo);
  158. KERNEL32$CloseHandle(dupHandle);
  159. continue;
  160. }
  161. //if the PID of the handle is 0 or pointing to itself, skip it otherwise print output to stream
  162. if(procID != 0 && objHandle.UniqueProcessId != procID) {
  163. WCHAR WprocHostName[100];
  164. WCHAR WprocNameTemp[100];
  165. KERNEL32$MultiByteToWideChar(CP_ACP, 0, SHLWAPI$PathFindFileNameA(procHostName), -1, WprocHostName, 100);
  166. KERNEL32$MultiByteToWideChar(CP_ACP, 0, SHLWAPI$PathFindFileNameA(procNameTemp), -1, WprocNameTemp, 100);
  167. BeaconPrintToStreamW(L"\nHandle from:\t%s [%d]\nHandle to:\t%s [%d]\nHandle object:\t%#x\nAccess rights:\t%#x\n",
  168. WprocHostName,
  169. KERNEL32$GetProcessId(processHandle),
  170. WprocNameTemp,
  171. procID,
  172. objHandle.HandleValue,
  173. objHandle.GrantedAccess); //https://learn.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights
  174. foundHandle = TRUE;
  175. }
  176. MSVCRT$free(objectTypeInfo);
  177. MSVCRT$free(objectNameInfo);
  178. KERNEL32$CloseHandle(dupHandle);
  179. }
  180. MSVCRT$free(handleInfo);
  181. KERNEL32$CloseHandle(processHandle);
  182. return foundHandle;
  183. }
  184. int go(char *args, int len) {
  185. int basePid = 0;
  186. int targetPid = 0;
  187. BYTE flags;
  188. CHAR *search;
  189. CHAR *query;
  190. BOOL res = NULL;
  191. datap parser;
  192. BeaconDataParse(&parser, args, len);
  193. search = BeaconDataExtract(&parser, NULL);
  194. query = BeaconDataExtract(&parser, NULL);
  195. //BeaconPrintf(CALLBACK_OUTPUT, "search: %s\n", search); //DEBUG
  196. //BeaconPrintf(CALLBACK_OUTPUT, "query: %s\n", query); //DEBUG
  197. if (MSVCRT$strcmp(query, "proc") == 0) flags = QUERY_PROC;
  198. else if (MSVCRT$strcmp(query, "thread") == 0) flags = QUERY_THREAD;
  199. else {
  200. BeaconPrintf(CALLBACK_ERROR, "Please specify either proc (PROCESS_HANDLE) or 2 (THREAD_HANDLE) as handle search options.\n");
  201. return 0;
  202. }
  203. if (MSVCRT$strcmp(search, "all") == 0) {
  204. BeaconPrintf(CALLBACK_OUTPUT, "[*] Start enumerating all processes with handles to all other processes\n");
  205. res = GetHandles(0, flags, 0);
  206. }
  207. else if (MSVCRT$strcmp(search, "h2p") == 0) {
  208. targetPid = BeaconDataInt(&parser);
  209. BeaconPrintf(CALLBACK_OUTPUT, "[*] Start enumerating all processes that have a handle to PID: [%d]\n", targetPid);
  210. res = GetHandles(0, flags, targetPid);
  211. }
  212. else if (MSVCRT$strcmp(search, "p2h") == 0) {
  213. basePid = BeaconDataInt(&parser);
  214. BeaconPrintf(CALLBACK_OUTPUT, "[*] Start enumerating handles from PID [%d] to all other processes\n", basePid);
  215. res = GetHandles(basePid, flags, 0);
  216. }
  217. else {
  218. BeaconPrintf(CALLBACK_ERROR, "Please specify one of the following process search options: ht | h2p | p2h\n");
  219. return 0;
  220. }
  221. if(!res) BeaconPrintf(CALLBACK_ERROR, "No handle found for this search query!\n");
  222. else {
  223. BeaconOutputStreamW();
  224. BeaconPrintf(CALLBACK_OUTPUT, "\n[+] DONE");
  225. }
  226. return 0;
  227. }