PORT SCANNING | nmap, connect()
Tags: webdev, tutorial, security, cybersecurity
Published: 2022-02-04 22:20:02

Each service provided by a computer monitors a specific port for incoming connection requests. There are 65,535 different possible ports on a machine. The main goal of port scanning is to find out which ports are open, which are closed, and which are filtered.

Looking at your machine from the outside, a given port on your machine is open only if you are running a server program on the machine and the port is assigned to the server. If you are not running any server programs, then, from the outside, no ports on your machine are open. This could be the case with a brand new digital device that is not meant to provide any services to the rest of the world. But, even with a device that was “**clean**” originally, should you happen to click accidentally on an email attachment consisting of malware, you could inadvertently end up installing a small server program in your machine that the bad guys could use to do their bad deeds.

When we say a port is **filtered**, what we mean is that the packets passing through that port are subject to the filtering rules of a firewall.

If a port on a remote host is **open** for incoming connection requests and you send it a SYN packet, the remote host will respond back with a SYN+ACK packet. 

If a port on a remote host is **closed** and your computer sends it a SYN packet, the remote host will respond back with a RST packet.

Let’s say a port on a remote host is **filtered** with something like an `iptables` based packet filter and your scanner sends it a SYN packet or an ICMP ping packet, you may not get back anything at all.

> If you are wondering about definitions such as SYN, ICMP, RST, you can specify them in the comments. I can explain these. But now let's continue without going beyond the subject of the article.

A frequent goal of port scanning is to find out if a remote host is providing a service that is vulnerable to buffer overflow attack. Port scanning may involve all of the 65,535 ports or only the ports that are well-known to provide services vulnerable to different security-related exploits. 

## Port Scanning with Calls to `connect()`

The simplest type of a scan is made with a call to `connect()`. The manpage for this system call on Unix/Linux systems has the following prototype for this function:

```c
#include <sys/socket.h>

int connect(int socketfd, const struct sockaddr *address, socklen_t address_len);
```

where the parameter `socketfd` is the file descriptor associated with the internet socket constructed by the client (with a call to three-argument `socket()`), the pointer parameter `address` that points to a `sockaddr` structure that contains the IP address of the remote server, and the parameter `address_len` that specifies the length of the structure pointed to by the second argument.

A call to `connect()` if successful completes a three-way handshake for a TCP connection with a server. The header file `sys/socket.h` includes a number of definitions of the **structs** needed for socket programming in C.

When `connect()` is successful, it returns the integer **0**, otherwise it returns **-1**.

In a typical use of `connect()` for port scanning, if the connection succeeds, the port scanner immediately closes the connection (having ascertained that the port is open).

## Port Scanning with TCP SYN Packets

Scanning remote hosts with SYN packets is probably the most popular form of port scanning. If your machine wants to open a TCP connection with another machine, your machine sends the remote machine a SYN packet. If the remote machine wants to respond positively to the connection request, it responds back with a SYN+ACK packet, that must then be acknowledged by your machine with an ACK packet. 

In a port scan based on SYN packets, the scanner machine sends out SYN packets to the different ports of a remote machine. When the scanner machine receives a SYN+ACK packet in return for a given port, the scanner can be sure that the port on the remote machine is open. It is the “**duty**” of a good port-scanner to immediately send back to the target machine an RST packet in response to a received SYN+ACK packet so that the half-open TCP circuit at the target is closed immediately.

Ordinarily, when a target machines receives a SYN packet for a closed port, it sends back an RST packet back to the sender. Note that when a target machine is protected by a packet-level firewall, it is the firewall rules that decide what the machine’s response will be to a received SYN packet.

## The `nmap` Port Scanner

`nmap` stands for “**network map**”. This open-source scanner, developed by **Fyodor** (see **http://insecure.org/**), is one of the most popular port scanners for Unix/Linux machines. There is good documentation on the scanner under the “**Reference Guide**” button at **http://nmap.org/**.

`nmap` is actually more than just a port scanner. In addition to listing the open ports on a network, it also tries to construct an inventory of all the services running in a network. It also tries to detect as to which operating system is running on each machine, etc. In addition to carrying out a TCP SYN scan, `nmap` can also carry out TCP `connect()` scans, UDP scans, ICMP scans, etc. Regarding UDP scans, note that SYN is a TCP concept, so there is no such thing as a UDP SYN scan. In a UDP scan, if a UDP packet is sent to a port that is not open, the remote machine will respond with an ICMP port-unreachable message. So the absence of a returned message can be construed as a sign of an open UDP port. However, a packet filtering firewall at a remote machine may prevent the machine from responding with an ICMP error message even when a port is closed.

As listed in its manpage, nmap comes with a large number of options for carrying out different kinds of security scans of a network. In order to give the reader a taste of the possibilities incorporated in these options, here is a partial description of the entries for a few of the options:

### -sP:

This option, also known as the “**ping scanning**” option, is for ascertaining as to which machines are up in a network. Under this option, `nmap` sends out ICMP echo request packets to every IP address in a network. Hosts that respond are up. But this does not always work since many sites now block echo request packets. To get around this, `nmap` can also send a TCP ACK packet to (by default) port 80. If the remote machine responds with a RST back, then that machine is up. Another possibility is to send the remote machine a SYN packet and wait for an RST or a SYN/ACK. For root users, `nmap` uses both the ICMP and ACK techniques in parallel. For non-root users, only the TCP `connect()` method is used.

### -sV:

This is also referred to as “**Version Detection**”. After `nmap` figures out which TCP and/or UDP ports are open, it next tries to figure out what service is actually running at each of those ports. A file called `nmap-services-probes` is used to determine the best probes for detecting various services. In addition to determine the service protocol (http, ftp, ssh, telnet, etc.), `nmap` also tries to determine the application name (such as Apache httpd, ISC bind, Solaris telnetd, etc.), version number, etc.

### -sT:

The “-sT” option carries out a TCP `connect()` scan. 

### -sU:

This option sends a dataless UDP header to every port. As mentioned earlier in this article, the state of the port is inferred from the ICMP response packet (if there is such a response at all).

-------------------------------------------
-------------------------------------------

If `nmap` is compiled with **OpenSSL** support, it will connect to SSL servers to figure out the service listening behind the encryption.

To carry out a port scan of your own machine, you could try (called as root):

`nmap -sS localhost`

The “-sS” option carries out a SYN scan. If you wanted to carry out an “**aggressive**” SYN scan of, say, **dev.to**, you would call as root:

`nmap -sS -A dev.to`

where you can think of the “**-A**” option as standing for either “**aggressive**” or “**advanced**.” This option enables OS detection, version scanning, script scanning, and more. 

> If the target machine has the DenyHosts shield running to ward off the dictionary attacks and you repeatedly scan that machine with the ’-A’ option turned on, your IP address may become quarantined on the target machine (assuming that port 22 is included in the range of the ports scanned). When that happens, you will not be able to SSH into the target machine. The reason I mention this is because, when first using nmap, most folks start by scanning the machines they normally use for everyday work. Should the IP address of your machine become inadvertently quarantined in an otherwise useful-to-you target machine, you will have to ask the administrator of the target machine to restore your SSH privileges there. This would normally require deleting your IP address from six different files that are maintained by DenyHosts.

You can limit the range of ports to scan with the “`-p`” option, as in the following call which will cause only the first **1024 ports** to be scanned:

`nmap -p 1-1024 -sT dev.to`

The larger the number of **router/gateway** boundaries that need to be crossed, the less reliable the results returned by `nmap`. 

By default, nmap first pings a remote host in a network before scanning the host. The idea is that if the machine is down, why waste time by scanning all its ports. But since many sites now block/filter the ping echo request packets, this strategy may bypass machines that may otherwise be up in a network. To change this behavior, the following sort of a call to nmap may produce richer results (at the cost of slowing down a scan):

`nmap -sS -A -P0 dev.to`

The ’**-P0**’ option (the second letter is ’zero’) tells `nmap` to not 
use ping in order to decide whether a machine is up.

`nmap` can make a good guess of the OS running on the target machine by using what’s known as “**TCP/IP stack fingerprinting**.” It sends out a series of TCP and UDP packets to the target machine and examines the content of the returned packets for the values in the various header fields. These may include the sequence number field, the initial window size field, etc. Based on these values, nmap then constructs an OS “**signature**” of the target machine and sends it to a database of such signatures to make a guess about the OS running on the target machine.

## Conclusion

Port Scanning is important for every developer to know how ports and communication packets work. By knowing at least these basics, you can find your own open doors and try to find solutions to them. If you have any questions about web pentesting, bug bounty and game development feel free to write.

Take care of yourselves.