PHP was originally called Personal home Page, and then as PHP became a very popular scripting language, the name changed, called Professional hypertext preprocessor. For example, the Web server that supports it is PHP4.2: Apache, Microsoft Internet information Sereve, Microsoft Personal Web Server,aolserver,netscape Enterprise and so on.
PHP is a powerful language and interpreter, whether included as a modular approach to a Web server or installed as a separate CGI program, to access files, execute commands, or open links on the server. These features all make PHP runtime security issues. Although Ph P is deliberately designed to be a more secure language than a CGI program written in Perl or C, the proper use of compile-time and Run-time configuration options and appropriate application coding will ensure that it is safe to run.
First, the security starts with compiling PHP.
Before compiling PHP, first make sure that the operating system version is up to date and that the necessary patches must be installed. In addition, the use of compiled PHP should also be the latest version of PHP security vulnerabilities are often found, please use the latest version, if you have installed PHP please upgrade to the latest version: 4.2.3
RELATED Links: http://security.e-matters.de/advisories/012002.html
3 issues to note during the installation of PHP:
1. Only allow CGI files to be executed from a specific directory: first delete the default handle to the CGI script, and then add Scriptalias instructions to the http.conf file in the directory where you want to execute the CGI script.
#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 the Sriptalias indicates the available relative paths in the Web, and the second parameter indicates the directory where the script is placed on the server. should be on each directory
Aliases are used in directory, which makes it possible for people other than the system administrator to know the list of CGI scripts on the Web server.
Directory allows users to create their own CGI scripts. Sriptaliasmatch can also be used, but directory is easier to use. Allow users to create their own
CGI scripts can cause security problems and you may not want users to create their own CGI. The Apache default configuration is to comment out the processing handle of the cgi-script, but there are/cgi-bin directories using Sriptalias and directory directives. You can also disable CGI execution, but still allow PHP scripts to execute.
2. Put the PHP parser outside the web directory
It is important to place the PHP parser outside the web directory tree. This will prevent the Web server from abusing PHP's parser. Especially
Do not place the PHP parser in Cgi-bin or in directories that allow CGI programs to execute. However, it is not possible to use the action parsing script, because when you use the Action directive, most PHP parsers are placed in a directory that can execute CGI only if the PHP script executes as a CGI program, the PHP parser can be placed outside the web directory tree.
If you want your PHP script to execute as a CGI program (which allows you to place the PHP parser outside the web directory tree), you can:
(1) All PHP scripts must be located in a directory capable of executing CGI programs.
(2) The script must be executable (only in the Unix/linux machine).
(3) The script must include the path to the PHP parser in the file header.
You can use the following command to make the PHP script executable:
#chmod +x TEST.PHP4
This causes the file name in the current directory to be named Test. The PhP4 script becomes executable. Here is a small example of a PHP foot that can be run as a CGI program.
#!/usr/local/bin/php
echo "This is a" I small CGI program
3. Install by Apache module:
When used with PHP as the Apache module, it inherits the Apche user rights (typically the user is "nobody"). This is for security and
Validation has a lot of impact. For example, using PHP to access a database, unless the database supports built-in access control, will have to set up the database for the user "nobody"
The accessibility permissions. This would mean that a malicious script would be able to access and modify the database without accessing the username and password. Apache authentication is used to protect data from exposure, or to use LDAP,. htaccess files, and so on, design your own access control model and introduce this code as part of the PHP script. Typically, once the security is established, the PHP user (this case, the Apache user) is significantly less risky and will find that the PHP protection is now banned from writing possible virus files to the user directory. The most common security error here is giving Apache server root (root) permissions. It is extremely dangerous to elevate Apache user rights to root permissions. May endanger the entire system, so be careful to use sudo,chroot security hidden orders, and so on. Unless you have absolute control over security, do not let it run with root privileges.
Second, make the use of PHP more secure.
1. Running PHP in Safe mode
Running PHP in Safe mode is a good way to make PHP scripts safe to use, especially if you allow users to use PHP scripts that they develop. Using safe mode will allow PHP to check for security issues when running functions. Include, ReadFile, fopen, file, unlink, RmDir, and so on: the included file or the owner of the directory in which the file resides must be the owner of the running script; Exec, System, Passthm et cetera: The program to be executed must be in a specific directory (default is/usr/local/php/bin). You can set this value with the-with-exe-dir option when compiling PHP.
Mysql-connect: This function connects to the MySQL database with an optional username. In safe mode, the user name must be the owner of the currently executed script, or the user name (usually nobody) running httpd.
HTTP authentication: The user ID (numeric type) that contains the HTTP authentication code script owner is automatically added to the authentication domain. This prevents someone from using a password-grabbing program to spoof an HTTP authentication script on the same server.
2, the use of user identification and verification
Sometimes it is necessary to uniquely identify a user. Users are typically identified by the request and response system. User name/password combination is a good example of this system, such as the system requires a a1i password, the response is Ali's password. This verification is because only Ali knows the password.
(1) Server-side user verification
This is the authentication method that is used on the server to minimize the requirements of the PHP program. Just let Apache manage the validation of the user.
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 place the above file (file name. htaccess) where it needs to be protected. With the Apache HTPASSWD program, you can create files that contain a combination of user names and passwords. Put this file outside the Web directory tree, and just let the owner of the file view and modify the file. Of course, the Web server must be able to read this file.
If you want to read a protected directory, the Web server requires the browser to provide a username and password. The Browser pop-up dialog box allows the user to enter their username and password. If the user name and password match in the password file, the user is allowed to read the protected page, otherwise the error page will be given to tell the user not to pass the validation. The protected domain is displayed so that the user knows to enter that username and password.
(2) User identification and verification in PHP
Compared with user identification and authentication on the Apache server side, user identification and authentication in PHP has the following advantages:
A, can be written off.
B, can be invalidated. If the user does not browse your site for 40 minutes after logging in, you can force them to validate again.
C, can be customized.
D, can be based on the database. You can use data stored in a variety of databases to authenticate users and log detailed logs of visitors ' visits to the site.
E, available for each page. You can decide on each page whether you want validation.
F, you can also make the Browser pop-up dialog box. The following example shows how to retrieve the username and password from the MySQL database: Let the user fill in the username and password.
?
if (!isset ($PHP _auth_user)) {
Header ("Www-authenticate:basic realm=\" restricted area\ "");
Header ("http/i.0 401 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/i.0 401 Unauthorized");
echo "You failed to provide the correct password...\n";
Exit
}
}
?>
Only users with a working Username/password combination can
(3) Detect IP Address
It is generally accepted that an IP address uniquely identifies a visitor. But it's not really like that. The proxy server can send requests from different users with the same IP address. In addition, the misappropriation of IP addresses is common. Detection of IP addresses is useful, but quite limited. For example, you are a forum moderator, you find a user to paste some unhealthy, illegal content. You can find his IP address and evict the user from the forum by connecting to the IP. Use the following line of commands to get the source IP address of a particular request:
# ip = $REMOTE _addr
4, the use of PHP encryption technology
In PHP, cryptography is used primarily to encrypt information, generate checksums and summaries. Using encryption technology can greatly enhance security performance. There are only a few ideas for using cryptography. If you want to know more, you should refer to some good encryption technology data. The standard of encryption technology is BMCE Schneier's application encryption technology, which is well worth reading. His website (www.counterpane.com/labs.html) is a good starting point for searching the Internet for information on encryption technology. Data encryption is a very complex topic, just a brief introduction.
Most cryptographic functions in PHP are provided by the MCrypt Library and the Mhash library. You need to load the two libraries in the system and add the--ith-mcrypt and--ith-hash options at compile time. PHP from 3. Version 013 begins to support the MCrypt library.
5. Using SSL Technology
SSI is an abbreviation for English server Side includes. With a Web server with SSL (Secure Sockets Layer) functionality, you can improve the security performance of your Web site without changing one line of code. SSI uses encryption to protect the flow of information between the Web server and the browser. SSL is used not only to encrypt data streams that are passed over the Internet, but also to provide both authentication. This way, you can safely shop online without having to worry about other people's information about your credit card. This feature enables SSL to be used where important information is exchanged, such as E-commerce and web-based Mail.
SSL uses public key cryptography, where the server sends a public key to the client to encrypt the information at the end of the connection, and the encrypted information is only unlocked by the server using its own private key. The client encrypts the data with a public key and sends it to the server's own key to uniquely identify itself, preventing spoofing between the two ends of the system by posing as a server or client.
The encrypted HTTP connection replaces the 80 port number with a 443 port number to distinguish it from the normal unencrypted HTTP. When a client uses an encrypted HTTP connection, it automatically uses port 443 instead of Port 80. This makes it easier for the server to respond accordingly.
Under the Apache server, you can start SSI by directly editing the server configuration file or by creating a. htaccess file in a directory that needs to use SSI. Log on to the server, locate the configuration file, use the text editor to open the file srm.conf, and locate the following lines:
# If you are want to use server side includes, or CGI outside
# scriptaliased Directories, uncomment the following lines.
#AddType text/x-server-parsed-html. shtml
#AddType application/x-httpd-cgi. Cgi
Two lines begin with AddType and the "#" symbol at the front of each row is removed. Save the changes, and then open the file access.conf.
# This may also is ' None ', ' all ', or any combination of ' Indexes ',
# "Includes", or "followsymlinks"
Options Indexes FollowSymLinks
Change the options Indexes followsymlinks to: Options Indexes followsymlinks Includes.
6, the use of Apache suexec mechanism
Usually CGI programs or PHP scripts can only be run with user privileges to start the Web server (usually www or nobody), and one of the things that happens is that you can read and write files (such as scripts and password files) that are generated by CGI and PHP scripts from another user. It may also allow users to connect to other users ' databases, but this is related to the configuration of the database. The default configuration of MySQL is allowed, but it can be remedied by forcing the database for password verification. The Safe-mode of PHP reduces these problems, but all scripts still run with the same user identity. Apache can solve this problem. suEXEC (changing the user's identity before execution) is a gadget that allows CGI programs to be run with any user ID, including, of course, PHP scripts, except for the root user. And it can be used with Usedir and virtualhost items.
So suexec is also called CGI encapsulation. This means that it needs to pass a set of security checks before the script runs. With Apache2. The 0 release suexec has 26 checkpoints. suEXEC can solve some security problems while allowing users to develop and execute their own scripts more securely. But suEXEC can degrade service performance because suexec can only run on CGI versions of PHP, and the CGI version runs slower than the module version. The reason is that the module version uses threads, and the CGI version is the process. Environment conversions between different threads and access to common storage areas are obviously much faster than between different processes. Another problem with suexec is that it increases the difficulty of writing and using PHP scripts. You want to make sure that the script passes the suEXEC test. Otherwise, your script will not be executed. We recommend that you use suEXEC when you have a higher safety performance requirement, and that you have to pay at the expense of speed.
7, create a secure PHP script
There are many programming tips to make PHP scripts run more securely. One of the most important is to use some security common sense. Running PHP is more secure than running a CGI script, but it still has a lot of errors in place. Converting to a safe run mode can limit the results of an error. If you have errors in your PHP script, you may be found and exploited to destroy the site or even the database. So regular backups are also necessary.
(1) Security settings software
Web-based applications, such as online catalogs, are usually run with no close monitoring. If there is an error, you cannot take action immediately. Often visitors first notice what's going on, and you should make it easy for them to report what's going on. Further, these issues can be tracked by the scripts that make up the site. For example, your visitors may do something you can't imagine. Or you may not have checked the value returned by an important function, and the script might run in unpredictable ways.
By writing more secure programs, you can avoid these problems. For example, you should check the return value of the database function, and if the database crashes, the information displayed to the user should be an error message page instead of a full screen error. You can even let your scripts automatically notify you when a serious problem occurs, such as a database crash, or when your hard disk space is full. You should also check all data from the user. Obviously the latter is more important. If your program can handle a variety of errors, your program is not only more reliable, but it can take less time to maintain. These times can make up for the extra time you spend developing your programs.
(2) Storing and exchanging sensitive information
Obviously, you should try to avoid sending sensitive information in the form of Get, POST, cookie, or URL encoding on the Internet, so that the information is easily stolen. This can be done using a Web server that supports SSL, because it encrypts all the information flow between the site and the visitor's browser.
If you do not have a Web server that supports SSL, then you need other options. For example, there is no need to always send data to the browser, save the data in the database, only send keywords to the browser, so it is easy to find the required data, and send all the data in encrypted form, and so on. The easiest way to implement this functionality is to use session. PHP4 supports localized session functionality, PHP3 uses PHPMB libraries.
HTTP protocol is a stateless protocol, it is not responsible for good connection status information, so can not track the client's various information, session of the appearance of change this situation. When a user browses to a CGI script that supports the session function, he can save the user information under the consent session ID before he leaves the page, that is, the user information can be accessed between different pages.
If you don't use PHP's Safe mode or run PHP in CGI under suEXEC, it's impossible to monitor the contents of your files. 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 language has a feature called stain detection (taint checking). When stain detection is in effect, you cannot run functions that contain suspicious variables, even if no significant errors occur. A variable that becomes suspect when its value is part or all of the data provided by the user, as the data is considered unsafe. This can improve system safety. PHP does not have this feature, but PHP has a escapeshellcmd function that can achieve the same effect. Another way to keep users from abusing their scripts is to allow only rigorously checked input.
(4) Use the latest PHP version 4.2.xx
For a long time, one of the biggest selling points of PHP as a server-side scripting language is the automatic creation of a global variable for the value submitted from the form. In PHP 4.1, the producers of PHP recommend an alternative way to access the submitted data. In PHP 4.2, they canceled the old practice. In PHP 4.1, a special set of data is added to access external data. These arrays can be invoked in any scope, which makes access to external data more convenient. In PHP 4.2, register_globals is closed by default to encourage the use of these arrays to prevent inexperienced developers from writing unsafe PHP code. Such changes are made for security reasons.
Third, summary
A thoroughly secure system is theoretically impossible, so what we mean by security is just a trade-off between cost and usability. If each of the variables submitted by the user requires biological validation (such as fingerprint identification), it will achieve very high levels of reliability. But it can also cause users to fill out a form for a few 10 minutes. Users will then take the approach of bypassing security authentication. 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, and technology alone cannot make the system secure.
PHP is still in the process of evolving, and you need to keep an eye on his security information. Here I recommend that you always focus on security focus (www.security-focus.com) and Packetstorm (www.packetstorm.com). &NBSP