How to programmatically gain root privileges?

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.

Leave a Comment