Translation PHP Security

Source: Internet
Author: User
Tags activate safe mode sprintf sql injection attack
[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]
Translators: Heiyeluren
Translation time: 2006-3-15
Translation Chapter: "Lesson 24." PHP Security "
English Name: PHP security



PHP is undoubtedly a very powerful server-side scripting language, but powerful features are always associated with significant dangers, and in this chapter you will learn to use PHP's Safe mode to block some of the potentially dangerous elements of PHP.


"Safe Mode"

PHP's security model provides a basic secure shared environment on a PHP open Web server that has multiple user accounts present. When PHP running on a Web server opens Safe mode, some functions will be completely banned and will limit the functionality available.


[Use Safe mode to enforce restrictions]
In safe mode, some function functions that attempt to access the file system will be limited. Run the Web server user ID, if you want to manipulate a file, you must have access to the file read or write, the implementation of this restriction function is not a problem for PHP.

When Safe mode is turned on, when attempting to read or write to a local file, PHP checks whether the current access user is the owner of the target file. If it is not the owner, the operation is forbidden. (Write permission: Under the lower level of file access, you may be allowed to read or write to the system's operating system files, through the safe mode of PHP to prevent you from operating another user file operation.) Of course, a Web server may be able to access an arbitrary file with global write permissions. )

When Safe mode is turned on, the functions 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, Show_source , include, symlink, link, touch, mkdir, unlink

Similarly, some of the functions in the PHP extension will also be affected. (Loading module: In Safe mode, the DL function will be disabled, if you want to load the extension, you can only modify the extension options in the php.ini, load when PHP starts)

When the PHP security mode is open, you need to execute the operating system program, must be the SAFE_MODE_EXEC_DIR option to specify the directory of the program, otherwise execution will fail. Even if execution is allowed, 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 marker operator (') is also closed.

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


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

Safe_mode = On

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

If you have a shared library file on your system, when you encounter an include or require, you can use the SAFE_MODE_INCLUDE_DIR option to set your path to ensure that your code works correctly. (Include path: If you want to use the SAFE_MODE_INCLUDE_DIR option to include more include paths, you can use colons for segmentation under the Unix/linux system, like the Include_path option, and split with semicolons under Windows)

For example, if you want to include files under/usr/local/include/php in Safe mode, you can set the options 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 path of the file can be executed, then you can set the options are:

Safe_mode_exec_dir =/usr/local/php-bin

(Executable: If you execute the program in the/usr/bin directory, then you can put these binary files, connect to the path you can execute under the specified options)

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, the default is to allow PHP_ to start the environment variable, if you want to change, you can set the value of this option, multiple environment variable prefixes using commas to split.

For example, the environment variable TZ, which allows the time zone, changes the value of this option to:

Safe_mode_allowed_env_vars = Php_,tz



"Other security Features"

In addition to Safe mode, PHP provides many other features to keep PHP safe.


[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 of the attacks from automated scripting against Web servers. Typically, the header information for HTTP 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 opened, the PHP version information will not be included in the header information above.

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

AddType application/x-httpd. php

You can modify. PHP for any file name extension you like. You can specify as many file extensions as you have, using spaces in the middle to split them. 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

(Parsing HTML: Configure your Web server to use PHP to parse all HTML files, but if the non-server-side code needs to be parsed by PHP, it will affect the performance of the server.) Static pages You can use different extensions, which will eliminate the dependency on the PHP scripting engine and enhance performance. )


[File system security]

Security mode restricts the script owner to access only its own files, 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 that directory and subdirectories. The Open_basedir option can work outside of safe mode.

To restrict the file system from accessing the/tmp directory only, the setting options are:

Open_basedir =/tmp


[function access Control]

You can set the function name using the comma partition in the Disable_functions option, then these functions will be closed in the PHP script. This setting can work outside of safe mode.

Disable_functions = DL

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


[Database Security]

Suppose your php script contains a MySQL query that is executed based on the 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 a form field, followed by a 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 this query will update col1 in the MyTable table. This is not a problem, but the second expression, which executes the 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 this harmful query is completed. This attack is what you often call SQL injection (note: SQL injection).

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

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

In addition, your script output will prompt for a query error, which contains a lot of important information about the structure of the database. On a working website, you should consider setting the Display_errors option to off, and use 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 correct permissions to connect the database correctly by scripting.) You should not use the administrator in the script to connect to the database. If you do this, an attacker would probably get all the database permissions and include the permissions of the other same server. An attacker would likely run the GRANT or CREATE USER command to gain more access. )

If you want to prevent a SQL injection attack, you must ensure that the user table dropdowns commits the content that 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 quotation mark, the attacker must submit a closed reference to the entire SQL expression before the semicolon. However, when the MAGIC_QUOTES_GPC option is turned on, the quotation marks submitted in the Web form are automatically escaped.

In order to prevent a malicious attacker from making a SQL injection attack, you should always confirm that the submitted data 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 and clear any silly SQL statement.

If you develop a program that requires several committed values in an SQL expression, you can use the sprintf function to construct an SQL string that uses a format character 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 the string has been filtered by 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.