pythonlinuxrootgksudo

How do I sudo the current process?


Is it possible to use a sudo frontend (like gksudo) to elevate the privileges of the current process? I know I can do the following:

sudo cat /etc/passwd-

But I'm interested in doing this:

sudo-become-root # magic function/command
cat /etc/passwd-

I'm writing in Python. My usecase is that I have a program that runs as the user, but may encounter files to read/write that are root-owned. I'd like to prompt for password, gain root privileges, do what I need, and then optionally drop privileges again.

I know I could separate admin logic and non-admin logic into separate processes, and then just run the admin process as root (with some communication -- policykit/dbus would be a good fit here). But I was hoping for a much simpler (though admittedly more risky) solution.

I'm thinking something like running Solaris's ppriv through sudo to then modify the current process's privileges. Which seems like a hacky-but-workable roundtrip. But as far as I know, linux doesn't offer ppriv.

(I'm surprised this isn't obvious already; it seems like a not-uncommon thing to want and doesn't seem to be a security hole to allow escalation in-process over escalation of a new process.)


Solution

  • Unfortunately, I'm not aware of a way to do what you want to do cleanly. I think your best bet is to make the program setuid (or run it under sudo) and then either do your dirty work and drop permissions, or fork() and drop permissions from one process and keep the other one around to do your root work.

    What you're looking for are the setuid(2) / setreuid(2) / setregid(2) / setgroups(2) calls, but they are all hard wired to not allow you to gain privileges mid-invocation. You can only use them to "give away" privileges, as far as I know.