Skip to content

Instantly share code, notes, and snippets.

@tommybutler
Created October 12, 2013 00:18
Show Gist options
  • Save tommybutler/6944027 to your computer and use it in GitHub Desktop.
Save tommybutler/6944027 to your computer and use it in GitHub Desktop.
How to drop privileges in a Perl script when initially run as root
BEGIN { # give up root identity and run as an unprivileged user ASAP
use POSIX;
my $run_as = 'user_you_want_to_run_as';
my ( $uid, $gid ) = ( getpwnam $run_as )[ 2, 3 ];
die $! unless $uid && $gid;
if ( $> == 0 )
{
POSIX::setgid( $gid ); # GID must be set before UID!
POSIX::setuid( $uid );
}
elsif ( $> != $uid )
{
warn <<__ABORT__ and exit 1;
** ABORT! **
This application only runs as the "$run_as" user,
not as your user account with ID: $>
__ABORT__
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment