How to use PHP to develop secure applications

Source: Internet
Author: User
Tags sybase
PHP is a cross-platform server-side embedded scripting language. It relies heavily on the syntax of C, Java, and Perl, coupled with PHP's own features, so that WEB developers can quickly write dynamic pages. The latest version of PHP5.01 supports the vast majority of databases (Mysql, PostgreSQL, Oracle, DB2, Sybase, and so on ). Another point is that PHP is completely free, and PHP is a cross-platform server-side embedded scripting language. It relies heavily on the syntax of C, Java, and Perl, coupled with PHP's own features, so that WEB developers can quickly write dynamic pages. The latest version of PHP5.01 supports the vast majority of databases (Mysql, PostgreSQL, Oracle, DB2, Sybase, and so on ). Another point is that PHP is completely free of charge. you can freely download it from the official site of PHP (http: // www.php.net. PHP expands the functions of the WEB Server and implements the backend extension interface of the best Web service, as shown in-1.



Figure-1 PHP expands WEB Server functions
PHP is short for Professional HyperText PreProcessor. The latest PHP5.01 is used as an example to support the following WEB servers: Apache, Microsoft Internet information Sereve, Microsoft Personal web Server, AOL server, 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. Since PHP can be used in many different ways, it has many configuration options to control its behavior.

A large set of optional parameters can ensure that you can use PHP for many different purposes, but it also means that the combination of these parameters and server configuration will bring some security issues. PHP configuration has the same flexibility as its code. PHP can be used to build a complete server-side application with the permissions of all Shell users. It can also be used as a simple server-side inclusion in a strictly controlled environment, with only a small risk. How you establish the environment and how secure it is depends largely on PHP developers. Note: all operations in this article are completed under Red Hat Linux 9.0.

   I. security starts from scratch

Before compiling PHP, make sure that the operating system version is up-to-date and necessary patches must be installed. Note the following four issues during PHP installation and compilation:

1. use apachpoliclbox to integrate Apache, PHP, and Mysql. Currently, the best combination of web site construction is Linux Apache Mysql PHP. However, you need to download, install, and configure apache separately during actual work, php and mysql, and apache httpd needs to be modified according to the actual situation. conf, php. ini also has the mysql configuration file. if you still need to provide the ssl function, you have to download the correct ssl apache module and customize it. INI files, etc. any errors in the steps will cause the website to fail to run correctly.

It is difficult for an experienced Linux network administrator to complete the configuration at a time. Apache Toolbox is written in shell scripts. Apache Toolbox makes it easy for you to customize your apache according to your requirements and select among the 52 third-party software packages supported by Apache and 36 modules.

The customization process is completely menu-driven and has simple instructions. All components are installed in source code mode. during the installation process, if an RPM package is found to be faulty, it will use wget to re-download the new available package. I believe it is a useful tool for network administrators.

You can install Apache Toolbox in the GUN command line or in the X Window. to facilitate your reading, this article takes the installation in the X Window as an example. Download the latest apachpoliclbox installation package from www.apachpoliclbox.com. Including common website software and APC (a module that provides Cache for PHP) such as apache2.0, mysql3.23.51, php4.3, Python 2.0, and ipvssqlv7.1 ), apache Toolbox provides a simple way to compile Apache, allowing 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, and openldap. and the latest gd libraries that support PNG format. It supports a full menu interface.


Figure 2 apachpoliclbox installation page

2. install PHP based on the Apache Module. When PHP is used as the Apache module, it inherits the user permissions of Apache (typically the user "nobody "). This will have some impact on the security and authorization mechanisms.

For example, if you use PHP to access the database, unless the database itself has built-in access control, you will enable the database to be accessed by the user "nobody. This means that malicious scripts can access and modify databases without the need for usernames and passwords. It is entirely possible for a network hacker to accidentally access the WEB page of the database administrator and delete all databases here.

You can use the authentication mechanism of Apache to prevent such attacks, or use LDAP or. design your own access mode and include the code as part of your PHP script.

