03 Injection DLL
03 Injection DLL
There are slight difference in writing C code for exe and DLL. The basic difference is how you call you
code in your module or program. In exe case there should be a function called main which is being
called by the OS loader when it finishes all in initialization if a new process. At this point your program
starts its execution when the OS loader finishes its job.
On the other hand with the DLL's when you want to run your program as a dynamic library, it's a slighty
different way, so the loader has already created process in memory and for some reason that process
needs your DLL or any other DLL to be load it into the process and it might be due to the function your
DLL implements.
/*
* evil.c
* simple DLL for DLL inject to process
* author: @cocomelonc
*/
#include <windows.h>
#pragma comment (lib, "user32.lib")
NULL,
"Hello, Prishtina!",
"=^..^=",
MB_OK
);
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
This is important in the context of DLL Injection, as we are looking for simplest way to execute code in
the context of other process. That is why most of malicious Dlls which are being injected have most of
the malicious code in DllMain. There are ways to force a process to run exported function, but writing
your code in DllMain is usually the simplest solution to get code execution.
When run in injected process it should display our message: Hello, Prishtina!, so we will know
that injection was successful. Now we can compile it (on attacker’s machine):
Now we only need a code which will inject this library into the process of our choosing.
In our case we are going talk about classic DLL injection. We allocate an empty buffer of a size at least
the length of the path of our DLL from disk. And then we copy the path to this buffer:
/*
PROFESSEUR : M.DA ROS BTS SIO BORDEAUX - LYCÉE GUSTAVE EIFFEL
✦2/8✦
* hack.c
* classic DLL injection example
* author: @cocomelonc
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <tlhelp32.h>
// parse process ID
if ( atoi(argv[1]) == 0) {
printf("PID not found :( exiting...\n");
return -1;
}
printf("PID: %i", atoi(argv[1]));
ph = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi(argv[1])));
It’s pretty simple as you can see. It's same as in my previous code injection example. The only difference
is we add path of our DLL from disk:
and before we finally inject and run our DLL - we need a memory address of LoadLibraryA -
https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya:
HMODULE LoadLibraryA(
[in] LPCSTR lpLibFileName
);
, as this will be an API call that we will execute in the context of the victim process to load our DLL:
.\hack.exe <PID>