Performing port scans

Now that you’ve a list of targets, we can continue our examination by scanning the ports on each of the IP addresses we found. Recall that the goal of port scanning is to identify which ports are open and determine what services are available on our target system. A service is a specific job or task that the computer performs like e-mail, FTP, printing or providing webpages. Port scanning is like knocking on the various doors and windows of a house and seeing who answers. For example, if we find that port 80 is open, we can attempt a connection to the port and oftentimes get specific information about the webserver that is listening on that port.

There are a total of 65536 (0-65535) ports on every computer. Ports can be either TCP or UDP depending on the service utilizing the port or nature of the communication occurring on the port. We scan computers to see what ports are in use or open. This gives us a better picture of the purpose of the machine, which, in turn, gives us a better idea about how to attack the box.

If you had to choose only one tool to conduct port scanning, you’d undoubtedly choose Nmap. Nmap was written by Gordon “Fyodor” Lyon and is available for free and is built into many of today’s Linux distributions including BlackArch. Although it’s possible to run Nmap from a graphical user interface (GUI), we’re going to focus on using the terminal to run our port scans. People who are new to security and hacking often ask why they should learn to use the command line or terminal version of a tool rather than relying on a GUI. These same people complain that using the terminal is not at easy. The response is very simple. First, using the command-line version of a tool will allow you to learn the parameters and options that change the behaviour of your tool. This gives you more flexibility, more granular control and a better understanding of the tool you’re running. Second (and maybe more importantly), rarely does hacking work like it’s portrayed in the movies. Finally, the command line can be scripted. Scripting and automation become key when you want to advance your skillset to the next level.

Remember the movie swordfish where Hugh Jackman is creating a virus? He’s dancing and drinking wine, and apparently building a virus in a very graphical, GUI-driven way. The point is that this is just not realistic. Most people who are new to hacking assume that hacking is a very GUI-oriented task: that once you take over a machine you’re presented with a desktop and control of the mouse and screen. Although it scenario is possible, it’s rarely the case. In most jobs, your main goal will be to get an administrative shell or backdoor access to the machine. This shell is literally a terminal that allows you to control the target PC from the command-line. It looks and feels just like the terminals we’ve been working with, except a remote shell allows you to enter the commands on your computer terminal and have them executed on the target machine. So learning the command line version of your tools is critical because once you’ve control of a machine you’ll need to upload your tools and interact with the target through a command prompt, not through a GUI.

Let us assume you still refuse to learn the command line. Let us also assume that with the several tools you were able to gain access to a target system. When you gain access to that system, you won’t be presented with a GUI but rather with a command prompt. If you don’t know how to copy files, add users, modify documents and make other changes through the command line, your work of owning the target will have been in vain. You’ll be stuck, like Moses who was able to see the promised land but not allowed to enter.

When we conduct a port scan, our tool will literally create a packet and send it to each designated port on the machine. The goal is to determine what kind of a response we get from the target port. Different types of port scans can produce different results. It’s important to understand the type of scan you’re running as well as the expected output of that scan.

TCP Scan

The first scan we’ll look at is called the TCP Connect Scan. This scan is considered the most basic and stable of all the port scans because Nmap attempts to complete the three-way handshake on each port specified in the Nmap command. Because this scan actually completes the three-way handshake and then tears down the connection gracefully, there’s a little chance that you’ll flood the target system and cause it to crash.

If you don’t specify a specific port range. Nmap will scan the 1000 most common ports. Unless you’re in a great hurry, it’s always recommended specifying all ports. The reason is that oftentimes crafty administrators will attempt to obscure a service by running it on a nonstandard port. You can scan all the ports by specifying “-p” when running Nmap. Using the “-Pn” switch with every Nmap scan is recommended. Utilizing the “-Pn” switch will cause Nmap to disable host discovery and force the tool to scan every system as if it were alive. This is extremely useful for discovering additional systems and ports that otherwise may be missed.

To run a TCP connect, we issue the following command from a terminal:

nmap -sT -p- -Pn 216.58.222.206

Take a moment to review this command. The first “nmap” cases the Nmap port scanner to start. The second command “-sT” tells Nmap to run a TCP Connect Scan. Specifically, to break this switch down even further, the “-s” is used to tell Nmap what kind of scan we want to run. The “-T” in the “-sT” is used to run a scan type of TCP Connect. We use the “-p-” to tell Nmap to scan all the ports not just the default 1000. We use the “-PN” switch to skip the host discovery phase and scan all the addresses as if the system were alive and responding to ping requests. Finally, we specify the target IP address; obviously, your target’s IP address will be different from the one shown in the previous example!.

Oftentimes, we need to run our scans against an entire subnet, or range of IP addresses. When this is the case, we can instruct Nmap to scan a continuous range of IPs by simply appending the last octet of the ending IP address onto the scan like so:

nmap -sT -p- -PN 192.168.1.1-254

Issuing this command will cause Nmap to port scan all the hosts between the IP addresses 192.168.1.1 and 192.168.1.254. Just like ping sweeps, this is a very powerful technique that can greatly improve the productivity of your scanning life!

If you need to scan a series of hosts that ain’t in sequential order, you can create a text file and list each host IP address on a single line. The add the “-iL path_to_the_text_file” switch to your Nmap command. Doing this allows you to scan all of your target hosts from a single command. Whenever possible, always try to create a single text file containing all of your target IPs. Most of the tools we discuss have a switch or mechanism for loading this text file, which saves the effort of retyping, but more importantly, reduces the number of times you’ll type each IP address and therefore reduces the change that you’ll fat-finger the IP address and scan the wrong target.

SYN Scan

The SYN Scan is arguably the most popular Nmap port scan. There are many reasons for its popularity, including that it happens to be the default Nmap scan. If you run the Nmap command without specifying a scan type (using the “-s” switch), Nmap will use the SYN scan by default.

Aside from the fact that the SYN scan is the default choice, it’s also popular because it’s faster than the TCP connect and yet remains quite safe, with little chance of DOS’ing or crashing the target system. SYN scans are faster because rather than completing the entire three-way handshake, it only completes the first two steps.

In a SYN scan, the scanning machine sends a SYN packet to the target and the target responds with a SYN/ACK (assuming the ports is in use and not filtered) just like it did when we ran a TCP Connect Scan. However, at this point, rather than sending the traditional ACK packet, the scanning machine sends an RST (reset) packet to the target. The reset packet tells the target machine to disregard any previous packets and close the connection between the two machines. It should be clear that the speed advantage of the SYN scan over the TCP Connect Scan comes from the fact that there are fewer packets sent between the hosts when using a SYN Scan rather than a TCP Connect Scan. Although a few packets may not sound like a bid advantage, it can add up quickly when scanning multiple hosts.

If we consider the example of comparing the three-way handshake to a phone call, SYN scans would be like calling someone up, having the receiver pick up the phone and saying “Hello?”, and then simply hanging up on the person without a single word.

Another advantage to the SYN scan is that in some instances, it provides a level of obscurity or stealth. Because of this feature, the SYN scan is often referred as the “Stealth Scan”. The stealth portion of this scan comes from the fact that because the three-way handshake is never fully completed, the official connection was never 100 per cent established. There are applications and log files that require the connection of the three-way handshake before they begin recording activity. As a result, if a log file only records completed connections and the SYN Scan never officially completes a single connection, this scan may be undetected by some applications. Please note, this is the exception and not the rule. All modern firewalls and intrusion detection systems in use today will detect and report a SYN scan!.

Because the SYN scan is the default Nmap Scan, we don’t technically need to specify the scan type with the “-s” switch. However, because this course focuses on the basics, it’s worth the effort to get into the habit of specifying your scan type.

