Skip to content

tcp: random ephemeral ports with TIME_WAIT quarantine - #196

Merged
douglasmun merged 1 commit into
mainfrom
fix/ephemeral-port-random
Oct 21, 2026
Merged

douglasmun merged 1 commit into
mainfrom
fix/ephemeral-port-random

Conversation

@douglasmun

Copy link
Copy Markdown
Owner

Fixes the five issues recorded in doc/EPHEMERAL_PORT_ISSUES.md (PR #195).

Test

New harness verify/verify-tcp-ephemeral-port.sh (FAULT_INJECT tcpport command):

  • Runs ten real socket/connect/close cycles with transmission muted.
  • Runs a synthetic full table that forces a TIME_WAIT eviction.
  • Positive controls: every draw falls in range, and an unrelated port and the evicted port read free once their quarantine has expired.
Mutant Result
main's allocator, verbatim (fail-first) FAIL: draws 49152, 49153, ...
Quarantine not consulted FAIL on evicted
CLOSED-slot exception restored FAIL on closed

The TCP_LOCK part of #5 has no witness; the race it closes is a 1-in-16384 event.

Regression (TCP harnesses)

Harness Result
verify-tcp-ephemeral-port PASS
verify-tcp-state-fixes PASS
verify-tcp-socket-cap PASS
verify-tcpsock-race PASS
verify-tcp-quiet PASS
verify-tcp-serverpath PASS
verify-tcp-rx-counters FAIL, pre-existing: fails identically on main (0f03f03). Injected mcast frames never reach the guest (RX ring 0) on this host.

🤖 Generated with Claude Code

Fixes the five issues in doc/EPHEMERAL_PORT_ISSUES.md:

1. tcp_allocate_port() draws each port from global_csprng over
   49152-65535 (up to 64 tries) instead of counting up from 49152 on
   every boot. No fallback: the CSPRNG fails closed and is up before
   any network bring-up.
2. The unreachable exhaustion check and its counter are gone.
3. Local-port-only collision check kept, now documented.
4. tcp_evict_oldest_time_wait() quarantines the evicted port for the
   rest of its 30 s; tcp_port_is_free() refuses quarantined ports.
   Random allocation would otherwise reuse it early.
5. tcp_connect() holds TCP_LOCK across state check, half-open count and
   allocation; an in_use CLOSED slot now holds its port.

verify-tcp-ephemeral-port.sh (FAULT_INJECT `tcpport`) drives ten real
connect cycles and a synthetic eviction. Mutation-checked: main's
allocator, no quarantine check, and the CLOSED exception each FAIL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@douglasmun
douglasmun merged commit fbbf938 into main Oct 21, 2026
2 checks passed
@douglasmun
douglasmun deleted the fix/ephemeral-port-random branch October 21, 2026 14:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant