Analysis of common Vulnerability attacks in PHP programs

Source: Internet
Author: User
Tags ftp site session id php script

Summary: PHP program is not impregnable, with the extensive use of PHP, some hackers are also in the absence of the trouble to find PHP, through the PHP program vulnerability to attack is one of them. In the 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 do I attack with global variables?

Variables in PHP do not need to be declared beforehand, they are created automatically when they are first used, and their types are automatically determined based on the context. From the programmer's point of view, this is undoubtedly a very convenient way of handling. Once a variable has been created, it can be used anywhere in the program. The result of this feature is that programmers seldom initialize variables.

Obviously, the main function of the PHP-based application is generally to accept the user's input (mainly form variables, upload files and cookies, etc.), and then process the input data, and then return the results to the client browser. In order for the PHP code to access the user's input as easily as possible, in fact, PHP is the input data as a global variable to handle.

For example:

Program code




This displays a text box and a Submit button. When the user clicks the Submit button, "test.php" processes the user's input, and when "test.php" runs, "$hello" contains the data that the user entered in the text box. From here we should see that attackers can create arbitrary global variables as they wish. If an attacker does not invoke "test.php" through form input, but instead enters Http://server/test.php?hello=hi&setup=no directly into the browser's address bar, then more than just "$hello" is created, "$setup "was also created.

The following user authentication code exposes the security issues caused by the global variables of PHP:

Program code

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", that is, through authentication. Then 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, and through a method like "http://server/test.php?auth=1", we can spoof this code to convince it that we are already certified.

Therefore, in order to improve the security of PHP programs, we cannot trust any variables that are not explicitly defined. If there are a lot of variables in the program, this is a very difficult task.

A common protection method is to check the variables in the array http_get[] or post_vars[], which depends on how we submit (GET or POST). When PHP is configured to open the "track_vars" option (this is the default), the user-submitted variable can be obtained in the global variable and the array mentioned above.

But it's worth noting that PHP has four different array variables to handle the user's input. The Http_get_vars array is used to handle variables that are submitted by the GET mode, http_post_vars arrays are used to handle variables submitted by POST, http_cookie_vars arrays are used to handle variables submitted as COOKIE headers, and for HTTP_ The post_files array, which is provided by newer PHP, is an optional way for the user to commit the variable. A user's request can easily put variables in these four arrays, so a secure PHP program should check for these four arrays. How do I attack from a remote file?

PHP is a rich language that provides a number of functions that make it easy for programmers to implement specific functions. But from a security standpoint, the more features, the more difficult it is to secure it, a good example of this problem is the remote file:

Program code

