stevemk14ebr / PolyHook_2_0

C++20, x86/x64 Hooking Libary v2.0
MIT License
1.6k stars 226 forks source link

Crash caused by unsafe read #188

Closed enginelesscc closed 1 year ago

enginelesscc commented 1 year ago

Here it just blindly dereferences an arbitrary pointer assuming its valid, causing a crash on invalid ptr

https://github.com/stevemk14ebr/PolyHook_2_0/blob/245a9c06fc24865e46b6bee388c58d3bf02c289c/polyhook2/Instruction.hpp#L71 https://github.com/stevemk14ebr/PolyHook_2_0/blob/245a9c06fc24865e46b6bee388c58d3bf02c289c/polyhook2/Instruction.hpp#L73

repro:

push ebp                      // <-- hook here
push ebp, esp
sub esp, 0xC
call dword ptr [80000000]     // --> will crash here during disassembly due to *(uint32_t*)0x80000000
...

backtrace:

!PLH::ZydisDisassembler::addToBranchMap::__l5::<lambda>(const PLH::Instruction &)
!std::find_if(std::_Vector_iterator<std::_Vector_val<std::_Simple_types<PLH::Instruction>>>)
!PLH::ZydisDisassembler::addToBranchMap(std::vector<PLH::Instruction,std::allocator<PLH::Instruction>> &)
!PLH::ZydisDisassembler::disassemble(unsigned __int64 firstInstruction, unsigned __int64 start, unsigned __int64 end, const PLH::MemAccessor & accessor)
!PLH::x86Detour::hook()
stevemk14ebr commented 1 year ago

If that call is invalid then the process itself would crash on execution anyways?

Can you please inform me of situations where code like this exists and why we should guard against it?

enginelesscc commented 1 year ago

For a 32bit process its quite likely someone chooses to use absolute addressing and lazy-map some pages on fault. In my case polyhook is used before the actual process has executed the entrypoint so none of that is ready there.

But either way polyhook already provides a return value on failure and I'd certainly prefer if it did so in such cases. (Here it could keep that call as-is and just copy it without trying to deref its ptr..) .. otherwise i'll have to use SEH around polyhook calls as alternative.

stevemk14ebr commented 1 year ago

I wouldn't say that's so common unless your maybe hooking a jit but I see your point. The fix is easy enough, we have safe memory read apis in the library, I'll just switch to those

stevemk14ebr commented 1 year ago

resolved with https://github.com/stevemk14ebr/PolyHook_2_0/commit/71553ebf0d197e73c49365cc3ab2a6aa326b3c37