Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UNHOOK_WITH_INHOUSE_NTPROTECTVIRTUALMEMORY_TRAMPOLINE assumes patch starts at function start #29

Open
rafaelscheel opened this issue Jun 23, 2024 · 1 comment

Comments

@rafaelscheel
Copy link
Contributor

rafaelscheel commented Jun 23, 2024

In the function getSafeVirtualProtectUsingTrampoline, the method UNHOOK_WITH_INHOUSE_NTPROTECTVIRTUALMEMORY_TRAMPOLINE creates the trampoline from function start to (function start + patchsize). This does not work, if the patch does not start at the beginning of the function. In my opinion, instead of using patchSize, "sizeFromFunctionStart" should be used. E.g. like this:

size_t sizeFromFunctionStart = (size_t)patchAddr - (size_t)mem_NtProtectVirtualMemory + patchSize;
PBYTE trampoline = VirtualAlloc(NULL, sizeFromFunctionStart + JUMP_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (NULL == trampoline) {
	debugf("\tError : VirtualAlloc: 0x%x\n\n", GetLastError());
	exit(1);
}
DWORD oldProtect;
memcpy(trampoline, disk_NtProtectVirtualMemory, sizeFromFunctionStart);
#if _WIN64
* ((WORD*)(trampoline + sizeFromFunctionStart)) = 0x25FF; //RIP relative jmp
*((DWORD*)(trampoline + sizeFromFunctionStart + 2)) = 0x0; // [RIP + 0]
*((QWORD*)(trampoline + sizeFromFunctionStart + 2 + 4)) = (QWORD)(((BYTE*)mem_NtProtectVirtualMemory) + sizeFromFunctionStart);
#else
* (trampoline + sizeFromFunctionStart) = 0xE9; //far JMP
*((DWORD*)(trampoline + sizeFromFunctionStart + 1)) = (DWORD)(((DWORD)mem_NtProtectVirtualMemory) + sizeFromFunctionStart - (((DWORD)trampoline) + sizeFromFunctionStart + JUMP_SIZE));
#endif
VirtualProtect(trampoline, sizeFromFunctionStart + JUMP_SIZE, PAGE_EXECUTE_READ, &oldProtect);

Did I missunderstand something? If not I will gladlay create a pull request.

Thanks!

@themaks
Copy link
Collaborator

themaks commented Aug 30, 2024

Hello Rafael,
This is correct, a wrong assumption that patchAddr==mem_NtProtectVirtualMemory was made, my bad.
At first read, your approach seems sound and your code correct; have you something to test the code against? I do not really have access to EDRs anymore 😁

Thank you for your contribution !

PS: I should have commented the code 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants