#include <windows.h> #pragma comment(lib, "Advapi32.lib") #pragma comment(lib, "User32.lib") #define PATHNAME_LENGTH 256 void EnableDebugPriv() { HANDLE hToken; // 进程访问令牌的句柄 LUID luid; // 用于存储调试权对应的局local unique identifier TOKEN_PRIVILEGES tkp; // 要设置的权限 OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); // 获取访问令牌 LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid); // 获得调试权的luid tkp.PrivilegeCount = 1; // 设置调试权 tkp.Privileges[0].Luid = luid; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof tkp, NULL, NULL); // 使进程拥有调试权 CloseHandle(hToken); } int main(int argc, TCHAR* argv[], TCHAR* envp[]) { HWND hWnd = FindWindow(NULL, L"InjectDst"); // 查找目标进程 DWORD pid; // GetWindowThreadProcessId(hWnd, &pid); // EnableDebugPriv(); // 获得进程的调试权 HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); // 打开进程 char szLibName[PATHNAME_LENGTH] = "E://InjectedDll.dll"; // 要注入的dll void* pLibNameRemote = VirtualAllocEx(hProcess, NULL, PATHNAME_LENGTH, MEM_COMMIT, PAGE_READWRITE); // 在目标进程的地址空间分配内存 WriteProcessMemory(hProcess, pLibNameRemote, szLibName, PATHNAME_LENGTH, NULL); // 写入dll路径 HMODULE hKernel32 = GetModuleHandle(L"Kernel32"); // 获得kernel32.dll的句柄 FARPROC fp = GetProcAddress(hKernel32, "LoadLibraryA"); // 获得loadibrary的便宜地址 HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, // 启动远程线程 (LPTHREAD_START_ROUTINE)fp, // --要注入的代码写在dll的DllMain里 pLibNameRemote, 0, NULL); // WaitForSingleObject(hThread, INFINITE); // 等待线程结束,也就是dllmain结束 DWORD hLibModule; GetExitCodeThread(hThread, &hLibModule); // 返回注入的dll的句柄 CloseHandle(hThread); VirtualFreeEx(hProcess, pLibNameRemote, PATHNAME_LENGTH, MEM_RELEASE); hThread = CreateRemoteThread(hProcess, NULL, 0, // 释放注入的dll (LPTHREAD_START_ROUTINE)::GetProcAddress(hKernel32, "FreeLibrary"), (void*)hLibModule, 0, NULL ); WaitForSingleObject( hThread, INFINITE ); CloseHandle(hThread ); CloseHandle(hProcess); return 0; }
1.在调试的时候我们的进程本来就具有调试权。但是当程序独立运行时,就一定要手动获得调试权。