Chapters

4 Transmission Control Protocol (TCP)

transport-protocols
tcp
iot

A gateway streams sensor history to a remote service that has slowed down. The connection remains established, yet queued records accumulate locally. Transmission control can regulate byte flow without making the application queue unlimited.

4.1 Start With One Connection

Separate a Working Connection From a Completed Action

Picture a building device sending a door command to a service. The connection opens and every byte arrives in order, yet the door stays locked because the service rejects the request. A healthy connection did not prove a successful action.

A protocol is an agreed set of message and timing rules. A gateway is a device that joins one network to another. Transmission Control Protocol (TCP) keeps an ordered byte stream between two endpoints and resends missing parts. Write the application result beside the connection result. Name the request identity, send time, reply, final physical state, and deadline after which the command is no longer safe.

Break one layer at a time. Refuse the connection, lose a segment, delay the reply, close halfway through a message, restart an endpoint, and return an application error over a healthy stream. Check that each failure has a distinct record and recovery rule.

This test does not prove the remote service, user permission, or physical device by itself. The deeper sections show how connection setup, flow, loss recovery, closing, and attack limits support transport evidence without overstating it as end-to-end proof.

Picture a gateway opening a TCP connection before it sends a command that must arrive in order. TCP gives the path connection state, acknowledgements, retransmission, and stream behavior, but it still cannot prove that the application accepted the command correctly. The review starts by separating connection evidence from end-to-end outcome evidence.

4.2 Overview: TCP Evidence Is Connection Evidence, Not Application Proof

TCP gives an application a connection-oriented byte stream. It can provide ordered bytes, acknowledgements, retransmission behavior, flow control, and close state below the application boundary. That makes TCP useful for many IoT paths that need a session, a command channel, a configuration transfer, or a gateway stream.

The review mistake is treating the transport evidence as proof of the whole system result. A completed TCP connection does not prove that the receiver parsed the message, authorized it, stored it, acted on it, or cleaned up application state after close.

Consider a controller that downloads a new sampling interval from a cloud service through a gateway. The TCP trace can show connection setup, bytes acknowledged, retransmissions, and whether the connection closed cleanly. The transport review still needs the application record: where the command frame begins and ends, which endpoint accepted it, whether the gateway forwarded or queued it, and whether the device rejected stale or repeated commands.

This distinction prevents two common overclaims. First, a sender-side ACK does not prove that the final device changed configuration. Second, an orderly close does not prove that the application cleaned up state or persisted the change. The TCP decision is strong only when it is paired with receiver-side evidence and a retest trigger for parser, gateway, security, or reconnect-policy changes.

If you only need the intuition, this layer is enough: TCP can protect byte-stream order and retry missing bytes below the application, but the review still needs message framing, receiver behavior, security boundary, and retest evidence.

4.3 Connection-State Attacks

Inspect Figure 4.1 to compare one successful handshake with spoofed branches that consume half-open state and backlog capacity.

TCP SYN flood diagram contrasting SYN, SYN ACK, ACK established flow with five spoofed SYN requests left in SYN RCVD, a nine of ten backlog, and SYN-cookie, expiry, validation, and monitoring controls.
Figure 4.1: Normal TCP handshake beside spoofed SYN branches stuck in SYN RCVD, a backlog meter, and defensive controls.

Read Figure 4.1 from ACK → ESTABLISHED on the normal handshake path to the spoofed fan-out that leaves every branch in SYN_RCVD. The BACKLOG 9 / 10 meter makes state exhaustion visible, and the defence strip pairs prevention with monitoring.

Then inspect Figure 4.2 to compare three different acceptance boundaries rather than grouping all transport attacks together.

Normal FIN ACK FIN ACK close, forged RST sequence-window question, and UDP sweep to closed ports, each paired with authentication, challenge, ICMP rate limiting, or source-validation evidence.
Figure 4.2: Three transport panels for normal TCP FIN teardown, forged RST acceptance, and spoofed UDP sweep with ICMP amplification controls.

Compare NORMAL FIN with FORGED RST in Figure 4.2, then inspect UDP SWEEP. The VALIDATE strips connect ordered close, sequence-window checks, ICMP rate limits, and ingress source validation to the state transition they protect.

TCP’s guarantees are easiest to keep in scope when the review follows one application path through the transport lifecycle. Figure 4.3 previews that route before the chapter examines individual connection properties.

TCP review evidence route from application path through connection role, stream framing, acknowledgement evidence, flow control, close state, and retest trigger.
Figure 4.3: TCP review follows the path from application purpose to endpoint role, stream framing, acknowledgement behavior, flow control, close state, and retest trigger.

Trace Figure 4.3 from application purpose and endpoint roles into stream framing, acknowledgements, and flow control. Continue through close or reset state to the retest trigger. The route shows exactly where TCP evidence stops: it can establish byte-stream behavior, but parser acceptance, authorization, persistence, and actuator outcome still require application evidence.

