Nmap
Tags: computerscience, cybersecurity, programming
Published: 2021-05-19 11:36:05

# About Nmap
Nmap is a network discovery and compliance auditing tool. In a nutshell, nmap shows exposed utilities on a target computer as well as other valuable details including version and Iso detection. It's also free and open source!

Nmap is an abbreviation for Network Mapper. It is a free and open-source Linux command-line utility for scanning IP addresses and ports in a network and detecting installed applications. Nmap helps network administrators to discover the machines that are connected to their network, discover available ports and services, and identify vulnerabilities.Gordon Lyon (pseudonym Fyodor) created Nmap as a method for quickly mapping an entire network and locating available ports and facilities.

Nmap is favoured over other scanning applications for a variety of purposes. Nmap allows you to easily map out a network without the need for complex commands or configurations. Nmap supports both basic commands (such as checking to see whether a host is up) and complex scripting through the Nmap scripting engine.

Other capabilities of Nmap include the ability to automatically identify all devices on a single or multiple networks, such as servers, routers, switches, handheld devices, and so on.
Identify the utilities that are running on a device, such as web servers, DNS servers, and other commonly used software. Nmap can also detect device variants with good precision, which can aid in the detection of known vulnerabilities.

Nmap will discover knowledge about the operating system that is currently running on a smartphone. It may include specific details such as OS models, making alternate approaches during penetration testing easier to schedule.
Nmap can be used to target applications using existing scripts from the Nmap Scripting Engine during security auditing and vulnerability scanning.

Zenmap is the graphical user interface for Nmap. It enables you to create visual network mappings for improved accessibility and monitoring.

# Commands
Let's have a look at a few Nmap commands. If you don't already have Nmap installed, you can obtain it here.
# Basic scans
The initial stage in network mapping is to scan the list of active devices on a network. There are two kinds of scans you may utilise for this:
**Ping scan ** — Scans the list of devices up and running on a given subnet.
`nmap -sp IP/24`

Scan a single host for 1000 well-known ports — Scans a single host for 1000 well-known ports. These are the ports used by prominent services such as SQL, SNTP, Apache, and others.

`nmap domain`

#Nmap Basic Scan
**Stealth scan** : Stealth scanning is performed by sending an SYN packet and analyzing the response. If SYN/ACK is received, it means the port is open, and you can open a TCP connection. However, a stealth scan never completes the 3-way handshake, hence it's hard for the target to determine the scanning system.

`nmap -sS domain`

To execute a stealth scan, use the ‘-sS' command. Keep in mind that stealth scanning is slower and less aggressive than other forms of scanning, so you may have to wait a while for a response.

**Version scanning**

Finding programme versions is an essential component of penetration testing. It makes your life simpler since you may locate an existing vulnerability for a specific version of the service in the Common Vulnerabilities and Exploits (CVE) database. Then, using an exploitation tool such as Metasploit, you may utilise it to attack a system.

`nmap -sV domain`

Use the ‘-sV' command to do a version scan. Nmap will provide a list of services along with their versions. Keep in mind that version scans are not always 100% correct, but they do get you one step closer to effectively entering a system.

#Nmap Version Scanning
**OS Scanning**
Nmap can offer information on the underlying operating system via TCP/IP fingerprinting in addition to the services and their versions. During an OS scan, Nmap will also attempt to determine the system uptime.

`nmap -sV domain`

You can use the additional flags like `--osscan-limit` to limit the search to a few expected targets. Nmap will display the confidence percentage for each OS guess. Again, OS detection is not always accurate, but it goes a long way in helping a pen tester get closer to his / her target.

**Nmap OS Scanning**

**Aggressive Scanning**

Nmap features an aggressive mode that allows it to detect operating systems, versions, scripts, and traceroutes. To execute an aggressive scan, use the -A parameter.

`nmap -A domain`

Regular scans do not give as much information as aggressive scans. An aggressive scan, on the other hand, sends out more probes and is more likely to be identified during security audits.

**Nmap Aggressive Scan**
**Scanning Multiple Hosts**

