GetModuleHandle(), for a DLL in another process

user1591117 picture user1591117 · Oct 16, 2014 · Viewed 11.7k times · Source

The title explains this all really, I have a process tapping into another process. I need to be able to GetModuleHandle, on this program for a certain DLL which isn't Windows standard, and I don't have the source code to the main program.

I need to use it to call an exported function with GetProcAddress and in the end use it in CreateRemoteThread to remotely start a task on that program.

Is there anyway I can get a ModuleHandle from another program, instead of the local program it is creating the remote thread with?

Thanks.

Answer

Smith_61 picture Smith_61 · Oct 16, 2014

I see three possible solutions to this. As far as I know, there is no windows API that allows you to get a function address for a module in another process.


Solution 1:

The easiest solution, IMO, is to inject a DLL into the target process and retrieve all the needed information from within the target process itself. There are many different ways to get your DLL into the target process, my favorite is Reflective DLL Injection.


Solution 2:

Solution 2 uses EnumProcessModules ( Usage ) to fetch HMODULE references from another process. You can not use these in calls to GetProcAddress directly. The way around this is to load the DLL into your process using LoadLibraryEx( "MODULE_NAME", NULL, DONT_RESOLVE_DLL_REFERENCES ). This, on successful module load, will provide you with an HMODULE instance that you can pass to GetProcAddress.

The address returned from GetProcAddress is only valid for your address space, but luckily it is also relative to the module base. By subtracting your HMODULE reference from the address and then adding it to the HMODULE reference in the target process, you will get the address of the function in the target process.

Ex: targetProc = myProc - myModule + targetModule; where myProc is a char * and myModule and targetModule are HMODULE.


Solution 3:

Solution 3 is the hardest IMO to implement. This solution requires you to read the target's process memory to locate the required modules, and then parse the modules to find the function addresses.

Resources for this solution can be found here and here.


I haven't personally tested either solution 2 or 3, but in theory they should work. I have used solution 1 personally, and would recommend that as the way to achieve this. The other two solutions require a lot of boilerplate code to emulate existing Windows API methods.