Skip to content

Port Scanning

Port scanning means systematically checking a target's servers for open ports. It's core active recon - like knocking on every door to see what's open. You'll find which services are running and accessible.

1. Introduction to Port Scanning

Every service on a server (web, FTP, database) listens on a specific port. You check all 65,535 possible TCP and UDP ports to see which are open, closed, or filtered.

  • Open: The port accepts connections. Something's listening. This is your target.
  • Closed: The port responds but nothing's listening. The server says "nope, nothing here."
  • Filtered: You can't tell if it's open or closed. A firewall is blocking your probe. That tells you a firewall exists.

The goal of port scanning is to create a map of all open ports on a target host, which is the first step toward Service Fingerprinting.

2. Core Concepts: TCP vs. UDP

Understanding TCP vs UDP is crucial for port scanning. They work differently, so you'll scan them differently too.

TCP (Transmission Control Protocol)

  • Connection-Oriented: Establishes a reliable connection using a "three-way handshake" (SYN, SYN/ACK, ACK).
  • Reliable: Guarantees that data arrives in order and without errors.
  • Scanning: TCP scanning is generally faster and more reliable because you get a definitive response.

The Three-Way Handshake: 1. Client -> Server: SYN (Synchronize) 2. Server -> Client: SYN/ACK (Synchronize/Acknowledge) 3. Client -> Server: ACK (Acknowledge)

UDP (User Datagram Protocol)

  • Connectionless: Sends packets ("datagrams") without establishing a connection first.
  • Unreliable: No guarantee of delivery or order. "Fire and forget."
  • Scanning: UDP scanning is slow and less reliable. An open UDP port might not send a response, forcing the scanner to time out. A closed UDP port will typically respond with an ICMP "Port Unreachable" message.

3. The King of Port Scanners: nmap

nmap (Network Mapper) is the industry standard for port scanning. It's powerful, flexible, and you can extend it with scripts. This is your go-to tool.

Basic nmap Commands

# Scan a single target for the top 1000 most common ports
nmap target.example.com

# Scan multiple targets
nmap target1.example.com target2.example.com

# Scan a range of hosts
nmap 192.168.1.1-254

# Scan a CIDR range
nmap 192.168.1.0/24

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

Choosing Which Ports to Scan

By default, nmap scans the 1,000 most common TCP ports. Want a thorough scan? Specify the port range yourself.

# Scan a specific port
nmap -p 80 target.example.com

# Scan a range of ports
nmap -p 1-100 target.example.com

# Scan all 65,535 TCP ports
nmap -p- target.example.com

# Scan the most common ports faster
nmap --top-ports 100 target.example.com

# Scan specific UDP ports
nmap -sU -p 53,161 target.example.com

4. Common Scan Types

nmap offers various scan types, each with different levels of speed and stealth.

Flag Scan Type Description Stealth Privilege Required
-sT TCP Connect Scan Completes the full three-way handshake. Reliable but easily logged. Low No
-sS SYN (Stealth) Scan Sends only a SYN packet. If it receives a SYN/ACK, the port is open. Never completes the connection. High Yes (root/admin)
-sU UDP Scan Sends a UDP packet to each target port. Slow and used for specific services like DNS, SNMP. High Yes (root/admin)
-sN Null Scan Sends a TCP packet with no flags set. Very High Yes (root/admin)
-sF FIN Scan Sends a TCP packet with only the FIN flag set. Very High Yes (root/admin)
-sX Xmas Scan Sends a TCP packet with FIN, PSH, and URG flags set. Very High Yes (root/admin)

Default Scan: If run with root privileges, nmap defaults to -sS (SYN Scan). If run as a normal user, it defaults to -sT (Connect Scan).

Practical nmap Recipes

# Fast, stealthy scan of the top 1000 ports
sudo nmap -sS target.example.com

# A comprehensive and aggressive scan
# -A: Enables OS detection, version detection, script scanning, and traceroute
# -T4: Sets timing to "aggressive" (faster)
sudo nmap -A -T4 target.example.com

# The "all ports" scan - your go-to for a full assessment
# -p-: Scan all TCP ports
# -sV: Probe open ports to determine service/version info
# -sC: Run default NSE scripts
# -oN: Save output in normal format
sudo nmap -p- -sV -sC -oN nmap_full_scan.txt target.example.com

5. High-Speed Scanners

When scanning a very large number of hosts or ports, nmap can be slow. High-speed scanners are designed for one thing: speed.

masscan

masscan is an incredibly fast port scanner that can scan the entire internet in minutes. It uses its own TCP/IP stack and operates asynchronously.

# Scan a single host for a specific port, very fast
masscan 192.168.1.1 -p443

