MSSQL Link Crawl - OpenQuery Quotes Calculator

MSSQL Link Crawls

During many Red Team engagements, and Red Team exams we find ourselves grappling with MSSQL linked servers. One way to query a linked SQL servers is to use Openquery.

SQL Server Crawl

The Openquery Problem

The problem with using openquery is that it gets really complicated with the numbers of quotes which grows exponentially. Its very easy to loose track and waste hours on debugging one simple osquery.

The Solution

I saw that PowerUpSQL has some link crawling functionality for exploitation and they may have an automated way to generate queries. With some bit of digging, I was able to find Get-SQLServerLinkQuery

I extracted it and made 1 line change to make it print the openquery commands. Following is the extracted powershell code

Function Get-SQLServerLinkQuery{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false,
HelpMessage="SQL link path to crawl. This is used by Get-SQLServerLinkCrawl.")]
$Path=@(),
[Parameter(Mandatory=$false,
HelpMessage="SQL query to build the crawl path around")]
$Sql,
[Parameter(Mandatory=$false,
HelpMessage="Counter to determine how many single quotes needed")]
$Ticks=0
)
if ($Path.length -le 1){
return($Sql -replace "'", ("'"*[Math]::pow(2,$Ticks)))
} else {
Write-Output("select * from openquery(`""+$Path[1]+"`","+"'"*[Math]::pow(2,$Ticks)+
(Get-SQLServerLinkQuery -path $Path[1..($Path.Length-1)] -sql $Sql -ticks ($Ticks+1))+"'"*[Math]::pow(2,$Ticks)+")")
}
}

Above powershell script is also hosted at this github repository https://github.com/shantanu561993/SQLServerLinkQuery

Usage

Usage of this script is simple. You can import the script with Import-Module and then run the following powershell command

Get-SQLServerLinkQuery -Path @(0,'a','b','c','d') -Sql "select * from db.tables"

where

Path represents the SQL servers to be crawled. a, b, c and din this case are the four servers to be crawled. 0 in front of them is mandatory to make the query work properly

Sql represents the final SQL query you want to run on the SQL server d . In above example its Select * from db.tables

Output

The output of running above query will be

select * from openquery("a",'select * from openquery("b",''select * from openquery("c",''''select * from openquery("d",''''''''whoami'''''''')'''')'')')

Queries

If you have any queries on the usage reach out to me on https://twitter.com/shantanukhande