...stuff I do and things I like...

Friday, March 06 2015

Load time DLL Injection via QueueUserAPC

This is hopefully my last post on DLL injection. See here Injecting a DLL into a process on load time with the ability to hook the process' entrypoint from the DLL for my initial goal and a follow up post.

After reading up on QueueUserAPC I implemented it for the use with pydbg (I use pydbg for other parts so it made sense to do this).

The trick of QueueUserAPC is that the function is called before the application's main thread is started. Basically what you have to do is:
dbg.load(exe_name)
injectdll_apc(dbg, dll_name)
dbg.run()

You can download the code for injecdll_apc() here: inject_dll_queueuserapc_pydbg.py.

Now I can finally continue working on my actual project!

DLL Injection followup

Yesterday I wrote about load time DLL injection and of course somebody (Jurriaan Bremer of cuckoo sandbox) pointed out that there is of course a pre existing tool. Specifically his inject tool that is part of cuckoo sandbox. The tool uses QueueUserAPC as the way to execute code within the process to call LoadLibrary.

updated: March 6th 2015
    I couldn't figure out what the exact difference is between QueueUserAPC and CreateRemoteThread in terms of when it is executed. The RemoteThread only executes while the program is running and if it is running it will execute code. I don't see the obvious difference for QueueUserAPC. I will read up on this but so far I will just continue with my actual project. For my project I need the guarantee that I can run my code first. That is why I went through all this hassle.

The important information from the QueueUserAPC documentation is:
    If an application queues an APC before the thread begins running, the thread begins by calling the APC function. After the thread calls an APC function, it calls the APC functions for all APCs in its APC queue.

This means: if you start the process in suspended mode and call QueueUserAPC before resuming the process the APC function will be called before the thread starts executing.