Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Metasploit

You're reading from   Mastering Metasploit Take your penetration testing and IT security skills to a whole new level with the secrets of Metasploit

Arrow left icon
Product type Paperback
Published in May 2018
Publisher Packt
ISBN-13 9781788990615
Length 492 pages
Edition 3rd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Nipun Jaswal Nipun Jaswal
Author Profile Icon Nipun Jaswal
Nipun Jaswal
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Approaching a Penetration Test Using Metasploit FREE CHAPTER 2. Reinventing Metasploit 3. The Exploit Formulation Process 4. Porting Exploits 5. Testing Services with Metasploit 6. Virtual Test Grounds and Staging 7. Client-Side Exploitation 8. Metasploit Extended 9. Evasion with Metasploit 10. Metasploit for Secret Agents 11. Visualizing with Armitage 12. Tips and Tricks 13. Other Books You May Enjoy

Case study - diving deep into an unknown network

Recalling the basics of Metasploit, we are all set to perform our first penetration test with Metasploit. Consider an on-site scenario where we are asked to test an IP address and check if it's vulnerable to an attack. The sole purpose of this test is to ensure all proper checks are in place or not. The scenario is quite straightforward. We presume that all the pre-interactions are carried out with the client, and that the actual testing phase is going to start.

Please refer to the Revisiting the case study section if you want to perform the hands-on alongside reading the case study, as this will help you emulate the entire case study with exact configuration and network details.

Gathering intelligence

As discussed earlier, the gathering intelligence phase revolves around collecting as much information as possible about the target. This includes performing active and passive scans, which include port scanning, banner grabbing, and various other scans. The target under the current scenario is a single IP address, so here, we can skip gathering passive information and can continue with the active information gathering methodology only.

Let's start with the footprinting phase, which includes port scanning, banner grabbing, ping scans to check whether the system is live or not, and service detection scans.

To conduct footprinting and scanning, Nmap proves as one of the finest tools available. Reports generated by Nmap can be easily imported into Metasploit. However, Metasploit has inbuilt Nmap functionalities, which can be used to perform Nmap scans from within the Metasploit framework console and store the results in the database.

Using databases in Metasploit

It is always a better approach to store the results automatically alongside when you conduct a penetration test. Making use of databases will help us build a knowledge base of hosts, services, and the vulnerabilities in the scope of a penetration test. To achieve this functionality, we can use databases in Metasploit. Connecting a database to Metasploit also speeds up searching and improves response time. The following screenshot depicts a search when the database is not connected:

We saw in the installation phase how we can initialize the database for Metasploit and start it. To check if Metasploit is currently connected to a database or not, we can just type the db_status command, as shown in the following screenshot:

There might be situations where we want to connect to a separate database rather than the default Metasploit database. In such cases, we can make use of db_connect command, as shown in the following screenshot:

To connect to a database, we need to supply a username, password, and a port with the database name along with the db_connect command.

Let's see what other core database commands are supposed to do. The following table will help us understand these database commands:

Command

Usage information

db_connect

This command is used to interact with databases other than the default one

db_export

This command is used to export the entire set of data stored in the database for the sake of creating reports or as an input to another tool

db_nmap

This command is used for scanning the target with Nmap, and storing the results in the Metasploit database

db_status

This command is used to check whether database connectivity is present or not

db_disconnect

This command is used to disconnect from a particular database

db_import

This command is used to import results from other tools such as Nessus, Nmap, and so on

db_rebuild_cache

This command is used to rebuild the cache if the earlier cache gets corrupted or is stored with older results

Starting a new penetration test, it is always good to separate previously scanned hosts and their respective data from the new pentest so that it doesn't get merged. We can do this in Metasploit before starting a new penetration test by making use of the workspace command, as shown in the following screenshot:

To add a new workspace, we can issue the workspace -a command, followed by an identifier. We should keep identifiers as the name of the organization currently being evaluated, as shown in the following screenshot:

We can see that we have successfully created a new workspace using the -a switch. Let's switch the workspace by merely issuing the workspace command followed by the workspace name, as shown in the preceding screenshot. Having the workspace sorted, let's quickly perform a Nmap scan over the target IP and see if we can get some exciting services running on it:

The scan results are frankly heartbreaking. No services are running on the target except on port 80.

By default, Nmap scans the top 1000 ports only. We can use -p- switch to scan all the 65535 ports.

Since we are connected to the Metasploit database, everything we examine gets logged to the database. Issuing services commands will populate all the scanned services from the database. Also, let's perform a version detection scan through db_nmap using the -sV switch, as shown in the following screenshot:

