Self-deleting executables

Source: Internet
Author: User

From: http://www.catch22.net/tuts/selfdel.asp

Download Source

This is a subject that tends to come up every so often in the newsgroups, so I thought I 'd write an article about the techniques I 've collected to enable an executable to delete itself from disk (whilst running, that is ). there is very little information on the Web, and what information exists is also hard to find.

Why wocould you want a program to delete itself? The only good reason I know of is an un-install program that needs to remove an application, as well as itself in order to completely remove the application from disk. i'm sure there are other good reasons for self-deleting executables, but un-installation is probably the most common.

I know divide different methods, each of which I will describe shortly. I must take this opportunity to mention that only one of these techniques has been developed by myself. apart from the last method, I am presenting the same material described by Jeffrey Richter In his January 1996 MSJ column, titled "Win32 Q & ". click here to read the original article. the rest of the techniques were originally developed by Gary nebbett-or heavily influenced by his work. so, I hope no-one thinks I am ripping off other people's ideas becauseAllThese techniques have existed for years before I encountered them.

There used to be two methods for a program to delete itself-actually doing it from the same program, and forcing a separate program to do it on your behalf. when Windows XP came out the "self-deleting" executable became a part of history-it is no longer possible for a Windows program (which runs on any version of Windows) to delete itself. however there are lots of techniques which can achieve the same effect-the ones I know about are listed below.

Why the obvious doesn' t work

If you try to run the following code, nothing will happen.

TCHAR szFilePath[_MAX_PATH];// Get current executable pathGetModuleFileName(NULL, szFilePath, _MAX_PATH);// Delete specified fileDeleteFile(szFilePath);

The code above retrieves the full path to the current executable, and then tries to delete the file whilst running. this code will fail-because all 32bit versions of Windows (95, 98, me, NT, 2000, XP etc) use a mechanical called memory-mapped files to load an executable image into memory.

When the Windows loader runs an executable, it opens the executable's disk file and maps that region of disk into memory, implements tively loading the executable into memory. this disk file is kept open during the lifetime of the process, and is only closed when the process terminates. because of this lock on the file, it is normally impossible to delete an executable file whilst it is running. just run notepad.exe, then try to delete the notepad executable-it won't work.

The movefileex Method

I'm going to mention this technique even though it doesn' t really solve our problem, because it is quite useful to know and can be handy in other situations.

MoveFileEx(szExistingFile, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); 

TheMovefileexAPI moves a file to a new location. when you pass null as the second parameter, this causes the file to be moved "Nowhere", please tively deleting the file. now, ordinarily this wowould fail if you tried this with the path to the current executable. however, if we specifyMovefile_delay_until_rebootIn the dwflags parameter, this tells windows not to move (or delete) the file until the system is shutdown or rebooted.

There are a few problems with this technique. firstly, you cannot remove the directory that the executable resides in. second, the file is not deleted immediately-if your system doesn't get rebooted very often, then the file will stay around. but the biggest problem is that movefileex is not implemented on Windows 95/98/ME. today this is not really a problem and the movefileex is the neatest, safest way for a program to delete itself.

The wininit. ini Method

Under Windows 95/98/Me, an application called wininit. EXE runs each time the system is started. this application looks for a file called wininit. ini. if this file exists, wininit. EXE looks for a section called [rename]. each entry in the [rename] section specifies a file RENAME operation which will occur (once) when time the system starts. this method is obviusly very similar to the movefileex method described above.

[Rename]NUL=c:/dir/myapp.exec:/dir/new.exe=c:/dir/old.exe

The filename to the left of the equal sign specifies the new name of the filename on the right. WhenNulIs used as the new filename, the file is deleted. This means that an application can write an entry into wininit. ini, specifying NUL and the Applications own full path.

You must be careful when writing an entry to the [rename] section. You cannot useWriteprivateprofilestringAPI call, because this function prevents any duplicate entries from occuring under the same section. this restriction wowould prevent there from being more than one "NUL =" entry. therefore you must manually write any entry if you want to use this technique.

The self-deleting batch file Method

This is quite a well known method, and was has ented in msdn some time ago. this technique works on both Windows 95 and Windows NT. it works because MS-DOS batch files are able to delete themselves. to test this technique, create a small batch file containing the single command:

del %0.bat

The batch file, when run, deletes itself and issues an error "the batch file cannot be found ". this error is just a simple message, so it can be safely ignored. by itself this isn't too useful, but when modified to delete our executable it solves our problem, albeit in a rather forceful manner. our executable will create a batch file (calledC:/delus. bat) With the following content:

:Repeatdel "C:/MYDIR/MYPROG.EXE"if exist "MYPROG.EXE" goto Repeatrmdir "C:/MYDIR"del "/DelUS.bat"

This batch file repeatedly attempts to delete the specified file, and will run continuously consuming CPU until it succeeds. When the execuable has been deleted, the batch file then deletes itself.

The executable needs to spawn off the batch file using CreateProcess, and then shoshould Exit immediately. it wocould be a good idea to give the batch file's thread of execution a low priority so that it doesn't get much execution time until the original executable has terminated.

