Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically gain root privileges?

I am writing some software (in C++, for Linux/Mac OSX) which runs as a non-privileged user but needs root privileges at some point (to create a new virtual device).

Running this program as root is not a option (mainly for security issues) and I need to know the identity (uid) of the "real" user.

Is there a way to mimic the "sudo" command behavior (ask for user password) to temporarily gain root privileges and perform the particular task ? If so, which functions would I use ?

Thank you very much for your help !

like image 224
ereOn Avatar asked Mar 20 '10 16:03

ereOn


People also ask

How do I give root script privileges?

To give root privileges to a user while executing a shell script, we can use the sudo bash command with the shebang. This will run the shell script as a root user. Example: #!/usr/bin/sudo bash ....

Which command we need to type to gain root privileges?

After typing "su -" and pressing Enter. You'll be prompted for the root password. If you get an "authentication error" message, your root account is likely locked.


1 Answers

If you need root privileges every time, the best thing is to start your program as root and drop them (in a subprocess) with setuid and setgid. That's what apache does when it needs to bind to the restricted port 80.

If gaining root rights is the exception instead of the rule and the program is run interactively, another way is to write a program add_interface and execute

sudo add_interface args 

and let sudo handle authentication for you. Instead of sudo, you may want to use a graphical frontend like gksu, gksudo, kdesu, or kdesudo. I wouldn't try to implement secure password input myself; it can be a tricky problem and you'll probably leave gaping security holes and functionality problems (Do you support fingerprint readers?).

Another alternative is polkit, previously called PolicyKit.

like image 159
phihag Avatar answered Sep 21 '22 06:09

phihag