Security | program PHP is a cross-platform server-side embedded scripting language. It borrows heavily from the syntax of the C,java and Perl languages and is coupled with PHP's own features, enabling Web developers to quickly write dynamically generated pages. The latest version PHP5.01 supports most of the current databases (Mysql, PostgreSQL, Oracle, DB2, Sybase, etc.). Also, PHP is completely free, and you can download it free from the official PHP site (http://www.php.net) without spending money. PHP expands the functionality of Web server and implements the back-end extension interface for best Web services, see Figure 1.
Figure-1 PHP expands the functionality of the Web server
PHP Full name professional hypertext preprocessor. The Web servers that support it with the latest PHP5.01 are: Apache, Microsoft Internet information Sereve, Microsoft Personal Web server, AOL server, Netsca PE 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. Since we can make use of PHP in many different ways, it has many settings to control its behavior.
A large set of optional parameters guarantees that you can use PHP for many different purposes, but it also means that the combination of these parameters and the server-side configuration poses some security issues. PHP's configuration has the same flexibility as its code. PHP can be used to build a complete server application with all shell users, and it can be used in tightly controlled environments as a simple service-side inclusion, with little risk. How you build the environment, and how well it's secured, depends largely on the PHP developer. Note: All operations in this article are done under Red Hat Linux 9.0.
First , security start from scratch
Before compiling PHP, first make sure that the operating system version is up to date and that the necessary patches must be installed. 4 issues to note during the installation of PHP:
1, the use of Apachetoolbox integration Apache,php,mysql the current best web site to build a gold combination is linux+apache+mysql+php, but in the actual work process need to download, install, configure Apache, PHP and MySQL, and need to modify the Apache httpd.conf, php php.ini and MySQL configuration file, if you also need to provide SSL functionality, it also has to download the correct SSL Apache module, and customizing its. ini file, and so on, any of these steps will cause the Web site to run incorrectly.
Trying to be fully configured at once is even more difficult for an experienced Linux network administrator. The Apache Toolbox is written in Shell script. Apache Toolbox can be very handy for you to customize your Apache to your requirements in the Apache supported 52 Third-party packages and 36 modules to choose from.
The custom process is completely menu-driven and has a simple description. All components are installed in source code, and if the RPM package is found to be problematic during installation, it will also use wget to download the new available component packages. Trust is a useful tool for those network administrators.
The Apache Toolbox can be installed under the gun command line or under the X window to facilitate readers to read this article to install under the X window for example. Download the latest Apachetoolbox installation package in www.apachetoolbox.com. Including Apache2.0,mysql3.23.51,php4.3,python 2.0, PostgresSQLv7.1 and other common construction station software and APC (a module for PHP to provide cache), Apache Toolbox Apache Toolbox provides a simple compiled Apache method that allows you to easily install Apache, ssl,php, Zendoptimizer, mod_auth-nds,mod-dynvhost,webdav,mod_fastcgi, Mod_gzip,mod_layout,mod_throttle,mod_accessref, Mod_auth_sys, Mod_bandwidth, Mod_auth_ldap, Mod_perl, OpenLDAP. And so on, and the latest version of the GD library that supports PNG format. It supports a full menu interface.
Figure-2 Apachetoolbox Installation Interface 2, in accordance with the Apache module installed when PHP is used as the Apache module, it will inherit Apache user rights (typically the user "nobody"). This will have some impact on security and authorization mechanisms.
For example, if you use PHP to access a database, you will make the database accessible to the user "nobody" unless the database itself has built-in access control. This means that malicious scripts can access and modify the database without even requiring a username and password. It is entirely possible for cyber hackers to inadvertently visit the database administrator's WEB page and delete all the databases here.
You can use the Apache authentication mechanism to prevent these occurrences, or you can design your own access patterns using LDAP or. htaccess files, and include them as part of your PHP script.
Typically, once the security mechanism is established and the PHP is used (in this case, for Apache users) to take only a small risk, we find that PHP is prevented from writing any files to the user directory at this time, or it may be blocked from accessing and changing the database. The security is equal regardless of the quality of the files being written to the object being prevented and the entry of the database transaction.
At this point, a frequent security error is to give Apache root permission, or to use other methods to elevate Apache capabilities.
Giving the Apache user root permissions is dangerous and potentially compromising the entire system. As a result, operations such as sudo, chroot, or running as root account should not be considered for use by non-security professionals. There are a few simpler situations. You can use Open_basedir to control and limit the directories that PHP can use. You can also establish a dedicated area of Apache to restrict all web-based activities to non-users, systems, and files.
3, put the PHP parser outside the web directory
A very high security approach is to place the PHP parser somewhere outside the WEB file directory tree, for example, to/usr/local/bin. The only drawback to this is that you now need to add something similar to the following in all the first rows that contain PHP tag files:
You need to make these files executable files. In other words, treat them like any other CGI script. These CGI scripts may be in Perl, SH, or any other use of #! The shell-escape mechanism to start their own scripting language to write. To enable PHP to properly handle PATH_INFO and path_translated information in this method, you must use the configuration parameter--enable-discard-path when compiling the PHP parser. Here is an example of a PHP foot that can be run as a CGI program.
#!/usr/local/bin/phpecho ' This are a My small program '
|
4, the last PHP please upgrade to the latest stable version: 4.3.8.
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.3.8, 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. Link: http://www.php.net/downloads.php
second, the safe use of PHP
1. Install security Module
The PHP security model is designed to attempt to resolve shared server (Shared-server) security issues. In structure, it is unreasonable to try to solve this problem on the PHP layer, but it is very unrealistic to modify the WEB server layer and the operating system layer. So many people, especially ISPs, are currently using safe mode.
Table-1. Safe Mode configuration Instructions
Name |
Default value |
Type |
Safe_mode |
"0" |
Boolean type |
Safe_mode_gid |
"0" |
Boolean type |
Safe_mode_include_dir |
Null |
String |
Safe_mode_exec_dir |
"" |
String |
Safe_mode_allowed_env_vars |
Php_ |
String |
Safe_mode_protected_env_vars |
Ld_library_path |
String |
Disable_functions |
"" |
String |
Disable_classes |
"" |
String |
Open_basedir |
Null |
String |
The following is a brief explanation of this configuration option.
(1) Safe_mode Boolean
Whether to enable Safe mode for PHP.
(2) Safe_mode_gid
By default, Safe mode does a UID comparison check when the file is opened. If you want to relax it to a GID comparison, open Safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) to check for file access.
(3) Safe_mode_include_dir
Cross Uid/gid checks when this directory and its subdirectories (directories must be included in include_path or with full paths) include files.
Starting with the PHP 4.2.0, this directive accepts a semicolon-delimited path, not just a directory, from a style similar to the include_path instruction.
(4) Safe_mode_exec_dir
If PHP uses safe mode, System () and other functions that perform system programs will refuse to start programs that are not in this directory.
(5) Safe_mode_allowed_env_vars
Setting some environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe mode, users can only change the environment variables whose names have the prefixes provided here. By default, users can only set environment variables (such as Php_foo = BAR) that start with Php_.
(6) Safe_mode_protected_env_vars
This directive contains a comma-delimited list of environment variables that the end user cannot use Putenv () to change these environment variables. You cannot change these variables even when you have set up permission modifications in Safe_mode_allowed_env_vars.
(7) Disable_functions
This directive allows you to prohibit certain functions based on security reasons. Accept a comma-delimited list of function names as arguments. Disable_functions is not affected by the security mode. This directive can only be set in php.ini. For example, you cannot set it in httpd.conf.
(8) Disable_classes
This directive allows you to disable certain classes for security reasons. Separate the class names with commas. Disable_classes is not affected by the security mode. This directive can only be set in php.ini. For example, you cannot set it in httpd.conf. This directive is available from PHP 4.3.2.
(9) Open_basedir
Limit the files that PHP can open to the specified directory tree, including the file itself. This directive is not affected by Safe mode turning on or off.
2. 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: 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. 3, 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" authtype basic# The password file has been placed outside the web Treeauthuserfile/hom E/car2002/website.pw<limit Get post>requirevalid-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. Users can unregister authentication, which is not possible in Apache.
B, can be invalidated. You can make the landing invalid after a certain design. If the user does not browse your site for 60 minutes after logging in, you can force them to validate again.
C, can be customized. For example, you can encrypt a password to be sent with a small javaapplet and decrypt it on a server using the Mcryet library, which can be done on any Java-enabled browser.
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 need to verify, of course, in the Apache server by changing the domain can also do this.
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/1.0 401 Unauthorized"); echo "You failed to provide the correct"; exit;} else{mysql_select_db ("users"); $user _id = Strtolower ($PHP _auth_user); $result = mysql_query ("Select Passwordfrom users " ." WHERE username = ' $username '); $row = Mysql_fetch_array ($result); if ($PHP _auth_pw!= $row ["password"]) {Header ("Www-aut Henticate:basic realm=\ "Restricted area\" Header ("http/1.0 401 Unauthorized"); echo "You failed to provide the correct pass Word...\n "; exit;} }?>only users with a working Username/password combination can
|
Example: HTTP authentication with PHP
PHP's HTTP authentication mechanism works only when PHP is running in Apache mode, so this feature does not apply to CGI versions. In the Apache module's PHP script, you can use the header () function to send "authentication Required" information to the client browser to eject a username/password input window.
When the user enters the username and password, the PHP script containing the URL will be invoked again with the predefined variable php_auth_user, PHP_AUTH_PW, and Auth_type, which are set to the username, password, and authentication type respectively. Predefined variables are saved in an array of $_server or $HTTP _server_vars. The system supports only "basic" authentication. Here is a sample script that forces client authentication on the page:
<?phpif (!isset ($_server[' Php_auth_user ')) {header (' Www-authenticate:basic realm= ' my Realm '); header (' http/1.0 401 Unauthorized '); Echo ' Text to send if user hits Cancel button '; exit;} else{echo "<p>hello {$_server[' php_auth_user ']}.</p>"; echo "<p>you entered {$_server[' PHP_AUTH_ PW ']} as your password.</p> ";}? >
|
(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:
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.
Now about the encryption of PHP programs, in addition to Zend Company's products, the other is not satisfactory. Here I introduce an open source product, a lot of good PHP encryption software--php_screw. His advantage is to use the PHP Zend engine, but also to code encryption, and the system platform does not have any relationship, solve the product is placed in other places of confidentiality issues.
(1) Installation Php_screw
#wget Http://belnet.dl.sourceforge.net/sourceforge/php-screw/php_screw-1.3.tgz#tar zxvfphp_screw.1.3.tar.gz # CD php_screw.1.3#/opt/php/bin/phpize #/configure--with-php-config=/opt/php/bin/php-config # VI my_screw.h# This is a cipher file, Users can set their own encrypted password # make# CP./modules/php_screw.so/usr/local/php/lib/php #cd Tools # make #make生成screw this executable file, which is used to encrypt PHP files, Generates the encrypted. php file.
|
(2) Encrypted file:
Encrypting a file is a screw file generated with the previous make command to generate a new encrypted file.
Example: Encrypting/opt/php/htdocs/index.htm File
#./screw/opt/php/htdocs/index.htm
|
The cryptographic program generates the encrypted file called index.php, and the original encrypted file is automatically backed up into Index.php.screw. After encrypting the files that the product will encrypt, you can delete the backup files. Back up php_screw.so and screw files, and you can continue to use them later to encrypt and interpret. Finally, deletes the Php_screw directory. 5. Using SSL Technology
SSL is an abbreviation for the 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. SSL 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 SSL 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.
Example: How to establish an SSL server that accepts strong encryption requests only, while allowing stronger encryption for external browsers?
This feature is referred to as server-Gated Cryptography (Server Gated Cryptography [SGC]) and is described in detail in readme.globalid documentation. Simply put: The server has a server ID issued by a special CA certificate from VeriSign to enable strong encryption on external browsers.
The process is as follows:
The browser uses an external password to connect, the server returns its global ID ID card, and the browser verifies its password group before the subsequent HTTP traffic is generated.
The question now is: How to allow such a promotion, and forcibly use strong encryption. In other words, the browser must use strong encryption at the start of the connection, or promote strong encryption, but maintaining an external password is not allowed. The following is a clever solution to this problem:
httpd.conf:# allows all passwords to be used during the initial handshake phase, # to allow the external server to elevate the password group sslciphersuite through the SGC function all:! adh:rc4+rsa:+high:+medium:+low:+sslv2:+exp:+enull<directory/usr/local/apache2/htdocs># But it will eventually reject all browsers that do not have an elevated password group Sslrequire%{ssl_cipher_usekeysize}>= 128</directory>
|
6, 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) Reasonable storage and exchange of 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. For example, if you need to enter an IP address, you should check that this IP address is very effective. You can do this with regular expressions. The following function example verifies whether a string contains a valid IP address.
function Validate_ip ($IP) {if is_string ($IP) && ereg (, ^ ([0-9]{1,3}) \. ( [0-9] {l,3}) \. ' ([0-9]{1,3}] \. ([0-9]{1,3}) $ ', $ip, $part)] {if ($part [l] <= 255 && $part [2]<= 255 && $part [3] <= 255&& $p ART[4] <= 255) return true;# Valid IP}return false;# IP}
|
The security flaw in many PHP programs is not the programming language itself, but the security of submitting data that is not considered in coding. So for users to submit data, you should carefully check the code to ensure that any variables submitted by the Web browser are checked accordingly. Here is a dangerous variable to use:
<?php//Delete files from a user directory ... Could it be another user's file? Unlink ($evil _var)//Note access log ... Perhaps not necessary? Fputs ($fp, $evil _var); >
|
third, the operating system itself patch
Patching a known vulnerability to the system is the most basic responsibility of the system administrator, and this is also the last line of defense. After the above configuration, although not impregnable, but also to a considerable extent to the attacker's test caused a lot of trouble, even if the PHP script program has a more serious vulnerabilities, the attackers can not cause the actual damage.
Iv. Summary
The above describes the security policy of PHP, the application of encryption and SSL, and any authentication identification with PHP. 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.
The best security policies can often be less clearly adapted to the needs of the environment, which does not prevent users from completing their work or unduly burdening the code writer with complex situations.
PHP as an open source software, open mode is a double-edged sword. From the mechanism, developers all over the world can get the source code, to find out the flaws in it, it seems that security should be better, but at the same time, if the network manager can not update the version in time, will leave a security risk.
Moreover, there are many factors that affect security. From the programming level to the user's level of use, and so on, will affect the security of the system. Simply by opening or closing the source code, you cannot fundamentally solve the security problem. If you are a PHP programmer, you often need to look at the appropriate site, whether there are patches, whether there is a bug fix, whether you need to upgrade. Don't get lucky, or a shell script might take your site. Apply a famous saying: Your server will never be taken over by hackers the next day.
PHP server running software mainly includes: Samba,ftp,telnet,ssh,mysql,apache,mozilla, these software, mostly open source software, and are constantly upgraded, stable version and beta version appear alternately. On www.samba.org and www.apache.org, the latest changelog is written in the words: Bug fix, security bug fix. Therefore, the PHP network administrator should always pay attention to the relevant site bug fix and upgrade, timely upgrade or add patches. This article hopes that PHP will help you find the right combination of freedom and security you really need.