How do i secure a web server's image upload directory?

phpneedshelp99 picture phpneedshelp99 · May 6, 2009 · Viewed 12.3k times · Source

For my web application, people can upload images from a web form to my web server.

What should I set the CHMOD settings for that image upload directory so that people can upload images (from the web server) to that directory but not execute any files they upload for security reasons.

Would the chmod settings be? :

chmod 744 directory/   

Answer

Cheekysoft picture Cheekysoft · May 6, 2009

There are two possible meanings for "executable" in this context, and both are things you need to configure against.

  1. An executable binary file that may run from the command line by typing the file's name into a shell

  2. A file that may be read and processed as script by a web server.

Handling binary-executable

To configure against case 1 on a un*x system, you need to ensure that your upload directory, and files therein, are owned by the web server user and only readable by that user. The directory must be executable; this means that the files inside that directory can be accessed). If the web user needs to list the files in the directory, it must also be readable. It, of course, must also be writable to allow new files to be created.

Thus the octal set you want would be

chown <web-server-user> <upload-dir>
chmod 0700 <upload-dir>

The files must not be executable and should only be readable and writable by the web server,so these should be

chmod 0600 <uploaded-file>

Please note that this means that only the web server user will be able to see these files. This is the best situation for security. However, if you really do need other local users to be able to see these files,then use

chmod 0755 <upload-dir>
chmod 0644 <uploaded-file>

Handling web-server excutable

Coding against case 2 is web server specific.

One option is to place the upload directory outside of the webroot, dissalowing direct URL access to the uploaded files completely and only to serve them via server-side code. Your code reads and echoes the file content, thus ensuring it is never processed as script by the web server

The other option is to configure your web server to not allow script processing of files in the upload directory. This configuration is web-server specific. However, for example, in Apache you can achieve this this by entering into your server configuration:

<Directory "path-to-upload-dir">
  AllowOverride None
  Options -ExecCGI
</Directory>

AllowOverride None is important, as it stops anyone uploading a .htaccess file to your uploads directory and re-configuring the web server permissions for that directory.