# MSSQL Link Crawl - OpenQuery Quotes Calculator

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. &#x20;

![SQL Server Crawl](https://2978447173-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MDtkWzdvgRTZWDjfsGa%2F-MTCAsLC1b_IOtDWBkcG%2F-MTCBxVNhzTEmQMggBZd%2FMSSQL_Crawl.jpg?alt=media\&token=71ddbab1-2f13-462c-9ac2-1918ecb01b7b)

### 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&#x20;

I saw that [`PowerUpSQL`](https://github.com/NetSPI/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`&#x20;

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

```csharp
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&#x20;

```csharp
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 d`in 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

```csharp
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>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.redteam.cafe/red-team/database/mssql-link-crawl-openquery-quotes-calulator.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
