# Nmap (Network Mapper)

> **The Swiss Army Knife of Network Security Scanning**

## 📋 Overview

Nmap (Network Mapper) adalah open-source tool yang powerful untuk network discovery dan security auditing. Dikembangkan oleh Gordon Lyon (Fyodor), Nmap menjadi standar industri untuk network exploration, port scanning, dan vulnerability assessment.

## 🎯 Key Features

### 🔍 **Port Scanning Techniques**

* **TCP Scan** (-sT) - Standard TCP connect scan
* **SYN Scan** (-sS) - Stealthy half-open scan
* **UDP Scan** (-sU) - UDP port discovery
* **ACK Scan** (-sA) - Determine firewall rules
* **Window Scan** (-sW) - Advanced TCP scanning
* **Maimon Scan** (-sM) - Unix-specific detection

### 🌐 **Host Discovery**

* **Ping Scan** (-sn) - Host discovery without port scan
* **ARP Discovery** - Local network host detection
* **ICMP Echo** - Traditional ping
* **TCP ACK Ping** - Alternative discovery method
* **ICMP Timestamp** - OS fingerprinting
* **IP Protocol Ping** - Protocol-specific discovery

### 📊 **Service and Version Detection**

* **Service Detection** (-sV) - Identify running services
* **Version Fingerprinting** - Detailed service versions
* **Script Scanning** (-sC) - Automated vulnerability scripts
* **OS Detection** (-O) - Operating system fingerprinting
* **Traceroute** --traceroute - Network path analysis

### 🔧 **Advanced Features**

* **IPv6 Support** (-6) - Full IPv6 capability
* **NSE Scripts** - Lua scripting engine
* **NSE Categories** - auth, brute, default, discovery, etc.
* **Timing Templates** (-T0 to -T5) - Performance control
* **Decoy Scanning** (-D) - IP address spoofing
* **Fragmentation** (-f) - Packet fragmentation

## 🚀 Installation

### Linux Installation

```bash
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install nmap

# CentOS/RHEL/Fedora
sudo dnf install nmap

# Arch Linux
sudo pacman -S nmap

# From source
wget https://nmap.org/dist/nmap-7.93.tar.bz2
tar xjf nmap-7.93.tar.bz2
cd nmap-7.93
./configure
make
sudo make install
```

### macOS Installation

```bash
# Using Homebrew
brew install nmap

# Using MacPorts
sudo port install nmap

# Download DMG from https://nmap.org/download.html
```

### Windows Installation

```powershell
# Download installer from https://nmap.org/download.html
# Run nmap-7.93-setup.exe
# Add to PATH during installation

# Or using Chocolatey
choco install nmap

# Or using Winget
winget install --id=Insecure.Nmap -e
```

### Docker Installation

```bash
# Pull Nmap image
docker pull instrumentisto/nmap

# Run container
docker run --rm -it instrumentisto/nmap nmap -sS scanme.nmap.org
```

## 🔧 Basic Usage

### Port Scanning Basics

```bash
# Basic port scan (most common 1000 TCP ports)
nmap target.com

# Scan specific ports
nmap -p 80,443,8080 target.com

# Scan port range
nmap -p 1-65535 target.com

# Fast scan (-F scans 100 most common ports)
nmap -F target.com

# Scan all TCP ports
nmap -p- target.com
```

### Host Discovery

```bash
# Ping scan (discover hosts, no port scan)
nmap -sn 192.168.1.0/24

# List scan (simply list targets without sending packets)
nmap -sL 192.168.1.0/24

# Disable ping discovery (assume host is up)
nmap -Pn target.com

# Skip DNS resolution (faster scanning)
nmap -n 192.168.1.0/24
```

### Service Detection

```bash
# Service version detection
nmap -sV target.com

# OS detection
nmap -O target.com

# Aggressive scan (enables OS detection, version detection, etc.)
nmap -A target.com

# Script scanning with default scripts
nmap -sC target.com

# Script scanning with specific scripts
nmap --script vuln target.com
```

## 🎯 Common Use Cases

### 1. **Basic Network Reconnaissance**

```bash
# Scan a single host
nmap target.com

# Scan an entire subnet
nmap 192.168.1.0/24

# Scan multiple hosts
nmap 192.168.1.1 192.168.1.5 192.168.1.10

# Scan from file
nmap -iL targets.txt
```

### 2. **Vulnerability Scanning**

```bash
# Run default vulnerability scripts
nmap --script vuln target.com

# Scan for specific vulnerabilities
nmap --script smb-vuln-ms17-010 target.com

# Check for web vulnerabilities
nmap --script http-vuln-* target.com
```

