COMP-221 · Lesson 5 of 12 · 20 min

Port and service scanning

▶ Video coming soon A video version of this lesson is on the way.

The two addresses with no DNS names, 203.0.113.41 and 203.0.113.44, bothered Tobias all weekend. On Tuesday, October 6, Dario sent the next notification to Felix: TCP and UDP port scanning of the fourteen live external hosts, from the declared address, at a capped rate. Within the hour the two mystery addresses had stories of their own.

Port scanning finds which network services a host offers. It covers objective 2.1's protocol scanning of TCP and UDP and objective 2.2's service discovery, and it is the heart of the Nmap material in objective 2.4. This lesson explains how scans work at the packet level, how to read the port states Nmap reports, how to choose ports and scan types, and how passive services such as Shodan and Censys show similar data without sending a packet.

Ports and protocols

A port number identifies a service on a host. TCP and UDP each have 65,536 ports, numbered 0 to 65,535. Ports 0 to 1,023 are the well-known ports assigned to common services, ports 1,024 to 49,151 are registered ports, and the rest are dynamic or private ports used mostly for the client side of connections. Assignments are conventions, not rules: any service can listen on any port, which is why lesson 6 is about confirming what is really there.

Ports every tester should recognize.
PortProtocolUsual serviceWhy it matters in reconnaissance
21TCPFTPCleartext logins; anonymous access sometimes enabled
22TCPSSHRemote administration; version and authentication methods
25, 587TCPSMTP and submissionMail servers; may reveal names and allow address checks
53TCP and UDPDNSName servers; zone transfers use TCP
80, 443, 8080, 8443TCPHTTP and HTTPSWeb applications and management interfaces
123UDPNTPTime service; old versions can be abused for amplification
135, 139, 445TCPMicrosoft RPC, NetBIOS, SMBWindows file sharing and remote management
161UDPSNMPDevice management; default community strings leak configuration
389, 636TCPLDAP and LDAPSDirectory services
500, 4500UDPIKE and IPsec NAT traversalVPN gateways
1433, 3306, 5432TCPSQL Server, MySQL, PostgreSQLDatabases that should never face the internet
3389TCPRemote Desktop ProtocolRemote access; a common initial access target
5985, 5986TCPWinRMWindows remote management

How a TCP scan works

TCP connections begin with a three-way handshake: the client sends SYN, the server replies SYN-ACK, and the client completes with ACK. Port scans exploit the fact that the reply to the first packet reveals the port's state.

Three rows, each showing a scanner sending SYN to a target port. In the first, the reply is SYN-ACK and the state is open; the scanner sends RST instead of completing the connection. In the second, the reply is RST and the state is closed: the host is up but nothing is listening. In the third, there is no reply or an ICMP unreachable message, and the state is filtered: a firewall dropped or rejected the probe.
In a SYN scan, the target's reply to a single SYN determines the port state.

In a TCP SYN scan (Nmap -sS), the scanner sends a SYN and reads the reply. SYN-ACK means open; the scanner then sends RST rather than completing the handshake, which is why this is also called a half-open scan. RST means closed. No reply, or an ICMP unreachable error, means filtered. SYN scanning is fast and is Nmap's default when it runs with privileges, because it needs to craft raw packets.

A TCP connect scan (Nmap -sT) asks the operating system to make a full connection to each port. It needs no special privileges and works where raw packets are not allowed, but it is slower and every completed connection may be logged by the service itself. Without privileges, it is Nmap's default.

Other TCP scan types send unusual flag combinations. An ACK scan (-sA) cannot find open ports, but it maps firewall rules: an unfiltered port returns RST, while a filtered one returns nothing. FIN, NULL and Xmas scans (-sF, -sN, -sX) rely on a detail of the TCP standard by which closed ports answer such packets with RST and open ports stay silent; Windows systems do not follow it, so the results are unreliable against them. You should recognize these for the exam, but SYN and connect scans do most of the work in practice.

