Question

I have a simple DLL that I inject inside notepad for testing purposes only. My code for injector is like this:

uses
  Windows;

var
  BytesWritten:  cardinal;
  PID, Process, Thread, ThreadId, hKernel: dword;
  pLoadLibrary, Paramaters: pointer;
    DLL: AnsiString;

    begin
      DLL := 'C:\test.dll'; // Must be full path name.
      PID := 3160;
      Process := OpenProcess(PROCESS_ALL_ACCESS,
                             False,
                             PID);

      Paramaters := VirtualAllocEx(Process,
                                 nil,
                                   Length(DLL),
                                   MEM_COMMIT,
                                 PAGE_EXECUTE_READWRITE);

      WriteProcessMemory(Process,
                         Paramaters,
                         PAnsiChar(DLL),
                         Length(DLL),
                         BytesWritten);

      hKernel := GetModuleHandle('KERNEL32.DLL');

      pLoadLibrary := GetProcAddress(hKernel,
                                     'LoadLibraryA');

      Thread := CreateRemoteThread(Process,
                                   nil,
                                   0,
                                   pLoadLibrary,
                                   Paramaters,
                                   0,
                                   ThreadId);

      WaitForSingleObject(Thread, INFINITE);

      VirtualFreeEx(Process,
                    Paramaters,
                    0,
                    MEM_RELEASE);

      CloseHandle(Thread);
      CloseHandle(Process);
end.

My DLL code is simple like this:

uses
  SysUtils,
  Classes,
  Windows;

{$R *.res}


procedure EntryPoint(Reason: dword); stdcall;
begin
  if Reason = DLL_PROCESS_ATTACH then
  begin
    MessageBox(0, 'DLL Injected', 'DLL Injected', 0);
  end;
end;


begin
  DLLProc:= @EntryPoint;
  EntryPoint(DLL_PROCESS_ATTACH);
end.

When I inject the dll in the Notepad process, I get the MessageBox sayin DLL Injected, but after few seconds it crash saying: Exception EAccessViolation in module test.dll at 00FFE102. Access violation at address 00FFF102. Write of address 00FFF102. I'm using Delphi 2010, Windows 7 x64, Admin rights, no UAC, notepad and dll are both x32...

Was it helpful?

Solution

Your EntryPoint function is declared incorrectly. It should not use stdcall. The correct declaration is:

procedure EntryPoint(Reason: Integer);

Check in the RTL source code for the declaration of TDLLProc, or refer to the documentation, to confirm that this is accurate.

If only you had not used the @ operator when assigning to DLLProc, the compiler would have been able to tell you this.

As Sertac said, you should also include a null-terminator in the file name that you write into the target process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top