PHP Security Configuration 2

Source: Internet
Author: User
Tags error handling execution file upload functions mysql variables parent directory php file

5, File Upload

PHP's file upload mechanism is to save the user uploaded files in the php.ini Upload_tmp_dir defined temporary directory (default is the system's temporary directory, such as:/tmp) in a similar phpxxuoxg random temporary file, the program execution ended, the temporary file was also deleted. PHP defines four variables for uploaded files: (for example, the form variable name is file and Register_globals opens)

$file #就是保存到服务器端的临时文件 (e.g./TMP/PHPXXUOXG)
$file _size #上传文件的大小
$file _name #上传文件的原始名称
$file _type #上传文件的类型

Recommended Use:

$HTTP _post_files[' file ' [' Tmp_name ']
$HTTP _post_files[' file ' [' Size ']
$HTTP _post_files[' file ' [' name ']
$HTTP _post_files[' file ' [' type ']

This is one of the simplest file upload codes:

?
test_5.php
if (Isset ($upload) && $file!= "None") {
Copy ($file, "/usr/local/apache/htdocs/upload/". $file _name);
echo "File". $file _name. " Upload success! Click <a href=\ "$PHP _self\" > Continue to upload </a> ";
Exit
}
?>
<title> File Upload </title>
<meta http-equiv= "Content-type"
Content= "text/html; charset=gb2312 ">
<body bgcolor= "#FFFFFF" >
<form enctype= "Multipart/form-data" method= "POST" >
Upload file:
<input type= "File" name= "file" size= ">"
<input type= "Submit" name= "Upload" value= "upload" >
</form>
</body>

Such uploading code has significant problems reading arbitrary files and executing commands.

The following request can copy the/etc/passwd document to the Web directory/usr/local/apache/htdocs/test (Note: This directory must be nobody writable) under Attack.txt file:

Http://victim/test_5.php?upload=1&file=/etc/passwd&file_name=attack.txt

You can then read the password file with the following request:

Http://victim/test/attack.txt

An attacker could copy a PHP file into another extension, revealing the source code of the script.

An attacker can customize the value of a file_name variable in a form and upload files that overwrite any write permissions.

An attacker could also upload a PHP script to execute a host command.

Workaround:

PHP-4.0.3 later provides the is_uploaded_file and Move_uploaded_file functions to check whether the file is uploaded by the user, thereby avoiding copying the system files to the Web directory.

Use the $http_post_files array to read the file variables uploaded by the user.

Check the upload variables Strictly. For example, PHP script files are not allowed.

Restricting PHP script operations to web directories prevents programmers from using the copy function to copy system files to a web directory. Move_uploaded_file is not limited by open_basedir, so you do not have to modify the Upload_tmp_dir values in php.ini.

The PHP script is encrypted with Phpencode to avoid leaking source code because of the copy operation.

Strict configuration files and directory permissions, only allow the uploaded directory to allow nobody users to write.

For the upload directory to remove the PHP interpretation function, you can modify the httpd.conf implementation:

<Directory/usr/local/apache/htdocs/upload>
Php_flag engine off
#如果是php3换成php3_engine off
</Directory>

Restart the Apache,upload directory of PHP files can not be explained by Apache, even upload the php file is not a problem, can only directly display the source code.

6. Order Execution

The following code fragment is taken from the Phpnettoolpack, detailed description see:

http://www.securityfocus.com/bid/4303

?
test_6.php
System ("Traceroute $a _query", $ret _strs);
?>

Because the program does not filter the $a_query variable, an attacker can append the execution command with a semicolon.

An attacker can execute the CAT/ETC/PASSWD command by entering the following request:

Http://victim/test_6.php?a_query=www.example.com;cat /etc/passwd

PHP's command execution function also has system (), PassThru (), Popen () and "". Command execution functions are dangerous and cautious. Be sure to check user input strictly if you want to use it.

Workaround:

The programmer is required to use the Escapeshellcmd () function to filter the shell commands entered by the user.

Enabling Safe_mode can eliminate many execution commands, but be aware that PHP's version must be up to date, and less than PHP-4.2.2 may bypass Safe_mode restrictions to execute commands.

7, Sql_inject

The following SQL statement has a problem if the variable is not processed:

SELECT * FROM login where user= ' $user ' and pass= ' $pass '

An attacker can enter a username and password of 1 ' or 1 = ' 1 to bypass authentication.

Fortunately, however, PHP has a default option MAGIC_QUOTES_GPC = ON, which automatically adds Addslashes () to the variables from Get, POST, and Cookie. The above SQL statement becomes:

SELECT * FROM login where user= ' 1\ ' or
1=\ ' 1 ' and pass= ' 1\ ' or 1=\ ' 1 '

Thus avoiding this kind of sql_inject attack.

For fields of numeric types, many programmers write this:

SELECT * FROM Test where id= $id

Because the variables are not amplified in single quotes, they can cause sql_inject attacks. Thanks to the simplicity of MySQL, there is no SQL Server database that executes commands, and PHP's mysql_query () function only allows you to execute an SQL statement, so an attack that separates multiple SQL statements with semicolons doesn't work. But the attacker can at least make the query statement error, leak some information about the system, or something unexpected.

Workaround:

Programmers are required to filter the variables submitted by all users to the SQL statements.

Even in fields of numeric types, variables are expanded in single quotes, and MySQL itself handles strings as numbers.

In MySQL do not give the PHP program high level permissions of users, only allow their own library to operate, which also avoids the problem of the program is SELECT into outfile ... This attack.

8. Warning and error message

PHP Displays all warnings and error messages by default:

error_reporting = E_all & ~e_notice
Display_errors = On

This is useful when developing debugging, and you can find the error of the program immediately based on the warning message.

When formally applied, warnings and error messages overwhelmed the user and gave the attacker the physical path where the script was located, providing favorable information for further attacks by the attacker. And because they do not have access to the wrong place, but can not modify the program in time error. So it's wise to log all of the warnings and error messages in PHP to a file that doesn't leak the physical path to the attacker and lets you know where the bug is.

Modify the contents of the error handling and Logging section in PHP.ini:

error_reporting = E_all
Display_errors = Off
Log_errors = On
Error_log =/usr/local/apache/logs/php_error.log

Then restart Apache, noting that file/usr/local/apache/logs/php_error.log must be available for nobody users to write.

9, Disable_functions

If you feel that some of the functions are still a threat, you can set the disable_functions in the php.ini (this option is not set in httpd.conf), such as:

Disable_functions = Phpinfo, Get_cfg_var

You can specify more than one function, separated by commas. After restarting Apache, phpinfo, the Get_cfg_var function is banned. It is recommended to turn off functions Phpinfo, Get_cfg_var, which are easy to leak server information and are of no practical use.

10, Disable_classes

This option is available from PHP-4.3.2, and it can disable certain classes if there are multiple comma-separated class names. Disable_classes can also not be set in httpd.conf and can only be modified in php.ini configuration file.

11, Open_basedir

The previous analysis routines also mentioned several times to use Open_basedir to limit the script operation path, and here is a brief description of its characteristics. The limit specified with Open_basedir is actually a prefix, not a directory name. That is to say, "Open_basedir =/dir/incl" will also allow access to "/dir/include" and "/dir/incls" if they exist. If you want to restrict access to only the specified directory, end the path name with a slash. For example: "Open_basedir =/dir/incl/".

You can set up multiple directories, and in Windows, separate the directories with semicolons. Separate the directories with colons in any other system. As an Apache module, the Open_basedir path in the parent directory is automatically inherited.

Iv. Other security configurations

1, cancellation of other users of common, important system commands read and write execution rights

General Administrator maintenance requires only one ordinary user and management user, in addition to these two users, the less the things that can be performed and accessed by other users, the more likely it is that removing other users ' ability to read and write to common, important system commands can be confusing to attackers when a program or service is compromised. Remember to be sure to read the permissions also removed, otherwise in Linux can be used/lib/ld-linux.so.2/bin/ls this way to execute.

If you want to cancel a path if it is in the chroot environment, this work is easier to achieve, otherwise, this work is still some challenges. Because canceling some of the program's execution permissions can cause some services to run abnormally. PHP mail functions need to/bin/sh to invoke SendMail letter, so/bin/bash execution permissions can not be removed. It's a very tiring job,

2, remove the Apache log other users Read permission

Apache's Access-log provides the door to some programs that appear to contain vulnerabilities locally. By submitting a URL that contains PHP code, you can make access-log include PHP code, then point the containing file to Access-log to execute those PHP code and gain local access.

If you have other virtual hosts, you should also remove the Read permissions for other users of the log file.

Of course, if you follow the configuration described earlier in PHP, then generally can not read the log file.



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.