远程线程注入代码

                                                              远程线程注入代码 

       远程线程注入可以实现向一个正在运行的进程注入特定的代码。每个进程都有自己的私有空间。远程线程注入可以实现向一个正在运行的进程注入代码。通过进程名找到进程ID,在远程进程开辟空间,启动一个线程,执行一个DLL中的函数,通过得到kernel32中LoadLibrary函数地址,通过执行LoadLibrary载入DLL中的导出函数,执行我们自己定一的代码。实现如下:

//通过进程名得到进程ID

DWORD GetProcessIdFromName(LPCTSTR name)
{
 PROCESSENTRY32 pe;
 DWORD id = 0;
 
 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
 pe.dwSize = sizeof(PROCESSENTRY32);
 if( !Process32First(hSnapshot,&pe) )
  return 0;
 
 do
 {
  pe.dwSize = sizeof(PROCESSENTRY32);
  if( Process32Next(hSnapshot,&pe)==FALSE )
   break;
  if(strcmp(pe.szExeFile,name) == 0)
  {
   id = pe.th32ProcessID;
   break;
  }
  
 } while(1);
 
 CloseHandle(hSnapshot);
 
 return id;
}

//注入代码

void CMTestDlg::OnButton1()
{
 // TODO: Add your control notification handler code here
 DWORD dwRemoteProcessId=GetProcessIdFromName("notepad.exe");
 CString str;
 str.Format("%u",dwRemoteProcessId);
 AfxMessageBox(str,MB_OK);
 HANDLE hRemoteProcess=OpenProcess(PROCESS_CREATE_THREAD|PROCESS_VM_OPERATION|PROCESS_VM_WRITE,FALSE,dwRemoteProcessId);
 WCHAR* pszLibFileName=L"MDll.dll";
 int cb=(1+lstrlenW(pszLibFileName))*sizeof(WCHAR);
 LPVOID pszLibFileRemote=(PWSTR)VirtualAllocEx(hRemoteProcess,NULL,cb,MEM_COMMIT,PAGE_READWRITE);
 BOOL iReturnCode=WriteProcessMemory(hRemoteProcess,pszLibFileRemote,(PVOID)pszLibFileName,cb,NULL);
 //HMODULE hModule=GetModuleHandle(TEXT("kernel32"));
 HMODULE hModule=LoadLibrary("C:/WINDOWS/system32/kernel32");
 //typedef HModule (* pfunc)(LPCSTR filename);
 PTHREAD_START_ROUTINE pfnStartAddr=(PTHREAD_START_ROUTINE)GetProcAddress(hModule,"LoadLibraryA");

 //格式化出错信息
 TCHAR szBuf[80];
    LPVOID lpMsgBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    wsprintf(szBuf,
        " failed with error %d: %s",
        dw, lpMsgBuf);
 
    AfxMessageBox(szBuf,MB_OK);

    LocalFree(lpMsgBuf);

 

 HANDLE hRemoteThread=CreateRemoteThread(hRemoteProcess,NULL,0,pfnStartAddr,pszLibFileRemote,0,NULL);

  //等待远程线程退出    
  WaitForSingleObject(hRemoteThread,   INFINITE);    
  //清场处理    
  if   (pszLibFileRemote   !=   NULL)    
  VirtualFreeEx(hRemoteProcess,   pszLibFileRemote,   0,   MEM_RELEASE);    
  if   (hRemoteThread   !=   NULL)   CloseHandle(hRemoteThread   );    
  if   (hRemoteProcess!=   NULL)   CloseHandle(hRemoteProcess);       

}

你可能感兴趣的:(thread,c,null,System,buffer,dll)