AfxCodeHook Example - Inject Executable

posted 17 Oct 2010, 15:48 by Delphi Basics
{
  Inject Exe Demo 
  by Aphex 

  This program demonstrates more of InjectLibraryEx's
  true power. The ability to inject EXE files. This means
  that the EXE you inject can be stored somewhere encrypted
  or compressed and then later it can be loaded into memory
  and executed. Or as this program does, it can inject itself
  into another application. The target application will show
  no signs of the injection.
}

program InjExe;

uses
  Windows,

var
  StartInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
  BytesRead, Module, Process, Size: dword;
  Path: array [0..MAX_PATH] of char;
  Data: pointer;

function ExtractFileName(FileName: string): string;
begin
  while Pos('\', FileName) <> 0 do Delete(FileName, 1, Pos('\', FileName));
  while Pos('/', FileName) <> 0 do Delete(FileName, 1, Pos('/', FileName));
  Result := FileName;
end;

begin
  //check our location
  if lstrcmpi('notepad.exe', pchar(ExtractFileName(ParamStr(0)))) = 0 then
  begin
    MessageBox(0, 'hello from notepad :)', 'afxCodeHook', 0);
    ExitThread(0);
  end;

  //create process to inject into
  ZeroMemory(@StartInfo, SizeOf(TStartupInfo));
  StartInfo.cb := SizeOf(TStartupInfo);
  CreateProcess(nil, 'notepad.exe', nil, nil, False, 0, nil, nil, StartInfo, ProcInfo);

  //get the dll data to inject
  Process := ProcInfo.hProcess;
  GetCurrentDirectory(MAX_PATH, Path);
  Module := CreateFile(pchar(ParamStr(0)), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  Size := GetFileSize(Module, nil);
  GetMem(Data, Size);
  ReadFile(Module, Data^, Size, BytesRead, nil);
  CloseHandle(Module);

  //get it boi
  InjectLibrary(Process, Data);
  FreeMem(Data);
end.
Comments