Simple Analysis of PHP File Upload Vulnerability

Source: Internet
Author: User

The file upload vulnerability does not exist in php, but may be caused by poor performance of our users during program development. In the past, asp also had the File Upload Vulnerability, next, I will introduce you to the simple Analysis and Solution to the PHP File Upload Vulnerability.


Below is a simple File Upload form

The Code is as follows: Copy code

<Form action = "upload. php" method = "post" enctype = "multipart/form-data" name = "form1">
<Input type = "file" name = "file1"/> <br/>
<Input type = "submit" value = "Upload File"/>
<Input type = "hidden" name = "MAX_FILE_SIZE" value = "1024"/>
</Form>

Php configuration file: php. ini. The option upload_max_filesize specifies the size of the file to be uploaded. The default value is 2 MB.

$ _ FILES array variable

PHP uses the variable $ _ FILES to upload FILES. $ _ FILES is an array. If test.txt is uploaded, the content of the $ _ FILES array is:

The Code is as follows: Copy code

$ FILES

Array

{

[File] => Array

{

[Name] => test.txt // file name

[Type] => text/plain // MIME type

[Tmp_name] =>/tmp/php5D. tmp // temporary file

[Error] => 0 // error message

[Size] => 536 // file size, in bytes

}

}

If the name attribute value of the Upload file button is file

The Code is as follows: Copy code

<Input type = "file" name = "file"/>

Use $ _ FILES ['file'] ['name'] to obtain the name of the uploaded file on the client, excluding the path. Use $ _ FILES ['file'] ['tmp _ name'] to obtain the temporary file path for the server to save the uploaded file.

Folder for storing uploaded files

