- #include <stdio.h>
- #include <tchar.h>
- #include <windows.h>
- #include <atlbase.h>
- BOOL EnableDebugPriv(LPCTSTR name)
- {
- HANDLE h;
- TOKEN_PRIVILEGES tp;
- LUID id;
- // 打开进程令牌环
- if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &h))
- return FALSE;
- // 获得进程本地唯一ID
- if (!LookupPrivilegeValue(NULL, name, &id))
- return FALSE;
- tp.PrivilegeCount = 1;
- tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
- tp.Privileges[0].Luid = id;
- // 调整权限
- if (!AdjustTokenPrivileges(h, 0, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
- return FALSE;
- return TRUE;
- }
- BOOL InjectDll(LPCTSTR dll_full_path, DWORD remote_process_id)
- {
- HANDLE h;
- if (!EnableDebugPriv(SE_DEBUG_NAME))
- return FALSE;
- // 打开远程线程.
- h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, remote_process_id);
- if (!h)
- return FALSE;
- DWORD size = _tcsclen(dll_full_path) + 1;
- // 使用VirtualAllocEx函数在远程进程的内存地址空间分配DLL文件名空间
- LPVOID r = VirtualAllocEx(h, NULL, size, MEM_COMMIT, PAGE_READWRITE);
- if (!r)
- return FALSE;
- // 使用WriteProcessMemory函数将DLL的路径名写入到远程进程的内存空间
- if (!WriteProcessMemory(h, r, (void *)dll_full_path, size, NULL))
- return FALSE;
- // 计算LoadLibraryA的入口地址
- PTHREAD_START_ROUTINE start =
- (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "LoadLibraryA");
- if (!start)
- return FALSE;
- // (关于GetModuleHandle函数和GetProcAddress函数)
- // 启动远程线程LoadLibraryA,通过远程线程调用创建新的线程.
- DWORD tid;
- HANDLE t = CreateRemoteThread(h, NULL, 0, start, r, 0, &tid);
- if(!t)
- return FALSE;
- WaitForSingleObject(t, INFINITE);
- // 释放资源和句柄
- VirtualFreeEx(h, r, size, MEM_DECOMMIT);
- CloseHandle(t);
- CloseHandle(h);
- return TRUE;
- }
- int main(int argc, char **argv)
- {
- if (argc < 3)
- {
- printf("usage: InjectDll.exe <dll_path> <process_id>\\n");
- return -1;
- }
- TCHAR dll[MAX_PATH];
- int id = atoi(argv[2]);
- USES_CONVERSION;
- _tcscpy(dll, A2T(argv[1]));
- if (!InjectDll(dll, id))
- {
- printf("inject dll failed!\\n");
- return -1;
- }
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/230920136085.html
来源: http://www.codesnippet.cn/detail/230920136085.html