Yes, your server could run PHP code within an image file if it is not configured correctly:
http://www.phpclasses.org/blog/post/67-PHP-security-exploit-with-GIF-images.html
An example from that is image.gif.php
. A file can be be both a valid image and a valid PHP script, it's not sufficient to simply check image size or other properties. Nor is it sufficient to strip metadata, an uncompressed GIF can contain PHP as image data (though it may be unpretty), PNG supports arbitrary data chunks.
The flaw is accepting uploads with insufficient sanity checking, specifically attempting to prevent unwanted filenames (e.g .php
) by using a non-anchored regex like \.(png|gif|jpg|jpeg)
(no $
anchor), and allowing those images to be served from a directory with PHP processing enabled. Best practise is that you should probably never use a user provided filename as-is.
These are fairly classic data validation and input validation failures.
If you follow the PHP installation instructions (for Apache 2) you'll have something like this in your Apache config:
<FilesMatch "\.ph(p[2-6]?|tml)$">
SetHandler application/x-httpd-php
</FilesMatch>
Note the $
anchor, it will prevent file.php.gif
from being interpreted by PHP.
(What's missing from those instructions is making sure that PHP is limited by a <Directory>
context containing only trusted code, and not writeable by the web server user.)
If you don't follow those instructions, and use mod_mime
's AddType
(or AddHandler
) instead:
AddType application/x-httpd-php .php # STOP!
This can cause the same problem because mod_mime
may do something you don't expect with multiple extensions. See http://blog.dynom.nl/archives/Be-careful-with-double-extensions_20081024_25.html (thanks to Hendrik Brummermann for pointing this out). This risk can be mitigated with correctly configured <Directory>
context to allow only trusted code.
This document (PDF) is a little old, but it covers the mitigations well:
http://www.net-security.org/dl/articles/php-file-upload.pdf
Another possible source of problems is insecure include
/require
statements (also covered in that PDF) which allow an attacker to include
uploaded content by altering query strings or HTTP request headers.
See also the recent related question: Risks of a PHP image upload form
(though I do not think it is correct to rely on getimagesize
to verify images), and
Use PHP to check uploaded image file for malware? (which contains a useful set of links).