PHP was originally called the personal home page. Later, as PHP became a very popular scripting language, its name also changed, called professional Hypertext Preprocessor. For example, php4.2 supports Apache, Microsoft Internet Information sereve, Microsoft Personal Web server, aolserver, and Netscape Enterprise.
PHP is a powerful language and interpreter, Whether installed on a Web server as a module or as a separate CGIProgramAll programs installed can access files, execute commands, or open links on the server. These features bring security issues during PHP runtime. Although pH P is designed to be a safer language than CGI programs written in Perl or C, however, correct use of some configuration options during compilation and running, as well as appropriate application encoding, will ensure its running security.
1. Security starts from compiling PHP.
Before compiling PHP, make sure that the operating system version is up-to-date and necessary patches must be installed. In addition, the compiled PHP version should be the latest version, and security vulnerabilities in PHP are often found. Please use the latest version. If you have installed PHP, upgrade it to the latest version 4.2.3.
Link: http://security.e-matters.de/advisories/012002.html
Note the following three issues during PHP installation and Compilation:
1. Only cgi files can be executed from a specific directory: first, delete the default handle for processing CGI scripts, and then in the directory where the CGI script is to be executed in HTTP. add the ScriptAlias command to the conf file.
# Addhadler CGI-script. cgi
ScriptAlias/cgi-bin/"/usr/local/Apache/cgi-bin /"
<Directory "/usr/local/Apache/cgi-bin '>
AllowOverride none
Options none
Order allow, deny
Allow from all
</Directory>
<Directory "/home/*/public_html/cgi-bin">
AllowOverride none
Options execcgi
Order allow, deny
Allow from all
</Directory>
The first parameter of sriptalias specifies the available relative path on the web, and the second parameter specifies the directory where the script is placed on the server. For each directory
Aliases all use directory, so that no one except the system administrator knows the CGI script list on the Web server.
Directory allows users to create their own CGI scripts. Sriptaliasmatch is also available, but directory is easier to use. Allow users to create themselves
CGI scripts may cause security issues. You may not want to create your own CGI. The default configuration of Apache is to comment out the processing handle of CGI-script, but the/cgi-bin directory uses sriptalias and directory commands. You can also disable CGI execution, but still allow PHP script execution.
2. Place the PHP parser outside the web directory
It is very important to put the PHP parser outside the web directory tree. This prevents the Web server from abusing the PHP parser. Especially
Do not place the PHP parser in the cgi-bin or directory where the CGI program can be executed. However, using action to parse scripts is impossible, because when using action commands, most PHP Resolvers should be placed in the directory where CGI can be executed only when PHP scripts are executed as CGI programs, in order to put the PHP parser outside the web directory tree.
If you want the PHP script to be executed as a CGI program (you can place the PHP parser outside the web directory tree), you can do this:
(1) All PHP scripts must be in the directory where CGI programs can be executed.
(2) The script must be executable (only on Unix/Linux machines ).
(3) The script must include the path of the PHP parser in the file header.
You can run the following command to make the PHP script executable:
# Chmod + X test. PhP4
In this way, the script named test. PhP4 in the current directory becomes executable. The following is a small example of a PHP script that can run as a CGI program.
#! /Usr/local/bin/PHP
Echo "this is a my small CGI program"
3. Install the SDK using the Apache module:
When PHP is used as an Apache module, it inherits the user permissions of Apche (generally "nobody "). This is applicable to security and
Verification has a lot of impact. For example, if you use PHP to access the database, unless the database supports built-in access control, you will have to set the "nobody"
. This means that malicious scripts can access and modify databases without accessing the user name and password. Use Apache authentication to protect data from being exposed, or use LDAP and. htaccess files to design your own access control model.CodeAs part of the introduction. In general, once security is established, PHP users (in this case, Apache users) are at a much lower risk, you will find that PHP protection has been banned from writing potential infected files to the user directory. The most common security error here is to grant the Apache server root permission. It is extremely dangerous to escalate Apache user permissions to root permissions. The entire system may be compromised. Therefore, use sudo and chroot commands with high security risks. Do not run it as root unless you have absolute security knowledge.
2. Make PHP usage safer.
1. run php In safe Mode
Running PHP in safe mode is a good way to secure PHP scripts, especially when users are allowed to use their own PHP scripts. Using the safe mode will enable PHP to check for security issues when running the function. Include, readfile, fopen, file, unlink, rmdir, and so on: the owner of the contained file or directory of the file must be the owner of the running script; exec, system, passthm, and so on: the program to be executed must be in a specific directory (/usr/local/PHP/bin by default ). You can use the-with-Exe-Dir option to set this value during PHP compilation.
Mysql-Connect: This function uses an optional user name to connect to the MySQL database. In safe mode, the user name must be the owner of the currently executed script or the user name (usually nobody) that runs httpd ).
HTTP Authentication: the user ID (number type) containing the HTTP verification code script owner is automatically added to the verification domain. This prevents someone from spoofing the HTTP verification script on the same server by capturing the password program.
2. Use user identification and verification
Sometimes it is necessary to uniquely identify a user. The user is usually confirmed by the request and response system. User name/password combination is a good example of such a system. For example, the system requires the a1i password and responds with the Ali password. This is because only Ali knows the password.
(1) server-side user verification
This method is used to verify the PHP program with the minimum requirements on the server. You only need Apache to manage user authentication.
Authname "secret page" # The Realm
Authtype basic
# The password file has been placed outside the Web tree
Authuserfile/home/car2002/website. pw
<Limit get post>
Require valid-user
</Limit>
You need to put the above file (File Name:. htaccess) in the area to be protected. You can use Apache's htpasswd program to create a file that contains a combination of user names and passwords. Place the file outside the web directory tree and only the owner of the file can view and modify the file. Of course, the web server must be able to read this file.
If you want to read the protected directory, the web server requires the browser to provide the user name and password. In the browser pop-up dialog box, users can enter their usernames and passwords. If the user name and password match the password file, the user is allowed to read the protected page. Otherwise, the error page is displayed, indicating that the user has not passed the verification. The protected domain is displayed so that the user can know the user name and password entered.
(2) user identification and verification in PHP
Compared with user identification and verification on the Apache server, user identification and verification in PHP have the following advantages:
A. You can log out.
B. It may be invalid. If the user does not browse your website 40 minutes after Logging On, you can force them to pass the verification again.
C. customizable.
D. Database-based. You can use data stored in a variety of databases to authenticate users and record detailed logs of visitors accessing the website.
E. Can Be Used on each page. On each page, you can determine whether verification is required.
F. You can also make the browser pop-up dialog box. The following example shows how to retrieve the user name and password from the MySQL database: Ask the user to enter the user name and password.
<?
If (! Isset ($ php_auth_user )){
Header ("www-Authenticate: Basic realm = \" Restricted Area \"");
Header ("HTTP/i2.16401 unauthorized ");
Echo "You failed to provide the correct password... \ n ";
Exit;
} Else {
Mysql_select_db ("users ");
$ User_id = strtolower ($ PHP ^ auth_user );
$ Result = mysql_query ("select password from users ".
"Where username = '$ username '");
$ ROW = mysql_fetch_array ($ result );
If ($ php_auth_pw! = $ Row ["password"]) {
Header ("www-Authenticate: Basic realm = \" Restricted Area \"
Header ("HTTP/i2.16401 unauthorized ");
Echo "You failed to provide the correct password... \ n ";
Exit;
}
}
?>
Only users with a working username/password combination can see this
(3) Check IP addresses
It is generally believed that an IP address uniquely identifies a visitor. But this is not the case. The proxy server can send requests from different users with the same IP address. In addition, IP address theft is also common. IP addresses are useful for detection, but they are quite limited. For example, if you are a forum moderator, you find that a user is pasting unhealthy and illegal content. You can find the IP address of the user who connects from the IP address to the Forum. Use the following command to obtain the source IP address of a specific request:
# IP = $ remote_addr
4. Use PHP encryption technology
In PHP, encryption technology is mainly used to encrypt information, generate verification and summarization. Encryption technology can greatly enhance security performance. Here we will only describe the concepts of encryption technology. If you want to learn more, please refer to some good EncryptionTechnical materials. The standard of encryption technology is the application encryption technology of BMCE Schneier, which is worth reading. His website (www.counterpane.com/labs.html) is a good starting point for searching encrypted technical materials on the Internet. Data encryption is a very complex topic. Here is a brief introduction.
Most of the encryption functions in PHP are provided by the mcrypt library and mhash library. You need to install these two libraries in the system and add the -- ith-mcrypt and -- ith-Hash options during compilation. PHP supports the mcrypt library from version 3.013.
5. Use SSL Technology
SSI is short for server side encryption DES. Using a web server with the SSL (Secure Socket protocol layer) function can improve the security performance of the website without changing a line of code. SSI uses encryption to protect the information flow between the Web server and the browser. SSL is used not only to encrypt data streams transmitted over the Internet, but also to authenticate the two parties. In this way, you can shop online safely without worrying about your credit card information. This feature makes SSL applicable to areas where important information is exchanged, such as e-commerce and web-based mail.
SSL uses the public key encryption technology. The server sends a public key to the client at the end of the connection to encrypt the information. The encrypted information can only be unlocked by the server with its own private key. The client encrypts data with a public key and sends the key to the server to uniquely identify itself. This prevents spoofing by impersonating the server or the client between the two ends of the system.
The encrypted HTTP connection uses port 443 instead of port 80 to distinguish it from the common unencrypted HTTP connection. When the client uses encrypted HTTP connections, port 443 is automatically used instead of port 80. This makes it easier for the server to respond accordingly.
On the Apache server, you can directly edit the server configuration file or create a. htaccess file in the directory where SSI is needed to start ssi. Log on to the server, find the directory where the configuration file is stored, open the file SRM. conf in the text editor, and find the following lines:
# If you want to use server side except des, or CGI outside
# Scriptaliased directories, uncomment the following lines.
# Addtype text/X-server-parsed-html. shtml
# Addtype application/X-httpd-CGI. cgi
Remove the two rows starting with addtype and the "#" symbol at the beginning of each row. Save the modification, and then open the file access. conf.
<Directory/usr/local/etc/httpd/htdocs>
# This may also be "NONE", "all", or any combination of "indexes ",
# "Includes", or "followsymlinks"
Options indexes followsymlinks
</Directory>
Change the options indexes followsymlinks to: Options indexes followsymlinks between des.
6. Use the suexec mechanism of Apache
Generally, CGI programs or PHP scripts can only run with the user permission to start the Web server (usually www or nobody ), in this case, you can read, write, and modify the files (such as scripts and password files) generated by another user's CGI and PHP scripts ). It may also allow users to connect to other users' databases, but this is related to the database configuration. For example, the default configuration of MySQL is allowed, but it can be compensated by forcing the database to perform password verification. PHP's safe-mode reduces these issues, but all scripts are still running with the same user ID. Apache can solve this problem. Suexec (Change User identification before execution) is a small tool that allows you to run CGI programs as any user identity, including PHP scripts, except for root users. It can also be used with usedir and virtualhost.
Suexec is also called CGI encapsulation. This means that before the script runs, it needs to pass a series of prescribed security checks. With apache2. Suexec released in version 0 has 26 checkpoints. Suexec can solve some security problems while allowing users to develop and execute their own scripts more securely. However, suexec reduces service performance because suexec can only run on the CGI version of PHP, while the CGI version is slower than the module version. The reason is that the module version uses threads, while the CGI version uses processes. Environment conversion between different threads and access to public storage areas are obviously much faster than between different processes. Another problem with using suexec is that it increases the difficulty of writing and using PHP scripts. Make sure that the script passes the suexec check. Otherwise, your script will not be executed. We recommend that you use suexec when you have high security performance requirements, at the cost of speed.
7. Create a secure PHP script
There are many programming techniques to make PHP scripts run more securely. The most important one is to use some common security knowledge. Running PHP is safer than running CGI scripts, but it still has many errors. Switching to safe running mode can limit the results of errors. If an error occurs in your PHP script, it may be found and used to damage the site or even the database. Therefore, regular backup is also necessary.
(1) Security Settings Software
Web-based applications, such as online directories, usually run without close monitoring. If an error occurs, you cannot take immediate action. Generally, visitors are the first to notice the problem. You should make it easy for them to report the problem. Furthermore, you can track these problems by the scripts that make up the website. For example, your visitor may do something unexpected. Or you may not check the returned values of important functions, and the script may run in an unpredictable way.
Write safer programs to avoid these problems. For example, you should check the return value of the database function. If the database crashes, the error information page should be displayed to the user, rather than a full screen error. You can even let the script automatically notify you when serious problems occur, such as database crashes and hard disk space is full. You should also check all data sent from the user. Obviously, the latter is more important. If your program can handle all kinds of errors, your program is not only more reliable, but also can take less time to maintain. These times can greatly make up for the extra time you spend developing programs.
(2) store and exchange sensitive information
Obviously, you should try to avoid passing sensitive information on the Internet in the form of get, post, cookie or URL encoding, so that information can be easily stolen. This can be done using an SSL-enabled web server because it encrypts all the information flows between the site and the visitor's browser.
If you do not have a web server that supports SSL, you need other methods. For example, there is no need to always send data to the browser; store the data in the database, and only send keywords to the browser, which makes it easy to find the required data; and send all the data in encrypted form. The simplest way to implement this function is to use session. PhP4 supports the local session function, and php3 uses the phpmb library.
HTTP is a stateless protocol, which is not responsible for the status information of better connections. Therefore, it cannot track various client information, and the session changes. When a user browses a CGI script that supports the session function, he can save the user information under the consent session ID before leaving the webpage, that is, user information can be accessed from different webpages simultaneously.
If you do not use the safe mode of PHP or run php In CGI Mode Under suexec, it is impossible to monitor the content of your file. At this time, the only way to prevent others from reading data is to save the data to the database as soon as possible.
(3) check user input
Per1 has a taint checking feature ). When the stain check is effective, you cannot run a function containing suspicious variables even if no major error occurs. A variable becomes suspicious when its value is part or whole of the data provided by the user, because the data is considered insecure. This improves system security. PHP does not have this feature, but PHP has the escapeshellcmd function, which can achieve the same effect. Another way to prevent users from abusing scripts is to allow only strictly-checked input.
(4) use the latest PHP version 4.2.xx
For a long time, as one of the biggest selling points of the server-side scripting language, PHP automatically creates a global variable for the value submitted from the form. In PHP 4.1, PHP producers recommended an alternative way to access and submit data. In PHP 4.2, they canceled the old practice. In PHP 4.1, a set of special data is added to access external data. These arrays can be called within any range, making it easier to access external data. In PHP 4.2, register_globals is disabled by default to encourage the use of these arrays to prevent inexperienced developers from coding insecure PHP code. This change is made out of security considerations.
Iii. Summary
A thoroughly secure system is theoretically impossible, so we mean that security is only balanced between the cost and availability. If every variable submitted by the user requires biological verification (such as fingerprint identification), an extremely high level of reliability will be achieved. However, it may take tens of minutes for a user to enter a table. In this case, the user will bypass the security authentication method. The reliability of a system can only be determined by the weakest link in the chain. In any security system, people are the most vulnerable connections. technology alone cannot secure the system.
PHP is still developing, and you need to pay attention to its security information frequently. Here I recommend you pay attention to the security focus (www.security-focus.com) and packetstorm (www.packetstorm.com ).