Re: [OT] checking for legal chars in a filename passed in by upload params?

[prev] [thread] [next] [Date index for 2005/04/11]

From: Scott Gifford
Subject: Re: [OT] checking for legal chars in a filename passed in by upload params?
Date: 15:19 on 11 Apr 2005
Carl Brewer <carl@xx.xxxxxxx.xx.xx> writes:

[...]

> I'm not too worried about the upload filenames, but the defensive
> programmer in me somewhere says if I'm going to write this, I should
> prevent the uploadee from doing bad things.  The uploadee *should*
> be a trusted user, but may not be...  I don't mind a DoS sort of
> thing, but I don't want them being able to scribble outside the
> upload directory.

First, CGI scripts (mod_perl or not) should always be run in taint
mode, which wouldn't let you use the filename directly in a file open,
and in general stops you from doing lots of things that could cause a
security problem.

More specific to your question, I generally do things like:

    $uploaded_filename =~ /^(\w+)$/)
      or die "Dangerous filename!\n";
    $uploaded_filename = $1;

to die on unsafe characters and untaint.  It's always safer to specify
what's a safe character than what's an unsafe character, since it errs
on the side of paranoia.

Dying on any non-word character could confuse users who upload files
with strange names, though.  If you don't care about the filename,
just make one up, and avoid the problem altogether.  If you do, you
could try using URI::Escape before opening the file, and having it
escape all non-word characters:

    uri_escape($uploaded_filename, "\W");

followed by the regexp match above, which should always succeed, but
will satisfy the paranoiac inside you while untainting the escaped
filename.

Hope these hints get you pointed in the right direction,

----ScottG.

Re: [OT] checking for legal chars in a filename passed in by upload params?
Scott Gifford 15:19 on 11 Apr 2005

Generated at 12:49 on 16 Apr 2005 by mariachi v0.52