Will a python subprocess Popen call 'inherit' root privs if the calling script is run with sudo?

StackOverflow https://stackoverflow.com/questions/22233454

  •  10-06-2023
  •  | 
  •  

سؤال

I am writing a python script that will use subprocess Popen (with communicate() I am thinking) to run various shell commands, etc. Often, the shell commands that I am executing would typically be run (manually) with sudo.

I am running the script that uses subprocess with sudo. I am wondering if I can safely leave sudo off all of my subprocess calls or if I need to include it and use stdin to provide a password.

This seems like a pretty simple question, but I have been unable to find the answer yet. From my experimentation, it seems like I might not need to sudo, but I am not sure if that is really true or if it is simply 'working this way' because I have recently provided my password.

EDIT: I figured out how to drop and recover root. Its pretty simple with the multiprocessing package

...
from multiprocessing import Process, Pipe
...
parent_conn, child_conn = Pipe()
p = P(input_list, child_conn)
p.start()
p.join()
return RunSyncReturn(**parent_conn.recv())
...

class P(Process):
    def __init__(self, input_list, conn):
        super(P, self).__init__()
        self._input_list = input_list
        self._conn = conn

    def run(self):
        drop_privileges()
        process = Popen(self._input_list, stdout=PIPE)
        stdout, stderr = process.communicate()
        pmap = {}
        pmap['stdout'] = stdout
        pmap['stderr'] = stderr
        pmap['exit_code'] = process.returncode
        self._conn.send(pmap)
        self._conn.close()

RunSyncReturn is just a data holder class. When the Process launched with the multiprocessing Process class dies, the lowered privileges go away with it.

هل كانت مفيدة؟

المحلول

User IDs and access rights will get inherited by subprocesses. As long as none of the commands you're running is owned by a different user and has the s-bit set, they will run as root as well.

نصائح أخرى

I was hoping to do this: change_privileges(); do_something(); change_privileges('root', 'root')

Instead of trying temporarily to change privileges in the same process, use prexec_fn function to drop privileges only for the child process started by Popen() e.g., look at demote() function.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top