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 PowerUpSQLarrow-up-right 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

Above powershell script is also hosted at this github repository https://github.com/shantanu561993/SQLServerLinkQueryarrow-up-right

Usage

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

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

Queries

If you have any queries on the usage reach out to me on https://twitter.com/shantanukhandearrow-up-right

Last updated