Subject: setegid() magic..
To: None <>
From: Jorgen Lundman <>
List: netbsd-users
Date: 04/21/2003 15:03:47
Just out of curiosity,

If I write a piece of code, run as root, or setuid root, that does:

    F=fopen("testfile", "w");

It creates the file as the user I want. Now I also want to do the same with 
groups, so we add:

    F=fopen("testfile", "w");

It creates the file as 10000, but the group is "wheel". Or to be precise, it is 
the same group as "." of the directory.

Is there a way that I can "become" the user "properly" so items are created both 
as user 10000 and group 10001?

I've tried sticking

    gid_t p = 10001;
    setgroups(1, &p);
    F=fopen("testfile", "w");

Which made no difference, however, in the last example, if I stick
   fchown(fileno(F), -1, 10001);

.. after the fopen then it works in that I am now allowed to chgrp the file (as 
user 10000) to 10001. But it would be nice to become a user, then have all 
open/fopen etc calls just create it the files as I wanted (10000,10001).

Oh and it makes no difference if I use 10001 that isn't in /etc/group, or gid 
20, that is in /etc/group.

I could also seteuid; fopen; seteuid(root); chown(uid,gid).  But wonder if there 
was a better way.


Jorgen Lundman       | <>
Unix Administrator   | +81 (0)3 -5456-2687 ext 1017 (work)
Shibuya-ku, Tokyo    | +81 (0)90-5578-8500          (cell)
Japan                | +81 (0)3 -3375-1767          (home)