Five boxes. TCP connect, -sT: full handshake, no special privileges, logged by services. TCP SYN, -sS: half-open, fast, the usual default with privileges. UDP, -sU: slow, open or filtered common, needed for DNS, SNMP and NTP. Version, -sV: probes services to name product and version. OS detection, -O: compares TCP/IP responses to a fingerprint database.
The scan types used most often, and what each is for.

Port states

Nmap reports each port in one of six states. Reading them correctly is a common exam task.

The six Nmap port states.
StateMeaningTypical cause
openA service is accepting connections or packetsSYN-ACK to a SYN; a UDP response
closedReachable, but nothing is listeningRST to a SYN; ICMP port unreachable for UDP
filteredNmap cannot tell, because probes are blockedNo reply, or ICMP administratively prohibited
unfilteredReachable, but open or closed is unknownSeen only in ACK scans
open|filteredOpen or filtered; no response either wayCommon in UDP scans
closed|filteredClosed or filteredSeen only in the rarely used IP ID idle scan

Closed ports are more informative than they look. They prove the host is up and reachable, and a host where everything not explicitly allowed is filtered rather than closed has a well-configured firewall. A scan that shows hundreds of closed ports and a few open ones points to a host firewall that is off or permissive.

Choosing ports

By default Nmap scans the 1,000 most common ports for each protocol. That finds most services but misses anything on an unusual port. Testers choose the port set deliberately.

Port selection options in Nmap.
OptionEffectWhen to use
(none)Top 1,000 portsFirst pass on many hosts
-FTop 100 portsQuick look, very large ranges
--top-ports NThe N most common portsA tuned middle ground
-p 22,80,443Only the listed portsChecking specific services
-p 1-1024A rangeWell-known ports only
-p-All 65,535 ports (1 to 65,535)Thorough scans of a small number of important hosts
-p U:53,161,T:22,443Protocol-specific listsCombined TCP and UDP scans

Ironwhistle's external approach was typical: a full TCP scan of every port on the fourteen live hosts, because there were few of them and external exposure matters most, and a UDP scan of the top 100 UDP ports, because UDP scans are slow. Internally, with more than a hundred hosts, the team scanned the top 1,000 TCP ports broadly and all ports on servers.

External TCP and UDP scans, with rate limits from the rules of engagement and output saved for evidence.
# All TCP ports on the live external hosts, capped rate, all output formats
sudo nmap -sS -p- --max-rate 300 -iL E1-live.txt --excludefile exclude-E1.txt -oA E1-tcp-all-20261006

# Top 100 UDP ports on the same hosts
sudo nmap -sU --top-ports 100 --max-rate 100 -iL E1-live.txt -oA E1-udp-top100-20261006
Full TCP scan of the two unnamed hosts. The SERVICE column is a guess from the port number, not a confirmed identification.
sudo nmap -sS -p- 203.0.113.41,44
Output
Nmap scan report for 203.0.113.41
Host is up (0.023s latency).
Not shown: 65532 filtered tcp ports (no-response)
PORT     STATE  SERVICE
443/tcp  open   https
8443/tcp open   https-alt
10443/tcp closed unknown

Nmap scan report for 203.0.113.44
Host is up (0.025s latency).
Not shown: 65533 filtered tcp ports (no-response)
PORT     STATE SERVICE
443/tcp  open  https
3389/tcp open  ms-wbt-server

Nmap done: 2 IP addresses (2 hosts up) scanned in 412.37 seconds

Read the output carefully. The line "Not shown: 65532 filtered tcp ports" means Nmap collapsed the most common state to keep the listing short; almost every port is filtered, which is good. On 203.0.113.41, ports 443 and 8443 are open and 10443 is closed, which means the firewall lets traffic reach that port but nothing listens. On 203.0.113.44, HTTPS and Remote Desktop are open. The service names, https-alt and ms-wbt-server, come from Nmap's table of common port assignments. They are guesses until the version detection in lesson 6 confirms them.

