Loading content...
Before any attack can succeed, an adversary must understand their target. In physical warfare, this means scouts gathering intelligence on enemy positions, fortifications, and supply lines. In network security, this translates to reconnaissance—the systematic gathering of information about target systems, networks, and services.
Port scanning is the cornerstone of network reconnaissance. It is the digital equivalent of checking every door and window of a building to see which ones are open, what type of lock each uses, and what lies behind them. A port scan reveals the network's surface area—every service listening for connections becomes a potential entry point.
This page provides an exhaustive exploration of port scanning: how it works at the packet level, the spectrum of scanning techniques from stealthy to aggressive, how defenders detect scans, and what the scan results actually reveal about target systems.
Port scanning systems you don't own or have explicit authorization to test is illegal in most jurisdictions. This knowledge is presented for defensive purposes—understanding attacker techniques is essential for effective defense. Always obtain written authorization before scanning any network.
By mastering this page, you will: (1) Understand port scanning at the TCP/IP packet level, (2) Master multiple scanning techniques and their tradeoffs, (3) Interpret scan results to assess network security posture, (4) Recognize scan patterns as a defender, and (5) Understand the relationship between ports, services, and vulnerabilities.
To understand port scanning, we must first deeply understand what ports are and why they exist.
The fundamental problem:
An IP address identifies a computer on a network, but modern computers run dozens or hundreds of network-capable applications simultaneously. A web server, SSH daemon, email server, database, and numerous system services might all need to receive network traffic. How does the operating system know which application should receive an incoming packet?
The solution: Transport Layer Ports
The transport layer protocols (TCP and UDP) add a port number to each packet—a 16-bit unsigned integer ranging from 0 to 65,535. This number acts as a sub-address within the host, directing traffic to specific applications.
A socket is the combination of IP address + port number + protocol, creating a unique endpoint:
192.168.1.100:443/TCP → Web server accepting HTTPS
192.168.1.100:22/TCP → SSH daemon
192.168.1.100:53/UDP → DNS resolver
When a packet arrives, the OS kernel examines the destination port and routes the packet to the application that has bound to that port—or rejects the packet if nothing is listening.
| Range | Name | Purpose | Access Required |
|---|---|---|---|
| 0-1023 | Well-Known Ports | Standard services (HTTP, SSH, SMTP, DNS) | Root/Administrator (Unix-like systems) |
| 1024-49151 | Registered Ports | Vendor-specific applications (MySQL, PostgreSQL, Redis) | Standard user privileges |
| 49152-65535 | Dynamic/Ephemeral Ports | Temporary client-side connections, OS-assigned | Standard user privileges |
From a scanner's perspective, ports exist in three states: Open (a service is accepting connections), Closed (port is reachable but nothing listens), and Filtered (a firewall blocks access, preventing determination of state). Each state reveals information about the target's configuration.
Why port scanning matters:
Every open port represents:
A machine with only ports 22, 80, and 443 open presents a much smaller attack surface than one with 50 services running. Port scanning quantifies this exposure.
Most port scanning techniques exploit the behavior of TCP connection establishment. Understanding TCP's three-way handshake is essential for grasping how scans work and how they can be detected.
The Normal Three-Way Handshake:
Detailed breakdown:
Step 1: SYN (Synchronize)
Step 2: SYN-ACK (Synchronize-Acknowledge)
Step 3: ACK (Acknowledge)
Alternative responses:
| Response | Meaning | Port State |
|---|---|---|
| SYN-ACK | Service accepting connections | Open |
| RST (Reset) | Nothing listening | Closed |
| No response | Firewall dropping packets | Filtered |
| ICMP unreachable | Firewall rejecting packets | Filtered |
TCP flags are 6 bits in the TCP header: SYN (synchronize sequence numbers), ACK (acknowledgment field valid), FIN (no more data from sender), RST (reset connection), PSH (push data immediately), URG (urgent pointer valid). Port scans manipulate and observe these flags to determine port states without completing connections.
Resource implications:
The three-way handshake has significant implications for both scanning and defense:
For servers:
For scanners:
For defenders:
The TCP Connect Scan (also called full-open scan or vanilla scan) is the most straightforward scanning technique. It uses the operating system's standard connect() system call to attempt a full TCP connection to each target port.
How it works:
123456789101112131415161718192021222324252627282930313233343536373839404142
import socket def tcp_connect_scan(target_ip, port, timeout=1): """ Perform a TCP connect scan on a single port. Returns True if port is open, False otherwise. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) try: # This performs the full three-way handshake result = sock.connect_ex((target_ip, port)) if result == 0: # Connection successful - port is OPEN return True else: # Connection failed - port is CLOSED or FILTERED return False except socket.timeout: # Timeout - port is likely FILTERED return None finally: sock.close() def scan_port_range(target_ip, start_port, end_port): """Scan a range of ports on the target.""" open_ports = [] for port in range(start_port, end_port + 1): result = tcp_connect_scan(target_ip, port) if result: open_ports.append(port) print(f"Port {port}: OPEN") elif result is None: print(f"Port {port}: FILTERED (timeout)") return open_ports # Example usage (only scan systems you own!)# open_ports = scan_port_range("192.168.1.1", 1, 1024)TCP Connect scans are appropriate when: (1) You don't have root/admin privileges on your scanning system, (2) You're performing authorized internal audits where stealth isn't required, (3) You need maximum reliability and accuracy, or (4) You're just learning about port scanning.
The SYN Scan (also called half-open scan or stealth scan) is the most popular port scanning technique among security professionals. It exploits the TCP handshake by never completing the connection, reducing detectability and increasing speed.
How it works:
Key insight: By sending RST before the handshake completes, the connection never fully establishes. The target's application never sees the connection attempt—only the TCP/IP stack does.
Technical implementation:
SYN scanning requires raw socket access because we need to craft custom TCP packets rather than using the OS's connection logic. This requires root/administrator privileges on most systems.
Why it's called "stealth":
Historically, SYN scans were called stealth scans because:
Modern reality:
Today, SYN scans are well-understood and easily detected:
However, SYN scans remain popular because they're still faster and less intrusive than full connect scans.
| Response Received | Port State | Meaning |
|---|---|---|
| SYN-ACK | Open | Service is listening and accepting connections |
| RST (Reset) | Closed | Port is reachable but no service listening |
| No response | Filtered | Firewall dropping packets (or severe congestion) |
| ICMP Type 3 (unreachable) | Filtered | Firewall actively rejecting with ICMP |
| ICMP admin prohibited | Filtered | Firewall configured to announce filtering |
In nmap, SYN scan is the default when running as root: nmap -sS target.com. The -sS flag explicitly requests SYN scan. nmap handles all the raw packet crafting, timing, and interpretation automatically.
Beyond Connect and SYN scans, security professionals employ numerous specialized techniques. Each exploits different aspects of TCP/IP behavior to gain different advantages in stealth, speed, or firewall evasion.
These scans exploit RFC 793's specification of how systems should handle packets that don't match any connection:
FIN Scan: Sends packet with only FIN flag (normally indicates end of data) Xmas Scan: Sends packet with FIN, PSH, and URG flags ("lit up like a Christmas tree") NULL Scan: Sends packet with no flags set at all
Expected behavior (per RFC 793):
Advantage: May bypass simple packet-filter firewalls that only block SYN packets.
Windows systems (and many others) don't follow RFC 793 for these packets. They send RST for ALL ports regardless of state, making these scans ineffective against Windows targets. These work primarily against Unix-like systems.
Port scanning performance involves careful tradeoffs between speed, accuracy, and stealth. Understanding these tradeoffs is essential for both effective scanning and defending against scans.
The timing dilemma:
| Template | Name | Use Case | Characteristics |
|---|---|---|---|
| -T0 | Paranoid | IDS evasion | 5 minutes between probes, serialized |
| -T1 | Sneaky | IDS evasion | 15 seconds between probes |
| -T2 | Polite | Reduced bandwidth | 0.4 seconds between probes |
| -T3 | Normal | Default | Balances speed and reliability |
| -T4 | Aggressive | Fast reliable networks | 1.25s timeout, parallel |
| -T5 | Insane | Very fast networks | 0.3s timeout, maximum parallel |
Factors affecting scan speed:
Network conditions:
Target behavior:
Scanner resources:
Parallelization:
Modern scanners send multiple probes simultaneously:
For scanning large networks, tools like masscan can probe the entire IPv4 Internet in minutes using stateless techniques. It sends SYN packets without tracking them, waiting for async responses. This trades some reliability for extreme speed—useful for Internet-wide research but overkill for targeted assessments.
Knowing a port is open is just the beginning. The next step is service detection—determining what software is actually listening and its version.
Why standard ports aren't reliable:
Service detection techniques:
12345678910111213141516171819202122232425262728
import socket def grab_banner(ip, port, timeout=2): """ Connect to a service and capture its banner. Many services send identifying information upon connection. """ try: sock = socket.socket() sock.settimeout(timeout) sock.connect((ip, port)) # Some services need a nudge to send banner # HTTP requires sending a request if port in [80, 8080, 443, 8443]: sock.send(b"GET / HTTP/1.1\r\nHost: target\r\n\r\n") banner = sock.recv(1024) sock.close() return banner.decode('utf-8', errors='ignore') except Exception as e: return f"Error: {e}" # Example banners you might receive:# SSH: "SSH-2.0-OpenSSH_8.4p1 Ubuntu-5ubuntu1.1"# FTP: "220 (vsFTPd 3.0.3)"# SMTP: "220 mail.example.com ESMTP Postfix"# MySQL: Binary header containing version infonmap service detection:
nmap's -sV flag enables version detection using its probe database:
# Basic service detection
nmap -sV target.com
# More aggressive probing (slower but more accurate)
nmap -sV --version-intensity 9 target.com
# Combine with OS detection
nmap -sV -O target.com
How nmap version detection works:
Service detection requires actual connections and data exchange, making it much more visible than port scanning alone. Version detection creates application-level logs and is easily noticed. Use judiciously in sensitive situations.
From a defender's perspective, detecting port scans is essential for identifying reconnaissance attempts before they lead to attacks. Different scan types leave different traces.
Detection approaches:
IDS/IPS signatures:
Modern intrusion detection systems maintain signatures for common scanning behavior:
# Snort rule example for detecting SYN scan
alert tcp $EXTERNAL_NET any -> $HOME_NET any (
msg:"SCAN nmap SYN";
flags:S,12;
threshold:type both, track by_src, count 50, seconds 60;
classtype:attempted-recon;
sid:1001;
)
This rule triggers when a source sends 50+ SYN packets within 60 seconds.
Honeypots:
Deploying services on unused ports creates tripwires:
| Scan Type | Detection Indicators | Log Location |
|---|---|---|
| TCP Connect | Completed connections to many ports, immediate disconnects | Application logs, firewall logs |
| SYN Scan | Many SYN packets, no corresponding ACKs | Firewall logs, netflow, IDS |
| FIN/Xmas/NULL | Invalid flag combinations, protocol violations | IDS, raw packet capture |
| UDP Scan | ICMP port unreachable bursts, many UDP to closed ports | Firewall logs, IDS |
| Slow Scan | Same source accessing many ports over days/weeks | Long-term traffic analysis, SIEM correlation |
Detection alone isn't sufficient. Combine scan detection with: (1) Minimal exposed services, (2) Firewall rules allowing only required access, (3) Intrusion prevention to block detected scanners, and (4) Rapid response procedures for detected reconnaissance.
Port scanning is the foundation of network reconnaissance—the first step in understanding a network's attack surface. Let's consolidate the key concepts:
What's next:
Port scanning reveals what doors are open—but doesn't show what's behind them. The next page explores Network Mapping, the techniques for understanding network topology, discovering hosts, and building a comprehensive picture of the target infrastructure.
You now understand port scanning at both the conceptual and technical levels. You can explain how different scan types work, their tradeoffs, and how defenders detect them. Next, we'll expand from individual hosts to mapping entire networks.