Yes to all, if you're root (or have CAP_SETGID
).
Perl can do it for you through the $)
($EGID
) variable. Here's a proof of concept script to do exactly that:
#!/usr/bin/perl
use English;
use warnings;
$gid = int $EGID;
$groups = shift;
if ($groups =~ s/^\+//) {
$EGID = "$EGID $groups";
} else {
$EGID = "$gid $gid $groups";
}
system @ARGV;
It takes a space-delimited list of group id's, optionally starting with
a plus; and a command to execute:
# id
uid=0(root) gid=0(root) groups=0(root),44(video),50(staff)
# perl setgroups.pl "" id
uid=0(root) gid=0(root) groups=0(root)
# perl setgroups.pl "20 24" id
uid=0(root) gid=0(root) groups=0(root),20(dialout),24(cdrom)
# perl setgroups.pl "+20 24" id
uid=0(root) gid=0(root) groups=0(root),20(dialout),24(cdrom),44(video),50(staff)
A pre-made tool for doing it is Laurent Bercot's s6-applyuidgid
, which one uses like
s6-applyuidgid -G 20,24 id
However, since you need to be root to change the groups, you are very likely to want to change the user id too. I'll leave that as an exercise to the interested reader, along with changing the primary group id's, and finding the groups by name.
If you want to start from an unprivileged user and gain groups, it's probably easier to use sudo
with -g group
or by making a target user that holds the required groups.