Network Port Scanning with Nmap
Table of Contents
- [Introduction](#introduction) - [Installation](#installation) - [Basic Concepts](#basic-concepts) - [Command Structure](#command-structure) - [Scan Types](#scan-types) - [Target Specification](#target-specification) - [Port Specification](#port-specification) - [Timing and Performance](#timing-and-performance) - [Output Formats](#output-formats) - [Advanced Features](#advanced-features) - [Practical Examples](#practical-examples) - [Security Considerations](#security-considerations) - [Troubleshooting](#troubleshooting)Introduction
Nmap (Network Mapper) is a powerful open-source network discovery and security auditing tool. Originally written by Gordon Lyon, Nmap has become the de facto standard for network reconnaissance and port scanning. It is designed to rapidly scan large networks, although it works fine against single hosts.
Nmap uses raw IP packets to determine what hosts are available on the network, what services those hosts are offering, what operating systems they are running, what type of packet filters/firewalls are in use, and dozens of other characteristics. While Nmap is commonly used for security audits, many systems and network administrators find it useful for routine tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime.
Key Features
| Feature | Description | |---------|-------------| | Host Discovery | Identify live hosts on networks | | Port Scanning | Determine open ports and services | | Service Detection | Identify service versions | | OS Detection | Fingerprint operating systems | | Scriptable Interaction | NSE (Nmap Scripting Engine) | | Output Flexibility | Multiple output formats | | IPv6 Support | Full IPv6 scanning capabilities | | Performance | Highly optimized scanning engine |
Installation
Linux (Ubuntu/Debian)
`bash
sudo apt update
sudo apt install nmap
`Linux (CentOS/RHEL/Fedora)
`bash
CentOS/RHEL
sudo yum install nmapFedora
sudo dnf install nmap`macOS
`bash
Using Homebrew
brew install nmapUsing MacPorts
sudo port install nmap`Windows
Download the installer from the official Nmap website (https://nmap.org/download.html) and follow the installation wizard.Verification
`bash
nmap --version
`Basic Concepts
Port States
Nmap categorizes ports into six states:
| State | Description | |-------|-------------| | Open | Application is actively accepting connections | | Closed | Port is accessible but no application is listening | | Filtered | Cannot determine if port is open due to packet filtering | | Unfiltered | Port is accessible but cannot determine if open or closed | | Open/Filtered | Cannot determine if port is open or filtered | | Closed/Filtered | Cannot determine if port is closed or filtered |
Protocol Types
| Protocol | Description | Common Ports | |----------|-------------|--------------| | TCP | Transmission Control Protocol | 80 (HTTP), 443 (HTTPS), 22 (SSH) | | UDP | User Datagram Protocol | 53 (DNS), 67/68 (DHCP), 161 (SNMP) | | SCTP | Stream Control Transmission Protocol | 2905, 3863, 4739 |
Command Structure
The basic Nmap command structure follows this pattern:
`bash
nmap [Scan Type] [Options] [Target Specification]
`
Essential Components
| Component | Purpose | Example | |-----------|---------|---------| | Scan Type | Defines how the scan is performed | -sS, -sT, -sU | | Options | Modify scan behavior | -p, -O, -A | | Target | Specifies what to scan | 192.168.1.1, google.com |
Scan Types
TCP Scans
#### SYN Scan (-sS) The default and most popular scan type, also known as "half-open" scanning.
`bash
nmap -sS target
`
Notes: - Sends SYN packet and waits for response - Does not complete TCP handshake - Stealthy and fast - Requires root privileges on Unix systems
#### TCP Connect Scan (-sT) Uses the system's connect() call to establish connections.
`bash
nmap -sT target
`
Notes: - Completes full TCP handshake - Does not require root privileges - More likely to be logged by target systems - Slower than SYN scan
#### ACK Scan (-sA) Used to map firewall rulesets and determine if ports are filtered.
`bash
nmap -sA target
`
Notes: - Sends ACK packets to ports - Cannot determine if ports are open - Useful for firewall analysis - Helps identify filtered vs unfiltered ports
UDP Scan (-sU)
Scans UDP ports, which are connectionless.`bash
nmap -sU target
`
Notes: - Much slower than TCP scans - Many UDP services don't respond to empty packets - Requires root privileges - Often combined with TCP scans
Specialized Scans
| Scan Type | Command | Purpose | |-----------|---------|---------| | NULL Scan | -sN | Sends packets with no flags set | | FIN Scan | -sF | Sends packets with FIN flag | | Xmas Scan | -sX | Sends packets with FIN, PSH, and URG flags | | Window Scan | -sW | Examines TCP window field | | Maimon Scan | -sM | Sends FIN/ACK packets |
Target Specification
Single Targets
`bash
IP address
nmap 192.168.1.100Hostname
nmap example.comIPv6 address
nmap 2001:db8::1`Multiple Targets
`bash
Multiple IPs
nmap 192.168.1.1 192.168.1.5 192.168.1.10IP range with dash
nmap 192.168.1.1-20CIDR notation
nmap 192.168.1.0/24Wildcard
nmap 192.168.1.*`Target Lists
`bash
From file
nmap -iL targets.txtExclude targets
nmap 192.168.1.0/24 --exclude 192.168.1.1,192.168.1.5Exclude from file
nmap 192.168.1.0/24 --excludefile exclude.txt`Advanced Target Specification
| Method | Syntax | Example | |--------|--------|---------| | Octet ranges | 192.168.1-3.1-50 | Scans multiple subnets | | Random targets | -iR [num] | nmap -iR 100 | | IPv6 targets | [IPv6] | nmap 2001:db8::/32 |
Port Specification
Default Behavior
Nmap scans the 1000 most common ports by default.Custom Port Ranges
`bash
Single port
nmap -p 80 targetMultiple ports
nmap -p 80,443,22 targetPort range
nmap -p 1-1000 targetAll ports
nmap -p- targetNamed ports
nmap -p http,https,ssh target`Protocol-Specific Ports
`bash
TCP ports only
nmap -p T:80,443 targetUDP ports only
nmap -p U:53,67 targetMixed protocols
nmap -p T:80,443,U:53,67 target`Common Port Categories
| Category | Ports | Services | |----------|-------|----------| | System Ports | 1-1023 | Well-known services | | User Ports | 1024-49151 | Registered services | | Dynamic Ports | 49152-65535 | Ephemeral ports |
Timing and Performance
Timing Templates
Nmap provides timing templates to balance speed and stealth:
| Template | Speed | Stealth | Command | |----------|-------|---------|---------| | T0 (Paranoid) | Very Slow | Maximum | -T0 | | T1 (Sneaky) | Slow | High | -T1 | | T2 (Polite) | Slow | Medium | -T2 | | T3 (Normal) | Normal | Normal | -T3 | | T4 (Aggressive) | Fast | Low | -T4 | | T5 (Insane) | Very Fast | Minimum | -T5 |
Custom Timing Options
`bash
Minimum delay between probes
nmap --scan-delay 1s targetMaximum delay between probes
nmap --max-scan-delay 10s targetMinimum packet rate
nmap --min-rate 100 targetMaximum packet rate
nmap --max-rate 1000 target`Parallelism Control
| Option | Description | Example | |--------|-------------|---------| | --min-hostgroup | Minimum parallel host scan groups | --min-hostgroup 10 | | --max-hostgroup | Maximum parallel host scan groups | --max-hostgroup 100 | | --min-parallelism | Minimum parallel probes | --min-parallelism 10 | | --max-parallelism | Maximum parallel probes | --max-parallelism 100 |
Output Formats
Standard Output Formats
| Format | Extension | Command | Description | |--------|-----------|---------|-------------| | Normal | .nmap | -oN | Human-readable format | | XML | .xml | -oX | Machine-parseable format | | Grepable | .gnmap | -oG | Grep-friendly format | | All formats | - | -oA | Saves in all three formats |
Output Examples
`bash
Normal output
nmap -oN scan_results.nmap targetXML output
nmap -oX scan_results.xml targetGrepable output
nmap -oG scan_results.gnmap targetAll formats with basename
nmap -oA scan_results target`Verbosity Control
`bash
Increase verbosity
nmap -v target nmap -vv targetDebugging information
nmap -d target nmap -dd targetQuiet mode
nmap -q target`Advanced Features
Service Version Detection
`bash
Basic version detection
nmap -sV targetIntensity levels (0-9)
nmap -sV --version-intensity 5 targetVersion detection with all ports
nmap -sV -p- target`Operating System Detection
`bash
OS detection
nmap -O targetAggressive OS detection
nmap -O --osscan-guess targetOS detection without port scan
nmap -O -Pn target`Script Scanning (NSE)
The Nmap Scripting Engine allows for advanced reconnaissance and vulnerability detection.
#### Script Categories
| Category | Purpose | Example Scripts | |----------|---------|-----------------| | auth | Authentication bypass | auth-owners, auth-spoof | | broadcast | Network broadcast discovery | broadcast-dhcp-discover | | brute | Brute force attacks | ssh-brute, ftp-brute | | default | Default safe scripts | http-title, ssl-cert | | discovery | Network discovery | dns-zone-transfer | | dos | Denial of service | http-slowloris | | exploit | Exploit vulnerabilities | ms17-010, eternal-blue | | external | External resources | whois-ip, geoip-geolocation | | fuzzer | Fuzzing attacks | http-form-fuzzer | | intrusive | Intrusive scripts | http-enum | | malware | Malware detection | http-malware-host | | safe | Safe scripts | banner, http-title | | version | Version detection | ssh-hostkey, ssl-cert | | vuln | Vulnerability detection | vuln, ssl-heartbleed |
#### Script Usage Examples
`bash
Run default scripts
nmap -sC targetRun specific script
nmap --script http-title targetRun script category
nmap --script vuln targetMultiple scripts
nmap --script "http-* and safe" targetScript with arguments
nmap --script http-form-brute --script-args userdb=users.txt,passdb=passwords.txt target`Aggressive Scanning
`bash
Aggressive scan (combines -O -sV -sC --traceroute)
nmap -A targetCustom aggressive combination
nmap -sS -sV -O -sC -p- target`Practical Examples
Basic Network Discovery
`bash
Discover live hosts on network
nmap -sn 192.168.1.0/24Quick scan of common ports
nmap -F targetScan specific service ports
nmap -p 80,443,22,21,25,53,110,995,993,143 target`Web Server Analysis
`bash
Comprehensive web server scan
nmap -p 80,443,8080,8443 -sV -sC targetHTTP-specific scripts
nmap -p 80,443 --script http-enum,http-headers,http-methods,http-robots.txt targetSSL/TLS analysis
nmap -p 443 --script ssl-enum-ciphers,ssl-cert,ssl-date target`Database Server Scanning
`bash
Common database ports
nmap -p 1433,3306,5432,1521,27017 -sV targetDatabase-specific scripts
nmap -p 3306 --script mysql-info,mysql-enum target nmap -p 1433 --script ms-sql-info,ms-sql-enum target nmap -p 5432 --script pgsql-brute target`Mail Server Analysis
`bash
Mail server ports
nmap -p 25,110,143,465,587,993,995 -sV targetSMTP enumeration
nmap -p 25 --script smtp-enum-users,smtp-commands targetMail server vulnerabilities
nmap -p 25,110,143 --script smtp-vuln-cve2010-4344,pop3-capabilities target`Comprehensive Security Audit
`bash
Full security scan
nmap -sS -sV -O -sC -p- -T4 -oA full_scan targetVulnerability assessment
nmap -sV --script vuln targetNetwork service discovery
nmap -sS -sV -p 1-65535 -T4 -A -v target`Security Considerations
Legal and Ethical Guidelines
| Consideration | Description | |---------------|-------------| | Authorization | Only scan networks you own or have explicit permission to test | | Scope | Stay within the defined scope of authorized testing | | Impact | Consider the potential impact on target systems | | Documentation | Maintain detailed logs of all scanning activities | | Disclosure | Follow responsible disclosure practices for vulnerabilities |
Stealth Techniques
`bash
Slow scan to avoid detection
nmap -sS -T1 --scan-delay 5s targetFragment packets
nmap -f targetUse decoys
nmap -D decoy1,decoy2,ME targetSpoof source port
nmap --source-port 53 targetRandom host order
nmap --randomize-hosts target1 target2 target3`Firewall Evasion
| Technique | Command | Description | |-----------|---------|-------------| | Fragment packets | -f | Split packets into fragments | | MTU specification | --mtu 16 | Specify custom MTU | | Decoy scanning | -D RND:10 | Use random decoys | | Idle zombie scan | -sI zombie_host | Use intermediate host | | Source port | --source-port 53 | Spoof source port | | Data length | --data-length 25 | Add random data to packets |
Troubleshooting
Common Issues and Solutions
| Issue | Cause | Solution | |-------|-------|---------| | Permission denied | Insufficient privileges | Run with sudo/administrator rights | | No response | Firewall blocking | Try different scan types or ports | | Slow scans | Conservative timing | Use faster timing template (-T4) | | Incomplete results | Rate limiting | Adjust timing and parallelism | | DNS resolution errors | DNS issues | Use IP addresses or --dns-servers |
Debugging Commands
`bash
Enable debugging
nmap -d targetPacket trace
nmap --packet-trace targetShow reason for port states
nmap --reason targetInterface and route information
nmap --iflist`Performance Optimization
`bash
Skip host discovery
nmap -Pn targetSkip DNS resolution
nmap -n targetOptimize for speed
nmap -T5 --min-rate 1000 --max-retries 1 targetParallel host scanning
nmap --min-hostgroup 50 --max-hostgroup 100 target`Network-Specific Considerations
| Network Type | Considerations | Recommended Approach | |--------------|----------------|----------------------| | Internal LAN | Less restrictive firewalls | Standard TCP SYN scans | | DMZ | Moderate filtering | Multiple scan types | | Internet | Heavy filtering | Stealth techniques | | Wireless | Variable connectivity | Conservative timing | | VPN | Encrypted tunnels | Standard scans with authentication |
Output Analysis Tips
`bash
Extract open ports from grepable output
grep "open" scan_results.gnmapFind hosts with specific services
grep "80/open" scan_results.gnmapParse XML output with xmlstarlet
xmlstarlet sel -t -v "//port[@portid='80']/../@addr" scan_results.xml`Conclusion
Nmap is an incredibly versatile and powerful tool for network discovery and security auditing. Its extensive feature set allows for everything from simple port scans to comprehensive security assessments. Understanding the various scan types, timing options, and advanced features enables security professionals to conduct thorough network reconnaissance while maintaining appropriate stealth and performance characteristics.
The key to effective Nmap usage lies in understanding the target environment, selecting appropriate scan techniques, and interpreting results correctly. Always ensure you have proper authorization before scanning networks, and consider the potential impact of your scanning activities on target systems.
Regular practice with different scan types and options will help develop proficiency with this essential security tool. The Nmap Scripting Engine provides additional capabilities for specialized testing scenarios, making Nmap suitable for both basic network discovery and advanced penetration testing engagements.