Domanda

Sto cercando di usare setuid () e setgid () per impostare i rispettivi ID di un programma per eliminare i privilegi dalla radice, ma per usarli ho bisogno di conoscere l'UID e il GID dell'utente che voglio cambiare a.

Esiste una chiamata di sistema per farlo? Non voglio codificarlo o analizzarlo da / etc / passwd.

Inoltre, vorrei farlo a livello di programmazione anziché utilizzare:

id -u USERNAME

Qualsiasi aiuto sarebbe molto apprezzato

È stato utile?

Soluzione

Dai un'occhiata alle getpwnam () e getgrnam () funzioni.

Altri suggerimenti

Si desidera utilizzare la famiglia di chiamate di sistema getpw *, generalmente in pwd.h . È essenzialmente un'interfaccia di livello C per le informazioni in / etc / passwd.

#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;
}

Guarda getpwnam e struct passwd.

Puoi utilizzare i seguenti snippet di codice:

#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;
}

Rif: getpwnam () getgrnam ()

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top