Linux C programming execute as user
If you use fork+exec
you can change euid
of the child process while staying as root in the parent.The code could look something like this:
#include <stdio.h> #include <unistd.h> #include <stdlib.h> int runAs(int gid, int uid, char **env, char *command) { int child = fork(); if (child == 0) { setgid(100); setuid(1000); do { putenv(*env); env++; } while (env != null); exec(command); } else if (child > 0) { waitpid(child); } else { // Error: fork() failed! } } int main(int argc, char *argv[] ) { char *env[3]; if ( argc != 2) { printf("usage: %s command\n",argv[0]); exit(1); } env[0] = "HOME=/home/caroline"; env[1] = "DISPLAY=:0"; env[2] = NULL; runAs(100, 1000, env, argv[1]); env[0] = "HOME=/home/john"; env[1] = "DISPLAY=:1"; runAs(100, 1001, env, argv[1]); return 0; }
From setuid manual: [if caller was root] it is impossible for the program to regain root privileges
.
What are you trying to do? You could set SUID-bit to your program and run it as user - then you could use seteuid to temporary drop root priveleges and become calling user, then reset privileges again. If you really have to run it as root - my guess is that you should fork(), leaving one process as root, and another as setuid().