Thread Enumeration - NtQuerySystemInformation
In a previous module, the process of enumerating a system's threads was demonstrated using the snapshot WinAPIs. The Thread Hijacking Remote Thread Enumeration module, for exa...
Jump to Section (8)
Introduction
In a previous module, the process of enumerating a system's threads was demonstrated using the snapshot WinAPIs. The Thread Hijacking Remote Thread Enumeration module, for example, utilized CreateToolhelp32Snapshot, Thread32First, and Thread32Next WinAPIs.
Unfortunately, that approach can be problematic since it would first require the use of API hashing to hide these WinAPIs from the IAT. Secondly, even with API hashing in use, the previously mentioned WinAPIs make use of lower-level syscalls that can eventually be hooked by security vendors. For example, the following image shows ZwMapViewOfSection being called by Thread32Next.

Using syscalls to enumerate threads is preferable as it skips past the use of WinAPIs.
SYSTEM_PROCESS_INFORMATION Structure
As previously mentioned in the Process Enumeration NtQuerySystemInformation module, the SYSTEM_PROCESS_INFORMATION structure was vaguely documented by Microsoft, where the official definition contained many reserved members, hiding the purpose behind many members. As an alternative, Process Hacker's definition will be used for this module. Based on that, SYSTEM_PROCESS_INFORMATION will be defined as follows:
typedef struct _SYSTEM_PROCESS_INFORMATION
{
ULONG NextEntryOffset;
ULONG NumberOfThreads; // Size of the Threads member
LARGE_INTEGER WorkingSetPrivateSize;
ULONG HardFaultCount;
ULONG NumberOfThreadsHighWatermark;
ULONGLONG CycleTime;
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
ULONG HandleCount;
ULONG SessionId;
ULONG_PTR UniqueProcessKey;
SIZE_T PeakVirtualSize;
SIZE_T VirtualSize;
ULONG PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
SIZE_T PrivatePageCount;
LARGE_INTEGER ReadOperationCount;
LARGE_INTEGER WriteOperationCount;
LARGE_INTEGER OtherOperationCount;
LARGE_INTEGER ReadTransferCount;
LARGE_INTEGER WriteTransferCount;
LARGE_INTEGER OtherTransferCount;
SYSTEM_THREAD_INFORMATION Threads[1]; // Threads member
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;The member to be focused on is Threads, which is an array of the SYSTEM_THREAD_INFORMATION structure, with a size equal to NumberOfThreads. Each element in this array represents a running thread in the process being enumerated. Further details regarding the SYSTEM_THREAD_INFORMATION structure will be discussed in the following section.
SYSTEM_THREAD_INFORMATION & CLIENT_ID Structures
Based on Process Hacker's definition, the SYSTEM_THREAD_INFORMATION structure look like the following
typedef struct _SYSTEM_THREAD_INFORMATION
{
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientId;
KPRIORITY Priority;
KPRIORITY BasePriority;
ULONG ContextSwitches;
KTHREAD_STATE ThreadState;
KWAIT_REASON WaitReason;
} SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;The member of particular interest is ClientId, which is defined by Process Hacker to be of type CLIENT_ID. The definition of CLIENT_ID can be found in the Process Hacker repository here and is also shown below.
typedef struct _CLIENT_ID
{
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID, *PCLIENT_ID;The elements UniqueProcess and UniqueThread are defined as handles, but in reality, their values are process and thread IDs respectively. The UniqueThread element is of particular interest because it enables one to open a thread handle through the OpenThread WinAPI and achieve the purpose of thread enumeration.
The Implementation
To simplify matters, this module will be using the function pointer of NtQuerySystemInformation obtained through the GetModuleHandle and GetProcAddress WinAPIs. However, in real-world scenarios, it is recommended to use an alternative approach that can bypass userland hooks, such as direct or indirect syscalls.
Additionally, the syscall NtQuerySystemInformation will be invoked with the SystemProcessInformation flag to obtain an array of SYSTEM_PROCESS_INFORMATION. In this array, every element corresponds to a running process. By accessing the Threads member of each element, which is an array of the SYSTEM_THREAD_INFORMATION structure, one can uncover the active threads within the process.
ListRemoteProcessThreads
NtQuerySystemInformation will be called twice, the first call retrieves the SYSTEM_PROCESS_INFORMATION array size, which is then used to allocate a buffer. The second call is to use the allocated buffer to fetch the array. This is demonstrated in the following ListRemoteProcessThreads function that is used to list the running threads of process szProcName.
szProcNameThe name of the target process.
VOID ListRemoteProcessThreads(IN LPCWSTR szProcName) {
fnNtQuerySystemInformation pNtQuerySystemInformation = NULL;
ULONG uReturnLen1 = NULL,
uReturnLen2 = NULL;
PSYSTEM_PROCESS_INFORMATION SystemProcInfo = NULL;
PSYSTEM_THREAD_INFORMATION SystemThreadInfo = NULL;
PVOID pValueToFree = NULL;
NTSTATUS STATUS = NULL;
// Fetching NtQuerySystemInformation's address from ntdll.dll
pNtQuerySystemInformation = (fnNtQuerySystemInformation)GetProcAddress(GetModuleHandle(L"NTDLL.DLL"), "NtQuerySystemInformation");
if (pNtQuerySystemInformation == NULL) {
printf("[!] GetProcAddress Failed With Error : %d\n", GetLastError());
goto _EndOfFunc;
}
// First NtQuerySystemInformation call - retrieve the size of the return buffer (uReturnLen1)
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, NULL, NULL, &uReturnLen1)) != STATUS_SUCCESS && STATUS != STATUS_INFO_LENGTH_
MISMATCH) {
printf("[!] NtQuerySystemInformation [1] Failed With Error : 0x%0.8X \n", STATUS);
goto _EndOfFunc;
}
// Allocating buffer of size "uReturnLen1"
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (SIZE_T)uReturnLen1);
if (SystemProcInfo == NULL) {
printf("[!] HeapAlloc Failed With Error : %d\n", GetLastError());
goto _EndOfFunc;
}
// Setting a fixed variable to be used later to free, because "SystemProcInfo" will be modefied
pValueToFree = SystemProcInfo;
// Second NtQuerySystemInformation call - returning the SYSTEM_PROCESS_INFORMATION array (SystemProcInfo)
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, SystemProcInfo, uReturnLen1, &uReturnLen2)) != STATUS_SUCCESS) {
printf("[!] NtQuerySystemInformation [2] Failed With Error : 0x%0.8X \n", STATUS);
goto _EndOfFunc;
}
// Enumerating SystemProcInfo, looking for process "szProcName"
while (TRUE) {
// Searching for thr process name
if (SystemProcInfo->ImageName.Length && wcscmp(SystemProcInfo->ImageName.Buffer, szProcName) == 0) {
printf("[+] Found target process [ %ws ] - %ld \n", SystemProcInfo->ImageName.Buffer, SystemProcInfo->UniqueProcessId);
// Fetching the PSYSTEM_THREAD_INFORMATION array
SystemThreadInfo = (PSYSTEM_THREAD_INFORMATION)SystemProcInfo->Threads;
// Enumerating "SystemThreadInfo" of size SYSTEM_PROCESS_INFORMATION.NumberOfThreads
for (DWORD i = 0; i < SystemProcInfo->NumberOfThreads; i++) {
printf("[+] Thread [ %d ] \n", i);
printf("\t> Thread Id: %d \n", SystemThreadInfo[i].ClientId.UniqueThread);
printf("\t> Thread's Start Address: 0x%p\n", SystemThreadInfo[i].StartAddress);
printf("\t> Thread Priority: %d\n", SystemThreadInfo[i].Priority);
printf("\t> Thread State: %d\n", SystemThreadInfo[i].ThreadState);
}
// Break from while
break;
}
// If we reached the end of the SYSTEM_PROCESS_INFORMATION structure
if (!SystemProcInfo->NextEntryOffset)
break;
// Calculate the next SYSTEM_PROCESS_INFORMATION element in the array
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)SystemProcInfo + SystemProcInfo->NextEntryOffset);
}
// Free the SYSTEM_PROCESS_INFORMATION structure
_EndOfFunc:
if (pValueToFree)
HeapFree(GetProcessHeap(), 0, pValueToFree);
return;
}GetRemoteProcessThreads
The GetRemoteProcessThreads function, shown below, utilizes the ListRemoteProcessThreads function to retrieve both the PID and TID of the specified process named szProcName. It is important to note that the TID returned by GetRemoteProcessThreads corresponds to the first thread in the SYSTEM_THREAD_INFORMATION array, which is typically the main thread of the process. Refer to the code snippet below to view the implementation of the GetRemoteProcessThreads function.
szProcNameThe name of the target process.pdwPidA pointer to a DWORD variable that will recieve the target process PID.pdwThreadA pointer to a DWORD variable that will recieve the target process main TID.
BOOL GetRemoteProcessThreads(IN LPCWSTR szProcName, OUT DWORD* pdwPid, OUT DWORD* pdwThread) {
fnNtQuerySystemInformation pNtQuerySystemInformation = NULL;
ULONG uReturnLen1 = NULL,
uReturnLen2 = NULL;
PSYSTEM_PROCESS_INFORMATION SystemProcInfo = NULL;
PVOID pValueToFree = NULL;
NTSTATUS STATUS = NULL;
// Fetching NtQuerySystemInformation's address from ntdll.dll
pNtQuerySystemInformation = (fnNtQuerySystemInformation)GetProcAddress(GetModuleHandle(L"NTDLL.DLL"), "NtQuerySystemInformation");
if (pNtQuerySystemInformation == NULL) {
printf("[!] GetProcAddress Failed With Error : %d\n", GetLastError());
goto _EndOfFunc;
}
// First NtQuerySystemInformation call - retrieve the size of the return buffer (uReturnLen1)
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, NULL, NULL, &uReturnLen1)) != STATUS_SUCCESS && STATUS != STATUS_INFO_LENGTH_
MISMATCH) {
printf("[!] NtQuerySystemInformation [1] Failed With Error : 0x%0.8X \n", STATUS);
goto _EndOfFunc;
}
// Allocating buffer of size "uReturnLen1"
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (SIZE_T)uReturnLen1);
if (SystemProcInfo == NULL) {
printf("[!] HeapAlloc Failed With Error : %d\n", GetLastError());
goto _EndOfFunc;
}
// Setting a fixed variable to be used later to free, because "SystemProcInfo" will be modefied
pValueToFree = SystemProcInfo;
// Second NtQuerySystemInformation call - returning the SYSTEM_PROCESS_INFORMATION array (SystemProcInfo)
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, SystemProcInfo, uReturnLen1, &uReturnLen2)) != STATUS_SUCCESS) {
printf("[!] NtQuerySystemInformation [2] Failed With Error : 0x%0.8X \n", STATUS);
goto _EndOfFunc;
} // Enumerating SystemProcInfo, looking for process "szProcName"
while (TRUE) {
if (SystemProcInfo->ImageName.Length && wcscmp(SystemProcInfo->ImageName.Buffer, szProcName) == 0) {
// Target process is found, return PID & TID and break
*pdwPid = (DWORD)SystemProcInfo->UniqueProcessId;
*pdwThread = (DWORD)SystemProcInfo->Threads[0].ClientId.UniqueThread;
break;
}
// If we reached the end of the SYSTEM_PROCESS_INFORMATION structure
if (!SystemProcInfo->NextEntryOffset)
break;
// Calculate the next SYSTEM_PROCESS_INFORMATION element in the array
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)SystemProcInfo + SystemProcInfo->NextEntryOffset);
}
// Free the SYSTEM_PROCESS_INFORMATION structure
_EndOfFunc:
if (pValueToFree)
HeapFree(GetProcessHeap(), 0, pValueToFree);
if (*pdwPid != NULL && *pdwThread != NULL)
return TRUE;
else
return FALSE;
}Demo
ListRemoteProcessThreads function output, targetting notepad.exe.

