Full ban on SQL injection attacks in PHP

Source: Internet
Author: User
Tags sql injection attack vars what sql what sql injection mysql gui
One of the completely banned SQL injection attacks in PHP

I. Types of injection attacks

There may be many different types of attack motives, but at first glance there seems to be more types. This is very real-if a malicious user invents a measure that can perform multiple queries. We will discuss this in detail later in this article.

If your script is performing a SELECT command, an attacker could force the display of every row in a table-by injecting a condition such as ' 1=1 ' into the WHERE clause, as shown below (where the injection part is shown in bold):

SELECT * FROM wines WHERE variety = ' Lagrein ' OR 1=1; '



As we discussed earlier, this may be useful information in itself, as it reveals the general structure of the table (which is not achievable by an ordinary record), and an ambush to display records containing confidential information.

An update command ambush has a more direct threat. By placing other attributes in the SET clause, an attacker can fix any field in the record that is currently being updated, 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 condition such as 1=1 to the WHERE clause of an update instruction, this category of corrections can be extended to each record, such as the following example (where the injection section is shown in bold):

UPDATE Wines SET type= ' red ', ' vintage ' = ' 9999 WHERE variety = ' Lagrein ' OR 1=1; '



The most dangerous instructions could be delete-. This is not difficult to imagine. The injection technique is similar to what we have seen-by modifying the WHERE clause to enlarge the category of the affected record, such as the following example (where the injection is shown in bold):

DELETE from wines WHERE variety = ' Lagrein ' OR 1=1; '



Second, multiple query injection

Multiple query bets can exacerbate an ambush that an attacker could cause-by agreeing to multiple corrupt instructions contained in a single query. When applying a MySQL database, an attacker could easily do this by inserting an unexpected terminator into the query-at which point a quoted quotation mark (single or double quote) marks the end of the variable, and then applies a semicolon to terminate the instruction. Now, an additional attack instruction may be added to the end of the original instruction that is now terminated. The ultimate corrupt query might look like the following:

SELECT * FROM wines WHERE variety = ' Lagrein ';
GRANT all on * * to ' badguy@% ' identified by ' gotcha '; '



This injection will create a new user Badguy and give it network privileges (with all the privileges on all tables), and an ' ominous ' password is entered into this abbreviated SELECT statement. If you follow our recommendations in previous articles-strictly restricting the privileges of the process user, this should not work because the Web server daemon no longer has the grant privilege that you withdrew. In theory, however, such an attack might give badguy the freedom to achieve any control over your database.



As to whether such a multi-query will be processed by the MySQL server, the conclusion is not unique. Some of these reasons may be due to different versions of MySQL, but most of this is due to the way multiple queries exist. The MySQL monitoring program is complete to allow such a query. The common MySQL gui-phpmyadmin, which copies all the previous content before the final query, is only done.

However, most of the multiple queries in a high-low text are governed by PHP's expanded MySQL. Fortunately, by default, it does not promise to perform multiple instructions in a query; Attempting to perform two instructions (such as the one shown above) will briefly lead to a failure-no errors are set and no output information is inherently produced. In this case, although PHP is only ' whisper ' to implement its default action, it does protect you from most of the abbreviated injection attacks.

The new mysqli extension in PHP5 (refer to Http://php.net/mysqli), like MySQL, inherently does not support multiple queries, but it provides a mysqli_multi_query () function to support you in implementing multiple queries-if you really want to do this.

However, the sqlite-and PHP5 bound to the embedded SQL database engine (reference http://sqlite.org/and http://php.net/sqlite) are more frightening and attract a large number of users because of their ease of application. In some cases, sqlite defaults to such a multi-directive query, because the database can optimize batch queries, especially the very efficient batch INSERT statement processing. However, if the results of the query are applied to your script (for example, if a SELECT statement is used to retrieve records), the Sqlite_query () function does not promise to perform multiple queries.


Iii. invision Power BOARD SQL Injection Vulnerability

Invision Power Board is a well-known forum system. May 6, 2005, a SQL injection vulnerability was invented in the login code. Its inventor 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 applied the following two lines of code are retrieved from the My_cookie () function:

$mid = Intval ($std->my_getcookie (' member_id '));
$pid = $std->my_getcookie (' Pass_hash ');
Here, the My_cookie () function applies the following statement to retrieve the requested variable from the cookie:

Return UrlDecode ($_cookie[$ibforums->vars[' cookie_id '). $name]);
"Beware" the value returned from the cookie is basically not processed. Although $mid is forced to convert to an integer before it is applied to the query, $pid remains the same. Therefore, it is very easy to encounter the injection type of attack we discussed earlier.

Therefore, by correcting the My_cookie () function in the following way, this vulnerability will be exposed:

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 this correction, the key variables are returned after the ' Global Clean_value () function, while the other variables are not checked.

Now that we have a general understanding of what SQL injection is, its injection principle, and the vulnerability of this injection, let's explore how to prevent it effectively. Fortunately, PHP provides us with a wealth of resources, so we have full confidence to predict that a use program built using our recommended technique carefully and thoroughly will eliminate any possibility of SQL injection from your script-by ' clearing ' your users ' data before it can cause any damage.

Iv. define each value in your query

We recommend that you ensure that each value in your query is defined. String values are the first, and those that you normally see should apply ' single ' (Not ' double ') quotes. On the one hand, if you use double quotes to allow PHP to change the variables within the string, this can make it easier to input queries, on the other hand, this (can not be denied, only a very small amount) will also reduce the subsequent PHP code analysis work.

Below, let's use the non-injection query we started with to illustrate this title:

SELECT * FROM wines WHERE variety = ' Lagrein '
or expressed as a PHP statement as:

$query = ' SELECT * FROM wines WHERE variety = ' $variety ';
Technically, quotation marks do not need to be applied to numeric values. However, if you do not mind enclosing a value in quotation marks for a field such as wine and if your user enters an empty value into your form, you will see a query similar to the following:

SELECT * FROM wines WHERE vintage =
Of course, this 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. Checking the type of user-submitted values

As we can see from the previous discussion, the important origins of SQL injection so far tend to be in an unexpected form import. However, when you submit certain values through a form-one-way user supply opportunity, you should have a fairly good chance of determining what kind of input you want to get-which can make it easier for us to check the validity of user imports. In previous articles, we have discussed such a check title, so here we just briefly summarize the points we discussed at that time. If you are looking at a number, then you can apply one of the following techniques to make sure that you get really a number type:

· Apply the Is_int () function (or Is_integer () or Is_long ()).

· Apply the GetType () function.

· Apply the Intval () function.

· Apply the Settype () function.

To check the length of the user input, you can apply the strlen () function. You can apply the Strtotime () function to check if the time or date is valid for a period. It will almost certainly ensure that a user's imports do not contain semicolon characters (unless punctuation can be properly included). You can easily do this with the help of the Strpos () function, as shown below:


if (Strpos ($variety, '; ')) exit (' $variety is a invalid value for variety! ');
As we mentioned earlier, as long as you carefully analyze your users ' input, you should be able to easily check out many of the titles that exist.

Six, filter every suspicious character from your query

Although we have discussed how to filter out the title of dangerous characters in previous articles, let us again briefly exaggerate and return to the title:

· Do not apply the MAGIC_QUOTES_GPC directive or its ' behind the scenes '-addslashes () function, which is limited by application development, and this function also requests an additional step-apply the Stripslashes () function.

· In contrast, the mysql_real_escape_string () function is more commonly used, but it has its own problems.

The above is in PHP completely prohibit SQL injection attack of the second 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.