I am taking in filenames from "the evil user", and would like to know the most effective way to escape them. Basically, I want to avoid accessing files in lower directories using ../ or similar. I am not using the filenames to execute any code via the shell, so I think most metacharacters are OK. My code does the following:

my $filename = take_user_input();
$filename =~ s/\.\./\\\.\\\./g; # this is the part in question

open IN, "<", $filename or die "Cannot open file '$filename' for input: $!\n";
print join "", <IN>;
close IN;

Do you think this simple regular expression is sufficient, or are there other things I should keep in mind? In case you're wondering: yes this is for a CGI, but I'm not so sure it matters. Nothing further is done with this filename, other than opening it and printing the contents to the browser.


In reply to escaping filenames taken in via user input by revdiablo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.