Connection

Which endpoint opens the connection, which endpoint listens, what identifies the peer, and what evidence shows established state?

Byte Stream

How does the application find one complete message inside a stream that can split or combine reads?

Backpressure

What happens when the receiver, gateway, queue, or application cannot keep up with the sender?

Close State

How are graceful close, reset, idle timeout, reconnect, and stale application state handled?

Overview Knowledge Check

4.4 Practitioner: Build the TCP Review Record

A TCP review record should name the application path before it names the protocol. The same product might use TCP safely for configuration transfer, use UDP for replaceable status messages, and require a separate protected command path. The TCP record approves only the tested path and its stated boundaries.

For a practical review, capture one path at a time. If a device keeps a long-lived MQTT connection for telemetry and the same gateway opens a separate TCP connection for firmware download, those are different records. The telemetry record should focus on session reuse, backpressure, reconnect behavior, and message framing. The firmware record should focus on chunk ordering, resume behavior, integrity checks, close/reset recovery, and who owns retry after interruption.

Connection evidence begins with the state transition both endpoints must complete. Inspect Figure 4.4 before using an established socket as evidence for the wider application path.

TCP three-way handshake sequence showing client CLOSED to SYN_SENT to ESTABLISHED, server LISTEN to SYN_RCVD to ESTABLISHED, and SYN, SYN-ACK, and ACK messages.
Figure 4.4: TCP connection setup evidence shows the SYN, SYN-ACK, and ACK exchange that establishes transport state, but it still needs application framing and receiver evidence.
  1. Broker Bex: Bex carries a sealed opening pennant from the client office onto an empty bridge.

    The client sends a connection request and opens half-state.

  2. Broker Bex: The server returns a paired pennant while opening its side of the bridge.

    The server answers and opens its matching half-state.

  3. Broker Bex: Bex returns a final receipt; the bridge locks into place at both offices.

    The client confirms. Both transport ends are established.

  4. Broker Bex: Bex stands at a bright checkpoint beyond the bridge where parsing, permission, action, and cleanup remain unchecked.

    Stop at the app boundary. No action is proved yet.

CW-0028 walkthrough: The client opens with a request, the server answers and opens its half, and the client confirms; both ends are connected, but app success is still unproved.

Read Figure 4.4 from the client’s SYN and SYN_SENT state to the server’s SYN-ACK and SYN_RCVD state, then follow the final ACK until both endpoints are established. The sequence proves negotiated transport state between endpoints; it does not show how later bytes are framed or acted upon. That distinction feeds directly into the practitioner ledger.

4.4.1 SYN floods at the connection-establishment boundary

The three-way handshake costs the listener state before it has proof that the apparent client can receive traffic at its claimed address. After a SYN arrives, a conventional listener chooses its initial sequence number, returns SYN-ACK, creates a half-open control block in SYN_RCVD, and waits for the final ACK. The SYN itself consumes one sequence number, so a legitimate final acknowledgement confirms the server’s initial sequence plus one.

A SYN flood exploits that gap with many requests whose final acknowledgements never arrive. Spoofed source addresses make the SYN-ACK packets go elsewhere; non-spoofed bots can simply abandon the handshake. Until each half-open entry expires, it consumes backlog, timer, and retransmission work. Once that queue or another resource limit is exhausted, legitimate SYN traffic is dropped or delayed even though the application workers may be healthy.

Trace or counterNormal pressureFlood warning
New SYN rateFollows expected client arrival patternSudden rate or source-distribution change
SYN_RCVD populationBrief entries that convert to ESTABLISHEDLarge or persistent half-open population
Handshake completion ratioMost SYN-ACK packets receive a valid final ACKCompletion collapses while SYN-ACK retransmits rise
Listen-backlog dropsRare and correlated with known loadSustained overflow while application capacity remains
Source/service distributionExpected clients and published portsBroad port scan or many implausible/spoof-prone sources

Mitigation is layered because no one knob proves legitimacy:

  1. SYN cookies encode enough temporary handshake state into the server’s initial sequence number that the listener need not allocate the ordinary half-open control block. A valid final ACK lets the server reconstruct the state. Verify which TCP options the implementation can preserve in cookie mode rather than assuming the fallback is behaviorally identical.
  2. Backlog and timeout tuning absorbs short bursts and reclaims abandoned entries sooner. Oversizing only moves the exhaustion point, while an aggressive timeout can reject slow legitimate paths.
  3. Per-source and aggregate rate limits bound work at the host, load balancer, firewall, or upstream provider. Distributed attacks require aggregate and service-level controls, not only a per-address rule.
  4. Source validation and filtering drop clearly invalid or unauthorized traffic. Network ingress/egress source-address validation reduces spoofing where it is deployed, while an allowlist may fit a closed management plane.
  5. Service minimisation and telemetry close unused listening ports and alert on half-open occupancy, completion ratio, retransmitted SYN-ACKs, backlog drops, and legitimate latency.

Port scanning is reconnaissance at the same boundary: different replies can reveal open, closed, or filtered services and sometimes expose a service fingerprint. The defensive response is not to rely on obscurity. Publish only required ports, authenticate the protected service, rate-limit abnormal probes, keep service versions patched, and correlate scan evidence with later handshake or authentication activity.

Record Field
Evidence To Capture
Common Gap
Review Action
Application path
Command, telemetry flow, file transfer, gateway handoff, or session being reviewed.
The record says "uses TCP" but does not identify the application behavior.
Name the flow and receiver action before deciding.
Endpoint role
Active opener, listener, peer identity, connection reuse, and reconnect rule.
The trace cannot be tied to the reviewed endpoint pair.
Revise until endpoint roles are clear.
Stream framing
Length field, delimiter, envelope, parser state, partial-read handling, and combined-write handling.
TCP byte completion is treated as application message completion.
Require application framing evidence.
Backpressure
Receiver slowdown, queue limits, send blocking, drop policy, fault reporting, or close decision.
Slow receivers are hidden as a generic timeout.
Record how the application reacts.
Close state
Graceful close, reset, idle timeout, reconnect, stale session cleanup, and retry ownership.
The record stops once data is sent.
Finish the lifecycle evidence.

Accept

The path, roles, framing, acknowledgements, backpressure, close state, security boundary, limits, and retest triggers are all visible for the reviewed scope.

Revise

The TCP trace is useful, but one required field is missing or overclaims what the transport evidence proves.

Defer

The reviewer cannot tie the trace, endpoint, parser, security boundary, or receiver action to the candidate configuration.

Practitioner Knowledge Check

4.5 Under the Hood: TCP State Moves Below the Application Boundary

TCP tracks byte-stream state below the application. The transport can acknowledge bytes, retransmit missing data, adjust sending to receiver capacity, and close or reset the connection. The application still owns message meaning, parser state, idempotency, command acceptance, authorization, persistence, and user-visible outcome.

This boundary is why TCP evidence should be connected to receiver evidence. A command response can be truncated by a reset after the command changed state. A telemetry stream can reconnect and repeat the last application frame. A slow receiver can create backpressure that changes queue behavior before TCP itself reports a clear error.

A byte stream also means application framing is not optional evidence. A sender can write one 256-byte command and the receiver can read it as two smaller chunks, or the sender can write two short frames and the receiver can read them together. TCP has not violated its contract in either case. The application parser must still know where each command starts and ends, what to do with partial reads, and how to discard stale bytes after timeout or reset.

Backpressure creates another boundary. A receiver window can slow the sender, but the product behavior depends on queues above TCP: whether telemetry waits, drops, compresses, reports a fault, or closes the session. Under-the-hood review therefore asks for both transport state and application policy before accepting a reliability or latency claim.

Transport-layer state abuse: reset and session injection

A normal TCP close is an ordered state transition, usually exchanging FIN and ACK in each direction so queued bytes can be accounted for. A reset is different: an acceptable RST tells the endpoint to abandon the connection immediately. A forged reset attack therefore needs a packet that matches the connection tuple and passes the receiver's sequence-window validation. An on-path observer can see that state; a blind attacker must guess it. Modern randomized initial sequence numbers and stricter reset validation make blind guessing harder, but they do not stop an on-path party from causing denial of service.

Session injection asks for still more state. A forged segment must name one endpoint's source and destination addresses and ports and present sequence/acknowledgement values the receiver accepts. If a blind injection succeeds, replies normally travel to the spoofed peer, so the attacker may obtain one-way command injection rather than a readable two-way session. An on-path attacker can observe both directions and is consequently a different threat class.

AbuseRequired protocol positionPrimary controlEvidence
Forged RSTCorrect four-tuple and acceptable sequence stateStrict reset validation or challenge-ACK behavior; authenticated tunnel where appropriateReset flags, sequence accept/reject counters, challenge ACKs, reconnect cause
Blind injectionGuess tuple plus current receive-window stateRandom sequence state, filtering, and application cryptographic integrityOut-of-window drops, invalid MAC/TLS record, duplicate application id
On-path injectionObserve or alter the active flowTLS or another mutually authenticated, integrity-protected channelCertificate/peer identity, record-authentication failure, channel binding
Replay after reconnectReuse a previously valid application messageFresh session context, command nonce/id, expiry, and idempotencyReplay rejection and receiver transaction log

