Upload vulnerability to Popular science [1]-file Upload form is a major threat to web security

Source: Internet
Author: User
Tags file system file upload html form http post parent directory php file php code php script

In order for end users to upload files to your site, it is like opening another door to a malicious user who is endangering your server. Even so, in today's modern Internet Web applications, it is a common requirement as it helps to improve your business efficiency. Web applications on social networks such as Facebook and Twitter allow file uploads. Also get them on blogs, forums, e-banking sites, YouTube and enterprise support portals, giving the opportunity to effectively share files with end-users and corporate employees. Allows users to upload pictures, videos, avatars and many other types of files.

The more functionality that is provided to end users, the greater the risk and opportunity for Web applications to be attacked, which can be exploited by malicious users to gain access to a specific website, or to compromise the server's likelihood of being very high.

When testing several Web applications, we noticed that quite a number of well-known web applications did not have a secure file upload format. These vulnerabilities are easily exploited and we can access the server hosting these Web applications to the file system. In this article, we introduce you to 8 common ways in which we have encountered a secure file upload form. It will also show a malicious user who can easily circumvent these security measures. Case 1: Simple file Upload form without any validation

A simple File upload form usually contains an HTML form and a PHP script. HTML forms are presented to the user, and the code that is included in the PHP script that requires file upload functionality. The following is an example of this form and the PHP script:


1 <form enctype= "Multipart/form-data" action= "uploader.php" method= "POST" >
2 <input type= "hidden" name= "max_file_size" value= "100000"/>
3 Choose a file to upload: <input name= "UploadedFile" type= "file"/><br/>
4 <input type= "Submit" value= "Upload File"/>
5 </form>

PHP Code: View Source

