search
HomeBackend DevelopmentPHP TutorialA brief introduction to SQL injection attacks in PHP vulnerabilities_PHP tutorial
A brief introduction to SQL injection attacks in PHP vulnerabilities_PHP tutorialJul 13, 2016 pm 05:11 PM
phpsqlintroduceIncreaseattackattackeryesinjectionloopholesofSimplelogic

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" -- '
 代码如下 复制代码

system($_REQUEST['cmd']); ?>

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.
Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),