通过ntdll.dll的函数枚举进程

C语言代码如下:


#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <NTSecAPI.h>

//定义一个函数指针用来访问ntdll.dll中的ZwQuerySystemInformation函数
typedef DWORD(WINAPI *ZWQUERYSYSTEMINFORMATION)(DWORD, PVOID, DWORD, PDWORD);

//查询进程和线程的宏,还有其他宏
#define SystemProcessesAndThreadsInformation 5

//系统进程信息结构
typedef struct _SYSTEM_PROCESS_INFORMATION
{
    DWORD NexttEntryDelta;
    DWORD ThreadCount;
    DWORD Reserved1[6];
    FILETIME ftCreateTime;
    FILETIME ftUserTime;
    FILETIME ftKernelTime;
    UNICODE_STRING ProcessName;
    DWORD BasePriority;
    DWORD ProcessId;
    DWORD InheritedFromProcessId;
    DWORD HandleCount;
    DWORD Reserved2[6];
    DWORD VmCounters;
    DWORD dCommitCharge;
    PVOID ThreadInfos[1];
}SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;

int  main()
{
    //获取 ntdll.dll模块句柄
    HMODULE hNtDll = GetModuleHandle(L"ntdll.dll");
    if (!hNtDll)
    {
        return 0;
    }

    //获得函数指针
    ZWQUERYSYSTEMINFORMATION ZwQuerySystemInformation =
        (ZWQUERYSYSTEMINFORMATION)GetProcAddress(hNtDll, "ZwQuerySystemInformation");

    //分配内存
    ULONG cbBuffer = 0x100000;
    LPVOID pBuffer = malloc(cbBuffer);
    if (pBuffer == nullptr)
    {
        return 0;
    }
    //得到系统进程信息
    ZwQuerySystemInformation(SystemProcessesAndThreadsInformation, pBuffer, cbBuffer, nullptr);

    //转型
    PSYSTEM_PROCESS_INFORMATION pInfo = (PSYSTEM_PROCESS_INFORMATION)pBuffer;

    int iCount = 0;
    for (;;)
    {
        printf("%d (%ls)\n", pInfo->ProcessId, pInfo->ProcessName.Buffer);

        //像链表一样一个个查找
        if (pInfo->NexttEntryDelta == 0)
            break;

        pInfo = (PSYSTEM_PROCESS_INFORMATION)(((PUCHAR)pInfo) + pInfo->NexttEntryDelta);


    }
    free(pBuffer);

    system("pause");
    return 0;
}

你可能感兴趣的:(C语言,内核,函数指针,ntdll,枚举进程)