Metasploit Series : Part 1 – Basics of Metasploit

Metasploit Basics

Metasploit is an Open Source Exploitation Framework developed by Rapid7, used for simulated attack during penetration testing. It provides a platform and tooling for scanning a target, launching attacks using exploits, post exploitation modules as well as tooling for exploit development.

The Metasploit Framework is a Ruby-based, modular penetration testing platform that enables you to write, test, and execute exploit code. The Metasploit Framework contains a suite of tools that you can use to test security vulnerabilities, enumerate networks, execute attacks, and evade detection. At its core, the Metasploit Framework is a collection of commonly used tools that provide a complete environment for penetration testing and exploit development.

The metasploit is originally developed by HD Moore in 2003, and now owned by the security company Rapid7. rapid7 offers a Metasploit Pro version (commercial) as will as open sourced Metasploit community edition.

Metasploit is a very powerful tool and because of if open-source availability, it is used by almost anyone form the growing area of Cyber Security, Penetration Testing, DevSecOps etc. Metasploit is a reliable and easy to install/use tool. As of the current metasploit version 6.0.45 contains 2134 exploits, 1139 auxiliary modules, 364 post exploitation modules, 592 payloads, 45 encoders, 10 nops and 8 evasion techniques.

Metasploit Architecture

Tools

These tools are the group of appropriate utilities.

Plugins

At runtime, plugins are some loadable extensions.

Libraries

These libraries are appropriate libraries of Ruby. Theses libraries allows metasploit to run exploits without having to write additional code for rudimentary tasks, such as HTTP requests or encoding of payloads. Some important libraries are :

  • REX : It handles almost every core function like setting up formatting, connections, sockets, and other functions.
  • MSF CORE : It offers the common API and the original core that defines the framework.
  • MSF BASE : Provides simplified APIs for use in the Framework

Interfaces

Interfaces provide users the capability for accessing Metasploit in so many different ways (web and CLI for instance).

  • MSFConsole : It is the most popular interface to use in metasploit, it provide an interctive shell to run and use metasploit.
  • MSF CLI : It uses a command line to run directly instead of using a unique interpreter for framework.
  • Armitage : It contains a graphical user interface, which is very interactive.

Modules

Modules are used to implement specific tasks.

Metasploit Modules

All the actions in metasploit are performed using modules. In kali linux all the modules located in /usr/share/metasploit-framework/modules directory. Metasploit version 6 offers 7 modules :

Exploit Module

An exploit is a piece of code or set of instructions that take advantage of vulnerabilities in a system and cause the program to behave unexpectedly is termed as an exploit. Exploits can takes advantage of various vulnerability classes like buffer overflow, code injection, use-after-free, string overflow, and other web application vulnerabilities. Metasploit consists huge database of these kind of exploits.

Payload Module

A payload is an action you do once you have access to somebody’s system. Suppose, you have hacked somebody and you have gained access to their system, now every activity you want to perform is carried out through a payload. The payloads in metasploit are command shells, meterpreter etc.

payloads are divided into three submodules :

  1. Singles : singles are small self-contained code designed to take some single action. In other words it would be a fire-and-forget kind of payload. This can be used when the target has no network access. For example, just creating a user.
  2. stagers : stagers implement a communication channel that can be used to deliver another payload that can used to control the target system. For example a payload that an attacker can use to upload a bigger file onto a victim system.
  3. stages : Stages are payload components that are downloaded by Stagers modules. The various payload stages provide advanced features with no size limits such as Meterpreter and VNC Injection.

Auxiliary Module

Auxiliary modules help in information gathering, service identification and enumeration of the remote systems and services. These modules includes fuzzers, port scanners, sniffers and more.

encoders module

The encoder modules are designed to enocde/re-encode payloads and exploits to enable them to get past security defense systems such AV and IDS’s.

Post module

Post is short for post-exploitation. These are modules that are used after exploitation of a system. These modules are often used after the system has been compromised and has the Meterpreter running on the system. These can include such modules as keyloggers, privilege escalation, enabling the web cam or microphone, etc.

Nops module

In machine language, a NOP is short for “no operation”. This causes the system’s CPU to do nothing for a clock cycle. Often, NOP’s are essential for getting a system to run remote code after a buffer overflow exploit. These are often referred to as “NOP sleds”. These modules are used primarily to create NOP sleds.

