5

Is there possible situation where a file contains malicious codes and after the code is excuted, the virus attach itself to another file and delete the malicious code from the file where it comes from?

2
  • 1
    Yes. Programs (including malicious ones like viruses) can do some task and delete themselves. How do you think uninstall programs work? – dr jimbob Mar 5 at 4:03
  • It's been done before. Stuxnet was programmed to erase itself after a particular date to avoid detection. – James Westman Mar 5 at 16:34
9

Is there possible situation where a file contains malicious codes and after the code is executed, the virus attach itself to another file and delete the malicious code from the file where it comes from?

Yes, once the virus program is a running process (program loaded in RAM), it can easily access its own program file and delete its executable file from persistent storage.

The C code to do this self deletion is very simple, since the program file name is the zeroth argument of the argv input array pointer to the C main function. And, for example, the remove function can be used from the stdio library to delete a file by name.

For example:

#include <stdio.h>
int main(int argc, char *argv[]) {
    remove(argv[0]);
    return 0;
}

If you compile and run the above source code it will delete its own executable.

Injection into another process is also fairly straightforward, but the exact form of the source code to perform such functionality is more operating-system dependent.

2
  • 5
    - this is very easy on unix-ish systems, but it's not so easy on Windows, as Windows doesn't let you delete running executables - viruses have various workaround for this on windows, but none are as easy as that. one solution is to inject themselves to explorer.exe (or something like that) via VirtualAllocEx+WriteProcessMemory+CreateRemoteThread, then exit the original process, and have the explorer.exe-thread delete the original file; there's plenty of other options too ofc, but your approach is valid for unix-systems, but not Windows systems. (and Windows is the most popular OS for viruses) – user1067003 Mar 5 at 15:36
  • 1
    One way to get this very easy example to work on Windows is to compile/run it via Cygwin. I have confirmed it does work via cygwin on Windows. OTOH, you are correct that it doesn't "just work" if compiled directly with Visual Studio on Windows (the call to "remove" returns -1, but I haven't investigated further). – hft Mar 5 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.