# Scan a large network range for multiple ports
# --rate: specifies packets per second
masscan -p80,443,8080 10.0.0.0/8 --rate=10000

# Save output in a format that can be fed into nmap for service scanning
masscan -p1-65535 192.168.1.0/24 --rate=1000 -oG masscan.grep
nmap -sV -sC -iL masscan.grep

rustscan

A modern port scanner that finds open ports very quickly and then automatically pipes them into nmap for deeper analysis. It's a great workflow enhancement.

# Scan all ports on a host and run default nmap scripts on the open ones
rustscan -a target.example.com -- -sV -sC

# Adjust batch size for speed
rustscan -a target.example.com -b 5000 -- -A

6. Advanced Techniques and Evasion

  • Timing Templates (-T): Control the speed of your scan. -T0 (paranoid) is extremely slow for IDS evasion, while -T5 (insane) is very fast but noisy. -T4 (aggressive) is a common choice.
  • Packet Fragmentation (-f): Splits the probe packets into smaller fragments, which can sometimes bypass older firewalls or intrusion detection systems.
  • Decoys (-D): Make the scan appear to be coming from other IP addresses (decoys) in addition to your own, making it harder for defenders to determine the true source.
    sudo nmap -sS target.example.com -D RND:10,ME
    
  • Source Port Spoofing (--source-port): Some poorly configured firewalls might trust traffic coming from a specific source port (e.g., 53 for DNS). You can specify the source port for your probes.

7. Notes and Pitfalls

  • Legality and Authorization: Port scanning a system without permission is often against the terms of service of your ISP and can be considered a precursor to an attack. Only scan systems you have explicit, written permission to test.
  • Network Noise: Aggressive scanning can be disruptive to sensitive networks or legacy systems. Always understand the target environment before launching a scan.
  • Firewalls and IPS/IDS: Filtered ports are a strong indication of a firewall. Scans may be blocked entirely, or your IP may be blacklisted after a certain number of probes.
  • TCP vs. UDP: Don't forget to scan for common UDP ports. Services like DNS (53), SNMP (161), and IKE (500) run over UDP and are often fruitful targets.

8. Advanced Port Scanning Techniques

Service-Specific Scanning

Web Services Deep Scan:

# Comprehensive web service discovery
nmap -p 80,443,8080,8443,8000,8008,8081,8888,9000,9001 --script http-enum,http-title,http-headers target.example.com

# SSL/TLS scanning
nmap -p 443,8443 --script ssl-cert,ssl-enum-ciphers target.example.com

# HTTP methods testing
nmap -p 80,443 --script http-methods --script-args http-methods.url-path='/api' target.example.com

Database Services:

# MySQL comprehensive scan
nmap -p 3306 --script mysql-info,mysql-databases,mysql-users,mysql-variables,mysql-audit target.example.com

# PostgreSQL assessment
nmap -p 5432 --script pgsql-brute,pgsql-commands target.example.com

# MongoDB enumeration
nmap -p 27017 --script mongodb-info,mongodb-databases,mongodb-brute target.example.com

# Redis security check
nmap -p 6379 --script redis-info target.example.com

Network Services:

# SSH security assessment
nmap -p 22 --script ssh2-enum-algos,ssh-hostkey,ssh-auth-methods target.example.com

# FTP enumeration
nmap -p 21 --script ftp-anon,ftp-bounce,ftp-syst target.example.com

# SMB/CIFS scanning
nmap -p 139,445 --script smb-enum-shares,smb-enum-users,smb-os-discovery,smb-vuln-* target.example.com

Advanced Nmap Scripting Engine (NSE) Usage

The Nmap Scripting Engine allows for powerful, targeted scanning beyond basic port discovery:

Discovery Scripts:

# Discover hosts even if they don't respond to ping
nmap -sn --script targets-sniffer

# Find hosts with specific services
nmap --script broadcast-dhcp-discover

Vulnerability Detection:

# Scan for common vulnerabilities
nmap --script vuln target.example.com

# Check for specific vulnerabilities
nmap --script http-vuln-cve2017-5638 target.example.com

Service Enumeration:

# Enumerate HTTP services
nmap --script http-enum target.example.com

# Enumerate SMB shares
nmap --script smb-enum-shares target.example.com

# Enumerate SNMP information
nmap -sU -p 161 --script snmp-info target.example.com

Network Segmentation and Firewall Bypass Techniques

Identifying Network Segments:

# Use traceroute to map network paths
traceroute target.example.com

# Nmap traceroute with port scanning
nmap -sn --traceroute target.example.com

# Discover network topology
nmap --script targets-ipv6-multicast-echo

Firewall Evasion Methods:

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

# Specify custom fragment size
nmap --mtu 24 target.example.com

