본문 바로가기
프로그램 (PHP,Python)

Secure File Upload Check List With PHP

by 날으는물고기 2009. 8. 19.

Secure File Upload Check List With PHP

Uploading file on your website is a very common thing nowadays. Image, zip and many other common file type are the usual things we want our users to be able to upload. However, potential evil files such as .exe, .php and other script files are those that we wish they can never be able to upload on to our server. And i am sure you are like me who will wonder whether my upload handler is secure enough to prevent attacks from coming in. In this article, i will try to list down most of the secure ways to protect our server and business from these potential threat. On the other hand, feel free to share your experience with the readers and me on the security tips you have.

Content Type Verification

Checking the content-type of a file is the first level of verification that many of us will do.

1.<?php
2.#easiest way to verify it is a image file
3.if(!eregi('image/', $_FILES['hpt_files']['type']))
4.{
5.     echo 'Please upload a valid file!';
6.     exit(0);
7.}
8.?>

Although, this can be easily bypass by attacker by changing the Content-type header which we will look at later. Nonetheless, it is something we must always check. Please take note that different MIME type may differ in different web browsers.

Verify Image File Content

Uploading image file is something most application will allow. An attacker can change the content-type to a valid one in order for your script to accept the file. Thus, we will have to ensure that this is really an image file by using getimagesize() in PHP.

1.<?php
2.$imageinfo = getimagesize($_FILES['uploadfile']['tmp_name']);
3.if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && isset($imageinfo))
4.{
5.     echo "Sorry, we only accept GIF and JPEG images\n";
6.     exit(0);
7.}
8.?>

You might want to check on other information as well. However, 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. How? By taking an image file (.jpg) and upload as a php extension file(.php). When getimagesize() look at it, it is a valid image file but when the PHP interpreter looks at it, the PHP code in the comment will be executed and other binary code will be discarded as junk (similar to HTML + PHP + JavaScript). Thus, getimagesize() only provides certain level of verification while many more have to be there in order to fully protect yourself.

Verify File Extension

This is something every upload handler in PHP must do. An attacker can fake the content-type of a file to the server, the extension must be a valid extension for PHP machine to interpret it correctly. Although this is not all of the security measure, this is definitely one of the important verification. I have included both white and black list on the code (although only one of them is required usually) since we won’t know what will happen to the server configuration especially in a shared hosting environment.

01.<?php
02.$filename = strtolower($_FILES['uploadfile']['name']);
03.$whitelist = array("jpg", "png", "gif", "jpeg"); #example of white list
04.$backlist = array("php", "php3", "php4", "phtml","exe"); #example of black list
05.if(!in_array(end(explode(".", $fileName)), $whitelist))
06.{
07.     echo "Invalid file type";
08.     exit(0);
09.}
10.if(in_array(end(explode(".", $fileName)), $backlist))
11.{
12.     echo "Invalid file type";
13.     exit(0);
14.}
15.?>

This way even if an attacker fake their way by changing the content-type, they will not be able to change the fact that the extension is required for the file to be interpreted by the machine. However, what file extensions will be passed on to the PHP interpreter will depend on the server configuration. A developer will have no knowledge or control over the web server configuration. Some web application may require that files with .gif or .jpg extension are interpreted by PHP. Thus, any comment in the image file will be interpreted by the PHP machine as a valid instruction to be executed.

Basically, we can’t guarantee that knowing what file extension is being interpreted by PHP machine can help eliminate all attack and it does not change at some point in the future, when some other application is installed on the web server.

The Upload Folder

We want to prevent users from requesting uploaded files directly. This means that the best place to keep these uploaded files is somewhere outside of the web root (www, public_html, etc.) or creating a directory under the web root and blocking web access to it in the Apache configuration or in a .htaccess file. If the attackers is able to upload some harmful file into your system, this will prevent them from executing the files and enter arbitrary code into the system as they are unable to access the location. Consider the following example,

01.<?php
02.$upload_dir = '/var/domainame/uploads/'; # Outside of web root
03.$upload_file = $uploaddir . basename($_FILES['uploadfile']['name']);
04.if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile))
05.{
06.     echo "Upload Successfully.";
07.     exit(0);
08.}
09.else
10.{
11.     echo "Upload Fail";
12.     exit(0);
13.}
14.?>

This is somehow good but now the web server will not be able to access the directory too! Therefore, we need to provide another file for web server to access and display the file if necessary.

1.<?php
2.$upload_dir = '/var/domainame/uploads/'; # Outside of web root
3.$name = $_GET['name'];
4.readfile($uploaddir.$name);
5.?>

Now, both users and system will be able to access the directory provided that they know the name of the file. However, the above suffer from directory traversal vulnerability where a malicious user can use this script to read any readable file on the system. Consider the following example,

1.http://www.example.com/readfile.php?name=../secret/passwd

This will most probably return the password stored in the server. Therefore, always remember to secure your POST and GET in your PHP script.

IIS PUT Function