To run a SYN Scan, you can open a terminal window and run the following command:

nmap -sS -p- -PN 192.168.1.7

This command is exactly the same as the previous example with one exception (rather than using an “-sT” we used an “-sS”). This instructs Nmap to run a SYN scan rather than a TCP Connect Scan. The Scan types are easy to remember because a TCP Connect Scan begins with the letter “T”, whereas the SYN Scan begins with the letter “S”. Each of the other switches was explained in the previous lesson. Please review the “Using Nmap to Complete a TCP Connect Scan” for a detailed breakdown of the switches in this command.

Take a moment to compare the total run time between the two scans (TCP and SYN). Even against a single host, the SYN scan completed its execution faster.

UDP Scan

One of the most common port scanning mistakes of new penetration testers is that they overlook UDP. These aspiring hackers oftentimes fire up Nmap, run a single scan (usually a SYN scan), and move onto vulnerability scanning. Don’t neglect to scan UDP ports! Failing to scan your target for open UDP ports is like reading the Cliff Notes version of a book. You’ll probably have a solid understanding of the story, but you’re likely to miss many of the details.

It’s important to understand that both TCP Connect Scans and SYN scans use TCP as the basis for their communication. TCP is an acronym for Transmission Control Protocol. UDP is an acronym for User Data gram Protocol. Computers can communicate with each other using either TCP or UDP; however, there are several key differences between the two protocols.

TCP is considered a “Connection oriented protocol” because it requires that the communication between both of the sender and the receiver stays in sync. This process ensures that the packets sent from one computer to another arrive at the receiver intact and in the order they were sent. On the other hand, UDP is said to be “connectionless” because the sender simply sends packets to the receiver with no mechanism for ensuring that the packets arrive at the destination. There are many advantages and disadvantages to each of the protocols including speed, reliability and error checking. To truly master port scanning, you’ll need to have solid understanding of these protocols. Take some time and learn about each of them.

Recall the earlier the three-way handshake process was described by comparing the process to a phone call. The three-way handshake is a key component of TCP communication that allows the sender and the receiver to stay in sync. Because UDP is connectionless, this type of communication is most often compared to dropping a letter in a mailbox. In most cases, the sender simply writes an address on an envelope, puts a stamp on the letter, and puts the letter in the mailbox. Eventually, the mailman comes along and picks up the letter where it’s entered into the mail routing system. In this example, there is no return receipt or delivery information for the sender. Once the mailman takes the letter, the sender has no guarantee that the letter will get to its final destination.

Now that you’ve a very simple understanding between the difference between TCP and UDP, it’s important to remember that not every service utilizes TCP. Several prominent services make use of UDP including DHCP, DNS (for individual lookups), SNMP and TFTP. One of the most important traits for a pentester to have is thoroughness. It’ll be quite embarrassing to you if you overlook or miss a service because you forgot to run a UDP Scan against your target.

Both the TCP Connect Scan and the SYN Scan use TCP as the basis for their scanning techniques. If we want to discover services utilizing UDP, we need to instruct Nmap to create scans using UDP packets. Fortunately, Nmap makes this process very simple. To run a UDP scan against our target, we’d enter the following command in a terminal:

nmap -sU 192.168.1.7

Notice the difference between this command and the others we’ve learned. First, we specify the Nmap UDP scan by using the “-sU” command. Astute readers will also notice that the “-p-” and the “-pN” switches have been dropped from the scan. The reason for this is simple. UDP scans are very slow; running even a basic UDP scan on the default 1000 ports can take 20-30 minutes.

It’s important to remember that UDP communication doesn’t require a response from the receiver. If the target machine doesn’t send back a reply saying a packet was received, how can Nmap differentiate between an opened port and a filtered (firewalled) port? In other words, it a service is available and accepting UDP packets, the normal behavior for this service is to simply accept the packet but not send a message back to the receiver saying “GOT IT!”. Likewise, a common firewall strategy is to simply absorb the packet and not send a response back to the sender. In this example, although one packet went through and one packet was blocked, because no packets were returned to the sender, there’s no way of knowing if the packet was accepted by a service or dropped by the firewall.

