<转>内核层 进程列举 NtQuerySystemInformation

/*--------- 1.c -----------*/ 
#include "1.h"   

//---------列举进程---------   
NTSTATUS EnumProcess()   
{   
int iCount = 1;    //进程计数   
NTSTATUS status;   //返回值   
PVOID pSi = NULL; /*指向SystemInformationClass的指针,此处为SystemProcessesAndThreadsInformation,即我们所要获取的信息*/ 
PSYSTEM_PROCESS_INFORMATION pSpiNext = NULL; //同上   
ULONG uSize;       //pSi的大小,以BYTE为单位   
ULONG pNeededSize = 0; //系统返回所需长度,因在WIN2000下不会返回,故不使用,设置为0   
BOOL bOver = FALSE; //标识是否列举完成   

//设定pSi大小uSize初始为32K,并为pSi分配uSize的内存,根据返回值逐步累加uSize,步长为32K   
for (uSize = 0x8000; ((pSi = ExAllocatePoolWithTag(NonPagedPool, uSize, 'tag1')) != NULL); uSize += 0x8000)   
{   
    //检索指定的系统信息,这里是有关进程的信息   
    status = NtQuerySystemInformation(SystemProcessesAndThreadsInformation,   
                      pSi,   
                      uSize,   
                      &pNeededSize);   
    if (STATUS_SUCCESS == status) //NtQuerySystemInformation返回成功   
    {   
      DbgPrint("[Aliwy] SUCCESS uSize = 0x%.8X, pNeededSize = 0x%.8X, status = 0x%.8X\n", uSize, pNeededSize, status);   
      pSpiNext = (PSYSTEM_PROCESS_INFORMATION)pSi; /*使用pSpiNext操作,pSi要留到后面释放所分配的内存*/
      while (TRUE)   
      {   
        if (pSpiNext->ProcessId == 0)   
        {   
          DbgPrint("[Aliwy] %d - System Idle Process\n", pSpiNext->ProcessId); /*进程标识符为0的是System Idle Process,需手动标明*/ 
        }   
        else 
        {   
          DbgPrint("[Aliwy] %d - %wZ\n", pSpiNext->ProcessId, &pSpiNext->ImageName); /*打印出进程标识符和进程名称*/ 
        }   
        if (pSpiNext->NextEntryOffset == 0) //如果NextEntryOffset为0即表示进程已列举完   
        {   
          DbgPrint("[Aliwy] EnumProcess Over, Count is: %d\n", iCount);   
          bOver = TRUE; //标识进程列举已完成   
          break; //跳出列举循环(while循环)   
        }           
        pSpiNext = (PSYSTEM_PROCESS_INFORMATION)((ULONG)pSpiNext + pSpiNext->NextEntryOffset); //指向下一个进程的信息   
        iCount++;   //计数累加   
      }   
      ExFreePool(pSi); //释放为sPi分配的内存   
      if (bOver) //进程列举完成   
      {   
        break; //跳出内存分配循环(for循环)   
      }   
    }   
    else 
    {   
      DbgPrint("[Aliwy] FAILURE uSize = %.8X, pNeededSize = %.8X, status = %.8X\n", uSize, pNeededSize, status);   
    }   
}   
return STATUS_SUCCESS;   
}   
//------------------------------   

//---------DriverUnload---------   
VOID OnUnload( IN PDRIVER_OBJECT DriverObject )   
{   
DbgPrint("[Aliwy] OnUnload\n");   
}   
//------------------------------   

//----------DriverEntry---------   
NTSTATUS DriverEntry( IN PDRIVER_OBJECT theDriverObject, IN PUNICODE_STRING theRegistryPath )   
{   
DbgPrint("[Aliwy] DriverEntry\n");   
     
EnumProcess();   
     
theDriverObject->DriverUnload = OnUnload;    
     
return STATUS_SUCCESS;   
}   
//------------------------------   


/*----------- 1.h ------------*/ 
#include <ntddk.h>   

#define DWORD unsigned long   
#define BOOL int   

