Summary of PHP development security issues

  • 2021-12-04 09:33:08
  • OfStack

For the development of Internet applications, as developers, we must always keep in mind the concept of security and reflect it in the developed code. The PHP scripting language doesn't care much about security, especially for most inexperienced developers. Whenever you do any transaction involving money affairs, you should pay special attention to security considerations.

General points of safety protection 1

1. Don't trust the form

For Javascript foreground authentication like 1, malicious data is sent to the server through POST because the user's behavior cannot be known, such as shutting down the browser's javascript engine. Validation is required on the server side to validate the data passed to each php script to prevent XSS attacks and SQL injections

2. Don't trust users

Assume that every piece of data received by your website has malicious code and hidden threats, and clean up every piece of data

3. Turn off global variables

Configure the following in the php. ini file: register_globals = Off

If this configuration option is turned on, there will be a great security risk. For example, if there is a script file for process. php, the received data will be inserted into the database, and the form for receiving user input data may be as follows:


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

In this way, after submitting data to process. php, php registers a $username variable, submits this variable data to process. php, and sets this variable for any POST or GET request parameter. If it is not displayed for initialization, the following problems will occur:


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

Here, assume that authenticated_user The function determines the value of the $authorized variable. If the register_globals configuration is turned on, any user can send a request to set the value of the $authorized variable to any value to bypass this authentication.

All of these submitted data should be retrieved through PHP predefined built-in global arrays, including $_ POST, $_ GET, $_ FILES, $_ SERVER, $_ REQUEST, and so on, where $_ REQUEST is a joint variable of 1 $_ GET/$ _ POST/$ _ COOKIE 3 arrays, and the default order is $_ COOKIE, $_ POST, $_ GET.

Recommended security configuration options

error_reporting is set to Off: Do not expose error information to users, it can be set to ON during development
safe_mode set to Off
register_globals set to Off
Disable the following functions: system, exec, passthru, shell_exec, proc_open, popen
open_basedir is set to/tmp, which gives storage permission to session information and sets a separate website root directory
expose_php set to Off
allow_url_fopen set to Off
allow_url_include set to Off

SQL injection attack

For SQL statements that manipulate the database, special attention needs to be paid to security, because users may enter specific statements that change the functionality of the original SQL statements. Similar to the following example:


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

At this time, if the $product parameter entered by the user is:


39'; DROP pinfo; SELECT 'FOO 

Eventually, the SQL statement looks like this:


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

This would turn into three SQL statements, causing the pinfo table to be deleted, with 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) . "'";

Preventing SQL injection attacks requires two things to do well:

Always type validate input parameters

Always use for special characters such as single quotation marks, double quotation marks, and reverse quotation marks mysql_real_escape_string Function to escape

However, based on development experience, don't turn on Magic Quotes of php, which has been abolished in php 6, and always escape it when needed.

Preventing Basic XSS Attacks

Unlike other attacks, XSS attacks are carried out on the client. The most basic XSS tool is to prevent an javascript script from stealing the data submitted by the user and cookie on the form page to be submitted by the user.

XSS tool is more difficult to protect than SQL injection, and websites of major companies have been attacked by XSS. Although this attack has nothing to do with php language, php can be used to filter user data to protect user data. Here, the main use is to filter user data, and filter out HTML tags, especially a tags. Here 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 HTML special characters into HTML entities, which are rendered as plain text by the browser. 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 most XSS attacks.

However, for experienced XSS attackers, there is a more clever way to attack: encode their malicious code in 106 or utf-8 instead of ordinary ASCII text, for example, in 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" >

The result of this browser rendering is actually:


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

In this way, the purpose of attack is achieved. To prevent this, you need to convert # and% to their corresponding entity symbols in addition to the transform_HTML function, and add the $length parameter to limit the maximum length of the submitted data.

Using SafeHTML to prevent XSS attacks

The above protection against XSS attacks is very simple, but it does not include all the tags of users. At the same time, there are hundreds of ways to bypass the filter function and submit javascript code, and there is no way to completely prevent this situation.

At present, there is no single 1 script to ensure that it will not be attacked, but there are always relatively better protection. 1 There are two ways of security protection: white list and black list. Whitelist is simpler and more effective.

One whitelist solution is SafeHTML, which is smart enough to identify valid HTML, and then remove any dangerous tags. This needs to be parsed based on the HTMLSax package.

How to install SafeHTML:

1. Go to http://pixel-apes.com/safehtml/? page=safehtml Download the latest SafeHTML 2. Place the files in the server's classes directory, which contains all SafeHTML and HTMLSax libraries 3. Include the SafeHTML class file in your own script 4. Create an SafeHTML object 5. Filter using parse method

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

SafeHTML does not completely prevent XSS attacks, but is a relatively complex way of scripting.

Use one-way HASH encryption to protect data

One-way hash encryption guarantees that each user's password is only 1 and cannot be deciphered. Only the end user knows the password, and the system does not know the original password. One advantage of this is that the attacker cannot know the original password data after the system is attacked.

Encryption and Hash are two different processes. Unlike encryption, Hash cannot be decrypted and is unidirectional. Two different strings at the same time may get the same hash value, which does not guarantee the uniqueness of hash value.

The hash value processed by MD5 function can hardly be cracked, but it is always possible, and there is also an hash dictionary of MD5 on the Internet.

Encrypt data using mcrypt

The MD5 hash function can display data in a readable form, but when storing the user's credit card information, it needs to be encrypted and then stored, and then decrypted.

The best way is to use the mcrypt module, which contains more than 30 encryption methods to ensure that only the encrypter can decrypt the data.


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

The mcrypt function requires the following information:

1. Data to be encrypted 2. key used to encrypt and decrypt data 3. The specific algorithm selected by the user to encrypt data (cipher: such as MCRYPT_TWOFISH192, MCRYPT_SERPENT_256, MCRYPT_RC2, MCRYPT_DES, and MCRYPT_LOKI97) 4. The mode used for encryption 5. The seed of encryption, the data used to start the encryption process, is an extra binary data used to initialize the encryption algorithm 6. Encrypt the length of key and seed, which can be obtained by using mcrypt_get_key_size function and mcrypt_get_block_size function

If both the data and key are stolen, the attacker can traverse ciphers to find the way to operate, so we need to ensure the security of encrypted key after MD 51 times. At the same time, because the encrypted data returned by mcrypt function is 1 binary data, it will cause other errors when saved in the database field. base64encode is used to convert these data into 106 binary numbers for convenient storage.

Summarize


Related articles: