CreateRemoteThread on LoadLibrary and get the HMODULE back

萝らか妹 提交于 2019-12-01 08:51:42

You could assume that the code as shown is likely to work and that the truncated HMODULE is likely to actually be fine most of the time as modules are usually loaded low enough in the process address space that it doesn't matter. To ensure that the code always works though you could follow your 'broken' example code with a call to EnumProcessModules() function. If the returned HMODULE appears in the list of process modules for the target process then you're good to go. If not, you need to iterate the returned HMODULEs and call GetModuleBaseName() or GetModuleFileNameEx() until you locate your injected DLL.

Alternatively, if you're already running as a custom debugger (which I find useful when I want to inject anyway), then you can match the module that's loaded when you inject up to the corresponding LOAD_DLL_DEBUG_EVENT that will be reported by WaitForDebugEvent(). This would give you the both the HMODULE (base of image) and image file name and the event would occur immediately after you injected your DLL.

Personally I'd take the later approach, but in practice I've yet to see the truncated HMODULE returned from the broken code to be anything but correct, but I expect I've just been lucky and am relying on the loader to load DLLs low in the process's address space.

For 64bit process, I could use IPC (http://msdn.microsoft.com/en-us/library/windows/desktop/aa365574%28v=vs.85%29.aspx) to get the HMODULE back.

I should note that not every IPC mechanism could works in DLLMain, for example Pipe will cause dead-lock, refer to the document "Best Practices for Creating DLLs" (http://download.microsoft.com/download/a/f/7/af7777e5-7dcd-4800-8a0a-b18336565f5b/DLL_bestprac.doc) of Microsoft, call functions in kernel32.dll (except some specified functions) will be OK.

I have tested shared memory (on Windows XP with SP3 and Windows 7 64bit PRO), it works.

You can safely use the returned 32-bit handle as according to https://docs.microsoft.com/en-us/windows/desktop/WinProg64/interprocess-communication, 64 bit windows still use 32-bit handle.

64-bit versions of Windows use 32-bit handles for interoperability. When sharing a handle between 32-bit and 64-bit applications, only the lower 32 bits are significant, so it is safe to truncate the handle (when passing it from 64-bit to 32-bit) or sign-extend the handle (when passing it from 32-bit to 64-bit). Handles that can be shared include handles to user objects such as windows (HWND), handles to GDI objects such as pens and brushes (HBRUSH and HPEN), and handles to named objects such as mutexes, semaphores, and file handles.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!