SQL injection attacks with PHP vulnerabilities-PHP Tutorial

Source: Internet
Author: User
SQL injection attacks with PHP vulnerabilities. SQL injection is an attack that allows attackers to add additional logical expressions and commands to query existing SQL statements. The attack is successful and the data submitted by the user is incorrect, concurrent SQL injection is an attack that allows attackers to add additional logical expressions and commands to query existing SQL statements. this attack can be successfully verified when the data submitted by the user is incorrect, there is a legitimate SQL query together, so SQL injection attacks are not a problem for php and programmers.


General steps for SQL injection attacks:

1. attacker visits websites with SQL injection vulnerabilities to find injection points

2. attackers construct injection statements, which are combined with the SQL statements in the program to generate new SQL statements.

3. the new SQL statement is submitted to the database for processing.

4. the database executes new SQL statements, triggering SQL injection attacks.

Instance

Database

Create table 'postmessage '(

'Id' int (11) not null auto_increment,

'Subobject' 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 '2017-00-00 00:00:00 ′,

Primary key ('id ')

) ENGINE = MyISAM default charset = gb2312 COMMENT = 'Caller's message 'AUTO_INCREMENT = 69;

Grant all privileges on ch3. * to 'sectop' @ localhost identified by '123 ′;

// Add. php insert a message

// List. php message list

// Show. php displays the message

Page/show. php? Id = 71 there may be injection points. let's test

/Show. php? Id = 71 and 1 = 1

Back to page


Once the record is found, once not, let's look at the source code

// Show. php 12-15 lines

// Execute the 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 preceding string is put into the database for query.

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

Submit and 1 = 2, the statement becomes select * from postmessage where id = 71 and 1 = 2. the value before the statement is true, the value after the statement is false, and the value after and is false. no data can be found.

Normal SQL queries have formed SQL injection attacks after the statements we have constructed. Through this injection point, we can further obtain permissions, such as using union to read management passwords, read database information, or using functions such as mysql load_file and into outfile to further penetrate.

Anti-SQL injection method

$ Id = intval ($ _ GET ['id']);

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


Signature parameters:

Use the addslashes function to convert single quotes "'" to "'", double quotes "to", backslash "" "\", NULL character plus backslash ""

Function prototype

String addslashes (string str)

Str is the string to be checked

We can fix the code vulnerability just now.

// Execute the 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 character type, first determine that magic_quotes_gpc cannot be On. when it is not On, use addslashes to escape special characters.

The code is as follows:

If (get_magic_quotes_gpc ())

{

$ Var = $ _ GET ["var"];

}

Else

{

$ Var = addslashes ($ _ GET ["var"]);

}

]


Enclose variables with quotation marks in SQL statements

SQL code:

The code is as follows:

SELECT * FROM article WHERE articleid = '$ ID'

SELECT * FROM article WHERE articleid = $ id

The two writing methods are common in various programs, but the security is different. The first sentence is to put the variable $ id in a pair of single quotes, so that all the variables we submit become strings, even if a correct SQL statement is included, the statement will not be executed normally, but the second sentence is different. because the variable is not put into single quotes, everything we submit, as long as it contains spaces, the variables after spaces are executed as SQL statements. Therefore, we need to develop the habit of adding quotation marks to the variables in SQL statements.

3. pseudo-static URL

URL pseudo-static, that is, URL rewriting technology, such as Discuz! In the same way, all URLs are rewriteinto the xxx-xxx-x.html format, which is conducive to SEO and achieves a certain degree of security. it is also a good way. However, to prevent SQL injection in PHP, you must have a "regular expression.

4. filter and escape using PHP functions

One of the most important aspects of php SQL injection is the setting of GPC, because versions earlier than MySQL 4 do not support substatements, and when php. when magic_quotes_gpc in ini is On, all "'" (single quotation marks), "(double quotation marks), and" "(backslash) in the submitted variables) and empty characters are automatically converted into escape characters containing backslash, which brings a lot of obstacles to SQL injection.

5. filter and escape using the MySQL function of PHP

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

So what are the differences between the three functional functions? The following is a detailed description:

① The problem with addslashes is that hackers can use 0xbf27 to replace single quotes, while addslashes only modifies 0xbf27 to 0xbf5c27, which is called a valid multi-byte character, where 0xbf5c is still regarded as single quotes, therefore, addslashes cannot be intercepted.

Of course, addslashes is not useless either. it is used for processing single-byte strings and mysql_real_escape_string is used for multi-byte characters.

In addition, the example of get_magic_quotes_gpc in the php Manual is as follows:

The code is as follows:

If (! Get_magic_quotes_gpc () {$ lastname = addslashes ($ _ POST ['lastname']);} else {$ lastname = $ _ POST ['lastname'];}


If magic_quotes_gpc is enabled, check $ _ POST ['lastname.

Let's talk about the differences between the two functions mysql_real_escape_string and mysql_escape_string:

The code is as follows:
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 for creating and writing system files. The command format is as follows:

The code is as follows:

Mysq> select "text" into outfile "file.txt"

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

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

The code is as follows:

Select user, password from user where user = "admin" and password = '000000'
Result query:

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

As a result of the preceding command, the file/tmp/file.txt will be created, including the query results.
Command 2-read arbitrary files
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:

Mysql> select load_file ("PATH_TO_FILE ");

Web shell

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

The following is a very basic shell of the PHP code to be executed (the parameter is passed through California ):

The code is as follows:

...

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.