If you are running PHP on Microsoft IIS, you will have to take particular care on your writable web directories. Unlike Apache, Microsoft IIS supports ‘PUT’ HTTP requests, which allows users to upload files directly, without using an upload PHP page. However, ‘PUT’ requests can only be used to upload a file to your web directory if the file system permissions allow IIS to write to the directory and if IIS permission allowed writing for that directory.

To prevent this, we have to ensure that IIS permissions do not allow writing although we will have to allow the directory to be writable in order to upload using PHP script. This will caused one of the condition to fail and ‘PUT’ request will not be enable by IIS which is used to bypass all the check you have done on PHP script by using ‘PUT’ request to upload into your directory.

The Include Function

In some script, we tend to use the receive value from users to determine which file to include into the PHP script. This is usually not a good idea as the attacker can execute certain file in your web server. Consider the following example,

01.<?php
02.# ... some code here
03.if(isset($_COOKIE['lang']))
04.     $lang = $_COOKIE['lang'];
05.elseif (isset($_GET['lang']))
06.     $lang = $_GET['lang'];
07.elseif (isset($_GET['lang']))
08.     $lang = $_GET['lang'];
09.else
10.     $lang = 'english';
11.  
12.include("language/$lang.php");
13.# ... some more code here
14.?>

Assuming no filter is done on the data received, we determine the language and include the language file into the page which is a common piece of code for some of you. An attacker can take this flaws and enter a path on the URL to execute certain file in the system. Therefore, it is important to secure your upload function to prevent attacker from execute any file that are harmful to your system.(imagine they are able to upload certain shell or execution command and activate it via the URL)

Random File Name

We talk about how a file name should not be access directly by the users to prevent any form of attack. However, we can still access these file indirectly with the help of another script. But if the attacker do not know the name of the file that he have just uploaded, they might not be able to execute these arbitrary code into your web server. Thus, it is always good to randomly rename your file with md5 or other encryption algorithm. Consider the following example,

01.<?php
02.$filename = $_FILES[$uploadfile]["name"];
03.$save_path = '/var/domainame/uploads/'; # Outside of web root
04.$extension = end(explode(".", $filename)); #extension of the file
05.$renamed = md5($filename. time());      #rename of the file
06.if (!@move_uploaded_file($_FILES[$uploadfile]["tmp_name"], $save_path.$renamed. $extension))
07.{
08.     echo "File could not be saved.";
09.     exit(0);
10.}
11.?>

However, if the uploading is done by yourself through an upload function, renaming these uploaded files might not be good for SEO purposes. Thus, the security measure here are for upload function that allows visitors or external users to upload certain file into your web server. ( basically you don’t trust others than yourself )

Disable Script Execution

You can also try to disabled script execution on the uploaded folder where all the files go. You can do this by writing a .htacess file on the folder.

1.AddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi
2.Options -ExecCGI

This will gives you an extra layer of protection. You can also restrict certain file to be placed into the folder and only allows certain file to be placed into the folder. But remember that if some web application allows your ‘white list’ extension file to be interpreted by php machine, the chances of this protection might not be very useful. Nonetheless, this still serve as one of the many layer of protection for your web serverr.

HTML Upload Size

Although not all browsers do not support this but some still does. This can help provides certain level of protection against upload restriction.

1.<!-- allow 100kb -->
2.<input type="hidden" name="MAX_FILE_SIZE" value="100000" />

PHP Upload Size

We must also restrict the upload size on PHP to prevent any harmful file that is large enough to caused a sever damage to our server (any attack can caused a huge damage anyway). Checking the file size can also help you minimize the amount of disk space needed for your server.

01.<?php
02.#check for appropriate size with php.ini
03.$POST_MAX_SIZE = ini_get('post_max_size');
04.$mul = substr($POST_MAX_SIZE, -1);
05.$mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1)));
06.if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) $error = true;
07.$max_file_size_in_bytes = 2147483647;                  // 2GB in bytes
08.if(!$error)
09.{
10.     #restrict the limit
11.     $file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
12.     if (!$file_size || $file_size > $max_file_size_in_bytes) {
13.          HandleError("File exceeds the maximum allowed size");
14.          exit(0);
15.     }
16.}
17.else
18.{
19.     HandleError("File exceeds the maximum allowed size in php.ini");
20.     exit(0);
21.}
22.?>

You can visit the PHP handing file uploads for more information.

Limit File Upload

DOS attack (Denial of service) might be one of the concern that you have. Users might be able to upload a lot of large files and consume all available disk space which prevented other users from using the service. Hence, certain restriction should be imposed to prevent such cases from happening. The application designer might want to implement a limit on
the size and number of files one user can upload in a given period (a day)

BLOB Type Storage

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. However, this approach probably wouldn’t be a good solution for large files or if the performance is critical.

Verify The Session

You may wish to impose certain security measure by having a session between the upload form and the upload handler to ensure that the user is authenticate to proceed with the upload.

Verify Upload

We must also verify that there is indeed a file being uploaded into the server to process the upload handler script.

