Most modern Unix systems use PAM to handle authentication. The
pam_unix module is the one that does password authentication against
However, you shouldn't reinvent the wheel. Asking for the user's password and running as root is a basic configuration of sudo, the de facto standard way to elevate privileges. Note that properly elevating privileges is tricky: did you remember to purge all environment variables that could affect your program? Sudo takes pains to do it safely.
To allow user
alice to run
/usr/local/bin/myprogram as root with any arguments of her choice after typing her password, use the following line in the
sudoers file (the sudo configuration file):
alice ALL = (root) /usr/local/bin/myprogram
To edit the
sudoers file, run the command
Alice will have to run
sudo myprogram. If you want her to be able to type just the program name, hide this in a wrapper script. But note that Alice may prefer to run something like
gksudo myprogram to get a GUI prompt.
Many variations are possible, including forbidding the caller from passing arguments:
alice ALL = (root) /usr/local/bin/myprogram ""
or applying the entry to a group:
%mygroup ALL = (root) /usr/local/bin/myprogram
If your program needs to know who invoked it, sudo makes that available in the environment variables