# Nmap

{% hint style="info" %}
https://nmap.org
{% endhint %}

***

## Target Specification

When the server returns more than 1 IP associated with the domain name then we have to use :&#x20;

```
nmap <target> --resolve-all
```

#### Scanning the network range :&#x20;

```
nmap <network range> {options} 
```

#### Scan options for this section :&#x20;

```
nmap -iL <options> : Scan hosts from file
nmap -iR {number} <network range> <options> : scan hosts in the network randomly
nmap -iL <options> --exclude <IPS> :  Exclude scaning on certain hosts
nmap -iL <options> --excludefile <IPS> :  Exclude scaning on file hosts
nmap <target> -n : No DNS Resolution
nmap <target> -R : Compulsant DNS Resolution for each target
nmap --system-dns :  use the systems specified dns servers
nmap --dns-servers <DNSserver ip> : Use the following DNS servers
nmap --unique --iL <file> <options> : Only scan duplicate hosts once
```

<figure><img src="https://3312899877-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fwq2mVR4al0Q9L9ELuENl%2Fuploads%2F4cEFDPNCGwAmWFjPFaXI%2Fimage.png?alt=media&#x26;token=bc185202-ecfd-4b91-b015-019c63fedefc" alt=""><figcaption><p>target scan using the specified DNS server</p></figcaption></figure>

<figure><img src="https://3312899877-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fwq2mVR4al0Q9L9ELuENl%2Fuploads%2FQShRXxxvK2iIQrJYUNtF%2Fimage.png?alt=media&#x26;token=4c0c7565-e760-4c4c-8cb1-85e290199532" alt=""><figcaption><p>Compulsant DNS Resolution</p></figcaption></figure>

***

## Host Discovery&#x20;

One of the very first steps in any network reconnaissance mission is to reduce a (sometimes huge) set of IP ranges into a list of active or interesting hosts. Scanning every port of every single IP address is slow and usually unnecessary.

* **`-sL` (List Scan)**: Lists all target hosts with DNS resolution, without sending any packets to them.
* **`-sn` (No Port Scan)**: Performs a host discovery to check which hosts are up, but skips port scanning.
* **`-Pn` (No Ping)**: Skips host discovery and attempts to scan all specified targets as if they are up.
* **`-PS <port list>` (TCP SYN Ping)**: Sends SYN packets to specified ports to check if hosts are up by receiving SYN/ACK or RST responses.
* **`-PA <port list>` (TCP ACK Ping)**: Sends ACK packets to specified ports to check if hosts are up by receiving RST responses.
* **`-PU <port list>` (UDP Ping)**: Sends UDP packets to specified ports and waits for ICMP "port unreachable" responses to determine if a host is up.
* **`-PY <port list>` (SCTP INIT Ping)**: Sends SCTP INIT packets to specified ports to check if hosts are up by receiving INIT-ACK or ABORT responses.
* **`-PE` (ICMP Echo Request)**: Sends ICMP Echo Request (ping) packets to discover live hosts that respond with Echo Replies.
* **`-PP` (ICMP Timestamp Request)**: Sends ICMP Timestamp Request packets to discover live hosts based on Timestamp Replies.
* **`-PM` (ICMP Address Mask Request)**: Sends ICMP Address Mask Request packets to discover live hosts based on Address Mask Replies.
* **`-PO <protocol list>` (IP Protocol Ping)**: Sends IP packets with specified protocol numbers to check if hosts support those protocols.
* **`--disable-arp-ping`**: Disables ARP or IPv6 Neighbor Discovery (ND) ping on local networks.
* **`--discovery-ignore-rst`**: Ignores TCP RST responses during host discovery to avoid false positives from firewalls.
* **`--traceroute`**: Traces the network path to the target after a scan to find intermediate hops.

***

## Port Scanning Basics&#x20;

