A Python extension I've written requires root access to do a single hardware initialisation call. I'd rather not run the whole script as root just for this one call in my extension, so I would like to write a wrapper to do this initialisation before dropping to user privileges and running the actual script.
I intend for this wrapper to be run via sudo
, eg
$ sudo devwrap python somescript.py
I was considering something like (updated to fix a couple of bugs):
int main(int argc, char * argv[])
{
if(argc < 2) return 0;
int res = do_hardware_init();
if(res != OK_VALUE)
{
// Print error message
return HW_ERR;
}
const char *sudo_uid = getenv("SUDO_UID");
if(sudo_uid)
{
int real_uid = (int) strtol(sudo_uid, NULL, 0);
setuid(real_uid);
}
return execvp(argv[1], &argv[1]); // No return if successful
}
So I have three questions:
- Does this look sane? I don't usually need to mess with the *uid() calls, so I'm not familiar with the usual pitfalls. The
execvp
call also looks a little bizarre, but as far as I can see it has arguments in the right place). - The
execvp
man page says that "The environ array should not be accessed directly by the application" - does this make thegetenv
call a bad idea? - Is there a better call than
execvp
, so I can dosudo devwrap somescript.py
(note absence of "python")