note
Fastolfe
<p>If you really <i>must</i> rely on user-provided data that maps directly to path/filenames, and can't use a token system to represent the same thing, I would explicitely declare what your valid "root" directory is, and do a check like this:</p>
<code>
use CGI ':standard';
use File::Spec 'rel2abs';
my $ROOT = "/var/myapp/docroot/"; # wherever
my $user_path = param('path'); # perhaps s/^\/+// also
my $absolute = rel2abs($user_path, $ROOT);
if ($absolute =~ /^\Q$ROOT/) {
# $absolute is probably within $ROOT, so process it
if (open(INF, "< $absolute")) {
# it's here, do whatever
} else {
# "404 not found"
}
} else {
# ERROR - They've tried to ../ their way out
}
</code>
<p>Keep in mind, though, that this still lets them ../ their way anywhere they want under your declared <code>$ROOT</code>, so if you're expecting a filename to be in a certain place or under a certain hierarchy under your <code>$ROOT</code>, you need to do some additional checking/tokenizing to be sure that it actually does end up there. All this code does is keep the user sandboxed.</p>
<p>I too highly recommend reading [perlsec] and using taint-checking (<code>-T</code>) to better prepare yourself for potentially unsafe user-provided data.</p>
56763
56763