* **Open**: The port is actively accepting connections, datagrams, or associations for TCP, UDP, or SCTP protocols.
* **Closed**: The port is accessible but not actively in use by any application, and responds to probes with no service listening.
* **Filtered**: Nmap cannot determine if the port is open or closed because packet filtering (e.g., firewalls) prevents probes from reaching it.
* **Unfiltered**: The port is accessible, but Nmap cannot determine if it is open or closed, typically seen in ACK scans.
* **Open|Filtered**: Nmap cannot distinguish between open or filtered, often due to lack of response to probes (e.g., UDP scans).
* **Closed|Filtered**: Nmap cannot determine whether a port is closed or filtered, typically seen in IP ID idle scans.

***

## Port Scanning Techniques&#x20;

* **-sS (TCP SYN scan)**: Fast and stealthy scan that sends SYN packets and waits for responses to determine port status.
* **-sT (TCP connect scan)**: Uses the operating system's connect system call to establish a full connection to the target.
* **-sU (UDP scan)**: Scans for open UDP ports by sending UDP packets and waiting for ICMP or UDP responses.
* **-sY (SCTP INIT scan)**: SCTP equivalent of SYN scan, sending INIT chunks and interpreting responses to identify open/closed ports.
* **-sN (TCP NULL scan)**: Sends a packet with no flags set to differentiate open/closed ports based on RST responses.
* **-sF (TCP FIN scan)**: Sends a packet with the FIN flag set to distinguish open from closed ports using RST responses.
* **-sX (TCP Xmas scan)**: Sends packets with the FIN, PSH, and URG flags set to determine port status based on responses.
* **-sA (TCP ACK scan)**: Determines firewall rulesets by sending ACK packets to map open/closed/filtered ports.
* **-sW (TCP Window scan)**: Similar to ACK scan, but analyzes the TCP Window size in the RST responses to determine port status.
* **-sM (TCP Maimon scan)**: Uses a FIN/ACK probe to scan ports, exploiting systems that ignore such packets when a port is open.
* **--scanflags (Custom TCP scan)**: Allows custom TCP flags to be set for scans, modifying base scan behavior.
* **-sZ (SCTP COOKIE ECHO scan)**: SCTP scan using COOKIE ECHO chunks to quietly identify open ports.
* **-sI \<zombie host> (Idle scan)**: Blind scan using a "zombie" host to send packets, making the scan undetectable from the target.
* **-sO (IP protocol scan)**: Scans for supported IP protocols (not ports) by sending IP packets and looking for responses.
* **-b \<FTP relay host> (FTP bounce scan)**: Scans target ports by relaying FTP requests through an FTP server, bypassing firewalls.

***

## Port Specification & Scan Order

Here is a concise one-liner explanation for each option:

#### 1. **-p** : Specifies which ports to scan, either individual ports or ranges, and overrides the default port scan behavior

#### 2. **--exclude-ports** : Excludes specified ports from being scanned during the scan.

#### 3. **-F (Fast scan)** : Scans fewer ports (100 common ports) for a faster, limited scan.

#### 4. **-r (Don't randomize ports)** : Scans ports sequentially instead of randomly, starting from the lowest port number.

#### 5. **--port-ratio** : Scans ports with a likelihood (ratio) greater than the specified value (0.0 to 1.0).

#### 6. **--top-ports** : Scans the top most common ports based on frequency from the nmap-services file.

***

## Service & Version  Detection

* **-sV (Version detection)**\
  Enables version detection to identify the software and version of services running on open ports.