Nmap is capable of scanning many hosts at the same time. This function is extremely useful for managing a large network architecture.

You may scan several hosts using a variety of methods, including:
To scan all of the hosts at the same time, write all of the IP addresses in a single row.

`nmap 192.164.1.1 192.164.0.2 192.164.0.2`

Use the asterisk (*) to scan all of the subnets at once.

`nmap 192.164.1.*`

Add commas to separate the addresses endings instead of typing the entire domains

`nmap 192.164.0.1,2,3,4`

Use a hyphen to specify a range of IP addresses

`nmap 192.164.0.0–255`

**Port Scanning**

Port scanning is one of the most fundamental features of Nmap. You can scan for ports in several ways.

Using the `-p` param to scan for a single port

`nmap -p 973 192.164.0.1`

You can scan for information about a certain sort of connection if you provide the kind of port.

 eg. for a TCP connection,

`nmap -p T:7777, 973 192.164.0.1`

A range of ports can be scanned by separating them with a hyphen.

`nmap -p 76–973 192.164.0.1`

You can also use the `--top-ports` flag to specify the top n ports to scan
`nmap --top-ports 10 domain`

**Scanning from a File**

If you want to scan a large list of IP addresses, you can do it by importing a file with the list of IP addresses.

`nmap -iL /input_ips.txt`

The above command will produce the scan results of all the given domains in the “input_ips.txt” file. Other than simply scanning the IP addresses, you can use additional options and flags as well.

**Verbosity and Exporting Scan Results**

Penetration testing can last days or even weeks. Exporting Nmap results can be useful to avoid redundant work and to help with creating final reports. Let’s look at some ways to export Nmap scan results.

_Verbose Output_ : `nmap -v domain`

The verbose output offers more information about the scan that is being done. It is important to observe Nmap's activity on a network step by step, especially if you are an outsider scanning a client's network.

Nmap Verbose Output**
Normal output
Nmap scans may also be saved as text files. It will alter significantly from the original command line output, but it will contain all of the important scan findings.

`nmap -oN output.txt domain`

#Nmap File output
**XML output**
Nmap scans may be exported to XML as well. It's also the preferred file format for most pen-testing programmes, so it's easy to parse when importing scan results.

`nmap -oX output.xml domain`

**Nmap XML Output**

**Multiple Formats**

You can also export the scan results in all the available formats at once using the -oA command.

`nmap -oA output domain`
The above command will export the scan result in three files — output.xml, output. Nmap and output.gnmap.

**Nmap Help**

Nmap has a built-in help command that lists all the flags and options you can use. It is often handy given the number of command-line arguments Nmap comes with.
`nmap -h`

#Nmap Help

**Nmap Scripting Engine**: Nmap Scripting Engine (NSE) is a tremendously powerful tool for writing scripts and automating many networking capabilities. You may discover a plethora of scripts spread around Nmap, or you may develop your own script based on your needs. You may even use the Lua programming language to change existing scripts.

**Nmap Scripts**: NSE also includes attack scripts for assaulting the network and various networking protocols. Going through the scripting engine in detail would be beyond the scope of this post, but here is some additional information regarding the Nmap scripting engine.

**Zenmap**

Nmap's graphical user interface is Zenmap. It is a free and open-source programme that assists you in getting started with Nmap.

**Zenmap UI**
Zenmap not only provides visual network mappings, but it also allows you to save and search your scans for later use. Zenmap is ideal for novices who want to test the possibilities of Nmap without having to use a command-line interface.

**Conclusion**

Because of its extensive command set, Nmap is definitely the networking equivalent of the "Swiss Army Knife." Nmap allows you to swiftly scan and uncover important information about your network's hosts, ports, firewalls, and operating systems. Nmap includes a plethora of parameters, flags, and options that assist system administrators in thoroughly analysing a network.

#Nmap Scan Types

**TCP Connect**

