Locking a script to a given user with Perl

From a security point of view it is useful if you lock sensitive scripts (for example things which download untrusted data from the Internet) to run with a low privileged user. However it is also a good idea to make sure programatically that they are run only with the given user. One possible solution (which I will present today) is to create a module which checks the current user (and dies if it isn’t what you expected) and include it in your scripts. The module can be something like the following:

package LimitedUser;

use strict;
use warnings;

 if (not $^C) {
  my $expected_user = 'limited_user';
  if ($expected_user ne getlogin()) {
   require Term::ANSIScreen;
   my $message = qq{This script can only be launched from the account "$expected_user"n};
   print STDERR color('bold'), color('red'), $message, color('reset');     


Now lets look at this script a little. First of, it does its work very early on, in a BEGIN block. This means that if you import this module with use (rather than require), it will run before most other code gets a chance to run, and prevent them from running if the current user is not the one expected.

Second of, it checks the $^C variable to see if we are only compiling the script (which is often used to syntax check them, although it does slightly more than a plain syntax check in other languages). If this is the case, the user check is not performed, so that development can be done using any user.

The script has been tested on both Windows and Linux and should work without any problems.

3 responses to “Locking a script to a given user with Perl”

  1. how to disallow the root user even?
    say if I login as ‘appuser’ and do a sudo to become ‘root’, still getlogin gives me ‘appuser’ not ‘root’

  2. I use the method on Windows to prevent the scripts from accidentally being executed as other than the intended user, so I regret to say, but I don’t know how to do it.

Leave a Reply

Your email address will not be published.