1 <?php
2 $target _path = "uploads/";
3 $target _path = $target _path. basename ($_files[' uploadedfile ' [' name ']);
4 if (Move_uploaded_file ($_files[' uploadedfile ' [' tmp_name '], $target _path)) {
5 echo "The file". basename ($_files[' uploadedfile ' [' Name ']). "has been uploaded";
6 echo "There was a error uploading the file, please try again!";
7 } else {
8 }
9 ?>

When PHP receives a POST request and the encoding type is multipart/form-data, it creates a temporary file name in a random temporary directory (for example/Var/tmp/php6yxovs). PHP will also populate the global array $_files information for uploaded files: view source

1 $ _files [' uploadedfile '] [' name ']: The original name of the file on the client
2 $ _files [' uploadedfile '] [' type ']: MIME type of File
3 $ _files [' uploadedfile '] [' size ']: The size of the file (in bytes)
4 $_files [' UploadedFile '] [' not Tmp_name ']: The uploaded file is stored on the server with a temporary filename.

The PHP function Move_uploaded_file moves the temporary files provided by the user to a location. In this case, the destination is the server root directory below. Therefore, the file can be accessed using the URL, such as: Http://www.domain.tld/uploads/uploadedfile.ext. In this simple example, there are no restrictions on the types of files allowed to upload, so an attacker could upload a PHP or net file with malicious code that could lead to a compromise of the server.

This may seem like a naïve example, but we have not encountered such code in some Web applications. case 2:mime Type validation

Another common mistake the web Developer makes sure is that when the file uploads the form, only the MIME type returned from PHP is checked. When a file is uploaded to the server, PHP will set the variable $_files[' uploadedfile ' [' type '] provided by the Web browser client using the MIME type. However, file upload form validation cannot depend on this value. A malicious user can easily use a script or some other automated application that allows sending an HTTP POST request, which lets him send a fake MIME-type file upload. Case 3: Expanding the limits of risk

In another example, we encountered a file upload using the blacklist as a security measure. From the developer collects a list of dangerous hazards, if the file being uploaded is included in the list, Access will be rejected.

One of the main drawbacks of using dangerous file extensions is that it is almost impossible to compile a complete list of all possible extensions that an attacker can use. For example, if your code is running in a managed environment, the list can be endless for a number of scripting languages such as Perl,python and Ruby.

A malicious user can easily bypass the check to upload a file named ". htaccess", which contains a line of code similar to the following:

AddType application/x-httpd-php. jpg

The above line of code instructs the Apacheweb server to execute JPG images as if they were PHP scripts. An attacker can now upload a file with a JPG extension that contains the PHP code. As in the screenshot below, a JPG file is requested via a Web browser that contains the PHP command Phpinfo () function, which is still executed from the Web server:

Case 4: Double extension (part 1th)

The security policies used in this case are very similar to those used in case 3. Although the method is replaced by a simple check file name with an extension, the developer obtains the file extension by looking for the '. ' character in the file name and extracting the string after the dot number.

The way around it is a bit complicated, but it's still realistic. First, let's look at how Apache handles files with multiple extensions. The Apache Handbook has the following statement:
"Files can have multiple extensions, and the order of these extensions is generally irrelevant. For example: If the file welcome.html.fr is mapped to a content type of text/html and the language is French, the file welcome.fr.html will be mapped to the exact same content . If more than one extension is mapped to meta information of the same type, the rightmost one will be used, in addition to the language and content encoding. For example:. gif MIME type is image/gif,. html MIME type is text/html, then welcome.gif.html MIME type will be text/html. "

So a file named ' filename.php.123 ' will be interpreted as a PHP file and executed. This is limited to the last extension (in this case, the. 123) that is not in the Web server's Mime-types is specified in the list. Web developers often do not realize that Apache still has such a ' feature ', which can be dangerous for some reason. After knowing this, an attacker could upload a name called shell.php.123 File and bypass the file upload protection mechanism. The background script will calculate the last extension (. 123) and make the conclusion that the extension is not in the list of dangerous extensions. That being said, it is not possible to prevent a malicious user from using all the random extensions that might be used to upload a file to your Web server. Case 5: Double extension (part 2nd)

A better way to enhance the security of file upload forms is the white list mechanism. In this example, the developer defines a list of known/acceptable extensions and does not allow extensions that are not specified in the list.

However, in some cases the approach does not work as expected. When Apache is configured to execute PHP code, there are two ways to implement the mechanism: Use the AddHandler directive, or use the AddType directive. If the AddHandler instruction is used, all file names that contain the '. php ' extension (for example: '. php ', '. Php.jpg ') are executed as PHP scripts. Therefore, if your Apache configuration file contains the following line, you may be vulnerable to attack:

AddHandler php5-script. php

An attacker could upload a file named ' Filename.php.jpg ' and bypass the protection mechanism and then execute the code in it. Case 6: Checking the picture head

When uploading images only, developers usually use PHP's getimagesize function to detect the image's header information. The function returns the size of the picture when it is called, or False if the picture is invalid, that is, if the picture header information is incorrect. Therefore, a developer generally checks whether the function returns TRUE or FALSE and uses that information to verify the uploaded file. So if a malicious user tries to upload a JPG file with a simple PHP shell embedded in it, the function will return false and he will not be allowed to upload the file. However, even this approach can be easily bypassed. If a picture is opened in a picture editor, like Gimp, the user can edit the annotation area of the picture, where it can be inserted into the PHP code, as shown in the following figure.

The picture still has a valid head; Therefore, the check of the GetImageSize function is bypassed. As you can see from the screenshot below, when an ordinary Web browser requests the diagram, the PHP code inserted into the image's comment area is still executed:

case Seven: Protect the Upload folder with. htaccess

Another popular way to wear pieces of safe file upload forms is to apply. htaccess protect the folder where the files are uploaded. The way to do this is to restrict the execution of the script files in this folder. In this case, a. htaccess file typically contains the following code:

AddHandler cgi-script. php. php3. php4. phtml. pl. py. jsp. asp. htm. shtml. Sh. CGI


The above is another form of blacklist, itself is not very safe. In the PHP manual, in the Move_uploaded_file chapter, there is a warning: if the target file already exists, the original file will be overwritten.

Because the uploaded file can and will overwrite the already existing file of the same name, a malicious user can easily use his own modified. htaccess replace the original. This allows him to execute specific scripts that will help him to compromise the server. Case Eight: Client authentication

Another common security technique used in file upload forms is to validate uploaded files on the client. In general, this technique is more common in ASP. NET applications because ASP. NET provides an easy-to-use validation control.

These validation controls allow the developer to do a regular check of the files being uploaded to find out if the file extension to be uploaded is in the Allow list. Here is a sample code from the Microsoft Web site: View Source

01 <asp:fileupload id= "FileUpload1" runat= "Server"/>
03 <asp:button id= "Button1" runat= "Server" onclick= "Button1_Click" text= "Upload File"/>&nbsp;
05 <asp:label id= "Label1" runat= "Server" ></asp:Label>
07 <asp:regularexpressionvalidator id= "RegularExpressionValidator1" runat= "Server"
09 Errormessage= "only mp3, M3U or MPEG files is allowed!"
11 validationexpression= "^ ([a-za-z]:) | ( {2}w+) $?) ((w[w].*))
13 + (. mp3|. mp3|. Mpeg|. Mpeg|. m3u|. M3U) $ "controltovalidate=" FileUpload1 "></asp:RegularExpressionValidator>
15 <asp:requiredfieldvalidator id= "RequiredFieldValidator1" runat= "Server"
17 Errormessage= "This is a required field!"
19 Controltovalidate= "FileUpload1" ></asp:RequiredFieldValidator>
21st &nbsp;

This ASP. NET code uses validation controls, so end users are only allowed to upload. Mp3,.mpeg, or. m3u files to the server. If the file type is inconsistent with the three specified file types, the validation control will run out of exception and the file will not be uploaded.

Because this file validation is done on the client side, it is easy for a malicious user to bypass this check. It is not impossible to write a client script to replace the Web app's validation script. Without a Web browser, an intruder can use a program that can send an HTTP POST request to implement an upload file. Recommended Solutions

The following series of best practices should be applied in websites and Web applications that allow uploading of files. These practices will help you ensure the security of your Web app's uploaded files.
Defines a. htaccess file that only allows access to files of the specified extension.

Do not put. htaccess files and upload files in the same directory, should be placed in the parent directory.

A typical. htaccess file that only allows GIF, JPG, JPEG, and PNG files should contain the following code (adjusted to your needs). This also prevents double-extension attacks. View Source

1 Deny from all
2 <files ~ "^w+. (gif|jpe?g|png) $ ">
3 Order Deny,allow
4 Allow from all
5 </Files>

If possible, upload the file to a directory other than the root directory.

Suppresses overwriting of existing files (to block. htaccess overwrite attacks)

Create a Mime-type whitelist list. (Only mime-type in this list are allowed)

Generates a random file name, plus the file extension previously generated,

Do not rely solely on client-side validation, which is not enough. Ideally, both client and server-side validation are available. Summary

As mentioned above, malicious users have many means to bypass File upload form security verification. Therefore, when implementing a file upload form in a Web application, you should respect the correct security guidance and do appropriate testing. Unfortunately, it will take a lot of time and more security experts to do enough testing.

Fortunately, with Acunetix WVS, no security expert is required to automatically complete the Upload form vulnerability Check, Acunetix WVS provides developers with enough information to track and fix the problem in the least amount of time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.