evasion module

Evasion module provides various scripts to generate evasive payloads to bypass antivirus and intrusion detection softwares.

Get Started with Metasploit

Since Metasploit comes preinstalled with kali linux, so we are going to use kali linux, you can dowonload the iso or vm images from here : https://www.kali.org/get-kali/.

First start the postgresql server

sudo service postgresql start

Now to initialize database type

sudo msfdb init

Now start metasploit

$ msfconsole 

MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMM                MMMMMMMMMM
MMMN$                           vMMMM
MMMNl  MMMMM             MMMMM  JMMMM
MMMNl  MMMMMMMN       NMMMMMMM  JMMMM
MMMNl  MMMMMMMMMNmmmNMMMMMMMMM  JMMMM
MMMNI  MMMMMMMMMMMMMMMMMMMMMMM  jMMMM
MMMNI  MMMMMMMMMMMMMMMMMMMMMMM  jMMMM
MMMNI  MMMMM   MMMMMMM   MMMMM  jMMMM
MMMNI  MMMMM   MMMMMMM   MMMMM  jMMMM
MMMNI  MMMNM   MMMMMMM   MMMMM  jMMMM
MMMNI  WMMMM   MMMMMMM   MMMM#  JMMMM
MMMMR  ?MMNM             MMMMM .dMMMM
MMMMNm `?MMM             MMMM` dMMMMM
MMMMMMN  ?MM             MM?  NMMMMMN
MMMMMMMMNe                 JMMMMMNMMM
MMMMMMMMMMNm,            eMMMMMNMMNMM
MMMMNNMNMMMMMNx        MMMMMMNMMNMMNM
MMMMMMMMNMMNMMMMm+..+MMNMMNMNMMNMMNMM
        https://metasploit.com

       =[ metasploit v6.0.45-dev                          ]
+ -- --=[ 2134 exploits - 1139 auxiliary - 364 post       ]
+ -- --=[ 592 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 8 evasion                                       ]

Metasploit tip: After running db_nmap, be sure to
check out the result of hosts and services

msf6 >

Metasploit Commands

Here are some basic metasploit commands to starts with

help

Shows all commands with details. The different categories of commands are :

Core commands : Used within the msfconsole session.

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 : Used within metasploit command.

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
    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

Other categories of commands are listed below :

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_status         Show the current data service status
    hosts             List all hosts 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

search

search command is used to find right modules for your target. With thousands of modules available, finding a specific module could be problematic and therefore the search command comes to the rescue. Example

msf6 > search heartbleed

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

   #  Name                                              Disclosure Date  Rank    Check  Description
   -  ----                                              ---------------  ----    -----  -----------
   0  auxiliary/server/openssl_heartbeat_client_memory  2014-04-07       normal  No     OpenSSL Heartbeat (Heartbleed) Client Memory Exposure
   1  auxiliary/scanner/ssl/openssl_heartbleed          2014-04-07       normal  Yes    OpenSSL Heartbeat (Heartbleed) Information Leak

To narrow down the search we can specific keywords

type : State the type of module you are searching for. It could be an exploit, payload, encoder, or post.
platform : The target Operating System for which the module was made for.
name : The descriptive module name you are searching for.
cve : Modules with a matching CVE ID.

Some examples are :

search type:scanner platform:windows name:heartbleed
search type:exploit platform:windows name:smb
search platform:linux name:ssl

For more detailed help on search type help search.

use

The use command load a module.

use <module_name/path>

Example

use exploit/windows/local/cve_2020_0796_smbghost

module is set successfully, and it responds with the type of module (exploit) abd the abbreviated module name in red color.

info

Shows information about staged/set modules. To use this command first stage a module and run the command.

msf6 exploit(linux/samba/is_known_pipename) > info

       Name: Samba is_known_pipename() Arbitrary Module Load
     Module: exploit/linux/samba/is_known_pipename
   Platform: Linux
       Arch:
 Privileged: Yes
    License: Metasploit Framework License (BSD)
       Rank: Excellent
  Disclosed: 2017-03-24

Provided by:
  steelo <knownsteelo@gmail.com>
  hdm <x@hdm.io>
  bcoles <bcoles@gmail.com>