This conundrum makes it very difficult for Nmap to determine if a UDP port is open or filtered. As a result, when Nmap doesn’t receive a response from a UDP scan, it returns the following message for the port “open | filtered”. It’s important to note that on rare occasions a UDP service will send a response back to the original source. In these cases, Nmap is smart enough to understand that there is clearly a service listening and responding to requests and will mark those ports as “open”.

As was discussed earlier, oftentimes people who are new to port scanning overlook UDP scans. This is probably due in part to the fact that most ordinary UDP port scans provide very little information and mark nearly every port as “open | filtered” After seeing the same output on several different hosts, it’s easy to become disillusioned with UDP scans. However, all ain’t lost! The fine folks who wrote Nmap provide us with a way to draw more accurate results from our UDP Scans.

To elicit a more useful response from our target, we can add the “-sV” switch to our UDP Scan. The “-sV” switch is used for version scanning, but, in this case, can also help us narrow the results of our UDP Scan.

When version scanning is enabled, Nmap sends additional probes to every “open | filtered” port that is reported by the scan. These additional probes attempt to identify services by sending specifically crafted packets. These specially crafted packets are often much more successful in provoking a response from the target. Oftentimes, this will change the reported results from “open | filtered” to “open”.

As mentioned above, the simplest way to add version scanning to an UDP probe is to include the “-sV” switch. Please note that because we’re already using the “-sU” switch to specify the type of scan, we can simply append the capital “V” onto back of the “-sU”. As a result, our new command becomes:

nmap -sUV 192.168.1.7

X-Mas scan

In the computer world, an RFC is a document that contains either notes or the technical specifications covering a given technology or standard. RFCs can provide us with a tremendous amount of detail about the inner workings of a particular system. Because RFCs describe the technical details of how a system should work, attackers and hackers will often review RFCs looking for potential weaknesses or loopholes described in the documentation. Xmas Tree Scans and Null Scan exploit just such a loophole.

Xmas Tree Scans get their name from the fact that the FIN, PSH and URG packet flags are set to “on”; as a result, the packet has so many flags turned on and the packet is often described as being “lit up like a Christmas tree”. Given what we already know about TCP communications and the three-way handshake, it should be clear that an Xmas Tree packet is highly unusual because neither the SYN nor ACK flags are set. However, this unusual packet has a purpose. If the system we’re scanning has followed the TCP RFC implementation, we can send one of these unusual packets to determine the current state of the port.

The TCP RFC says if a closed port receives a packet that doesn’t have a SYN, ACK or RST flag set (i.e., the type of packet that is created from an Xmas Tree Scan), the port should respond with an RST packet of its own. Furthermore, the RFC states that if the port is open and it receives a packet without a SYN, ACK or RST flag set the packet should be ignored. Take a moment to reread the last two sentences, as they’re critical to understanding the response we get from these scans.

Assuming the operating system of the target fully complies with the TCP RFC, Nmap is able to determine the port state without completing or even initializing a connection to the target system. The word “assuming” was used because not every operating system on the market today is fully RFC compliant. In general, the Xmas Tree and Null scans work against Unix and Linux machines but not Windows. As a result, Xmas Tree and Null scans are rather ineffective against Microsoft targets.

To execute an Xmas Tree scan, we simply replace the “-sU” switch from our last example with an “-sX”. To run the full scan in the terminal, we’d issue:

nmap -sX -p- -PN 192.168.1.7

Null Scan

Null scans, like Xmas Tree scans, are probes made with packets that violate traditional TCP communication. In many ways, the Null scan is the exact opposite of an Xmas Tree scan because the Null scan utilizes packets that are devoid of any flags (completely empty).

