Created
October 12, 2013 00:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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