Hemant
Hemant

Reputation: 867

How to get current working directory from windows kernel mode driver code?

I am writing a Windows kernel mode driver which uses API

PsSetCreateProcessNotifyRoutineEx

In its callback function, I need to get the current working directory of process. How this can be done? Any ideas, leads would be very useful.

Thanks in advance.

Upvotes: 2

Views: 1599

Answers (1)

Hemant
Hemant

Reputation: 867

Following code solved the issue

KAPC_STATE ka_state;
WCHAR   CWDBuffer[MAX_PATH] = { 0 };
USHORT  CWDBytes = 0;

UNICODE_STRING GetProcessPeb = RTL_CONSTANT_STRING(L"PsGetProcessPeb");
PsGetPeb = (PsGetProcessPeb)MmGetSystemRoutineAddress(&GetProcessPeb);
if (PsGetPeb)
{
    Peb = PsGetPeb(Process); // Process is handle to current process
    if (Peb) {
        KeStackAttachProcess(Process, &ka_state);

        if (Peb->ProcessParameters->CurrentDirectory.DosPath.Length < (MAX_PATH * sizeof(WCHAR)))
        {
            CWDBytes = Peb->ProcessParameters->CurrentDirectory.DosPath.Length;
        }
        else
        {
            CWDBytes = MAX_PATH * sizeof(WCHAR);
        }

        memcpy(CWDBuffer, Peb->ProcessParameters->CurrentDirectory.DosPath.Buffer, CWDBytes);

        KeUnstackDetachProcess(&ka_state);
    }
    else {
        DbgPrintEx(
            DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL,
            "Unable to get PEB\n"
        );
    }
}

Upvotes: 3

Related Questions