01.<?php
02.if (!isset($_FILES[$upload_name])) {
03.     echo "No upload found in \$_FILES for " . $upload_name;
04.     exit(0);
05.} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
06.     echo $uploadErrors[$_FILES[$upload_name]["error"]];
07.     exit(0);
08.} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
09.     echo "Upload failed is_uploaded_file test.";
10.     exit(0);
11.} else if (!isset($_FILES[$upload_name]['name'])) {
12.     echo "File has no name.";
13.     exit(0);
14.}
15.?>

The above is an example to verify whether there is an upload file and whether it is secure to proceed the file that the user has uploaded.

Upload Folder within www

Don’t want your folder to be located outside of www or public_html? There is another solution for this. However, you might need to have dedicated or vps which has root access in order for this to work. Rather than giving write permission to the users, we give to apache instead. You can do this with a chown on the writable folder to apache or nobody and assign 770 permission.

Basically, this will disable public access to file in the directory. Short to say, external users will not be able to execute, read or write on the directory, only Apache is allowed to since it is the owner of the folder.

My Upload Handler

This is the upload handler that i usually rely on which you might be interested.

01.<?php
02.     #check for session
03.     if (isset($_POST["PHPSESSID"]))
04.          session_id($_POST["PHPSESSID"]);
05.     else if (isset($_GET["PHPSESSID"]))
06.          session_id($_GET["PHPSESSID"]);
07.     else
08.     {
09.          HandleError("No Session was found.");
10.     }
11.     session_start();
12.// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
13.     $POST_MAX_SIZE = ini_get('post_max_size');
14.     $unit = strtoupper(substr($POST_MAX_SIZE, -1));
15.     $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
16.  
17.     if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
18.          HandleError("POST exceeded maximum allowed size.");
19.  
20.// Settings
21.     $save_path = getcwd() . "/uploads/";                   // The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
22.     $upload_name = "Filedata";                                  // change this accordingly
23.     $max_file_size_in_bytes = 2147483647;                  // 2GB in bytes
24.     $whitelist = array("jpg", "png", "gif", "jpeg");  // Allowed file extensions
25.     $backlist = array("php", "php3", "php4", "phtml","exe"); // Restrict file extensions
26.     $valid_chars_regex = 'A-Za-z0-9_-\s ';// Characters allowed in the file name (in a Regular Expression format)
27.  
28.// Other variables
29.     $MAX_FILENAME_LENGTH = 260;
30.     $file_name = "";
31.     $file_extension = "";
32.     $uploadErrors = array(
33.        0=>"There is no error, the file uploaded with success",
34.        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
35.        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
36.        3=>"The uploaded file was only partially uploaded",
37.        4=>"No file was uploaded",
38.        6=>"Missing a temporary folder"
39.     );
40.  
41.// Validate the upload
42.     if (!isset($_FILES[$upload_name]))
43.          HandleError("No upload found in \$_FILES for " . $upload_name);
44.     else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0)
45.          HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
46.     else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"]))
47.          HandleError("Upload failed is_uploaded_file test.");
48.     else if (!isset($_FILES[$upload_name]['name']))
49.          HandleError("File has no name.");
50.  
51.// Validate the file size (Warning: the largest files supported by this code is 2GB)
52.     $file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
53.     if (!$file_size || $file_size > $max_file_size_in_bytes)
54.          HandleError("File exceeds the maximum allowed size");
55.  
56.     if ($file_size <= 0)
57.          HandleError("File size outside allowed lower bound");
58.// Validate its a MIME Images (Take note that not all MIME is the same across different browser, especially when its zip file)
59.     if(!eregi('image/', $_FILES[$upload_name]['type']))
60.          HandleError('Please upload a valid file!');
61.  
62.// Validate that it is an image
63.     $imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
64.     if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && isset($imageinfo))
65.          HandleError("Sorry, we only accept GIF and JPEG images");
66.  
67.// Validate file name (for our purposes we'll just remove invalid characters)
68.     $file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", strtolower(basename($_FILES[$upload_name]['name'])));
69.     if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH)
70.          HandleError("Invalid file name");
71.  
72.// Validate that we won't over-write an existing file
73.     if (file_exists($save_path . $file_name))
74.          HandleError("File with this name already exists");
75.  
76.// Validate file extension
77.     if(!in_array(end(explode(".", $file_name)), $whitelist))
78.          HandleError("Invalid file extension");
79.     if(in_array(end(explode(".", $file_name)), $backlist))
80.          HandleError("Invalid file extension");
81.// Rename the file to be saved
82.     $file_name = md5($file_name. time());
83.  
84.// Verify! Upload the file
85.     if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
86.          HandleError("File could not be saved.");
87.     }
88.     exit(0);
89.  
90./* Handles the error output. */
91.function HandleError($message) {
92.     echo $message;
93.     exit(0);
94.}
95.?>

Conclusion

This is not a full proof solution for your file upload handler. However, this can used as references and also discussion that can help enhance the overall security of our web application today.


원문 : http://hungred.com/2009/08/17/useful-information/secure-file-upload-check-list-php/

728x90

댓글