DLL injection has been used for both good and evil for quite some time. Everywhere you look you will see DLL injection occurring. From fancy Windows shell extensions that give you a glittering pony for a mouse cursor to a piece of malware stealing your banking information, DLL injection is everywhere. Even security products inject DLLs to monitor processes for malicious behavior. The nice thing about DLL injection is that we can write a compiled binary, load it into a process, and have it execute as part of the process. This is extremely useful, for instance, to evade software firewalls that let only certain applications make outbound connections. We are going to explore this a bit by writing a Python DLL injector that will enable us to pop a DLL into any process we choose.
In order for a Windows process to load DLLs into memory, the DLLs must use the LoadLibrary() function that's exported from kernel32.dll. Let's take a quick look at the function prototype:
HMODULE LoadLibrary( LPCTSTR lpFileName
The lpFileName parameter is simply the path to the DLL you wish to load. We need to get the remote process to call LoadLibraryA with a pointer to a string value that is the path to the DLL we wish to load. The first step is to resolve the address where LoadLibraryA lives and then write out the name of the DLL we wish to load. When we call CreateRemoteThread(), we will point lpStartAddress to the address where LoadLibraryA is, and we will set lpParameter to point to the DLL path that we have stored. When CreateRemoteThread() fires, it will call LoadLibraryA as if the remote process had made the request to load the DLL itself.
NOTE The DLL to test injection for is in the source folder for this book, which you can download at http://www.nostarch.com/ghpython.htm. The source for the DLL is also in the main directory.
Let's get down to the code. Open a new Python file, name it dll_injector.py, and hammer out the following code.
Was this article helpful?