Summary of PHP Development Security issues

Source: Internet
Author: User
Tags md5 hash
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. Simplified
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 of PHP, including $ _ POST, $ _ GET, $ _ FILES, $ _ SERVER, and $ _ REQUEST, $ _ REQUEST is a federated variable of $ _ GET/$ _ POST/$ _ COOKIE arrays. the default sequence is $ _ COOKIE, $ _ POST, and $ _ GET.


Recommended security configuration options
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.
The mysql_real_escape_string function is always used for special characters such as single quotes, double quotes, and backquotes.


Escape
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 example BoldWill be displayed:
BoldText


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 wowould 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. specific algorithms used to encrypt data (such as MCRYPT_TWOFISH192, MCRYPT_SERPENT_256, MCRYPT_RC2, MCRYPT_DES, and MCRYPT_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, because the encrypted data returned by the mcrypt function is a binary data, saving it to the database field will cause other errors. base64encode is used to convert the data to a hexadecimal number for easy storage.

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.