PHP Development Security Issues

Source: Internet
Author: User
Tags mcrypt md5 hash sql injection attack

1, do not believe the form

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

2, do not trust the user

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

3, the Phpini configuration

register_globals = offerror_reporting = Offsafe_mode = Onsafe_mode_gid = Onallow_call_time_pass_reference = Offdisable_ functions = Phpinfo,system,passthru,shell_exec,escapeshellarg,escapeshellcmd,proc_close,proc_open,dl,popen,show_ Sourceopen_basedir =/data/www/tmp/:/data/www/expose_php = Offallow_url_fopen = Offallow_url_include = Off

4. SQL injection attack

There are two things you need to do to prevent SQL injection attacks:

1) Always type validation for input parameters, and special characters such as single quotes, double quotes, and anti-quotes are always escaped with the mysql_real_escape_string function

2) do not turn on PHP magic Quotes

Other ways

1) using PDO

$stmt = $pdo->prepare (' SELECT * FROM employees WHERE name =: Name '), $stmt->execute (Array (' name ' = = $name)); Forea CH ($stmt as $row) {do  something with $row}

Note that using PDO by default does not allow the MySQL database to execute a true preprocessing statement (for reasons below). To solve this problem, you should prohibit PDO from simulating pre-processing statements. A good example of using PDO to create a database connection is as follows:

$dbConnection = new PDO (' Mysql:dbname=dbtest;host=127.0.0.1;charset=utf8 ', ' user ', ' Pass '); $dbConnection SetAttribute (Pdo::attr_emulate_prepares, false); $dbConnection->setattribute (Pdo::attr_errmode, Pdo::errmode_ EXCEPTION);

2) Use Mysqli

$stmt = $dbConnection->prepare (' SELECT * FROM employees WHERE name =? '); $stmt->bind_param (' s ', $name); $stmt->execute (); $result = $stmt->get_result (), while ($row = $result->fetch_assoc ()) {    //does something with $row}

5. Prevent basic XSS attacks

1) This attack is done 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's pending form page.
2) XSS tools are more difficult to protect than SQL injection, major corporate websites have been attacked by XSS, the main use is to filter the user's data, generally filter out 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);    }    return $string;}

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:

&lt; Strong&gt; Boldtext&lt;/strong&gt;

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:

<a href= "http://host/a.php?variable=%22%3e%3c%53%43%52%49%50%54%3e%44%6f%73%6f%6d%65%74%68%69%6e%67%6d%61%6c %69%63%69%6f%75%73%3c%2f%53%43%52%49%50%54%3e ">

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 SafeHTML2, put the file into the server's classes directory, this directory contains all the safehtml and Htmlsax Library 3 , including safehtml class file 4 in your own script, building a SafeHTML object 5, filtering using the Parse method

The code is as follows:

<?php/* If you ' re storing the htmlsax3.php in the/classes directory, alongwith the safehtml.php script, define Xml_htm LSAX3 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. $sa  fehtml = new safehtml ();//Parse and sanitize the data. $safe _data = $safehtml->parse ($data);//Display Result.echo ' the sanitized data is '. $safe _data;

Note: safehtml does not completely prevent XSS attacks, just a relatively complex script to verify the way


6, the use of one-way hash encryption to protect the data
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.

7. 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_ "; $mode =" MCRYPT_MODE_CBC "; function Encrypt ($data, $key, $cipher, $mode) {//Encrypt DataReturn (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, to encrypt data 2, used to encrypt and decrypt data key3, user-selected encryption data specific algorithm (cipher: mcrypt_twofish192,mcrypt_serpent_256, MCRYPT_RC2, Mcrypt_des, and MCRYPT_LOKI97) 4, used to encrypt the pattern 5, the encrypted seed, used to start the encryption process of data, is an additional binary data used to initialize the encryption algorithm 6, the encryption key and the length of the seed, using the Mcrypt_get_key_size function and Mcrypt_ The Get_block_size function can 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. At the same time, because the encrypted data returned by the MCrypt function is a binary data, saving to a database Word can cause other errors to be saved to the database field, using Base64Encode to convert the data to hexadecimal numbers for easy storage.

Reference:http://www.codeproject.com/Articles/363897/PHP-Security

PHP Development Security Issues

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.