4

I'd like to fork and exec and program as a non root user while the parent retains root permissions.

pseudo code:

  pid = fork();

  if (pid == 0) {
      if (RunAsUser(ConvertStringToUserId("John")) == false) {
          stop();
      }
      if (RunAsUser(ConvertStringToUserId("admin")) == true) {
          stop();
      }
      CreateProcess();
  }
chrk
  • 4,037
  • 2
  • 39
  • 47
clockley1
  • 464
  • 5
  • 16

2 Answers2

4

If you want to drop privileges in C code, use the function setuid.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
  • To get the uid for setuid will I need to search /etc/passwd? – clockley1 Aug 21 '14 at 20:16
  • 3
    If you need to adjust groups, remember to do that before changing the user privileges. – Jonathan Leffler Aug 21 '14 at 20:23
  • 2
    To get the UID for `setuid()`, use `getpwnam()`, which logically searches `/etc/passwd` -- unless you've got other name services (LDAP, etc) in use as well or instead. – Jonathan Leffler Aug 21 '14 at 20:24
  • see http://stackoverflow.com/questions/1009254/programatically-getting-uid-and-gid-from-username-in-unix to know how to get `uid` from `username` – pqnet Aug 21 '14 at 20:24
0

Get your program to invoke the child process as

sudo -u user /path/to/externalprogram

instead of just

/path/to/externalprogram
chiastic-security
  • 20,430
  • 4
  • 39
  • 67
  • no. OP wants to **DROP** root privileges, not gain them. – Marc B Aug 21 '14 at 20:10
  • 1
    That IS how to drop root privileges. If you're root, running `sudo -u user prog` will run `prog` as user `user`. – chiastic-security Aug 21 '14 at 20:11
  • Spawn a new process that basically only does a `seduid()` call? – amphetamachine Aug 21 '14 at 20:11
  • But OP wants to do it on a forked child, not on the entire process. – Marc B Aug 21 '14 at 20:13
  • 1
    Yes. If his program runs `sudo -u user prog` as a child process, that child process will run as `user`. – chiastic-security Aug 21 '14 at 20:15
  • Of the two answers this is the most straightforward one. As I'll be collecting the user name not the uid(whatever that is.) sudo makes the most sense. I would prefer to use setsid but it's impossible to find a way to translate a username to a uid. – clockley1 Aug 21 '14 at 20:24
  • @user1450181 there is, see my comment on Wojtek Surowka's answer. `sudo`, or better `su` because `sudo` may not be installed, makes sense if you want to run a different application. Beware that you are actually forking three time: first fork to shell, which forks to sudo, which forks to the target process. – pqnet Aug 21 '14 at 20:30