Mastering Metasploit
上QQ阅读APP看书,第一时间看更新

Conducting a penetration test with Metasploit

After setting up the work environment, we are now ready to perform our first penetration test with Metasploit. However, before we start with the test, let's recall some of the basic functions and terminologies used in the Metasploit framework.

Recalling the basics of Metasploit

After we run Metasploit, we can list down all the workable commands available in the framework by typing help in Metasploit console. Let's recall the basic terms used in Metasploit, which are as follows:

  • Exploits: This is a piece of code, which when executed, will trigger the vulnerability at the target.
  • Payload: This is a piece of code that runs at the target after a successful exploitation is done. Basically, it defines the type of access and actions we need to gain on the target system.
  • Auxiliary: These are modules that provide additional functionalities such as scanning, fuzzing, sniffing, and much more.
  • Encoders: Encoders are used to obfuscate modules to avoid detection by a protection mechanism such as an antivirus or a firewall.

Let's now recall some of the basic commands of Metasploit and see what they are supposed to do as shown in the following table:

Note

If you are using Metasploit for the very first time, refer to http://www.offensive-security.com/metasploit-unleashed/Msfconsole_Commands for more information on basic commands.

Penetration testing Windows XP

Recalling the basics of Metasploit, we are all set to perform our first penetration test with Metasploit. We will test an IP address here and try to find relevant information about the target IP. We will follow all the required phases of a penetration test here, which we discussed in the earlier part of this chapter.

Assumptions

Considering a black box penetration test on a Windows XP system, we can assume that we are done with the preinteraction phase. We are going to test a single IP address in the scope of the test, with no prior knowledge of the technologies running on the target. We are performing the test with Kali Linux, a popular security-based Linux distribution, which comes with tons of preinstalled security tools.

Gathering intelligence

As discussed earlier, the gathering intelligence phase revolves around gathering as much information as possible about the target. Active and passive scans that include port scanning, banner grabbing, and various other scans depends upon the type of target that is under test. The target under the current scenario is a single IP address, located in a local network. So here, we can skip passive information gathering and can continue with the active information-gathering methodology.

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

To conduct internal FootPrinting, NMAP proves as one of the finest available tool. Let's perform a simple ping scan with NMAP on the target to check whether the target is online or not, as shown in the following screenshot:

Gathering intelligence

The usage of the -sP switch in NMAP followed by the IP address of the target will direct NMAP to perform a ping scan over the target. NMAP not only tells us whether the system is alive or not, but it also displays the MAC address of the target by sending an ARP request. However, if the target blocks ICMP packets, NMAP ping scan automatically switches the approach by changing from ICMP to TCP-based packets.

In addition, if you are running the NMAP scan from the user account you can ensure that the access is switched to the root by typing the sudo –s command.

Once you're done with the ping scan, it is very clear that the target in scope is online.

The next step is to find out information regarding the operating system and open ports. Port scanning is the method of finding open ports and identifying running services on ports that are found. NMAP offers a variety of scan methods used to identify open ports. Using the -O switch will direct NMAP to perform operating system detection, device type identification, network distance, open ports, and services running on them. This NMAP scan is famous by the name of operating system detection type scan. Let's see how we can perform this type of scan on the target:

Gathering intelligence

The output of the scan lists various services found on the open ports as well as the OS details of the target. Therefore, at this point, we know that the target is up. Ports 80, 135, 139, 443, 445, and 3306 are open. The target is running on Windows XP Professional SP2 or Windows Server 2003. However, it may happen that the OS details are not correct every time. So, to confirm this, use other operating system fingerprinting tools such as Xprobe2, p0f, and so on.

Note

Refer to http://nmap.org/bennieston-tutorial/ for more information on NMAP scans.

Refer to http://null-byte.wonderhowto.com/how-to/hack-like-pro-conduct-os-fingerprinting-with-xprobe2-0148439/ for operating system detection scans with Xprobe2.

Refer to an excellent book on NMAP at http://www.packtpub.com/network-mapper-6-exploration-and-security-auditing-cookbook/book.

Tip

For better service detection, we can use the –sV switch in NMAP. Additionally, we can also use the –o switch to save the output and export the result to a different tool such as Nessus and so on. We will also look at how to export functions in the latter chapters.

Modeling threats

From the preceding phase, we know that the operating system is either Windows XP Professional SP2 or the Windows 2003 server. Explore the vulnerabilities on Windows XP systems or Windows 2003 servers via http://www.cvedetails.com/product/739/Microsoft-Windows-Xp.html and http://www.cvedetails.com/product/2594/Microsoft-Windows-2003-Server.html?vendor_id=26 respectively, and match the vulnerabilities with the ports that are found. It can be concluded that majority of these groups of operating systems are vulnerable to attack on port 445. Due to the NETAPI vulnerability on port 445, this can lead to a complete system compromise. However, a vulnerability check on third-party software such as Apache and MySQL must be part of the checklist as well.