The TCP Connect search concludes the three-way handshake.
If a port is open, the operating system has finished the TCP three-way handshake, and the port scanner closes the connection automatically to prevent DOS. This is considered "noisy" since the services will record the sender's IP address and can initiate Intrusion Detection Systems.

**UDP Scan**

This scan checks to see if there are any UDP ports listening.
Since UDP, unlike TCP, does not react with a positive acknowledgment and only reacts to an incoming UDP packet when the port is closed, this form of scan may sometimes produce false positives. It can, however, expose Trojan horses running on high UDP ports as well as secret RPC services.

It can be very slow, since some computers deliberately slow down responses to this type of traffic in order to avoid being overloaded. Machines running Windows OS, on the other hand, do not enforce this slowdown bug, so you should be able to search Windows hosts normally using UDP.

**SYN Scan**

TCP scanning is also known as SYN scanning.
Rather than using the network features of the operating system, the port scanner produces raw IP packets and watches for responses. Since it never establishes a complete TCP link, this scan style is also known as "half-open scanning." A SYN packet is created by the port scanner. If the target port is available, it will send a SYN-ACK packet in response.

The scanner host responds with a RST packet, effectively terminating the link before the handshake is done. If the port is closed but not filtered, the aim will answer immediately with a RST packet. There is some disagreement about which search is less invasive on the target host. The benefit of SYN scan is that the individual providers never receive a connection.

**FIN Scanner**

This is a stealthy scan, similar to the SYN scan, but only sends a TCP FIN packet.
Most, but not all, computers will respond with a RST packet if they receive this information, so the FIN scan may produce false positives and negatives, but it may slip past certain IDS programmes and other countermeasures.

**ACK Scan**

Ack screening decides whether or not the port is screened.
This is particularly useful when trying to detect the presence of a firewall and its rulesets. Simple packet filtering will make existing connections (packets with the ACK bit set), but a more advanced stateful firewall does not.

**NULL Scan**

Another quite stealthy check that disables or nullifies all TCP header flags.
This is not a true packet in most cases, and certain hosts may not know what to do about it. Windows operating systems are included in this category, and scanning them with NULL scans would yield untrustworthy performance. However, for non-Windows servers that are covered by a firewall, this may be a workaround.

**XMAS Scan**

Similar to the NULL search, except that all of the TCP header flags are set to on.
Because of the way their TCP stack is implemented, Windows machines will not react to this. The term "Xmas search" refers to a collection of flags that are allowed within a packet. These scans are intended to exploit the TCP header's PSH, URG, and FIN flags.

**RPC Scan**

This form of scan searches for devices that respond to RPC (Remote Procedure Call) services.
In such cases, RPC, which allows remote commands to be run on the server, can be a risky operation. Since RPC services can operate on a variety of ports.

It is difficult to know which ones are operating RPC from a standard scan. If RPC is working, this scan will probe the open ports on a computer with commands to display the programme name and version. It's not a bad thing to run all of these scans on a regular basis just to see whether and when you have these services going.

**IDLE Scan**

The scan packets are bounced off an external host, making it a very stealthy process.
You may not need power over the other host, but it must be configured and follow those specifications. You must enter the IP address of our "zombie" host as well as the port code. It is one of the most contentious solutions in Nmap because it is actually only useful for malicious attacks.

#Scan Techniques

| Switch |       Description      |        Example       |
|--------|:----------------------:|---------------------:|
|   -sS  |   TCP SYN port scan.   | nmap -sS IP |
|   -sT  | TCP Connect port scan. | nmap -sT IP |
|   -sU  |     UDP port scan.     | nmap -sU IP |
|   -sA  |   TCP ACK port scan.   | nmap -sA IP |


#Host Discovery

| Switch |       Description      |        Example       |
|--------|:----------------------:|---------------------:|
|   -Pn  |  Only port scan.       | nmap -Pn IP |
|   -sn  | Only host discovery.   | nmap -sn IP |
|   -PR  |ARP discovery on local network.| nmap -PR IP |
|   -n   | Disable DNS resolution.| nmap -n IP  |

#Port Specification

| Switch |         Description       |          Example          |
|--------|:-------------------------:|--------------------------:|
|   -p   |    Port or port range.    | nmap -p 22-80 IP |
|   -p-  |      Scan all ports.      |    nmap -p- IP   |
|   -F   | Fast port scan. (top 100) |    nmap -F IP    |

#Service and Version Detection

| Switch |         Description       |          Example          |
|--------|:-------------------------:|--------------------------:|
|   -sV  |Detect the version of services.| nmap -sV IP |
|   -A  |Enable OS detection,version detection,script scanning and traceroute.|nmap -A IP   |

#OS Detection

| Switch |         Description       |          Example          |
|--------|:-------------------------:|--------------------------:|
|   -O   |Identify OS using TCP/IP strack fingerprinting.| nmap -O IP |


#Timing and Performance

| Switch |       Description      |        Example       |
|--------|:----------------------:|---------------------:|
|   -T0  |   Paranoid IDS evasion.   | nmap -T0 IP |
|   -T1 | IDS evasion. | nmap -T1 IP |
|   -T2  |     IDS scan requires less bandwidth.| nmap -T2 IP|
|   -T3  |   IDS Default Scan   | nmap -T3 IP |
| -T4 | IDS Scan requires fast network |nmap -T4 IP|
| -T5| IDS Scan requires massive network speed|nmap -T5 IP|


#NSE Scripts

| Switch |         Description       |          Example          |
|--------|:-------------------------:|--------------------------:|
|   -sC   |Default script scan.| nmap -sC IP |
|   --script banner  | Just banner grabbing|nmap --script banner IP|


#Firewall / IDS Evasion

| Switch |         Description       |          Example          |
|--------|:-------------------------:|--------------------------:|
|   -f   |fragmented IP packets for the packet filter invasion| nmap -f IP |
|   -D  |Decoy Scan for spoofing the IP's|nmap -D IP|
|   -g   |Use given source port number. |nmap -g 22 IP|



Somwe of the Python Scripts adn the commands that is going to be very helpul in gettign the eraly recon for the programing geeks.

```python
>>> import nmap
>>> nm = nmap.PortScanner()
>>> nm.scan('127.0.0.1', '22-443')
>>> nm.command_line()
'nmap -oX - -p 22-443 -sV 127.0.0.1'
>>> nm.scaninfo()
{'tcp': {'services': '22-443', 'method': 'connect'}}
>>> nm.all_hosts()
['127.0.0.1']
>>> nm['127.0.0.1'].hostname()
'localhost'
>>> nm['127.0.0.1'].state()
'up'
>>> nm['127.0.0.1'].all_protocols()
['tcp']
>>> nm['127.0.0.1']['tcp'].keys()
[80, 25, 443, 22, 111]
>>> nm['127.0.0.1'].has_tcp(22)
True
>>> nm['127.0.0.1'].has_tcp(23)
False
>>> nm['127.0.0.1']['tcp'][22]
{'state': 'open', 'reason': 'syn-ack', 'name': 'ssh'}
>>> nm['127.0.0.1'].tcp(22)
{'state': 'open', 'reason': 'syn-ack', 'name': 'ssh'}
>>> nm['127.0.0.1']['tcp'][22]['state']
'open'

>>> for host in nm.all_hosts():
>>>     print('----------------------------------------------------')
>>>     print('Host : %s (%s)' % (host, nm[host].hostname()))
>>>     print('State : %s' % nm[host].state())
>>>     for proto in nm[host].all_protocols():
>>>         print('----------')
>>>         print('Protocol : %s' % proto)
>>>
>>>         lport = nm[host][proto].keys()
>>>         lport.sort()
>>>         for port in lport:
>>>             print ('port : %s\tstate : %s' % (port, nm[host][proto][port]['state']))
```
Host : 127.0.0.1 (localhost)
State : up
----------
Protocol : tcp
port : 22   state : open
port : 25   state : open
port : 80   state : open


for more refer to the NMAP Documentation.

Thank you all.
port : 111  state : open
port : 443  state : open