Secure File Upload in PHP Web Applications

Jan 12, 2009 insic 24 Comments

Various web applications allow users to upload files. Web forums let users upload avatars. Photo galleries let users upload pictures. Social networking web sites may allow uploading pictures, videos, etc. Some prestigious web hosting company already handles much of the security but still it is in developers hand to handle proper uploading of files. Providing file upload function without opening security holes proved to be quite a challenge in PHP web applications. The applications we have tested suffered from a variety of security problems, ranging from arbitrary file disclosure to remote arbitrary code execution. In this article I am going to point out various security holes occurring in file upload implementations and suggest a way to implement a secure file upload.

Naive implementation of file upload

Handling file uploads normally consists of two somewhat independent functions – accepting files from a user and displaying files to the user. Both can be a source of security problems. Let us consider the first naive implementation:

Users will retrieve uploaded files by surfing to http://www.domain-name.com/uploads/filename.jpg

Normally users will upload the files using a web form like the one shown below:

An attacker, however, does not have to use this form. He can write Perl scripts to do uploads or use an intercepting proxy to modify the submitted data to his liking.

This implementation suffers from a major security hole. upload1.php allows users to upload arbitrary files to the uploads/ directory under the web root. A malicious user can upload a PHP file, such as a PHP shell and execute arbitrary commands on the server with the privilege of the web server process.
A PHP shell is a PHP script that allows a user to run arbitrary shell commands on the server. A simple PHP shell is shown below:

If this file is installed on a web server, anybody can execute shell commands on the server by surfing to

More advanced PHP shells can be found on the Internet. Those can allow uploading and downloading arbitrary files, running SQL queries, etc.

The Perl script shown below uploads a PHP shell to the server using upload1.php:

This script uses libwwwperl which is a handy Perl library implementing an HTTP client.

When we run the perl scripts above this is what happens on the wire.

The client request

The server reply

After that we can request the uploaded file, and execute shell commands on the web server:

cURL is a command-line HTTP client available on Unix and Windows. It is a very useful
tool for testing web applications. cURL can be downloaded from http://curl.haxx.se/

Content-type verification

Letting users run arbitrary code on the server and view arbitrary files is usually not the intention of the webmaster. Thus most application take some precautions against it. Consider the following lines of codes.

In this case, if the attacker just tries to upload shell.php, the application will check the MIME type in the upload request and refuse the file as shown in HTTP request and response below:

The client request

The server reply

So far, so good. Unfortunately, there is a way for the attacker to bypass this protection.What the application checks is the value of the Content-type header. In the request above it is set to “text/plain”. However, nothing stops the attacker from setting it to “image/gif”.

After all, the attacker completely controls the request that is being sent. Consider perl script below:

Running this script produces the following HTTP request and response:

The Client Request

The server reply

The perl script changes the Content-type header value to image/gif, which makes upload2.php scripts happily accept the file.

Image file content verification

Instead of trusting the Content-type header a PHP developer might decide to validate the actual content of the uploaded file to make sure that it is indeed an image. The PHP getimagesize() function is often used for that. getimagesize() takes a file name as an argument and returns the size and type of the image. Consider scripts below.

Now if the attacker tries to upload shell.php even if he sets the Content-type header to “image/gif”, upload3.php won’t accept it anymore:

The Client request

The server reply

You would think that now the webmaster can rest assured that nobody can sneak in any file that is not a proper GIF or JPEG image. Unfortunately, this is not enough. A file can be a proper GIF or JPEG image and at the same time a valid PHP script. Most image formats allow a text comment. It is possible to create a perfectly valid image file that contains some PHP code in the comment. When getimagesize() looks at the file, it sees a proper GIF or JPEG image. When the PHP interpreter looks at the file, it sees the executable PHP code inside of some binary garbage. A file like that can be created in any image editor that supports editing GIF or JPEG comment, for example Gimp.

Consider the following perl scripts (sample.pl)

