ZwProtectVirtualMemory() returning NTSTATUS 0xC0000018

I am trying to call ZwProtectVirtualMemory() from my driver, when I call it with parameters I think are correct nothing happens and NTSTATUS 0xC0000018 is returned (STATUS_CONFLICTING_ADDRESSES).

Here I grab the PEPROCESS pointer.

if (!NT_SUCCESS(PsLookupProcessByProcessId((void*)request->target_pid, &target_process)))

I know this is correct because I can use this to read and write with MmCopyVirtualMemory(). Then I attempt to call ZwProtectVirtualMemory() like so first I context switch with KeStackAttachProcess() then I attempt to call it.

KAPC_STATE apc;
KeStackAttachProcess(target_process, &apc); 
{
    auto protect_base = (void*)request->target_addr; // ZwProtectVirtualMemory writes to target_addr
    unsigned long old_prot = 0;
    DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "base : %X size : %i protection : %X" , protect_base, request->size, request->protection);
    status = ZwProtectVirtualMemory(ZwCurrentProcess(), &protect_base, (unsigned long*)&request->size, request->protection, &old_prot);
    DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "returned : %X", status);
}
KeUnstackDetachProcess(&apc);

The first DbgPrintEx() prints the parameters I expect and the second one returns 0xC0000018 like previously stated.

IIRC, Windows memory-protection functions work on per-region basis, rather than per-page one. Therefore, judging from the error that you get, the very first thought that gets into my head is that you are trying to change the protection of some particular page(s) in a region, which conflicts with with the protection of other pages in the given range.

In general, changing page protection in a random process from a driver does not really seem to be a great idea in itself. Taking into consideration that you are trying to do it by means of calling undocumented functions…well, I would not get too surprised to see a “funny” reaction from the usual suspects…

Anton Bassov