Quantcast
Channel: Hakin9 – IT Security Magazine
Viewing all articles
Browse latest Browse all 612

Writing A Simple Ransomware Using Python

$
0
0

Introduction:

Ransomware is a program designed to prevent a user or organization from accessing files on their computers. It encrypts the files and demands a ransom for the decryption key; this places organizations and individuals in a position where paying the ransom is the easiest,  cheapest, and quickest way to regain access to their files. Some types of ransomware have added functionalities – such as data theft too.

Recent ransomware attacks have impacted hospitals’ ability to provide crucial services and crippled public services in cities. Ransomware doesn’t need to be complex to cause damage, which makes it even more dangerous. Bad actors don’t require a strong knowledge of programming, either. In this article, I will explore how to write a simple ransomware using Python. 

How it works:

The ransomware code can be split into three parts, the directory crawler,  encryption,  and decryption. The first function crawls through all accessible directories within the directory that holds the malware.  The crawler looks for files and other directories and will keep going until it reaches the deepest point in the directory tree and then saves the files' names and paths to be used during the encryption phase.

Diagram

Description automatically generated

P1 directory tree

For example, let’s assume that the ransomware exists in D1. The crawler function will start going through the directories — it will go to D11, then will add all the files in D11 (F1, F2, F3) to a list and will continue to do the same for D12 through D14. Once the ransomware acquires all its targets,  it is ready to start encrypting the victims’ files. When the encryption begins, it will use the list made by the crawler and start encrypting all the files it can reach. When it finishes encrypting, it will show the user a message telling them that their data was compromised and give them a set of instructions that they must follow if they want to restore their data; for example, sending some cryptocurrency to get the decryption key. Once the user enters the key, all of their data may be restored, allowing them to access the data again.

Coding tutorial:

For this tutorial, you can use any text editor you prefer, as all will do the job; I used python3 and the library cryptography Fernet. I will leave a link to the library at the end of this article.  In short, it provides symmetric encryption and authentication of data. It uses an AES-CBC algorithm with a 128-bit key length. 

Now, let’s create our victim directory where the ransomware will be installed. I am using Kali Linux, so let’s begin by creating a new directory. Next, type the command :
mkdir <dir name >

A screenshot of a computer

Description automatically generated with medium confidence

P2 creating a directory in Kali using cmd.

Create two other directories inside “userdata” and put some files inside them. For example, create a small text file or an image and keep copies of the files in case anything goes south, so you won’t have to create or download the files again.

I created the following directories:

Graphical user interface, text

Description automatically generated with medium confidence

P3 user directories 

I put a couple of files in each one of the directories:

Text

Description automatically generated

P4 user text files 

Text

Description automatically generated

P5 user photos 

Now that the test environment is done, let’s start coding, First, we need to create the directory crawler for this, I will use the “OS” module in Python, which provides functions for creating and removing a directory (folder), fetching its contents, changing, and identifying the current directory, etc.

Text

Description automatically generated

P6 crawler code 

Import the OS module and create a list. This list will be used to save all files that the crawler finds.

To understand how the second loop works, let’s take a look at the os.walk function. This method is taking  an argument that tells the function where to start crawling.  In our case, it's telling it to start from the same directory where the program we are writing resides.  Next,  the walk function generates the file names in a directory tree by walking the tree. For each directory in the tree rooted at directory top, it returns a 3-tuple (dirpath, dirnames, filenames). The second for loop is to go over all the files that the walk function found and add them to the list of files. The command inside the second loop will generate a full path. For example (./userdata/userphotos/user), now lets see our code in action:

Text

Description automatically generated

P7 crawler output

As you can see, the crawler searched the test directory and retrieved all the file names and their paths. Now, we can do something more dangerous! We can tell the walk function to go through any directory we want. For example, let's make it go through the system /etc/.

A picture containing text, plaque

Description automatically generated

P8 using crawler on /etc.

We can basically tell the crawler to start from any directory we want. We can even provide it with a list of directories to search in. This will take a bit more time but will allow the ransomware to encrypt more data.