It takes the file insic.gif and uploads it with the name of insic.php. Running this script results in the following HTTP exchange:

The Client Request

The server Reply

Now the attacker can request uploads/insic.php. The PHP interpreter ignores the binary data in the beginning of the image and executes the string “<?php phpinfo(); ?>” in the GIF comment.

File name extension verification

The reader of this document might wonder why don’t we just check and enforce the file extension of the uploaded file? If we do not allow files with the .php extension, the server will not attempt to execute the file no matter what its contents are. Let us consider this approach.

We can make a black list of file extensions and check the file name specified by the user to make sure that it does not have any of the known-bad extensions:

The expression preg_match("/$item$/i", $_FILES['userfile']['name']) matches the file name specified by the user against the item in the blacklist. The “i” modifier make the regular expression case-insensitive. If the file name matches one of the items in the blacklist the file is not uploaded.

If we try to upload a file with the extension which is in the blacklist, it is being refused.

So, can we stop worrying now? Uhm, unfortunately, the answer is still no. What file extensions will be passed on to the PHP interpreter will depend on the server configuration. A developer often has no knowledge and no control over the configuration of the web server where his application is running. We have seen web servers configured to pass files with .html and .js extensions to PHP. Some web applications may require that files with .gif or .jpeg extensions are interpreted by PHP (this often happens when images, for example graphs and charts, are dynamically generated on the server by a PHP script).

Even if we know exactly what file extensions are interpreted by PHP now, we have no guarantee that this does not change at some point in the future, when some other application is installed on the web server. By that time everybody is bound to forget that the security of our server depends on this setting.

Particular care has to be taken with regards to writable web directories if you are running PHP on Microsoft IIS. As opposed to Apache, Microsoft IIS supports “PUT” HTTP requests, which allow users to upload files directly, without using an upload PHP page. PUT requests can be used to upload a file to the web server if the file system permissions allow IIS (which is running as IUSR_MACHINENAME) to write to the directory and if IIS permissions for the directory allow writing.

To allow uploads using a PHP script you need to change file system permissions to make the directory writable. It is very important to make sure that IIS permissions do not allow writing. Otherwise users will be able to upload arbitrary files to the server using PUT requests, bypassing any checks you might have implemented in your PHP upload script.

Indirect access to the uploaded files

The solution is to prevent the users from requesting uploaded files directly. This means either storing the files outside of the web root or creating a directory under the web root and blocking web access to it in the Apache configuration or in a .htaccess file. Consider the next example:

The users cannot just surf to /uploads/ to view the uploaded files, so we need to provide an additional script for retrieving the files:

The sample scripts in viewing the file.

The file viewing script above suffers from a directory traversal vulnerability. A malicious user can use this script to read any file readable the web server process. For example accessing view5.php as http://www.example.com/view5.php?name=../../../etc/passwd will most probably return the contents of /etc/passwd.

Local file inclusion attacks

The last implementation stores the uploaded files outside of the web root where they cannot be accessed and executed directly. Although it is reasonably secure, an attacker may have a chance to take advantage of it if the application suffers from another common flaw – local file inclusion vulnerability. Suppose we have some other page in our web application that contains the following code:

This is a common piece of code that usually occurs in multi-language web applications. Similar code can provide different layouts depending on user preference.

This code suffers from a local file inclusion vulnerability. The attacker can make this page include any file on the file system with the .php extension, for example:

This request makes local_include.php include and execute “language/../../../../../../../../tmp/phpinfo.php” which is simply /tmp/phpinfo.php. The attacker can only execute the files that are already on the system, so his possibilities are rather

However, if the attacker is able to upload files, even outside the web root, and he knows the name and location of the uploaded file, by including his uploaded file he can run arbitrary code on the server.

Reference implementation

The solution for that is to prevent the attacker from knowing the name of the file. This can be done by randomly generating file names and keeping track of them in a database. Consider the code below.

File Upload Script:

Viewing uploaded file:

Now the uploaded files cannot be requested and executed directly (because they are stored outside of web root). They cannot be used in local file inclusion attacks, because the attacker has no way of knowing the name of his file used on the file system. The viewing part fixes the directory traversal problem, because the files are referred to by a numeric index in the database, not any part of the file name. I would also like to point out the use of the PEAR::DB module and prepared statements for SQL queries. The SQL statement uses question marks as placeholders for the query parameters. When the data received from the user is passed into the query, the values are automatically quoted,
preventing SQL injection problems.

An alternative to storing files on the file system is keeping file data directly in the database as a BLOB. This approach has the advantage that everything related to the application is stored either under the web root or in the database. This approach probably wouldn’t be a good solution for large files or if the performance is critical.

Download the PDF Source

About the author: insic

Subscribe in my RSS Feed for more updates on Web Design and Development related articles. Follow me on twitter or drop a message to my inbox.

  • http://blog.wardelldesign.com/ Wardell

    Great Tips! I think content and extension verification are probably two of the most important.

  • http://www.jhaygamba.com Jhay

    Thanks for the great tips! :)

  • centaur

    All important (as I know) approaches covered in one article.
    Very nice

  • http://swapnilsarwe.phpnet.us/ Swapnil Sarwe

    Very nice article. Thinking of making a not of it and put it into one good library, for the projects.

    Thanx a lot.

  • webtuto

    that was great gee , i love it

    tryo to do video tutorials :d

  • http://www.pushingbuttons.net Timothy

    Nice tutorial. Keep it up

  • TravelingPerson

    Damn, I thought all the PHP/Perl code snippets were images you screenshotted from elsewhere, but you wrote all those yourself just for this blog? Yikes, you know your stuff.

  • http://polymath.mit.edu/blog Adam Schwartz

    Great post. Very thorough and very useful.

    Though I’m curious about this example from your post.


    $uploaddir = ‘/var/spool/uploads/’;

    $name = $_GET['name'];


    Forgive my ignorance, but are you suggesting that




    would read the same file? I guess I’m saying, I always assumed that using ellipses in the middle of a nested folder sequence would evaluate as an error or something. No?

  • http://abcoder.com Adnan

    Nice tips. But one thing I wanna add. If the file name contains any special characters, for example !@#$%^&*()’”.jpg this will cause a lot of problems. If the uploaded image is kept with this name lightbox and many other javascript function won’t work. So you must remove the special characters from file name.


  • http://www.wrichards.com Bill

    Nice tutorial :) I would suggest using exif_imagetype() to verify image type instead but you have a nice approach to everything. Look forwards to seeing more from you.

    Take care :)

  • http://janckos.net Janckos

    Muy buen tutorial, gracias!.

  • inf3rno

    Nice article!
    Probably if you put the content of the file to the database, then you dont need the original name, and filesystem access.

  • nazim

    how can file upload in user admin panel in php ?

  • http://farinspace.com Dimas

    Very thorough tutorial and excellent points about security.

  • http://kaizentech.co.uk kaizentech

    Nice Tips Here. There are lots of security risks for uploading file to server since it allows executable files to upload also. One of the solutions is to check file extension by JavaScript before submitting upload form and don’t allow users to upload risky file extensions.

  • http://myfacefriends.com Myfacefriends

    this is wonderful tutorial including security issue… many thanks.

  • http://www.split5.com SplitFive

    This is really a nice tutorial.

  • John kerry

    Good jonb Thanks!

  • Pingback: Seguridad en Upload de Archivos | unijimpe

  • Pingback: Hack all the world - Open Penetration Testing - Focusecurity.Org

  • Pingback: opasylum.net» Blog Archive » bookmarks for using.

  • Pingback: CakePHP 2.3 File Upload? « CakePHP Articles

  • Pingback: Huge List of Pentesting links.. Nice, makes me want to create a huge links database now | HåCkDÖx

  • Pingback: Hacker Media