Skip to content

Instantly share code, notes, and snippets.

@vallahor
Last active January 12, 2024 19:04
Show Gist options
  • Save vallahor/d2c071ca5366cabd49bb2e160631aecd to your computer and use it in GitHub Desktop.
Save vallahor/d2c071ca5366cabd49bb2e160631aecd to your computer and use it in GitHub Desktop.
Simple dll injector using CreateRemoteThread
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
DWORD GetPid(const char* processName) {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
printf("Snapshot error: %lu\n", GetLastError());
return 0;
}
DWORD pid = 0;
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
Process32First(snapshot, &pe);
do {
if (!strcmp(processName, pe.szExeFile)) {
pid = pe.th32ProcessID;
break;
}
} while (Process32Next(snapshot, &pe));
CloseHandle(snapshot);
return pid;
}
int main(void) {
const char* dll_path = "";
DWORD pid = GetPid("notepad.exe");
HANDLE process = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_CREATE_THREAD, FALSE, pid);
if (!process) {
printf("Error while opening process: %lu\n", GetLastError());
return EXIT_FAILURE;
}
// 1 << 12 is a full page because it'll ends up allocation that any way.
LPVOID path = VirtualAllocEx(process, NULL, 1 << 12, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!path) {
printf("Error while allocating memory: %lu\n", GetLastError());
return EXIT_FAILURE;
}
size_t len = strlen(dll_path) + 1;
WriteProcessMemory(process, path, dll_path, len, NULL);
HMODULE kernel32 = GetModuleHandle("kernel32");
HANDLE thread = CreateRemoteThread(process, NULL, 0,
(LPTHREAD_START_ROUTINE)GetProcAddress(kernel32, "LoadLibraryA"), path, 0, NULL);
if (!thread) {
printf("Error creating thread: %lu\n", GetLastError());
return EXIT_FAILURE;
}
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);
CloseHandle(process);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment