lighthouse icon indicating copy to clipboard operation
lighthouse copied to clipboard

Fix TOCTOU bug in unused_port module

Open jimmygchen opened this issue 1 month ago • 2 comments

Description

The current unused_tcp*_port() and unused_udp*_port() functions in the unused_port module have a Time-of-Check-Time-of-Use (TOCTOU) vulnerability. These functions bind to port 0, get the assigned port number, then immediately close the socket. Between getting the port number and later binding to it, another process can claim the same port, causing test flakiness or binding failures.

PR #8016 by @sashaodessa proposed a fix by replacing these functions with secure APIs that return already-bound sockets:

  • bind_tcp4_any() / bind_tcp6_any() → returns TcpListener
  • bind_udp4_any() / bind_udp6_any() → returns UdpSocket

The PR went stale without merging. We should implement this fix to eliminate the race condition.

Steps to resolve

  1. Review the changes from #8016 and update them for current unstable
  2. Replace usage of the unsafe port-finding functions with the new bound socket APIs
  3. Remove the old functions and LRU cache that provided false security
  4. Test that the new APIs work correctly across the test suite

Additional Info

Original PR: https://github.com/sigp/lighthouse/pull/8016

jimmygchen avatar Nov 28 '25 02:11 jimmygchen

@jimmygchen Hey new contributor here. Is it cool I work on this?

0xmrree avatar Dec 04 '25 19:12 0xmrree

Went ahead and implemented first part of fix in above pull request

0xmrree avatar Dec 08 '25 03:12 0xmrree