> For the complete documentation index, see [llms.txt](https://thenullgod.gitbook.io/blackhat/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://thenullgod.gitbook.io/blackhat/nmap.md).

# NMAP

Nmap (Network Mapper) is a free, open-source tool used for network discovery and security auditing.

It can

* Discover live hosts on a network
* Identify open ports on a host
* Detect services like web servers, FPT, and SSH
* Determine the operating system (OS) of a target
* Perform vulnerbaility scans with scripts

Basic Usage

`nmap [target]`

`nmap 192.168.1.1 # Scan a single IP nmap`&#x20;

`scanme.nmap.org # Scan a domain nmap`&#x20;

`192.168.1.1-10 # Scan a range of IPs nmap`&#x20;

`192.168.1.0/24 # Scan an entire subnet`

| Option | Meaning                                                                           | Example                      |
| ------ | --------------------------------------------------------------------------------- | ---------------------------- |
| `-p`   | Specify ports to scan                                                             | `nmap -p 80,443 192.168.1.1` |
| `-sS`  | TCP SYN scan (stealthy)                                                           | `nmap -sS 192.168.1.1`       |
| `-sV`  | Version detection (what service/version is running)                               | `nmap -sV 192.168.1.1`       |
| `-O`   | OS detection                                                                      | `nmap -O 192.168.1.1`        |
| `-A`   | Aggressive scan (OS detection + version detection + script scanning + traceroute) | `nmap -A 192.168.1.1`        |
| `-T`   | Set timing (0 = slow, stealthy; 5 = very fast, noisy)                             | `nmap -T4 192.168.1.1`       |
| `-v`   | Verbose (show more output)                                                        | `nmap -v 192.168.1.1`        |

Example

`nmap -sS -p 22,80,443 -T4 -v 192.168.1.1`

* `-sS`: SYN scan (stealthy)
* `-p 22,80,443`: Only check ports 22 (SSH), 80 (HTTP), 443 (HTTPS)
* `-T4`: Make the scan faster
* `-v`: Show more details
* `192.168.1.1`: Target

Scan Types

* **TCP Connect Scan** (`-sT`): Full connection (basic, easy to detect)
* **SYN Scan** (`-sS`): Half-open scan (common for stealthy scanning)
* **UDP Scan** (`-sU`): Scan UDP ports (slower and trickier)
* **Service Version Scan** (`-sV`): Find out what service versions are running
* **OS Detection** (`-O`): Try to determine the operating system

Tip: Some scans (especially `-A` and `-O`) can be noisy and easily detected by firewalls.

What is port scanning?

Port scanning checks which ports on a host are open, closed, or filtered.\
Each port represents a possible **entry point** (like SSH on port 22 or HTTP on port 80).

Port States

* **open** – An application is actively accepting connections.
* **closed** – No service is listening, but the host responds.
* **filtered** – A firewall or filter is blocking the request.
* **unfiltered** – Port is reachable, but Nmap can't determine if it’s open or closed.
* **open|filtered** – Nmap can't tell if it’s open or filtered.
* **closed|filtered** – Nmap can't determine if it’s closed or filtered.

Common Scan types

#### 1. **TCP Connect Scan** (`-sT`)

* **Full 3-way handshake (SYN, SYN-ACK, ACK)**
* Easy to detect but works without raw packet privileges.

`nmap -sT 192.168.1.1`

#### 2. **SYN Scan** (`-sS`) - *Stealth scan*

* Sends only SYN packets, doesn’t complete the handshake.
* Fast, stealthy, and widely used by pentesters.

`nmap -sS 192.168.1.1`

#### 3. **UDP Scan** (`-sU`)

* Scans UDP ports (like DNS on port 53 or SNMP on 161).
* Slower and more difficult (due to lack of replies).

`nmap -sU 192.168.1.1`

#### 4. **TCP Null, FIN, Xmas Scans**

Used for evading some firewalls.

* **Null scan**: `nmap -sN`
* **FIN scan**: `nmap -sF`
* **Xmas scan**: `nmap -sX`

Targeting Specific Ports

You can scan specific ports using `-p`: `nmap -sS -p 22,80,443 192.168.1.1 # Common ports nmap -sS -p- 192.168.1.1 # All 65,535 ports`

Time Options

Use `-T` to control scan speed:

* `-T0`: Paranoid (very slow, evades IDS)
* `-T4`: Aggressive (fast, more detectable)

`nmap -sS -p- -T4 192.168.1.1`

Service Detection

Detects what software/version is running on open ports.

`nmap -sV 192.168.1.1`

Scanning all ports with version detection

`nmap -sS -p- -sV -T4 192.168.1.1`

&#x20;

&#x20;Scanning multiple targets

`nmap 192.168.1.1 192.168.1.2 nmap 192.168.1.1-20 nmap 192.168.1.0/24`

&#x20;

&#x20;Output Formats

* Default: console
* Save to file: `-oN` (normal), `-oG` (grepable), `-oX` (XML)

Example:

`nmap -sS -p 22,80 -oN result.txt 192.168.1.1`

The TCP 3-way handshake

When two devices communicate over TCP, they establish a connection using **SYN** and **ACK** packets through a **3-step handshake**:

#### Step 1: **SYN (Synchronize)**

* The client sends a **SYN** packet to the server.
* It’s saying: *“I want to connect and here’s my initial sequence number.”*

#### Step 2: **SYN-ACK (Synchronize-Acknowledge)**

* The server responds with a **SYN-ACK** packet.
* It says: *“Okay, I hear you (ACK), and I also want to connect (SYN).”*
* It includes its own sequence number.

#### Step 3: **ACK (Acknowledge)**

* The client responds with an **ACK** packet.
* It says: *“Connection established, I acknowledge your SYN.”*

Diagram of the TCP Handshake

`Client Server | SYN (seq=x) → | | | | ← SYN-ACK (seq=y, ack=x+1) | | | | ACK (ack=y+1) → | |_____________________________| Connection Established`

Why is this important for scanning?

Tools like **Nmap** use this to check if ports are open:

#### **SYN Scan (`-sS`)** - *"Half-open" scan*

* Sends **SYN** to a port.
* If it receives **SYN-ACK**, the port is **open**.
* It immediately sends a **RST** (reset) instead of completing the handshake.
* Stealthy: doesn't finish the connection, so it may go unnoticed by firewalls/IDS.

Packet roles in summary

| Packet    | Purpose                                                          |
| --------- | ---------------------------------------------------------------- |
| `SYN`     | Starts the connection                                            |
| `SYN-ACK` | Acknowledges the SYN and sends its own SYN                       |
| `ACK`     | Acknowledges the server’s SYN                                    |
| `RST`     | Resets the connection (used in SYN scan to avoid full handshake) |

It's steathly, but can an IDS or Wireshark see the influx of packets coming from the client using Nmap?

Let's break it down

SYN Scan Stealth

* **Why it’s “stealthy”:**\
  It *does not complete the full TCP handshake*. Instead of sending the final `ACK`, it sends a `RST` (reset). This avoids full connection logs on some systems and may bypass basic logging tools.
* **Why it’s&#x20;*****not*****&#x20;invisible:**\
  An **IDS (Intrusion Detection System)** or **Wireshark** can still absolutely:
  * Detect and log the **SYN packet flood**
  * See repeated **SYN** requests from one host
  * Identify **no follow-up ACKs** or normal traffic patterns
  * Flag unusual port scan behavior (e.g., many SYNs to many ports in a short time)

Real World Example in Wireshark

If you filter Wireshark with: ini

`tcp.flags.syn == 1 && tcp.flags.ack == 0`

You’ll see all incoming **SYN** packets — the first packet in a scan or handshake. If you're scanning with Nmap using `-sS`, you'll see a stream of these.

IDS Detection

IDS tools like **Snort**, **Suricata**, or **Zeek** can detect SYN scans easily using signature rules or behavioral analysis:

* Large number of SYNs with no follow-up traffic
* SYN packets targeting many different ports
* Timing patterns from `nmap -T4` or `-T5` (faster scans)

Using Slower Timing Templates

Nmap's `-T` options control speed and timing.

* `-T0`: Paranoid (very slow)
* `-T1`: Sneaky (slow)
* `-T2`: Polite

These reduce packet frequency to avoid triggering IDS thresholds.

`nmap -sS -T1 192.168.1.1`

&#x20;

&#x20;Randomize Scan Order

Avoid linear port scanning.

`nmap --randomize-hosts -sS -T1 192.168.1.0/24`

&#x20;

Use Decoys

Insert fake IP addresses to confuse detection and attribution.

`nmap -sS -D 192.168.1.100,192.168.1.101,ME 192.168.1.1`

* `ME` represents your real IP.

Fragment Packets

Break scan packets into tiny fragments to evade deep packet inspection.

`nmap -sS -f 192.168.1.1`

Use Source Port Spoofing

Some firewalls allow traffic from trusted ports (like 53 or 443).

`nmap -sS --source-port 53 192.168.1.1`

Idle Scan

Use a **zombie host** to perform scans for you. No packets are sent directly from your IP to the target.

`nmap -sI zombieIP 192.168.1.1`

Avoid Ping Detection

IDS might log ICMP ping requests. Disable host discovery:

`nmap -Pn 192.168.1.1`

&#x20;

&#x20;Use DNS instead of IP

Avoid suspicious reverse DNS lookups (or enable/disable as needed):

`nmap -n -sS 192.168.1.1`

&#x20;

Combine Techniques

Here’s a stealthy scan combining methods:

`nmap -sS -T1 -Pn -f -D 192.168.1.100,ME --source-port 53 192.168.1.1`

Stealth does not mean undetectable, advanced IDS/IPS can still flag anomalies

What is Linear Scanning?

Linear scanning means Nmap scans targets or ports **in order**, like:

* IPs: `192.168.1.1`, then `.2`, then `.3`, etc.
* Ports: 1, 2, 3, 4, ..., 65535

This pattern can trigger IDS/IPS systems because it's predictable and fast.\
To avoid this, Nmap can **randomize hosts and port scan order**:

`nmap --randomize-hosts -sS 192.168.1.0/24`

List of Timing Options

| Option | Name       | Behavior                                                   |
| ------ | ---------- | ---------------------------------------------------------- |
| `-T0`  | Paranoid   | Very slow, avoids detection. Ideal for IDS evasion.        |
| `-T1`  | Sneaky     | Slow, more practical than `-T0`, still stealthy.           |
| `-T2`  | Polite     | Slows down scan to use less bandwidth or CPU.              |
| `-T3`  | Normal     | Default timing setting.                                    |
| `-T4`  | Aggressive | Faster, may be flagged by IDS.                             |
| `-T5`  | Insane     | Very fast, very noisy. Useful on LAN or with no firewalls. |

Use `-T1` or `-T2` for stealth, and `-T4` for speed when detection doesn't matter.

How Do You Use Decoys in Detail?

Nmap’s `-D` option adds **fake IPs** to the scan. The target sees packets coming from multiple IPs, making it harder to tell which IP is the real one.

**Syntax:**

`nmap -sS -D decoy1,decoy2,ME target`

* `decoy1`, `decoy2` = fake IPs (public IPs or LAN IPs)
* `ME` = tells Nmap to insert your real IP in the mix

**What the target sees:**

They’ll see incoming SYN packets from all listed IPs. IDS logs may not be able to distinguish which is real.

**Important notes:**

* Decoy IPs **must be valid** and reachable on the network.
* Too many decoys may cause network noise or detection by behavior-based IDS.
* Not effective if only one IP responds to the scan (the rest are silent).

Why Do Firewalls Allow Traffic from Trusted Ports

Some firewalls allow **incoming traffic from "trusted" source ports** like:

* **53 (DNS)**
* **67 (DHCP)**
* **443 (HTTPS)**
* **20/21 (FTP)**

**Why?**

* These ports are used for **legit services**.
* Some misconfigured or older firewalls don't inspect the **source port**, only the **destination port**.
* Attackers can exploit this by setting the **source port** of their scan to a trusted value, tricking the firewall.

**Nmap usage:**

`nmap -sS --source-port 53 target`

How Do Zombie Hosts Work?

**Zombie hosts** are systems with:

* Predictable IP ID increments (used in packet headers)
* Low network activity (so their IP ID count isn’t disturbed)

**Idle Scan Workflow:**

1. Nmap sends a **SYN** to the **target**, **spoofing the zombie’s IP**.
2. If the port is **open**, the target sends a **SYN-ACK** to the zombie.
3. The zombie, confused, sends a **RST**, and its **IP ID** increases.
4. Nmap probes the zombie’s IP ID before and after to detect this change.

**Command:**

`nmap -sI zombieIP targetIP`

**Benefit:** No packets are sent directly from your IP to the target. Super stealthy.

Whats the Benefit of Using DNS instead of IP?

**Using a domain name:**

`nmap scanme.nmap.org`

**vs Using an IP address:**

bash

Copy code

`nmap 45.33.32.156`

**Benefits of using DNS:**

* Allows targeting dynamic or **load-balanced** services.
* Helps find **multiple IPs** behind a domain (e.g., round-robin DNS).
* More **human-readable** for scripting and automation.
* Some domains may resolve to **different IPs at different times** — useful in cloud environments.

**Caveat:**

Sometimes, DNS lookups cause delays or alert logs. Use `-n` to **skip DNS** if needed:

`nmap -n 192.168.1.0/24`

What is DHCP?

**DHCP = Dynamic Host Configuration Protocol**

* It’s the protocol that **automatically assigns IP addresses** to devices on a network.

**Workflow:**

1. Device connects to network and sends a **DHCPDISCOVER** broadcast.
2. DHCP server replies with a **DHCPOFFER**.
3. Device sends a **DHCPREQUEST** to accept the offer.
4. Server responds with **DHCPACK** confirming the lease.

> DHCP assigns:

* IP address
* Subnet mask
* Gateway
* DNS server

**Why it matters:**

* Most networks use DHCP to manage IPs dynamically.
* Attackers can spoof DHCP replies to perform **man-in-the-middle** attacks.
* Some firewall rules blindly trust DHCP ports (like UDP 67/68), which can be exploited.

How Can Attackers Exploit Source Port Values?

Some **poorly configured firewalls** and **stateful inspection rules** allow or trust traffic **based on the source port**.

**Example Scenario:**

* A firewall allows **DNS traffic (port 53)** to go *in or out*.
* An attacker sends **Nmap scans** with a **spoofed source port** of 53.

`nmap -sS --source-port 53 target`

**Why this works:**

* Firewalls might assume any traffic **from port 53** is DNS — and therefore *trusted*.
* The firewall might not **inspect packet content** deeply — just see the port and allow it.

> This technique is called **source port spoofing** and can bypass weak firewall rules.

**Note:**

* **Modern firewalls and IDS** can detect this tactic, especially if behavior doesn’t match the port (e.g., SYN scans from port 53 look suspicious).
* Still useful in legacy systems, embedded environments, or misconfigured firewalls.

What is an IP ID Increment?

The **IP ID** (Identification field) is a 16-bit field in the **IP header** used to help **reassemble fragmented packets**.

* Each IP packet has an ID number.
* Many systems increment the IP ID **by 1** for each packet they send, globally.

**Example:**

* IP packet 1: ID = 34500
* IP packet 2: ID = 34501
* IP packet 3: ID = 34502

**Why does it matter for Idle Scanning?**

* Nmap probes a **zombie host** to learn its current IP ID.
* Then it spoofs the zombie’s IP and sends a packet to the target.
* If the target responds to the zombie, the zombie’s **IP ID increments**.
* Nmap checks again — if the ID changed, the port was open (because the zombie sent a RST back).

> If the IP ID didn’t change, the port was closed (no response was needed).

**Conditions for Idle Scan to work:**

* Zombie must use **sequential IP ID generation**.
* Must be **idle** (low traffic) to keep IP ID predictable.

How to Resolve Multiple IPs using DNS

When you scan a domain (like `example.com`), DNS resolution might return **multiple A or AAAA records** — each pointing to a different server.

**Example:**

`nslookup google.com`

**Result:**

`Name: google.com Addresses: 142.250.190.14 142.250.190.78 142.250.190.110`

This means `google.com` has multiple backend servers — part of a **load-balanced or distributed** infrastructure.

**Why:**

* High availability
* Load balancing
* Geographic distribution (CDN)

Nmap Can Resolve and Scan All Returned IPs

When you pass a **domain name** to Nmap (like `nmap scanme.nmap.org`), it will:

* **Resolve the domain to one or more IPs**
* **Scan all resolved IPs**, unless limited with options

Using dig or host to Discover More

You can manually query a domain’s DNS records using tools like `dig`:

`dig +short example.com`

Or enumerate subdomains:

`dig sub.example.com`

Or use a subdomain brute-forcer like `dnsrecon` or `dnscan` to find **hidden** or **unlisted** DNS entries:

`dnsrecon -d example.com`

Nmap NSE Script Examples

Nmap can use scripts like `dns-brute` to find IPs from DNS records:

`nmap --script dns-brute -Pn example.com`

This can uncover:

* Multiple subdomains
* Different IPs for each subdomain
* Hidden services

Load Balancing

**Load balancing**, in the context of scanning, refers to when a target domain (like a website or service) uses **multiple backend servers** to handle traffic — and **distributes incoming connections among them** to prevent overload.

How It Works

When a client (or scanner like Nmap) tries to connect to `example.com`:

* DNS may return **multiple IPs** (e.g., `192.0.2.1`, `192.0.2.2`, `192.0.2.3`).
* A **load balancer** sits in front of those servers and:
  * Routes traffic to a different backend based on load, location, round-robin, etc.
  * Can be DNS-based (Layer 3) or proxy-based (Layer 4/7).

When Scanning Load-Balanced Targets

1. **You might get different responses** on different scans.
   * One scan might hit server A, the next hits server B.
   * They may have different open ports, banners, or service versions.
2. **Nmap may resolve the same domain to different IPs**, especially with:

   `nmap example.com`
3. Load balancers may **filter or throttle scans**:
   * Some detect rapid port scans and block or reroute you.
   * You may get inconsistent or missing data unless you scan each backend IP directly.

How to Handle it

* Use `dig` or `nslookup` to find all IPs tied to the domain.
* Scan **each IP individually**:

  `nmap -sS 192.0.2.1,192.0.2.2,192.0.2.3`
* Consider using **slow timing (`-T1`)** or **host discovery (`-sL`, `-sn`)** to avoid triggering WAFs/load balancer rules.
