githubEdit

library-path

In python, each version has specified order in which libraries are searched and imported from. The order in which python imports modules from are based on a priority system, meaning that paths higher on the list take priority over ones lower on the list. We can see this by issuing the following command:

PYTHONPATH listing (list python paths)

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

Two prerequisites are necessary.

  • The module that is imported by the script is located under one of the lower priority paths listed via the PYTHONPATH variable.

  • We must have write permissions to one of the paths having a higher priority on the list.

Use sudo -l absolute path to run commands with sudo

Therefore, if the imported module is located in a path lower on the list and a higher priority path is editable by our user, we can create a module ourselves with the same name and include our own desired functions. Since the higher priority path is read earlier and examined for the module in question, Python accesses the first hit it finds and imports it before reaching the original and intended module.

Check misconfigure directory permission (psutil installation location)

pip3 show psutil

Misconfigured python dir

ls -la /usr/lib/python3.8

Create a file "psutil.py" in /usr/lib/python3.8 dir (Hijack module content - psutil.py)

#!/usr/bin/env python3
import os

def virtual_memory():
	os.system('id')

Privilege escalation via Hijacking python library path

Last updated