One is that the input data is not filtered (the input is filtered), and the other is that the data sent to the database is not escaped (Escape output ). These two important steps are indispensable and need special attention at the same time to reduce program errors.
For attackers, it is necessary to think about and test SQL injection attacks and make rational reasoning on the database solution (assuming that the attacker cannot see your source program and database solution ), consider the following simple logon form:
Copy codeThe Code is as follows:
<Form action = "/login. php" method = "POST">
<P> Username: <input type = "text" name = "username"/> </p>
<P> Password: <input type = "password" name = "password"/> </p>
<P> <input type = "submit" value = "Log In"/> </p>
</Form>
As an attacker, he starts to speculate on the query statement used to verify the user name and password. By viewing the source file, you can start to guess your habits.
Such as naming conventions. It is usually assumed that the field name in your form is the same as the field name in the data table. Of course, ensuring that they are different may not be a reliable security measure.
The first prediction generally uses the query in the following example:
Copy codeThe Code is as follows:
<? Php
$ Password_hash = md5 ($ _ POST ['Password']);
$ SQL = "SELECT count (*)
FROM users
WHERE username = '{$ _ POST ['username']}'
AND password = '$ password_hash '";
?>
Using the MD5 value of the user password is a common practice, but it is not particularly safe now. Recent research shows that the MD5 algorithm is flawed, and a large number of MD5 databases reduce the difficulty of MD5 reverse cracking. Please visit http://md5.rednoize.com/view the demo (the original article, professor of Shandong University Wang Xiaoyun's research shows that MD5 "Collision" can be quickly found ", it is two different files and strings that can generate the same MD5 value. MD5 is an information digest algorithm, rather than an encryption algorithm. Reverse cracking is impossible. However, in the preceding special case, using md5 directly is dangerous .).
The best protection method is to append a custom string to the password, for example:
Copy codeThe Code is as follows:
<? Php
$ Salt = 'shiflett ';
$ Password_hash = md5 ($ salt. md5 ($ _ POST ['Password']. $ salt ));
?>
Of course, attackers may not be able to guess for the first time. They often need to perform some tests. A better test method is to input single quotes as user names, because this may expose some important information. Many developers call the mysql_error () function to report errors when an error occurs in Mysql statement execution. See the following example:
Copy codeThe Code is as follows:
<? Php
Mysql_query ($ SQL) or exit (mysql_error ());
?>
Although this method is useful in development, it can expose important information to attackers. If the attacker uses single quotes as the user name and mypass as the password, the query statement will become:
Copy codeThe Code is as follows:
<? Php
$ SQL = "SELECT *
FROM users
WHERE username = '''
AND password = 'a029d0df84eb5549c641e04a9ef389e5 '";
?>
After the statement is sent to MySQL, the system displays the following error message:
Copy codeThe Code is as follows:
You have an error in your SQL syntax. Check the manual that corresponds to your
MySQL server version for the right syntax to use near 'where username = ''' AND
Password = 'a029d0df84eb55
The attacker knows the two field names (username and password) and the order in which they appear in the query. In addition, attackers also know that the data is not properly filtered (the program does not prompt illegal user names) and escaped (database errors occur), and the format of the WHERE condition is also exposed, attackers can then try to manipulate records that match the query.
At this point, attackers have many options. First, try to enter a special user name to make the query match regardless of whether the user name and password match:
Copy codeThe Code is as follows:
Myuser' or 'foo' = 'foo '--
Assuming that mypass is used as the password, the entire query will become:
Copy codeThe Code is as follows:
<? Php
$ SQL = "SELECT *
FROM users
WHERE username = 'myuser' or 'foo' = 'foo '--
AND password = 'a029d0df84eb5549c641e04a9ef389e5 '";
?>
Fortunately, SQL injection is easy to avoid. As mentioned above, you must always filter input and escape output.
Although neither step can be omitted, most SQL Injection risks can be eliminated as long as one of them is implemented. If you only filter the input without escaping the output, you may encounter a database error (legal data may also affect the correct format of the SQL query), but this is also not reliable, legal data may also change the behavior of SQL statements. On the other hand, if you escape the output without filtering the input, you can ensure that the data does not affect the SQL statement format, and also prevent a variety of common SQL injection attacks.
Of course, you still need to follow these two steps at the same time. The method for filtering input depends entirely on the type of input data (see the example in chapter 1), but escape is used to send the output data to the database as long as the same function is used. For MySQL users, you can use the mysql_real_escape_string () function ():
Copy codeThe Code is as follows:
<? Php
$ Clean = array ();
$ Mysql = array ();
$ Clean ['last _ name'] = "O 'Reilly ";
$ Mysql ['last _ name'] = mysql_real_escape_string ($ clean ['last _ name']);
$ SQL = "INSERT
INTO user (last_name)
VALUES ('{$ mysql ['last _ name']}') ";
?>
Try to use the escape functions designed for your database. If not, using the addslashes () function is the final better method.
When all data used to create an SQL statement is properly filtered and escaped, the risk of SQL injection is actually avoided. If you are using a database operation class that supports parameterized query statements and placeholders (such as PEAR: DB and PDO), you will get another protection. See the following example of using PEAR: DB:
Copy codeThe Code is as follows:
<? Php
$ SQL = 'insert
INTO user (last_name)
VALUES (?) ';
$ Dbh-> query ($ SQL, array ($ clean ['last _ name']);
?>
As the data in the preceding example cannot directly affect the format of the query statement, the risk of SQL injection is reduced. PEAR: The DB will automatically escape according to your database requirements, so you only need to filter the output.
If you are using a parameterized query statement, the input content will only be processed as data. In this way, there is no need to escape, although you may think this is a necessary step (if you want to stick to the escape output habit ). In fact, whether to escape is basically not affected, because there is no special character to be converted. To prevent SQL injection, parameterized query statements provide powerful protection for your program.
Note: For SQL injection, most virtual hosts now enable the magic_quotes_gpc option. In this case, all client GET and POST data are automatically processed by addslashes, therefore, SQL injection of string values is not feasible, but SQL injection of numeric values should be prevented, such as processing using functions such as intval. However, if you write generic software, you need to read magic_quotes_gpc from the server and then process it accordingly.