I have a perl script running as root, and from within it I want to execute a system command bar
as a lesser priveleged user foo
. So I have my system
call wrapped as follows:
sub dosys
{
system(@_) == 0
or die "system @_ failed: $?";
}
And so I want to say:
as user foo dosys("bar")
Is there a mechanism within perl or the underlying bash shell that I can use to do this? (I would prefer one that didn't require installing an additional cpan library if possible)
The POSIX
module is a Perl core module, and it includes the functions:
setuid()
setgid()
and related get*id()
functions, though the values are also available through special variables:
$)
and $(
(effective and real GID) $<
and $>
(effective and real UID) You can also try setting those directly (per $EGID and $UID ).
system('su www-data -c whoami')
> www-data
You have to change groups first, remember to quash supplementary groups, and then change user. You'll want to do this in a separate process, so that the [UG]ID changing doesn't affect privs on your root process.
sub su_system {
my $acct = shift;
my $gid = getgrnam $acct; # XXX error checking!
my $uid = getpwnam $acct;
if (fork) { # XXX error checking!
wait;
return $? >> 8;
}
# -- child
$( = $) = "$gid $gid"; # No supp. groups; see perlvar $)
$< = $> = $uid;
exec @_; # XXX not as safe as exec {prog} @argv
# oh, and what if $acct had [ug]id zero? darn
}
Proceed with caution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.