Home  >  Article  >  Backend Development  >  Common vulnerability attack analysis of PHP program, PHP program vulnerability attack_PHP tutorial

Common vulnerability attack analysis of PHP program, PHP program vulnerability attack_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:58:46681browse

Analysis of common vulnerability attacks on PHP programs, PHP program vulnerability attacks

Overview: PHP programs are not impregnable. With the widespread use of PHP, some hackers are also thinking about it all the time. To find trouble with PHP, attacking through PHP program vulnerabilities is one of them. In this section, we will analyze the security of PHP from the aspects of global variables, remote files, file uploads, library files, Session files, data types and error-prone functions.

How to attack through global variables?

Variables in PHP do not need to be declared in advance, they are automatically created the first time they are used, and their types are automatically determined based on the context. From a programmer's perspective, this is undoubtedly an extremely convenient approach. Once a variable is created, it can be used anywhere in the program. The result of this feature is that programmers rarely initialize variables.

Obviously, the main function of PHP-based applications generally accepts user input (mainly form variables, uploaded files, cookies, etc.), then processes the input data, and then returns the results to the client browser . In order to make it as easy as possible for PHP code to access user input, PHP actually treats this input data as global variables.

For example:

Program code

<FORM METHOD="GET" ACTION="test.php">
<INPUT TYPE="TEXT" NAME="hello">
<INPUT TYPE="SUBMIT">
</FORM>


This will display a text box and submit button. When the user clicks the submit button, "test.php" will process the user's input. When "test.php" is run, "$hello" will contain the data entered by the user in the text box. From here we should see that the attacker can create any global variables according to his wishes. If the attacker does not call "test.php" through form input, but directly enters http://server/test.php?hello=hi&setup=no in the browser address bar, then not only "$hello" will be created , "$setup" is also created.

The following user authentication code exposes security issues caused by PHP's global variables:

Program code

<?php
<?php
if ($pass == "hello")
$auth = 1;
...
if ($auth == 1)
echo "some important information";
?>
if ($pass == "hello")

$auth = 1;

...

if ($auth == 1)

echo "some important information";

?>

The above code first checks whether the user's password is "hello". If it matches, set "$auth" to "1", which means the authentication is passed. Afterwards, if "$suth" is "1", some important information will be displayed.

This code assumes that "$auth" is empty when no value is set, but an attacker can create any global variable and assign a value, through something like "http://server/test.php?auth=1" Method, we can completely trick this code into believing that we have authenticated it.

Therefore, in order to improve the security of PHP programs, we cannot trust any variables that are not clearly defined. This can be a very difficult task if there are many variables in the program.

A common protection method is to check the variables in the array HTTP_GET[] or POST_VARS[], which depends on our submission method (GET or POST). When PHP is configured with the "track_vars" option turned on (which is the default), user-submitted variables are available in global variables and the array mentioned above.

