# 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:
* DLLs listed in the registry entry HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs are loaded into every process that loads User32.dll during the initial call of that DLL. Beginning with Windows Vista, AppInit_DLLs are disabled by default. Beginning with Windows 7, the AppInit_DLL infrastructure supports code signing. Starting with Windows 8, the entire AppInit_DLL functionality is disabled when Secure Boot is enabled, regardless of code signing or registry settings.
* DLLs listed under the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\AppCertDLLs are loaded into every process that calls the Win32 API functions CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, CreateProcessWithTokenW and WinExec. That is the right way to use legal DLL injection on current version of Windows - Windows 10. DLL must be signed by a valid certificate.
* Process manipulation functions such as CreateRemoteThread or code injection techniques such as AtomBombing, can be used to inject a DLL into a program after it has started.
** Open a handle to the target process. This can be done by spawning the process or by keying off something created by that process that is known to exist – for instance, a window with a predictable title, or by obtaining a list of running processes and scanning for the target executable's filename.
** Allocate some memory in the target process, and the name of the DLL to be injected is written to it.
    This step can be skipped if a suitable DLL name is already available in the target process. For example, if a process links to User32.dll, GDI32.dll, Kernel32.dll or any other library whose name ends in 32.dll, it would be possible to load a library named 32.dll. This technique has in the past been demonstrated to be effective against a method of guarding processes against DLL injection.
** Create a new thread in the target process with the thread's start address set to be the address of LoadLibrary and the argument set to the address of the string just uploaded into the target.
    Instead of writing the name of a DLL-to-load to the target and starting the new thread at LoadLibrary, one can write the code-to-be-executed to the target and start the thread at that code.
** The operating system then calls the initialization routine of the injected DLL.
    Note that without precautions, this approach can be detected by the target process due to the DLL_THREAD_ATTACH notifications sent to every loaded module as a thread starts.
* Windows hooking calls such as SetWindowsHookEx.
* Use the SuspendThread or NtSuspendThread function to suspend all threads, and then use SetThreadContext or NtSetContextThread function to modify an existing thread's context in the application to execute injected code, that in turn could load a DLL.
* Exploit design limitations in Windows and applications that call the LoadLibrary or LoadLibraryEx function without specifying a full-qualified path to the DLL being loaded.
* Operating system-level shims.
* Substituting an application-specific DLL with a rogue replacement that implements the same function exports as the original.

## Approaches on Unix-like systems

On Unix-like operating systems with the dynamic linker based on ld.so (on BSD) and ld-linux.so (on Linux), 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, on a Linux system, this command launches the command "prog" with the shared library from file "test.so" linked into it at the launchtime:
Such a library can be created in the same way as other shared objects. With GCC, this involves 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:
It is also possible to use debugger-based techniques on Unix-like systems.

## Sample code
### Copying a LoadLibrary-loaded DLL to a remote process

As there is no LoadLibrary call to load a DLL into a foreign process you have to copy a locally loaded DLL into remotely allocated memory. The following commented code shows how to do that.
The main issue solved here is that a locally loaded DLL copied to a remote process must occupy the same addresses as in the injecting process. The above code does this by allocating memory for the same address range as occupied before in the injecting process. If this fails the DLL is locally freed, the former address range is marked as reserved, and the LoadLibrary call is tried again. By reserving the former address range the code prevents that the next LoadLibrary attempt will assign the same address range as used before.
The main drawback with that approach is that the DLL copied into the foreign process is that there aren't any other DLL library dependencies of that DLL loaded into the foreign address space or pointers, f.e. function calls, to DLLs loaded by the foreign process are adjusted according to the dependencies of the copied DLL. Luckily DLLs usually have preferred loading addresses which are honored by the kernel's loader. Some DLLs like kernel32.dll are reliably loaded in the early beginning when the process address space is occupied by the executable image and its depending DLLs. These normally have reliable and non-conflicting addresses. So the copied DLL can use any kernel32.dll calls, f.e. to load another DLL with full advantages of a locally loaded DLL, i.e. having all relative library-dependencies. The path to that DLL is copied to the foreign address space and given as a void-parameter to the thread-function. The above implementation also allows to have additional parameters, which are passed to the remotely copied DLL after the string with the DLL to remotely loaded to passed to that DLL.
The following code is the source of the remotely copied loader DLL which only does kernel32.dll calls:
The last code shows an example of a DLL loaded by the loader DLL which prints the parameters to a file.
One important fact is that there are no exports called from the loader DLL, but instead all initialization is done from DllMain. The only export is that of initData, which receives the parameters given by the injecting process through the loader DLL. And one must be aware that the thread created from a DllMain-function isn't scheduled until after its DLL_THREAD_ATTACH-function has succeeded. So there may not be any synchronization from inside DllMain with the created thread.