### 3. **Firewall Evasion**

```bash
# SYN scan (stealthier than TCP connect)
nmap -sS target.com

# Fragment packets to bypass firewalls
nmap -f target.com

# Use decoy IP addresses
nmap -D RND:10 target.com

# Source port manipulation
nmap -g 53 target.com

# Idle scan using zombie host
nmap -sI zombie.target.com target.com
```

### 4. **Service Enumeration**

```bash
# Quick service detection
nmap -sV --version-intensity 5 target.com

# Web server enumeration
nmap -p 80,443 --script http-enum target.com

# SMB enumeration
nmap -p 139,445 --script smb-enum-shares target.com

# SSH enumeration
nmap -p 22 --script ssh2-enum-algos target.com
```

## 🔍 Advanced Scanning Techniques

### Timing Templates

```bash
# Paranoid (T0) - Very slow, avoids IDS
nmap -T0 target.com

# Sneaky (T1) - Slower than default
nmap -T1 target.com

# Polite (T2) - Slower than normal
nmap -T2 target.com

# Normal (T3) - Default timing
nmap -T3 target.com

# Aggressive (T4) - Faster scanning
nmap -T4 target.com

# Insane (T5) - Very fast, may miss ports
nmap -T5 target.com
```

### Custom Scanning

```bash
# Custom port specification
nmap -p T:80,U:53 target.com  # TCP 80, UDP 53

# Multiple port ranges
nmap -p 80-443,8080,9000-9100 target.com

# Excluding ports
nmap -p- --exclude-ports 25,53 target.com

# Randomizing scan order
nmap -r target.com  # Don't randomize
nmap target.com     # Default: randomize
```

### Script Scanning

```bash
# Run specific script
nmap --script http-title target.com

# Run script category
nmap --script "auth" target.com

# Run multiple scripts
nmap --script smb-os-discovery.nse,smb-vuln-ms17-010.nse target.com

# Run scripts with arguments
nmap --script http-sql-injection --script-args http-sql-injection.db=mysql target.com

# List available scripts
nmap --script-help all
```

## 📊 Output Formats

### Normal Output

```bash
# Save to file
nmap -oN scan.txt target.com

# Append to file
nmap -oA scan --append-output target.com
```

### XML Output

```bash
# Generate XML output
nmap -oX scan.xml target.com

# XML with all information
nmap -oA scan -v -A target.com
```

### Grepable Output

```bash
# Grepable format for parsing
nmap -oG scan.txt target.com

# Extract open ports from grepable output
grep "open" scan.txt
```

### All Formats

```bash
# Generate all formats at once
nmap -oA scan target.com  # Creates scan.nmap, scan.xml, scan.gnmap
```

## 🔧 Nmap Scripting Engine (NSE)

### Script Categories

