PHP Security "PHP secure"

Source: Internet
Author: User
Tags expression file system connect mysql mysql query split sprintf sql injection
Safety [original book information]
"SAMS Teach yourself PHP in Minutes"
Author:chris Newman
Publisher:sams Publishing
Pub Date:march 29, 2005
Isbn:0-672-32762-7
pages:264

[Translation Information]
Translation staff: Heiyeluren
Translation time: 2006-3-15
Translation section: "Lesson 24." PHP Security "
Chinese Name: PHP security

PHP is no doubt a very powerful server-side scripting language, but powerful features are always associated with significant risks, and in this chapter you will learn to use PHP's Safe mode to block some of the potential risk factors for PHP.

"Safe Mode"

PHP's Safe Mode provides a basic, secure, shared environment in a PHP-open Web server with multiple user accounts. When PHP running on a Web server opens Safe mode, some functions are completely blocked and some of the available features are restricted.

[Use Safe mode to enforce restrictions]
In safe mode, some function functions that attempt to access the file system are limited. To run a Web server user ID, if you want to manipulate a file, you must have access to the file read or write, which is not a problem for PHP.

When Safe mode is turned on, when you try to read or write to a local file, PHP checks to see if the current access user is the owner of the target file. If it is not the owner, the operation is prohibited. (Write access: Under the lower level of file access, you may be allowed to read or write files to the System OS, and the PHP security mode enables you to prevent the operation of another user file.) Of course, a Web server might be able to access an arbitrary file with global write permissions. )

When Safe mode is open, the functionality of the following list of functions will be limited:

ChDir, Move_uploaded_file, Chgrp, Parse_ini_file, Chown, rmdir, copy, rename, fopen, require, highlight_file, s How_source, include, symlink, link, touch, mkdir, unlink

Similarly, functions in some PHP extensions will also be affected. (Load module: In Safe mode, the DL function will be prohibited, if you want to load the extension, you can only modify the extended option in php.ini, loading when PHP starts)

When PHP security mode is open, you need to execute the operating system program, you must be in the SAFE_MODE_EXEC_DIR option to specify the directory of the program, or execution will fail. Even if it is allowed to execute, it is automatically passed to the Escapeshellcmd function for filtering.

The following list of functions that execute the command will be affected:
exec, Shell_exec, PassThru, System, Popen

In addition, the back tag operator (') will also be closed.

When running in Safe mode, the PUTENV function will not be valid, although it will not cause an error. Similarly, other functions that attempt to change the PHP environment variable are set_time_limit, and Set_include_path will also be ignored.

[Open Safe Mode]
The Safe mode of turning PHP on or off is taking advantage of the Safe_mode option in php.ini. If you want to activate Safe mode to all users of the current shared Web server, just set the configuration options to:

Safe_mode = On

The file owner will be checked when the function accesses the file system. By default, the user ID of the owner of the file is checked, when you are able to modify the file owner's group ID (GID) specified for the Safe_mode_gid option.

If you have a shared library file on your system, and when you encounter a need for include or require, then you can use the SAFE_MODE_INCLUDE_DIR option to set your path to ensure that your code works properly. (Include path: If you want to use the SAFE_MODE_INCLUDE_DIR option to include more include paths, then you can split with a colon in the unix/linux system, like the include_path option, split with semicolons under Windows)

For example, if you want to include/usr/local/include/php files in Safe mode, you can set the option to:

Safe_mode_include_dir =/usr/local/include/php

If your included files need to be executed, then you can set the Safe_mode_exec_dir option. For example, you need to/usr/local/php-bin the file under the path can be executed, then you can set the option to:

Safe_mode_exec_dir =/usr/local/php-bin

(Executable: If you execute a program that is in the/usr/bin directory, then you can connect the binaries to the path that you can execute under the specified option)

If you want to set some environment variables, you can use the Safe_mode_allowed_env_vars option. The value of this option is the prefix of an environment variable, which defaults to an environment variable that allows the php_ to start, and if you want to change, you can set the value of the option and divide the prefixes between the environment variables using commas.

For example, the following allows the time zone's environment variable TZ, and the value to modify this option is:

Safe_mode_allowed_env_vars = Php_,tz

"Other security Features"

In addition to Safe mode, PHP offers many other features to keep PHP secure.


[Hide PHP]
You can use the expose_php option in php.ini to prevent the Web server from leaking PHP report information. As follows:

expose_php = On

With the entire setup, you can block some attacks from automated scripts against Web servers. Typically, HTTP header information contains the following information:

server:apache/1.3.33 (Unix) php/5.0.3 mod_ssl/2.8.16
openssl/0.9.7c

After the expose_php option is turned on, the PHP version information will not be included in the header information above.

Of course, users can also see the. php file name extension when they visit the site. If you want the entire use of different file extensions, you need to find the following line in the httpd.conf:

AddType application/x-httpd. php

You can modify. PHP for any file name extension you like. You can specify any number of file extensions, using spaces in the middle to split. If you want to use PHP on the server side to parse. html and. htm files, then you set the options as follows:

AddType application/x-httpd. html. htm

(Parse HTML: Configure your Web server to parse all HTML files using PHP, but if the server-side code also needs to be parsed by PHP, it can affect the performance of the server.) Static pages You can use different extensions, which eliminates reliance on the PHP scripting engine and enhances performance. )

