Programmatically getting UID and GID from username in Unix?

后端 未结 5 2016
别那么骄傲
别那么骄傲 2020-12-10 12:11

I\'m trying to use setuid() and setgid() to set the respective id\'s of a program to drop privileges down from root, but to use them I need to know the uid and gid of the us

相关标签:
5条回答
  • 2020-12-10 12:49
    #include <sys/types.h>
    #include <pwd.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <stdio.h>
    
    int main()
    {
        char *username = ...
    
        struct passwd *pwd = calloc(1, sizeof(struct passwd));
        if(pwd == NULL)
        {
            fprintf(stderr, "Failed to allocate struct passwd for getpwnam_r.\n");
            exit(1);
        }
        size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX) * sizeof(char);
        char *buffer = malloc(buffer_len);
        if(buffer == NULL)
        {
            fprintf(stderr, "Failed to allocate buffer for getpwnam_r.\n");
            exit(2);
        }
        getpwnam_r(username, pwd, buffer, buffer_len, &pwd);
        if(pwd == NULL)
        {
            fprintf(stderr, "getpwnam_r failed to find requested entry.\n");
            exit(3);
        }
        printf("uid: %d\n", pwd->pw_uid);
        printf("gid: %d\n", pwd->pw_gid);
    
        free(pwd);
        free(buffer);
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-10 12:56

    Look at getpwnam and struct passwd.

    0 讨论(0)
  • 2020-12-10 13:07

    You can use the following code snippets:

    #include <pwd.h>
    #include <grp.h>
    
    gid_t Sandbox::getGroupIdByName(const char *name)
    {
        struct group *grp = getgrnam(name); /* don't free, see getgrnam() for details */
        if(grp == NULL) {
            throw runtime_error(string("Failed to get groupId from groupname : ") + name);
        } 
        return grp->gr_gid;
    }
    
    uid_t Sandbox::getUserIdByName(const char *name)
    {
        struct passwd *pwd = getpwnam(name); /* don't free, see getpwnam() for details */
        if(pwd == NULL) {
            throw runtime_error(string("Failed to get userId from username : ") + name);
        } 
        return pwd->pw_uid;
    }
    

    Ref: getpwnam() getgrnam()

    0 讨论(0)
  • 2020-12-10 13:11

    Have a look at the getpwnam() and getgrnam() functions.

    0 讨论(0)
  • 2020-12-10 13:15

    You want to use the getpw* family of system calls, generally in pwd.h. It's essentially a C-level interface to the information in /etc/passwd.

    0 讨论(0)
提交回复
热议问题