PHP development cannot violate the security rules

Source: Internet
Author: User
Tags form post php form php form processing tainted
As a PHP programmer, especially a newbie, I always know too little about the sinister nature of the Internet. It is often difficult to handle external intrusions, they do not know how hackers intrude, commit intrusions, upload vulnerabilities, SQL injection, and cross-script attacks. As the most basic precaution, you need to pay attention to your external submissions and handle the first security mechanism.

As a PHP programmer, especially a newbie, I always know too little about the sinister nature of the Internet. It is often difficult to handle external intrusions, they do not know how hackers intrude, commit intrusions, upload vulnerabilities, SQL injection, and cross-script attacks. As the most basic precaution, you need to pay attention to your external submissions and handle the first security mechanism.

As a PHP programmer, especially a newbie, I always know too little about the sinister nature of the Internet. It is often difficult to handle external intrusions, they do not know how hackers intrude, commit intrusions, upload vulnerabilities, SQL injection, and cross-script attacks. As the most basic precaution, you need to pay attention to your external submissions and make the first security mechanism to handle the firewall.

Rule 1: Never trust external data or input

The first thing that must be realized about Web Application Security is that external data should not be trusted. External data includes any data that is not directly input by programmers in PHP code. Before taking measures to ensure security, any data from any other source (such as GET variables, form POST, database, configuration file, session variables, or cookies) is untrusted.

For example, the following data elements can be considered safe because they are set in PHP.

  1. Listing 1. Safe and flawless code
  2. $ MyUsername = 'tmyer ';
  3. $ ArrayarrayUsers = array ('tmyer ', 'Tom', 'Tommy ');
  4. Define ("GREETING", 'Hello there'. $ myUsername );
  5. ?>

However, the following data elements are flawed.

  1. List 2. insecure and defective code
  2. $ MyUsername = $ _ POST ['username']; // tainted!
  3. $ ArrayarrayUsers = array ($ myUsername, 'Tom ', 'Tommy'); // tainted!
  4. Define ("GREETING", 'Hello there'. $ myUsername); // tainted!
  5. ?>

Why is the first variable $ myUsername defective? Because it is directly from form POST. You can enter any strings in this input field, including malicious commands used to clear files or run previously uploaded files. You might ask, "isn't it possible to avoid this risk using a client that only accepts letters of A-Z (Javascr into pt) Form validation script ?" Yes, this is always a good step, but as you will see later, anyone can download any form to their machine and modify it, then resubmit any content they need.