GetRemoteProcessThreads function output, targetting RuntimeBroker.exe.

Video Demo

Companion Project & Source Code
5 readable source/config files extracted directly from the archive
// @NUL0x4C | @mrd0x : MalDevAcademy
#include <Windows.h>
#include <stdio.h>
#include "Structs.h"
// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/thread.htm?ts=0,313
#define STATUS_SUCCESS 0x00000000
#define STATUS_INFO_LENGTH_MISMATCH 0xC0000004
// function pointer
// https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysysteminformation
typedef NTSTATUS (WINAPI* fnNtQuerySystemInformation)(
SYSTEM_INFORMATION_CLASS SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength
);
BOOL GetRemoteProcessThreads(IN LPCWSTR szProcName, OUT DWORD* pdwPid, OUT DWORD* pdwThread) {
fnNtQuerySystemInformation pNtQuerySystemInformation = NULL;
ULONG uReturnLen1 = NULL,
uReturnLen2 = NULL;
PSYSTEM_PROCESS_INFORMATION SystemProcInfo = NULL;
PVOID pValueToFree = NULL;
NTSTATUS STATUS = NULL;
// Fetching NtQuerySystemInformation's address from ntdll.dll
pNtQuerySystemInformation = (fnNtQuerySystemInformation)GetProcAddress(GetModuleHandle(L"NTDLL.DLL"), "NtQuerySystemInformation");
if (pNtQuerySystemInformation == NULL) {
printf("[!] GetProcAddress Failed With Error : %d\n", GetLastError());
goto _EndOfFunc;
}
// First NtQuerySystemInformation call - retrieve the size of the return buffer (uReturnLen1)
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, NULL, NULL, &uReturnLen1)) != STATUS_SUCCESS && STATUS != STATUS_INFO_LENGTH_MISMATCH) {
printf("[!] NtQuerySystemInformation [1] Failed With Error : 0x%0.8X \n", STATUS);
goto _EndOfFunc;
}
// Allocating buffer of size "uReturnLen1"
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (SIZE_T)uReturnLen1);
if (SystemProcInfo == NULL) {
printf("[!] HeapAlloc Failed With Error : %d\n", GetLastError());
goto _EndOfFunc;
}
// Setting a fixed variable to be used later to free, because "SystemProcInfo" will be modefied
pValueToFree = SystemProcInfo;
// Second NtQuerySystemInformation call - returning the SYSTEM_PROCESS_INFORMATION array (SystemProcInfo)
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, SystemProcInfo, uReturnLen1, &uReturnLen2)) != STATUS_SUCCESS) {
printf("[!] NtQuerySystemInformation [2] Failed With Error : 0x%0.8X \n", STATUS);
goto _EndOfFunc;
}
// Enumerating SystemProcInfo, looking for process "szProcName"
while (TRUE) {
if (SystemProcInfo->ImageName.Length && wcscmp(SystemProcInfo->ImageName.Buffer, szProcName) == 0) {
// Target process is found, return PID & TID and break
*pdwPid = (DWORD)SystemProcInfo->UniqueProcessId;
*pdwThread = (DWORD)SystemProcInfo->Threads[0].ClientId.UniqueThread;
break;
}
// If we reached the end of the SYSTEM_PROCESS_INFORMATION structure
if (!SystemProcInfo->NextEntryOffset)
break;
// Calculate the next SYSTEM_PROCESS_INFORMATION element in the array
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)SystemProcInfo + SystemProcInfo->NextEntryOffset);
}
// Free the SYSTEM_PROCESS_INFORMATION structure
_EndOfFunc:
if (pValueToFree)
HeapFree(GetProcessHeap(), 0, pValueToFree);
if (*pdwPid != NULL && *pdwThread != NULL)
return TRUE;
else
return FALSE;
}
VOID ListRemoteProcessThreads(IN LPCWSTR szProcName) {
fnNtQuerySystemInformation pNtQuerySystemInformation = NULL;
ULONG uReturnLen1 = NULL,
uReturnLen2 = NULL;
PSYSTEM_PROCESS_INFORMATION SystemProcInfo = NULL;
PSYSTEM_THREAD_INFORMATION SystemThreadInfo = NULL;
PVOID pValueToFree = NULL;
NTSTATUS STATUS = NULL;
// Fetching NtQuerySystemInformation's address from ntdll.dll
pNtQuerySystemInformation = (fnNtQuerySystemInformation)GetProcAddress(GetModuleHandle(L"NTDLL.DLL"), "NtQuerySystemInformation");
if (pNtQuerySystemInformation == NULL) {
printf("[!] GetProcAddress Failed With Error : %d\n", GetLastError());
goto _EndOfFunc;
}
// First NtQuerySystemInformation call - retrieve the size of the return buffer (uReturnLen1)
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, NULL, NULL, &uReturnLen1)) != STATUS_SUCCESS && STATUS != STATUS_INFO_LENGTH_MISMATCH) {
printf("[!] NtQuerySystemInformation [1] Failed With Error : 0x%0.8X \n", STATUS);
goto _EndOfFunc;
}
// Allocating buffer of size "uReturnLen1"
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (SIZE_T)uReturnLen1);
if (SystemProcInfo == NULL) {
printf("[!] HeapAlloc Failed With Error : %d\n", GetLastError());
goto _EndOfFunc;
}
// Setting a fixed variable to be used later to free, because "SystemProcInfo" will be modefied
pValueToFree = SystemProcInfo;
// Second NtQuerySystemInformation call - returning the SYSTEM_PROCESS_INFORMATION array (SystemProcInfo)
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, SystemProcInfo, uReturnLen1, &uReturnLen2)) != STATUS_SUCCESS) {
printf("[!] NtQuerySystemInformation [2] Failed With Error : 0x%0.8X \n", STATUS);
goto _EndOfFunc;
}
// Enumerating SystemProcInfo, looking for process "szProcName"
while (TRUE) {
// Searching for thr process name
if (SystemProcInfo->ImageName.Length && wcscmp(SystemProcInfo->ImageName.Buffer, szProcName) == 0) {
printf("[+] Found target process [ %ws ] - %ld \n", SystemProcInfo->ImageName.Buffer, SystemProcInfo->UniqueProcessId);
// Fetching the PSYSTEM_THREAD_INFORMATION array
SystemThreadInfo = (PSYSTEM_THREAD_INFORMATION)SystemProcInfo->Threads;
// Enumerating "SystemThreadInfo" of size SYSTEM_PROCESS_INFORMATION.NumberOfThreads
for (DWORD i = 0; i < SystemProcInfo->NumberOfThreads; i++) {
printf("[+] Thread [ %d ] \n", i);
printf("\t> Thread Id: %d \n", SystemThreadInfo[i].ClientId.UniqueThread);
printf("\t> Thread's Start Address: 0x%p\n", SystemThreadInfo[i].StartAddress);
printf("\t> Thread Priority: %d\n", SystemThreadInfo[i].Priority);
printf("\t> Thread State: %d\n", SystemThreadInfo[i].ThreadState);
}
// Break from while
break;
}
// If we reached the end of the SYSTEM_PROCESS_INFORMATION structure
if (!SystemProcInfo->NextEntryOffset)
break;
// Calculate the next SYSTEM_PROCESS_INFORMATION element in the array
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)SystemProcInfo + SystemProcInfo->NextEntryOffset);
}
// Free the SYSTEM_PROCESS_INFORMATION structure
_EndOfFunc:
if (pValueToFree)
HeapFree(GetProcessHeap(), 0, pValueToFree);
return;
}
#define TARGET_PROCESS L"RuntimeBroker.exe"
int main(){
DWORD dwThreadId = NULL, dwProcessId;
if (!GetRemoteProcessThreads(TARGET_PROCESS, &dwProcessId, &dwThreadId))
return -1;
else
printf("[+] Target Process \"%ws\" Detected With PID [ %d ] & TID [ %d ]\n", TARGET_PROCESS, dwProcessId, dwThreadId);
//\
ListRemoteProcessThreads(TARGET_PROCESS);
return 0;
}
Full Archive Manifest (6 files inside .zip)
- NtQueryThreads/NtQueryThreads.sln
- NtQueryThreads/NtQueryThreads/NtQueryThreads.vcxproj
- NtQueryThreads/NtQueryThreads/NtQueryThreads.vcxproj.filters
- NtQueryThreads/NtQueryThreads/NtQueryThreads.vcxproj.user
- NtQueryThreads/NtQueryThreads/Structs.h
- NtQueryThreads/NtQueryThreads/main.c