Wrote a simple Dll injector for "calculator.exe" process, with printing out some lines I confirmed that the injector did its job but the messagebox doesn't appear.
Context:
-void inject_dll(DWORD, char*) takes the ID of the process that I want to inject and the name of the dll it will be injecting.
-DWORD get_PId(const w_char_t*) is a function that returns the processID of the given argument (processname)
I have confirmed that the get_PId function works properly, so the error should be somewhere else.
Injector code:
#include "stdafx.h"
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>
void inject_dll(DWORD PId, char* DllName)
{
HANDLE hProcess;
PVOID Alloc;
SIZE_T DllPathLen;
HMODULE Kernel32Base;
PVOID LoadLibAddress;
if (PId != 0 && DllName != NULL)
{
DllPathLen = strlen(DllName);
Kernel32Base = GetModuleHandleA("Kernel32.dll");
if (Kernel32Base == NULL)
{
std::cout << "kernel32.dll not found" << std::endl;
return;
}
LoadLibAddress = GetProcAddress(Kernel32Base, "LoadLibraryA");
if (LoadLibAddress == NULL)
{
std::cout << "LoadLibraryA not found" << std::endl;
return;
}
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PId);
if (hProcess == NULL)
{
std::cout << "hProcess handle not opened" << std::endl;
return;
}
Alloc = VirtualAllocEx(hProcess, NULL, DllPathLen + 1, MEM_COMMIT, PAGE_READWRITE);
if (Alloc == NULL)
{
std::cout << "no memory allocated for DllPath" << std::endl;
return;
}
if (!WriteProcessMemory(hProcess, Alloc, DllName, DllPathLen + 1, NULL))
{
std::cout << "didn't write dll to processmemory" << std::endl;
return;
}
CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)LoadLibAddress, Alloc, 0, NULL);
std::cout << "end reached" << std::endl;
}
}
DWORD get_PId( const wchar_t* ProcessName) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (hSnapshot != NULL)
{
if (Process32First(hSnapshot, &pe32)) {
do
{
if (!wcscmp(pe32.szExeFile, ProcessName))
return pe32.th32ProcessID;
} while (Process32Next(hSnapshot, &pe32));
}
}
return 0;
}
int main(int argc, char* argv[])
{
DWORD pid = get_PId(L"Calculator.exe");
std::cout << pid << std::endl;
if (pid) {
char dllName[] = "CORRECT PATH (dont worry about this)";
std::cout << dllName << std::endl;
inject_dll(pid, dllName);
}
ExitPoint:
system("Pause");
return 0;
}
The Dll code, when its in the memory of the injected process it should show a messagebox:
#include <windows.h>
VOID ShowMessageBox() {
MessageBoxA(NULL, "injected", "injector", MB_OK);
}
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ){
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
ShowMessageBox();
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}