Hi,
I created a program that needs to be run as root or with `sudo`. In the program, I need to use `execv` to run another program, after forking a new process. I have the following:
Code:
// Fork the process.
switch((pid = fork()))
{
case -1: // Error.
fprintf(stderr, "%s: %s error: fork failed (%s)\n", program_name, __func__, strerror(errno));
exit(EXIT_FAILURE);
case 0: // Child.
// Remove root privileges.
if(setuid(atoi(getenv("SUDO_UID"))) == -1)
{
fprintf(stderr, "%s: %s error: setuid failed (%s)\n", program_name, __func__, strerror(errno));
exit(EXIT_FAILURE);
}
// Proof the UID changed.
printf("2ID: %d\n", atoi(getenv("SUDO_UID")));
// Execute external program.
if(execl(program, program, (char *) NULL) == -1)
{
fprintf(stderr, "%s: %s error: execl failed (%s)\n", program_name, __func__, strerror(errno));
exit(EXIT_FAILURE);
}
}
But the program that is executed lists a bunch of errors because it is not supposed to be run as root.
How can I execute an external program with the original users UID?
**EDIT:
Upon further investigation, it seems it is changing the UID to the original user. The problem seems to stem from the $HOME directory the external program tries to use for reading/writing files. It is trying to use the files under root instead of the user.