Explain the TCP three-way handshake. What is exchanged besides SYN and ACK?
Show the answer
Say this first
The client sends a SYN with a random initial sequence number and its options. The server answers with a SYN-ACK carrying its own ISN and acknowledging the client's ISN plus one. The client sends an ACK for the server's ISN plus one. Along the way both sides announce their MSS, window scale, SACK support, timestamps and ECN support. The client goes SYN_SENT to ESTABLISHED; the server goes LISTEN to SYN_RCVD to ESTABLISHED.
Go deeper
The three segments
Client (SYN_SENT) Server (LISTEN)
SYN seq=x MSS 1460, SACK ok, TS, wscale 7 ->
(SYN_RCVD)
<- SYN,ACK seq=y ack=x+1 MSS 1460, SACK ok, TS, wscale 7
(ESTABLISHED)
ACK seq=x+1 ack=y+1 ->
(ESTABLISHED)The SYN and the SYN-ACK each use up one sequence number, which is why the acknowledgments are ISN plus one.
Why three and not two
Each side has to learn the other's ISN and know that its own ISN was received. Two ISNs need two acknowledgments; the server's SYN and its ACK share one segment, so three segments are enough. The exchange also defeats old duplicate SYNs: if a stale SYN reaches the server, the client answers the unexpected SYN-ACK with a RST instead of an ACK, and no connection opens.
Why the ISN is random
A predictable ISN lets an attacker who cannot see the traffic forge segments into a connection. RFC 6528 describes generating it from a keyed hash of the four-tuple plus a clock.
Options that only exist in the handshake
MSS, window scale and SACK permitted are only valid in SYN and SYN-ACK. If one side does not offer window scaling or SACK, neither side uses it. The third ACK may already carry data.
They will ask next
What happens if the SYN-ACK is lost?
The client retransmits the SYN when its timer fires: 1 second initially, doubling each time. Linux retries 6 times by default (
net.ipv4.tcp_syn_retries), about 127 seconds in total, before connect() fails with a timeout. The server also retransmits its SYN-ACK from SYN_RCVD.How do you tell a closed port from a firewall drop from the client side?
A closed port answers the SYN with RST-ACK and the client gets "connection refused" at once. A silent firewall drop makes the client retry SYNs until it times out. Some firewalls reject with a RST or an ICMP administratively prohibited message instead, which fails fast but tells the attacker a filter exists.
What is a simultaneous open?
Both sides send a SYN at the same time. Each moves from SYN_SENT to SYN_RCVD on receiving the other's SYN, and one connection forms with four segments. It is rare, but NAT traversal techniques use it.
Traps
- Saying the acknowledgment number is the next byte the sender will send. It is the next byte it expects to receive.
- Reading Wireshark's relative sequence numbers and claiming the ISN is 0.