Prevent SQL injection implementation code in PHP

Source: Internet
Author: User
Tags php code sql injection sqlite valid vars what sql mysql database mysql gui

PHP to prevent SQL injection implementation code, need friends can refer to the following

The type of injection attack may have many different types of attack motives, but at first glance there seems to be more types. This is very real-if a malicious user discovers a way to execute multiple queries. We will discuss this in detail later in this article. If your script is executing a SELECT command, an attacker can force the display of every row in a table-by injecting a condition such as "1=1" into the WHERE clause, as follows (where the injection portion is shown in bold): SELECT * FROM Wines where variety = ' Lagrein ' OR 1=1; ' As we discussed earlier, this may be useful information in itself because it reveals the general structure of the table (which is not achievable by a common record), and potentially displays records that contain confidential information. An update directive potentially has a more immediate threat. By placing other attributes in the SET clause, an attacker can modify any field in the currently updated record, such as the following example (where the injection section is shown in bold): UPDATE wines SET type= ' red ', ' vintage ' = ' 9999 ' WHERE Variety = ' Lagrein ' by adding a constant true condition such as 1=1 to a WHERE clause of an update instruction, the scope of the modification can be extended to each record, such as the following example (where the injection part is shown in bold): Update wines SET Type = ' red ', ' vintage ' = ' 9999 WHERE variety = ' lagrein ' or 1=1; ' The most dangerous instruction may be delete-it is not difficult to imagine. The injection technology is the same as we have seen-by modifying the WHERE clause to extend the scope of the affected record, such as the following example (where the injection portion is shown in bold): DELETE from wines WHERE variety = ' Lagrein ' OR 1=1; '

Two, multiple queries inject multiple query injection will exacerbate the potential damage an attacker could cause-by allowing multiple destructive instructions to be included in a query. When using the MySQL database, an attacker could easily do this by inserting an unexpected terminator into the query-at which point a injected quotation mark (either single or double quotes) marks the end of the desired variable, and then terminates the instruction with a semicolon. Now, an additional attack instruction may be added to the end of the original instruction that is now terminated. The final destructive query might look like this: The copy code code is as follows: SELECT * FROM wines WHERE variety = ' Lagrein '; GRANT all in *.* to ' badguy@% ' identified by ' gotcha '; ' This injection will create a new user Badguy and give its network privileges (all the privileges on the table); and there's a "jinx". Password is added to this simple SELECT statement. If you follow our recommendations in previous articles-strictly restricting the privileges of users of the process, this should not work because the Web server daemon no longer has the grant privileges you have withdrawn. In theory, however, such an attack could give badguy free authority to implement whatever he does to your database. As to whether such a multiple query will be handled by the MySQL server, the conclusion is not unique. Some of these may be due to different versions of MySQL, but most of them are due to the way multiple queries exist. The MySQL monitor completely allows such a query. The common MySQL gui-phpmyadmin will copy all of the previous content before the final query and do just that. However, most of the multiple queries in an injection context are managed by PHP's MySQL extensions. Fortunately, by default, it is not allowed to execute multiple instructions in a single query; Attempting to execute two directives (such as the one shown above) will simply result in failure-no errors are set and no output information is generated. In this case, although PHP is just "behaving" to its default behavior, it does protect you from most simple injection attacks. The new mysqli extension (reference http://php.net/mysqli) in PHP5, like MySQL, inherently does not support multiple queries, but provides a mysqli_multi_query () function to support you in implementing multiple queries-if you really want to. However, for sqlite-, an embeddable SQL database engine bound to PHP5 (reference Http://sqlite.org/and Http://php.net/sqlite) are more frightening, because they are easy to use and attract the attention of a large number of users. In some cases, SQLite allows such a many-to-many query by default, because the database can optimize batch queries, especially very efficient batch INSERT statement processing. However, if the results of the query are used by your script (for example, when retrieving records with a SELECT statement), the Sqlite_query () function will not allow multiple queries to execute.

