Phpsql injection and anti-injection Classic Case Analysis _ PHP Tutorial

Source: Internet
Author: User
Tags how to prevent sql injection how to prevent sql injection attacks mysql functions simple sql injection sql injection attack sql injection methods sql injection prevention
Phpsql injection and anti-injection Classic case analysis. SQL injection and anti-injection are actually Attacks and Defenses. today we want to tell you the most basic injection and prevention methods, the principle is to take advantage of some features of php or mysql, and we did not note that SQL injection and anti-injection are actually an attack and defense, today, we want to tell you that the most basic injection and prevention methods are based on some features of php or mysql, which we did not pay attention.

A simple SQL injection attack case
Assume that we have a company website that stores all customer data and other important information in the background database of the website. Assume that the code on the website logon page contains such a command to read user information.

The code is as follows:

$ Q = "SELECT 'id' FROM 'users' WHERE 'username' = '". $ _ GET ['username']. "'AND 'password' = '". $ _ GET ['password']. "'";

?>

Now a hacker wants to attack your database. he will try to enter the following code in the username input box on the logon page:

The code is as follows:

'; Show tables;

Click the login key. This page displays all tables in the database. If he uses the following command:

The code is as follows:

'; Drop table [table name];

In this way, a table is deleted!

Of course, this is just a simple example. the actual SQL injection method is much more complicated than this one. hackers are willing to spend a lot of time trying to attack your code. Some program software can also automatically attempt SQL injection attacks. After understanding the principles of SQL injection attacks, let's take a look at how to prevent SQL injection attacks.

Injection attack when magic_quotes_gpc = On
When magic_quotes_gpc = On, attackers cannot perform SQL injection On fields of the stable type. This does not mean this is safe. In this case, you can use numeric fields for SQL injection.

In MYSQL 5.x of the latest version, data type input is strictly specified, and automatic type conversion is disabled by default. A numeric field cannot be a quote type marked with quotation marks. That is to say, if the uid is numeric, in the previous mysql version, such a statement is legal:

The code is as follows:

Insert into tbl_user SET uid = "1 ";
SELECT * FROM tbl_user WHERE uid = "1 ";

In the latest MYSQL 5.x, the preceding statement is not legal and must be written as follows:

The code is as follows:

Insert into tbl_user SET uid = 1;
SELECT * FROM tbl_user WHERE uid = 1;

In this case, I think it is correct. As a developer, it is the most basic requirement to submit correct data types that comply with the rules to the database.

How can attackers attack magic_quotes_gpc = On? It is very simple, that is, SQL injection to numeric fields. The following php script is used as an example:

The code is as follows:

If (isset ($ _ POST ["f_login"])
{
// Connect to the database...
//... Code omitted...

// Check whether the user exists
$ T_strUid = $ _ POST ["f_uid"];
$ T_strPwd = $ _ POST ["f_pwd"];
$ T_strSQL = "SELECT * FROM tbl_users WHERE uid = $ t_strUid AND password = '$ t_strPwd' LIMIT 0, 1 ";
If ($ t_hRes = mysql_query ($ t_strSQL ))
{
// Processing after successful query...
}

}
?>
Sample test



The above script requires the user to enter userid and password to log on. A normal statement. The user inputs 1001 and abc123. the SQL statement submitted is as follows:

The code is as follows:
SELECT * FROM tbl_users WHERE userid = 1001 AND password = 'abc123' LIMIT

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

The code is as follows:
SELECT * FROM tbl_users WHERE userid = 1001 OR 1 = 1 # AND password = 'abc123' LIMIT

The attacker achieved the goal.

Prevent SQL injection-use the mysql_real_escape_string () function

In the database operation code, use this function mysql_real_escape_string () to filter out special characters in the code, such as quotation marks. For example:

The code is as follows:

$ Q = "SELECT 'id' FROM 'users' WHERE 'username' = '". mysql_real_escape_string ($ _ GET ['username']). "'AND 'password' = '". mysql_real_escape_string ($ _ GET ['password']). "'";

?>

Prevent SQL injection-use the mysql_query () function

Especially for mysql_query (), it will only execute the first SQL code, but will not be executed later. In the previous example, the hacker executed multiple SQL commands in the background using code to display the names of all tables. Therefore, the mysql_query () function can be further protected. We further evolved the code and got the following code:

The code is as follows:

// 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 determine the length of the input value in the PHP code, or use a function to check the input value. Therefore, you must filter and check the input content where user input values are accepted. Of course, it is also very important to learn and understand the latest SQL injection methods so that we can prevent them with purpose. If you are using a desktop website system such as Wordpress, be sure to promptly install official patches or upgrade to a new version. Leave a message in the comment area if you do not know anything or do not understand it.

The display_errors option in php. ini should be set to display_errors = off. In this way, php scripts do not output errors on web pages, so that attackers can analyze the information.
When calling mysql functions such as mysql_query, add @, I .e. @ mysql_query (...), so that mysql errors will not be output. Similarly, attackers may not analyze useful information. In addition, some programmers are used to output errors and SQL statements when mysql_query errors during development, such:

The code is as follows:
$ T_strSQL = "SELECT a from B ....";
If (mysql_query ($ t_strSQL ))
{
// Correct handling
}
Else
{
Echo "error! SQL statement: $ t_strSQL rn error message ". mysql_query ();
Exit;
}

This approach is quite dangerous and stupid. To do this, you 'd better set a global variable or define a macro in the website configuration file and set the debug flag:

In the global configuration file:

The code is as follows:
Define ("DEBUG_MODE", 0); // 1: debug mode; 0: RELEASE MODE

// In the call script:

The code is as follows:
$ T_strSQL = "SELECT a from B ....";
If (mysql_query ($ t_strSQL ))
{
// Correct handling
}
Else
{
If (DEBUG_MODE)
Echo "error! SQL statement: $ t_strSQL rn error message ". mysql_query ();
Exit;
}


About SQL Injection Prevention content http://www.bKjia. c0m/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.