A few bits of documentation to start:
From man 3 system's caveats section:
Do not use system()
from a privileged program (a set-user-ID or set-group-ID program, or a program with capabilities) because strange values for some environment variables might be used to subvert system integrity. For example, PATH
could be manipulated so that an arbitrary program is executed with privilege. Use the exec(3)
family of functions instead, but not execlp(3)
or execvp(3)
(which also use the PATH
environment variable to search for an executable).
system()
will not, in fact, work properly from programs with set-user-ID or set-group-ID privileges on systems on which /bin/sh
is bash version 2: as a security measure, bash 2 drops privileges on startup. Debian uses a different shell, dash(1)
, which does not do this when invoked as sh.)
And from the bash manual's description of the -p
command line argument (Emphasis added):
Turn on privileged mode. In this mode, the $BASH_ENV
and $ENV
files are not processed, shell functions are not inherited from the environment, and the SHELLOPTS
, BASHOPTS
, CDPATH
and GLOBIGNORE
variables, if they appear in the environment, are ignored. If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, these actions are taken and the effective user id is set to the real user id. If the -p option is supplied at startup, the effective user id is not reset. Turning this option off causes the effective user and group ids to be set to the real user and group ids.
So even if your /bin/sh
doesn't drop privileges when run, bash
will when it's run in turn without explicitly telling it not to.
So one option is to scrap using system()
, and do a lower-level fork()
/exec()
of bash -p your-script-name
.
Some other approaches to allowing scripts to run at elevated privileges are mentioned in Allow suid on shell scripts. In particular the answer using setuid()
to change the real UID looks like it's worth investigating.
Or configure sudo
to not require a password for a particular script for a given user.
Also see Why should I not #include <bits/stdc++.h>
?