Saltar a contenido

04.-Herramienta `metasploit`

Metasploit es un framework “open source” de Explotación y Postexplotación en infraestructuras y sistemas. Escrito en lenguaje Ruby, contiene herramientas orientadas a la explotación de vulnerabilidades.

Características principales

  • Gran base de datos de exploits de vulnerabilidades conocidas.
  • Herramientas para la generación de payloads específicos.
  • Plugins para integración con motores de bases de datos, Nessus y Nmap.

Interfaces disponibles

msfconsole: Interfaz en modo consola (opción por defecto). armitage: Interfaz gráfica, que debe instalarse por separado.

Módulos principales

Metasploit está organizado en cinco módulos principales:

Auxiliary

  • Herramientas para la fase de enumeración y escaneo.
  • Incluye módulos para ataques de fuerza bruta.

Exploits

  • Contiene todos los exploits disponibles en Metasploit.
  • Organizados jerárquicamente por sistemas operativos y software afectado.

Payloads

  • Incluye payloads para acciones simples (creación de usuarios, modificación de configuraciones).
  • Incluye shells inversas (non-staged y staged) y la shellcode avanzada meterpreter.

Encoders

  • Modifican el código de los payloads para ofuscarlos y evadir antivirus o IDS.

Post

  • Módulos para postexplotación.
  • Incluyen herramientas para:
    • Transferencia de archivos.
    • Persistencia en la víctima.
    • Automatización de procesos.
    • Técnicas de elevación de privilegios.

Uso de Metasploit

Acceso a msfconsole

Para acceder a msfconsole, invoca el siguiente comando en la línea de comandos:

$ msfconsole

Una vez iniciada la consola, puedes usar el comando help para listar los comandos disponibles.

msf6 > help

Core Commands
=============

    Command           Description
    -------           -----------
    ?                 Help menu
    banner            Display an awesome metasploit banner
    cd                Change the current working directory
    color             Toggle color
    connect           Communicate with a host
    debug             Display information useful for debugging
    exit              Exit the console
    features          Display the list of not yet released features that can be opted in to
    get               Gets the value of a context-specific variable
    getg              Gets the value of a global variable
    grep              Grep the output of another command
    help              Help menu
    history           Show command history
    load              Load a framework plugin
    quit              Exit the console
    repeat            Repeat a list of commands
    route             Route traffic through a session
    save              Saves the active datastores
    sessions          Dump session listings and display information about sessions
    set               Sets a context-specific variable to a value
    setg              Sets a global variable to a value
    sleep             Do nothing for the specified number of seconds
    spool             Write console output into a file as well the screen
    threads           View and manipulate background threads
    tips              Show a list of useful productivity tips
    unload            Unload a framework plugin
    unset             Unsets one or more context-specific variables
    unsetg            Unsets one or more global variables
    version           Show the framework and console library version numbers


Module Commands
===============

    Command           Description
    -------           -----------
    advanced          Displays advanced options for one or more modules
    back              Move back from the current context
    clearm            Clear the module stack
    favorite          Add module(s) to the list of favorite modules
    favorites         Print the list of favorite modules (alias for `show favorites`)
    info              Displays information about one or more modules
    listm             List the module stack
    loadpath          Searches for and loads modules from a path
    options           Displays global options or for one or more modules
    popm              Pops the latest module off the stack and makes it active
    previous          Sets the previously loaded module as the current module
    pushm             Pushes the active or list of modules onto the module stack
    reload_all        Reloads all modules from all defined module paths
    search            Searches module names and descriptions
    show              Displays modules of a given type, or all modules
    use               Interact with a module by name or search term/index


Job Commands
============

    Command           Description
    -------           -----------
    handler           Start a payload handler as job
    jobs              Displays and manages jobs
    kill              Kill a job
    rename_job        Rename a job


Resource Script Commands
========================

    Command           Description
    -------           -----------
    makerc            Save commands entered since start to a file
    resource          Run the commands stored in a file


Database Backend Commands
=========================

    Command           Description
    -------           -----------
    analyze           Analyze database information about a specific address or address range
    db_connect        Connect to an existing data service
    db_disconnect     Disconnect from the current data service
    db_export         Export a file containing the contents of the database
    db_import         Import a scan result file (filetype will be auto-detected)
    db_nmap           Executes nmap and records the output automatically
    db_rebuild_cache  Rebuilds the database-stored module cache (deprecated)
    db_remove         Remove the saved data service entry
    db_save           Save the current data service connection as the default to reconnect on startup
    db_stats          Show statistics for the database
    db_status         Show the current data service status
    hosts             List all hosts in the database
    klist             List Kerberos tickets in the database
    loot              List all loot in the database
    notes             List all notes in the database
    services          List all services in the database
    vulns             List all vulnerabilities in the database
    workspace         Switch between database workspaces


Credentials Backend Commands
============================

    Command           Description
    -------           -----------
    creds             List all credentials in the database


Developer Commands
==================

    Command           Description
    -------           -----------
    edit              Edit the current module or a file with the preferred editor
    irb               Open an interactive Ruby shell in the current context
    log               Display framework.log paged to the end if possible
    pry               Open the Pry debugger on the current module or Framework
    reload_lib        Reload Ruby library files from specified paths
    time              Time how long it takes to run a particular command


DNS Commands
============

    Command           Description
    -------           -----------
    dns               Manage Metasploit's DNS resolving behaviour

Comandos básicos de msfconsole

El comando search se utiliza para realizar búsquedas en los módulos de Metasploit. La búsqueda se lleva a cabo en los campos de nombre y descripción, lo que permite encontrar módulos que coincidan con un término específico.

Por ejemplo, si se busca el término Windows, el comando incluirá todos los resultados que contengan la palabra Windows en el nombre del módulo o en su descripción.

msf6 > search usermap_script

Matching Modules
================

   #  Name                                Disclosure Date  Rank       Check  Description
   -  ----                                ---------------  ----       -----  -----------
   0  exploit/multi/samba/usermap_script  2007-05-14       excellent  No     Samba "username map script" Command Execution


Interact with a module by name or index. For example info 0, use 0 or use exploit/multi/samba/usermap_script

Info

  • El comando info proporciona información detallada sobre un módulo específico de Metasploit. Este comando es útil para:

  • Ver la descripción del módulo.

  • Identificar el objetivo (target) al que está destinado.
  • Consultar las opciones de configuración necesarias, como:
    • Dirección IP y puerto de la víctima.
    • Credenciales requeridas (si aplica).
    • Otros parámetros específicos del módulo.

Uso del Comando:

Antes de seleccionar un módulo para su uso, es recomendable ejecutar info para entender cómo configurarlo adecuadamente. Por ejemplo:

  msf6 > info exploit/windows/smb/ms09_050_smb2_negotiate_func_index

         Name: MS09-050 Microsoft SRV2.SYS SMB Negotiate ProcessID Function Table Dereference
       Module: exploit/windows/smb/ms09_050_smb2_negotiate_func_index
     Platform: Windows
         Arch: 
   Privileged: Yes
      License: Metasploit Framework License (BSD)
         Rank: Good
    Disclosed: 2009-09-07

  Provided by:
    Laurent Gaffie <laurent.gaffie@gmail.com>
    hdm <x@hdm.io>
    sf <stephen_fewer@harmonysecurity.com>

  Available targets:
        Id  Name
        --  ----
    =>  0   Windows Vista SP1/SP2 and Server 2008 (x86)

  Check supported:
    No

  Basic options:
    Name    Current Setting  Required  Description
    ----    ---------------  --------  -----------
    RHOSTS                   yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit/ba
                                       sics/using-metasploit.html
    RPORT   445              yes       The target port (TCP)
    WAIT    180              yes       The number of seconds to wait for the attack to complete.

  Payload information:
    Space: 1024

  Description:
    This module exploits an out of bounds function table dereference in the SMB
    request validation code of the SRV2.SYS driver included with Windows Vista, Windows 7
    release candidates (not RTM), and Windows 2008 Server prior to R2. Windows Vista
    without SP1 does not seem affected by this flaw.

  References:
    https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/2009/MS09-050
    https://nvd.nist.gov/vuln/detail/CVE-2009-3103
    http://www.securityfocus.com/bid/36299
    OSVDB (57799)
    https://seclists.org/fulldisclosure/2009/Sep/0039.html


  View the full module info with the info -d command.

Show

El comando show permite listar todos los módulos disponibles en Metasploit. Además, es posible filtrar los resultados por categorías específicas de módulos, como exploits, payloads, auxiliares, entre otros.

Ejemplos:

  • Mostrar módulos auxiliares:
msf > show auxiliary
  • Mostrar exploits disponibles:
msf > show exploits
  • Mostrar opciones del módulo seleccionado:
msf > show options
  • Mostrar sistemas operativos compatibles con el exploit seleccionado:
msf > show targets
  • Mostrar payloads compatibles con el exploit seleccionado:
msf > show payloads

Use

Selecciona un módulo para su uso:

msf > use nombre_del_modulo

Set

Configura las opciones de un módulo:

msf (nombre_del_modulo) > set nombre_de_la_variable valor

Exploit o Run

Ejecuta el módulo seleccionado:

msf > run

Para saber más

Se puede obtener un listado completo de los comandos de Metasploit desde el siguiente enlace: Comandos Metasploit.

También puedes ver un video sobre el uso básico de Metasploit en el siguiente enlace: Video tutorial.