系统相关
首页 > 系统相关> > 【Windows内核研究】使用 NtQuerySystemInformation API 获取进程信息

【Windows内核研究】使用 NtQuerySystemInformation API 获取进程信息

作者:互联网

  1. 需要附加依赖项ntdll.lib
  2. 需要导入NtQuerySystemInformation等相关函数的定义。这里使用了ProcessHacker的phnt库。
    Github ProcessHacker phnt
    代码如下:
#include <iostream>
#include <phnt_windows.h>
#include <phnt.h>
using namespace std;

#define PTR_ADD_OFFSET(Pointer, Offset) ((PVOID)((ULONG_PTR)(Pointer) + (ULONG_PTR)(Offset)))

#define PH_NEXT_PROCESS(Process) ( \
    ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset ? \
    (PSYSTEM_PROCESS_INFORMATION)PTR_ADD_OFFSET((Process), \
    ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset) : \
    NULL \
    )

#define PH_FIRST_PROCESS(Processes) ((PSYSTEM_PROCESS_INFORMATION)(Processes))

int main()
{
    ULONG bufferSize;
    PVOID buffer;
    NTSTATUS status;
    PVOID PhHeapHandle;

    PhHeapHandle = RtlCreateHeap(
        HEAP_GROWABLE | HEAP_CLASS_1,
        NULL,
        2 * 1024 * 1024, // 2 MB
        1024 * 1024, // 1 MB
        NULL,
        NULL
    );

    if (! PhHeapHandle)
    {
        return -1;
    }

    bufferSize = 0x4000;
    buffer = RtlAllocateHeap(PhHeapHandle,HEAP_GENERATE_EXCEPTIONS,bufferSize);

    while (TRUE)
    {
        status = NtQuerySystemInformation(
            SystemProcessInformation,
            buffer,
            bufferSize,
            &bufferSize
        );

        if (status == STATUS_BUFFER_TOO_SMALL || status == STATUS_INFO_LENGTH_MISMATCH)
        {
            RtlFreeHeap(PhHeapHandle,0,buffer);
            buffer = RtlAllocateHeap(PhHeapHandle, HEAP_GENERATE_EXCEPTIONS, bufferSize);
        }
        else
        {
            break;
        }
    }

    if (!NT_SUCCESS(status))
    {
        RtlFreeHeap(PhHeapHandle, 0, buffer);
        return status;
    }

    PSYSTEM_PROCESS_INFORMATION process = PH_FIRST_PROCESS(buffer);

    while (process != NULL)
    {
        printf("ImageName is: %ws .\r\n", process->ImageName.Buffer);
        process = PH_NEXT_PROCESS(process);
    }

    RtlFreeHeap(PhHeapHandle, 0, buffer);
    RtlDestroyHeap(PhHeapHandle);

    return 0;
}

标签:status,NtQuerySystemInformation,PhHeapHandle,INFORMATION,Windows,PROCESS,API,buf
来源: https://www.cnblogs.com/ComputerPlayerJs/p/16484056.html