I am trying to create a DLL Injector that will directly execute functions within the DLL in the target process. I am trying to get the entry point of the DLL I injected so I can get the offset of the function. I read on the Microsoft Docs to use GetModuleInfo()
. I used the header psapi.h
and found that compilation worked, but it failed on linkage providing the following error:
g++ dll_injector.cpp -o dll_injector.exe
C:\Users\DELKAR~1\AppData\Local\Temp\ccOeKdhW.o:dll_injector.cpp:(.text+0x187): undefined reference to `GetModuleInformation@16'
C:\Users\DELKAR~1\AppData\Local\Temp\ccOeKdhW.o:dll_injector.cpp:(.text+0x1ae): undefined reference to `GetModuleInformation@16'
collect2.exe: error: ld returned 1 exit status
I have already tried putting Psapi.lib
in the same directory as dll_injector.cpp
and then compiling with
g++ dll_injector.cpp -o dll_injector.exe -Xlinker -L Psapi.lib
but it still threw the same error.
Here is the dll_injector.cpp
code:
#include <windows.h>
#include <iostream>
#include <psapi.h>
using namespace std;
int main() {
DWORD pid;
const char* dll_path = "C:\\Users\\Delkarix\\Desktop\\target_dll.dll";
HWND hwnd = FindWindow(NULL, "C:\\Users\\Delkarix\\Desktop\\target_process.exe");
GetWindowThreadProcessId(hwnd, &pid);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
LPVOID addr = VirtualAllocEx(hProcess, NULL, strlen(dll_path) + 1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProcess, addr, dll_path, strlen(dll_path) + 1, NULL);
CreateRemoteThread(hProcess, NULL, 0, LPTHREAD_START_ROUTINE(GetProcAddress(LoadLibrary("kernel32"), "LoadLibraryA")), addr, 0, NULL);
HMODULE lib = LoadLibrary("target_dll.dll");
FARPROC proc_addr = GetProcAddress(lib, "test_function");
MODULEINFO info;
MODULEINFO info_current;
BOOL success1 = GetModuleInformation(GetCurrentProcess(), lib, &info_current, sizeof(info_current));
BOOL success2 = GetModuleInformation(hProcess, lib, &info, sizeof(info));
cout << success1 << endl; // Test if it works
cout << success2 << endl; // Test if it works
}
Here is the target_dll.cpp
code:
#include <iostream>
using namespace std;
extern "C" __declspec(dllexport) void test_function() {
cout << "Hello World" << endl;
}
I expect dll_injector.exe
to print values that say if the functions succeed or not. I will change the code later so I will be able to get the entry point values. For now, I just want the functions to succeed without having to create a Visual Studio C++ Console Project. My question: Why is the linkage failing, and how can I get the linkage to succeed?
Change
g++ dll_injector.cpp -o dll_injector.exe -Xlinker -L Psapi.lib
to
g++ dll_injector.cpp -o dll_injector.exe -L. -lPsapi
-L(library path) - specify a lib directory. .
specify current path.
-l(library) - link with library. Psapi
specify the name of library.(Omit suffix name of .lib
in windows or prefix name lib
and suffix name .a
in linux)
Doc From Compiling with g++