PHP Goto Replicator

This PHP code is a basic metamorphic code example, although it is a script and not a compiled binary. After initially running the script it copies itself to a new file with a random file name, with the lines of code in a new random order, it then forks a new process which is executing the new copy of the script file and the original copy exits. Now there is a new copy of the script running, which is a copy of the original file but with a random file name and the lines of code are in a different order. So this is a perpetual process; reordering and replicating, then executing a new instance (process) killing the previous one.

It is a basic example of replicating metamorphic code. The new file is always in the same directory as this is just a proof of concept. Where the new file is stored could be more random or covert, this is just one improvement that could be made for example, but those type of steps lean towards malicious intentions rather than purely educational exercises for a PoC.

The script is in three sections, "a", "l" and "f". Section "a" generates a random new file name and opens the file for writing. In section "l" the script copies its self to that new file name and this is where the lines of the code are reordered. Finally in section "f" the script forks off a child process, which is the new copy of the script, and the original copy exits. The process ID is always changing. This is why there is the “sleep(10)” statement.

Below after initially starting the script, a scrambled version is printed to the screen (this is something to show that the script is actually running!). After that, 10 seconds later a different scrabmled version is printed to the screen. This process repeats, with a different order of code being printed each time. Each time that happens, a new file has been created, executed, and a new fork is launched.