Available targets:
  Id  Name
  --  ----
  0   Automatic (Interact)
  1   Automatic (Command)
  2   Linux x86
  3   Linux x86_64
  4   Linux ARM (LE)
  5   Linux ARM64
  6   Linux MIPS
  7   Linux MIPSLE
  8   Linux MIPS64
  9   Linux MIPS64LE
  10  Linux PPC
  11  Linux PPC64
  12  Linux PPC64 (LE)
  13  Linux SPARC
  14  Linux SPARC64
  15  Linux s390x

Check supported:
  Yes

Basic options:
  Name            Current Setting  Required  Description
  ----            ---------------  --------  -----------
  RHOSTS                           yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
  RPORT           445              yes       The SMB service port (TCP)
  SMB_FOLDER                       no        The directory to use within the writeable SMB share
  SMB_SHARE_NAME                   no        The name of the SMB share containing a writeable directory

Payload information:
  Space: 9000

Description:
  This module triggers an arbitrary shared library load vulnerability
  in Samba versions 3.5.0 to 4.4.14, 4.5.10, and 4.6.4. This module
  requires valid credentials, a writeable folder in an accessible
  share, and knowledge of the server-side path of the writeable
  folder. In some cases, anonymous access combined with common
  filesystem locations can be used to automatically exploit this
  vulnerability.

References:
  https://nvd.nist.gov/vuln/detail/CVE-2017-7494
  https://www.samba.org/samba/security/CVE-2017-7494.html

show

Show available payloads, targets and options corresponding with the staged exploit. Some important show command are :

show payloads : Gives the list of compatible with the staged exploit.

msf6 exploit(linux/samba/is_known_pipename) > show payloads

Compatible Payloads
===================

   #  Name                       Disclosure Date  Rank    Check  Description
   -  ----                       ---------------  ----    -----  -----------
   0  payload/cmd/unix/interact                   normal  No     Unix Command, Interact with Established Connection

show targets : List all the targets vulnerable to the staged exploit.

msf6 exploit(linux/samba/is_known_pipename) > show targets

Exploit targets:

   Id  Name
   --  ----
   0   Automatic (Interact)
   1   Automatic (Command)
   2   Linux x86
   3   Linux x86_64
   4   Linux ARM (LE)
   5   Linux ARM64
   6   Linux MIPS
   7   Linux MIPSLE
   8   Linux MIPS64
   9   Linux MIPS64LE
   10  Linux PPC
   11  Linux PPC64
   12  Linux PPC64 (LE)
   13  Linux SPARC
   14  Linux SPARC64
   15  Linux s390x

show options : Shows the options yet to be set before running the exploit. Options to be set may include RHOST, LHOST, PATH, LPORT, etc.

msf6 exploit(linux/samba/is_known_pipename) > show options

Module options (exploit/linux/samba/is_known_pipename):

   Name            Current Setting  Required  Description
   ----            ---------------  --------  -----------
   RHOSTS                           yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT           445              yes       The SMB service port (TCP)
   SMB_FOLDER                       no        The directory to use within the writeable SMB share
   SMB_SHARE_NAME                   no        The name of the SMB share containing a writeable directory


Payload options (cmd/unix/interact):

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------


Exploit target:

   Id  Name
   --  ----
   0   Automatic (Interact)

Other available options are :

msf6> help show
[*] Valid parameters for the "show" command are: all, encoders, nops, exploits, payloads, auxiliary, post, plugins, info, options, favorites
[*] Additional module-specific parameters are: missing, advanced, evasion, targets, actions

set

Used to set/overwrite the options on the staged module. These options are RHOST, LHOST, PATH, etc.

set RHOSTS 192.168.1.115
set RPORT 8080
set LHOST 192.168.1.110

unset

Used to unset the previousely set options.

unset RHOSTS

exploit

Once the exploit is staged and all the options have been set, the attack is launched using exploit or run command.

msf6> exploit

back

This command takes us one step back. It is applicable in cases when you want to make changes to the options set.

exit

Exit from the msfconsole.

msf6> exit

save

Save the current state (modules, current settings etc) into a file. So if exit from msfconsole, and restart again then the current state is loaded using saved file.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.