Summary _php related skills development for PHP security issues - PHP

Source: Hi learning network sensitive and eager Forum www.piaodoo.com welcome to learn from each other

For the development of Internet applications, as developers must keep in mind the concept of security, and reflected in the development of the code. PHP scripting language and do not care about security, especially for the most inexperienced developers. Whenever you make any transactions related to the issue of money affairs, should pay special attention to security issues to consider.

Important Safety general protection

1, do not believe Form

For the average Javascript front desk verification, unable to know the user's behavior, such as turning off the browser's javascript engine, so by malicious POST data to the server. Needs to be verified on the server side, the verification data is transmitted to each php script and SQL injection attacks prevent XSS

2, do not believe users

To assume that your site receives each piece of data is the presence of malicious code, there is a hidden threat to every piece of data will be cleaned

3, turn off global variables

Follows in the php.ini file:register_globals = Off

If after this configuration option is turned on, there will be a great security risk. Process.php example, a script file, copies of the received data into the database, receiving user input form data may be as follows:

<input name="username" type="text" size="15" maxlength="64">

Thus, when submitting data to process.php after, php $ username will register a variable, the variable data will be submitted to process.php, while for any POST or GET request parameters, such variables are set. If not, then initialize the display will appear the following questions:

<?php
// Define $authorized = true only if user is authenticated
if (authenticated_user()) {
  $authorized = true;
}
?>

Here, assume that authenticated_userthe function is to determine the value of the variable $ authorized, if turned register_globals configuration, any user can send a request to set an arbitrary value so that the value of the variable $ authorized can bypass this verification.

All of these submission of data should be obtained by PHP predefined built-in global array, including the $ _POST, $ _ GET, $ _ FILES, $ _ SERVER, $ _ REQUEST, of which $ _REQUEST is a $ _GET / $ _ POST / $ _ COOKIE three joint array of variables, 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, the development time can be set to ON
safe_mode is set to Off
Set register_globals to Off
following functions disabled: System, Exec, passthru, shell_exec, proc_open, popen
open_basedir is set to / tmp, so allows session information storage have permission, set up a separate web root
expose_php set to Off
allow_url_fopen to Off
to allow_url_include Off

SQL injection attacks

SQL statements for the database, you need to pay special attention to security, because the user may enter a specific statement making the original SQL statement to change the function. Similar to the following example:

$sql = "select * from pinfo where product = '$product'";

At this time, if the user enters a $ product parameters:

39'; DROP pinfo; SELECT 'FOO 

Then the final SQL statement becomes the following way:

select product from pinfo where product = '39'; DROP pinfo; SELECT 'FOO' 

This will become three SQL statements will cause pinfo table is deleted, this will have serious consequences.

This problem can be simply solved using PHP's built-in functions:

$sql = "Select * from pinfo where product = '" . mysql_real_escape_string($product) . "'";

Prevent SQL injection attacks need to do two things:

Of input parameters always type validation

Single quotes, double quotes, back quotes and other special characters are always using the mysql_real_escape_stringfunction escape

However, based on development experience here, do not open the Magic Quotes php, this feature has been abolished in php6, it is always their own escape when needed.

Basic prevent XSS attacks

XSS attacks Unlike other attacks, this attack on the client side, the most basic tool is to prevent XSS javascript script in some form page to be submitted by the user, the user-submitted data and cookie stealing over.

XSS SQL injection tool is more difficult than protection, the major company websites are XSS attacks before, though this attack has nothing to do with the php language, but can be used for screening purposes php user data to protect user data, where the main use is for the user filtering data, HTML tags typically filtered out, particularly a tag. The following is a conventional filtration 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 will convert HTML special characters to HTML entity, the browser displays in plain text in this text rendering time. The <strong> bold </ strong> it will be displayed as:

<STRONG>BoldText</STRONG> 

The core function of the above is htmlentities function that will convert html special tags for html entity characters, so you can filter most of the XSS attack.

But for those who have experienced XSS attacks, there are more subtle ways to attack: their malicious code in hexadecimal or utf-8 encoding, rather than plain ASCII text, for example, can use the following ways:

<a href="http://www.codetc.com/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" rel="external nofollow" >

So the browser is actually rendering results:

<a href="http://www.codetc.com/a.php?variable=" rel="external nofollow" ><SCRIPT>Dosomethingmalicious</SCRIPT>

This will achieve the purpose of the attack. To prevent this, and as necessary, and # transform_HTML% conversion function on the basis of their physical corresponding symbol, while $ length parameter added to limit the maximum length of the data submitted.

Use SafeHTML prevent XSS attacks

Protection on the above XSS attack is very simple, but does not contain all marks of users, but there are hundreds of ways to submit javascript code to bypass the filter function, there is no way to completely prevent this situation.

Currently, no single script to ensure that a breakthrough will not be attacked, but there are relatively better level of protection. There are two ways of security: white and black lists. Where the white list more simple and effective.

One kind whitelisting solution is SafeHTML, it is smart enough to be able to recognize valid HTML, and then you can remove any danger label. This needs to be based HTMLSax package to resolve.

SafeHTML method of installation:

  • 1, go http://pixel-apes.com/safehtml/?page=safehtml download the latest SafeHTML
  • 2, classes will file into the directory server, this directory contains all the library SafeHTML and HTMLSax
  • 3, SafeHTML contains class files in your scripts
  • 4, establish a target SafeHTML
  • 5, using the filtering method parse
<?php
/* 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 can not completely prevent XSS attacks, just the way a relatively complex scripts to test.

One-way encryption to protect data HASH

A one-way hash encryption to ensure that each user's password is unique and can not be deciphered, only the end user knows the password, the system also does not know the original password. One benefit of this system is that after the attack the attacker can not know the original password data.

Encryption and Hash are two different processes. Unlike encryption, Hash can not be decrypted, is one-way; also two different strings might get the same hash value, and can not guarantee the uniqueness of hash values.

MD5 hash function processed value base can not be cracked, but there is always a possibility, but there are also online dictionary MD5 hash of.

Data encryption using mcrypt

MD5 hash function can display the data in a readable form, but the time for storing user credit card information, the need for storing the encrypted, and after decrypting required.

The best method is to use mcrypt module, which contains the encryption method over 30 to ensure that only those who can decrypt the encrypted data.

<?php
$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))
        );
}
?>

mcrypt function requires the following information:

  • 1, data to be encrypted
  • 2, used to encrypt and decrypt data key
  • 3, the user selects a particular algorithm encrypted data (cipher: eg MCRYPT_TWOFISH192, MCRYPT_SERPENT_256, MCRYPT_RC2, MCRYPT_DES, and MCRYPT_LOKI97)
  • 4, is used to encrypt mode
  • 5, the encryption seeds used to encrypt data start process, an additional binary data is used to initialize the encryption algorithm
  • 6, the length of the encryption key and seeds, functions and use mcrypt_get_key_size mcrypt_get_block_size function to obtain

If the data and key are stolen, an attacker can traverse ciphers looking for ways to open the lines of, so we need to perform MD5 encryption key after the first guarantee security. And because encrypted data mcrypt function returns a binary data stored in the database so that the field can cause other errors, uses base64encode these data conversion for hexadecimal easy to save.

to sum up

That's all for this article, I hope the contents of this paper has some reference value of learning for all of us to learn or work, thank you for the support sensitive and eager Forum / Hi learning network. If you want to know more details, please see the related links below

The original address is: http: //www.piaodoo.com/thread-3553-1-1.html

Guess you like

Origin www.cnblogs.com/txdah/p/12093232.html
php