The fork command is a vital part of the Unix shell environment. It works by creating a new thread, called the child, which is identical to the original (parent) thread. From there the new thread will execute the command called by the user, while the shell can either wait for that execution to finish, or can continue on.
This is useful for “silent” commands which run in the background. The parent and child threads are generally identical with one exception. The fork command will return the process ID in the parent, while returning zero in the child. This difference is what separates a working program from malicious code. When used incorrectly, the fork command can create a vicious denial of service attack called a fork bomb.
Fork bombs are potential system killers. They start with a single thread and multiply quickly to consume every available resource so that no new processes can be initiated. This is particularly bad when the only way to stop these processes from spawning is to create a new process to kill them. While killing a fork bomb is difficult, preventing them is relatively easy. To do so is as simple as limiting the number of processes available to each individual user. The goal is to set this number low enough so that if every user implements a fork bomb at the same time, there will still be enough resources available to start a kill process.
Limiting the number of processes is as easy as changing the ‘/etc/security/limits.conf’ file, appending a single line at the bottom. Adding ‘* hard nproc 15′ for example would limit all users to 15 processes each, with the exception of the root user. After this the user implementing the bomb would begin recieving error messages – ‘Cannot fork: Resource temporarily unavailable’. In the limits.conf file, ‘*’ indicates all users, ‘hard’ ensures the hard limit is enforced, ‘nproc’ is number of processes, and ’15′ is the limit you want to enforce. By doing this, you can secure your servers against fork bombs and ensure that your service is not interrupted.