Search code examples
pythonfork

python os.fork() for performing operation under degraded credentials


I'm looking to implement the following command in python.

su ${USER} -c "whoami"

which simply create child process which runs under different privilege, and return the result of whoami back to the parent process.

As bash works, It should be done using os.fork() while the result is retrieved to parent process once the Chile process terminate its work.

def runWhoamiOtherUser(self):
    pid = os.fork()
    if pid == 0:
        os.setuid(getpwnam(os.environ['USER'])[2])
        x = getpass.getuser()
        return x

    pid, status = os.waitpid(pid, 0)

Is this the right way to do it ?


Solution

  • It has been added as a new feature to the subprocess module in Python 3.9, to the subprocess.Popen constructor:

    New in version 3.9.

    If user is not None, the setreuid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up via pwd.getpwnam() and the value in pw_uid will be used. If the value is an integer, it will be passed verbatim. (POSIX only)

    https://docs.python.org/3.9/library/subprocess.html

    Before 3.9, probably best to use that same setreuid() call. Same facilities are there for changing the group too, if you prefer that to user. The code was added in this commit, if you wanna check the specifics of the setting and maybe copy-paste the relevant part to your program: https://github.com/python/cpython/commit/2b2ead74382513d0bb9ef34504e283a71e6a706f