A comprehensive ban on SQL injection attacks in PHP three

Source: Internet
Author: User
Tags how sql injection works sql injection attack
First, establish a layer of security abstraction

We do not recommend that you manually use the preceding techniques for each user input instance, but strongly recommend that you create an abstraction layer for this purpose. A shorthand abstraction is to take your validation plan to a function and call it for each entry that the user has entered. Of course, we can also create a more complex, higher-level abstraction-encapsulating a secure query into a class, thus leveraging the full utility. There are already many such free classes available online, and in this article we are going to discuss some of them.

There are at least three advantages to doing this abstraction (and each one will improve the security level):

1. Localize the code.

2. Make the query structure faster and more reliable-as this can be done by putting some of the work into abstract code.

3. When built based on security features and applied appropriately, this will effectively prevent the various injection attacks we have discussed earlier.

Ii. Improvement of existing utilization procedures

If you want to improve an existing utilization program, it is most appropriate to apply a shorthand abstraction layer. A function that can simply ' liquidate ' any user you collect into the content may look like this:

function Safe ($string) {
Return '. Mysql_real_escape_string ($string). '''
}
"Take care" we have built the single quotation mark and the mysql_real_escape_string () function corresponding to the value request. Next, you can apply this function to structure a $query variable, as follows:

$variety = Safe ($_post[' variety ');
$query = ' SELECT * from Wines WHERE variety= '. $variety;
Now your user is trying to make an injection attack-by entering the following as the value of the variable $variety:

Lagrein ' or 1=1;
Note that if you do not perform the above ' liquidation ', the final query will look like this (which will result in unpredictable results):

SELECT * FROM wines WHERE variety = ' lagrein ' or 1=1; '
Now, however, since the user's input has been liquidated, the query statement becomes the following non-persecution situation:

SELECT * FROM wines WHERE variety = ' lagrein\ ' or 1=1\; '

Since there is no variety domain in the database that corresponds to the specified value (which is exactly what the malicious user has entered-lagrein ' or 1=1;), the query will not return any results, and the injection will fail.

Iii. protection of a new use procedure

If you are creating a new use program, you can create a layer of security abstraction from the beginning. Today, PHP 5 's newly improved support for MySQL (which is important in the new MYSQLI expansion) provides strong support for this security feature (both procedural and object-oriented). You can get information about mysqli from the site Http://php.net/mysqli. Be aware that this mysqli support is only available when you compile PHP with the--with-mysqli=path/to/mysql_config option. Here is a procedural version of the code to protect a mysqli-based query:



<?php
Retrieving the user's input
$animalName = $_post[' animalname ');
Connecting to a database
$connect = Mysqli_connect (' localhost ', ' username ', ' password ', ' database ');
if (! $connect) exit (' Connection failed: '. Mysqli_connect_error ());
Create a query statement source
$stmt = Mysqli_prepare ($connect, ' SELECT intelligence from animals WHERE name =? ');
if ($stmt) {
Bind the swap to the statement
Mysqli_stmt_bind_param ($stmt, ' s ', $animalName);
Fulfill the statement
Mysqli_stmt_execute ($stmt);
Search results ...
Mysqli_stmt_bind_result ($stmt, $intelligence);
// ... and show it
if (Mysqli_stmt_fetch ($stmt)) {
print ' A $animalName has $intelligence intelligence.\n ';
} else {
print ' Sorry, no records found. ';
}
Clear statement Source
Mysqli_stmt_close ($stmt);
}
Mysqli_close ($connect);
? >
The mysqli expands to provide a set of functions for structuring and performing queries. Moreover, it also provides a very accurate supply of the benefits of the previous application of our own safe () function.

In the above fragment, the input content of the user submission is collected first and the database connection is established. Then, apply the Mysqli_prepare () function to create a query statement source-named $stmt here to react to the name of the function that applied it. This function applies two parameters: a connection resource and a string (each time you apply a widening into a value, '? ') tags are inserted into them). In this case, you have only one such value-the name of the animal.

Notice that in a SELECT statement, place '? ' The only valid status of the tag is in the Value analogy section. That's why you don't need to specify which variable to apply (except in the Mysqli_stmt_bind_param () function). Here, you also need to specify its type-in this case, ' s ' for the string. Other possible types are: ' I ' for integers, ' d ' for double-precision numbers (or floating-point numbers), and ' B ' for binary strings.

function Mysqli_stmt_execute (), Mysqli_stmt_bind_result (), and Mysqli_stmt_fetch () are responsible for fulfilling the query and retrieving the results. If there is a search result, they are displayed; if there is no result, a harmless message is displayed. Finally, you need to close $stmt resources and database connections-to release them from memory.

Assuming that a legitimate user has entered the string ' lemming ', the routine will (presumably the appropriate data in the database) output the message ' A lemming have very low intelligence. ' Suppose there is a tentative injection-for example ' lemming ' or 1=1; ', then this routine will print (harmless) message ' Sorry, no records found. '
In addition, the mysqli extension also provides an object-oriented version of the same routine. Below, we want to clarify how this version is applied.

<?php
$animalName = $_post[' animalname ');
$mysqli = new mysqli (' localhost ', ' username ', ' password ', ' database ');
if (! $mysqli) exit (' Connection failed: '. Mysqli_connect_error ());
$stmt = $mysqli->prepare (' SELECT intelligence

From animals WHERE name =? ');
if ($stmt) {
$stmt->bind_param (' s ', $animalName);
$stmt->execute ();
$stmt->bind_result ($intelligence);
if ($stmt->fetch ()) {
print ' A $animalName has $intelligence intelligence.\n ';
} else {
print ' Sorry, no records found. ';
}
$stmt->close ();
}
$mysqli->close ();
? >
In fact, this part of the code is a copy of the previous description of the code-it applies an object-oriented syntax and organization approach, rather than strict procedural code.


Iv. a higher level of abstraction

If you apply an external library Peardb, you can use the program's security module for a comprehensive abstraction.

On the other hand, applying this inventory in a prominent problem: You can only be limited to some people's minds, and the code governance aspect has also added a lot of work. To do this, you need to think carefully before deciding whether to apply them. If you decide to do this, you can at least make sure that they really help you ' liquidate ' what your users have entered.

Five, test your injection-type protection in order to

As we discussed earlier, an important part of making sure that your scripts are safe is to test them. The best way to do this is to create your own SQL code injection test.
Here, we provide an example of such a test. In this example, we test the injection attack against a SELECT statement.

<?php
The protected function being tested
function Safe ($string) {
Return '. Mysql_real_escape_string ($string). '''
}
Connecting to a database
///////////////////////
Trying to make a bet
///////////////////////
$exploit = ' lemming ' and 1=1; ';
For liquidation
$safe = Safe ($exploit);
$query = ' SELECT * from animals WHERE name = $safe ';
$result = mysql_query ($query);
Testing whether the protection is sufficient
if ($result && mysql_num_rows ($result) = = 1) {
Exitt ' Protection succeeded:\n
Exploit $exploit was neutralized. ';
}
else {
Exit (' Protection failed:\n
Exploit $exploit is able to retrieve all rows. ');
}
? >
If you want to create such a test set and experiment with different bets based on different SQL commands, you will quickly detect any vulnerabilities in your protection strategy. Once you've corrected the headings, you can be sure-you've built a real injection-attack protection mechanism.

Vi. Summary

At the beginning of this series of articles, we analyzed a specific threat to your script through a SQL injection discussion-the result of inappropriate user input. After that, we describe how SQL injection works and accurately analyze how PHP is easy to be injected into. We then provide a practical example of the injection. After that, we recommend a series of measures to make an attempted injection attack harmless-this will be resolved by ensuring that all committed values are enclosed in quotation marks, by checking the type of user-submitted values, and by filtering out the characters of the ambush danger that your users have entered. Finally, we recommend that you better abstract your validation routines and supply script examples for changing an existing exploit. Then, we discuss the advantages of third-party abstract planning.

The above is in PHP completely prohibit SQL injection attack three of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.