1

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;

}
  • but... why not just give user A permission to the file?? – KamilCuk Oct 18 '22 at 10:27
  • Add the users who can access the file to a group and give the file group write permission. – stark Oct 18 '22 at 10:35
  • 1
    A clean solution would be to define a group G which is used for the file with sufficient permissions and add this group G as a supplementary group to all users that are supposed to access the file. Or make the program setgid G to allow anyone to access the file by running the program without adding the supplementary group. – Bodo Oct 18 '22 at 12:23
  • @KamilCuk User A already has read/write permissions for the file, I am trying to create a program which will allow users other than User A (and root) temporary access to the file. – strugglecity Oct 18 '22 at 17:44

1 Answers1

1

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 */
}
Ismael Luceno
  • 2,055
  • 15
  • 26
  • 2
    Reorder the `chomd` and `chown` lines. Otherwise, the `chown` command will overwrite the mode settings. – Tinkerer Oct 25 '22 at 03:48