The fork bomb explained

2012-05-09

Last night on #crunchbang @Freenode the infamous fork bomb came up. Some people didn't know what it was and what it did, and some people knew what it's “side effect” was but didn't know how it works, so I thought I'd break it down here and give a hint what you can do to prevent someone freezing your machine up with it.

Breaking it down

The most common form of the fork bomb is

:(){ :|:&};:

Entering that to your terminal most likely will cause your machine to freeze as it chokes on insane amount of processes. Despite of looking a bit cryptic to untrained eye, it's really a very simple piece of shell script. Let's take it apart, now.

:() { ... }

This construct is used to define a function. A function also needs a name, which comes before the parenthesis i.e. my_awesome_function() { return 0 }. So in this case, where we have :(){ ... } we define a function called :.

:|:&

Now, this is the contents of the function. What it does is call the function : (itself) and pipe the result to the function :. So in effect the the function calls itself twice. The ampersand means the function call is moved to background so the child processes couldn't get killed.

;:

; is there only to tell the parser that the function definition ends here, and what follows is a new command. It's only needed because we want to keep the bomb as a one-liner. The last character, : is of course the command to start the bomb: call the :-function we just defined.

There's no magic there, it's just a regular recursive function. Only that it doesn't terminate, but starts instantly eating up more and more of your system's resources until the machine freezes. To make it look more like regular shell script it could be re-written for example like this:

bomb() { bomb | bomb & } bomb

I don't recommend running that on your local machine. Even if a hard reset wouldn't harm your machine it never does any good, either.

Protective measures

Since the fork bomb works by spawning processes, you can shield your system against it by limiting the amount of processes a user can simultaneously have.

On a Linux system you can do this by editing your /etc/security/limits.conf file. There's probably some kind of template for you to take example of. What you want to limit is nproc:

harski hard nproc 100
@users hard nproc 50

The target whose attributes you want to target can be a single user (like on the first line) or a group (the second line). If it's a group, you need to indicate it by prepending the group name by @. “hard” on that line means it's a hard limit. The other possible value would be soft limit (only warns about having too many processes).

It also takes wildcards and can enforce limits to many more resources than just the number of processes, take a look at its man page for more information.