views:

681

answers:

6

I'm trying to develop a file uploading module on our new site that allows you to upload any file to our servers. The uploaded file is uploaded to /files, in which the following .htaccess to prevent users from executing i.e a .php file:

<Files *.*>
ForceType applicaton/octet-stream
</Files>

This triggers the browsers download window (at least in FF and Safari), but is it safe to assume the file won't be run on the server using this method? If not, how would you implement such a solution?

+3  A: 

I think the safest thing is to restrict 100% web access to the directory, and have a script like download.php through which you pass a file id that then fetches the appropiate file and outputs it to the browser. However, I am pretty sure that what you have will work and is safe.

Paolo Bergantino
+1  A: 

I think you actually want this:

<Directory /path/to/files>
    SetHandler default-handler
</Directory>

What you have might work in practice, because the server is configured by default not to execute anything unless specifically told to do so, but it doesn't really guarantee that nothing will be executed. ForceType just sets the content type for static files (I'm not sure, but I doubt that it affects executable scripts).

David Zaslavsky
A: 

I agree with Paolo, his way is more secure. There is always the issue of someone exploiting your PHP files to execute an uploaded one. Bad Example:

include_once("/modules/".$_GET["module"].".php");

Where someone passed in module=../Files/exploit

St. John Johnson
+1  A: 

Seconding Paolo's answer, move your files directory out of the accessible path. You can then write the download.php script using PEAR's HTTP_Download module to serve the files.

Brent B
+1  A: 

is it safe to assume the file won't be run on the server using this method?

Kind of, but it depends on what other directives are present in your config; maybe there are other rules set up to allow PHP files to run. If the only way you're enabling PHP is by keying the PHP handler on file type, that should stop PHP executing.

However, stopping PHP executing is just one of your worries. If people upload files that contain active content, such as HTML or Flash — even if the filetype says it's an innocent image — they can gain control of other users' sessions on your site through cross-site scripting (XSS). See http://stackoverflow.com/questions/602539/stop/602904#602904 for some discussion of this.

A ‘download.php’ interface that uses Content-Disposition to always trigger the download box, coupled with storing the files under non-user-supplied filenames like ‘1234.dat’, is much safer.

bobince
A: 

For maximum security, you shuold have the folder containing the uploaded files be mounted from a separate partition with the no-exec flag.

eliego