Three, Invision Power BOARD SQL injection Vulnerability Invision Power BOARD is a well-known forum system. May 6, 2005, a SQL injection vulnerability was found in the login code. The discovery is James Bercegay of Gulftech Security. This login query looks like this: $DB->query ("select * from Ibf_members WHERE id= $mid and password= ' $pid '"); Where the member ID variable $mid and the password ID variable $pid are retrieved from the My_cookie () function using the following two lines of code: the copy code is as follows: $mid = Intval ($std->my_getcookie (' member_id ')); $pid = $std->my_getcookie (' Pass_hash '); Here, the My_cookie () function retrieves the required variables from the cookie using the following statement: Return UrlDecode ($_cookie[$ibforums->vars[' cookie_id ']. $name]); "Note" The value returned from this cookie is not processed at all. Although $mid is coerced into an integer before it is used in a query, $pid remains unchanged. Therefore, it is very easy to suffer from the type of injection we discussed earlier. Thus, the vulnerability is exposed by modifying the My_cookie () function as follows: if (! In_array ($name, Array (' Topicsread ', ' forum_read ', ') Collapseprefs ')) {return $this-> clean_value (UrlDecode ($_cookie[$ibforums->vars[' cookie_id '). $name])) else {return UrlDecode ($_cookie[$ibforums->vars[' cookie_id ']. $name]); After such corrections, key variables in the "Through" Global Clean_value () function is returned, but the other variables are not checked. Now that we have a general idea of what SQL injection is, how it is injected, and how vulnerable it is, then let's explore how to effectively advanceAgainst it. Fortunately, PHP provides us with a wealth of resources, so we have sufficient confidence to predict that an application built carefully and thoroughly using the technology we recommend will fundamentally eliminate any possibility of SQL injection from your script-by "cleaning up" your users ' data before it can cause any damage.

Iv. define each value in your query we recommend that you make sure that you define every value in your query. String values are first and foremost, and those that you normally expect should use "single" (Not "double") quotes.   On the one hand, if you use double quotes to allow PHP to replace variables within the string, this makes the input query easier; On the other hand, this (admittedly, very small amount) will also reduce the analysis of the PHP code later. Next, let's use the non-injected query we started with to illustrate this problem: SELECT * FROM wines WHERE variety = ' lagrein ' or expressed as a PHP statement: $query = "SELECT * FROM Wines W Here variety = ' $variety '; Technically, quotes are not needed for numeric values. But if you don't mind enclosing a value in quotation marks for a field such as wine, and if your user enters a null value into your form, you will see a query similar to the following: SELECT * from wines WHERE vintage = of course, The query is syntactically invalid, but the following syntax is valid: SELECT * FROM wines WHERE vintage = ' The second query will (presumably) not return any fruit, but at least it will not return an error message.

V. Check the type of value submitted by the user from the previous discussion, we have seen that so far the main source of SQL injection has often been on an unexpected form entry. However, when you provide a way for users to submit certain values through a single table, you should have a considerable advantage in determining what kind of input you want to make-which makes it easier for us to check the validity of the user's entry. In previous articles, we have discussed such a checksum problem; So, here we simply summarize the main points we discussed at the time. If you're expecting a number, then you can use one of these techniques to make sure that you're getting really a numeric type: · Use the Is_int () function (or Is_integer () or Is_long ()). · Use the GetType () function. · Use the Intval () function. · Use the Settype () function. To check the length of user input, you can use the strlen () function. To check whether a desired time or date is valid, you can use the Strtotime () function. It can almost certainly ensure that a user's entry does not contain a semicolon character (unless the punctuation mark can be legally included). You can easily implement this with the help of the Strpos () function, as follows: if (Strpos ($variety, '; ')) exit ("$variety is a invalid value for variety!"); As we mentioned earlier, as long as you analyze your user input expectations carefully, you should be able to easily check out many of the problems that exist. Six, filter every suspicious character from your query although in the previous article, we have discussed how to filter out the problem of dangerous characters, but here, let us briefly emphasize and summarize the problem: · Do not use the MAGIC_QUOTES_GPC directive or its "behind the Scenes"-addslashes () function, which is restricted in application development, and this function requires additional steps-use the Stripslashes () function. · In contrast, the mysql_real_escape_string () function is more commonly used, but it has its own drawbacks.

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.