[!NOTE] This “Programming Thursday” post assumes you know what a variable is. We are moving directly to how Python is used to break systems.

Python is the lingua franca of offensive security. From exploits (PoCs) to C2 frameworks (Mythic, PoshC2), if you can’t read and write Python, you are fighting with one hand tied behind your back. This guide skips the “intro to loops” and focuses on the libraries and techniques used in Red Team development.

1. The Offensive Environment

Before writing code, stop installing libraries globally.

  • Virtual Environments: Always use venv or poetry. Dependency hell is real when mixing impacket versions.
  • Pipx: Use pipx to install tools like crackmapexec or mitm6 in isolated environments so they don’t break each other.
1
2
3
python3 -m venv .venv
source .venv/bin/activate
pip install requests pwntools scapy

2. Low-Level Networking (Sockets vs Requests)

While requests is great for web apps, Red Teamers live in the raw TCP/UDP layer.

The Raw Socket

Custom protocols (like a proprietary C2 or an old SCADA protocol) require raw sockets.

 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
import socket
import sys

def netcat_clone(target_ip, port):
    # 1. Create a raw TCP socket
    # AF_INET = IPv4, SOCK_STREAM = TCP
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.settimeout(5)
        try:
            s.connect((target_ip, port))
            print(f"[+] Connected to {target_ip}:{port}")

            # 2. Send Data (Must be bytes, not string)
            payload = b"HEAD / HTTP/1.0\r\n\r\n"
            s.send(payload)

            # 3. Receive Data
            data = s.recv(4096)
            print(f"[<] Received: \n{data.decode('utf-8', errors='ignore')}")

        except ConnectionRefusedError:
            print("[-] Connection refused.")

if __name__ == "__main__":
    netcat_clone("127.0.0.1", 80)

3. Handling Binary Data (struct)

Exploits and C2 beacons don’t speak JSON; they speak bytes. The struct module is essential for packing and unpacking binary data (Big Endian / Little Endian).

Scenario: You need to parse a custom packet header: [ID (4 bytes)][Flags (2 bytes)][Length (2 bytes)].

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import struct

# Simulating receiving a raw binary buffer
packet_data = b'\xDE\xAD\xBE\xEF\x00\x01\x00\x10' + b'A' * 16

# Unpack:
# ! = Network (Big) Endian
# I = Unsigned Int (4 bytes)
# H = Unsigned Short (2 bytes)
packet_id, flags, length = struct.unpack('!IHH', packet_data[:8])

print(f"ID: {hex(packet_id)}")   # 0xdeadbeef
print(f"Flags: {flags}")         # 1
print(f"Length: {length}")       # 16

4. Interacting with Windows API (ctypes)

Did you know Python can call Windows DLLs directly? This is how offensive Python tools inject shellcode or interact with the OS without compiling C++.

Example: The Pop-up Box (Hello World of Malware)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import ctypes

# Load User32.dll
user32 = ctypes.windll.user32

# Define constants
MB_OK = 0x0

# Call MessageBoxA
# Arguments: (hWnd, lpText, lpCaption, uType)
user32.MessageBoxW(0, "Python says hello from the WinAPI!", "UncleSp1d3r", MB_OK)

Weaponization: This same logic applies to kernel32.VirtualAlloc, kernel32.WriteProcessMemory, and kernel32.CreateRemoteThread. You can write a fully functional shellcode loader in Python using ctypes.

5. Packet Crafting with Scapy

Nmap is noisy. Sometimes you need to craft a specific packet to bypass a firewall or trigger a bug. Scapy is the Swiss Army knife for packets.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from scapy.all import *

# Context: Create a "Christmas Tree" packet (FIN, URG, PSH flags set)
# and send it to port 80.
ip_layer = IP(dst="192.168.1.50")
tcp_layer = TCP(dport=80, flags="FPU")

packet = ip_layer / tcp_layer
response = sr1(packet, timeout=1)

if response:
    response.show()

6. Essential Libraries for the Arsenal

  • Impacket: The bible of Windows network protocols (SMB, Kerberos, DCERPC). Learn it. Love it.
  • Pwntools: Designed for CTFs, but excellent for exploiting binary services and rapid prototyping (buffer overflows).
  • Paramiko: SSH interaction. Great for building SSH botnets or automations.
  • Faker: Generating fake PII (Personally Identifiable Information) to flood phishing portals or pollute exfiltrated databases (Canary tokens).

Conclusion

Python is not just a scripting language; it is an interface to the network stack and the operating system. Don’t just use tools other people wrote. Use Python to extend them, fix them, or build your own bespoke weapons that EDRs have never seen before.

UncleSp1d3r