The sourcecode download at the top of this article contains the full code to this technique.

The comspec Method

This is a method kindly shared by Tony varnas, who recently emailed me this snippet:

BOOL SelfDelete(){  TCHAR szFile[MAX_PATH], szCmd[MAX_PATH];  if((GetModuleFileName(0,szFile,MAX_PATH)!=0) &&     (GetShortPathName(szFile,szFile,MAX_PATH)!=0))  {    lstrcpy(szCmd,"/c del ");    lstrcat(szCmd,szFile);    lstrcat(szCmd," >> NUL");    if((GetEnvironmentVariable("ComSpec",szFile,MAX_PATH)!=0) &&       ((INT)ShellExecute(0,0,szFile,szCmd,0,SW_HIDE)>32))       return TRUE;  }  return FALSE;}

This method is very similar to the batch-file method (abve) but is alot neater in its implementation. it works under all 32bit versions of Windows (2000, 98, me, NT, XP), as long asComspecEnvironment variable is defined. this is always defined (by default) to be the full path to the operating system's command interpreter. for Windows 95, this is "command.exe ". for Windows NT, this is "cmd.exe ".

The function will only work if the executable has exited, so it is important to call this function and then exit immediately. it works by spawning a copy of the system's command interpreter, and asking it to perform the following command:

del exepath >> NUL

This deletes the current executable, and pipes the output to NUL (no output). The shell process is created with a hidden window as well, so the whole process is invisible.

The delete_on_close Method

TheCreatefileAPI call accepts several flags which affect how a file is created or opened. one of these flags, file_flag_delete_on_close, specifies that the file will be deleted when the last handle to it is closed. the basis to this technique will be to run an executable with this flag set, so that when it exits, It is deleted automatically.

The first step is to create an empty file with the delete_on_close flag specified. the exact binary content of the current executable file is then copied into this new file, in effect duplicating the executable on disk. A new process is then created (using the new executable file ). this has the effect that the duplicate file's handle count is incremented. also, when the new process was created, the full path of the current process was passed through the command-line argument.

Next, the current executable (which wants to delete itself) closes the file handle used to create the new process, and then exits. now, the duplicate's file-handle count is decremented, but because CreateProcess incremented its handle count when it started, the file is not deleted.

At this point, the duplicate executable has started running. the PID specified on the command-line is used to open a handle to the original process. the duplicate waits for the original process to terminate, usingWaitforsingleobject. When this call returns, the duplicate can call deletefile on the filename also specified through its command-line argument. the original executable (the one that wanted to delete itself) has been successfully deleted. this just leaves the duplicate copy, which Exits normally. the duplicate's file-handle count drops to zero, the delete_on_close flag comes into effect, and the duplicate file is deleted also.

It sounds a bit complicated, but it's not too difficult. Here's the steps one more time:

[ Current process ]1. Create a new file with FILE_FLAG_DELETE_ON_CLOSE.2. Copy the current executable's content into the new file.3. Create a new process with the duplicate executable:4. Pass the current executable's full path and PID in the call to CreateFile.5. Sleep for a short time to give the new process time to start.6. Close the new file.7. Exit current process.[ Duplicate process ]8.  Wait for the process specified on command-line to die.9.  Delete file specified on command-line.10. Exit duplicate process.  