//---------系统信息结构---------   
typedef enum _SYSTEM_INFORMATION_CLASS {   
SystemBasicInformation,   
SystemProcessorInformation,   
SystemPerformanceInformation,   
SystemTimeOfDayInformation,   
SystemNotImplemented1,   
SystemProcessesAndThreadsInformation,   
SystemCallCounts,   
SystemConfigurationInformation,   
SystemProcessorTimes,   
SystemGlobalFlag,   
SystemNotImplemented2,   
SystemModuleInformation,   
SystemLockInformation,   
SystemNotImplemented3,   
SystemNotImplemented4,   
SystemNotImplemented5,   
SystemHandleInformation,   
SystemObjectInformation,   
SystemPagefileInformation,   
SystemInstructionEmulationCounts,   
SystemInvalidInfoClass1,   
SystemCacheInformation,   
SystemPoolTagInformation,   
SystemProcessorStatistics,   
SystemDpcInformation,   
SystemNotImplemented6,   
SystemLoadImage,   
SystemUnloadImage,   
SystemTimeAdjustment,   
SystemNotImplemented7,   
SystemNotImplemented8,   
SystemNotImplemented9,   
SystemCrashDumpInformation,   
SystemExceptionInformation,   
SystemCrashDumpStateInformation,   
SystemKernelDebuggerInformation,   
SystemContextSwitchInformation,   
SystemRegistryQuotaInformation,   
SystemLoadAndCallImage,   
SystemPrioritySeparation,   
SystemNotImplemented10,   
SystemNotImplemented11,   
SystemInvalidInfoClass2,   
SystemInvalidInfoClass3,   
SystemTimeZoneInformation,   
SystemLookasideInformation,   
SystemSetTimeSlipEvent,   
SystemCreateSession,   
SystemDeleteSession,   
SystemInvalidInfoClass4,   
SystemRangeStartInformation,   
SystemVerifierInformation,   
SystemAddVerifier,   
    SystemSessionProcessesInformation   
} SYSTEM_INFORMATION_CLASS, *PSYSTEM_INFORMATION_CLASS;   
//------------------------------   

//---------线程信息结构---------   
typedef struct _SYSTEM_THREAD {   
LARGE_INTEGER           KernelTime;   
LARGE_INTEGER           UserTime;   
LARGE_INTEGER           CreateTime;   
ULONG                   WaitTime;   
PVOID                   StartAddress;   
CLIENT_ID               ClientId;   
KPRIORITY               Priority;   
LONG                    BasePriority;   
ULONG                   ContextSwitchCount;   
ULONG                   State;   
KWAIT_REASON            WaitReason;   
} SYSTEM_THREAD, *PSYSTEM_THREAD;   
//------------------------------   

//---------进程信息结构---------   
typedef struct _SYSTEM_PROCESS_INFORMATION {   
ULONG                   NextEntryOffset; //NextEntryDelta 构成结构序列的偏移量   
ULONG                   NumberOfThreads; //线程数目   
LARGE_INTEGER           Reserved[3];   
LARGE_INTEGER           CreateTime;   //创建时间   
LARGE_INTEGER           UserTime;     //用户模式(Ring 3)的CPU时间   
LARGE_INTEGER           KernelTime;   //内核模式(Ring 0)的CPU时间   
UNICODE_STRING          ImageName;    //进程名称   
KPRIORITY               BasePriority; //进程优先权   
HANDLE                  ProcessId;    //ULONG UniqueProcessId 进程标识符   
HANDLE                  InheritedFromProcessId; //父进程的标识符   
ULONG                   HandleCount; //句柄数目   
ULONG                   Reserved2[2];   
ULONG                   PrivatePageCount;   
VM_COUNTERS             VirtualMemoryCounters; //虚拟存储器的结构   
IO_COUNTERS             IoCounters; //IO计数结构   
SYSTEM_THREAD           Threads[0]; //进程相关线程的结构数组   
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;   

//typedef SYSTEM_PROCESSES SYSTEM_PROCESS_INFORMATION;   
//typedef PSYSTEM_PROCESSES PSYSTEM_PROCESS_INFORMATION;   
//MSDN此结构定义在SDK的winternl.h中,以上部分信息未文档化   
//_SYSTEM_PROCESS_INFORMATION = _SYSTEM_PROCESSES   
//------------------------------   

//---------函数声明-------------   
NTSYSAPI    
NTSTATUS   
NTAPI   
NtQuerySystemInformation(IN SYSTEM_INFORMATION_CLASS SystemInformationClass,   
             OUT PVOID SystemInformation,   
             IN ULONG SystemInformationLength,   
             OUT PULONG ReturnLength OPTIONAL);   
//------------------------------

另外再转一个

#include "ntddk.h"

#define printf DbgPrint

typedef enum _SYSTEM_INFORMATION_CLASS { 
SystemBasicInformation,      // 0 
   SystemProcessorInformation,     // 1 
   SystemPerformanceInformation,     // 2
   SystemTimeOfDayInformation,     // 3
   SystemNotImplemented1,      // 4
   SystemProcessesAndThreadsInformation,    // 5
   SystemCallCounts,       // 6
   SystemConfigurationInformation,     // 7
   SystemProcessorTimes,      // 8
   SystemGlobalFlag,       // 9
   SystemNotImplemented2,      // 10
   SystemModuleInformation,      // 11
   SystemLockInformation,      // 12
   SystemNotImplemented3,      // 13
   SystemNotImplemented4,      // 14
   SystemNotImplemented5,      // 15
   SystemHandleInformation,      // 16
   SystemObjectInformation,      // 17
   SystemPagefileInformation,      // 18
   SystemInstructionEmulationCounts,     // 19
   SystemInvalidInfoClass1,      // 20
   SystemCacheInformation,      // 21
   SystemPoolTagInformation,      // 22
   SystemProcessorStatistics,      // 23
   SystemDpcInformation,      // 24
   SystemNotImplemented6,      // 25
   SystemLoadImage,       // 26
   SystemUnloadImage,      // 27
   SystemTimeAdjustment,      // 28
   SystemNotImplemented7,      // 29
   SystemNotImplemented8,      // 30
   SystemNotImplemented9,      // 31
   SystemCrashDumpInformation,     // 32
   SystemExceptionInformation,     // 33
   SystemCrashDumpStateInformation,     // 34
   SystemKernelDebuggerInformation,     // 35
   SystemContextSwitchInformation,     // 36
   SystemRegistryQuotaInformation,     // 37
   SystemLoadAndCallImage,      // 38
   SystemPrioritySeparation,      // 39
   SystemNotImplemented10,      // 40
   SystemNotImplemented11,      // 41
   SystemInvalidInfoClass2,      // 42
   SystemInvalidInfoClass3,      // 43
   SystemTimeZoneInformation,      // 44
   SystemLookasideInformation,     // 45
   SystemSetTimeSlipEvent,      // 46
   SystemCreateSession,      // 47
   SystemDeleteSession,      // 48
   SystemInvalidInfoClass4,      // 49
   SystemRangeStartInformation,     // 50
   SystemVerifierInformation,      // 51
   SystemAddVerifier,      // 52
   SystemSessionProcessesInformation     // 53
} SYSTEM_INFORMATION_CLASS;

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 ContextSwitchCount;
LONG State;
LONG WaitReason;
} SYSTEM_THREAD_INFORMATION, * PSYSTEM_THREAD_INFORMATION;

