LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Run as different user (https://www.linuxquestions.org/questions/programming-9/run-as-different-user-269528/)

Ephracis 12-23-2004 07:20 AM

Run as different user
 
I am setting up my own daemon and are now working with the config-file. I wonder if I should enable running as a different user. How can I do this then?

The language is C++.

My daemon starts, forks and dies, letting the fork be the running daemon.

Hko 12-23-2004 07:55 AM

You say it is a daemon, so I suppose it is started as root, and you want to change to a different user ("drop root privileges" as they say) to increase security of your program.

You can do that like below. Though this is in C, it largely (if not entirely) applies to C++.
Code:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    uid_t uid;  /* user to change to */
    gid_t gid;  /* group to change to */

    /* Change these to your needs */
    uid = 65534;
    gid = 65534;

    /* ... other things ... */

    /* Become daemon */
    if (daemon(0,0) < 0) {
        perror("Error becoming daemon");
        return 1;
    }

    /* Become non-root */
    setregid(gid, gid);
    if (getgid() == 0 || getegid() == 0) {
        perror("Could not drop GID root");
        return 1;
    }

    setuid(uid);
    if (getuid() == 0 || geteuid() == 0) {
        perror("Could not drop UID root");
        return 1;
    }

    /* Start doing work here */

    /*  ...  */

    return 0;
}


Ephracis 12-24-2004 03:50 PM

Ok.. Thanks a lot.

But now I am working on a config-file and I thought that maby it would be better if the user of the program just had to type in the name of the user/group instead of their IDs and then the program could get the uid/gid out of that.

Is that possible?

aluser 12-24-2004 03:56 PM

sure, see getpwnam(3)


All times are GMT -5. The time now is 09:47 AM.