The previous Nmap scan found port 80 and logged it in the database. However, the version detection scan found the service running on port 80 which is Apache 2.4.7 Web Server, found the MAC address, the OS type, and updated the entry in the database, as shown in the preceding screenshot. Since gaining access requires explicitly the exact exploit targeting a particular version of the software, it's always good to perform a double check on the version information. Metasploit contains an inbuilt auxiliary module for HTTP version fingerprinting. Let's make use of it, as shown in the following screenshot:

To launch the http_version scanner module, we issue the use command followed by the path of the module, which in our case is auxiliary/scanner/http/http_version. All scanning-based modules have the RHOSTS option to incorporate a broad set of IP addresses and subnets. However, since we are only testing a single IP target, we specify RHOSTS to the target IP address, which is 192.168.174.132 by using the set command. Next, we just make the module execute using the run command, as shown in the following screenshot:

This version of Apache is precisely the version we found in the previous Nmap scan. This version of Apache web server running on the target is secure, and none of the public exploits are present at exploit databases such as exploit-db.com and 0day.today. Hence, we are left with no other option than looking for vulnerabilities in the web application, if there are any. Let's try browsing this IP address and see if we can find something:

Well! We have an index page, but there is no content. Let's try to look for some known directories by making use of the dir_scanner module from Metasploit, as we can see following screenshot:

After loading the auxiliary/scanner/http/dir_scanner module, let's provide it with a dictionary file containing a list of known directories by setting the path in the DICTIONARY parameter. Also, we can speed up the process by increasing the number of threads by setting the THREADS parameter to 20 from 1. Let's run the module and analyze the output:

The space character between the individual directory entries has yielded a lot of false positives. However, we got 302 response code from a phpcollab directory, which indicated that while trying to access phpcollab directory, the module got a response to redirect (302). The response is interesting; let's see what we get when we try to open the phpcollab directory from the browser:

Nice! We have a PHP-based application running. Hence, we got a 302 response in the Metasploit module.

Modeling threats

From the intelligence gathering phase, we can see that only port 80 is open on the target system and the application running on it isn't vulnerable and is running the PhpCollab Web application on it. To gain access to the PhpCollab portal, trying some random passwords and username yields no success. Even searching Metasploit, we don't have modules for PhpCollab:

Let's try searching PhpCollab using the searchsploit tool from https://exploit-db.com/. The searchsploit allows you to easily search from all the exploits currently hosted on exploit database website as it maintains an offline copy of all the exploits:

Voila! We have an exploit for PhpCollab, and the good news is that it's already in the Metasploit exploit format.

Vulnerability analysis - arbitrary file upload (unauthenticated)

The PhpCollab application does not filter the content of the uploaded files correctly. Hence, it is possible for an unauthenticated attacker to upload a malicious file and run arbitrary code.

Attacking mechanism on the PhpCollab 2.5.1 application

The application can get compromised if an attacker uploads a malicious PHP file by sending a POST request on the /clients/editclient.php?id=1&action=update URL. The code does not validate the request if it's originating from an authenticated user or not. The problematic code is as follows:

From line number 2, we can see that the uploaded file is saved to the logos_clients directory with the name as $id followed by the $extention, which means that since we have id=1 in the URL, the uploaded backdoor will be saved as 1.php in the logos_clients directory.

Exploitation and gaining access

To gain access to the target, we need to copy this exploit into Metasploit. However, copying external exploits directly to Metasploit's exploit directory is highly discouraged and bad practice since you will lose the modules on every update. It's better to keep external modules in a generalized directory rather than Metasploit's modules directory. However, the best possible way to keep the modules is to create a similar directory structure elsewhere on the system and load it using the loadpath command. Let's copy the found module to some directory:

Let's create the directory structure, as shown in the following screenshot:

We can see that we created a Metasploit-friendly structure in the MyModules folder which is modules/exploits/nipun, and moved the exploit into the directory as well. Let's load this structure into Metasploit as follows:

We have successfully loaded the exploit into Metasploit. Let's use the module, as shown in the following screenshot:

The module requires us to set the address of the remote host, remote port, and the path to the PhpCollab application. Since the path (TARGETURI) and the remote port (RPORT) are already set, let's set RHOST to the IP address of the target and issue the exploit command:

Voila! We got access to the system. Let's make use of some of the basic post-exploitation commands and analyze the output, as shown in the following screenshot:

As we can see in the preceding screenshot, running the sysinfo command harvests the system's information such as computer name, OS, architecture, which is the 64-bit version, and the Meterpreter version, which is a PHP-based Meterpreter. Let's drop into a system shell on the compromised host using the shell command, as shown in the following screenshot:

We can see that as soon as we dropped into a system shell, running commands such as id provides us with the input that our current user is using, www-data which means that to gain complete control of this system, we require root privileges. Additionally, issuing the lsb_release -a command outputs the OS version with the exact release and codename. Let's take a note of it as it would be required in gaining root access to the system. However, before we move on to the rooting part, let's gain some of the basic information from the system, such as the current process ID using the getpid command, the current user ID using the getuid command, the uuid for the unique user identifier, and the machine_id, which is the identifier to the compromised machine. Let's run all of the commands we just discussed and analyze the output:

The amount of information we got is pretty straightforward. We have the ID of the current process our Meterpreter is sitting in, we have the user ID, UUID, and the machine ID. However, an important thing to take note of here is that our access is PHP Meterpreter-based and the limitation of the PHP Meterpreter is that we can't run privileged commands which can easily be provided by more concrete binary Meterpreter shells such as reverse TCP. First, let's escalate us onto a more concrete shell to gain a better level of access to the target. We will make use of the msfvenom command to create a malicious payload; we will then upload it to the target system and execute it. Let's get started:

Since our compromised host is running on a 64-bit architecture, we will use the 64-bit version of the Meterpreter, as shown in the preceding screenshot. MSFvenom generates robust payloads based on our requirements. We have specified the payload using the -p switch, and it is none other than linux/x64/meterpreter/reverse_tcp. This payload is the 64-bit Linux compatible Meterpreter payload which, once executed on the compromised system, will connect back to our listener and will provide us with access to the machine. Since the payload has to connect back to us, it should know where to connect to. We specify the LHOST and LPORT options for this very reason, where LHOST serves as our IP address where our listener is running, and LPORT specifies the port for the listener. We are going to use the payload on a Linux machine. Therefore, we specify the format (-f) to be elf, which is the default executable binary format for Linux-based operating systems. The -b option is used to specify the bad characters which may encounter problems in the communication and may break the shellcode. More information on bad characters and their evasion will follow in the upcoming chapters. Finally, we write the payload to the reverse_connect.elf file.

Next, since we already have a PHP Meterpreter access on the machine, let's upload the newly created payload using the upload command, which is followed by the path of the payload, as shown in the preceding screenshot. We can verify the current path of the upload by issuing the pwd command, which signifies the current directory we are working with. The uploaded payload, once executed, will connect back to our system. However, we need something on the receiving end as well to handle the connections. Let's run a handler which will handle the incoming connections, as shown in the following screenshot:

We can see that we pushed our PHP Meterpreter session to the background using the background command. Let's use the exploit/multi/handler module and set the same payload, LHOST, and LPORT we used in reverse_connect.elf and run the module using the exploit command.

Exploiting the -j command starts the handler in background mode as a job and can handle multiple connections, all in the background.

We have successfully set up the handler. Next, we just need to execute the payload file on the target, as shown in the following screenshot:

We can see that we just dropped in a shell using the shell command. We checked the current working directory on the target using the pwd command. Next, we gave executable permissions to the payload file so we can execute it and finally, we ran the reverse_connect.elf executable in the background using the & identifier. The preceding screenshot shows that as soon as we run the executable, a new Meterpreter session gets opened to the target system. Using the sessions -i command, we can see that we now have two Meterpreters on the target:

However, x64/Linux Meterpreter is apparently a better choice over the PHP Meterpreter, and we will continue interacting with the system through this Meterpreter unless we gain a more privileged Meterpreter. However, if anything goes unplanned, we can switch access to the PHP Meterpreter and re-run this payload like we just did. An important point here is that no matter if we have got a better level of access type on the target, we are still a low privileged users, and we would like to change that. The Metasploit framework incorporates an excellent module called local_exploit_suggester, which aids privilege escalation. It has a built-in mechanism to check various kinds of local privilege escalation exploits and will suggest the best one to use on the target. We can load this module, as shown in the following screenshot:

We loaded the module using the use command followed by the absolute path of the module, which is post/multi/recon/local_exploit_suggester. Since we want to use this exploit on the target, we will naturally choose the better Meterpreter to route our checks. Hence, we set SESSION to 2 to route our check through SESSION 2, which is the identifier for x64/Linux Meterpreter. Let's run the module and analyze the output:

Simply amazing! We can see that the suggester module states that the overlayfs_priv_esc local exploit module from the exploit/linux directory can be used on the target to gain root access. However, I leave it as an exercise for you all to complete. Let's do it manually by downloading the local root exploit on the target, compiling and executing it to get root access on the target system. We can download the exploit from: https://www.exploit-db.com/exploits/37292. However, let's gather some of the details about this exploit in the next section.

