Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating code for DLL Injection from Delphi 7 to Delphi XE2

I got an old injector which was made by me in Delphi 7 and I tried to change him in that way, that it still works in XE2 but i failed-.- The new test dll works with my old injector without any problems so im quite sure that my injector got a bug.

here is the code I made:

procedure TForm1.InjectDLL(const ADLLName: String; targetproc: Cardinal);
var
  dllname: String;
  pDLLname, pStartAddr: Pointer;
  bw: NativeUInt;
  hProcess, hRemoteThread: THandle;
  TID: Cardinal;
begin
  hProcess := OpenProcess(PROCESS_ALL_ACCESS, false, targetproc);
  pDLLname := VirtualAllocEx(hProcess, 0, length(dllname) + 1,
    MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);

  WriteProcessMemory(hProcess, pDLLname, Pointer(dllname),
    length(dllname) + 1, bw);

  pStartAddr := GetProcAddress(GetModuleHandle('kernel32.dll'), 'LoadLibraryA');
  hRemoteThread := CreateRemoteThread(hProcess, nil, 0, pStartAddr,
    pDLLname, 0, TID);
  WaitForSingleObject(hRemoteThread, INFINITE);
  showmessage('Fehler ' + IntToStr(GetLastError) + ': ' +
    SysErrorMessage(GetLastError));
  CloseHandle(hProcess);
end;

I just needed to change hProcess and hRemoteThread to THandle and bw to NativeUInt. The showmessage just tells me that all works. There must be a small difference since the String type changed from d7 to XE2. I also tried to cast the dll name as PAnsiChar but it changed nothing to me.

Hope I posted enough information for you.

like image 971
HolyShiru Avatar asked Dec 20 '22 20:12

HolyShiru


1 Answers

The net result of your code, under Unicode Delphi, is to pass UTF-16 text to LoadLibraryA. And of course, that expects 8 bit ANSI text. You have two options to resolve the problem:

  1. Stick with ANSI text and simply replace string with AnsiString in your code snippet.
  2. Switch to Unicode text. Use LoadLibraryW and apply the change suggested by Arnaud to correctly handle the length of the 16 bit text.
like image 167
David Heffernan Avatar answered Dec 24 '22 01:12

David Heffernan