Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically getting UID and GID from username in Unix?

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 user I want to change to.

Is there a system call to do this? I don't want to hardcode it or parse from /etc/passwd .

Also I'd like to do this programmatically rather than using:

id -u USERNAME

Any help would be greatly appreciated

like image 529
Evan Avatar asked Jun 17 '09 20:06

Evan


People also ask

Which command is used to check users UID GID?

id command in Linux is used to find out user and group names and numeric ID's (UID or group ID) of the current user or any other user in the server.

How do you get UID of a user in Linux?

You can find UID stored in the /etc/passwd file. This is the same file that can be used to list all the users in a Linux system. Use a Linux command to view text file and you'll see various information about the users present on your system. The third field here represents the user ID or UID.


2 Answers

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

like image 196
jpalecek Avatar answered Oct 06 '22 00:10

jpalecek


#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;
}
like image 45
Matthew Flaschen Avatar answered Oct 05 '22 23:10

Matthew Flaschen