Search code examples
c++winapidriverwdk

Get Process PID With PsLookupProcessByProcessId


#include<Ntifs.h>
#include <ntddk.h>
#include <WinDef.h>

void SampleUnload(_In_ PDRIVER_OBJECT DriverObject) {

    UNREFERENCED_PARAMETER(DriverObject);
    DbgPrint("Sample driver Unload called\n");
}

extern "C"
NTSTATUS
DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) {
    UNREFERENCED_PARAMETER(RegistryPath);
    DriverObject->DriverUnload = SampleUnload;

    DbgPrint("Sample driver Load called\n");

    PEPROCESS EP = NULL;
    if (PsLookupProcessByProcessId(::PsGetCurrentProcessId(), &EP) == STATUS_INVALID_PARAMETER) {
        DbgPrint("Can't get the eprocess");
    }
    else {
        DbgPrint("Its working");
    }
    LPBYTE pUpi = ((LPBYTE)EP) + 0x440;
    PVOID UniqueProcessId = *((PVOID*)pUpi);

    DbgPrint("Test Test Test!");
    DbgPrint((CHAR*)UniqueProcessId);

    return STATUS_SUCCESS;
}

Hello everyone, I am trying to print out the pid of the driver as an exercise. When I am starting the driver he is working but in the 30 line he doesn't print anything and in all the others he does! I want to print out the pid of the process using EPROCESS.

Can someone help me please?


Solution

  • but in the 30 line he doesn't print anything

    you try say that

    DbgPrint((CHAR*)UniqueProcessId);
    

    doesn't print anything.

    DbgPrint accept pointer to the format string to print in first argument. but (CHAR*)UniqueProcessId not a string, even if you cast it to (CHAR*). if UniqueProcessId valid value - it small number, usually less than 0x10000, and memory access to this location (DbgPrint will try read this "string") must cause exception/bsod. but because use hard-coded offset (0x440) from EPROCESS always wrong - you read not process UniqueProcessId but some random data, which in your case accidentally point to valid memory. valid code for print must be like

    DbgPrint("UniqueProcessId=%p\n",UniqueProcessId);
    

    also all your code before this line, not have sense and contains critical errors