【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;
}

原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/274803.html

(0)
上一篇 2022年7月17日
下一篇 2022年7月17日

相关推荐

发表回复

登录后才能评论