But it is worth mentioning that PHP has four different array variables used to process user input. The HTTP_GET_VARS array is used to process variables submitted in GET mode, the HTTP_POST_VARS array is used to process variables submitted in POST mode; the HTTP_COOKIE_VARS array is used to process variables submitted as cookie headers, and for the HTTP_POST_FILES array (provided by relatively new PHP), it is completely An optional way for users to submit variables. A user request can easily store variables in these four arrays, so a secure PHP program should check these four arrays. How to attack via remote files?
<?php
if (!($fd = fopen("$filename", "r"))
echo("Could not open file: $filename
n");
?>
PHP is a feature-rich language that provides a large number of functions to make it easy for programmers to implement specific functions. But from a security perspective, the more features you have, the harder it is to keep it secure. Remote files are a good example of this problem: Program code
<?phpif (!($fd = fopen("$filename", "r"))echo("Could not open file: $filename n");?>

The above script attempts to open the file "$filename" and displays an error message if it fails. Obviously, if we can specify "$filename", we can use this script to browse any file on the system. However, a less obvious feature of this script is that it can read files from any other WEB or FTP site. In fact, most of PHP's file handling functions handle remote files transparently.

For example:

If "$filename" is specified as "http://target/scripts/..� ../winnt/system32/cmd.exe?/c dir"

The above code actually exploits the unicode vulnerability on the host target to execute the dir command. This makes supporting include(), require(), include_once() and require_once() for remote files more interesting in context. The main function of these functions is to include the contents of specified files and interpret them according to PHP code. They are mainly used on library files.

For example:

Program code

<?php
include($libdir . "/languages.php");
?>

In the above example, "$libdir" is generally a path that has been set before executing the code. If the attacker can prevent "$libdir" from being set, then he can change this path. But the attacker can't do anything because they can only access the file languages.php in the path they specify (the "Poisonnull byte" attack in Perl has no effect on PHP). But with support for remote files, attackers can do anything. For example, an attacker can place a file languages.php on a server containing the following content:

Program code

<?php
passthru("/bin/ls /etc");
?>


Then set "$libdir" to "http:///", so that we can execute the above attack code on the target host, and the contents of the "/etc" directory will be returned as the result to the customer's browser.

It should be noted that the attack code will not execute its own PHP program on the server where it is located (that is, evilhost). Otherwise, the attack code will attack the server where it is located instead of executing on the target server.

How to attack via file upload?

PHP automatically supports file upload based on RFC 1867. Let’s look at the following example:

Program code

<FORM METHOD="POST" ENCTYPE="multipart/form-data">
<FORM METHOD="POST" ENCTYPE="multipart/form-data">
<INPUT TYPE="FILE" NAME="hello">
<INPUT TYPE="HIDDEN" NAME="MAX_FILE_SIZE" VALUE="10240">
<INPUT TYPE="SUBMIT">
</FORM>
<INPUT TYPE="FILE" NAME="hello">

<INPUT TYPE=" HIDDEN" NAME="MAX_FILE_SIZE" VALUE="10240">
<INPUT TYPE="SUBMIT">

</FORM>

The above code allows the user to select a file from the local machine. When submit is clicked, the file will be uploaded to the server. This is obviously a useful feature, but the way PHP responds would make this feature unsafe. When PHP first receives such a request, even before it starts parsing the called PHP code, it will first accept the file from the remote user and check whether the length of the file exceeds the value defined by the "$MAX_FILE_SIZE variable". If it passes these For testing, the file will be stored in a local temporary directory.

Therefore, an attacker can send arbitrary files to the host running PHP. Before the PHP program decides whether to accept the file upload, the file has already been stored on the server.

Let's consider a PHP program that handles file uploads. As we said above, the file is received and stored on the server (the location is specified in the configuration file, usually /tmp), and the extension is usually random. , similar to the form of "phpxXuoXG". The PHP program needs to upload the file's information in order to process it, and this can be done in two ways, one that was already used in PHP3, and the other that was introduced after we made a security advisory on the previous method.

Most PHP programs still use the old way to handle uploaded files. PHP sets four global variables to describe uploaded files, such as the above example:
$hello = Filename on local machine (e.g "/tmp/phpxXuoXG")
$hello_size = Size in bytes of file (e.g 1024)
$hello_name = The original name of the file on the remote system (e.g"c:\temp\hello.txt")
$hello_type = Mime type of uploaded file (e.g "text/plain")

Program code

$hello = Filename on local machine (e.g "/tmp/phpxXuoXG")$hello_size = Size in bytes of file (e.g 1024)
http://vulnhost/vuln.php?hello=/ ... e=10240&hello_type=
text/plain&hello_name=hello.txt
$hello_name = The original name of the file on the remote system (e.g"c:\temp\hello.txt")

$hello_type = Mime type of uploaded file (e.g "text/plain")

Then, the PHP program starts processing the file specified according to "$hello". The problem is that "$hello" is not necessarily a variable set by PHP, any remote user can specify it. If we use the following:

http://vulnhost/vuln.php?hello=/ ... e=10240&hello_type=
$hello = "/etc/passwd"
$hello_size = 10240
$hello_type = "text/plain"
$hello_name = "hello.txt"
text/plain&hello_name=hello.txt
leads to the following PHP global variables (of course POST method is also possible (even Cookie)): Program code
$hello = "/etc/passwd"$hello_size = 10240$hello_type = "text/plain"$hello_name = "hello.txt"

The above form data just meets the variables expected by the PHP program, but at this time the PHP program no longer processes the uploaded file that should be on the uploader's local machine, but processes "/etc/passwd" on the server (usually will result in content exposure) files. This attack can be used to expose the contents of any sensitive file.

The new version of PHP uses HTTP_POST_FILES[] to determine the uploaded file, and also provides many functions to solve this problem. For example, there is a function to determine whether a file is actually uploaded. But in fact there must be many PHP programs that still use the old method, so they are also vulnerable to this attack.

As a variant of the file upload attack method, let’s take a look at the following piece of code:

Program code

<?php
if (file_exists($theme)) // Checks the file exists on the local system (noremote files)
include("$theme");
?>

If an attacker can control "$theme", it is obvious that he can use "$theme" to read any file on the remote system. The attacker's ultimate goal is to execute arbitrary instructions on the remote server, but he cannot use the remote file, so he must create a PHP file on the remote server. This may seem impossible at first, but file uploading does this for us. If the attacker first creates a file on the local machine containing PHP code, and then creates a form containing a file field named "theme" , and finally use this form to submit the created file containing PHP code to the above code through file upload. PHP will save the file submitted by the attacker and set the value of "$theme" to the file submitted by the attacker. In this way, the file_exists() function will pass the check and the attacker's code will be executed.
After gaining the ability to execute arbitrary instructions, the attacker obviously wanted to escalate the privileges or expand the results, which in turn required some tool sets that were not available on the server, and file uploading once again helped the attacker. An attacker can use the file upload function to upload tools, store them on the server, and then use their ability to execute commands, use chmod() to change the permissions of the file, and then execute it. For example: an attacker can bypass the firewall or IDS to upload a local root attack program and then execute it, thus gaining root privileges.

How to attack through library files?

As we discussed earlier, include() and require() are mainly to support the code base, because we usually put some frequently used functions into a separate file, and this independent file is the code base. When we need to use the functions, we only need to include this code library into the current file.

Initially, when people developed and released PHP programs, in order to distinguish the code library from the main program code, they usually set a ".inc" extension for the code library file, but they soon discovered that this was a mistake, because Such files cannot be correctly parsed into PHP code by the PHP interpreter. If we directly request such a file on the server, we will get the source code of the file. This is because when PHP is used as an Apache module, the PHP interpreter determines whether to parse it into PHP based on the extension of the file. of code. The extension is specified by the site administrator, usually ".php", ".php3" and ".php4". If important configuration data is contained in a PHP file without the appropriate extension, it is easy for a remote attacker to obtain this information.

The simplest solution is to specify a PHP file extension for each file. This can effectively prevent the leakage of source code, but it also creates new problems. By requesting this file, the attacker It is possible to cause code that should be running in the context to run independently, which can lead to all the attacks discussed previously.

Here is an obvious example:

In main.php:

Program code

<?php
<?php 
$libDir = "/libdir"; 
$langDir = "$libdir/languages"; 
... 
include("$libdir/loadlanguage.php": 
?>
$libDir = "/libdir";

$langDir = "$libdir/languages";

...
<?php 
...

include("$langDir/$userLang"); 
?>

include("$libdir /loadlanguage.php": ?>
In libdir/loadlanguage.php:
<?php ... include("$langDir/$userLang"); ?>


It is quite safe when "libdir/loadlanguage.php" is called by "main.php", but because "libdir/loadlanguage" has the extension of ".php", a remote attacker can directly request This file, and the values ​​​​of "$langDir" and "$userLang" can be specified arbitrarily.

How to attack through Session file?

PHP 4 or newer versions provide support for sessions, whose main function is to save status information between pages in the PHP program. For example, when a user logs in to the website, the fact that he logged in and the information about who logged in to the website will be saved in the session. When he browses around the website, all PHP code can obtain this state. information.

In fact, when a session is started (actually set in the configuration file to automatically start on the first request), a random "session id" is generated, if the remote browser is always sending If you submit this "session id" when requesting, the session will be maintained. This is easily accomplished via cookies, or by submitting a form variable (containing the "session id") on each page. PHP programs can use session to register a special variable. Its value will be stored in the session file after each PHP script ends, and will also be loaded into the variable before each PHP script starts. Here is a simple example:

Program code

<?php
<?php 
session_destroy(); // Kill any data currently in the session 
$session_auth = "shaun"; 
session_register("session_auth"); // Register $session_auth as a session variable 
?>
session_destroy(); // Kill any data currently in the session

$session_auth = "shaun";
session_register("session_auth"); // Register $session_auth as a session variable

?>

New versions of PHP will automatically set the value of "$session_auth" to "shaun". If they are modified, future scripts will automatically accept the modified values, which is very important for the stateless Web. It is indeed a very good tool, but we should also be careful.
<?php 
if (!empty($session_auth)) 
// Grant access to site here 
?>

An obvious question is to ensure that the variable does come from the session. For example, given the above code, if the subsequent script looks like this:

<?php

if (!empty($session_auth))

// Grant access to site here

?>

The above code assumes that if "$session_auth" is assigned a value, it is assigned from the session, not from user input. If the attacker assigns the value through form input, he can gain access to the site. Note that the attacker must register the variable in the session before using this attack method. Once the variable is placed in the session, it will overwrite any form input.

Session data is generally saved in a file (the location is configurable, usually "/tmp"). The file name is generally in the form of "sess_". This file contains variable names, variable types, variable values ​​and some other data. In a multi-host system, because the file is saved as the user running the web server (usually nobody), a malicious site owner can create a session file to gain access to other sites, and even inspect the session file. sensitive information in.

The Session mechanism also provides another convenience for attackers to save their own input in files on the remote system. For the above example, the attacker needs to place a file containing PHP code on the remote system. If this cannot be done using file upload, he usually uses session to assign a value to a variable according to his own wishes, and then guesses the session file. The location, and he knows that the file name is "php", so he only needs to guess the directory, and the directory is usually "/tmp".

In addition, the attacker can arbitrarily specify the "session id" (such as "hello"), and then use this "session id" to create a session file (such as "/tmp/sess_hello"), but the "session id" can only be A combination of letters and numbers.

How to attack by data type?

PHP has relatively loose data types, and the types of variables depend on the context in which they are located. For example: "$hello" starts as a string variable with a value of "", but during evaluation, it becomes an integer variable "0", which may sometimes lead to unexpected results. If the value of "$hello" is different between "000" and "0", the result returned by empty() will not be true.

Arrays in PHP are associative arrays, that is to say, the index of the array is of string type. This means that "$hello["000"]" and "$hello[0]" are also different.

The above issues should be carefully considered when developing a program. For example, we should not test whether a variable is "0" in one place and use empty() to verify it in another place.
require():读取指定文件的内容并且作为PHP代码解释 
include():同上 
eval():把给定的字符串作为PHP代码执行 
preg_replace():当与"/e"开关一起使用时,替换字符串将被解释为PHP代码
How to attack via error-prone functions? The following is a more detailed list of error-prone functions: <PHP code execution>
require(): Read the contents of the specified file and interpret it as PHP code include(): Same as above eval(): Execute the given string as PHP code preg_replace(): When used with the "/e" switch, the replacement string will be interpreted as PHP code


<Command execution>

exec(): Execute the specified command and return the last line of the execution result
exec():执行指定的命令,返回执行结果的最后一行 
passthru():执行指定命令,返回所有结果到客户浏览器 
``:执行指定命令,返回所有结果到一个数组 
system():同passthru(),但是不处理二进制数据 
popen():执行指定的命令,把输入或输出连接到PHP文件描述符
passthru(): Execute the specified command and return all results to the client browser

``: Execute the specified Command, returns all results to an array

system(): Same as passthru(), but does not process binary data
fopen():打开文件,并对应一个PHP文件描述符 
readfile():读取文件的内容,然后输出到客户浏览器 
file():把整个文件内容读到一个数组中
popen(): Execute the specified command and connect the input or output to the PHP file descriptor

<Leaked documents>

fopen(): Open the file and correspond to a PHP file descriptor

readfile(): Read the content of the file and then output it to the client browser

file(): Put Read the entire file content into an array

How to enhance the security of PHP?

All the attacks we introduced above can be implemented well against the default installation of PHP4, but the configuration of PHP is very flexible. By configuring some PHP options, it is entirely possible for us to resist some of these attacks. Below we classify some configurations according to the difficulty of implementation:

*Low difficulty

**Medium-low difficulty

***Medium-high difficulty

****High difficulty

If you use all the options provided by PHP, then your PHP will be very safe, even for third-party code, because many of its functions are no longer available.

**** Set "register_globals" to "off"

This option will disable PHP from creating global variables for user input, that is, if the user submits the form variable "hello", PHP will not create "$ hello" ", while only "HTTP_GET/POST_VARS[''hello'']" will be created. This is an extremely important option in PHP. Turning off this option will bring great inconvenience to programming.

*** Set "safe_mode" to "on"

Turn this option on and the following restrictions will be added:

1. Limit which commands can be executed

2. Limit which functions can be used

3. File access restrictions based on script ownership and target file ownership

4. Disable file upload function

This is a "great" option for ISPs, and it also greatly improves PHP security.

** Set "open_basedir"

This option can prohibit file operations outside the specified directory, effectively eliminating attacks by include() on local files or remote files, but you still need to pay attention to attacks on file uploads and session files.

** Set "display_errors" to "off" and set "log_errors" to "on"

This option disables error messages from being displayed on the web page and instead records them in a log file, which can effectively resist attackers from detecting functions in the target script.

<p>转载自:http://www.aspnetjia.com/Cont-222.html</p>

* Set "allow_url_fopen" to "off"

This option disables the remote file function.

http://www.bkjia.com/PHPjc/1101500.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1101500.html
TechArticleAnalysis of common vulnerability attacks in PHP programs, summary of vulnerability attacks in PHP programs: PHP programs are not impregnable. With the development of PHP It is widely used, and some hackers also want to find trouble with PHP all the time, through...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn