How Port Scanning Works: Connect, SYN, UDP and Version Detection
A port scanner never "sees" a service. It sends a packet, waits, and draws a conclusion from what comes back or from silence. Every scan result is therefore an inference, and each scan type infers from different evidence. An assessor who knows the inference rules can read a result correctly ("filtered" is not "closed"), choose the right scan for the question, and predict what the target's logs and IDS will see. You ran connect scans in Nmap Connect Scans on Loopback; this lesson explains the decision rules behind all the common scan types.
TCP: what the handshake reveals
A TCP service is "open" if it completes the first two steps of the handshake (The TCP Handshake and State Machine). The lab shows the normal sequence; a scanner only needs the first two arrows.
| Scan | Sends | Open | Closed | Filtered | Needs |
|---|---|---|---|---|---|
Connect (-sT) |
the OS's normal connect(): SYN, then ACK, then closes |
handshake completes | RST → "connection refused" | timeout, or ICMP unreachable | nothing (any user) |
SYN / half-open (-sS) |
a raw SYN | SYN-ACK (scanner answers RST, never completes) | RST | no answer, or ICMP type 3 code 1, 2, 3, 9, 10, 13 | raw sockets (root) |
UDP (-sU) |
an empty or protocol-specific datagram | a UDP reply | ICMP port unreachable (type 3 code 3) | other ICMP unreachable codes | root |
| UDP, no answer | open|filtered: an open service may ignore junk, a firewall may drop |
Two consequences matter for defence:
- DROP vs REJECT. A firewall that drops silently makes the scanner wait for a timeout and report
filtered; one that rejects (RST or ICMP admin-prohibited) answers at once. Drop slows scans down and reveals less; reject is friendlier to legitimate clients, which fail fast. Both are acceptable; being consistent matters more. - The application doesn't see a SYN scan. The kernel answers the SYN; the server process never accepts a connection, so it logs nothing. A connect scan creates real connections that the application may log. Network sensors see both.
The inference rules as code
The function below is the core of a scanner's decision logic, applied to simulated answers (the "network" is a Python dictionary, so nothing is sent anywhere). Each answer is what a probe to one port of the lab server 10.10.0.10 got back.
TCP_ANSWERS = { # port -> what came back to a SYN
22: "SYN-ACK", 80: "SYN-ACK", 443: "SYN-ACK", 23: "RST",
3389: None, # silence: dropped by a firewall
445: "ICMP 3/13", # communication administratively prohibited (reject)
8443: "RST",
}
UDP_ANSWERS = { # port -> what came back to a UDP probe
53: "UDP reply", 123: "UDP reply", 161: None, # SNMP silent: open service ignoring junk, or dropped?
500: "ICMP 3/3", 514: None,
}
FILTER_CODES = {"ICMP 3/1", "ICMP 3/2", "ICMP 3/9", "ICMP 3/10", "ICMP 3/13"}
def syn_state(ans):
if ans == "SYN-ACK": return "open"
if ans == "RST": return "closed"
if ans is None or ans in FILTER_CODES or ans == "ICMP 3/3": return "filtered"
return "unknown"
def udp_state(ans):
if ans == "UDP reply": return "open"
if ans == "ICMP 3/3": return "closed"
if ans in FILTER_CODES: return "filtered"
if ans is None: return "open|filtered"
return "unknown"
print("TCP (SYN scan)")
for p in sorted(TCP_ANSWERS):
print(f" {p:>5}/tcp {str(TCP_ANSWERS[p]):10} {syn_state(TCP_ANSWERS[p])}")
print("UDP")
for p in sorted(UDP_ANSWERS):
print(f" {p:>5}/udp {str(UDP_ANSWERS[p]):10} {udp_state(UDP_ANSWERS[p])}")TCP (SYN scan)
22/tcp SYN-ACK open
23/tcp RST closed
80/tcp SYN-ACK open
443/tcp SYN-ACK open
445/tcp ICMP 3/13 filtered
3389/tcp None filtered
8443/tcp RST closed
UDP
53/udp UDP reply open
123/udp UDP reply open
161/udp None open|filtered
500/udp ICMP 3/3 closed
514/udp None open|filtered
161/udp and 514/udp can't be decided from silence. That is why UDP scans are slow and noisy: the scanner retransmits to be sure, and it sends protocol-specific payloads (a real SNMP or DNS query) that an open service will answer. Nmap's version detection (-sV) does the same for both protocols: it sends a series of probes from its nmap-service-probes file and matches the answers against patterns.
UDP on loopback: why silence is ambiguous
The sandbox has no root, so nmap -sU can't run, but the inference can be shown with an ordinary UDP socket. A connected UDP socket receives the ICMP "port unreachable" error that the kernel generates for a closed port, as a "connection refused" error. A listener that receives the datagram and doesn't answer produces only silence, which is exactly what a dropping firewall produces too.
ncat -u -l 127.0.0.1 5000 >/dev/null 2>&1 & # an open UDP port that never replies
for i in $(seq 50); do ss -Huln | grep -q ':5000' && break; sleep 0.1; done
python3 - <<'PY'
import socket
for port in (5000, 5001):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("127.0.0.1", port)); s.settimeout(1.0)
s.send(b"probe")
try:
s.recv(100); state = "open (got a reply)"
except ConnectionRefusedError:
state = "closed (ICMP port unreachable)"
except socket.timeout:
state = "open|filtered (silence)"
print(f"{port}/udp: {state}")
PY
echo "--- and Nmap's UDP scan without root:"
nmap -sU -p 5000 127.0.0.1 2>&1
kill %15000/udp: open|filtered (silence)
5001/udp: closed (ICMP port unreachable)
--- and Nmap's UDP scan without root:
You requested a scan type which requires root privileges.
QUITTING!
Version detection in one exchange
Version detection is just a polite client: connect, read what the server says first (the banner), and if it says nothing, send a probe and read the reply. The session starts a fake SMTP-style listener that greets every client and shows the banner grab by hand and by Nmap.
ncat -lk 127.0.0.1 2525 -c 'printf "220 mail.lab.test ESMTP Postfix (Ubuntu)\r\n"; sleep 1' >/dev/null 2>&1 &
for i in $(seq 50); do ss -Htln | grep -q ':2525' && break; sleep 0.1; done
echo "--- by hand:"
ncat --recv-only -w 2 127.0.0.1 2525 | tr -d '\r'
echo "--- by Nmap:"
nmap -sT -sV -p 2525 127.0.0.1 | grep '/tcp'
kill %1--- by hand:
220 mail.lab.test ESMTP Postfix (Ubuntu)
--- by Nmap:
2525/tcp open smtp Postfix smtpd
The banner names the software. It may also lie, and here it does: the listener is Ncat printing one line, yet Nmap reported Postfix smtpd because its patterns matched the greeting. A banner is whatever the administrator configured, so version evidence from a banner is a lead, to be confirmed by an authenticated check (Outdated Software and Version Evidence).
How scans are detected
| Scan | Footprint on the target and the network |
|---|---|
| Connect | full connections without data, often logged by the application; many in a burst |
| SYN | half-open connections, SYN followed by RST from the scanner; nothing in application logs; network IDS rules on "SYN to many ports" |
| UDP | many ICMP port-unreachable messages leaving the target (a good egress signal), protocol probes in service logs |
| Version | odd requests in service logs (as in the nmap-connect lesson's web log), malformed protocol greetings |
Network IDS rules count distinct destination ports or hosts per source within a window; IDS and IPS shows how. Linux also rate-limits its own ICMP errors (net.ipv4.icmp_ratelimit), which slows UDP scans further.
How exposure is reduced
- Default-deny filtering so only intended ports answer; consistent DROP or REJECT at the edge.
- Bind services to the interface they serve (
127.0.0.1for local admin interfaces). - Rate limits and alerts on scan patterns; scan yourself regularly and announce it.
Pitfalls
- Reading
filteredas "not running". The service may run and be reachable from a different network position. - Reading
open|filteredUDP as open: confirm with a protocol probe (-sV, ordigfor DNS,snmpgetfor SNMP within scope). - Trusting banners as versions without confirmation.
- Forgetting that a host firewall and a network firewall may answer differently: a RST from the network firewall makes a port look closed although the host never saw the probe.
Practice
1. A SYN scan gets SYN-ACK from port 8080, but a connect scan from the same machine a minute later reports it closed. Give two explanations.
The service stopped in between; or a stateful device (IPS, rate limiter, port-knocking daemon) answered the first probe and then blocked the source after seeing a scan pattern. Rescan slowly and compare from another source address within scope.
2. Which ICMP message tells a UDP scanner that a port is closed, and why can't the scanner rely on it?
Type 3 code 3, port unreachable. Hosts rate-limit ICMP errors, and firewalls often drop outgoing ICMP, so silence can mean closed but rate-limited, open but silent, or filtered.
3. Change TCP_ANSWERS[3389] to "RST". What does that say about the firewall in front of the host?
The port becomes closed: either the host answered (no firewall drops it), or the firewall is configured to reject with TCP RST. From the scan alone you can't tell which; the firewall configuration review can.
Test yourself
A SYN scan gets no answer at all from a port. What does Nmap report?
- open
- closed
- filtered
- open|filtered
Why does a UDP scan report open|filtered?
- UDP has no ports
- An open UDP service may ignore the probe and a firewall may drop it: both look like silence
- Nmap has a bug
- Because of IPv6
In the loopback session, what did the closed UDP port 5001 produce?
- A timeout
- A reply
- ConnectionRefusedError, from the ICMP port-unreachable error
- Nothing printed
Which scan leaves no trace in the target application's own logs?
- Connect scan
- SYN scan
- Version detection
- None of them