Home > Backend Development > PHP Tutorial > A brief introduction to SQL injection attacks in PHP vulnerabilities_PHP tutorial

A brief introduction to SQL injection attacks in PHP vulnerabilities_PHP tutorial

WBOY
Release: 2016-07-13 17:11:24
Original
1018 people have browsed it

SQL injection is an attack that allows an attacker to add additional logical expressions and commands to an existing SQL query. This attack is able to succeed whenever the data submitted by the user is not properly validated and stuck with a legitimate SQL queries are together, so SQL injection attacks are not a problem of PHP but a problem of programmers.


General steps for SQL injection attacks:

1. Attackers visit sites with SQL injection vulnerabilities and look for injection points

2. The attacker constructs an injection statement, and the injection statement is combined with the SQL statement in the program to generate a new SQL statement

3. The new sql statement is submitted to the database for execution

4. The database executed a new SQL statement, triggering a SQL injection attack

Examples

Database

CREATE TABLE `postmessage` (

 `id` int(11) NOT NULL auto_increment,

 `subject` varchar(60) NOT NULL default ",

 `name` varchar(40) NOT NULL default ",

 `email` varchar(25) NOT NULL default ",

`question` mediumtext NOT NULL,

`postdate` datetime NOT NULL default '0000-00-00 00:00:00′,

PRIMARY KEY (`id`)

 ) ENGINE=MyISAM DEFAULT CHARSET=gb2312 COMMENT='User's Message' AUTO_INCREMENT=69;

grant all privileges on ch3.* to 'sectop'@localhost identified by '123456′;

 //add.php insert message

//list.php message list

 //show.php Show messages

Page /show.php?id=71 There may be an injection point, let’s test it

 /show.php?id=71 and 1=1

Return to page


Once the record was queried, once there was no record, let’s take a look at the source code

 //show.php lines 12-15

// Execute mysql query statement

 $query = "select * from postmessage where id = ".$_GET["id"];

 $result = mysql_query($query)

or die("Failed to execute ySQL query statement: " . mysql_error());

After the parameter id is passed in, the sql statement combined with the previous string is put into the database to execute the query

Submit and 1=1, the statement becomes select * from postmessage where id = 71 and 1=1. The values ​​before and after this statement are both true, and after and is also true, and the queried data is returned

Submit and 1=2, the statement becomes select * from postmessage where id = 71 and 1=2. The first value of this statement is true, the last value is false, and the next value is false, and no data can be queried

A normal SQL query, after passing through the statement we constructed, forms a SQL injection attack. Through this injection point, we can further obtain permissions, such as using union to read the management password, read database information, or use mysql's load_file, into outfile and other functions to further penetrate.

Anti-SQL injection methods

$id = intval ($_GET['id']);

Of course, there are other variable types. If necessary, try to force the format.


Character parameter:

Use the addslashes function to convert single quotes "'" to "'", double quotes """ to """, backslashes "" to "", and NULL characters plus backslashes ""

Function prototype

 string addslashes (string str)

str is the string to be checked

Then we can fix the code vulnerability that just appeared

// Execute mysql query statement

$query = "select * from postmessage where id = ".intval($_GET["id"]);

 $result = mysql_query($query)

or die("Failed to execute ySQL query statement: " . mysql_error());

If it is a character type, first determine whether magic_quotes_gpc can be On. If it is not On, use addslashes to escape the special characters

The code is as follows Copy code
 代码如下 复制代码

 

  if(get_magic_quotes_gpc())

  {

  $var = $_GET["var"];

  }

  else

  {

  $var = addslashes($_GET["var"]);

  }

]

 if(get_magic_quotes_gpc())  { $var = $_GET["var"];  } else  {  $var = addslashes($_GET["var"]);  } ]


The SQL statement contains variables with quotes

SQL code:

The code is as follows Copy code
 代码如下 复制代码

SELECT * FROM article WHERE articleid = '$id'

SELECT * FROM article WHERE articleid = $id

SELECT * FROM article WHERE articleid = '$id'

SELECT * FROM article WHERE articleid = $id

Both writing methods are common in various programs, but the security is different. The first sentence puts the variable $id in a pair of single quotes, which makes the variables we submit become characters. The string, even if it contains the correct SQL statement, will not be executed normally. The second sentence is different. Since the variables are not put in single quotes, everything we submit, as long as it contains spaces, the variables after the spaces will be used as SQL statements are executed, so we need to develop the habit of adding quotes to variables in SQL statements.

3. URL pseudo-static

URL pseudo-static is URL rewriting technology, like Discuz! Similarly, it is a good idea to rewrite all URLs into a format similar to xxx-xxx-x.html, which is beneficial to SEO and achieves a certain level of security. But if you want to prevent SQL injection in PHP, you must have a certain "regular" foundation.

4. Use PHP functions to filter and escape

The more important point of SQL injection in PHP is the setting of GPC, because versions below MYSQL4 do not support sub-statements, and when magic_quotes_gpc in php.ini is On, all " ' " in the submitted variables (single quotation marks), " " " (double quotation marks), " " (backslash) and null characters will automatically be converted into escape characters containing backslashes, which brings a lot of obstacles to SQL injection.

5. Use PHP’s MySQL function to filter and escape

PHP’s MySQL operation functions include addslashes(), mysql_real_escape_string(), mysql_escape_string() and other functions, which can escape special characters or characters that may cause database operation errors.

So what are the differences between these three functional functions? Let’s talk about it in detail below:

① The problem with addslashes is that hackers can use 0xbf27 to replace single quotes, while addslashes just changes 0xbf27 to 0xbf5c27, which is called a valid multi-byte character. 0xbf5c is still regarded as a single quote, so addslashes cannot Successfully intercepted.

Of course, addslashes is not useless. It is used for processing single-byte strings. For multi-byte characters, use mysql_real_escape_string.
 代码如下 复制代码

if(!get_magic_quotes_gpc()){  $lastname = addslashes($_POST['lastname']);}else{  $lastname = $_POST['lastname'];}

In addition, for the example of get_magic_quotes_gpc in the php manual:

The code is as follows Copy code
if(!get_magic_quotes_gpc()){ $lastname = addslashes($_POST['lastname']);}else{ $lastname = $_POST['lastname'];}

 代码如下 复制代码
function daddslashes($string, $force = 0, $strip = FALSE) {   
if(!MAGIC_QUOTES_GPC || $force) {       
if(is_array($string)) {          
 foreach($string as $key => $val) {               
 $string[$key] = daddslashes($val, $force, $strip);         
   }      
  } else
  {           
  $string = addslashes($strip ? stripslashes($string) : $string);       
  }   
  }   
  return $string;
 }
It is best to check $_POST['lastname'] when magic_quotes_gpc is already turned on. Let’s talk about the difference between the two functions mysql_real_escape_string and mysql_escape_string:
The code is as follows Copy code
function daddslashes($string, $force = 0 , $strip = FALSE) { if(!MAGIC_QUOTES_GPC || $force) {  if(is_array($string)) {                                            foreach($string as $key => $val) {                                      $string[$key] = daddslashes($val, $force, $strip); }       } else {                                             $string = addslashes($strip ? stripslashes($string) : $string); }   }   return $string; }

Command 1 - Write arbitrary file

MySQL has a built-in command that can be used to create and write system files. The format of this command is as follows:

The code is as follows
 代码如下 复制代码

mysq> select "text" INTO OUTFILE "file.txt"

Copy code

mysq> select "text" INTO OUTFILE "file.txt"

 代码如下 复制代码

select user, password from user where user="admin" and password='123'
结果查询:

select user, password from user where user="admin" and password='123' union select "text",2 into outfile "/tmp/file.txt" -- '



A big disadvantage of this command is that it can be appended to an existing query using the UNION SQL token.

 代码如下 复制代码

mysql> select load_file("PATH_TO_FILE");

For example, it can be appended to the following query:

The code is as follows Copy code

select user, password from user where user="admin" and password='123'

Result query:

select user, password from user where user="admin" and password='123' union select "text",2 into outfile "/tmp/file.txt" -- '
 代码如下 复制代码

As a result of the above command, the /tmp/file.txt file will be created including the query results.

Command 2 - Read any file

MySQL has a built-in command that can be used to read arbitrary files. Its syntax is simple. B. We will utilize this b command plan.
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template