I have the following code snippet.
char *const parmList[] = {"sh", "-c", "whoami", NULL};
if(geteuid() == 0) {
seteuid(atoi(getenv("SUDO_UID")));
}
posix_spawn(&pid, "/bin/sh", NULL, NULL, parmList, environ);
From my understanding the default behavior of posix_spawn
is:
If the
POSIX_SPAWN_RESETIDS
flag is not set, the child process shall inherit the parent process' effective user ID.
However, when I run my program with sudo
, I still get root
as the output from posix_spawn
. How do I have it so posix_spawn will run as the original user? Is there a better way to do this?
I ended up accomplishing this by creating a function that fork
s then exec
s
pid_t runCmd(char *cmd) {
if(!cmd) return -1;
pid_t ans = fork();
if(ans == 0) {
if(geteuid() == 0) {
int uid = atoi(getenv("SUDO_UID"));
setreuid(uid, uid);
}
if(verbose_flag) println("uid %d; euid %d", getuid(), geteuid());
char *const parmList[] = {"sh", "-c", cmd, NULL};
execv("/bin/sh", parmList);
}
return ans;
}
whoami
now returns the original user