I'm trying to write a C program which is supposed to open a file which can only be read/written to by (non-root) User A. When run by users who are neither root nor User A, the program should allow the user to open the file with the effective user being User A.

Currently, my program is able to change euid only if it is run as sudo, which makes sense.

int main(int argc, char const *argv[]) {


    // should be userB's uid
    uid_t ruid = getuid(); 

    uid_t fake_uid = <userA-uid>;
    seteuid(fake_uid);

    /* open, read, write to and close file here */

    // returning euid to original uid
    seteuid(ruid);

    return 0;

}
1

There are 1 best solutions below

1
Ismael Luceno On

Consider using setuid to userA:

chown userA program
chmod 4555 program

Then the program can drop the privilege as soon as it opens the file:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

static void drop_privileges(void)
{
    uid_t uid = getuid();
    if (seteuid(uid)) {
        perror("drop_privileges");
        abort();
    }
}

int main()
{
    /* ... privileged operations */
    drop_privileges();
    /* ... rest */
}