# Spoof source port to appear as trusted traffic
nmap --source-port 53 target.example.com  # DNS traffic
nmap --source-port 80 target.example.com  # HTTP traffic

# Slow scan to avoid detection
nmap -T0 target.example.com  # Paranoid timing

# Randomize scan order
nmap --randomize-hosts target.example.com

# Spoof decoy addresses
nmap -D RND:10 target.example.com  # 10 random decoys

Protocol-Specific Scanning Techniques

HTTP/HTTPS Service Discovery:

# Scan for web services on non-standard ports
nmap -p 80,443,8000,8080,8443,9000 --script http-title target.example.com

# Detect web application frameworks
nmap -p 80,443 --script http-enum,http-headers target.example.com

# Check for HTTP methods
nmap -p 80,443 --script http-methods target.example.com

Industrial Control Systems (ICS):

# SCADA/ICS protocol scanning
nmap -p 502 --script modbus-discover target.example.com  # Modbus
nmap -p 44818 --script enip-info target.example.com     # EtherNet/IP
nmap -p 47808 --script bacnet-info target.example.com   # BACnet

Custom Scanning Automation

Bash Automation Script:

#!/bin/bash
TARGET=$1

echo "[+] Starting comprehensive port scan for $TARGET"

# Phase 1: Quick discovery scan
nmap -T4 -F $TARGET -oN quick_scan.txt

# Phase 2: Full TCP port scan
nmap -T4 -p- $TARGET -oN full_tcp_scan.txt

# Phase 3: Service detection
nmap -T4 -sV -sC $TARGET -oN service_scan.txt

# Phase 4: UDP scan for critical ports
nmap -T4 -sU -p 53,67,68,69,123,135,137,138,139,161,162,445,500,514,520,631,1434,1900,4500,49152 $TARGET -oN udp_scan.txt

echo "[+] Port scanning completed. Results saved to scan files."

Python Port Scanner:

import nmap
import threading

def comprehensive_scan(target):
    nm = nmap.PortScanner()

    # TCP SYN scan
    print("Running TCP SYN scan...")
    nm.scan(target, arguments='-sS -T4')

    # Service detection
    print("Running service detection...")
    nm.scan(target, arguments='-sV -sC')

    # UDP scan
    print("Running UDP scan...")
    nm.scan(target, arguments='-sU -p 53,161,500')

    return nm

# Usage
results = comprehensive_scan('target.example.com')
for host in results.all_hosts():
    print(f"Host: {host}")
    for proto in results[host].all_protocols():
        print(f"Protocol: {proto}")
        ports = results[host][proto].keys()
        for port in ports:
            print(f"Port {port}: {results[host][proto][port]['state']}")

9. real world Case Study: Financial Institution Assessment

Scenario: During a security assessment of a financial institution, initial port scans revealed only standard web ports (80, 443) and a few management ports.

Approach: 1. Comprehensive TCP Scan: Full port range scan with service detection 2. Targeted UDP Scanning: Focused on financial services and infrastructure ports 3. Timing Optimization: Used slower timing to evade detection systems 4. Source Port Manipulation: Tested different source ports to bypass firewall rules

Findings: - Discovered port 8443 running an unpatched Tomcat administration console - Found port 161 (SNMP) with default community strings exposing network infrastructure details - Located port 3389 (RDP) exposed externally with weak authentication policies - Identified port 1433 (MSSQL) with default credentials on a development server

Impact: These discoveries led to multiple critical vulnerabilities being identified, including potential remote code execution and unauthorized access to sensitive financial systems.

10. Quick Reference: nmap Flags

Flag Purpose Example
-p- Scan all 65,535 ports. nmap -p- target
-sS SYN (stealth) scan. sudo nmap -sS target
-sU UDP scan. sudo nmap -sU target
-sV Service/Version detection. nmap -sV target
-sC Run default NSE scripts. nmap -sC target
-A Aggressive scan (OS, version, scripts, trace). nmap -A target
-T4 Set timing to "aggressive". nmap -T4 target
-iL <file> Scan targets from a file. nmap -iL targets.txt
-oN <file> Save output in normal format. nmap target -oN report.txt
-oG <file> Save output in "grepable" format. nmap target -oG report.grep
-v / -vv Increase verbosity. nmap -vv target
-n Disable DNS resolution. nmap -n 192.168.1.1
Pn Skip host discovery (treat all as online). nmap -Pn target

11. Summary

Port scanning is a fundamental reconnaissance technique that provides critical visibility into a target's network services and potential attack surface. By mastering tools like nmap, masscan, and rustscan, security professionals can efficiently identify open ports, running services, and potential vulnerabilities. Understanding different scan types, timing options, and evasion techniques is essential for conducting effective and stealthy reconnaissance operations while maintaining ethical boundaries and proper authorization.