PHP vulnerability SQL injection attack simple Introduction _php tutorial

Source: Internet
Author: User
Tags sql injection attack
SQL injection is an attack that allows an attacker to add additional logical expressions and commands to an existing SQL query, the kind of attack that can succeed whenever a user submits data that is not properly validated, and sticks to a legitimate SQL query together, so that SQL injection attacks are not a problem with PHP and programmers.


General steps for SQL injection attacks:

1. An attacker accesses a site with a SQL injection vulnerability, looking for an injection point

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

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

4. The database executes a new SQL statement, triggering 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 the 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, let's test

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

Back to Page


One query to record, one time no, let's take a look at the source code

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 ());

When the parameter ID is passed in, the SQL statement that is combined with the preceding string is placed into the database to execute the query

Commits and 1=1, the statement becomes a select * from postmessage where id = 1=1 and the value after the statement is true, and later is true, the data returned to the query

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

Normal SQL queries, after the statements we construct, form a SQL injection attack. Through this injection point, we can further get permissions, such as the use of Union to read the management password, read the database information, or use MySQL load_file,into outfile functions such as further infiltration.

Anti-SQL injection method

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

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


Character type parameter:

Use the Addslashes function to convert single quotes "'" To "'", "" "," "", "" "," "", "" "," "", "" "," ""

Function prototypes

String addslashes (String str)

STR is the string to check

So the code bug 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 judge 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 formulations are common in various programs, but the security is different, the first sentence because the variable $id in a pair of single quotes, so that we commit the variables are changed into a string, even if the correct SQL statement is not executed, and the second sentence is different, because the variable is not put in single quotes, All we have to commit, as long as there are spaces, the variables after that space are executed as SQL statements, so we have to get into the habit of quoting the variables in the SQL statement.

3. URL pseudo-Static

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

4. Filtering and escaping with PHP functions

The most important point of SQL injection in PHP is the GPC setup problem, because the MYSQL4 below is not supported by 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 cause a lot of obstacles to SQL injection.

5. Filtering and escaping with PHP's MySQL function

PHP's MySQL operation function has functions such as addslashes (), mysql_real_escape_string (), mysql_escape_string (), which can escape special characters or characters that may cause errors in database operations.

So what's the difference between these three function functions? Let's go through the following details:

The problem with ①addslashes is that hackers can use 0xbf27 instead of single quotes, and addslashes just modifies 0xbf27 to 0xbf5c27, called a valid multibyte character, where 0xbf5c is still considered a single quote, So addslashes can't intercept successfully.

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

Another 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 ');}


It's a good idea to check $_post[' LastName ' for MAGIC_QUOTES_GPC already open.

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 drawback of this command is that it can be appended to an existing query using the Union's SQL token.

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 arbitrary file
MySQL has a built-in command that can be used to read arbitrary files. Its syntax is simple. B. We will use this B command to plan.

The code is as follows Copy Code

Mysql> Select Load_file ("Path_to_file");

Web Shell

Webshell is a tool that polpular and is widely used to execute commands from a shell 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 a very basic shell that executes the code PHP is to be (parameters via California):

The code is as follows Copy Code

http://www.bkjia.com/PHPjc/629607.html www.bkjia.com true http://www.bkjia.com/PHPjc/629607.html techarticle SQL injection is an attack that allows an attacker to add additional logical expressions and commands to an existing SQL query, which can be successful every time a user submits data that is incorrectly verified, and sticky ...

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