Moving to the second step, let’s start encrypting the files. For this, we need to import the second library called cryptography.fernet and create our encryption key, then the for loop will iterate through the files, then using open, we read the content of the files. The open command takes two arguments. The first one is the file path  and the other argument is for the reading mode, and because we want to be able to encrypt all file types, we need to use binary mode (“rb”) as (r) or (rt) won’t work. We read the content of the file to a variable and then, using the library build in encryption function, we encrypt the data and then we reopen the file with the open function. We use write in binary mode (“wb”) and write the data back again to the file. With these simple steps, we have encrypted the user data.

Text

Description automatically generated

P9 the code for encryption

In many cases, the ransomware will save the encryption key to a separate file, which will be saved somewhere in the system or sent to the attacker.

The ransomware will prompt a message informing the user that their data has been compromised and that they  need to pay a ransom to get a passcode to decrypt their data.

First, we need to choose a passcode. I went with “Ilovepython.” Next, we start an infinite loop that will display a message for the victim and will wait for user input; if the input matches the passcode, the ransomware will decrypt all files.

The decryption is the same as the encryption. We go through all the files and use the decrypt function. We also read and write the files in binary mode. 

Text

Description automatically generated

P10 the code for decryption 

Now that we have finished the code, it is time to test it. We created a test directory before called userdata and it has two folders, userphotos and usertxtfiles. The following is the content of these two folders:

Graphical user interface, application

Description automatically generated

P11 the content of userphotos

Graphical user interface, application

Description automatically generated

P12 content of usertxtfiles

Let’s run our ransomware and check to see what happens:

Text

Description automatically generated

P13 running the ransomware.

Looking at the content of the text files, we can see that their content is encrypted:

Text

Description automatically generated

P14 content of creditinfo.txt encrypted
Text

Description automatically generated

P15 content of passwords.txt encrypted.

The images are also lost, as we can’t open them:

Graphical user interface, application, Teams

Description automatically generated

P16 message cannot be shown. 

To get his data back, the user needs to pay the ransom, or they can try to brute force the passcode or the encryption key. This technique  will take a very long time and will cost more than paying the ransom.   So let’s say that the user paid the ransom and got the passcode:

Text

Description automatically generated

P17 passing the right passcode to the ransomware. 

All files have been decrypted. Let’s check the text files first:

Text

Description automatically generated

P18 the content of the text files


The  photos are also back and visible:

Graphical user interface, application

Description automatically generated

P19 photos 

The code worked seamlessly and  now you know how to write ransomware in Python.

Want to step it up?

If you are interested and want to go one step further (yet on your own responsibility), you can install a library called pyinstaller that will create an exe file for Windows.

To install: open cmd and type pip3 or pip based on the version of Python installed on your system and then install pyinstaller.

<pip install pyinstaller>

Disclaimers and warnings:

1-this code is not saving the encryption key to any file; we are creating it and saving it inside a variable, which means it's saved temporarily in the RAM, and once you enter the passcode or close the program it's gone forever, so in case you ran the program and then decided to quit before entering the passcode, note that all data encrypted is no longer retrievable. 

2- do not try to run this program in a directory other than the one you create for testing as a simple mistake can cost you your data.

3-this program is only for educational purposes; please never use it on anyone, even if it is just a joke.

Conclusion:
In conclusion, we have seen how ransomware works, what are the parts that make it, and how we can write a simple one using the Python language and a couple of libraries and modules. Also, we have seen in action how it works and how dangerous it can be for an unsuspecting victim, so always take caution when downloading files from the internet, as you never know, you might be the next victim of this software.  

On the web:

Fernet Library https://cryptography.io/en/latest/fernet/

Open () function: https://www.w3schools.com/python/ref_func_open.asp

References:

Directory tree:https://www.geeksforgeeks.org/structures-of-directory-in-operating-system/

Os.walk function : https://www.geeksforgeeks.org/os-walk-python/

About the author:

Name: Mohammad Saeed

I graduated in the year 2021 with a bac +5 , specializing in network design and architecture. I’m currently studying cybersecurity at Epita and planning to continue my studies  to obtain a PhD in cybersecurity.


Viewing all articles
Browse latest Browse all 612

Trending Articles