in reply to escaping filenames taken in via user input

Sure, you think so. Do you know?

What if I add a ; in the command and make the shell execute another command than you intended to as well?

You shouldn't even try to escape - check whether there's any character in your input that you didn't explicitly allow and if so, reject that input. The only way to achieve security is with a "default deny" policy that only explicitly allows known good input, rather than "default accept" that tries to reject known bad input. Someone may come up with a new way to pass bad input that slips through your filters, and bam.

You should if at all possible avoid the shell, too.

Maybe if you explain what you're really trying to do, someone could point you in a better direction.

Makeshifts last the longest.

  • Comment on Re: escaping filenames taken in via user input

Replies are listed 'Best First'.
Re: Re: escaping filenames taken in via user input
by revdiablo (Prior) on Oct 30, 2002 at 00:34 UTC

    I do avoid the shell, as I stated. The only thing I do with the filename is pass it to Perl's builtin open.

    As for what this CGI does; it takes a filename in and prints the contents of it to the browser. That's all. Literally. :) I eventually plan to add logging and possibly access control. I realize web servers already handle all these tasks exceptionally well, but the problem is I don't have access to the web server logs or configuration. This CGI is a workaround for the restricted system I'm using to host my site.

      Right. Then I'd say reject any filename that contains a dot - simple as that. Also, use the three-argument form of open as in open FH, "<", $filename; to avoid having tricks played on you with the magic open features of the two-argument forum. See Ovid's excellent CGI course for more information on the topic of security in CGI scripts.

      Makeshifts last the longest.

      the problem is I don't have access to the web server logs or configuration

      so it seems that your "evil user" has more access than you do. You are only escaping .. s/\.\./\\\.\\\./g; so if I supply /etc/passwd as my input, how does your script handle it?

      You probably should split the path into its components, and then decide from there what the file is.


      He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

      Chady | http://chady.net/

        Oops, forgot to mention an absolute pathname is appended on the front of the specified filename. I guess my sample code wasn't exactly representative of the real code. I didn't have access to it at the time I made the post, and paraphrased for the sake of brevity... I suppose next time I'll post the actual code. :)