Ensure the security of PHP applications

Source: Internet
Author: User

Target

This tutorial explains how to defend against the most common security threats: SQL Injection, GET and POST variables, buffer overflow attacks, cross-site scripting attacks, browser data manipulation, and remote form submission.

Prerequisites

This tutorial is written by PHP developers who have at least one year of programming experience. You should understand the PHP syntax and conventions. I will not explain them here. Developers who have experience using other languages (such as Ruby, Python, and Perl) can also benefit from this tutorial, because many of the rules discussed here also apply to other languages and environments.

Quick introduction to security

What is the most important part of a Web application? Different people answer questions. Business personnel need reliability and scalability. The IT support team needs robust and maintainable code. End users need beautiful user interfaces and high performance when performing tasks. However, if you answer "security", everyone will agree that this is important to Web applications.
However, most of the discussions are stuck here. Although security is included in the project checklist, it is often considered to solve the security issue before the project is delivered. The number of Web application projects in this way is amazing. After several months of work, developers only add security features at the end, so that Web applications can be opened to the public.
The results are often messy, and even need to be reworked, because the code has been tested, unit tests are combined into a larger framework, and then security features are added to it. After security is added, the main components may stop working. Security integration adds additional burden or steps to the original smooth (but insecure) process.
This tutorial provides a good way to integrate security into PHP Web applications. It discusses several general security topics and then discusses in depth the main security vulnerabilities and how to block them. After completing this tutorial, you will have a better understanding of security.
Topics include:
SQL injection attacks
Manipulate GET strings
Buffer overflow attacks
Cross-site scripting (XSS)
Data manipulation in the browser
Remote form submission

Web security 101

Before discussing the security details, we 'd better discuss the security of Web applications from a higher perspective. This section describes some basic principles of the security philosophy, which should be kept in mind no matter what Web applications are being created. Some of these ideas come from Chris Shiflett (his book on PHP security is an invaluable treasure), some from Simson Garfinkel (see references), and some from years of accumulated knowledge.
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.
Listing 1. Safe and flawless code
Copy the PHP content to the clipboard.
PHP code:
$ MyUsername = 'tmyer ';
$ ArrayUsers = array ('tmyer ', 'Tom', 'Tommy ');
Define ("GREETING", 'Hello there'. $ myUsername );

However, the following data elements are flawed.
Listing 2. insecure and defective code copying PHP content to the clipboard
PHP code:
$ MyUsername = $ _ POST [username]; // tainted!
$ ArrayUsers = array ($ myUsername, 'Tom ', 'Tommy'); // tainted!
Define ("GREETING", 'Hello there'. $ myUsername); // tainted!

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 use a client (JavaScript) Form validation script that only accepts letter A-Z to avoid this risk ?" 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.
Listing 3. Making user input secure copying PHP content to the clipboard
PHP code:
$ MyUsername = cleanInput ($ _ POST [username]); // clean!
$ ArrayUsers = array ($ myUsername, 'Tom ', 'Tommy'); // clean!
Define ("GREETING", 'Hello there'. $ myUsername); // clean!
Function cleanInput ($ input ){
$ Clean = strtolower ($ input );
$ Clean = preg_replace ("/[^ a-z]/", "", $ clean );
$ Clean = substr ($ clean, 0, 12 );
Return $ clean;
}

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.
The second setting to be checked is the error report level. During development, you want to get as many error reports as possible, but you want to record errors to log files rather than display them on the screen when delivering the project. Why? This is because malicious hackers use error report information (such as SQL errors) to guess what the application is doing. This kind of reconnaissance can help Hackers break through applications. To block this vulnerability, You need to edit the php. ini file, provide an appropriate destination for the error_log entry, and set display_errors to Off.

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?
Listing 4. Making the code easy to protect copying PHP content to the clipboard
PHP code:
// Obfuscated code
$ Input = (isset ($ _ POST [username])? $ _ POST [username]: ");
// Unobfuscated code
$ Input = ";
If (isset ($ _ POST [username]) {
$ Input = $ _ POST [username];
} Else {
$ Input = ";
}

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.
Listing 5. Copying PHP content to the clipboard using a simple login form
PHP code:
<Html>
<Head>
<Title> Login </title>
</Head>
<Body>
<Form action = "verify. php" method = "post">
<P> <label for = 'user'> Username </label>
<Input type = 'text' name = 'user' id = 'user'/>
</P>
<P> <label for = 'PW '> Password </label>
<Input type = 'Password' name = 'PW 'id = 'PW'/>
</P>
<P> <input type = 'submit 'value = 'login'/> </p>
</Form>
</Body>
</Html>

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:
Listing 6. Insecure PHP form processing code copying PHP content to the clipboard
PHP code:

<? Php
$ Okay = 0;
$ Username = $ _ POST [user];
$ Pw = $ _ POST [pw];
$ SQL = "select count (*) as ctr from users where
Username = '". $ username."' and password = '". $ pw." 'limit 1 ″;

$ Result = mysql_query ($ SQL );
While ($ data = mysql_fetch_object ($ result )){
If ($ data-> ctr = 1 ){
// They're okay to enter the application!
$ Okay = 1;
}
}
If ($ okay ){
$ _ SESSION [loginokay] = true;
Header ("index. php ");
} Else {
Header ("login. php ");
}
?>

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:
$ SQL = "select count (*) as ctr from users where
Username = 'foo' and password = "or '1' = '1' limit 1 ″;
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, so that it is impossible for a string to pass special characters such as an marker and

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.