Summary of PHP Development security issues. Summary of PHP Development security issues php gives developers great flexibility, but it also brings potential risks to security issues. we need to summarize previous problems in the near future, summary of PHP Development Security issues
Php provides developers with great flexibility, but it also brings potential risks to security issues. we need to summarize the previous problems in the near future, here, I would like to summarize some of my development feelings by translating an article.
Introduction
When developing an Internet service, you must always keep in mind the security concept and embody it in the developed code. The PHP scripting language is not concerned with security issues, especially for most inexperienced developers. Every time you talk about any transactions involving money and transactions, you need to pay special attention to security issues, such as developing a forum or a shopping cart.
General points of security protection
Do not trust the form
For general Javascript front-end verification, the user's behavior cannot be known, for example, the javascript engine of the browser is closed, so that malicious data is sent to the server through POST. Verify the data transmitted to each php script on the server to prevent XSS attacks and SQL injection.
Do not trust users
Assume that every piece of data received by your website has malicious code and hidden threats. clean up every piece of data.
Disable global variables
Configure the following in the php. ini file:
Register_globals = Off
If this configuration option is enabled, there will be a great security risk. For example, a script file of process. php inserts the received data into the database. the form for receiving user input data may be as follows:
In this way, when the data is submitted to the process. php registers a $ username variable and submits the variable data to process. php. this variable is set for any POST or GET request parameters. If initialization is not performed on the display, the following problems will occur:
-
- // Define $authorized = true only if user is authenticated
- if (authenticated_user()) {
- $authorized = true;
- }
- ?>
Assume that the authenticated_user function is used to determine the value of the $ authorized variable. if the register_globals configuration is enabled, any user can send a request, to set the value of the $ authorized variable to any value to bypass this verification.
All the submitted data should be obtained through the predefined global array in PHP, including $ _ POST, $ _ GET, $ _ FILES, $ _ SERVER, $ _ REQUEST, etc, $ _ REQUEST is a federated variable of $ _ GET/$ _ POST/$ _ COOKIE arrays. the default sequence is $ _ COOKIE, $ _ POST, and $ _ GET.
Error_reporting is set to Off: do not expose error information to users. you can set it to ON during development.
Set safe_mode to Off.
Set register_globals to Off.
Disable the following functions: system, exec, passthru, shell_exec, proc_open, and popen.
Open_basedir is set to/tmp, so that session information can be stored and a separate website root directory can be set.
Set expose_php to Off
Set allow_url_fopen to Off.
Set allow_url_include to Off.
SQL injection attacks
Pay special attention to security when operating SQL statements in the database, because the user may enter a specific statement to change the functions of the original SQL statement. For example:
$ SQL = "select * from pinfo where product = '$ product '";
In this case, if the $ product parameter you enter is:
39 '; DROP pinfo; SELECT 'foo
The final SQL statement will look like the following:
Select product from pinfo where product = '39 '; DROP pinfo; SELECT 'foo'
In this way, three SQL statements will be generated, and the pinfo table will be deleted, which will cause serious consequences.
This problem can be solved simply by using the built-in functions of PHP:
- $sql = 'Select * from pinfo where product = '"'
- mysql_real_escape_string($product) . '"';
To prevent SQL injection attacks, you must do the following:
Type verification is always performed on input parameters.
Use the mysql_real_escape_string function to escape special characters such as single quotes, double quotes, and backquotes.
However, based on development experience, do not enable Magic Quotes of php. this feature has been abolished in php6 and is always escaped as needed.
Prevent basic XSS attacks
XSS attacks are not like other attacks. these attacks are carried out on the client. the most basic XSS tool is to prevent a javascript script from stealing the data and cookies submitted by the user on the form page to be submitted by the user.
XSS tools are more difficult to defend against than SQL injection, and websites of major companies have been attacked by XSS. Although such attacks are irrelevant to the php language, however, php can be used to filter user data to protect user data. here, we mainly use to filter user data. generally, HTML tags, especially a tags, are filtered out. 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);
- }
- return $string;
- }
This function converts special characters in HTML to HTML objects. the browser displays the special characters in plain text when rendering the text. For exampleBoldWill be displayed:
<STRONG> BoldText </STRONG>
The core of the above function is the htmlentities function. this function converts special html tags to html entity characters, which can filter most XSS attacks.
But for experienced XSS attackers, there is a more clever way to attack: use hexadecimal or UTF-8 encoding for their malicious code, instead of common ASCII text, for example, you can use the following method:
In this way, the result of browser rendering is:
SCRIPT Dosomethingmalicious SCRIPT
In this way, the attack is achieved. To prevent this, you need to convert # and % to their corresponding entity symbols based on the transform_HTML function, and add the $ length parameter to limit the maximum length of the submitted data.
Use SafeHTML to prevent XSS attacks
The above protection against XSS attacks is very simple, but does not contain all the user's tags. at the same time, there are hundreds of methods to bypass the filter function to submit javascript code, and there is no way to completely stop this situation.
At present, there is no single script to ensure that the attack will not break through, but there is always a relatively better degree of protection. There are two security protection methods: whitelist and blacklist. The whitelist is simpler and more effective.
A whitelist solution is SafeHTML, which is smart enough to identify valid HTML and then can remove any dangerous tags. This needs to be parsed based on the HTMLSax package.
How to install and use 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, which contains all the SafeHTML and HTMLSax libraries.
3. include the SafeHTML class file in your script
4. create a SafeHTML object
5. use the parse method for filtering
-
- /* If you're storing the HTMLSax3.php in the /classes directory, along
- with the safehtml.php script, define XML_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
' . $safe_data;
- ?>
SafeHTML does not completely prevent XSS attacks, but is a relatively complex method of script testing.
Use one-way HASH encryption to protect data
One-way hash encryption ensures that each user's password is unique and cannot be decrypted. only the end user knows the password and the system does not know the original password. One advantage is that after the system is attacked, attackers cannot know the original password data.
Encryption and Hash are two different processes. Unlike encryption, Hash cannot be decrypted and is unidirectional. at the same time, two different strings may obtain the same hash value, which cannot guarantee the uniqueness of the hash value.
The hash value processed by the MD5 function cannot be cracked, but it is always possible, and there is also an MD5 hash dictionary on the Internet.
Use mcrypt to encrypt data
The MD5 hash function can display data in a readable form. However, when storing users' credit card information, you need to encrypt and store it, and then decrypt it.
The best way is to use the mcrypt module, which contains more than 30 encryption methods to ensure that only the Encryptor can decrypt the data.
-
- $data = "Stuff you want encrypted";
- $key = "Secret passphrase used to encrypt your data";
- $cipher = "MCRYPT_SERPENT_256";
- $mode = "MCRYPT_MODE_CBC";
- function encrypt($data, $key, $cipher, $mode) {
- // Encrypt data
- return (string)
- base64_encode
- (
- mcrypt_encrypt
- (
- $cipher,
- substr(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_decode($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 used to encrypt and decrypt data
3. cipher, a specific algorithm for user-selected data encryption, as shown in figureMCRYPT_TWOFISH192
, MCRYPT_SERPENT_256,MCRYPT_RC2
,MCRYPT_DES
, AndMCRYPT_LOKI97
)
4. encryption mode
5. the seed of encryption is used to start the data in the encryption process. it is an additional binary data used to initialize the encryption algorithm.
6. the encryption key and seed length can be obtained using the mcrypt_get_key_size function and the mcrypt_get_block_size function.
If both the data and key are stolen, attackers can traverse the ciphers to find the path. Therefore, we need to perform MD5 for the encrypted key to ensure security. At the same time, the encrypted data returned by the mcrypt function is a binary data, which will cause other errors when saved to the database field. base64encode is used to convert the data to a hexadecimal number for easy storage.
References: http://www.codeproject.com/Articles/363897/PHP-Security
Php gives developers great flexibility, but it also brings potential risks to security issues. we need to summarize the previous problems in the near future. here...