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

Jul 13, 2016 pm 05:11 PM
php sql introduce Increase attack attacker yes injection loopholes of Simple logic

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.
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles