Greetings, my code for injecting a dll seems to fail. My injector sometimes just doesn't find notepad++.exe. And when it does it injects, but then Notepad++ crashes. I also tried it with notepad.exe but Notepad doesn't crash OR show the messagebox.
First I tried to add a button to the menu as showed on another site, then I tried to just show a messagebox, both of them caused the results as I stated before.
Here is my injector code:
main.cpp
Code:
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
int GetProcessIdByName(char * procName);
int main()
{
char dllName[] = "NotepadHack.dll";
printf("DLL Injector\n");
printf("____________\n");
printf("\n");
printf("Openening process notepad++.exe...\n");
HANDLE hProcess = NULL;
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetProcessIdByName("notepad++.exe"));
if(hProcess == NULL)
{
printf("Process could not be opened.\n");
getchar();
return 1;
}
printf("Process opened successfully.\n");
getchar();
printf("Injecting DLL...\n");
LPVOID pLibAddress = GetProcAddress(GetModuleHandle("Kernel32.dll"), "LoadLibraryA");
LPVOID pDllAddress = VirtualAllocEx(hProcess, NULL, sizeof(dllName), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProcess, pDllAddress, dllName, sizeof(dllName), NULL);
CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)&pLibAddress, pDllAddress, 0, NULL);
printf("DLL injected successfully.\n");
printf("Closing process handle...\n");
CloseHandle(hProcess);
getchar();
return 0;
}
int GetProcessIdByName(char * procName)
{
PROCESSENTRY32 entry;
int procID = -1;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(Process32First(hSnapshot, &entry) == TRUE)
{
do
{
if(stricmp(entry.szExeFile, procName) == 0)
{
procID = entry.th32ProcessID;
}
}while(Process32Next(hSnapshot, &entry) == TRUE);
}
CloseHandle(hSnapshot);
return procID;
}
Here my DLL: (I commented out the CreateThread to test whether I could just get the MessageBox working.)
main.cpp
Code:
#include <windows.h>
HWND hWindow = NULL;
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
hWindow = hWnd;
return TRUE;
}
DWORD WINAPI StopProcess()
{
MessageBox(NULL, "This should appear", "NotepadHack", 0);
EnumWindows((WNDENUMPROC)EnumWindowsProc, NULL);
if(hWindow == NULL)
{
MessageBox(NULL, "The window was not found.", "NotepadHack", 0);
return FALSE;
}
HMENU hCurrentMenu = GetMenu(hWindow);
HMENU hNewMenu = CreateMenu();
AppendMenu(hCurrentMenu, MF_STRING | MF_POPUP, (unsigned int)hNewMenu, "NotepadHack");
AppendMenu(hNewMenu, MF_STRING, 2000, "Button");
DrawMenuBar(hWindow);
return TRUE;
}
BOOL WINAPI DllMain(HINSTANCE hModule,
DWORD fdwReason,
LPVOID lpReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
{
//CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)&StopProcess, NULL, 0, NULL);
MessageBox(NULL, "Hello World!", "Hack", 0);
}break;
}
return TRUE;
}
I'm using Windows 7 and I run the injector as Administrator.