There are just a couple of technicalities to mention. first, when the "new" process is spawned, the "old" process must sleep for a short period, enough to let the Windows loader open the file and create the process (thus incrementing It's file count ).

Second, the new process must wait until the old process terminates, which releasesItsFile count.

Third, when the duplicate executable is created, it must also have the file_assist_delete flag specified, otherwise CreateProcess will fail, because it won't be able to open the file whilst we have it open with the delete_on_close flag set.

Obviusly this method will require careful coding, because the program must be written in such a way so that it can perform these dual tasks. the "New" executable must know that it's job is to delete the file specified on the command line, for instance.

It's a little messy, but it does work very well. in fact, the uninstall program that I wrote, Which is wrongly ded with the software you can download from this site, uses this very method. I 've got ded an example program which demonstrates this technique.

An alternative method is to write a very small stand-alone executable, which it's sole task is to delete the file-name specified on it's command-line. this executable cocould then be imbedded as a "payload" to the executable which wants to delete itself. this payload wocould be created and executed in the same way as described above.

The ultimate self-deleting executable!

This inline assembly snippet is short and simple. I can't claim credit for this code-I found it posted on Usenet some time ago. the author's name is Gary nebbett, author of "Windows NT native api reference ". actually this technique was first published in Windows developer journal around 1996.

#include <windows.h>int main(int argc, char *argv[]){    char    buf[MAX_PATH];    HMODULE module;        module = GetModuleHandle(0);    GetModuleFileName(module, buf, MAX_PATH);    CloseHandle((HANDLE)4);        __asm     {      lea     eax, buf      push    0      push    0      push    eax      push    ExitProcess      push    module      push    DeleteFile      push    UnmapViewOfFile      ret    }         return 0;}

This snippet only works under Windows NT and 2000. As soon as you compile and run the above program, it just disappears from disk! It works because under NT and 2000 the OS keeps a usermode handle reference to the memory-mapped file which backs the executable image on disk. this handle always has a value of "4" under these OSS.

Unfortunately this gem only works under NT/2000, not XP or. NET Server. this is because these OSS no longer maintain a usermode handle to the executable's memory-mapped file-This section object is only accessible in kernel using a pointer reference. so although this technique is incredibly slick (it is the only true self-Deleting method) It is no longer as-is.

Now for Windows 9x!

Thanks must go to Tony varnas again for some great detective work. he managed to unearth the following runner er snippet which works exactly like the snippet abve, but this time for Windows 95.98, me (tested on all three ).

#include <windows.h>  int main(int argc, char *argv[]){    char    buf[MAX_PATH];    HMODULE module;        module = GetModuleHandle(0);    GetModuleFileName(module, buf, MAX_PATH);    __asm     {      lea     eax, buf      push    0      push    0      push    eax      push    ExitProcess      push    module      push    DeleteFile      push    FreeLibrary      ret    }        return 0;}
Solution for XP +

After the original self-deleting technique Gary nebbett posted a solution on Jan 19 2002 which works for XP. the following code shocould be packaged as a DLL which is callable from rundll32. the idea is that an external program (rundll32) is used which first waits for the original executable to finish. the dll which is loaded into rundll then performs the original self-deleting trick. this is possible because the kernel maintains references to DLLs differently to the main executable.

#include <windows.h> #pragma comment(linker, "-export:CleanupA=_CleanupA@16?) extern "C" void CALLBACK CleanupA(HWND, HINSTANCE, PSTR, int) {     static MEMORY_BASIC_INFORMATION mbi;     VirtualQuery(&mbi, &mbi, sizeof mbi);     PVOID module = mbi.AllocationBase;     CHAR buf[MAX_PATH];     GetModuleFileName(HMODULE(module), buf, sizeof buf);     __asm     {         lea     eax, buf         push    0         push    0         push    eax         push    ExitProcess         push    module         push    DeleteFile         push    FreeLibrary         ret     }}

The idea that an external program cocould be used to self-delete it's parent is what influenced me to develop the following technique which works for all versions of Windows, but does not require a separate dll which is dropped to disk.

The definitive self deleting executable

I am pleased to present what I believe is the definitive self-deleting executable, for all versions of Windows.

Now this technique isComplicatedSo I won't include the code here-Please get it from the sourcecode zipfile (selfdel05.c). Instead I will describe how it works and the issues involved.

  • Firstly a child process is created in a susponded state (any process will do-I. e. assumer.exe ).
  • Some code is then injected into the address-space of the child process.
  • The injected code waits for the parent-process to exit.
  • The Parent-process is then deleted.
  • The injected code then CILS exitprocess, which terminates the child process.

The neat thing about this technique is that the spawned child process never really executes (no windows ever appear)-only the "self-deleting" code in the child gets to execute. after the parent process terminates and is deleted, the child process terminates using exitprocess, preventing anything further from happening. specified tively an arbitrary child-process is hijacked and coerced into deleting it's parent.

My first version of this technique (inside selfdelxp. c) usedCreateRemoteThreadTo inject the code into the susponded child process. this was quite neat because the child never ran-only the injected thread with the self-deleting code ever executed. the downside to this technique is that it only ran on Windows-NT based platforms.

The latest version (selfdel05.c) does not use createremotethread to inject code into the child. it therefore works on all versions of Windows. the self-deleting code is injected into the spawned child by hijacking the primary thread of the process. the thread's stack is manipulated in such a way so that space is "allocated" on the stack-into which the self-deleting code is written. the instruction-pointer for the thread is then altered so that it points to the injected code on the thread's stack. when the child process (and primary thread) is resumed the code executes right off the stack, deleting the parent process, and then exits.

There are issues involved with this last technique. the first is the injection of code into an already running thread-this is not a desirable thing to do, but because the thread's "real" execution is never resumed (the process exits as soon as the parent is deleted) It seems like a viable way to do this.

The second issue involves the Win32 environment. when a child process is created in a suspended state the program has not started executing yet-there is still alot of Win32 environment setup that must be passed med before the entry-point to the executable is called. so when we hijack this thread to do our bidding, we are doing so in an environment that is not yet fully initialized, and is not read Y for Win32 api cils (it is still mid-way through executing some internel part of the OS !). The API callthat are made (waitforsingleobject, deletefile etc) do however work-but this is not guaranteed in furture OS releases.

The exact same issue exists when you createremotethread into a process that was started as suincluded-the OS hasn't yet finished intializing your process's environment before the remote thread starts to execute. this is why alot of Win32 api cils will fail (such as removedirectory ).

Conclusion

I 've used this article to describe all the methods I know of to delete an executable whilst it is running. you can take your pick of the techniques, but the last method presented is currently the only one which works well for all versions of Windows.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.