Injecter.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //#include "stdafx.h"
  2. #include "Injecter.h"
  3. Injecter::Injecter()
  4. {
  5. }
  6. Injecter::~Injecter()
  7. {
  8. }
  9. BOOL Injecter::EnablePrivilege(BOOL enable)
  10. {
  11. // 得到令牌句柄
  12. HANDLE hToken = NULL;
  13. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_READ, &hToken))
  14. return FALSE;
  15. // 得到特权值
  16. LUID luid;
  17. if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid))
  18. return FALSE;
  19. // 提升令牌句柄权限
  20. TOKEN_PRIVILEGES tp = {};
  21. tp.PrivilegeCount = 1;
  22. tp.Privileges[0].Luid = luid;
  23. tp.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
  24. if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL))
  25. return FALSE;
  26. // 关闭令牌句柄
  27. CloseHandle(hToken);
  28. return TRUE;
  29. }
  30. long Injecter::InjectDll(DWORD pid, LPCTSTR dllPath, long& error_code)
  31. {
  32. auto jhandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  33. /**pid = processInfo.dwProcessId;
  34. *process = processInfo.hProcess;*/
  35. if (!jhandle) {
  36. error_code = ::GetLastError();
  37. return -1;
  38. }
  39. DWORD dllPathSize = ((DWORD)wcslen(dllPath) + 1) * sizeof(TCHAR);
  40. // 申请内存用来存放DLL路径
  41. void* remoteMemory = VirtualAllocEx(jhandle, NULL, dllPathSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  42. if (remoteMemory == NULL)
  43. {
  44. //setlog(L"申请内存失败,错误代码:%u\n", GetLastError());
  45. error_code = ::GetLastError();
  46. return -2;
  47. }
  48. // 写入DLL路径
  49. if (!WriteProcessMemory(jhandle, remoteMemory, dllPath, dllPathSize, NULL))
  50. {
  51. //setlog(L"写入内存失败,错误代码:%u\n", GetLastError());
  52. error_code = ::GetLastError();
  53. return -3;
  54. }
  55. // 创建远线程调用LoadLibrary
  56. auto lpfn = GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW");
  57. if (!lpfn) {
  58. error_code = ::GetLastError();
  59. return -4;
  60. }
  61. HANDLE remoteThread = CreateRemoteThread(jhandle, NULL, 0, (LPTHREAD_START_ROUTINE)lpfn, remoteMemory, 0, NULL);
  62. if (remoteThread == NULL)
  63. {
  64. //setlog(L"创建远线程失败,错误代码:%u\n", GetLastError());
  65. error_code = ::GetLastError();
  66. return -5;
  67. }
  68. // 等待远线程结束
  69. WaitForSingleObject(remoteThread, INFINITE);
  70. // 取DLL在目标进程的句柄
  71. DWORD remoteModule;
  72. GetExitCodeThread(remoteThread, &remoteModule);
  73. // 恢复线程
  74. //ResumeThread(processInfo.hThread);
  75. // 释放
  76. CloseHandle(remoteThread);
  77. VirtualFreeEx(jhandle, remoteMemory, dllPathSize, MEM_DECOMMIT);
  78. CloseHandle(jhandle);
  79. error_code = 0;
  80. return 1;
  81. }