PHP gives developers a great deal of flexibility, but this also poses a potential risk to security issues, the recent need to summarize the past problems, here to lend a translation of an article at the same time with their own development of some feelings summed up.
Brief introduction
When developing an Internet service, you must always keep in mind the concept of security and be in the Code of development. The PHP scripting language does not care about security issues, especially for most inexperienced developers. Whenever you talk about transactions such as money issues, you need to pay particular attention to security considerations, such as developing a forum or a shopping cart.
General Essentials of Security protection
For general JavaScript foreground validation, the user's behavior is not known, such as shutting down the browser's JavaScript engine, thus passing the post malicious data to the server. Validation is required on the server side to validate the data passed to each PHP script to prevent XSS attacks and SQL injection
To assume that every piece of data your site receives is malicious code, there is a hidden threat to clean up every piece of data
The following configuration is made in the php.ini file:
Register_globals = Off
If this configuration option is turned on, there will be a large security risk. For example, there is a process.php script file that inserts the received data into the database, and the form that receives the user's input data might look like this:
<input name= "username" type= "text" size= "maxlength=" >
Thus, when the data is submitted to process.php, PHP registers a $username variable, submits the variable data to the process.php, and sets such a variable for any post or GET request parameters. If the display is not initialized then the following problem occurs:
<?php//Define $authorized = True only if the user is Authenticatedif (authenticated_user ()) { $authorized = true;}? >
Here, suppose the Authenticated_user function is the value of judging the $authorized variable, and if the register_globals configuration is turned on, then any user can send a request to set the $ The value of the authorized variable is any value so that the validation can be bypassed.
All of these submissions should be obtained through PHP's predefined built-in global arrays, including $_post, $_get, $_files, $_server, $_request, etc., where $_request is a $_get/$_post/$_ The COOKIE is a union variable of three arrays, and the default order is $_cookie, $_post, $_get.
- Recommended Security Configuration options
Error_reporting set to OFF: Do not expose the error message to the user, can be set to on when developing
Safe_mode set to Off
Register_globals set to Off
Disable the following functions: System, Exec, PassThru, shell_exec, Proc_open, Popen
The Open_basedir is set to/TMP, which allows the session information to have storage permissions while setting up a separate Web site root directory
Expose_php set to Off
Allow_url_fopen set to Off
Allow_url_include set to Off
SQL injection attacks for operationsthe SQL statement for the database requires special attention to security, because the user may enter specific statements to make the original SQL statement change functionality. Similar to the following example:
$sql = "SELECT * from pinfo where product = ' $product '";
At this point, if the user enters the $product parameter as:
Then the final SQL statement will look like this:
This will turn into three SQL statements that will cause the pinfo table to be deleted, which can have serious consequences.
This problem can be solved simply by using PHP's built-in functions:
$sql = ' Select ' from pinfo where product = ' ' ' mysql_real_escape_string ($product). ' ";
There are two things you need to do to prevent SQL injection attacks:
Type validation is always performed on the input parameters
Special characters, such as single quotes, double quotes, and anti-quotes, are always escaped using the Mysql_real_escape_string function
However, based on the development experience, do not open PHP magic Quotes, this feature has been abolished in the PHP6, always self when necessary to escape.
Prevent basic XSS attacks
XSS attacks are not like other attacks, which occur on the client side, and the most basic XSS tool is to prevent a JavaScript script from stealing user-submitted data and cookies from a user-submitted form page.
XSS tools are more difficult to protect than SQL injection, major corporate websites have been attacked by XSS, although this attack is not related to PHP language, but can use PHP to filter user data to achieve the purpose of protecting user data, the main use is to filter the user's data, generally filter out the HTML tags, especially a tag. The following is a common filtering method:
function transform_html ($string, $length = null) {//helps prevent XSS attacks //Remove dead space. $string = Trim ($string); Prevent potential Unicode codec problems. $string = Utf8_decode ($string); Htmlize html-specific characters. $string = Htmlentities ($string, ent_noquotes); $string = Str_replace ("#", "#", $string); $string = str_replace ("%", "%", $string); $length = Intval ($length); if ($length > 0) { $string = substr ($string, 0, $length); }
This function converts special characters of HTML into HTML entities, which are displayed in plain text when the browser renders the text. such as <strong>bold</strong> will be displayed as:
< Strong> Boldtext</strong>
The core of the above function is the Htmlentities function, which converts HTML special tags into HTML entity characters, which can filter out most XSS attacks.
But for experienced XSS attackers, there are more ingenious ways to attack: use hexadecimal or utf-8 encoding for their malicious code instead of plain ASCII text, for example, in the following way:
So the result of the browser rendering is actually:
<a href= "http://host/a.php?variable=" > <SCRIPT>Dosomethingmalicious</SCRIPT>
This will achieve the purpose of the attack. To prevent this, you need to convert # and% to their corresponding entity symbol on the basis of the transform_html function, plus the $length parameter to limit the maximum length of data submitted.
Using safehtml to prevent XSS attacks
The above protection against XSS attacks is very simple, but does not contain all the user's tags, there are hundreds of ways to bypass the filter function to submit JavaScript code, there is no way to completely stop the situation.
At present, there is no single script to ensure that the attack is not broken, but there is always a relatively better degree of protection. A total of two security protection methods: Whitelist and blacklist. Where the whitelist is simpler and more effective.
A white-list solution is safehtml, which is smart enough to recognize valid HTML, and then can remove any dangerous tags. This needs to be parsed based on the Htmlsax package.
To install a method that uses safehtml:
1, go to http://pixel-apes.com/safehtml/?page=safehtml download the latest safehtml
2, put the file into the server's classes directory, this directory contains all the safehtml and Htmlsax library
3. Include the SafeHTML class file in your own script
4. Set up a SafeHTML object
5. Filtering using the Parse method
<?php/* If you ' re storing the htmlsax3.php in The/classes directory, along with the safehtml.php script, define XM L_htmlsax3 as a null string. */define (Xml_htmlsax3, ");//Include the Class file.require_once (' classes/safehtml.php ');//define some sample bad code . $Data = "This data would raise an alert <script>alert (' XSS Attack ') </script>";//Create a SafeHTML object . $safehtml = new safehtml ();//Parse and sanitize the data. $safe _data = $safehtml->parse ($data);//Display Result.echo ' The sanitized data is <br/> '. $safe _data;? >
SafeHTML does not completely prevent XSS attacks, but is a relatively complex script to examine in a way.
Protect data with one-way hash encryption
One-way hash encryption to ensure that each user's password is unique, and can not be deciphered, only the end-user know the password, the system is not aware of the original password. One advantage of this is that the attacker cannot know the original password data after the system has been attacked.
Encryption and hashing are the two different processes. Unlike encryption, hash can not be decrypted, is unidirectional, and two different strings may be the same hash value, and does not guarantee the uniqueness of the hash value.
The hash value processed by the MD5 function is basically not cracked, but it is always possible, and there is a MD5 hash dictionary on the Web.
Encrypt data using MCrypt
The MD5 hash function can display data in a readable form, but when storing a user's credit card information, it needs to be encrypted and then decrypted.
The best approach is to use the MCrypt module, which contains more than 30 encryption methods to ensure that only the encrypted person can decrypt the data.
<?php$data = "Stuff you want Encrypted", $key = "Secret passphrase used to encrypt your data"; $cipher = "mcrypt_serpent_256"; $mod E = "MCRYPT_MODE_CBC"; function Encrypt ($data, $key, $cipher, $mode) {//Encrypt DataReturn (string) Base64_enco De (Mcrypt_encrypt ($cipher, Subs TR (MD5 ($key), 0,mcrypt_get_key_size ($cipher, $mode)), $data, $mode, substr (MD5 ($key), 0,mcrypt_get_block_size ($cipher, $mode)) ) );} function Decrypt ($data, $key, $cipher, $mode) {//Decrypt data Return (string) Mcrypt_decrypt ($cipher, substr (MD5 ($key), 0,mcrypt_get_key_size ($cipher, $mode)), Base64_d Ecode ($data), $mode, substr (MD5 ($key), 0,mcrypt_get_block_size ($cipher, $mode)) );}? >
The MCrypt function requires the following information:
1. Data to be encrypted
2. Key to encrypt and decrypt data
3. User-selected encryption data specific algorithm (cipher: mcrypt_twofish192,mcrypt_serpent_256, MCRYPT_RC2, Mcrypt_des, and mcrypt_loki97)
4, the mode used for encryption
5, the encryption of the seed, used to start the encryption process of data, is an additional binary data used to initialize the encryption algorithm
6. Encrypt key and seed length, use mcrypt_get_key_size function and mcrypt_get_block_size function to get
If both the data and the key are stolen, then the attacker can traverse the ciphers to find a way to open the line, so we need to MD5 the encrypted key once to ensure security. Also, because the encrypted data returned by the MCrypt function is a binary data, saving to a database field can cause other errors, and using Base64Encode to convert the data to hexadecimal numbers is easy to save.
Reference: Http://www.codeproject.com/Articles/363897/PHP-Security
Summary of PHP development security issues