Escalating privileges with local root exploits

The overlayfs privilege escalation vulnerability allow local users to gain root privileges by leveraging a configuration in which overlayfs is permitted in an arbitrary mounted namespace. The weakness lies because the implementation of overlayfs does not correctly check the permissions for file creation in the upper filesystem directory.

More on the vulnerability can be found here: https://www.cvedetails.com/cve/cve-2015-1328.

Let's drop into a shell and download the raw exploit onto the target from https://www.exploit-db.com/:

Let's rename the exploit from 37292 to 37292.c and compile it with gcc, which will generate an executable, as shown in the following screenshot:

We can see that we have successfully compiled the exploit, so let's run it:

Bingo! As we can see, by running the exploit, we have gained access to the root shell; this marks the total compromise of this system. Let's run some of the basic commands and confirm our identity as follows:

Remember, we have an exploit handler running in the background? Let's run the same reverse_connect.elf file:

Another Meterpreter session opened! Let's see how this Meterpreter is different from the other two:

We can see that we have the third Meterpreter from the target system. However, the UID, that is, the user ID, is 0, which denotes the root user. Hence, this Meterpreter is running with root privileges and can provide us unrestricted entry to the entire system. Let's interact with the session using the session -i command followed by the session identifier, which is 3 in this case:

We can confirm the root identity through the getuid command, as shown in the preceding screenshot. We now have the complete authority of the system, so what's next?

Maintaining access with Metasploit

Keeping access to the target system is a desired feature, especially when it comes to law enforcement agencies or by the red teams to test defenses deployed on the target. We can achieve persistence through Metasploit on a Linux server using the sshkey_persistence module from the post/linux/manage directory. This module adds our SSH key or creates a new one and adds it to all the users who exist on the target server. Therefore, the next time we want to login to the server, it will never ask us for a password and will simply allow us inside with the key. Let's see how we can achieve this:

We just need to set the session identifier using the set SESSION command followed by the session identifier. We will make use of the session with the highest level of privileges. Hence, we will use 3 as the SESSION identifier and directly run the module as follows:

We can see that the module created a new SSH key and then added it to two users on the target system, that is, root and claire. We can verify our backdoor access by connecting to the target on SSH with either root or the user claire, or both, as follows:

Amazing! We can see that we logged into the target system by making use of the newly created SSH key using the -i option, as shown in the preceding screen. Let's see if we can also log in as the user claire:

Yup! We can log in with both of the backdoored users.

Most of the servers do not permit root login. Hence, you can edit the sshd config file and change the root login to yes and restart the SSH service on the target.

Try to backdoor only a single user such as the root since, most of the folks won't log in through the root as default configurations prohibit it.

Post-exploitation and pivoting

No matter what operating system we have compromised, Metasploit offers a dozen of post-exploitation reconnaissance modules which harvest gigs of data from the compromised machine. Let's make use of one such module:

Running the enum_configs post-exploitation module, we can see that we have gathered all the configuration files which existed on the target. These configs help uncover passwords, password patterns, information about the services running, and much much more. Another great module is enum_system, which harvests information such as OS-related information, user accounts, services running, cron jobs running, disk information, log files, and much more, as shown in the following screenshot:

Having gathered an enormous amount of detail on the target, is it a good time to start reporting? Not yet. A good penetration tester gains access to the system, obtains the highest level of access, and presents his analysis. However, a great penetration tester does the same but never stops on a single system. They will try with the best of his abilities to dive into the internal network and gain more access to the network (if allowed). Let's use some of the commands which will aid us in pivoting to the internal network. One such example command is arp, which lists down all the contracted systems in the internal network:

We can see the presence of a separate network, which is in the 192.168.116.0 range. Let's issue the ifconfig command and see if there is another network adapter attached to the compromised host:

Yup! We got it right-there is another network adapter (Interface 3) which is connected to a separate network range. However, when we try to ping or scan this network from our address range, we are not able to because the network is unreachable from our IP address, which means we need a mechanism that can forward data from our system to the target (otherwise inaccessible) range through the compromised host itself. We call this arrangement pivoting. Therefore, we will add a route to the target range through our gained Meterpreter on the system, and the target systems in the range will see our compromised host as the source originator. Let's add a route to the otherwise unreachable range through Meterpreter, as shown in the following screenshot:

Using the autoroute post-exploitation module from post/multi/manage directory, we need to specify the target range in the SUBNET parameter and SESSION to the session identifier of the Meterpreter through which data would be tunneled. We can see that by running the module, we have successfully added a route to the target range. Let's run the TCP port scanner module from Metasploit and analyze whether we can scan hosts in the target range or not:

We simply run the portscanner module on the target we found using the arp command, that is, 192.168.116.133 with ten threads for ports 1-10000, as shown in preceding screenshot:

Success! We can see that port 80 is open. However, our access is limited through Meterpreter only. We need a mechanism where we can run some of our external tools for browsing port 80 through a web browser to understand more about the target application running on port 80. Metasploit offers an inbuilt socks proxy module which we can run and route traffic from our external applications to the target 192.168.116.133 system. Let's use this module as follows:

We simply need to run the socks4a module residing at the auxiliary/server path. It will set up a gateway on the local port, 1080, to route the traffic to the target system. Proxying on 127.0.0.1:1080 will forward our browser traffic through the compromised host. However, for external tools, we will need to use proxychains and configure it by setting the port to 1080. The port for proxychains can be configured using the /etc/proxychains.conf file:

The next thing is to only set this address as a proxy in the browser or use proxychains as the prefix on all the third-party command-line applications such as Nmap and Metasploit. We can configure the browser, as shown in the following screenshot:

Make sure to remove localhost and 127.0.0.1 from the No Proxy for section. After setting the proxy, we can just browse to the IP address on port 80 and check whether we can reach port 80:

Nice! We can see the application, which says it's a Disk Pulse Enterprise, Software v9.9.16, which is a known vulnerable version. We have plenty of modules for Disk Pulse in Metasploit. Let's make use of one of them, as follows:

Yup! I am one of the original authors of this exploit module. Let's understand the vulnerability before exploiting it.

Vulnerability analysis - SEH based buffer overflow

The vulnerability lies in parsing the GET request by the web server component of Disk Pulse 9.9.16. An attacker can craft malicious GET requests and cause the SEH frame to overwrite, which will cause the attacker to gain complete access to the program's flow. The attacker will gain full access to the system with the highest level of privileges since Disk Pulse runs with Administrator rights.

Let's make use of the vulnerability and exploit the system as follows:

Merely setting the RHOST and the LPORT (Gateway port which will allow us access to the successful exploitation of the target), we are ready to exploit the system. We can see that as soon as we run the exploit, we have Meterpreter session 5 opened, which marks a successful compromise of the target. We can verify our list of sessions using the sessions -i command as follows:

Let's interact with session 5 and check the level of access we have:

Issuing the getuid command, we can see that we already have NT AUTHORITY SYSTEM, the highest level of privilege on the Windows OS.

For more information on the vulnerability, refer to: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-13696.

Exploiting human errors by compromising Password Managers

Having the highest level of privileges, let's perform some post-exploitation as follows:

It is always great to look for the various kinds of applications installed on the target system, since some of the apps may have saved credentials to other parts of the network. Enumerating the list of installed applications, we can see that we have WinSCP 5.7, which is a popular SSH and SFTP client. Metasploit can harvest saved credentials from WinSCP software. Let's run the post/windows/gather/credentials/winscp module and check whether we have some of the saved credentials in the WinSCP software:

Amazing! We have a rescued credential for another host in the network, which is 192.168.116.134. The good news is the saved credentials are for the root account, so if we gain access to this system, it will be with the highest level of privilege. Let's use the found credentials in the ssh_login module as follows:

Since we already know the username and password, let's set these options for the module along with the target IP address, as shown in the following screenshot:

Bingo! It's a successful login, and Metasploit has gained a system shell on it automatically. However, we can always escalate to the better quality of access using Meterpreter shells. Let's create another backdoor with msfvenom as follows:

The backdoor will listen for connections on port 1337. However, how do we transfer this backdoor to the compromised host? Remember, we ran the socks proxy auxiliary module and made changes to the configuration? Using the proxychains keyword as a suffix for most of the tools will force the tool to use the route through proxychains. So, to transfer such a file, we can make use of scp as shown in the following screenshot:

We can see that we have successfully transferred the file. Running the matching handler, similarly to what we did for the first system, we will have the connection from the target. Let's have an overview of all the targets and sessions we gained in this exercise as follows:

Throughout this practice real-world example, we compromised three systems and gained the highest possible privileges off them through local exploits, human errors, and exploiting software that runs with the highest possible privileges.

You have been reading a chapter from
Mastering Metasploit - Third Edition
Published in: May 2018
Publisher: Packt
ISBN-13: 9781788990615
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image