Target systems will respond to Null scans in the exact same way they respond to Xmas Tree Scans. Specifically, an open port on the target system will send no response back to Nmap, whereas a closed port will respond with an RST packet. It’s important to remember that these scans are only reliable for operating systems that comply 100 per cent with the TCP RFC.

One of the main advantages of running Xmas Tree and Null scans is that in some cases, you’re able to bypass simple filters and Access Control Lists (ACLs). Some of these primitive filters work by blocking inbound SYN packets. The thought with this type of filter is that by preventing the SYN packet from entering the system, it ain’t possible for the three-way handshake to occur. If the three-way handshake doesn’t occur, there can be no TCP communication streams between the systems, or more precisely, no TCP communications can be originated from outside the filter.

It’s important to understand that neither the Xmas Tree nor the Null scans seek to establish any type of communication channel. The whole goal of these scans is to determine if a port is open or closed.

With the previous two paragraphs in mind, consider the following example. Assume that our Network Admin Ben Owned puts a simple firewall in from of his system to prevent anyone outside his network from connecting to the system. The firewall works by simply dropping any external communications that begin with a SYN packet. Ben hires his buddy, the ethical hacker, to scan his system. The ethical hacker’s initial TCP Connect Scans show nothing. However, being a seasoned penetration tester, the ethical hacking follows up his initial scan with UDP, Xmas Tree and Null scans. The ethical hacker smiles when he discovers that both his Xmas Tree Scans and Null Scans reveal open ports on Ben’s system.

This scenario is possible because Nmap creates packets without the SYN flag set. Because the filter is only dropping incoming packets with the SYN flag, the Xmas Tree and Null packets are allowed through. To run a Null Scan, we issue the following command in a terminal:

nmap -sN -p- -PN 192.168.1.7

Wrapping up the port scan

Now that we’ve covered the basics of port scanning, there are a few additional switches that need to be covered. These switches that need to be covered. These switches provide additional functionality that may be useful to you as you progress in your penetration testing career.

As mentioned earlier, the “-sV” switch is used for version scanning. When conducting version scanning, Nmap send probes to the open port in an attempt to determine specific information about the service that is listening. When possible, Nmap will provide details about the service including version numbers and other banner information. This information should be recorded in your notes. It’s recommended that you use the “-sV” switch whenever possible, especially on unusual or unexpected ports, because a wily administrator may have moved his web server to port 34623 in an attempt to obscure the service.

Nmap includes an option to change the speed of your port scan. This is done with the “-T” switch. The timing switch ranges on a numeric scale from 0 to 5, with 0 being the slowest scan and 5 being the fastest. Timing options are useful if you’re attempting to avoid detection by sending your scan more slowly; or if you’ve many IPs to scan and you’ve a limited time to complete the scan where faster scans would be more appropriate. Please be aware that by using the fastest scans possible, Nmap may provide less accurate results.

Lastly, the “-O” switch can be useful for fingerprinting the operating system. This handy for determining if the target you’ve attacking is a Windows, Linux or any other type of machine. Knowing the operating system of your target will save you time by allowing you to focus your attacks to known weaknesses of that system. There’s no use in exploring for a Linux machine if your target is running Windows.

Once we’ve completed port scanning on our target, we should have a list of open ports and services. This information should be documented and reviewed closely. While reviewing the Nmap output, you should take a few moments to attempt to log into any remote access services that were discovered in your port scan. The next chapter will address running a brute force tool to attempt log in. For the time being, you can attempt to log in using default usernames and passwords. You could also try logging in using any information, username or e-mail addresses you found during reconnaissance. It’s possible to complete a penetration test by simply discovering an open remote connection and logging into the box with a default username and password. Telnet and SSH are great remote services that you should try to connect to. You can do this from the command line by typing:

telnet target_ip
ssh root@target_ip

In this example, the “target_ip” is the IP address of your victim. Most likely these will fail, but on the rare occasion when you’re successful, these are an absolute home run.