I've got the following code, but I'm thinking that I need to sanitize the env variables, but I'm not sure how exactly I should sanitize them. I realize there's probably a limit to how much I can sanitize them, but what can I do?
#!/usr/bin/perl
use 5.012;
use warnings;
use autodie;
use Env qw( EDITOR VISUAL );
use File::Temp qw( :seekable );
my $editor = '/usr/bin/nano';
if ( $VISUAL ) {
$editor = $VISUAL;
}
elsif ( $EDITOR ) {
$editor = $EDITOR;
} else {
warn 'set VISUAL and EDITOR env variables not set falling back to nano'
. "\n";
}
my $tmpf = File::Temp->new;
system $editor, $tmpf->filename;
open $tmpf, '<', $tmpf->filename;
print while ( <$tmpf> );
I have only ever done something like this in CGI scripts, so perhaps this is not at all what you're looking for; I'm just hoping it'll help a bit. Here's a modified version of the selection of allowed characters I used, and a code suggestion:
my $editor = '/usr/bin/nano';
my $allowed = 'a-zA-Z0-9.\-_/';
# this is what I did, but you will probably not want to do this...
#$file =~ s/[^$allowed]//go; # Remove every character thats NOT in the OK-list
# check that the variables contain only allowed characters
if ($VISUAL =~ m/^[$allowed]+$/) {
$editor = $VISUAL;
}
elsif ($EDITOR =~ m/^[$allowed]+$/) {
$editor = $EDITOR;
}
else {
# message
}
# The code I have given above should also leave $editor in its default
# state if neither $VISUAL nor $EDITOR has been set, as the condition
# will not be true for empty strings/undef values.
Obviously, you cannot change the environment variables if you notice characters in them which you think shouldn't be there (i.e. characters which are not in the $allowed string), but you could check for the presence of such characters and fall back on your default editor in such a case. This is just my humble suggestion; perhaps an expert on the topic will reply in a while, and you'll get her/his wisdom served on a silver platter :)