Nmap 101: Mapping Your Target’s Attack Surface
Welcome back to the “100s Series”! After exploring network traffic analysis with tcpdump and Wireshark, it’s time to shift from passive observation to active reconnaissance. Nmap (short for “Network Mapper”) remains a cornerstone tool for network discovery and security auditing, turning hidden network infrastructures into comprehensive maps of potential attack surfaces. This comprehensive walkthrough will teach you to discover, enumerate, and analyze network targets with surgical precision.
Important: Network scanning should only be performed on networks you own or have explicit written permission to test. Unauthorized scanning is illegal in most jurisdictions and may violate computer crime laws, privacy regulations, and terms of service. Always obtain proper authorization before conducting any network reconnaissance activities.
Table of contents
- Introduction
- Understanding network discovery fundamentals
- Basic host discovery techniques
- Port scanning strategies
- Service enumeration and fingerprinting
- Advanced scanning techniques
- Nmap Scripting Engine (NSE)
- Output formats
- Wrap-up
1. Introduction
Nmap¹ represents one of the most essential tools in cybersecurity, network administration, and penetration testing. Created by Gordon Lyon (also known as Fyodor) in 1997, this free and open-source utility has evolved from a simple port scanner into a comprehensive network discovery and security auditing platform. Unlike passive monitoring tools like tcpdump and Wireshark, Nmap actively probes networks to reveal their structure, identify live hosts, enumerate services, and fingerprint operating systems.
Nmap’s role in the reconnaissance phase
In the classic cyber kill chain², Nmap operates primarily during the reconnaissance phase, where attackers (or security professionals) gather intelligence about their targets.
This active reconnaissance provides:
- Network topology mapping: Understanding how systems connect and communicate
- Asset inventory: Identifying all accessible systems and services
- Attack surface analysis: Discovering potentially vulnerable services and configurations
- Security posture assessment: Evaluating defensive measures and monitoring capabilities
Why Nmap matters for security professionals
Whether you’re a network administrator, a security analyst, or penetration tester, Nmap serves multiple critical functions:
- Vulnerability assessment: Identifying exposed services that shouldn’t be accessible
- Network inventory: Maintaining accurate asset databases for compliance and management
- Security monitoring: Detecting unauthorized services or configuration changes
- Incident response: Quickly mapping compromised network segments during investigations
- Compliance auditing: Verifying that security policies are properly implemented
The tool’s versatility extends beyond simple port scanning. Modern Nmap includes capabilities for OS detection, service version identification, vulnerability scanning through its scripting engine, and even basic exploitation through specialized scripts.
Installing Nmap
Nmap installation varies by operating system but remains straightforward across all platforms:
Linux:
- Debian-based:
sudo apt install nmap - Fedora-based:
sudo dnf install nmap - Arch-based:
sudo pacman -S nmap
Windows:
- Download the installer from https://nmap.org/download.html
- Choose between command-line only or include Zenmap (GUI)
- Run the installer with administrator privileges
macOS:
- Download the .dmg installer from https://nmap.org/download.html
- Or use Homebrew:
brew install nmap
For comprehensive functionality, install the complete Nmap suite, which includes:
- nmap: The core scanning engine
- zenmap: Graphical interface for Nmap
- ncat: Enhanced netcat replacement
- ndiff: Utility for comparing scan results
- nping: Packet generation and response analysis tool
For the examples in this article, I used Nmap 7.95 running on Ubuntu 25.04 (plucky). Version differences may affect some advanced features and script availability.
2. Understanding network discovery fundamentals
Before diving into specific scanning techniques, understanding the underlying principles of network discovery helps optimize your approach and interpret results accurately.
Network layers and discovery methods
Nmap operates across multiple layers of the OSI model³, using different techniques depending on the target environment and scanning objectives:
Layer 2 (Data Link): ARP Discovery
Within local network segments, Nmap can perform ARP (Address Resolution Protocol) discovery to identify active hosts. This method proves particularly effective because:
- ARP requests typically aren’t filtered by host firewalls
- All network-capable devices must respond to ARP to function properly
- ARP discovery works even when ICMP is blocked
Example ARP scan: nmap -PR 192.168.1.0/24
Layer 3 (Network): ICMP Discovery
Traditional ping-based discovery uses ICMP echo requests, though modern networks increasingly filter these packets:
- ICMP Echo (ping):
nmap -PE <target> - ICMP Timestamp:
nmap -PP <target> - ICMP Address Mask:
nmap -PM <target>
Layer 4 (Transport): TCP/UDP Discovery
When ICMP is blocked, TCP and UDP-based discovery often succeeds:
- TCP SYN ping:
nmap -PS80,443 <target> - TCP ACK ping:
nmap -PA80,443 <target> - UDP ping:
nmap -PU53,161 <target>
Target specification methods
Nmap accepts various target specification formats, enabling flexible scanning strategies:
- Single IP, e.g.:
nmap 192.168.1.100 - IP range, e.g.:
nmap 192.168.1.1-100 - CIDR notation, e.g.:
nmap 192.168.1.0/24 - Host name, e.g.:
nmap example.com - Multiple targets, e.g.:
nmap 192.168.1.1 192.168.1.5 example.com - Input file, e.g.:
nmap -iL targets.txt - Exclude targets, e.g.:
nmap 192.168.1.0/24 --exclude 192.168.1.1
Understanding scan timing
Nmap’s timing affects both scan speed and detectability. The tool provides six timing templates:
Example with timing: nmap -T4 192.168.1.0/24
3. Basic host discovery techniques
Host discovery forms the foundation of network reconnaissance, determining which IP addresses have active systems before conducting more intensive scans.
The ping sweep
The classic network sweep identifies active hosts across a range of IP addresses. Nmap’s default host discovery combines multiple techniques for maximum effectiveness:
nmap -sn <target>
This command performs a “ping sweep” without port scanning (-sn flag), using multiple ping techniques automatically.
Again, scanning networks or hosts without explicit permission is often illegal and can have serious consequences, including legal action or being blacklisted by network administrators. Always ensure you have authorization before scanning any target outside your own environment. For safe and legal practice, you can:
Scan your own local network or devices you own, set up local virtual machines or containers to create a controlled lab environment, use intentionally vulnerable test VMs such as Metasploitable or platforms like TryHackMe and Hack The Box that provide legal practice targets, or
Use the officially sanctioned public host scanme.nmap.org, which is provided by the Nmap project for light, non-aggressive scanning. However, be mindful of their rules: do not scan aggressively, limit your scanning frequency, and avoid resource-intensive scan types.
Customizing host discovery
Different network environments require adapted discovery strategies:
Corporate networks with ICMP filtering
Many corporate networks block ICMP traffic, requiring alternative approaches:
- TCP SYN ping to common ports:
nmap -PS22,80,443 192.168.1.0/24 - TCP ACK ping (useful against stateful firewalls):
nmap -PA80 192.168.1.0/24 - UDP ping to common services:
nmap -PU53,161 192.168.1.0/24
Local network segments
For maximum coverage on local networks, combine multiple techniques: nmap -PE -PP -PM -PS21,22,23,25,53,80,110,111,135,139,143,443,993,995 -PA80,113,443,10042 -PU40125 192.168.1.0/24
Disable ping (assume all hosts are up)
When targeting specific known hosts or working through proxies: nmap -Pn <target>. The -Pn flag treats all specified hosts as online, skipping host discovery entirely.
Analyzing discovery results
Understanding Nmap’s output helps interpret network topology.
Key information includes:
- Latency: Response time indicating network proximity
- MAC addresses: Available for local network segments, useful for device identification
- Vendor information: Derived from MAC address OUI (Organizationally Unique Identifier)
DNS considerations during discovery
Nmap performs reverse DNS lookups by default, which can:
- Reveal internal naming conventions
- Slow down scans significantly
- Generate DNS query logs
Control DNS behavior with:
- Skip DNS resolution:
nmap -n <target> - Force DNS resolution:
nmap -R <target> - Use custom DNS servers:
nmap --dns-servers 8.8.8.8,1.1.1.1 <target>
4. Port scanning strategies
Port scanning reveals which services are accessible on discovered hosts, forming the core of Nmap’s functionality. Nmap classifies ports into six states:
TCP Connect Scan
The most basic scan type, completing full TCP three-way handshakes:
nmap -sT <target>
Advantages:
- Works without special privileges
- Highly accurate for determining open ports
- Doesn’t require raw socket access
Disadvantages:
- Easily detected and logged
- Slower than other scan types
- May trigger intrusion detection systems
TCP SYN Scan
The default scan type when run with appropriate privileges, sending SYN packets without completing connections:
nmap -sS <target>
Advantages:
- Faster than connect scans
- Less likely to be logged by applications
- Stealthier than full connections
Disadvantages:
- Requires raw socket privileges (root/administrator)
- May still trigger network monitoring
UDP Scan (-sU)
UDP services require different scanning approaches due to the connectionless protocol:
nmap -sU <target>
Challenges with UDP scanning:
- Slower than TCP scans
- Difficulty distinguishing filtered from open ports
- Rate limiting by many systems
Optimization strategies:
- Scan common UDP ports only:
nmap -sU --top-ports 100 <target> - Combine with version detection:
nmap -sU -sV <target> - Increase timing for faster results:
nmap -sU -T4 <target>
Port specification and ranges
Control which ports Nmap scans using various specification methods:
- Specific ports:
nmap -p 22,80,443 <target> - Port ranges:
nmap -p 1-1000 <target> - Top 1000 most common ports (default):
nmap <target> - Top n ports, e.g., top 100:
nmap --top-ports 100 <target> - Exclude specific ports:
nmap -p 1-1000 --exclude-ports 135,139 <target>
Scan optimization strategies
Fast scanning for large networks
When scanning many hosts, optimize for speed:
- Fast scan of top 100 ports:
nmap -T4 --top-ports 100 192.168.1.0/24 - Skip host discovery and scan specific ports:
nmap -Pn -p 22,80,443 -T4 192.168.1.0/24
Comprehensive scanning for specific targets
Get january1073’s stories in your inbox
Join Medium for free to get updates from this writer.
For detailed analysis of known targets:
- Comprehensive TCP scan:
nmap -p- -T4 <target> - Combined TCP and UDP scan:
nmap -sSU -T4 <target> - All TCP ports with service detection:
nmap -p- -sV -T4 <target>
5. Service enumeration and fingerprinting
Identifying specific services and versions running on open ports transforms basic port scan results into actionable intelligence.
Service version detection
Nmap’s service detection probes open ports to identify running services and their versions:
- Basic service detection:
nmap -sV <target> - Intensity levels (0–9, default 7):
nmap -sV --version-intensity 5 <target> - All probes for maximum accuracy:
nmap -sV --version-all <target>
Service detection intensity levels:
Operating system detection
OS fingerprinting analyzes TCP/IP stack behavior to identify target operating systems:
- Basic OS detection:
nmap -O <target> - Aggressive OS detection:
nmap -O --osscan-guess <target> - Limit OS scan attempts:
nmap -O --max-os-tries 2 <target>
OS detection techniques:
- TCP sequence prediction: Analyzing TCP sequence number generation
- IP ID sequence generation: Examining IP identification field patterns
- TCP timestamp options: Evaluating timestamp implementation
- Window size analysis: Studying TCP window scaling behavior
Example OS detection output:
Banner grabbing and service interaction
Beyond automated detection, Nmap can interact with services to gather additional information:
- Enable script scanning for enhanced enumeration:
nmap -sC <target>
- Specific service scripts:
nmap --script=http-enum <target>
- Banner grabbing:
nmap --script=banner <target>
More details on scanning using scripts will follow later, in Chapter 7.
Aggressive scanning combination
Combine multiple detection techniques for comprehensive reconnaissance:
- Aggressive scan (OS detection, version detection, script scanning, traceroute):
nmap -A <target> - Custom aggressive combination:
nmap -sS -sV -O -sC -T4 <target>
Understanding service signatures
Service signatures help identify applications even on non-standard ports:
- HTTP service on port 8080:
nmap -sV -p 8080 <target>
Common service signatures Nmap recognizes:
- Web servers: Apache, Nginx, IIS with version information
- SSH servers: OpenSSH versions and configurations
- Database services: MySQL, PostgreSQL, MSSQL with version details
- Mail servers: Postfix, Exchange, sendmail configurations
- FTP servers: vsftpd, ProFTPD with banner information
Custom service probes
For specialized environments, create custom service probes:
nmap --datadir <path_to_custom_probes> -sV <target>
6. Advanced scanning techniques
Beyond basic port scanning, Nmap offers sophisticated techniques for specialized scenarios and evasion requirements.
Idle scan (Zombie scan)
One of Nmap’s most clever techniques, using a third-party “zombie” host to scan targets indirectly:
- Identify potential zombies:
nmap -O -v <zombie_candidate> - Perform idle scan:
nmap -sI <zombie_host>.<port> <target>
How idle scanning works:
- Nmap analyzes the zombie host’s IP ID sequence
- Sends spoofed packets to the target, appearing to come from the zombie, and
- Monitors zombie’s IP ID changes to determine port states.
The target never sees the scanner’s real IP address.
Requirements for effective idle scanning:
- Zombie host with predictable IP ID sequence,
- Zombie host with no network activity (“idle”), and
- Target and zombie on same network segment (preferred).
FTP bounce scan
Exploits misconfigured FTP servers to scan other hosts: nmap -b <ftp_server> <target>
This technique leverages the FTP PORT command to make the FTP server connect to arbitrary hosts and ports, effectively using the FTP server as a proxy scanner. This allowed attackers to hide their IP address, bypass firewall rules, and access internal systems via trusted FTP servers.
But… Almost all modern FTP servers disable PORT command relaying or restrict it. The technique is slow, unreliable, and easy to detect. Many FTP servers block arbitrary third-party connections. As a result, this option is mostly for historical or academic purposes.
However, you might use this in controlled penetration tests on legacy systems, for training or academic demonstrations of old attack techniques, or to test an in-house FTP server that you control and configured for bounce support.
Fragmentation and decoy scans
IP fragmentation
Split packets across multiple fragments to evade simple packet filtering:
- Fragment packets into 8-byte pieces:
nmap -f <target> - Fragment into 16-byte pieces:
nmap -ff <target> - Custom fragment size:
nmap --mtu 24 <target>
But be aware that packet fragmentation in scans is rarely effective against modern systems. It is also mostly useful for teaching, testing, or targeting old equipment. A big red flag for IDS/IPS if used in the wild.
If you need modern stealth scanning, you’re usually better off with:
-sS(SYN scan)--data-length(add padding to evade signature detection)--ttl,--source-port, or decoy scanning (-D)
Decoy scanning
Hide your scan among multiple decoy IP addresses:
- Use specific decoys (controlled obfuscation):
nmap -D <decoy_1>,<decoy_2>,ME <target>
ME tells Nmap to send the real probes from your machine. The rest are spoofed decoy IPs — they do not need to be reachable.
- Random decoys (quick, high-noise anonymization):
nmap -D RND:10 <target>
Requires --spoof-mac or root privileges to craft raw packets. Random IPs might be blacklisted, cause scanning delays, or be filtered.
- Mix of specific and random decoys (complex masking), e.g.:
nmap -D 192.168.1.1,192.168.1.2,RND:5,ME target.com
Mix known local decoys (e.g. in same subnet) and random IPs. Blend into real traffic + global noise. Very useful in lab exercises or simulating advanced attacker behavior.
Use decoys if you’re testing detection evasion or you want to simulate APT-like scan behavior. Don’t use decoys on production networks without consent or in places where spoofing might be blocked upstream (e.g. cloud VMs, firewalled NATs).
If you think it makes you invisible — it doesn’t.
Source port manipulation
Some firewalls permit traffic from specific source ports:
- Use source port 53 (DNS):
nmap --source-port 53 <target> - Use source port 20 (FTP-DATA):
nmap -g 20 <target>
Common privileged source ports that may bypass filters:
- 53: DNS queries
- 20: FTP data connections
- 67/68: DHCP
- 123: NTP
TCP window scan
Exploits differences in RST packet window sizes to identify ports:
nmap -sW <target>
This advanced technique works by:
- Sending RST packets to various ports
- Analyzing the TCP window size in responses
- Different window sizes may indicate open vs. closed ports
Null, FIN, and Xmas scans
These scans send unusual TCP flag combinations to elicit responses:
- Null scan (no flags set):
nmap -sN <target> - FIN scan (FIN flag only):
nmap -sF <target> - Xmas scan (FIN, PSH, URG flags):
nmap -sX <target>
Theory: RFC-compliant systems should respond with RST packets to these unusual combinations when ports are closed, but send no response when ports are open.
Limitations
- Many modern systems don’t follow RFC specifications exactly
- Windows systems typically respond identically regardless of port state
- Stateful firewalls often drop these packets
7. Nmap Scripting Engine (NSE)
The Nmap Scripting Engine transforms Nmap from a port scanner into a comprehensive vulnerability assessment and exploitation framework.
NSE fundamentals
NSE scripts are written in Lua and organized into categories:
- auth: Authentication testing
- broadcast: Network broadcast discovery
- brute: Brute force attacks
- default: Scripts run with -sC
- discovery: Host and service discovery
- dos: Denial of service testing
- exploit: Exploitation attempts
- external: Scripts requiring external resources
- fuzzer: Fuzzing tests
- intrusive: Aggressive tests that may crash services
- malware: Malware detection
- safe: Safe scripts unlikely to crash services
- version: Version detection enhancement
- vuln: Vulnerability detection
Basic script usage
- Run default scripts:
nmap -sC <target> - Run all scripts in a category (see the categories above; here, e.g., vulnerability detection):
nmap --script=vuln <target> - Run specific scripts (here, e.g.,
http-enumandhttp-headers):nmap --script=http-enum,http-headers <target> - Run scripts with wildcards (here, e.g., all
httpscipts:nmap --script="http-*" <target>
Essential NSE scripts for security assessment
On most Linux distributions (Debian, Ubuntu, Fedora, Arch, etc.), the Nmap scripts are located in:
/usr/share/nmap/scripts
Expect roughly 600–700 scripts, depending on your Nmap version. For example, my installation of Nmap 7.95 was shipped with 610 scripts.
For detailed descriptions and categories of each script, you can refer to the official NSE documentation at https://nmap.org/nsedoc/.
Here three examples:
Web application testing
- Enumerate web directories and files:
nmap --script=http-enum <target> - Check for common vulnerabilities:
nmap --script=http-vuln-* <target> - Enumerate HTTP methods:
nmap --script=http-methods <target> - Detect web application firewalls:
nmap --script=http-waf-detect <target>
Database security testing
- MySQL information gathering:
nmap --script=mysql-info <target> - Database brute force:
nmap --script=mysql-brute <target> - SQL injection testing:
nmap --script=mysql-injection <target>
SMB / NetBIOS enumeration
- SMB version and information:
nmap --script=smb-os-discovery <target> - SMB vulnerability scanning:
nmap --script=smb-vuln-* <target> - Enumerate SMB shares:
nmap --script=smb-enum-shares <target>
Advanced script usage
Script arguments
Many scripts accept arguments for customization. Here, again, only some examples for illustration:
- HTTP brute force :
nmap --script=http-brute --script-args http-brute.path=/admin <target> - DNS brute force with custom hostname list:
nmap --script=dns-brute --script-args dns-brute.hostlist=<hosts.txt> <target> - SNMP brute force with custom community strings:
nmap --script=snmp-brute --script-args snmp-brute.communitiesdb=<communities.txt> <target>
Script categories for different purposes
- Safe reconnaissance:
nmap --script=safe <target> - Vulnerability assessment:
nmap --script=vuln <target> - Brute force testing (use carefully):
nmap --script=brute <target> - Discovery and enumeration:
nmap --script=discovery <target>
Custom script development
And because the 600–700 built-in scripts are not enough, you can also create custom NSE scripts for specialized testing.
Here a basic NSE script template:
-- Basic NSE script template
local http = require "http"
local nmap = require "nmap"
local stdnse = require "stdnse"
description = [[
Custom script description here.
]]
author = "Your Name"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"discovery", "safe"}
portrule = function(host, port)
return port.protocol == "tcp" and port.number == 80
end
action = function(host, port)
local response = http.get(host, port, "/")
if response.status == 200 then
return "Custom check passed"
end
return nil
endSave as custom-script.nse and use with:
nmap --script=custom-script <target>
Example
Below you’ll find an example custom Nmap NSE script tailored for testing against scanme.nmap.org. This script performs an HTTP GET request to the root path /, checks for a successful HTTP 200 response, and attempts to extract the Server header, if present.
local http = require "http"
local nmap = require "nmap"
local stdnse = require "stdnse"
description = [[
Performs a basic HTTP check on port 80 of a target. If the response status is 200,
it extracts and reports the 'Server' header (if available). Designed for use with scanme.nmap.org.
]]
author = "january1073"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"discovery", "safe"}
portrule = function(host, port)
return port.protocol == "tcp" and port.number == 80
end
action = function(host, port)
local response = http.get(host, port, "/")
if not response then
return "No response received"
end
if response.status == 200 then
local server_header = response.header["server"]
if server_header then
return string.format("HTTP 200 OK received. Server header: %s", server_header)
else
return "HTTP 200 OK received. No Server header found."
end
else
return string.format("Unexpected HTTP status: %d", response.status)
end
end- Save the script as
http-scanme-check.nse - Move it to your Nmap scripts directory:
sudo mv http-scanme-check.nse /usr/share/nmap/scripts - Update the script database:
sudo nmap --script-updatedb - Run it against scanme.nmap.org:
nmap -p 80 --script http-scanme-check.nse scanme.nmap.org
Script performance optimization
Not least, Nmap provides you with various ways to optimize script performance, e.g.:
- Control script execution timing:
nmap --script=vuln --script-args timeout=30s <target> - Limit script threads:
nmap --script=brute --script-args threads=5 <target> - Debug script execution:
nmap --script=http-enum --script-trace <target>
The examples were primarily intended to demonstrate that the possibilities with Nmap are almost limitless.
8. Output formats
Effective reporting transforms raw Nmap data into actionable intelligence for security teams and management. Nmap supports multiple output formats for different use cases:
- Normal output (default):
nmap <target> - Verbose output:
nmap -v <target> - Save normal output to a file:
nmap -oN <scan_results.txt> <target> - XML output for parsing:
nmap -oX <scan_results.xml> <target> - Grepable output for text processing:
nmap -oG <scan_results.gnmap> <target> - All formats simultaneously:
nmap -oA <scan_results> <target>
Depending on the format you choose, you can reuse the output data, for instance, for automated processing and integration using custom reporting scripts or in security tools (SIEM, vulnerability management, automated reporting workflows, ticketing systems, compliance reporting, performance metrics and optimization, etc.). However, this would be too much for a “101” article. I’ll cover this in a later article. If you don’t want to miss it, follow me.
9. Wrap-up
Nmap stands as one of the most enduring and essential tools in cybersecurity, evolving from Gordon Lyon’s simple port scanner in 1997 into today’s comprehensive network reconnaissance platform. Through this guide, you’ve progressed from basic concepts to advanced techniques that form the backbone of professional network security assessment.
However, effective reconnaissance transcends tool operation — it requires thinking systematically about network architecture, security controls, and adversary perspectives. The methodology you’ve learned follows intelligence gathering principles used by both attackers and defenders:
- Systematic enumeration: Comprehensive coverage prevents blind spots that could hide critical vulnerabilities
- Layered analysis: Understanding how different network layers interact reveals attack paths that single-layer scans miss
- Context-aware scanning: Adapting techniques to specific environments maximizes both effectiveness and stealth
- Intelligence synthesis: Transforming raw scan data into actionable security insights
Ethical foundations
With reconnaissance capabilities comes responsibility. Always remember:
- Authorization first: Written permission isn’t just legal protection — it’s professional obligation
- Proportional response: Use the minimum scanning intensity necessary to achieve your objectives
- Responsible disclosure: Coordinate vulnerability reporting with system owners to enable patching before exposure
- Continuous education: Stay current with legal and ethical developments in your jurisdiction
Your journey with network reconnaissance has just begun. Use these capabilities responsibly, continue learning, and remember that the strongest networks are built by those who understand how they can be compromised.
Check out this: Nmap Cheatsheet
Engage through this interface: https://linktr.ee/january1073
Endnotes
- Nmap Network Scanning: https://nmap.org/
- Cyber Kill Chain: https://www.lockheedmartin.com/en-us/capabilities/cyber/cyber-kill-chain.html
- OSI Model: https://www.iso.org/iec-7498-1.html