Tobias raised both hosts with Dario immediately. An internet-facing Remote Desktop server was the sort of exposure attackers look for first, and it was not on Prairiefold's asset list. Dario agreed it was worth an early call, not a wait for the report. Gwendolyn's team traced 203.0.113.44 the next day: a remote support server set up in 2022 for a software vendor and never removed. 203.0.113.41 turned out to be the management interface of the head office firewall, reachable from the internet. Both went straight to the top of the findings list, each with a clear remediation: remove the remote support server or put it behind the VPN with multifactor authentication, and restrict firewall management to an internal management network.

UDP scanning

UDP has no handshake, which makes scanning harder. A UDP probe to a closed port normally triggers an ICMP port unreachable reply, so closed is easy to identify. An open port may reply only if the probe is a valid request for that service, and a filtered port says nothing. Many results therefore come back as open|filtered. Operating systems also rate-limit ICMP unreachable messages, which forces scanners to slow down, so a full UDP scan of one host can take hours.

Nmap improves accuracy by sending protocol-specific payloads for well-known UDP services, such as a valid DNS query to port 53 or an SNMP request to port 161. Version detection (-sV) combined with -sU sends more such probes and can resolve many open|filtered results into open or closed. UDP scanning matters because services like DNS, SNMP, NTP, TFTP and IKE all run over it, and SNMP in particular is a frequent source of internal findings.

UDP results are often ambiguous. The VPN gateway answers IKE on 500; the firewall answers NTP, and SNMP stays open|filtered.
sudo nmap -sU -sV --top-ports 20 203.0.113.20,41
Output
Nmap scan report for vpn.prairiefold.example (203.0.113.20)
PORT     STATE         SERVICE   VERSION
500/udp  open          isakmp
4500/udp open|filtered nat-t-ike

Nmap scan report for 203.0.113.41
PORT     STATE         SERVICE   VERSION
123/udp  open          ntp       NTP v4 (secondary server)
161/udp  open|filtered snmp

Performance and timing

Scans are a balance between speed, accuracy and impact. Nmap's timing templates, -T0 to -T5, adjust timeouts, retries and parallelism together; -T4 suits reliable networks, while -T2 or slower reduces load and noise. Finer controls include --max-rate and --min-rate (packets per second), --max-retries and --host-timeout. Faster is not always better: dropped probes at high speed show up as false filtered results, and aggressive scanning can overload old network equipment or fill a firewall's connection table.

Very fast scanners such as masscan can sweep huge address ranges in minutes by sending packets asynchronously. They are useful for internet-scale research and very large internal networks, but they are blunt: they report open ports with little detail and can overwhelm networks if misconfigured. In a client engagement, their speed must be capped to what the rules of engagement allow.

Passive alternatives: Shodan and Censys

Internet-wide scanning services scan every public IPv4 address continuously and publish what they find: open ports, banners, certificates and detected software. Shodan and Censys are the best known, and both are named in objective 2.4. Searching them for a client's address range or organization name shows exposed services without sending any traffic to the client, which makes them ideal for the passive phase.

Before October 5, Tobias had searched both services for Prairiefold's range. Shodan had already recorded Remote Desktop on 203.0.113.44 three months earlier, with a screenshot of the login screen showing a Windows Server version. The data was older than a live scan and could be out of date, but it told the team what to expect and showed how long the exposure had been visible to anyone who looked. That timeline went into the finding: an attacker would not have needed to scan Prairiefold at all.

Passive scan data compared with live scanning.
ApproachStrengthLimitation
Shodan or Censys searchPassive, instant, shows historyMay be stale; limited ports and depth; no internal view
Live Nmap scanCurrent, complete, configurableActive, slower, needs window and notification

Evidence and output formats

