You are not logged in.

#1 2022-11-13 00:13:08

lfitzgerald
Member
Registered: 2021-07-16
Posts: 110

Python: How to do privilege escalation?

I am working on a Python program that will edit various files on the computer. Some of these files are protected, like stuff in /etc. When the program encounters such a file (I suppose I would catch some permission related exception), I would like it to prompt the user for sudo password. This should be cached and the program should not repeatedly ask the user for each file. Ideally, running the program twice in quick succession should also not ask for a password again, but I understand this may be difficult to do.

What is a good way to accomplish this?

Offline

#2 2022-11-13 04:05:19

mpan
Member
Registered: 2012-08-01
Posts: 950
Website

Re: Python: How to do privilege escalation?

If the user wishes to give a script root privileges, they should do that explicitly — e.g. by using sudo. If they didn’t want to grant such access, the program should not attempt to circumvent that decision.

An external setuid-ed binary may be invoked to perform a specific privileged task, or an already privileged daemon may offer API to play with protected resources. That’s how sudo itself and unprivileged volume mounting in desktop environments work. This feature should be used sparingly and cautiously: it normalizes a security antipattern and it is vulnerable to confused deputy scenario.


Sometimes I seem a bit harsh — don’t get offended too easily! PGP: 7C848198AE93D3BB

Offline

#3 2022-11-13 10:05:25

seth
Member
Registered: 2012-09-03
Posts: 33,622

Re: Python: How to do privilege escalation?

w/o details on what you're trying to do there, edit local copies of all files and the subprocess.Popen to sudo mv them all back as batch at the end.
Do not elevate the entire script (plus I assume that should require to restart it, since you need to elevate the interpreter)

Offline

#4 2022-11-13 10:29:53

DeaD_EyE
Member
Registered: 2022-11-13
Posts: 1

Re: Python: How to do privilege escalation?

It elevates the running program to root and executes it again.
This is not the solution for everything.

import os
import sys


def elevate():
    if os.getuid() != 0:
        cmd = ("sudo", sys.executable, *sys.argv)
        os.execvp("sudo", cmd)


def main():
    elevate()
    print(f"UID after elevation: {os.getuid()}")
    # your main program


if __name__ == "__main__":
    main()

If your program is like a service, then you could use systemd to run your program with different capabilities and user/group.

Offline

Board footer

Powered by FluxBB