Web security 101 it is best to discuss Web Application Security from a higher perspective before discussing the details of security implementation. This section describes some basic principles of the security philosophy, which should be kept in mind no matter what Web applications are being created. Part of these ideas comes from ChrisShiflett (his book on PHP security is invaluable
Web security 101 it is best to discuss Web Application Security from a higher perspective before discussing the details of security implementation. This section describes some basic principles of the security philosophy, which should be kept in mind no matter what Web applications are being created. Part of these ideas comes from Chris Shiflett (his book on PHP security is invaluable
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)Include any data that is not directly input by programmers in PHP code. Comes from any other source (suchGETVariables and formsPOST, Database, configuration file, session variable, or cookie) any data is untrusted.
For example, the following data elements can be considered safe because they are set in PHP.
Listing 1. Safe and flawless code
$myUsername = 'tmyer';$arrayUsers = array('tmyer', 'tom', 'tommy');define("GREETING", 'hello there' . $myUsername); |
However, the following data elements are flawed.
List 2. insecure and defective code
$myUsername = $_POST['username']; //tainted!$arrayUsers = array($myUsername, 'tom', 'tommy'); //tainted!define("GREETING", 'hello there' . $myUsername); //tainted! |
Why is the first variable$myUsernameIs it defective? Because it comes directly from the formPOST. 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$_POST['username']Run the cleanup code. If this is not done$myUsernameAny other time (such as in an array or constant), these objects may be contaminated.
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
$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 disableregister_globals. Ifregister_globals, You may do some careless things, such as using$variableReplaceGETOrPOSTString. By disabling this setting, PHP forces you to reference the correct variables in the correct namespace. To use a formPOSTShould be referenced$_POST['variable']. In this way, the specific variable will not be misunderstood as a cookie, session, orGETVariable.
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 fileerror_logThe entry provides an appropriate destination anddisplay_errorsSet 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. Easy Code Protection
//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$inputIt is defective and needs to be cleared 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 you use PHPregexTo ensureGETThe variable is completely numeric, and measures can still be taken to ensure that the user input for SQL query uses escape characters.
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
InSQL injection attacksBy manipulating the form orGETQuery string to add the 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. Simple logon form
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
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 across 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 enterfooAs the user name, enter' or '1'='1As a 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.
The solution to this problem is to build the PHPmysql_real_escape_string()The function is used as a wrapper 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.
Listing 7. Safe PHP form processing code
ctr == 1){//they're okay to enter the application!$okay = 1;}}if ($okay){$_SESSION['loginokay'] = true;header("index.php");}else{header("login.php");}?> |
Usemysql_real_escape_string()As a package for user input, it 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:
select count(*) as ctr from users where /username='foo' and password='/' or /'1/'=/'1' limit 1" |
There is nothing in the database that matches this password. Simply taking a simple step blocks a major vulnerability in a Web application. The experience here is that user input for SQL queries should always be escaped.
However, several security vulnerabilities need to be blocked. The next item is manipulation.GETVariable.
Prevents users from manipulating GET Variables
In the previous section, users are prevented from logging on with malformed passwords. If you are smart, you should apply the method you have learned to ensure that all user input in the SQL statement is escaped.
However, the user has logged on safely. A user having a valid password does not mean that he will follow the rules-he has many opportunities to cause damage. For example, an application may allow users to view special content. All links directtemplate.php?pid=33Ortemplate.php?pid=321Such a location. The part after the question mark in the URL is calledQuery string. Because the query string is directly placed in the URL, it is also calledGET query string.
In PHP, if disabledregister_globals, You can use$_GET['pid']Access this string. On the template. php page, operations similar to those in listing 8 may be performed.
Listing 8. Sample template. php
fetchPage($pid);//and now we have a bunch of PHP that displays the page//......//......?> |
What's wrong here? First, we implicitly believe thatGETVariablepidIs safe. What will happen? Most users are less intelligent and cannot construct semantic attacks. However, if they notice that the pid in the URL field of the browser is 33, the problem may start. If they enter another number, it may be okay; but if they enter something else, such as an SQL command or the name of a file (such as/etc/passwd), or do other pranks, for example, if you enter a value up to 3,000 characters, what will happen?
In this case, remember the basic rules and do not trust user input. Application developers know that the personal identifier (PID) accepted by template. php should be a number, so PHP'sis_numeric()The function ensures that non-numeric PIDs are not accepted, as shown below:
Listing 9. Use is_numeric () to restrict GET Variables
fetchPage($pid);//and now we have a bunch of PHP that displays the page//......//......}else{//didn't pass the is_numeric() test, do something else!}?> |
This method seems to be valid, but the following inputs can be easily passed throughis_numeric()Check:
- 100 (valid)
- 100.1 (decimal places should not exist)
- + 0123.45e6 (Scientific notation-not good)
- 0xff33669f (hexadecimal -- dangerous! Dangerous !)
So what should PHP developers with security awareness do? Years of experience show that the best practice is to use regular expressions to ensure that the entireGETA variable is composed of numbers, as shown below:
Listing 10. use regular expressions to restrict GET Variables
if (strlen($pid)){if (!ereg("^[0-9]+___FCKpd___11quot;,$pid)){//do something appropriate, like maybe logging /them out or sending them back to home page}}else{//empty $pid, so send them back to the home page}//we create an object of a fictional class Page, which is now//moderately protected from evil user input$obj = new Page;$content = $obj->fetchPage($pid);//and now we have a bunch of PHP that displays the page//......//......?> |
All you need to do is usestrlen()Check whether the variable length is non-zero. If yes, use a full-number regular expression to ensure that the data element is valid. If the PID contains letters, slashes, dots, or anything similar to the hexadecimal format, this routine captures it and shields the page from user activity. If you have a lookPageClass behind the scenes, we can see that security-aware PHP developers have already entered$pidEscape, thus protectingfetchPage()Method:
Listing 11. Escape the fetchPage () method
You may ask, "since you have ensured that the PID is a number, why should we escape it ?" Because I don't know how many different contexts will be usedfetchPage()Method. It must be protected in all the places where this method is called, and escaping in the method reflects the meaning of in-depth defense.
What happens if you try to enter a very long value, for example, a buffer overflow attack with 1000 characters? This issue is discussed in more detail in the next section. However, you can add another check to ensure that the entered PID has the correct length. You knowpidThe maximum length of a field is 5 characters, so you can add the following check.
Listing 12. Use Regular Expressions and length checks to restrict GET Variables
5){//do something appropriate, like maybe logging /them out or sending them back to home page}}else{//empty $pid, so send them back to the home page}//we create an object of a fictional class Page, which is now//even more protected from evil user input$obj = new Page;$content = $obj->fetchPage($pid);//and now we have a bunch of PHP that displays the page//......//......?> |
Currently, no one can insert a 5,000-bit value in the database application-at least inGETThis is not the case where the string is located. Imagine a hacker biting his teeth when trying to break through your application and getting frustrated! Moreover, it is more difficult for hackers to conduct reconnaissance because the error report is disabled.
Buffer overflow attacks
Buffer overflow attacksAttempts to overflow the memory allocation buffer in PHP applications (or, more precisely, in Apache or the underlying operating system. Remember that you may write Web applications in advanced languages such as PHP, but you still need to call C (in Apache ). Like most low-level languages, C has strict rules for memory allocation.
The buffer overflow attack sends a large amount of data to the buffer, so that part of the data overflows to the adjacent memory buffer, thus damaging the buffer or Rewriting Logic. In this way, it can cause denial of service, damage data, or execute malicious code on a remote server.
The only way to prevent buffer overflow attacks is to check the length of all user input. For example, if there is a form element that requires the user's name to be input, add a value of 40 to this fieldmaxlengthAttribute, and usesubstr()Check. Listing 13 provides a brief example of the form and PHP code.
Listing 13. Check the length of user input
Why?maxlengthAttribute, which is also performed on the backendsubstr()Check? Because in-depth defense is always good. The browser prevents users from entering super-long strings that PHP or MySQL cannot safely process (imagine someone trying to enter a name up to 1,000 characters ), the backend PHP check ensures that no one remotely or in the browser can manipulate form data.
As you can see, this method is used withstrlen()CheckGETVariablepid. In this example, ignore any input value with a length of more than five characters, but you can also easily shorten the value to an appropriate length, as shown below:
Listing 14. Changing the length of the input GET variable
5){$pid = substr($pid,0,5);}//we create an object of a fictional class Page, which is now//even more protected from evil user input$obj = new Page;$content = $obj->fetchPage($pid);//and now we have a bunch of PHP that displays the page//......//......?> |
Note that the buffer overflow attack is not limited to long numeric or serial strings. You may also see a long hexadecimal string (usually looks like/xA3Or/xFF). Remember, the purpose of any buffer overflow attack is to drown out a specific buffer zone and place malicious code or instructions in the next buffer zone to corrupt data or execute malicious code. The easiest way to deal with hex buffer overflow is not to allow the input to exceed a specific length.
If you are allowed to enter a long form partition in the database, you cannot easily limit the Data Length on the client. After the data arrives in PHP, you can use a regular expression to clear any string like a hexadecimal string.
Listing 15. Preventing hexadecimal strings
You may find that these operations are a little too strict. After all, the hexadecimal string has a valid purpose, such as outputting characters in a foreign language. How to deploy hexadecimalregexIt is up to you to decide. A better strategy is to delete a hexadecimal string only when a row contains too many hexadecimal strings or the number of characters in the string exceeds a specified number (such as 128 or 255.
Cross-Site Scripting
InCross-Site ScriptingIn (XSS) attacks, a malicious user often enters information in a form (or in other user input mode), which inserts malicious client tags into the process or database. For example, assume that there is a simple visitor register program on the site, allowing visitors to leave their names, email addresses, and short messages. Malicious users can use this opportunity to insert things other than short messages, such as inappropriate images for other users, JavaScript redirection to another site, or cookie information theft.
Fortunately, PHP providesstrip_tags()Function, which can clear any content enclosed in HTML tags.strip_tags()Functions can also provide a list of allowed tags, suchOr.
Listing 16 provides an example built on the previous example.
Listing 16. Clear HTML tags from user input
From the security perspectivestrip_tags()It is necessary. If the form is in a protected area (such as the Content Management System) and you believe that the user will correctly execute their tasks (such as creating HTML content for a Web site), usestrip_tags()It may be unnecessary and may affect work efficiency.
Another problem: If you want to accept user input, such as comments to posts or visitor registration items, and you need to display this input to other users, you must put the response in the PHPhtmlspecialchars()Function. This function will work with the symbol,<And>Convert a symbol to an HTML object. For example (&)&. In this way, even if malicious content avoids the front-endstrip_tags()Will also be processed at the backendhtmlspecialchars()Processed.
Data manipulation in the browser
A browser plug-in allows users to tamper with header and form elements on a page. Using Tamper Data (a Mozilla plugin), you can easily manipulate simple forms containing many hidden text fields to send commands to PHP and MySQL.
The user clicksSubmitPreviously, he could start Tamper Data. When submitting a form, he will see a list of data fields in the form. Tamper Data allows users to Tamper with the Data, and then the browser completes form submission.
Let's go back to the example we created earlier. Check the string length, clear the HTML tag, and delete hexadecimal characters. However, some hidden text fields are added as follows:
Listing 17. Hiding Variables
Note: One of the hidden variables exposes the table name:users. The value iscreateOfactionField. With Basic SQL experience, we can see that these commands may control an SQL engine in middleware. To do this, you only need to change the table name or provide another option, for exampledelete.
Figure 1 illustrates the scope of failure that Tamper Data can provide. Note: Tamper Data not only allows users to access table Data elements, but also allows access to HTTP headers and cookies.
Figure 1. Tamper Data window
The simplest way to defend against such tools is to assume that any user may use Tamper Data (or similar tools ). Only the minimum amount of information required by the system to process the form is provided, and the form is submitted to some dedicated logic. For example, the registry form should only be submitted to the registration logic.
If a general form processing function has been created and many pages use this general logic, what should we do? What should I do if I use hidden variables to control the flow direction? For example, you may specify which database table to write or which File Repository to use in the hidden form variable. There are four options:
- Without changing anything, we secretly pray that there are no malicious users on the system.
- Rewrite function, use more secure special form processing functions, avoid using hidden form variables.
- Use
md5()Or other encryption mechanisms to encrypt table names or other sensitive information in hidden form variables. Do not forget to decrypt them on the PHP side.
- You can use abbreviations or nicknames to blur the meaning of values and then convert these values in the PHP form processing function. For example
usersTable, which can be useduOr any string (suchu8y90x0jkL.
The last two options are not perfect, but they are much better than making it easier for users to guess the middleware logic or data model.
What are the remaining problems? Remote form submission.
Remote form submission
The advantage of Web is that information and services can be shared. The downside is that you can share information and services, because some people do things without scruples.
Take the form as an example. Anyone can access a Web site and useFile> SaveCreate a local copy of the form. Then, he can modifyactionParameter to point to a fully qualified URL (not to formHandler. php, but to http://www.yoursite.com/formhandler.php, because the table is on this site), do whatever he wants, clickSubmitThe server receives the form data as a valid communication stream.
Check$_SERVER['HTTP_REFERER']To determine whether the request comes from your own server. This method can block most malicious users, but cannot block the most brilliant hackers. These people are smart enough to tamper with the reference information in the header so that the form's remote copy looks like it was submitted from your server.
A better way to process remote form submission is to generate a token based on a unique string or Timestamp and place the token in session variables and forms. After submitting the form, check whether the two tokens match. If they do not match, someone tries to send data from the form's remote copy.
To create a random Token, you can use the built-in PHPmd5(),uniqid()Andrand()Function:
Listing 18. Defense remote form submission
This technology is effective because session data in PHP cannot be migrated between servers. Even if someone has obtained your PHP source code, transfer it to your server and submit information to your server, your server only receives an empty or malformed session token and a previously provided form token. If they do not match, the remote form submission fails.
Conclusion
This tutorial discusses many issues:
- Use
mysql_real_escape_string()Prevents SQL Injection problems.
- Use regular expressions and
strlen()To ensureGETData has not been tampered.
- Use regular expressions and
strlen()To ensure that the data submitted by the user does not cause memory buffer overflow.
- Use
strip_tags()Andhtmlspecialchars()Prevents users from submitting potentially harmful HTML tags.
- This prevents the system from being broken through by tools such as Tamper Data.
- Use a unique token to prevent users from submitting forms to the server remotely.
This tutorial does not cover more advanced topics, such as file injection, HTTP Header Spoofing, and other vulnerabilities. However, the knowledge you have learned can help you immediately increase sufficient security to make the current project safer.