PHP Security Tip #18

p. When you allow users to upload files, your system may be at risk. Always restrict the file types that you allow. Don’t rely on a blacklist approach.

p. For example, a reasonable blacklist policy would seem to be **Don’t allow the upload of .php files**.

p. That’s a good policy until someone uploads a file named .htaccess. It’s not a PHP file so the blacklist won’t catch it. Placing this line in an .htaccess file and uploading it to a system only protected by a blacklist policy would open the door for the bad guys.

AddType application/x-httpd-php .php .htm

p. They can now upload any .htm file with PHP code in it and start poking around in your system.

p. For example.


p. Chances are good that the above code will give an attacker the name of every config file on the server. The possibilities for attacks are endless, all because of one unprotected upload form your server.

p. Be careful with file uploads and make sure you protect them with a whitelist policy instead. Make sure that the file that has been uploaded is of the type that you want to allow. There are several ways to do this, the easiest (and the easiest to defeat) is by checking the extension of the file uploaded. You can easily throw away any file that does not have the proper extension. However, that’s not the safest way to do it.

p. FOr a more secure check, look into the PECL extension, “FileInfo”:http://pecl.php.net/package/Fileinfo. The documentation for it can be found “here”:http://us3.php.net/manual/en/ref.fileinfo.php. FileInfo examins the contents of the file and tries to guess the content type based specific **magic byte** sequences. Using FileInfo as part of a strict whitelist policy is a much more secure way of allowing users to upload files to your system.

Published: March 28th, 2007 at 1:29
Categories: Uncategorized
Tags:

3 comments to “PHP Security Tip #18”

If the server isn’t yours and you don’t have the extension on the host, hat then?

Too many people here seem to think in one dimension and not on real world terms of hosting which is more common than the self serve solution where you do have access to what you need.

Awesome tip. I used to allow people to upload attachments to their petitions (<a href="http://www.petitionspot.com/">I own this petition site</a>) and I was using the blacklist method until one day I got burned. I never really understood HOW they got me, I found this article via Google and I think this may be how they got me. Needless to say, I may be able to re-open the uploading part of the site/petitions now that I know this. Thanks a lot man, great great help!