typedef struct _SYSTEM_PROCESS_INFORMATION {
ULONG NextEntryDelta;
ULONG ThreadCount;
ULONG Reserved1[6];
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ProcessName;
KPRIORITY BasePriority;
ULONG ProcessId;
ULONG InheritedFromProcessId;
ULONG HandleCount;
ULONG Reserved2[2];
VM_COUNTERS VmCounters;
IO_COUNTERS IoCounters;
SYSTEM_THREAD_INFORMATION Threads[1];
} SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION;

NTSYSAPI
NTSTATUS
NTAPI
ZwQuerySystemInformation(
       IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
       OUT PVOID SystemInformation,
       IN ULONG SystemInformationLength,
       OUT PULONG ReturnLength OPTIONAL
);

void Ring0EnumProcess();

VOID OnUnload(IN PDRIVER_OBJECT DriverObject)
{
printf("the driver is unload"); 
}

NTSTATUS DriverEntry(IN OUT PDRIVER_OBJECT theDriverObject, IN PUNICODE_STRING RegistryPath)
{
theDriverObject->DriverUnload = OnUnload;
Ring0EnumProcess();
return STATUS_SUCCESS;
}

void Ring0EnumProcess()
{
//初始化缓冲区大小 32kb
ULONG cbBuffer = 0x8000;

PVOID pBuffer = NULL;
NTSTATUS ntStatus;
PSYSTEM_PROCESS_INFORMATION pInfo;
do 
{ //分配内存缓冲区
   pBuffer = ExAllocatePool(NonPagedPool, cbBuffer);
   if (pBuffer == NULL)
   {
    KdPrint(("分配内存失败!"));
    return; 
   }
   ntStatus = ZwQuerySystemInformation(SystemProcessesAndThreadsInformation, pBuffer, cbBuffer, NULL);
   if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) //如果缓冲区太小
   {
    ExFreePool(pBuffer); //释放缓冲区
    cbBuffer*=2;   //增加缓冲区到原来的2倍
   }
   else if (!NT_SUCCESS(ntStatus)) //如果获取信息不成功
   {
    ExFreePool(pBuffer);
    return;
   }


while(ntStatus == STATUS_INFO_LENGTH_MISMATCH);

pInfo = (PSYSTEM_PROCESS_INFORMATION)pBuffer;
while(TRUE)
{
   LPWSTR pszProcessName = pInfo->ProcessName.Buffer;
   //如果获取映像名失败则返回空
   if (pszProcessName == NULL)
   {
    pszProcessName = L"NULL";
   }
   DbgPrint("pid %d ps %S\n", pInfo->ProcessId, pInfo->ProcessName.Buffer); //调试输出结果
   if (pInfo->NextEntryDelta == 0)
   {
    break; //没有后继了,退出链表循环.
   }
   pInfo = (PSYSTEM_PROCESS_INFORMATION)(((PUCHAR)pInfo)+pInfo->NextEntryDelta);
  
}

ExFreePool(pBuffer); //释放分配的内存
return;
}

本人新博客网址为:http://www.hizds.com
本博客注有“转”字样的为转载文章,其余为本人原创文章,转载请务必注明出处或保存此段。c++/lua/windows逆向交流群:69148232
原文地址:https://www.cnblogs.com/zhangdongsheng/p/2793897.html