PHP was originally called the personal Home Page, and later, as PHP became a very popular scripting language, the name changed, called Professional hypertext preprocessor. Take PHP4.2 as an example of a Web server that supports it: Apache, Microsoft Internet information Sereve, Microsoft Personal Web Server,aolserver,netscape Enterprise and so on.
PHP is a powerful language and interpreter that can access files, execute commands, or open links on the server, either as a module or as part of a Web server installation or as a separate CGI program. These features make PHP run with security issues. Although Ph P is deliberately designed to be a safe language than CGI programs written in Perl or C, the correct use of some of the configuration options at compile time and in operation and the appropriate application code will guarantee the security of their operation.
First, security starts from the beginning of compiling PHP.
Before compiling PHP, make sure that the operating system version is up-to-date and that necessary patches must be installed. In addition, the use of compiled PHP should also be the latest version, about 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
There are 3 issues to be aware of when installing a PHP compilation:
1. Only allow CGI files to be executed from a specific directory: first delete the default handle for the CGI script, and then add the Scriptalias directive 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/"
AllowOverride None
Options None
Order Allow,deny
Allow from all
AllowOverride None
Options execcgi
Order Allow,deny
Allow from all
The first parameter of Sriptalias indicates the available relative path in the Web, and the second parameter indicates the directory where the script is placed on the server. should be for each directory
Aliases are used in directory, which makes it possible for people other than the system administrator not 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 issues, and you may not want users to create their own CGI. The Apache default configuration is to comment out Cgi-script handles, but there are/cgi-bin directories that use Sriptalias and directory directives. You can also disallow CGI execution, but still allow PHP scripts to execute.
2. Put the PHP parser outside the web directory
It is important to put the PHP parser outside the web directory tree. This prevents the Web server from abusing PHP's parser. Especially
Do not place the PHP parser in the Cgi-bin or the directory where the CGI program is allowed to execute. However, it is not possible to parse the script with the action, because the PHP parser is mostly placed in a directory capable of executing CGI when the PHP script is executed as a CGI program to put the PHP parser out of the web directory tree.
If you want PHP scripts to be executed as CGI programs (which can put the PHP parser outside the web directory tree), you can:
(1) All PHP scripts must be in a directory that can execute CGI programs.
(2) The script must be executable (only in the Unix/linux machine).
(3) The script must include the path of 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 to be test in the current directory. The PhP4 script becomes executable. Here is a small example of a PHP pin that can be run as a CGI program.
#!/usr/local/bin/php
echo "This was a My small CGI program"
3. Install by Apache module:
When PHP is used as an Apache module, it inherits the user rights of Apche (typically the user is "nobody"). This is the point for security and
Validation has a number of implications. For example, using PHP to access a database, unless the database supports built-in access control, will have to set the database for the user "nobody"
Accessible permissions. This would mean that a malicious script could access and modify the database without accessing the user name and password. The Apache authentication is used to protect the data from being exposed, or you can use LDAP,. Design your own access control model, such as the htaccess file, and introduce this code as part of the PHP script. Typically, once security is established, PHP users (in this case, Apache users) are significantly less risky and will find that PHP protection is now blocked from writing potentially infected files to the user directory. The most common security error here is to give the 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 the sudo,chroot of large security risks. Unless you have an absolute grasp of 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 have developed. Using Safe Mode causes PHP to check for security issues when it runs the function. 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 wait: The program to be executed must be in a specific directory (default is/usr/local/php/bin). This value can be set with the-with-exe-dir option when compiling PHP.
Mysql-connect: This function connects to the MySQL database with an optional user name. In safe mode, the user name must be the owner of the script that is currently being executed, or the user name (typically nobody) that runs httpd.
HTTP authentication: The user ID (number type) that contains the HTTP validation code script owner is automatically added to the authentication domain. This prevents someone from tricking the password to spoof HTTP authentication scripts on the same server.
2. Use user identification and verification
Sometimes a user needs to be uniquely identified. The user is usually confirmed by the request and response system. Username/password combination is a good example of this system, such as the system required to give the a1i password, in response to Ali's password. This is verified because only Ali knows the password.
(1) Server-side user verification
This is the authentication method that is required to minimize the PHP program requirements on the service side. 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
Require Valid-user
You need to put the above file (file name. htaccess) where you need to protect it. With Apache's HTPASSWD program, you can create a file that contains a combination of user names and passwords. Put this file outside the Web directory tree and 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 user name and password. The Browser popup dialog box allows the user to enter their user name and password. If the user name and password match the password file, the user is allowed to read the protected page, otherwise the error page will be given and the user is not authenticated. The protected domain is displayed so that the user knows which user name and password to enter.
(2) User identification and verification in PHP
User identification and validation in PHP has the following advantages over user identification and validation on the Apache server side:
A, can be written off.
B, can be invalidated. If users do not browse your site for 40 minutes after logging in, you can force them to re-pass the verification.
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 ' access to the site.
E, available for each page. You can decide whether or not you want to validate on each page.
F, you can also make the browser pop-up dialog box. The following example shows how to retrieve the name and password from the MySQL database: Let the user fill in the user name 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 see this
(3) IP address detection
It is generally accepted that an IP address uniquely identifies a visitor. But that's not really the case. The proxy server can send requests from different users with the same IP address. In addition, the misappropriation of IP addresses is also prevalent. It is useful to detect IP addresses, but they are quite limited. For example, you are a forum moderator, you find a user paste some unhealthy, illegal content. You can find his IP address and evict the user from this IP forum. Use the following line command to get the source IP address for a particular request:
# ip = $REMOTE _addr
4. Using PHP encryption technology
In PHP, encryption is used primarily to encrypt information, generate checksums, and digest. The use of encryption technology can greatly enhance security performance. Here are just a few of the concepts that use cryptographic techniques. If you want to know more, you should refer to some good encryption technology information. The standard of cryptographic 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 finding encrypted technical data on the Internet. Data encryption is a very complex topic, just a brief introduction here.
Most of the 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 starts to support the MCrypt library.
5. Using SSL Technology
SSI is an abbreviation for the English server Side includes. Using a Web server with SSL (Secure Sockets Layer) functionality, you can improve the security performance of your website without changing one line of code. SSI uses cryptographic methods to protect the flow of information between the Web server and the browser. SSL is used not only to encrypt traffic that passes over the Internet, but also to provide both authentication. This way, you can safely shop online without worrying about other people's information with your credit card. This feature makes SSL suitable for those 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 at the end of the connection to encrypt the information, 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 someone from impersonating the server or the client on both sides of the system.
An encrypted HTTP connection replaces the 80 port number with a 443 port number to distinguish it from 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 the directory where you need to use SSI. Log in to the server, locate the configuration file directory, open the file srm.conf using the text editor, and find the following lines:
# If you 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
The two lines starting with AddType and the "#" symbol at the front of each line are 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. Using Apache's suexec mechanism
Typically, CGI programs or PHP scripts can only be run with the user right to start the Web server (usually www or nobody), and one of the things that can happen is that files that are generated by another user's CGI and PHP scripts (such as scripts and password files) are read and written and modified. It may also enable users to connect to other users ' databases, but this is related to the configuration of the database. The default configuration for MySQL is allowed, but it can be remedied by forcing the database for password validation. PHP's Safe-mode reduces these problems, but all scripts still run with the same user identity. Apache can solve this problem. suEXEC (changing the user ID before execution) is a gadget that allows a CGI program to run with any user ID, including, of course, PHP scripts, except for root users. And 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 of suEXEC has 26 checkpoints. suEXEC can solve some security problems while allowing users to develop and execute their own scripts more securely. However, suEXEC will 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, while the CGI version is the process. It is obviously much faster to transform the environment between different threads and access the common storage area than between different processes. Another problem with using suexec is that it adds to 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 high level of security performance requirements, and at the expense of speed.
7. Create a secure PHP script
There are many programming tricks to make PHP scripts run more safely. One of the most important is to use some safety knowledge. Running PHP is more secure than running a CGI script, but it still has a lot of errors in place. Switching to Safe run mode can limit the results of an error. If there is an error in your PHP script, it may be found and used 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 typically run without close monitoring. If an error occurs, you cannot take immediate action. Usually when the visitor first notices the problem, you should make it easy for them to report the problem. Further, these issues can be tracked by the script that makes up the site. For example, your visitors may do something you don't expect. It may also be that you do not check the value returned by the important function, and the script may run in an unpredictable way.
By writing more secure programs, you can avoid these problems. For example, you should check the return value of a database function, and if the database crashes, it should be the wrong information page instead of the full screen error that is displayed to the user. You can even let the script automatically notify you when a serious problem occurs, such as a database crash, when the hard disk space is full. You should also check all the data coming 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 greatly compensate for the extra time you spend developing your program.
(2) Storing and exchanging sensitive information
Obviously, you should try to avoid transmitting sensitive information on the Internet in the form of Get, POST, cookie, or URL encoding, so that information is easily stolen. This can be done with a Web server that supports SSL because it encrypts all traffic between the site and the visitor's browser.
If you do not have a Web server that supports SSL, then you need another way. For example, it is not necessary to always send data to the browser, keep 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 an encrypted form, and so on. The simplest way to achieve this is to use the session. The PHP4 supports localized session functionality, and PHP3 uses the PHPMB library.
HTTP protocol is a stateless protocol, it is not responsible for good connection status information, so can not track the client's various information, the presence of the session to change the situation. When a user browses a CGI script that supports session functionality, the user information can be saved under the consent session ID before he leaves the page, which means that user information can be accessed between different pages.
If you do not use PHP's Safe mode or run PHP as a CGI under suexec, it is impossible to monitor the contents of your files. The only way to prevent others from reading the data is to save the data to the database as soon as possible.
(3) Check user input
Per1 language has a feature called spot detection (taint checking). When spot detection is in effect, you cannot run a function that contains a suspicious variable, even if no significant error has occurred. A variable that becomes suspicious when its value is part or all of the data provided by the user, because the data is considered unsafe. This improves the safety of the system. 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 scripts is to allow only strictly 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 values submitted from the form. In PHP 4.1, the creators of PHP recommend an alternative way to access the submitted data. In PHP 4.2, they canceled that old practice. In PHP 4.1, a special set of data was added to access external data. These arrays can be called in any scope, making it easier to access external data. In PHP 4.2, register_globals is turned off 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.
Iii. Summary
A completely secure system is theoretically impossible, so the security we refer to is only a balance between cost and availability. If each of the variables submitted by the user requires a biological validation (such as fingerprint identification), then a very high level of reliability will be obtained. But it will also cause users to fill out a form for a few 10 minutes. The user is then taken to bypass the security verification method. The reliability of a system can only be determined by the weakest link in the chain. In any security system, the person is the most vulnerable connection, technology alone can not make the system security.
PHP is still 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).
http://www.bkjia.com/PHPjc/314931.html www.bkjia.com true http://www.bkjia.com/PHPjc/314931.html techarticle PHP was originally called the personal Home Page, and later, as PHP became a very popular scripting language, the name changed, called Professional hypertext preprocessor. Take PHP4.2 as ...