I'm tried to invoke NtProtectVirtualMemory from my dll, that was attached to application using followed code:
typedef NTSTATUS(__stdcall* tNtProtectVirtualMemory) (HANDLE, IN OUT PVOID*, IN OUT PULONG, IN ULONG, OUT PULONG);
...
HMODULE Ntdll = GetModuleHandle("ntdll.dll");
if (!Ntdll) {
char outtxt[64];
sprintf(outtxt, "GetModuleHandle error %d", GetLastError());
MessageBox(NULL, outtxt, "error", MB_OK);
}
tNtProtectVirtualMemory OrigNtProtectVirtualMemory = (tNtProtectVirtualMemory)GetProcAddress(Ntdll, "NtProtectVirtualMemory");
if (!OrigNtProtectVirtualMemory) {
char outtxt[64];
sprintf(outtxt, "tNtProtectVirtualMemory is null (%d)", GetLastError());
MessageBox(NULL, outtxt, "error", MB_OK);
}
NTSTATUS sts = OrigNtProtectVirtualMemory(-1, sectionData->address, sectionData->size, protect, &oldProtect);
GetModuleHandle returns correct handle and GetProcAddress works fine. NtProtectVirtualMemory returns 0xC0000005 (STATUS_ACCESS_VIOLATION).
Now what's most interesting: VirtualProtect works without any errors:
VirtualProtect(sectionData->address, sectionData->size, protect, &oldProtect);
But I have to use exactly NtProtectVirtualMemory. Any ideas?