PHP does not directly put the uploaded file in the root directory of the website, but saves it as a temporary file named $ _ FILES ['file'] ['tmp _ name, the developer must copy the temporary file to the saved website folder.

$ _ FILES ['file'] ['tmp _ name'] values are set by PHP, which is different from the original file name, developers must use $ _ FILES ['file'] ['name'] to obtain the original name of the uploaded file.

Error message during File Upload

$ _ FILES ['file'] ['error'] variable is used to save the error message during file upload. Its value is as follows:

Description of error message values
UPLOAD_ERR_ OK 0 no error
UPLOAD_ERR_INI_SIZE 1 the size of the uploaded file exceeds the php. ini setting.
UPLOAD_ERR_FROM_SIZE 2 the size of the uploaded file exceeds the value of MAX_FILE_SIZE in the HTML form.
UPLOAD_ERR_PARTIAL 3 upload partial files
UPLOAD_ERR_NO_FILE 4 No file to upload

File Upload Vulnerability

If you provide the function for website visitors to upload images, you must be careful that the visitor may not actually upload images, but can specify a PHP program. If the directory where images are stored is an Open folder, intruders can remotely execute the uploaded PHP file to launch attacks.

The following is a simple File Upload example:

The Code is as follows: Copy code

<? Php
// Set the directory of the uploaded file
$ Uploaddir = "D:/www/images /";

// Check whether the file exists
If (isset ($ _ FILES ['file1'])
{
// Complete path to be put in the website directory, including the file name
$ Uploadfile = $ uploaddir. $ _ FILES ['file1'] ['name'];
// Move the path stored on the server to the actual file name
Move_uploaded_file ($ _ FILES ['file1'] ['tmp _ name'], $ uploadfile );
}
?>
......
<Form method = "post" enctype = "multipart/form-data" name = "form1">
<Input type = "file" name = "file1"/> <br/>
<Input type = "submit" value = "Upload File"/>
<Input type = "hidden" name = "MAX_FILE_SIZE" value = "1024"/>
</Form>

This example does not check the file suffix and can upload any file. Obviously, the upload vulnerability is very simple to solve. Let's look at a piece of code.

The Code is as follows: Copy code
Switch ($ extension)
{
Case 'application/msword ':
$ Extension = 'Doc ';
Break;
Case 'application/vnd. ms-excel ':
$ Extension = 'xls ';
Break;
Case 'application/vnd.openxmlformats-officedocument.wordprocessingml.doc ument ':
$ Extension = 'docx ';
Break;
Case 'application/vnd. ms-powerpoint ':
$ Extension = 'ppt ';
Break;
Case 'application/pdf ':
$ Extension = 'pdf ';
Break;
Case 'application/vnd. openxmlformats-officedocument.spreadsheetml.sheet ':
$ Extension = 'xlsx ';
Break;
Default:
Die ('only upload doc, docx, xls, pdf, and pptfile <a href = "wend. php"> re-upload </a> ');

}

This is used to restrict the type number or suffix of the user's upload, so that you can filter simple files and cannot directly upload php files. But let's look at another example. You can find it terrible.

Create a jpg, gif, or png image format with a drawing tool. It must start with GIF, JPG, or PNG.

Write the php webhorse header into GIF

The Code is as follows: Copy code


Then write a simple php File Upload process (I can write it casually in a hurry, without any aesthetic ):

 

<? Php

If ($ _ FILES ){
Echo 'here is the error $ _ FILES: <br/> ';
Echo "<pre> ";
Print_r ($ _ FILES );
Echo "</pre> ";

Echo "the following error getimagesize () <br/> ";
Echo "<pre> ";
Print_r (getimagesize ($ _ FILES ['bug '] ['tmp _ name']);
Echo "</pre> ";
Exit;
$ Fp = fopen ($ _ FILES ['bug '] ['tmp _ name'], "r ");
$ Content = fread ($ fp, filesize ($ _ FILES ['bug '] ['tmp _ name']);
// Echo $ content can see the uploaded source code
}
?>

<Form action = "" method = "post" enctype = "multipart/form-data">

<Input type = "file" name = "bug"/>

<Input type = "submit">
</Form>

You can see the effect of such a pitfall.


First, print_r ($ _ FILES) directly displays the expanded jpg results.
The result of the php function getimagesize () is gif (which is based on the section starting with the file ).

Php cannot solve this problem, but we can operate it from the server directory permissions. The following provides some solutions.

As a matter of fact, let's take a few points. Let's take a look at it first. Since the user wants to store the file, and the file will be in a variety of formats, the contents of some files may be different from the format imported by the user, some files contain Trojan code. Therefore, we allow users to store files and perform separate authorization with site files for isolation.

Keep the stored directory independent. The directory permission is read-only and cannot be executed.
This step is authorized by the system design. No matter what file you used last time, it cannot be executed. Even if I do not perform any detection, your files are stored here, and it will not constitute a security for my system. (If a user saves images of reactionary words, what else needs to be processed)

 

Detection is performed for all input values without using the server.

This type is the same as the principle that all input operations are harmful. The type and name passed by the client must be determined and not directly used. For a file name to be generated to a directory.

The best file name method is: write your own dead directory (do not read the imported directory), file name, it is best to randomly generate your own, do not read the user file name. File Extension, which can be followed by "." On the rightmost side.

The above two methods impose overall constraints on memory from two aspects.

Method 2: Save the stored file name, write data to the specified directory, and generate the file name.

Method 1: ensure that the file is written to the correct location, and then control the permission to write the directory from the configuration. This is a permanent cure. Yes. No matter what files you store, you do not have the permission to jump out and run them.

 

The above two methods can be used together to ensure that the file is correctly stored in a local place, and then the permissions can be controlled. By the way, to determine whether the user's stored files meet the required types, you can directly check the file extension, as long as the file extension is satisfied, so that the file can be stored. In any case, the execution permission restriction is imposed, and it is okay if you do not store the content as required. It cannot be executed.

Correct steps:
1. Read the file name and verify that the extension is in the specified range.

2. Customize the generated file name, directory, and extension from the file name extension. Other values are configured by yourself and do not read the content stored on the storage.

3. Move the file to the new directory (the directory permission is set to read-only)

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.