[File system security]

Safe Mode restricts the script owner to access only the files that belong to them, but you can use Open_basedir to specify a directory that you must access. If you specify a directory, PHP will deny access to other directories except for that directory and subdirectories of that directory. The Open_basedir option can work outside of safe mode.

The limit file system can only access the/tmp directory, then the setting option is:

Open_basedir =/tmp

[function access Control]

You can use a comma split in the disable_functions option to set the function name, so these functions will be closed in the PHP script. This setting can work outside of safe mode.

Disable_functions = DL

Of course, you can also use the disable_classes option to turn off access to some classes.

[Database Security]

Suppose your php script contains a MySQL query that is based on form values:

$sql = "UPDATE mytable SET col1 =". $_post["Value"]. "
WHERE col2 = ' somevalue ';
$res = mysql_query ($sql, $db);

You want $_post["value" to contain an integer value to update your column col1. However, a malicious user can enter a semicolon in the form field, followed by an SQL statement that he or she wants to be executed arbitrarily.

For example, suppose the following is the value submitted by $_post["value":

0; INSERT into admin_users (username, password)
VALUES (' Me ', ' mypassword ');

So when this query is sent to the MySQL query, it becomes the following sql:

UPDATE mytable SET col1 = 0;
INSERT into admin_users (username, password)
VALUES (' Me ', ' mypassword ');
WHERE col2 = ' somevalue ';

This is obviously a harmful query! First of all, this query will update col1 in the MyTable table. This is not a problem, but the second expression, which executes an insert expression, inserts a new administrator who can log in. The third expression is discarded, but at the same time the SQL parser throws an error, and the unwanted query completes. This attack is what we often call SQL injection (note: SQL injection).

Of course, there is a problem with SQL injection, the other side must understand your database structure. In this case, the attacker is aware that you have a table admin_users and that the username and password fields are included, and that the stored password is unencrypted.

In addition to yourself, general site visitors are not aware of these information about the database. However, if you use an online e-business program that develops your source code, or if you use a free discussion program, the definitions of these tables are known, or some users can access your database.

In addition, your script output prompts a query error that contains a lot of important information about the structure of the database. On a working web site, you should consider setting the Display_errors option to off and using log_errors instead of display_errors to insert warnings and error messages into the file.

(Database permissions: It is a very important thing that you only have the right permissions to properly connect the database through the script.) You should not use the administrator to connect to the database in the script. If you do this, an attacker would probably get all of the database permissions and include other permissions for the same server. An attacker would probably run the GRANT or CREATE USER command to gain more access rights. )

If you want to prevent SQL injection attacks, you must ensure that the content submitted by the user table dropdowns is not a SQL expression that can be executed.

In the previous example, we used an integer value to update. If a string is followed by a single quote, the attacker must submit a closed reference to the entire SQL expression before the semicolon. However, quotes that are submitted in a Web form are automatically escaped when the MAGIC_QUOTES_GPC option is turned on.

To prevent SQL injection attacks by malicious attackers, you should always confirm that the data submitted is legitimate. If you need an integer value, you can use the Is_numeric function to test the expression, or use the Settype function to convert to a number that clears any silly SQL statement.

If you develop a program that requires a few submitted values in an SQL expression, you can use the sprintf function to construct an SQL string, using formatting characters to indicate each value of the data type. Look at the following example:

$sql = sprintf ("UPDATE mytable SET col1 =%d
WHERE col2 = '%s ',
$_post["Number"],
Mysql_escape_string ($_post["string"));

In the previous example, the entire MySQL data has been used, so this string has been filtered through the mysql_escape_string function. For other databases, you can use the Addslashes function to escape, or use other methods.



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.