In general, once the security mechanism is established and PHP is used (in this case, Apache users, we found that PHP is forbidden to write any files to the user directory at this time, or it may be forbidden to access and change the database. No matter whether the file is written to the object to be prevented or the database transaction to be written, the security is the same.

At this time, a frequent security error is to grant the Apache root permission or use other methods to improve Apache's capabilities.

It is dangerous to grant the root permission to Apache users, and the entire system may be exhausted. Therefore, operations such as sudo, chroot, or running with the root account should not be performed by non-security experts. There are some simpler cases. You can use open_basedir to control and limit the directories that PHP can use. You can also create a dedicated Apache region to restrict all WEB-based activities to non-users, systems, and files.

3. Place the PHP parser outside the Web Directory

A highly secure method is to place the PHP parser somewhere outside the WEB file directory tree, for example, to/usr/local/bin. The only drawback of this approach is that you now need to add content similar to the following in the first line of all PHP markup files:

     #!/usr/local/bin/php


Make these files executable. That is to say, treat them like any other CGI script. These CGI scripts may use Perl, sh, or any other #! Shell-escape mechanism to start their own scripting language for writing. To enable PHP to correctly process The PATH_INFO and PATH_TRANSLATED information in this method, you must use the configuration parameter -- enable-discard-path when compiling the PHP parser. The following is an example of a PHP script that can run as a CGI program.

     #!/usr/local/bin/phpecho "This is a  my small  program"


4. upgrade PHP to the latest stable version 4.3.8.

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.3.8, register_globals is disabled by default to encourage these arrays to prevent inexperienced developers from coding insecure PHP code. This change is made out of security considerations. Link: http://www.php.net/downloads.php

  II. safe use of PHP

1. install the security module

The PHP Security mode is set up to solve the shared-server security problem. In terms of structure, it is unreasonable to try to solve this problem on the PHP layer, but it is unrealistic to modify the WEB server layer and operating system layer. Therefore, many people, especially ISP, currently use the security mode.

Table-1. security mode configuration commands

Name Default value Type
Safe_mode "0" Boolean
Safe_mode_gid "0" Boolean
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 the configuration option.

(1) safe_mode boolean

Whether to enable PHP Security mode.

(2) safe_mode_gid

By default, the security mode checks the UID when opening a file. If you want to extend it to GID comparison, open safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) for check during file access.

(3) safe_mode_include_dir

When this directory and its subdirectories (the directory must be included in include_path or in the full path) contain files, the UID/GID check is performed.

Starting from PHP 4.2.0, this command can accept a path separated by semicolons in a similar style as the include_path command, not just a directory.

(4) safe_mode_exec_dir

If PHP uses safe mode, system () and other functions that execute system programs refuse to start programs not in this directory.

(5) safe_mode_allowed_env_vars

Setting certain environment variables may be a potential security gap. This command contains a comma-separated Prefix List. In security mode, you can only change the environment variables whose names have the prefix provided here. By default, you can only set environment variables starting with PHP _ (for example, PHP_FOO = BAR ).

(6) safe_mode_protected_env_vars

This command contains a comma-separated list of environment variables. end users cannot use putenv () to change these environment variables. These variables cannot be changed even when safe_mode_allowed_env_vars is set to allow modification.

(7) disable_functions

This command allows you to disable certain functions for security reasons. The list of function names separated by commas is used as parameters. Disable_functions is not affected by the security mode. This command can only be set in php. ini. For example, you cannot set it in httpd. conf.

(8) disable_classes

This command disables some classes for security reasons. Use commas to separate class names. Disable_classes is not affected by the security mode. This command can only be set in php. ini. For example, you cannot set it in httpd. conf. This command is available from PHP 4.3.2.

(9) open_basedir

Restrict files that can be opened by PHP to the specified directory tree, including the file itself. This command is not affected by enabling or disabling security mode.

2. 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 connects to the MySQL database with an optional user name. 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.

3. 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"  AuthType     Basic# The password file has been placed outside the web treeAuthUserFile/home/car2002/website.pw
     
      requirevalid-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. Users can cancel authentication, which cannot be implemented in Apache.

B. It may be invalid. You can invalidate the login after a certain design. If the user does not browse your website 60 minutes after logon, you can force them to pass the verification again.

C. customizable. For example, you can use a small Java applet to encrypt the password to be sent and decrypt it on the server using the mcryet Library. this work can be done in any browser that supports Java.

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. You can decide whether to verify on each page. of course, this can be done on the Apache server by changing the domain.

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.

     
     Only users with a working username/password combination can see this

Example: use PHP for HTTP authentication
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.