* **auth** - Authentication bypass scripts
* **brute** - Brute force attacks
* **default** - Default scripts run with -sC
* **discovery** - Host discovery scripts
* **dos** - Denial of service scripts
* **exploit** - Exploitation scripts
* **external** - Scripts that use external services
* **fuzzer** - Fuzzing scripts
* **intrusive** - Intrusive scripts
* **malware** - Malware detection
* **safe** - Safe scripts (won't crash services)
* **version** - Version detection scripts
* **vuln** - Vulnerability detection scripts

### Popular Scripts

```bash
# HTTP scripts
nmap --script http-enum target.com
nmap --script http-title target.com
nmap --script http-sql-injection target.com
nmap --script http-vuln-cve2017-5638 target.com

# SMB scripts
nmap --script smb-os-discovery target.com
nmap --script smb-vuln-ms17-010 target.com
nmap --script smb-enum-shares target.com

# SSL/TLS scripts
nmap --script ssl-enum-ciphers target.com
nmap --script ssl-heartbleed target.com

# Discovery scripts
nmap --script dns-brute target.com
nmap --script whois-domain target.com
```

## 📈 Performance Optimization

### Scan Optimization

```bash
# Parallel scanning (default is 100 threads)
nmap -T4 --min-parallelism 100 target.com

# Host timeout settings
nmap --host-timeout 30m target.com

# Scan delay to avoid detection
nmap --scan-delay 1s target.com

# Packet rate limiting
nmap --max-rate 100 target.com
```

### Large-Scale Scanning

```bash
# Scan multiple subnets
nmap 192.168.0.0/16 10.0.0.0/8

# Randomize targets
nmap -iR 1000  # Scan 1000 random hosts

# Exclude specific hosts
nmap 192.168.1.0/24 --exclude 192.168.1.1,192.168.1.100
```

## 🔗 Integration and Automation

### Python Integration

```python
import python-nmap

# Initialize scanner
nm = python-nmap.PortScanner()

# Scan host
nm.scan('192.168.1.1', '22-443')

# Get results
for host in nm.all_hosts():
    print(f"Host: {host} ({nm[host].hostname()})")
    print(f"State: {nm[host].state()}")
    for proto in nm[host].all_protocols():
        print(f"Protocol: {proto}")
        ports = nm[host][proto].keys()
        for port in ports:
            print(f"Port: {port}\tState: {nm[host][proto][port]['state']}")
```

### Bash Automation

```bash
#!/bin/bash
# Network discovery script

TARGETS="192.168.1.0/24"
OUTPUT_DIR="scan_results"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p $OUTPUT_DIR

# Ping scan to discover hosts
nmap -sn $TARGETS -oN $OUTPUT_DIR/ping_scan_$DATE.txt

# Port scan discovered hosts
for ip in $(cat $OUTPUT_DIR/ping_scan_$DATE.txt | grep "Nmap scan report" | awk '{print $5}'); do
    echo "Scanning $ip..."
    nmap -sV -oA $OUTPUT_DIR/port_scan_${ip}_$DATE $ip
done

echo "Scan completed. Results saved to $OUTPUT_DIR"
```

## 🎓 Learning Resources

### Official Documentation

* [Nmap Official Guide](https://nmap.org/book/)
* [Nmap Reference Guide](https://nmap.org/docs/man/)
* [NSE Documentation](https://nmap.org/nsedoc/)
* [Fyodor's Blog](https://insecure.org/blog/)

### Practice Targets

* **scanme.nmap.org** - Official Nmap test target
* **pentestlab.com** - Legal penetration testing lab
* **TryHackMe** - Hands-on cybersecurity training
* **Hack The Box** - Online penetration testing labs

## 📊 Comparison with Other Tools

| Feature          | Nmap          | Masscan   | ZMap      | Unicornscan |
| ---------------- | ------------- | --------- | --------- | ----------- |
| **Speed**        | Medium        | Very Fast | Very Fast | Fast        |
| **Features**     | Comprehensive | Basic     | Basic     | Medium      |
| **NSE Scripts**  | ✅             | ❌         | ❌         | ❌           |
| **OS Detection** | ✅             | ❌         | ❌         | Limited     |
| **IPv6 Support** | ✅             | ❌         | ❌         | Limited     |
| **Ease of Use**  | Medium        | Easy      | Easy      | Medium      |

## 🔧 Troubleshooting

### Common Issues

```bash
# Permission denied (needs root/admin)
sudo nmap -sS target.com

# Host appears down (try ping scan first)
nmap -sn target.com

# Slow scanning (use timing templates)
nmap -T4 target.com

# DNS resolution issues (use -n flag)
nmap -n 192.168.1.0/24

# Rate limiting issues (add delays)
nmap --scan-delay 1s target.com
```

### Debug Mode

```bash
# Verbose output
nmap -v target.com

# Very verbose output
nmap -vv target.com

# Debug packet tracing
nmap -d target.com

# Save debugging info
nmap --reason --stats-every 10s target.com
```

## 🛡️ Security Considerations

### Legal and Ethical Use

* **Authorization**: Only scan networks you own or have permission to test
* **Documentation**: Keep records of authorization
* **Impact**: Consider network impact before scanning
* **Stealth**: Use appropriate scanning techniques for the environment

### Detection Evasion

```bash
# Use timing templates to avoid detection
nmap -T2 --scan-delay 2s target.com

# Use decoys to obscure source
nmap -D decoy1,decoy2,ME target.com

# Fragment packets to bypass IDS/IPS
nmap -f target.com

# Randomize source ports
nmap --source-port 53 target.com
```

### Network Etiquette

* **Rate Limiting**: Avoid overwhelming target networks
* **Business Hours**: Scan during appropriate times
* **Notification**: Inform network administrators when possible
* **Documentation**: Document findings responsibly

***

**⚠️ Legal Notice**: Only use Nmap on networks you own or have explicit permission to scan. Unauthorized network scanning is illegal in most jurisdictions.

**⚡ Pro Tip**: Start with basic scans (-sS -sV) before running aggressive scans. Always consider the network impact and use appropriate timing templates.

*📅 Last Updated: 2024*
