pythonlinuxprivilege-elevation

Running self or other program as sudo once my Python script knows the password?


I'm researching on Linux hardening and found out that a script can escalate to root once it knows the sudo password of the user.

I want to make a POC.

How can a Python script escalate it self to root once it knows the sudo password? I'm assuming I would have to use subprocesses.

I'm not asking about getting the password. You have to assume that my script already has the password through any of the methods mentioned here https://superuser.com/a/793241


Solution

  • If you go down the subprocess route, then you can use the -S flag on sudo so that you can pass the password through stdin:

    p = subprocess.Popen(['sudo', '-S', 'python', 'my_script.py'], stdin=subprocess.PIPE)
    p.communicate(b'thesudopassword\n')
    

    As far as I am aware it is not possible to elevate the UID of a currently running process to root, however. It would probably be much easier to just launch a new Python or other process as root, as in the example.