http://www.perlmonks.org?node_id=147476


in reply to Security with open() in CGI scripts

...and as an add on to rob_au's excellent post, here's an idea to increase security, especially for open calls and such. Instead of passing directory names and filenames directly from the browser (which means worrying about shell escape characters and such) why not pass tokens that correspond to directories and files that are hard-coded into your script. So instead of
my $template = $theme->{ThemeDir}."index.html";
which makes you worry about $theme->{ThemeDir} why not
my %themes = {1 => '/dir1/', 2 => '/dir2/', 3 => '/dir3/'}; my $theme = param(theme); my $filename = "$themes{$theme}.index.html"; open (FILE, $filename);
Now everything is under control... if $theme ever contains anything it isn't supposed to then the worst thing that can happen is the hash lookup fails and the open fails. No way malicious code can hurt you, all because you insulated your open by using a hash.

Of course, this isn't always practical, but most of the time it's a good idea. This won't work if you let users name their own files, and upload (or create) those files directly on the server, but if you're doing that you're gonna have to jump through more hoops than we've covered here in order to maintain security.

Gary Blackburn
Trained Killer

Replies are listed 'Best First'.
Re: Re: Security with open() in CGI scripts
by brianarn (Chaplain) on Feb 26, 2002 at 05:48 UTC
    Another thought on the token idea here...

    I'd recommend having another file external to the script, which contains some quick perl code to create the token list, such as
    my %tokens = {1 => '/dir1/', 2 => '/dir2/', 3 => '/dir3/};
    <blatently stolen from Gary's reply ;)>

    and then just require this file when you need to reference the token. This way, it's easy to add to the themes without having to find where it's at in some script. I'm personally all about the use of extra files for data like this - it helps keep script sizes smaller and helps to separate the code from the data.

    ~Brian