If you really must 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:
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
}
Keep in mind, though, that this still lets them ../ their way anywhere they want under your declared $ROOT, so if you're expecting a filename to be in a certain place or under a certain hierarchy under your $ROOT, 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.
I too highly recommend reading perlsec and using taint-checking (-T) to better prepare yourself for potentially unsafe user-provided data.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|