Kristof Kovacs

Software architect, consultant

Avoiding the file upload exploit

Photo courtesy of nickwheeleroz

If I can upload a file to your website, like, for example, an avatar, a picture, or a document for review, do you protect your website from that file? What happens if I upload, for example, the infamous c99.php as my avatar? Will I be able to access it something like

http://your-site/avatars/username/c99.php

Once malicious code is on the server, it can access all files that your web application accesses, the same databases, the same directories, allowing it to disrupt business, to steal sensitive data, use your server to serve viruses to other people, or set up phishing sites.

How to avoid file upload exploits?

Don't assume that anything that comes from the user can be trusted (again).

(1) Rename all uploaded files, and store the original file name in the database. (This also allows avoiding filename clashes.)

(2/a) Put uploaded files into a directory that is unaccessible from the web server, and serve them from PHP code.

BUT: beware of URLs like download.php?file=../../../../../../etc/passwd

OR

(2/b) Use .htaccess to disable PHP execution in the directory where you put the files.

BUT: beware of file inclusion attacks.