Explaining the Linux Fork Bomb
About the bomb
You may have seen this before: :(){ :|:&};:
usually as a joke about new emoji support in Linux terminals.
If you run it you will probably see something like this:
Then your system becomes completely unusable.
What is it?
Well, let's explain what is going on, by breaking it up into multiple lines.
:(){
: | : &
}
:
So, it's a function :()
that contains {
itself :
a pipe |
to itself :
that runs in the background &
then closes the contains }
and finally calls itself ;
starting the whole loop.
Is is much easier to understand if you rename the function to something other than :
for instance this is the exact same thing:
fork(){
fork | fork &
}
fork
Using this updated code the one line version would be fork(){ fork | fork &}; fork
What is happening then?
Well, it initially starts, calls itself and passes itself to itself in the background making child processes of itself, each one doing the exact same thing, making children that make children ad infinitum. Quickly making the computer or server run out of resources, and it happens very fast.
Why does it matter?
Because it can be run with absolutely no permissions other than login, and will take it down in seconds.
What can I do if i run a server?
Good news if you run a server with systemd, It should prevent this by limiting the users to 33% of max cpu time. But, it wouldn't hurt to look at the soft and hard limits anyway.
What if I don't?
The best protection is to limit the number of background processes a user can spawn, which by default is usually 10k. This can be check with the command ulimit -u
if you would like to lower it, you can manually limit it by setting soft and hard limits with ulimit -S -u 5000
. If you want a permanent solution you would need to edit the file /etc/security/limits.conf
which has examples of settings you can set, but should look something like this:
@users hard nproc 5000
Thereby setting the group users hard limit to the number of processes to 5000