Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi self-deleting program

How do I auto-delete, my Delphi program? I tried this code:

procedure DeleteSelf;
var
  module : HMODULE;
  buf : array [ 0 .. MAX_PATH - 1 ] of char;
  p : ULONG;
  hKrnl32 : HMODULE;
  pExitProcess, pDeleteFile, pFreeLibrary : pointer;
begin
  module := GetModuleHandle ( nil );
  GetModuleFileName ( module, buf, sizeof ( buf ) );
  CloseHandle ( THandle ( 4 ) );
  p := ULONG ( module ) + 1;
  hKrnl32 := GetModuleHandle ( 'kernel32' );
  pExitProcess := GetProcAddress ( hKrnl32, 'ExitProcess' );
  pDeleteFile := GetProcAddress ( hKrnl32, 'DeleteFileA' );
  pFreeLibrary := GetProcAddress ( hKrnl32, 'FreeLibrary' );
  asm
    lea eax, buf
    push 0
    push 0
    push eax
    push pExitProcess
    push p
    push pDeleteFile
    push pFreeLibrary
    ret
  end;
end;

But it does not work, do not delete the file. My program is console. Thanks!

like image 850
Giacomo King Patermo Avatar asked Jun 25 '12 21:06

Giacomo King Patermo


1 Answers

Your code only will work under Windows NT and 2000. Because in these OSs the system keeps a usermode handle reference to the memory mapped file which backs the executable image on disk. This handle always has a value 0x4 in these Windows versions.

The most effective way to delete your own exe, is creating a child process in suspended state, inject the code to wait for the parent process (the exe to delete) , then detect when the parent process exits, delete the parent process and finally kill the child process.

You can found more about this topic in these recommendded resources.

  • Self-deleting Executables (Techniques which allow an executable file to delete itself whilst running)
  • Self deleting executables Ranju. V.
like image 180
RRUZ Avatar answered Oct 04 '22 11:10

RRUZ