Categorizing this vulnerability as high risk, all the other found threats need to be in the list according to the factors of their impact.

At this point of the test, we know that from the list of open ports, port number 445 is vulnerable to a high-risk attack on Windows XP professional or Windows 2003.

Tip

Refer to http://www.cvedetails.com/product-list/product_type-o/vendor_id-26/firstchar-/Operating-Systems.html for more information on various vulnerabilities in Windows-based operating systems.

Vulnerability analysis

Modeling out threats, let's consider the NETAPI vulnerability and discuss some of its details. However, the details of the vulnerability are available at http://www.cvedetails.com/cve/CVE-2008-4250/, which includes information on how operating systems are affected, links to hot fixes, and so on. Rapid7 also documents this vulnerability and its related exploit at http://www.rapid7.com/db/modules/exploit/windows/smb/ms08_067_netapi.

The attack procedure with respect to the NETAPI vulnerability

The users of Metasploit are only concerned with exploitation; however, we will still discuss the inside story behind the attack on this vulnerability. We must know what we are doing and how we are doing it. This will help us strengthen our exploitation skills.

The concept of attack

The concept of this attack is the absence of Address Space Layout Randomization (ASLR) usage in the previous and older versions of Windows operating systems. ASLR is responsible for loading a program dynamically into the memory, which means at a different place every time. Operating systems such as Windows XP SP1, XP SP2, 2003 Server, and so on, do not use ASLR. So the nonusage of ASLR makes Data Execution Prevention (DEP) vulnerable to an attack. The canonicalization flaw in the NETAPI32.dll file in Windows allows the attacker to bypass the DEP protection and overwrite the return addresses and various registers.

The procedure of exploiting a vulnerability

The exploit code in this attack makes a connection with the target first. Further, it creates a Server Message Block (SMB) login connection at the lower transport layer. Now, the specially crafted Remote Procedure Call (RPC) request overwrites the return addresses on the stack and sets the attacker's desired address to it. ShellCode is placed after the overwriting of the return address; after this is done, the program counter is adjusted in such a way that it points to the ShellCode. After the execution of ShellCode, the attacker gets back to the session. Some of the terms might look scary here, but things will get clearer as we move ahead.

Therefore, at this point, we have enough knowledge about the vulnerability, and we can go further with the exploitation of the vulnerability.

Exploitation and post-exploitation

Let's see how we can actually exploit the target that has a modelled-out threat with Metasploit. Let's launch the Metasploit console interface and search for the ms08_067_netapi exploit by typing the following command:

msf>search netapi

While executing the preceding command, we will see so many different versions of the exploit. However, we will start our approach with the ms08 version of the exploit. We selected this version of the exploit because we have the corresponding CVE details from the year 2008. Therefore, we proceed by selecting the ms08_067_netapi exploit using the use command as follows:

msf>use exploit/Windows /smb/ms08_067_netapi

To launch this exploit, we need to set the required options. Let's see what these options are and what they are supposed to do, as shown in the following table:

Let's now run the exploit against the target:

Exploitation and post-exploitation

Note

We are skipping the process of setting the values that are active by default. To check which default values are active, type the show options or show advanced command.

By setting up all the required parameters as shown in the preceding screenshot, we choose to exploit the system and gain access to the target by issuing the exploit command.

We can see the prompt changing to meterpreter. This denotes a successful payload execution and marks the exploit's success.

Let's use some of the post-exploitation features of Metasploit. Let's begin by collecting the basic information about the target by issuing the sysinfo command, as shown in the following screenshot:

Exploitation and post-exploitation

Next, we issue getuid and getpid to find out the current privileges' level and the current process we have broken into.

Consider a scenario where the user of a target machine terminates the process. In this case, the access will be lost, and we will need to relaunch the entire attack. To overcome this issue, we can migrate from this process into a more reliable process with the help of the migrate command. A more reliable process can be the main process in Windows, which is explorer.exe. However, to migrate, we need to have the process ID of the explorer.exe process. We can find out the process ID for explorer.exe with the ps command. By finding out the process ID of the process in which we wish to jump into, we can issue the migrate command followed by the process ID of the process, as shown in the following screenshot:

Exploitation and post-exploitation

We can verify the migration process by issuing the getpid command again. Moreover, we can see that meterpreter shows us the current process ID of the explorer.exe process. This denotes successful migration of the shell into the explorer.exe process. However, as soon as we try issuing the getuid command, it shows that we only have user-level access. This is because we migrated into a user-initiated process, explorer.exe. However, we can gain system-level access back again by issuing the getsystem command.