The solution is simple: you must run the cleanup code on $ _ POST ['username. Otherwise, $ myUsername may be contaminated at any other time (such as in an array or constant. A Simple Method for clearing user input is to use a regular expression to process it. In this example, only letters are allowed. It may be a good idea to limit a string to a specific number of characters, or to require that all letters be in lowercase.

  1. Listing 3. Making user input secure
  2. $ MyUsername = cleanInput ($ _ POST ['username']); // clean!
  3. $ ArrayarrayUsers = array ($ myUsername, 'Tom ', 'Tommy'); // clean!
  4. Define ("GREETING", 'Hello there'. $ myUsername); // clean!
  5. Function cleanInput ($ input) {$ clean = strtolower ($ input );
  6. $ Clean = preg_replace ("/[^ a-z]/", "", $ clean );
  7. $ Clean = substr ($ clean, 0, 12); return $ clean;
  8. }
  9. ?>

Rule 2: Disable PHP settings that make security difficult

You already know that you cannot trust user input. You should also know that you should not trust the PHP configuration method on the machine. For example, make sure to disable register_globals. If register_globals is enabled, you may do some careless things, such as replacing the GET or POST string with the same name with $ variable. By disabling this setting, PHP forces you to reference the correct variables in the correct namespace. To use a variable from form POST, you should reference $ _ POST ['variable']. In this way, the specific variable will not be misunderstood as a cookie, session, or GET variable.

Rule 3: if you cannot understand it, you cannot protect it.

Some developers use strange syntaxes, or organize statements very compact to form short but ambiguous code. This method may be highly efficient, but if you do not understand what the code is doing, you cannot decide how to protect it. For example, which of the following two sections of code do you like?

  1. Listing 4. Easy Code Protection
  2. // Obfuscated code
  3. $ Input = (isset ($ _ POST ['username'])? $ _ POST ['username']: ");
  4. // Unobfuscated code
  5. $ Input = ";
  6. If (isset ($ _ POST ['username']) {
  7. $ Input = $ _ POST ['username'];
  8. } Else {
  9. $ Input = ";
  10. }

In the second clear code segment, it is easy to see that $ input is defective and needs to be cleaned up before it can be processed safely.

Rule 4: "defense in depth" is a new magic weapon

This tutorial uses examples to illustrate how to protect online forms and take necessary measures in PHP code that processes forms. Similarly, even if PHP regex is used to ensure that the GET variable is completely numeric, you can still take measures to ensure that the SQL query uses escape user input. Defense in depth is not just a good idea. It ensures that you are not in serious trouble. Now that we have discussed the basic rules, we will study the first threat: SQL injection attacks.

◆ Prevent SQL injection attacks

In SQL injection attacks, you can manipulate the form or GET query string to add information to the database query. For example, assume there is a simple login database. Each record in this database has a username field and a password field. Create a logon form to allow users to log on.

  1. Login
  2. Username

  3. Password

This form accepts the user name and password entered by the user, and submits the user input to the file verify. php. In this file, PHP processes data from the login form, as shown below:

  1. Listing 5. Insecure PHP form processing code
  2. $ Okay = 0;
  3. $ Username = $ _ POST ['user'];
  4. $ Pw = $ _ POST ['PW '];
  5. $ SQL = "select count (*) as ctr from users where username ='
    ". $ Username." 'and password =' ". $ pw." 'limit 1 ″;
  6. $ Result = MySQL_query ($ SQL );
  7. While ($ data = mysql_fetch_object ($ result )){
  8. If ($ data-> ctr = 1 ){
  9. // They're okay to enter The application!
  10. $ Okay = 1;
  11. }
  12. }
  13. If ($ okay ){
  14. $ _ SESSION ['loginokay'] = true;
  15. Header ("index. php ");
  16. } Else {
  17. Header ("login. php ");
  18. }
  19. ?>

This code looks okay, right? Hundreds or even thousands of PHP/MySQL sites around the world are using this code. Where is the error? Well, remember "user input cannot be trusted ". No information from the user is escaped, so the application is vulnerable to attacks. Specifically, any type of SQL injection attacks may occur. For example, if you enter foo as the user name and 'or '1' = '1 as the password, the following string is actually passed to PHP and then the query is passed to MySQL:

  1. $ SQL = "select count (*) as ctr from users where username =
    'Foo' and password = "or '1' = '1' limit 1 ″;
  2. ?>

This query always returns a Count value of 1, so PHP will allow access. By injecting some malicious SQL statements at the end of the password string, hackers can dress up as legitimate users. To solve this problem, use the built-in mysql_real_escape_string () function of PHP as the package for any user input. This function is used to escape characters in a string, making it impossible for the string to pass special characters such as an apostrophes and allow MySQL to perform operations based on special characters. Listing 7 shows the Code with escape processing.

  1. Listing 7 shows the Code with escape processing.
  2. $ Okay = 0;
  3. $ Username = $ _ POST ['user'];
  4. $ Pw = $ _ POST ['PW '];
  5. $ SQL = "select count (*) as ctr from users where username = '". mysql_real _
    _ String ($ username). "'and password ='". mysql_real_escape_string ($ pw )."'
    Limit 1 ";
  6. $ Result = mysql_query ($ SQL );
  7. While ($ data = mysql_fetch_object ($ result )){
  8. If ($ data-> ctr = 1) {// they're okay to enter
    Application!
  9. $ Okay = 1;
  10. }
  11. }
  12. If ($ okay ){
  13. $ _ SESSION ['loginokay'] = true;
  14. Header ("index. php ");
  15. }
  16. Else {
  17. Header ("login. php ");
  18. }
  19. ?>

Using mysql_real_escape_string () as the package for user input can avoid any malicious SQL Injection in user input. If you try to pass a malformed password through SQL injection, the following query will be passed to the database:

  1. Select count (*) as ctr from users where username = 'foo' and password =
    '\' Or \ '1 \ '= \ '1' limit 1 ″

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.