How can PHP do the most basic security protection?

Source: Internet
Author: User
Tags mcrypt 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. 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 = trueonlyifuserisauthenticated
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 the session information can be stored, and a separate website root directory expose_php is set to Offallow_url_fopen and Offallow_url_include is set 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 = "selectfrompinfowhereproduct = '$ product '";
In this case, if the $ product parameter you enter is '39 '; DROPpinfo; SELECT 'foo
The final SQL statement will look like the following:
Selectproductfrompinfowhereproduct = '39 ';
DROPpinfo;
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 = 'selectfrompinfowhereproduct = '"'MySQL _ real_escape_string ($ product ).'"';
To prevent SQL injection attacks, you need to do two things well: type verification is always performed on input parameters. for special characters such as single quotes, double quotes, and backquotes, the mysql_real_escape_string function is always escaped. However, based on the development experience, do not enable MagicQuotes 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:
Functiontransform_HTML ($ string, $ lengthnull) {// HelpspreventXSSattacks
// Removedeadspace.
$ String = trim ($ string );
// PreventpotentialUnicodecodecproblems.
$ String = utf8_decode ($ string );
// HTMLizeHTMLspecificcharacters.
$ 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, bold is displayed as follows: BoldTextThe 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 utf8 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://pixelapes.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
Withthesafehtml. phpscript, defineXML_HTMLSAX3asanullstring./define (XML_HTMLSAX3, ''); // Includetheclassfile. require_once ('classes/safehtml. php ');
// Definesomesamplebadcode.
$ Data = Thisdatawouldraiseanalert script alert ('xssattack') script "; // Createasafehtmlobject. $ safehtml = newsafehtml (); // Parseandsanitizethedata. $ safe_data = $ safehtml> parse ($ data); // Displayresult. echo 'thesanitizeddatais '. $ 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.
The MD5hash function that uses mcrypt to encrypt data can display data in readable forms. However, when storing users' credit card information, you need to encrypt and store the data and decrypt it later. 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.
$ Key = "Secretpassphraseusedtoencryptyourdata ";
$ Cipher = "MCRYPT_SERPENT_256" $ mode = "Encrypt"; functionencrypt ($ data, $ key, cipher, $ mode) {// encrypt (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 ))));
} Functiondecrypt ($ data, $ key, $ cipher, $ mode) {// Decryptdata
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. a specific algorithm (cipher:
For example, MCRYPT_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. use the mcrypt_get_key_size function and the mcrypt_get_block_size function to obtain the length of the encrypted key and seed. if both the data and the key are stolen, attackers can traverse the ciphers to find the path, therefore, 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 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.