Injection.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "StdAfx.h"
  2. #include "Injection.h"
  3. CInjection::CInjection(DWORD dwPid, LPCTSTR lpDynamicLibraryPath)
  4. :m_dwInjectionPID(dwPid),
  5. m_hInjectionProcess(NULL),
  6. m_lpPathData(NULL),
  7. m_hInjectThread(NULL),
  8. m_hUnInjectThread(NULL),
  9. m_dwPathLen(0)
  10. {
  11. ASSERT(dwPid!=0);
  12. ASSERT(lpDynamicLibraryPath!=NULL);
  13. memset(m_szDllPath, 0, sizeof(m_szDllPath));
  14. _tcscpy_s(m_szDllPath,lpDynamicLibraryPath);
  15. m_hInjectionProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, m_dwInjectionPID);
  16. }
  17. CInjection::~CInjection(void)
  18. {
  19. FreeInjection();
  20. }
  21. int CInjection::ProcessInjection()
  22. {
  23. ASSERT(m_hInjectionProcess!=NULL);
  24. m_dwPathLen = _tcslen(m_szDllPath)*sizeof(TCHAR);
  25. m_lpPathData = VirtualAllocEx(m_hInjectionProcess,NULL, m_dwPathLen, MEM_COMMIT, PAGE_READWRITE);
  26. if (NULL == m_lpPathData)
  27. return -1;
  28. if (WriteProcessMemory(m_hInjectionProcess, m_lpPathData, m_szDllPath, m_dwPathLen, NULL) == 0)
  29. {
  30. VirtualFreeEx(m_hInjectionProcess, m_lpPathData, m_dwPathLen, MEM_DECOMMIT);
  31. return -1;
  32. }
  33. HMODULE hk32 = GetModuleHandle(_T("kernel32.dll"));
  34. // 注意:微信使用的是W版本;
  35. LPVOID lpAddr = GetProcAddress(hk32,"LoadLibraryW");
  36. m_hInjectThread = CreateRemoteThread(m_hInjectionProcess, NULL, 0, (LPTHREAD_START_ROUTINE)lpAddr, m_lpPathData, 0, NULL);
  37. if (NULL == m_hInjectThread)
  38. return -1;
  39. return 0;
  40. }
  41. int CInjection::FreeInjection()
  42. {
  43. ASSERT(m_hInjectionProcess!=NULL);
  44. TString str = m_szDllPath;
  45. int nIndex = str.find_last_of(_T('\\'));
  46. if (nIndex != TString::npos)
  47. str = str.substr(nIndex+1);
  48. MODULEENTRY32 me32 = FindModule(str.c_str(), m_dwInjectionPID);
  49. if (me32.hModule == NULL )
  50. {
  51. MessageBox(NULL, _T("xxxxx"), _T("dfdf"), MB_OK);
  52. return -1;
  53. }
  54. LPVOID lpAddr = GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "FreeLibrary");//FreeLibraryAndExitThread//FreeLibrary
  55. m_hUnInjectThread = CreateRemoteThread(m_hInjectionProcess, NULL, 0, (LPTHREAD_START_ROUTINE)lpAddr, me32.hModule, 0, NULL);
  56. WaitForSingleObject(m_hUnInjectThread, INFINITE);
  57. // 释放所有资源;
  58. if (m_hInjectThread)
  59. CloseHandle(m_hInjectThread);
  60. if (m_hUnInjectThread)
  61. CloseHandle(m_hUnInjectThread);
  62. if (m_lpPathData)
  63. VirtualFreeEx(m_hInjectionProcess, m_lpPathData, m_dwPathLen, MEM_DECOMMIT);
  64. if (m_hInjectionProcess)
  65. CloseHandle(m_hInjectionProcess);
  66. return 0;
  67. }
  68. void CInjection::InjectionExistProcess()
  69. {
  70. // 查找现在的进程;
  71. vector<DWORD> vtPID = FindAllProcess(WECHAT);
  72. }