if (! ( $FD = fopen ("$filename", "R"))
Echo ("Could not open File: $filename
\ n ");
? >

The above script tries 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 in the system. However, there is a less obvious feature of this script, which is that it can read files from any other Web or FTP site. In fact, most of PHP's file-handling functions are transparent to remote files.

For example:

If you specify "$filename" as "Http://target/scripts/..%c1%1c../winnt/system32/cmd.exe?/c+dir"

The above code actually takes advantage of the Unicode vulnerability on the host target and executes the dir command. This allows the include (), require (), include_once (), and require_once () to support remote files to become more interesting in the context. The main function of these functions is to include the contents of the specified file, and to interpret them in PHP code, mainly used in the library file.

For example:

Program code

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

In the above example, "$libdir" is usually a path that has been set before executing the code, and if the attacker can make the "$libdir" not set, then he can change the path. But attackers cannot do anything because they can only access file languages.php in the path they specify (the "Poisonnull byte" attack in Perl has no effect on PHP). But because of the support for remote files, attackers can do anything. For example, an attacker could place a file languages.php on a server that contains the following:

Program code

PassThru ("/bin/ls/etc");
? >


Then set the "$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 to the customer's browser as a result.

It is important to note that the attack code does not execute its own PHP program on its own server (that is, evilhost), otherwise the attack code will attack the server on which it resides, rather than executing it on the target server.

How do I attack through file uploads?

PHP automatically supports file uploads based on RFC 1867, and we look at the following example:

Program code




The above code allows the user to select a file from the local machine, and when the commit is clicked, the file is uploaded to the server. This is obviously a useful feature, but the way PHP responds will make this feature unsafe. When PHP first receives this request, even before it starts parsing the called PHP code, it accepts the remote user's file, checks whether the length of the file exceeds the value defined by the "$MAX _file_size variable", and, if passing these tests, The file will be present in a local temporary directory.
As a result, an attacker can send arbitrary files to a host running PHP, and the file is already on the server when the PHP program has not decided whether to accept the file upload.

Let's consider the PHP program that handles file uploads, as we said above, the file is received and is present on the server (the location is specified in the configuration file, usually/tmp), and the extension is generally random, similar to the form "Phpxxuoxg". The PHP program needs to upload the file's information in order to handle it, which can be done in two ways, one in PHP3, and the other after we introduce a security bulletin to the previous method.

Most PHP programs still use the old way to handle uploading files. PHP sets four global variables to describe uploaded files, such as the example above:

Program code

$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")


The PHP program then starts processing the files specified under "$hello". The problem is that "$hello" is not necessarily a PHP-set variable, and any remote user can specify it. If we use the following method:

http://vulnhost/vuln.php?hello=/... e=10240&hello_type=
Text/plain&hello_name=hello.txt

Causes the following PHP global variables (of course post can also (even a cookie)):

Program code

$hello = "/etc/passwd"
$hello _size = 10240
$hello _type = "Text/plain"
$hello _name = "Hello.txt"

The form data above satisfies the variables expected by the PHP program, but at this point the PHP program no longer processes the uploaded files that should be on the uploader's native computer, but instead handles the "/etc/passwd" (which usually results in content exposure) files on the server. This attack can be used to expose the contents of any sensitive file.

The new version of PHP uses http_post_files[] to decide to upload the file, but also provides a number of functions to solve the problem, such as a function to determine whether a file is actually loaded files. But there must be a lot of PHP programs still using the old method, so it's easy to be attacked.

As a variant of the attack method for file uploads, let's take a look at the following piece of code:

Program code

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

If an attacker can control the "$theme", it is clear that it can use "$theme" to read any file on the remote system. The attacker's ultimate goal was to execute arbitrary instructions on the remote server, but he was unable to use the remote file, so he had to create a PHP file on the remote server. This may seem impossible at first glance, but the file upload helps us, if the attacker first creates a file with PHP code on the local machine, and then creates a form with a file field named "Theme", Finally with this form through the file upload to create the file containing PHP code to the above code, PHP will save the file submitted by the attacker, and the "$theme" value is set to the attacker submitted files, so the file_exists () function will check through, The attacker's code will also be executed.
Given the ability to execute arbitrary instructions, an attacker would obviously want to elevate the privileges or increase the outcome, which would require a set of tools not available on the server, and the file upload would help the attacker. Attackers can use the file Upload feature to upload tools, place them on the server, and then use their ability to execute instructions, use chmod () to change the file's permissions, and then execute. For example, an attacker could bypass the firewall or IDs to upload a local root attack program and execute it, thus gaining root privileges.

How do I attack through a library file?

As we discussed earlier, the include () and require () are primarily designed to support code libraries, because we typically put some frequently used functions into a separate file, which is the code base, and when you need to use one of the functions, We just have to include this codebase in the current file.

Initially, when people developed and published PHP programs, in order to distinguish between the code base and the main program code, the code base file is usually set up a ". Inc" extension, but they quickly found that this is a mistake, because such a file can not be correctly parsed by the PHP interpreter into PHP code. If we directly request such a file on the server, we will get the source code of the file, because when using PHP as an Apache module, the PHP interpreter is based on the file extension to determine whether to parse into PHP code. The extension is specified by the site administrator, typically ". php", ". PhP3" and ". PhP4". If important configuration data is included in a PHP file that does not have the appropriate extension, it is easy for a remote attacker to get that information.

The simplest solution is to specify a php file extension for each file, which is a good way to prevent the source code from being compromised, but it creates a new problem by requesting that the attacker could run code that would otherwise run in the context, potentially leading to all the attacks discussed earlier.

The following is an obvious example:

In main.php:

Program code

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

In libdir/loadlanguage.php:

...

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


It is fairly secure when "libdir/loadlanguage.php" is called by "main.php", but because "libdir/loadlanguage" has an extension of ". PHP", remote attackers can request this file directly, You can optionally specify values for $langDir and $userLang.

How do I attack through a session file?

PHP 4 or later provides support for sessions, whose main purpose is to store state information between pages and pages in a PHP program. For example, when a user logs on to the site, the fact that he landed and the information about who landed on the site will be saved in the session, and all PHP code can obtain these status information when he is browsing around the site.

In fact, when a session is started (which is actually set in the configuration file to start automatically on the first request), a random "session ID" is generated, if the remote browser always submits the "session ID" when sending the request, The session will always be maintained. This can be done easily through cookies, or by submitting a form variable (containing "session ID") on each page. The PHP program can register a special variable with the session, and its value will be in the session file at the end of each PHP script, and will be loaded into the variable before each PHP script starts. The following is a simple example:

Program code

Session_destroy (); Kill any data currently in the session
$session _auth = "Shaun";
Session_register ("Session_auth"); Register $session _auth as a session variable
? >


The new version of PHP will automatically set the "$session _auth" value to "Shaun", if they are modified, the future script will automatically accept the modified value, which is a very good tool for the stateless web, but we should also be careful.

One obvious problem is to make sure that the variable really comes from the session, for example, given the code above, if the following script is:

if (!empty ($session _auth))
Grant access to Site here
? >

The above code assumes that if "$session _auth" is assigned, it is assigned from the session rather than the user input, and if the attacker assigns a value through form input, he can gain access to the site. Note that an attacker must use this attack method before the session registers the variable, and once the variable is placed in the session, it will overwrite any form input.

Session data is generally stored in the file (location is configurable, usually "/tmp"), the file name is generally similar to "sess_ " form, this file contains the variable name, variable type, variable value and some other data. In a multi-host system, because the file is stored as the user who runs the Web server (typically nobody), a malicious site owner can create a session file to gain access to other sites and even check for sensitive information in the session file.

The session mechanism also provides another convenience for attackers to save their input to files in the remote system. For the above example, an attacker would need to place a file containing PHP code in the remote system, and if not, he would usually use the session to assign a value to a variable at his own will, then guess the location of the session file, and he knew the filename was " Php ", so just guess the directory, and the directory is usually"/tmp ".

Alternatively, an attacker could arbitrarily specify the session ID (for example, "Hello") and then create a session file (such as "/tmp/sess_hello") with this session ID, but the session ID can only be a combination of letters and numbers.

How do I attack with a data type?

PHP has loosely typed data types, and the types of variables depend on the context in which they are located. For example: "$hello" begins as a string variable with a value of "", but when evaluated, it becomes the shaping variable "0", which can sometimes lead to unexpected results. If the value of "$hello" is different for "000" or "0", the result returned by empty () will not be true.

An array in PHP is an associative array, that is, the index of an array is of a string type. This means that "$hello [" 000 "]" and "$hello [0]" are also different.

The development of the program should carefully consider the above problem, for example, we should not be in one place to test whether a variable is "0", and in another place using empty () to verify.

How do I attack with an error-prone function? The following is a more detailed list of error-prone functions:

Require (): reads the contents of the specified file and interprets it as PHP code
Include (): Ibid.
Eval (): Executes the given string as PHP code
Preg_replace (): When used with the "/E" switch, the replacement string is interpreted as PHP code


Order execution

EXEC (): Executes the specified command, returning the last line of the execution result
PassThru (): Executes the specified command, returning all results to the client browser
": Executes the specified command, returning all results to an array
System (): Same as PassThru (), but does not process binary data
Popen (): Executes the specified command to connect the input or output to the PHP file descriptor

Disclosure of documents

fopen (): Open the file and correspond to a PHP file descriptor
ReadFile (): reads the contents of the file and then outputs it to the customer's browser
File (): reads the entire contents into an array

How to enhance the security of PHP?

All of the attacks we've described above are well-implemented for the PHP4 of the default installation, but the PHP configuration is very flexible, and by configuring some PHP options, we can completely resist some of these attacks. Below we classify some configurations according to the difficulty of implementation:

* Low Difficulty
* * Medium and low difficulty
Medium to High difficulty
High Difficulty

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

Set "Register_globals" to "off"
This option prevents PHP from creating global variables for user input, that is, if the user submits the form variable "Hello", PHP will not create "$ hello" and will only create "http_get/post_vars[" ' Hello ' ". This is an extremely important option in PHP, and turning off this option can cause great inconvenience to programming.

Set "Safe_mode" to "on"

Turning this option on will add the following restrictions:

1. Restrict which command can be executed
2. Restrict which function can be used
3. File access restrictions based on script ownership and target file ownership
4. Disable File Upload feature

This is a "great" option for ISPs, and it can greatly improve the security of PHP.

* * Set "Open_basedir"

This option disables file operations outside of the specified directory, effectively eliminating local files or remote files being used by include (), but still requires attention to file uploads and session file attacks.

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

This option prevents the error message from being displayed in the Web page, but is recorded in a log file, which effectively resists the attacker's ability to detect functions in the target script.

* Set "Allow_url_fopen" to "off"

This option prevents remote file functionality.

Reprinted from: http://www.aspnetjia.com/Cont-222.html

Analysis of common Vulnerability attacks in PHP programs

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.