Now, let's perform some of the basic post-exploitation functions such as removing a directory with the rmdir command, changing a directory with the cd command, listing the contents of a directory with the ls command, and downloading a file with the download command, as shown in the following screenshot:

Exploitation and post-exploitation

If you closely look at the preceding screenshot, you'll realize that we removed a directory named Confidential-Client with the rmdir command. Then, we downloaded a file present in the Market-Data directory named data.txt with the download command.

Maintaining access

Maintaining access is crucial because we might need to interact with the hacked system repeatedly. So, in order to achieve this, we can add a new user to the hacked system, or we can use the persistence module from Metasploit. Running the persistence module will make the access to the target system permanent by installing a permanent backdoor to it. Therefore, if in any case the vulnerability patches, we can still maintain the access on that target system, as shown in the following screenshot:

Maintaining access

Running the persistence module will upload and execute a malicious .vbs script on the target. The execution of this malicious script will cause a connection attempt to be made to the attacker's system with a gap of every few seconds. This process will also be installed as a service and is added to the start up programs list. So, no matter how many times the target system boots, the service will be installed permanently. Hence, its effect remains unless the service is uninstalled or removed manually.

In order to connect to this malicious service at the target and regain access, we need to set up a multi/handler. A multi/handler is a universal exploit handler used to handle incoming connections initiated by the executed payloads at the target machine. To use an exploit handler, we need to issue commands as shown in the following screenshot, from the Metasploit framework's console:

Maintaining access

A key point here is that we need to set the same payload and the LPORT option, which we used while running the persistence module.

After issuing the exploit command, the multi/handler starts to wait for the connection to be made from the target system. As soon as an incoming connection gets detected, we are presented with the meterpreter shell.

Clearing tracks

After a successful breach into the target system, it is advisable to clear every track of our presence. In order to achieve this, we need to clear the event logs. We can clear them with the event manager module as follows:

Clearing tracks

Note

We can also remove event logs by issuing the clearev command from the meterpreter shell.

At this point, we end up with the penetration testing process for the Windows XP environment and can continue with the report generation process. In the preceding test, we focused on a single vulnerability only, just for the sake of learning. However, we must test all the vulnerabilities to verify all the potential vulnerabilities in the target system.

Penetration testing Windows Server 2003

Windows Server 2003 can be tested in exactly the same way as we did for Windows XP. This is because both the operating systems fall under the same kernel code set. However, make sure that repeated attempts to exploit a Windows Server 2003 could cause the server to crash. Therefore, both the Windows XP and Windows Server 2003 are found vulnerable to the NETAPI-based vulnerability. However, the vulnerabilities in IIS and old instances of MSSQL can be additionally tested within the scope of the test.

Let's try out the same exploit for Windows Server 2003 as follows:

Penetration testing Windows Server 2003

We can see the exploit working like a charm in Windows Server 2003 as well, as shown in the following screenshot:

Penetration testing Windows Server 2003

Additionally, we can use the client-based exploitation approach here as well. We will study about client-based exploitation in the latter chapters. However, I leave Windows Server 2003 as an exercise for you.

Let's move further and test a much more advanced operating system in terms of security policies.

Penetration testing Windows 7

Exploiting a Windows 7 system is much more difficult than the previously discussed operating systems. This is due to the complex architecture of windows 7, the implementation of much greater security policies such as usage of ASLR, and much more advanced firewalls.

So, how can we attack Windows 7 systems? The answer to this question is by exploiting third-party applications in use or the client-based exploitation.

Gathering intelligence

Let's start by port scanning the target system. This time, however, let's perform a stealth scan by defining the –sS switch. Half-open scan/ Syn scan is another name given to the stealth scan because it only completes two of the three phases of a TCP's three-way handshake. Therefore, it creates less noise on the network. Let's also provide a few commonly found open ports with the –p switch. However, using this switch will instruct NMAP to only test these ports and skip every other port as shown in the following screenshot:

Gathering intelligence

After scanning the target at ports 21, 22, 25, 80, 110, and 445, we can only see port 80 and port 445 open.

At this point, we know that the target is up and running. We also know that port 80 and port 445 are open. Repeating the OS fingerprinting process from the previous scan on the windows XP system, we can conclude that the IP address is running Windows 7. I skip this step for you to encourage self-exploration.

We will use another type of scan here to identify services. This scan is known as service detection scan and is denoted by the –sV switch. We already know that port 445, by default, runs the microsoft-ds service, so we skip checking it. Therefore, the only port under exploration is port 80. We instruct NMAP in the preceding command to perform a service detection scan only on port 80 by specifying it using the –p switch.

Let's move further and figure out which service is running on port 80 along with its version, as shown in the following screenshot:

Gathering intelligence

Modeling threats

