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