Brendan Long
Brendan Long

Reputation: 54242

A method to change effective user id of a running program?

I'm writing a simple package manager and I'd like to automatically try sudo if the program isn't run as root. I found a function called seteuid, which looks likes it's exactly what I need, but I don't have the permissions to run it. So far all I can think of is a bash script to check before they get to the actual binary, but I'd like to do this all as C++ if possible.

Is there any method of changing a processes's euid after it starts executing? Or a way to call sudo?

Upvotes: 4

Views: 3334

Answers (2)

caf
caf

Reputation: 239011

As bmargulies says in his answer, you can do this if you binary is owned by root and has the setuid bit set - but then you will need to implement the authentication part (checking that the user is actually allowed to become root) yourself too.

You'd be essentially rewriting sudo within your application - the best way to handle this is to do what you suggested yourself, and install your application with a wrapper script that uses /usr/bin/id to check if it is root, and if not, call out to sudo (or su).

Upvotes: 3

bmargulies
bmargulies

Reputation: 100013

Here's how these functions work.

If a program has the setuid bit, it will execute as it's owner. Once it is executing, it can call seteuid to run as the original user instead of its owner. Ditty for setgid.

The principle is the principal of least privilege. If I write a program that needs special access, I want as little code as possible to run with the access. So, I install it setuid, but the first thing it does it give back the privileges until the narrow window of code that needs them.

You can't call sudo (except, of course, via fork/exec). You can be a program like sudo that is installed setuid and which decided when to use that awesome power appropriately.

Upvotes: 4

Related Questions