DLL injection


In computer programming, DLL injection is a technique used for running code within the address space of another process by forcing it to load a dynamic-link library. DLL injection is often used by external programs to influence the behavior of another program in a way its authors did not anticipate or intend. For example, the injected code could hook system function calls, or read the contents of password textboxes, which cannot be done the usual way. A program used to inject arbitrary code into arbitrary processes is called a DLL injector.

Approaches on Microsoft Windows

There are multiple ways on Microsoft Windows to force a process to load and execute code in a DLL that the authors did not intend:
On Unix-like operating systems with the dynamic linker based on ld.so and ld-linux.so, arbitrary libraries can be linked to a new process by giving the library's pathname in the LD PRELOAD environment variable, that can be set globally or individually for a single process.
For example, in Bash, this command launches the command "prog" with the shared library from file "test.so" linked into it at the launchtime:
LD_PRELOAD="./test.so" prog
Such a library can be created with GCC by compiling the source file containing the new globals to be linked, with the -fpic or -fPIC option, and linking with the -shared option. The library has access to external symbols declared in the program like any other library.
On macOS, the following command launches the command "prog" with the shared library from file "test.dylib" linked into it at the launchtime:
DYLD_INSERT_LIBRARIES="./test.dylib" DYLD_FORCE_FLAT_NAMESPACE=1 prog
It is also possible to use debugger-based techniques on Unix-like systems.

Sample Code

Using the LoadLibrary API function

The sample function below uses a method of DLL injection that exploits the fact that kernel32.dll is mapped to the same address in almost all processes. Therefore LoadLibrary is mapped to the same address as well. LoadLibrary also happens to fit the thread start routine required by CreateRemoteThread.

  1. include
HANDLE inject_DLL