Every scan Ironwhistle ran was saved in all three Nmap formats with -oA: normal output for people, XML for tools and reports, and grepable output for quick command-line filtering. File names carried the scope item, the scan type and the date. Lesson 11 shows how XML output feeds other tools and how short scripts turn raw output into tables. Saved output is also the evidence that defends the tester if anything goes wrong: it shows exactly what was sent, to which addresses, and when.

Defending against scanning

Port scanning cannot be prevented, but its value to an attacker can be reduced. The core defense is minimal exposure: only services that must face the internet do, and management interfaces sit behind a VPN or management network. A default-deny firewall that drops rather than rejects unsolicited traffic makes scans slower and less informative. Regular external scanning by the organization itself, comparing results with an approved list of exposed services, catches drift like the forgotten remote support server. Intrusion detection should alert on scanning patterns, but organizations should expect scanning from the internet all day and focus on what it finds rather than the scans themselves.

Worked problem

Reading a mixed result

An internal scan of 192.0.2.25 reports: 22/tcp open, 80/tcp closed, 443/tcp open, 3306/tcp filtered, and "Not shown: 996 closed tcp ports (reset)". What can Tobias conclude?

Show solution
  1. The host is up: closed ports returned RST.
  2. SSH and HTTPS are open and need version detection.
  3. Most ports are closed rather than filtered, so there is probably no host firewall, or it allows everything except a few rules.
  4. Port 3306, the usual MySQL port, is filtered: something is deliberately blocking it, which suggests a database is running and protected by a specific rule.

Answer: A live host with SSH and HTTPS exposed, little host firewalling, and a probably protected database port. Fingerprint the open services next and note the host firewall posture.

Common mistakes

  • MistakeTreating the SERVICE column as confirmed.

    InsteadIt is a guess from the port number; confirm with version detection and banners.

  • MistakeSkipping UDP because it is slow.

    InsteadScan the top UDP ports at least; DNS, SNMP, NTP and IKE live there.

  • MistakeScanning only the default 1,000 TCP ports on critical external hosts.

    InsteadScan all 65,535 ports on a small set of important hosts.

  • MistakeReading open|filtered as open.

    InsteadIt means no response either way; use version probes to resolve it.

  • MistakeSpeeding up scans until they finish quickly.

    InsteadKeep within agreed rates; dropped probes create false filtered results and risk outages.

Summary and key terms

  • TCP and UDP each have 65,536 ports; well-known services use conventional ports but can run anywhere.
  • A SYN scan reads the reply to one SYN: SYN-ACK open, RST closed, nothing filtered.
  • Connect scans need no privileges but complete connections; ACK scans map firewall rules.
  • Nmap reports open, closed, filtered, unfiltered, open|filtered and closed|filtered.
  • UDP scanning is slow and ambiguous; protocol payloads and -sV help.
  • Shodan and Censys provide passive, sometimes stale, views of exposed services.
  • Saved output in all formats is evidence; minimal exposure is the main defense.
Port scan
Probing a host's ports to find which services are reachable.
SYN scan
A half-open TCP scan that sends SYN and reads the reply without completing the connection.
Connect scan
A TCP scan that completes full connections through the operating system.
Filtered
A port state where probes are blocked, so Nmap cannot tell whether the port is open.
open|filtered
A state where no response was received, so the port could be open or filtered.
Shodan
A search engine for internet-connected devices built from continuous scanning.
Censys
A search platform for internet hosts, services and certificates built from continuous scanning.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why is a SYN scan called half-open?

    Show answer

    The scanner sends SYN and, on SYN-ACK, replies with RST instead of ACK, so the handshake is never completed.

  2. Which scan type maps firewall rules rather than finding open ports?

    Show answer

    The ACK scan, -sA.

  3. What does "Not shown: 65532 filtered tcp ports" tell you?

    Show answer

    Almost all ports gave no response, so a firewall is filtering them; Nmap hid them to shorten the output.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz