From: Carlos Date: 2007-09-13T04:29:05+09:00 Subject: Re: secure file writing (escaping characters from the file name) [Constantin Gavrilescu , 2007-09-12 19.39 CEST] > I have a cgi script that writes files on the filesystem. The files are > provided by the users. I need to save them with (almost) the same name > as the user requests. What characters I need to escape? > > This is on linux. Right now the file: "Mick Jagger / Chris Jagger - > Racketeer Blues" does not get saved because of the "/" character. I > don't escape any characters now. I want to keep as many of the original > characters in the file name as I can. For the characters that cannot be > escaped, I suppose I need a translation table... to figure out what was > the original filename. > > Any pointers? More importantly about escaping special characters, and > avoiding directory traversal. You can "semi-URL-escape" the filenames. I mean, use the same method as CGI::escape, but with more characters allowed. Just adapt the original function, adding more characters to the regex to allow them, and taking out the last #tr (spaces to "+")). It is in cgi.rb: def CGI::escape(string) string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do '%' + $1.unpack('H2' * $1.size).join('%').upcase end.tr(' ', '+') end Later, you can easily restore the original filename with CGI::unescape. For Unix/Linux you can let pass any character except "/" and "\000"; for Windows/Mac OS, here is a list of forbidden characters: http://www.xvsxp.com/files/forbidden.php Good luck. --