From the gathering intelligence phase, we know that port 80 and port 445 are open at the target premises. Additionally, we also know that port 80 is running PMSoftware Simple Web Server 2.2 and port 445 is running the Microsoft-ds service. Exploring the CVE details about the service running on port 445, we can easily figure out that Windows 7 operating system is free from the bug that was the most common bug in Windows XP/2003 operating systems. At this point of the test, we only have port 80 to attack. So, let's gather details about this vulnerability via http://www.osvdb.org/84310. Exploring the vulnerability details, we can see that a public exploit is available for this version of the HTTP server.

Note

Details about the exploit can be found at http://www.rapid7.com/db/modules/exploit/windows/http/sws_connection_bof.

Vulnerability analysis

A simple web server connection buffer overflow vulnerability can allow an attacker to send a malicious HTTP request in the HTTP Connection parameter to trigger a buffer overflow in the application and gain access to the system.

The exploitation procedure

A vulnerability is triggered when we send an HTTP/GET/1.1 request along with other parameters such as Connection and Host. We supply the target IP as host. However, when it comes to the Connection parameter, we supply enough junk data to possibly crash the buffer and fill up the remaining registers with our custom values. These custom values will overwrite Extended instruction pointer (EIP) and other registers that will cause a redirection in the program. Therefore, it will redirect the execution of the program and present us with the entire control of the system. The overflow actually occurs when this malicious request is tried to be printed by the software using the vsprintf() function, but instead, ends up filling the buffer and space beyond the limits of the buffer. This overwrites the values of EIP that holds the address of the next instruction and other registers with values supplied in the request itself.

Taking a step further, let's exploit the target system using the vulnerability.

Exploitation and post-exploitation

After launching the Metasploit framework, we issue the use command followed by the path of the exploit to start working with the exploit. We move further by exploiting the target after setting all the required options and the payload, as shown in the following screenshot:

Exploitation and post-exploitation

Bingo! We made it. We successfully exploited a Windows 7 system with a third-party application. Let's verify the target system by issuing the sysinfo command from meterpreter in order to verify the details of Windows 7.

Furthermore, we can elevate privileges, gain system-level access, run backdoors, and download/upload files to the exploited system easily. I leave these post-exploitation features as an exercise for you to complete.

Using the database to store and fetch results

It is always a better approach to store the results when you perform penetration testing. This will help us build a knowledge base about hosts, services, and the vulnerabilities in the scope of a penetration test. In order to achieve this functionality, we can use databases in Metasploit.

The latest version of Metasploit favors PostgreSQL as the default database. However, some users face many problems with it. The most common problem is the database not connected error. In order to address this issue, open a terminal and issue the following commands:

#services postgresql start
#services metasploit start

Now, restart Metasploit, and you will see that the error no longer exists.

After solving database issues, let's take one step further and start with database operations. To find out the status of the databases, open the Metasploit framework's console and type the following command:

msf>db_status

The preceding command will check whether the database is connected and is ready to store the scan results or not, as shown in the following screenshot:

Using the database to store and fetch results

Next, if we want to connect to a database other than the default one, we can change the database using the following command:

db_connect

However, typing only the preceding command will display its usage methods as we can see in the following screenshot:

Using the database to store and fetch results

In order 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 explore what various other commands that we have in Metasploit do for databases, as shown in the following screenshot:

Using the database to store and fetch results

We have seven different commands for database operations. Let's see what they are supposed to do. The following table will help us understand these database commands:

After gaining a basic knowledge of database commands, let's move further and perform an NMAP scan through a database extension in Metasploit. This scan will automatically add all the details that are found to various sections of Metasploit.

Let's run a service detection scan by using the –sV switch as follows:

Using the database to store and fetch results

Once you're done with the NMAP scan, we can clearly see the output on the screen. However, the question that arises here is whether the scan results are stored in the database.

Let's verify the hosts present in the database using the hosts command. This command will show the entire list of scanned hosts with relevant information associated with them such as the MAC address, OS information, and other details, as shown in the following screenshot:

Using the database to store and fetch results

In addition, we can see what services are available on these hosts by issuing the services command:

Using the database to store and fetch results

We can clearly see the list of all the services that are found on hosts present in the database.

The idea of using databases helps us store the scan details, which results in better vulnerability management.

Generating reports

Metasploit's pro edition provides great options to generate reports on a professional basis. However, when it comes to the Metasploit community edition, we can use databases efficiently to generate a report in the XML format. This can be simply achieved using the db_export function.

We can simply create an XML report by issuing the following command:

msf> db_export –f xml /home/apex/report.xml

The -f switch here defines the format of the report. The report in the XML format can be imported into many popular vulnerability scanners such as Nessus, and so on, which will help us in finding out more about the target host.