* **--allports (Don't exclude any ports from version detection)**\
  Forces version detection on all ports, even those excluded by default (like port 9100).
* **--version-intensity \<intensity>**\
  Sets the intensity (0-9) of version detection probes, with higher values increasing accuracy but slowing the scan.
* **--version-light (Enable light mode)**\
  A faster, lower-intensity version scan (equivalent to `--version-intensity 2`).
* **--version-all (Try every single probe)**\
  Forces Nmap to attempt every available probe, using the highest scan intensity (equivalent to `--version-intensity 9`).
* **--version-trace (Trace version scan activity)**\
  Prints detailed debugging information about the version scan process.

***

## OS Detection

* **-O (Enable OS detection)**\
  Enables OS detection to determine the operating system of the target.
* **--osscan-limit (Limit OS detection to promising targets)**\
  Restricts OS detection to hosts that have at least one open and one closed TCP port, optimizing the scan.
* **--osscan-guess; --fuzzy (Guess OS detection results)**\
  Makes Nmap more aggressive in guessing the OS if a perfect match is not found, showing possible OS guesses with a confidence percentage.
* **--max-os-tries (Set the maximum number of OS detection tries against a target)**\
  Sets the number of retries Nmap should perform to detect the OS, affecting the scan speed and accuracy.

***

## NMAP Scripting Engine

Here is the list of Nmap Scripting Engine options without examples and with bullet points:

* **-sC**\
  Performs a script scan using the default set of scripts (equivalent to `--script=default`).
* **--script ||/|\[,...]**\
  Runs a script scan using a specified list of scripts, categories, or directories. Advanced options allow for forcing certain scripts or using all available scripts.
* **--script-args =,={=},={,}**\
  Provides arguments to NSE scripts in the form of comma-separated name=value pairs.
* **--script-args-file**\
  Loads arguments for NSE scripts from a file, which supersede any arguments provided on the command line.
* **--script-help ||||all\[,...]**\
  Displays help about scripts, showing their name, categories, and description.
* **--script-trace**\
  Prints detailed information about the incoming and outgoing communication performed by scripts.
* **--script-updatedb**\
  Updates the script database used by Nmap to determine available scripts and categories.

***

## Timing & Performance

#### **Timeout and Retry Options**

1. **`--host-timeout <time>`**: Specifies the maximum time Nmap should wait for a response from a host. If the host takes longer than the specified time, it is skipped. This is useful to prevent Nmap from spending too much time on slow or unresponsive hosts.
2. **`--script-timeout <time>`**: Sets a timeout for Nmap scripts, ensuring that scripts that take too long are aborted. This prevents the entire scan from hanging due to a slow-running script.
3. **`--max-retries <numtries>`**: Specifies the maximum number of times Nmap will retransmit probes if there is no response. Reducing this number speeds up scans but may miss some ports, while increasing it improves accuracy but can slow down scans.
4. **`--max-rtt-timeout <time>`** and **`--initial-rtt-timeout <time>`**: These options adjust the round-trip time (RTT) for probes. Reducing the RTT can speed up scans, especially on fast networks, but risks missing responses if set too aggressively.

#### **Parallelism Options**

1. **`--min-hostgroup <numhosts>`** and **`--max-hostgroup <numhosts>`**: Control how many hosts are scanned in parallel. Larger groups increase efficiency but delay results. These options are useful for optimizing large network scans.
2. **`--min-parallelism <numprobes>`** and **`--max-parallelism <numprobes>`**: These adjust how many probes are sent in parallel within a host group. This setting helps optimize scanning speed, particularly for large networks or specific port scans.

#### **Scan Rate and Delay Options**

1. **`--scan-delay <time>`** and **`--max-scan-delay <time>`**: Adjust the delay between each probe sent. Useful for avoiding rate-limiting by the target or for evading intrusion detection systems (IDS).
2. **`--min-rate <number>` and `--max-rate <number>`**: Directly control the rate of scanning by setting a minimum and maximum number of packets per second. This is useful for fine-tuning scan speed or meeting specific network conditions.
3. **`--defeat-rst-ratelimit` and `--defeat-icmp-ratelimit`**: These options allow Nmap to bypass certain rate-limiting mechanisms, particularly when scanning ports that may generate a lot of error messages (RST or ICMP). While this can speed up scans, it may reduce accuracy.

#### **Timing Templates**

Nmap offers predefined timing templates to quickly adjust the scan’s aggressiveness:

* **`-T0` (paranoid)**: Very slow scan with long delays between probes to avoid detection.
* **`-T1` (sneaky)**: Slightly faster but still cautious.
* **`-T2` (polite)**: Slows down scans to avoid using too much bandwidth or affecting the target system too much.
* **`-T3` (normal)**: Default behavior.
* **`-T4` (aggressive)**: Faster scan suitable for reliable networks.
* **`-T5` (insane)**: Extremely fast, but sacrifices accuracy for speed.

***

## FW / IDS / IPS Evasion Techniques

* **-f / --mtu**: Splits packets into smaller fragments to evade detection.
* **-D**: Uses decoy IP addresses to hide the real source of a scan.
* **-S**: Spoofs the source IP address of the scan.
* **-e**: Specifies the network interface to send/receive packets on.
* **--source-port / -g**: Spoofs the source port number of packets.
* **--data / --data-string / --data-length**: Appends custom or random data to scan packets.
* **--ip-options**: Sends packets with custom IP options like source routing.
* **--ttl**: Sets the Time-to-Live (TTL) value in IP packets.
* **--randomize-hosts**: Randomizes the order of host scanning to avoid detection.
* **--spoof-mac**: Spoofs the MAC address used in raw ethernet frame scans.
* **--proxies**: Routes scan traffic through a chain of proxies to hide the origin.
* **--badsum**: Sends packets with invalid checksums to bypass detection.
* **--adler32**: Uses the Adler32 checksum for SCTP packets to interact with legacy systems.

***

## NMAP Output & Results

1. **-oN** : Saves scan results in normal, human-readable format.
2. **-oX** : Saves scan results in XML format for programmatic use.
3. **-oS** : Saves scan results in a humorous "script kiddie" format.
4. **-oG** : Saves scan results in a simple, grepable format (deprecated).
5. **-oA** : Saves scan results in all formats (normal, XML, grepable).
6. **-v / -v**: Increases verbosity of output, showing more scan details.
7. **-d / -d**: Increases debugging output for deeper analysis of scan processes.
8. **--reason**: Shows why a port or host is marked as up or down.
9. **--stats-every** : Periodically displays scan progress at specified intervals.
10. **--packet-trace**: Prints detailed trace of all packets sent and received during the scan.
11. **--open**: Displays only open or possibly open ports in the results.
12. **--iflist**: Lists the network interfaces and routes detected by Nmap.
13. **--append-output**: Appends results to existing output files instead of overwriting them.
14. **--resume** : Resumes a previously aborted scan from where it left off.
15. **--noninteractive**: Disables runtime interaction during the scan, useful for background execution.
16. **--stylesheet** : Sets a custom XSL stylesheet to transform XML output.
17. **--webxml**: Automatically uses the latest XSL stylesheet from Nmap.org for XML output.
18. **--no-stylesheet**: Prevents Nmap from linking an XSL stylesheet with its XML output.

***

## Miscellaneous Options

1. **-6**: Enables IPv6 scanning for Nmap.
2. **-A**: Runs an aggressive scan with OS detection, version scanning, script scanning, and traceroute.
3. **--datadir** : Specifies a custom directory for Nmap’s data files.
4. **--servicedb** : Uses a custom services file instead of the default `nmap-services` file.
5. **--versiondb** : Uses a custom service probes file instead of the default `nmap-service-probes` file.
6. **--send-eth**: Sends packets at the raw Ethernet layer (used on Windows).
7. **--send-ip**: Sends packets at the raw IP layer instead of Ethernet frames.
8. **--privileged**: Assumes the user has sufficient privileges for raw socket operations and packet sniffing.
9. **--unprivileged**: Assumes the user lacks privileges for raw socket operations.
10. **--release-memory**: Releases memory before quitting, useful for memory-leak debugging.
11. **-V / --version**: Prints the Nmap version number and exits.
12. **-h / --help**: Displays a help summary with common Nmap command flags.

***

