Search code examples
delphihookdll-injection

Hook process creation in Csrss


I'm trying to hook process creation and receive an 'notification' into my hook procedure when the user open any new process. To hook only one function, I'm trying to do this in CsrCreateProcess at csrss.exe. But everytime when I inject a DLL inside this process I get a BSOD (blue screen). My injection code is:

function Inject(DLL: PAnsiChar; ProcessID: Cardinal):Boolean;
var
  lProcess: THandle;
  lMem:     Pointer;
  lLibrary: Pointer;
  Bytes:    NativeUInt;
  lThread:  DWORD;
  RemoteThread: DWORD;
begin
  Result := FALSE;
  if FileExists(DLL) then  { If Path of DLL is valid }
  begin
    lProcess:= OpenProcess(PROCESS_ALL_ACCESS,False,ProcessID); { Open process to DLL Inyect }
    if lProcess <>  0 then  { If Process is opened }
    begin
      lMem:= VirtualAllocEx(lProcess,nil,Length(DLL),MEM_COMMIT,PAGE_READWRITE); { Reserve virtual space for load DLL }
      if (Assigned(lMem)) then
      begin
        lLibrary:= GetProcAddress(GetModuleHandle('kernel32'),'LoadLibraryA');  { Parameter used for load library DLL in remote process }
        WriteProcessMemory(lProcess,lMem,Pointer(DLL),Length(DLL),Bytes); { Write DLL in remote space created with VirtualAllocEx }
        RemoteThread:= CreateRemoteThread(lProcess,nil,0,lLibrary,lMem,0,lThread); { Create Remote Thread for run DLL }
        if (RemoteThread <> 0) then
        begin
          WaitForSingleObject(RemoteThread, INFINITE); // Wait for the LoadLibraryA thread to finish
          CloseHandle(RemoteThread); { Close handle of Thread }
          Result := TRUE;
        end;
      end;
      CloseHandle(lProcess); { Close handle of process opened }
    end;
  end
end;

And my DLL code is:

procedure DLLMain(dwReason: DWORD);
begin
  case dwReason of
  DLL_PROCESS_ATTACH:
  begin
    MessageBoxA(0,'Injected', 'Injected', MB_OK);
    //@TrampolineCreateProcess := InterceptCreate(@CsrCreateProcess, @HookCsrCreateProcess);
  end;
  end;
end;

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

Is a bad idea to try hook this function in csrss? I'm starting to think in inject inside explorer.exe and hook NtCreateSection, this should solve my problem right? Other quick question: is possible to inject a x64 DLL inside a x64 process, with a x86 executable?


Solution

  • In the comments you state that you are trying to inject a 64 bit DLL into a 64 bit target process from a 32 bit injector. That cannot be done using the CreateRemoteThread method. You need to create a 64 bit injector.

    On top of that csrss is a system integrity critical component. I would not be at all surprised if injecting into it was not allowed even if you resolved the bitness issues. I would definitely advise against continuing your attempts to inject into csrss.