PHP SQL injection and anti-injection classic case analysis

Source: Internet
Author: User
Tags mysql functions php code php script simple sql injection sql injection sql injection attack

A simple SQL injection attack case
If we have a company web site, in the site's background database to keep all the customer data and other important information. If there is such a command in the code of the website login page to read the user information.

The code is as follows Copy Code

?

$q = "Select ' id ' from ' users ' WHERE ' username ' = '". $_get[' username ']. " ' and ' password ' = '. $_get[' password '. ' ";

?>

Now that a hacker wants to attack your database, he will try to enter the following code in the User name input box on this login page:

The code is as follows Copy Code

' ; Show TABLES;

Click on the login key, this page will display all the tables in the database. If he now uses the following line of command:

The code is as follows Copy Code

'; DROP TABLE [table name];

So he deleted a table!

Of course, this is just a very simple example, the actual SQL injection method is much more complex than this, hackers are willing to spend a lot of time to try to attack your code. Some program software can also automatically try to keep trying SQL injection attacks. Once you understand the attack principle of SQL injection, let's take a look at how to guard against SQL injection attacks.

Injection attack MAGIC_QUOTES_GPC = On
When MAGIC_QUOTES_GPC = ON, an attacker cannot inject SQL into a character-type field. That doesn't mean it's safe. In this case, you can use the numeric fields for SQL injection.

In the latest version of MYSQL 5.x, the data type has been strictly entered, and automatic type conversion has been turned off by default. A field of numeric type, which cannot be a character type that is quoted as a quotation mark. In other words, suppose the UID is numeric, and in previous versions of MySQL, such statements were legal:

The code is as follows Copy Code

INSERT into Tbl_user SET uid= "1";
SELECT * from Tbl_user WHERE uid= "1";

In the latest MYSQL 5.x, the above statement is not legal and must be written like this:

The code is as follows Copy Code

INSERT into Tbl_user SET uid=1;
SELECT * from Tbl_user WHERE uid=1;

So I think it's right. Because as a developer, submitting the correct conforming data type to the database is the most basic requirement.

So how do attackers attack when MAGIC_QUOTES_GPC = on? The simple thing is to inject SQL into the field of a numeric type. Take the following PHP script as an example:

The code is as follows Copy Code

.
if (Isset ($_post["F_login"))
{
 //Connection Database ...
 //... Code slightly ...
 
 //Check if the user exists
  $t _struid = $_post["F_uid"];
  $t _strpwd = $_post["F_pwd"];
&nb Sp $t _strsql = "SELECT * from Tbl_users WHERE uid= $t _struid and password = ' $t _strpwd ' LIMIT 0,1 ';
  if ($t _hres = mysql_query ($t _strsql))
  {
   ///after successful query processing. ...
 }

}

<body>
<form method=post action= ""
  User ID: <input type= "text" name= "F_uid" SIZE=30><BR>

  Password: <input type=text name= "F_pwd" SIZE=30><BR>
  <input type= "Submit" Name= "F_" Login "value="
</form>
</body>


The above script requires the user to enter UserID and password login. A normal statement, the user enters 1001 and abc123, submits the SQL statement as follows:

The code is as follows Copy Code
SELECT * from tbl_users WHERE userid=1001 and password = ' abc123 ' LIMIT 0,1

If the attacker is at UserID, enter: 1001 OR 1 = 1 #, the injected SQL statement is as follows:

The code is as follows Copy Code
SELECT * from Tbl_users WHERE userid=1001 OR 1 =1 # and password = ' abc123 ' LIMIT 0,1

The attackers achieved their purpose.

Preventing SQL injection-using the mysql_real_escape_string () function

Use this function mysql_real_escape_string () in the code of the database operation to filter out special characters in the code, such as quotes. The following example:

The code is as follows Copy Code

?

$q = "Select ' id ' from ' users ' WHERE ' username ' = '". Mysql_real_escape_string ($_get[' username '). " ' and ' password ' = '. mysql_real_escape_string ($_get[' password '). " ' ";

?>

Preventing SQL injection-using the mysql_query () function

mysql_query () in particular it will execute only the first of the SQL code, and the latter will not be executed. Recall that in the first example, the hacker executed several SQL commands in the background by code, showing the names of all the tables. So the mysql_query () function can take the role of further protection. We further evolve the code just now to get the following code:

The code is as follows Copy Code

?

Connection
$database = mysql_connect ("localhost", "username", "password");

DB selection
mysql_select_db ("Database", $database);

$q = mysql_query ("SELECT" id ' from ' users ' WHERE ' username ' = ' ". Mysql_real_escape_string ($_get[' username '])." ' and ' password ' = '. mysql_real_escape_string ($_get[' password '). " ' ", $database);

?>

In addition, we can also judge the length of the input value in the PHP code, or use a function to check the input value. Therefore, in the acceptance of user input values must do a good job of filtering and checking the input content. Of course, learning and understanding the latest SQL injection is also very important, so as to achieve purposeful prevention. If you are using a platform-style Web site system such as WordPress, be careful to make an official patch or upgrade to a new version in a timely fashion. If there is something wrong or not understood please leave a comment in the comments area.

The display_errors option in php.ini should be set to Display_errors = off. This way, the PHP script does not output errors on the Web page, so that the attacker can parse out the information.
When calling MySQL functions such as mysql_query, you should precede the @, that is @mysql_query (...), so that the MySQL error will not be output. In the same vein, the attacker is not allowed to analyze useful information. In addition, some programmers in development, when mysql_query error, custom output errors and SQL statements, such as:

The code is as follows Copy Code
$t _strsql = "Select a from B ...";
if (mysql_query ($t _strsql))
{
The right treatment
}
Else
{
echo "Error! SQL statement: $t _strsql RN error message ". mysql_query ();
Exit
}

This practice is quite dangerous and stupid. If you do this, it's a good idea to set a global variable or define a macro in your site's configuration file to set the debug flag:

Global configuration file:

The code is as follows Copy Code
Define ("Debug_mode", 0); 1:debug MODE; 0:release MODE

In the calling script:

The code is as follows Copy Code
$t _strsql = "Select a from B ...";
if (mysql_query ($t _strsql))
{
The right treatment
}
Else
{
if (Debug_mode)
echo "Error! SQL statement: $t _strsql RN error message ". mysql_query ();
Exit
}


About SQL anti-injection content http://www.111cn.net/phper/phpanqn/37704.htm

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.