TLS does not prevent an attacker from dropping packets or forcing availability failures, but authenticated record integrity prevents a forged TCP payload from becoming a valid protected application record. Application command ids, freshness windows, authorization, and idempotency remain necessary because a valid peer can still repeat a valid command. Monitor resets by direction, invalid sequence events, challenge acknowledgements, TLS record failures, reconnect storms, and receiver-side transaction ids rather than diagnosing every disconnect from one packet.

Acknowledgements

Acknowledgements show byte-stream progress below the application. They do not prove payload validity, authorization, storage, or command execution.

Retransmission

Retransmission can recover missing bytes for the stream, but it does not define whether an application operation is safe to repeat.

Flow Control

Receiver pressure can change system behavior before the final outcome is visible. The review should capture queue, wait, fault, or close decisions.

Close and Reset

Close and reset events can leave uncertainty about partial responses, stale session state, and retry ownership unless the record ties them to receiver evidence.

The lifecycle review is incomplete until close, reset, and application cleanup evidence are recorded beside setup and transfer behavior. Inspect Figure 4.5 for the fields that support the final bounded decision.

TCP decision record fields for path, role, framing, acknowledgement evidence, flow control, close state, security boundary, decision, and retest trigger.
Figure 4.5: A compact TCP decision record keeps stateful transport evidence tied to one application path and one retest boundary.

In Figure 4.5, begin with the application path and endpoint roles, then follow framing, acknowledgement, and backpressure evidence into close or reset state. Finish with the security boundary, decision limit, owner, and retest trigger. Reading the record in that order connects transport mechanics to the chapter’s central rule: TCP delivery evidence is necessary but not sufficient application proof.

Under-the-Hood Knowledge Check

Before treating a listening socket as unlimited capacity, open the server-listener preset below. Step from `t0` to `t3`: attack SYNs first occupy the bounded half-open backlog, the legitimate `L1` attempt is dropped while the queue is full, and expiry eventually releases those entries. Then change only **SYN-cookie mode**. The legitimate outcome becomes established without allocating half-open entries, while the attack-packet and cookie-check counters remain non-zero—the mitigation moves the state boundary; it does not make unwanted traffic disappear.

4.6 Observe Backpressure before the Gateway Runs out of Memory

Assume the source produces 200 bytes per second while the receiving service drains only 120 bytes per second. The backlog grows at 80 bytes per second. A free queue of 4,800 bytes lasts 4,800 divided by 80 = 60 s under those constant rates. After that, the application needs a defined response such as pausing collection, storing elsewhere or reporting a gap; a successful socket connection does not create more memory.

The TCP receive window can apply flow control when the receiving endpoint cannot accept more bytes. Congestion control addresses a different limit: how much traffic the path can carry without excessive congestion. Neither mechanism determines which telemetry records the product may discard or how long a command remains valid in a sender-side queue.

Read Figure 4.3 from endpoint roles into framing, acknowledgements and flow control. Follow the trace through close or reset as well. The service may acknowledge bytes into its receive buffer before its parser accepts a complete record, so transport progress and durable application storage need separate evidence.

Predict what happens if the gateway reconnects after a timeout and resends the last record. A new established connection does not remember that record’s application identity. The service needs a repeat-handling rule if storing it twice would be wrong. Next, return an explicit validation error over the healthy connection. The gateway must retain the difference between delivered bytes and rejected content.

The connection-state attack diagrams extend the same resource lesson. Figure 4.1 contrasts completed handshakes with half-open backlog pressure, while the reset diagram identifies a separate acceptance boundary. Keep tuning and filtering tied to measured legitimate-service behaviour rather than assuming a larger queue solves every source of pressure.

This module’s TCP promise is powerful but bounded: ordered transport bytes, connection state and flow mechanisms support the service. The application still owns record framing, persistence, expiry and physical outcomes. A queue-growth calculation gives operations a concrete time budget for responding to a slow receiver before the gateway’s useful history is lost.

4.7 Summary

TCP is a strong transport candidate when a reviewed IoT path benefits from connection state, an ordered byte stream, acknowledgements, retransmission behavior, flow control, and explicit close behavior. The evidence still has to stay bounded. TCP can support a transport decision, but it does not prove the receiver parsed, authorized, stored, or acted on an application message.

The useful review record names the application path, endpoint roles, stream framing rule, acknowledgement and retransmission observations, backpressure behavior, close state, security boundary, decision, and retest trigger. Missing framing, missing receiver evidence, or unclear close behavior should lead to revision instead of broad acceptance.

4.8 Key Takeaway

Use TCP evidence to review connection and byte-stream behavior; use receiver evidence to prove application meaning, cleanup, and retry safety. Do not let a successful connection stand in for an application outcome.

4.9 See Also

Transport Layer Overview

Transport Layer Overview

User Datagram Protocol (UDP)

User Datagram Protocol (UDP)

TCP vs UDP: Comparison and Selection

TCP vs UDP: Comparison and Selection

Retries & Sequence Numbers

Retries & Sequence Numbers