PHP Insurance Study Notes

Source: Internet
Author: User
How to learn PHP Security? hhacker.comfiles2007091index.html? Php Security [original book information] SAMSTeachYourselfPHPin10Minutes Author: ChrisNewmanPublisher: SamsPublis PHP Security study notes



PHP Security Guide http://hhacker.com/files/200709/1/index.html

?

Php Security

[Original book information]
SAMS Teach Yourself PHP in 10 Minutes
Author: Chris Newman
Publisher: Sams Publishing
Pub Date: March 29,200 5
ISBN: 0-672-32762-7
Pages: 264

[Translation information]
Translated by: heiyeluren
Translation Time: 2006-3-15
Translated chapter: Lesson 24. PHP Security
Chinese name: PHP Security


PHP is undoubtedly a very powerful server-side scripting language, but its powerful functions are always at risk. in this chapter, you will learn how to use the security mode of PHP to prevent potential risk factors of PHP.

[Security mode]

The security mode of PHP provides a basic secure shared environment on a PHP open Web server with multiple user accounts. When PHP running on a Web server opens the safe mode, some functions will be completely disabled and some available functions will be restricted.

[Use security mode to force 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 operate a file, you must have the permission to read or write the file. to implement this restriction function, PHP is fine.

When security mode is enabled and a local file is read or written, PHP checks whether the current user is the owner of the target file. If it is not the owner, this operation is forbidden. (Write permission: under a lower level of file access permission, files in the operating system may be read or written, the PHP Security mode prevents you from operating another user file. Of course, a Web server may be able to access any file with the global write permission .)

When security mode is enabled, the functions of the following function list will be restricted:

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 PHP extension functions will also be affected. (Loading module: in safe mode, dl functions will be disabled. to load extensions, you can only modify the extension options in php. ini and load them when PHP starts)

When enabling PHP Security mode, you must specify the directory program in the safe_mode_exec_dir option when executing the operating system program. Otherwise, the execution will fail. Even if execution is allowed, it is automatically passed to the escapeshellcmd function for filtering.

The list of functions that execute the following commands will be affected:
Exec, shell_exec, passthru, system, popen

In addition, the back Mark operator (') will also be disabled.

When running in safe mode, although it does not cause errors, the putenv function will be invalid. Similarly, other functions that attempt to change the PHP environment variables set_time_limit and set_include_path will also be ignored.

[Enable security mode]
The safe mode for enabling or disabling PHP is to use the safe_mode option in php. ini. If you want to activate the security mode for all users who share the Web server, you only need to set the configuration options:

Safe_mode = On

When a function accesses the file system, it checks the file owner. By default, the user ID of the file owner is checked. when you can modify the group ID (GID) of the file owner to the ID specified by the safe_mode_gid option.

If you have a shared library file on your system and you need to include or require, you can use the safe_mode_include_dir option to set your path, ensure that your code works properly. (Include path: If you want to use the safe_mode_include_dir option to include more include paths, you can use colons in Unix/Linux systems like the include_path option, use semicolons in Windows)

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

Safe_mode_include_dir =/usr/local/include/php

If your included files need to be executed, you can set the safe_mode_exec_dir option. For example, if the file in the/usr/local/php-bin path is executable, you can set the options:

Safe_mode_exec_dir =/usr/local/php-bin

(Executable: if the program you run is in the/usr/bin directory, you can connect these binary files to the path that can be executed 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. the default value is an environment variable starting with PHP _. if you want to change it, you can set the value of this option, use commas to separate the prefixes of multiple environment variables.

For example, if the following environment variable TZ is allowed for the time zone, modify the value of this option:

Safe_mode_allowed_env_vars = PHP _, TZ

[Other security features]

In addition to the security mode, PHP also provides many other features to ensure PHP Security.
[Hide PHP]
You can use the expose_php option in php. ini to prevent Web servers from leaking PHP report information. As follows:

Expose_php = On

Using the entire configuration, you can block attacks from automatic scripts against Web servers. Generally, the HTTP header 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 enabled, the PHP version information will not be included in the header information above.

Of course, users can also see the. php file extension when visiting the website. If you want to use different file extensions, you need to find the following line in httpd. conf:

AddType application/x-httpd. php

You can modify. php to any file extension you like. You can specify multiple file extensions, separated by spaces. If you want to use PHP on the server to parse the. html and. htm files, set the options as follows:

AddType application/x-httpd. html. htm

(Parse HTML: Configure your Web server to use PHP to parse all HTML files. However, if non-server-side code is also parsed by PHP, the server performance will be affected. For static pages, you can use different extensions to eliminate dependencies on the PHP script engine and improve performance .)

[File system security]

Security mode limits the script owner to access only their own files, but you can use open_basedir to specify a directory that you must access. If you specify a directory, PHP rejects access to other directories except this directory and its subdirectories. The open_basedir option can work in a security mode.

To restrict the file system to access only the/tmp Directory, set the options:

Open_basedir =/tmp

[Function access control]

You can use commas (,) in the disable_functions option to set the function name. these functions will be disabled in the PHP script. This setting can work beyond the security mode.

Disable_functions = dl

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

[Database security]

Assume that your PHP script contains a Mysql Query executed based on the form value:

$ SQL = "UPDATE mytable SET col1 =". $ _ POST ["value"]."
WHERE col2 = 'somevalue '";
$ Res = mysql_query ($ SQL, $ db );

You want $ _ POST ["value"] to include an integer to update col1. However, a malicious user can enter a semicolon in the form field, followed by an SQL statement that he/she wants to execute at will.

For example, assume that the value submitted by $ _ POST ["value"] is as follows:

0; insert into admin_users (username, password)
VALUES ('me', 'mypassword ');

When the query is sent to Mysql, the following SQL statement is used:

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 updates col1 in the mytable table. This is not troublesome, but the second expression will execute the INSERT expression to INSERT a new administrator who can log on. The third expression is discarded, but the SQL parser throws an error and the harmful query is completed. This attack is commonly known as SQL injection (note: SQL injection ).

Of course, there is a problem with SQL injection. the other party must understand your database structure. In this example, the attacker knows that you have a table admin_users and that it contains the username and password fields. at the same time, the stored password is not encrypted.

Except yourself, visitors do not know the database information. However, if you use an online e-commerce program with development source code or a free version program, the definitions of these data tables are known, or some users can access your database.

In addition, your script output will prompt a query error, which contains a lot of important information about the database structure. On a normal website, you should consider setting the display_errors option to off, and use log_errors to replace display_errors, and insert warning and error information into the file.

(Database permission: it is a very important thing. only with the correct permissions can you properly connect to the database through scripts. You should not use the administrator to connect to the database in the script. If you do this, an attacker may obtain all the database permissions and include the permissions of other identical servers. Attackers may run the GRANT or create user command to obtain more access permissions. )

To prevent SQL injection attacks, you must ensure that the content submitted in the user form is not an SQL expression that can be executed.

In the previous example, we use an integer value for update. If the string is followed by a single quotation mark, the attacker must submit a closed reference in the entire SQL expression before the semicolon. However, when the magic_quotes_gpc option is enabled, the quotation marks submitted in the Web form are automatically escaped.

To prevent malicious attackers from launching SQL injection attacks, you should always confirm that the submitted data is legal. If you need an integer, you can use the is_numeric function to test the expression value, or use the settype function to convert it into a number to clear any silly SQL statement.

If the program you develop requires several submitted values in an SQL expression, you can use the sprintf function to construct an SQL string and use formatted characters to indicate each value of the data type. See the following example:

$ SQL = sprintf ("UPDATE mytable SET col1 = % d
WHERE col2 = '% s '",
$ _ POST ["number"],
Mysql_escape_string ($ _ POST ["string"]);

In the previous example, Mysql data has been used, so this 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.

?

?

Note:

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.