进程注入方法之 CreateRemoteThread

来源:互联网 发布:北京知产法院电话 编辑:程序博客网 时间:2024/05/23 22:22

function TForm1.InjectDll(ThreadId: DWORD; DllFilename: string): Boolean;
var
  hProcess ,hThread :THandle;
  pszLibFileRemote:PChar;
  dwMemLen:DWORD;
  dwWrited:DWORD;
  pfnThreadRtn:Pointer;
  dwThreadId:DWORD;
begin
   Result:= FALSE; // Assume that the function fails
   hProcess :=0;
   hThread :=0;

 

   try
      // Get a handle for the target process.
      hProcess := OpenProcess(
         PROCESS_QUERY_INFORMATION or   // Required by Alpha
         PROCESS_CREATE_THREAD     or   // For CreateRemoteThread
         PROCESS_VM_OPERATION      or   // For VirtualAllocEx/VirtualFreeEx
         PROCESS_VM_WRITE,             // For WriteProcessMemory
         FALSE, ThreadId);
      if (hProcess =0)   then
        Exit;

      dwMemLen  :=1 + Length(DllFilename);
      // Allocate space in the remote process for the pathname
      pszLibFileRemote := VirtualAllocEx(hProcess, nil, dwMemLen , MEM_COMMIT, PAGE_READWRITE);
      if (pszLibFileRemote = nil) then
        Exit;

      // Copy the DLL's pathname to the remote process's address space
      if ( not WriteProcessMemory(hProcess, pszLibFileRemote,
         PChar( DllFilename), dwMemLen, dwWrited)) then
         Exit;

      // Get the real address of LoadLibraryW in Kernel32.dll
      pfnThreadRtn :=   GetProcAddress( GetModuleHandle('Kernel32.dll'), 'LoadLibraryA');
      if (pfnThreadRtn =nil) then
        Exit;

      // Create a remote thread that calls LoadLibraryW(DLLPathname)
      hThread := CreateRemoteThread(hProcess, nil, 0,
         pfnThreadRtn, pszLibFileRemote, 0, dwThreadId);
      if (hThread =0) then
        Exit;

      Result:=True;

   finally // Now, we can clean everthing up

      // Free the remote memory that contained the DLL's pathname
      if (pszLibFileRemote <>nil)  then
         VirtualFreeEx(hProcess, pszLibFileRemote, 0, MEM_RELEASE);

      if (hThread  <>0)  then
         CloseHandle(hThread);

      if (hProcess <>0)   then
         CloseHandle(hProcess);
   end;

 

 

end;