Tuesday, June 28, 2011

Passing environmental variables through sudo in Perl

In the process of writing a set of backup scripts in Perl, I ran into a slight caveat with my overall design - after `rsync`'ing the files to be backed up to it's working directory, the backup user does not have the permissions to be able to delete the files before doing a clean backup. To solve this, I created a subscript that when called, checks the parent process for authorization and configuration, and then chown's the working directory to the calling user, in this case backup.

Now comes the question of how to determine the calling user. `sudo -E` allows us to pass environmental variables through sudo. Here is an example:

ben@******:~$ sudo -E whoami
root
ben@******:~$ sudo -E echo $USER
ben
 The problem with doing this in Perl however seems to be that when you do a system() call, Perl opens a new subshell, which for some reason recognizes the $USER environmental variable as 'root', though it keeps some of the other variables.

To work around this issue, we can do as follows:

#!/usr/bin/perl
# script.pl
use strict;

$ENV{'IAM'} = $ENV{'USER'};
system('sudo -E /usr/local/bin/subscript.pl');

...

#!/usr/bin/perl
# subscript.pl
use strict;

my $iam = `echo -n \$IAM`;
say $iam;
 Now the subscript can determine who the "backup" user is in a fairly agnostic way, and just grant permissions, rather than smiting the directory itself. It performs the minimum necessary action with superuser privileges, which should be the goal.

You can even `chmod` subscript.pl to 750 and then just add an entry to your /etc/sudoers file like this:

backup ALL=(ALL) SETENV:NOPASSWD: /usr/local/bin/subscript.pl
 I'm certain it would be possible to lock this process down even more if necessary. Your mileage may vary with older versions of sudo.

mu



Tuesday, June 14, 2011

In case of F5 break glass

while true; do renice -15 `ps ax | grep cgi | awk '{print $1}' | xargs`; sleep 5; done
A one-liner that has helped me out. Force throughput on a named process, in this case, processes containing the string "cgi" in their name.

Saturday, June 11, 2011

PPTP VPN with Android + m0n0wall

So I finally got the chance this past week to play around with a beefy network device given to me by my friend, Michael Adams, about 3 or 4 years ago. More after the jump.