Write PHP security policies. PHP was initially called PersonalHomePage. later, as PHP became a very popular scripting language, its name also changed, which is called plusionalhypertextpreprocessor. PHP with PHP4.2 was initially called the Personal Home Page. later, as PHP became a very popular scripting language, the 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. it is installed on a web server as a module or as a separate CGI program, 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 /"
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 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. Apache authentication is used to protect data from being exposed. Alternatively, you can design your own access control model using LDAP,. htaccess files, and introduce this code as part of it in a PHP script. 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
Require valid-user
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 encryption technical 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 ).
Home Page. later, as PHP became a very popular scripting language, the name also changed, called Professional HyperText PreProcessor. Use PHP4.2...