Nmap
Introduction
Nmap is a network exploration tool that can be used to scan the ports(TCP/UDP) that the hosts are listening on. It can used to scan a single host single port to multiple hosts multiple ports. It can also be used to determine the services hosted on certain ports by the server. The manual page of nmap(man nmap
) is pretty detailed and gives a good overview.
However, I will be listing the most common flags that I use frequently and their use.
Syntax
From man page of nmap, the most commonly used flags are:
Nmap 7.93 ( https://nmap.org )
Usage: nmap [Scan Type(s)] [Options] {target specification}
TARGET SPECIFICATION:
Can pass hostnames, IP addresses, networks, etc.
Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254
-iL <inputfilename>: Input from list of hosts/networks
-iR <num hosts>: Choose random targets
--exclude <host1[,host2][,host3],...>: Exclude hosts/networks
--excludefile <exclude_file>: Exclude list from file
HOST DISCOVERY:
-sL: List Scan - simply list targets to scan
-sn: Ping Scan - disable port scan
-Pn: Treat all hosts as online -- skip host discovery
SCAN TECHNIQUES:
-sS/sT: TCP SYN/Connect() scans
-sU: UDP Scan
PORT SPECIFICATION AND SCAN ORDER:
-p <port ranges>: Only scan specified ports
Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
--exclude-ports <port ranges>: Exclude the specified ports from scanning
-F: Fast mode - Scan fewer ports than the default scan
-r: Scan ports sequentially - don't randomize
--top-ports <number>: Scan <number> most common ports
SERVICE/VERSION DETECTION:
-sV: Probe open ports to determine service/version info
SCRIPT SCAN:
-sC: Performs a script scan using the default set of scripts. It is equivalent to --script=default.
Host Discovery
Before scanning ports, nmap checks if the host is online by sending ping request(-PE
). -Pn
flag can be used to ignore ICMP being used to determine if the host is up(all hosts are treated as online). Similarly, if we just want to perform host discovery to find out the network architecture, we can use -sn
flag to disable port scanning.
Default port scan
By default, Nmap will conduct a TCP-SYNC scan(-sS
) if run with root permissions, otherwise TCP scan(sT
). We can also specifically request to perform a UDP scan using -sU
flag. Out of 65536 possibilities for open ports, most of them are never open/used. Since, the scan time of nmap is directly proportional to the number of ports scanned, it only scans 1000 most used ports(standard ports) by default. Due to this, there is a chance that nmap might miss an open port that is not common. In such cases, we can specify the port or port range for scanning.
nmap -p-
: performs a full scan i.e. it will scan all 65536 ports.
It is recommended to perform a quick scan first to get overview of the services and then a full scan. Also, during the full scan, just find the port state without -sV
or -sC
to prevent extra activity on the target.
Types of TCP scan:
-
SYN scan:
-sS
During 3-way handshaking, client sends SYNC request. Upon receiving SYNC-ACK from server, client doesn’t acknowledge, server closes the connection by sending RST signal. Less no. of signals exchanged, comparatively less detectable.
-
Connect scan:
-sT
nmap scan is treated as other normal requests. All three handshaking signals are exchanged. Easily detected/logged.
Performance
Timeout
It is the amount of time that nmap waits for the server response. It is based upon the round trip time of the network request.
Options used to tweak this parameter are:
Option | Default Value |
---|---|
--initial-rtt-timeout |
1s |
--max-rtt-timeout |
10s |
--min-rtt-timeout |
100ms |
Specifying a lower
--max-rtt-timeout
and--initial-rtt-timeout
than the defaults can cut scan times significantly. This is particularly true for pingless (-Pn
) scans, and those against heavily filtered networks. Don’t get too aggressive though. The scan can end up taking longer if you specify such a low value that many probes are timing out and retransmitting while the response is in transit.If all the hosts are on a local network, 100 milliseconds (
--max-rtt-timeout 100ms
) is a reasonable aggressive value. If routing is involved, ping a host on the network first with the ICMP ping utility, or with a custom packet crafter such as Nping that is more likely to get through a firewall. Look at the maximum round trip time out of ten packets or so. You might want to double that for the--initial-rtt-timeout
and triple or quadruple it for the--max-rtt-timeout
. I generally do not set the maximum RTT below 100 ms, no matter what the ping times are. Nor do I exceed 1000 ms.
--min-rtt-timeout
is a rarely used option that could be useful when a network is so unreliable that even Nmap’s default is too aggressive.
Source: https://nmap.org/book/man-performance.html
Maximum Retries
This parameter determines how many times should the packet be retransmitted in case the server response is not received(timed out). Option --max-retries
is used to tweak this parameter. Its default value is 10. Increasing its value increases the scan time but also gives more reliable result.
Parallelism
This parameter determines the number of requests that nmap sends simultaneously during the scan. This parameter is adjusted dynamically by nmap based upon the network performance. --min-parallelism {num}
and --max-prallelism {num}
are the options used to configure this parameter. Increasing the --min-parallelism
speeds up the scan. At the same time, it reduces nmap’s dynamic control ability. So, this should be the last resort. A min parallel value of 10 might be reasonable.
Rates
When setting the minimum rate (--min-rate <number_per_second>
) for sending packets, we tell Nmap to simultaneously send the specified number of packets. It will attempt to maintain the rate accordingly. It differs from the parallelism as only the packets are sent simultaneously and not the whole request. A single request can consist of multiple packets. By default, it is handled dynamically by nmap.
Nmap Timing:
Tweaking all the parameters above to find the right balance can be difficult. So, nmap has provided 6 timing templates that tweaks the above parameters.
-T 0
->paranoid
-T 1
->sneaky
-T 2
->polite
-T 3
->normal
-T 4
->aggressive
-T 5
->insane
By default, if no timing specified, -T3
is used.
-T0
is slowest, it waits for few minutes before sending another request to the server.
-T5
quickest scan, it waits for few milliseconds before sending next request. Less reliable, less accurate.
-T 0
and -T 1
can be used for IDS evasion. However, they are extremely slow. So, manually tuning the above parameters is recommended.
In general, to increase the speed of scan, -T 4
is recommended.
Useful flags:
-A
- Scan the host to identify services running by matching against Nmap’s database with OS detection
- very handy, equivalent to adding
-sV
-sC
-O
flag
--disable-arp-ping
- Even when
-Pn
or-PE
host discovery options are specified, nmap does ARP scan of locally connected ethernet hosts. - this flag disables the ARP scan, which is not required at all during the port scanning against just a single host.
- Even when
-n
- Disables reverse DNS resolution of the IP addresses it finds.
- reduces scan time.
--dns-servers {nameserver1}[,{nameserver2}[,...]]
- specify the DNS server for reverse DNS resolution.
- useful when scanning private networks by using their private DNS server(most probably hosted on port 53).
--stats-every=5s
- Displays scan’s status every 5 seconds (
1m
=> every 1 minute) - Alternatively,
space-bar
key can be pressed to get the scan status
- Displays scan’s status every 5 seconds (
--packet-trace
- shows all the packets sent and received while performing the scan.
- useful to investigate more on the scan type and the server responses.
- based upon the packet exchange observed by tracing, manual requests can be sent using separate tools to extract information. For example,
nc
can be used for banner grabbing.
One thing to keep in mind is that the request should be similar to the one sent by nmap. Things such as source port, source IP, timeout, etc. should be considered.
--reason
- displays the reason for specific result.
- Example: why the host has been marked as active, why a port is in a particular state.
-S {IP}
- specify the source IP for scan.
- useful if the current host IP has been blocked by the firewall, or if only a subnet is allowed access to the service.
-g {port}
- specify the source port for scan.
- useful to bypass the firewall, if right port crafted wisely.
- setting the source port to any of the standard ports(e.g. 53 for dns ) used by the server itself, might bypass the firewall.
--script-updatedb
- can be used to update the nmap script database in the machine.
Nmap Scripts
Nmap Scripting Engine(NSE) provides a number of scripts in Lua that can be used to interact with various services. There are a total of 14 categories of the scripts:
Category | Description |
---|---|
auth | Determination of authentication credentials. |
broadcast | Scripts, which are used for host discovery by broadcasting and the discovered hosts, can be automatically added to the remaining scans. |
brute | Executes scripts that try to log in to the respective service by brute-forcing with credentials. |
default | Default scripts executed by using the -sC option. |
discovery | Evaluation of accessible services. |
dos | These scripts are used to check services for denial of service vulnerabilities and are used less as it harms the services. |
exploit | This category of scripts tries to exploit known vulnerabilities for the scanned port. |
external | Scripts that use external services for further processing. |
fuzzer | This uses scripts to identify vulnerabilities and unexpected packet handling by sending different fields, which can take much time. |
intrusive | Intrusive scripts that could negatively affect the target system. |
malware | Checks if some malware infects the target system. |
safe | Defensive scripts that do not perform intrusive and destructive access. |
version | Extension for service detection. |
vuln | Identification of specific vulnerabilities. |
Source: https://academy.hackthebox.com/module/19/section/108
Complete list of all the available Nmap scripts can be found here.
The script can be specified in the nmap command as:
sudo nmap <target> --script <category>
sudo nmap <target> --script <script-name>,<script-name>,...
If the category is specified, all the scripts within that category are executed. It is recommended to run nmap scripts (except the default
) on specific ports and not general port scanning as executing the script can take some time and it also creates activity on the target side increasing the chance of detection. Once the services have been identified, scripts related to the service can be searched in the complete list of available scripts.
Nmap port state
State | Description |
---|---|
open | This indicates that the connection to the scanned port has been established. These connections can be TCP connections, UDP datagrams as well as SCTP associations. |
closed | When the port is shown as closed, the TCP protocol indicates that the packet we received back contains an RST flag. This scanning method can also be used to determine if our target is alive or not. |
filtered | Nmap cannot correctly identify whether the scanned port is open or closed because either no response is returned from the target for the port or we get an error code from the target. |
unfiltered | This state of a port only occurs during the TCP-ACK scan and means that the port is accessible, but it cannot be determined whether it is open or closed. |
open|filtered | If we do not get a response for a specific port, Nmap will set it to that state. This indicates that a firewall or packet filter may protect the port. |
closed|filtered | This state only occurs in the IP ID idle scans and indicates that it was impossible to determine if the scanned port is closed or filtered by a firewall. |
Source: https://academy.hackthebox.com/module/19/section/102
Output(Example)
-
-sV
:The PORT column in the output shows the port number and type of scan.
-sC
: flag gives information regarding the certificates, validation dates for each port, etc.-A
:$ nmap -A 10.10.11.100 | tee nmap_scan Starting Nmap 7.91 ( https://nmap.org ) at 2021-08-05 00:47 EDT Nmap scan report for 10.10.11.100 Host is up (0.17s latency). Not shown: 998 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 d4:4c:f5:79:9a:79:a3:b0:f1:66:25:52:c9:53:1f:e1 (RSA) | 256 a2:1e:67:61:8d:2f:7a:37:a7:ba:3b:51:08:e8:89:a6 (ECDSA) |_ 256 a5:75:16:d9:69:58:50:4a:14:11:7a:42:c1:b6:23:44 (ED25519) 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) |_http-server-header: Apache/2.4.41 (Ubuntu) |_http-title: Bounty Hunters Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 26.94 seconds
Output Formats
Nmap can save the results in 3 different formats.
- Normal output (
-oN
) with the.nmap
file extension => whatever we see in the stdout\ - Grepable output (
-oG
) with the.gnmap
file extension# Nmap 7.80 scan initiated Tue Jun 16 12:14:53 2020 as: nmap -p- -oA target 10.129.2.28 Host: 10.129.2.28 () Status: Up Host: 10.129.2.28 () Ports: 22/open/tcp//ssh///, 25/open/tcp//smtp///, 80/open/tcp//http/// Ignored State: closed (4) # Nmap done at Tue Jun 16 12:14:53 2020 -- 1 IP address (1 host up) scanned in 10.22 seconds
- XML output (
-oX
) with the.xml
file extension
XML output is one of the most important output types, as it can be converted to HTML that are easy to read, even for non-technical people. Various parsers are available to parse the XML to HTML.
e.g. xsltprocxsltproc target.xml -o target.html
-oA
store the output in all three formats.
Defending nmap scan
- Open-source Intrusion Detection System(IDS) and Intrusion Prevention System(IPS) such as Snort and Suricata can be used to detect and block nmap scan.
- When multiple request packets to different ports of the server, from the same machine are detected, they block the IP address of the machine.
- Connect scan requests with
-T5
are more likely to be detected.
Bypassing the defense
- Nmap TCP ACK (
-sA
) scan is much harder to filter for firewalls and IDS/IDP systems. - Use decoy(
-D RND:5
) to camouflage the real source IP among multiple spoofed IP addresses so that it becomes difficult for the target side defense to detect and block.