Skip to contentSkip to conversation

tcp: fix false exhaustion of odd-sized bind port ranges

PATCH Applied Florin Badita-Nistor 4 participants 6 messages Nov 6 – Nov 12

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v2 cover tcp: fix false exhaustion of odd-sized bind port ranges

Fix false bind() exhaustion when an odd-sized local port range still contains an eligible free port. The wrap can flip parity in odd-sized ranges; even-sized scan sequences are unchanged. The namespace-wide connect() allocator is not changed by this series.

Earlier x86-64 KVM validation of this unchanged allocator/test code:
- Regression test: four failures before, zero after (eight cases).
- Full port-range suite: four failures before, zero after (80 cases); two existing SCTP XPASS results unchanged.
- Go net.Listen, 100 attempts per IP version: 100 failures before, zero after; explicit free-port controls succeed in both kernels.

Changes in v2:
- Target net-next and drop the stable Cc, as requested by Eric.
- Document parity changes on odd wraps and scope the fix to bind().
- Shorten the cover letter.

v1: https://lore.kernel.org/netdev/CADnh+D0zSzAyYCLo5cXU56o9X-P3RG3N2ix7ARPrP95d8sBXmg@mail.gmail.com/

Florin Badita-Nistor (2):
tcp: avoid false bind exhaustion with odd-sized port ranges selftests/net: cover odd-sized local port ranges with one free port

 net/ipv4/inet_connection_sock.c               |  2 -
 .../selftests/net/ip_local_port_range.c       | 67 ++++++++++++++++++-
 2 files changed, 64 insertions(+), 5 deletions(-)

base-commit: bb67589c87249c9bc2415ab11a754d6e303774e3

Signature · 1 line
2.51.0
#1 lore raw

PATCH v2 1/2 tcp: avoid false bind exhaustion with odd-sized port ranges

inet_csk_find_open_port() rounds the range length down to an even number but keeps the original exclusive upper bound for wrapping. For an odd-sized range, the two scans can therefore miss a valid port and return EADDRINUSE while an eligible port remains free.

For example, restrict a TCP socket to IP_LOCAL_PORT_RANGE [40000, 40002] and hold explicit binds on 40000 and 40001. bind(..., 0) always fails, although an explicit bind to 40002 succeeds. Both IPv4 and IPv6 TCP and MPTCP are affected. A namespace-wide odd-sized ip_local_port_range can also trigger the failure without a per-socket range setting.

Keep the full length for the scan bound and wrapping. The two scans then cover every candidate in an odd-sized range, with at most one repeated candidate when exhausted. Even-sized candidate sequences remain unchanged.

For odd-sized ranges, subtracting an odd remaining value when wrapping flips parity. The first scan can therefore also select offsets of the parity preferred by __inet_hash_connect(). Namespace-wide ranges with same-parity endpoints already trigger a sysctl warning, while connect() uses step 1 for a per-socket IP_LOCAL_PORT_RANGE.

This only fixes bind() allocation. The rounding in __inet_hash_connect() for namespace-wide ranges is unchanged, so connect() can still miss a port in an odd-sized namespace range.

The issue was triggered while developing port-range selftests with Codex assistance, then confirmed using userspace reproducers on unmodified kernels. No kernel instrumentation or fault injection was needed. Booted x86-64 KVM kernels were tested against the regression selftest, the full ip_local_port_range suite, and a Go net.Listen reproducer. The Go reproducer fails 100/100 times per IP version before the fix and 0/100 afterwards with a three-port namespace range and two listeners occupying its first two ports.

Fixes ea8add2b1903 ("tcp/dccp: better use of ephemeral ports in bind()")
---
 net/ipv4/inet_connection_sock.c | 2 --
 1 file changed, 2 deletions(-)
net/ipv4/inet_connection_sock.c +0 -2
index e56beec43..755fcea35 100644
@@ -343,8 +343,6 @@ inet_csk_find_open_port(const struct sock *sk, struct inet_bind_bucket **tb_ret,
 			low = half;
 	}
 	remaining = high - low;
-	if (likely(remaining > 1))
-		remaining &= ~1U;
 
 	offset = get_random_u32_below(remaining);
 	/* __inet_hash_connect() favors ports having @low parity
Signature · 1 line
2.51.0
#4 lore raw

PATCH v2 2/2 selftests/net: cover odd-sized local port ranges with one free port

In reply to Florin Badita-Nistor

Leave each port in three- and five-port socket-local ranges as the only available candidate and verify that bind(..., 0) can allocate it. Cover both lower-bound parities and repeat allocation to vary the random starting offset. Use the existing IPv4/IPv6 TCP, UDP, SCTP and MPTCP fixture variants.

This catches the false EADDRINUSE caused by rounding an odd-sized range down during TCP port allocation. Without the preceding fix, the TCP and MPTCP variants fail on both IP versions when the last port in a three-port range is the only free one. With the fix, all eight variants pass.

Allow the loopback bind helper to take a port so the test can hold explicit binds on every other candidate. Retain the existing helper for automatic binding and run under the existing isolated-network-namespace wrapper.

The regression test was developed with Codex assistance and exercised on booted x86-64 KVM kernels before and after the fix.

---
 .../selftests/net/ip_local_port_range.c       | 67 ++++++++++++++++++-
 1 file changed, 64 insertions(+), 3 deletions(-)
tools/testing/selftests/net/ip_local_port_range.c +64 -3
index 3d32b33cb..c17d95045 100644
@@ -44,7 +44,7 @@ static int get_so_domain(int fd)
 	return domain;
 }
 
-static int bind_to_loopback_any_port(int fd)
+static int bind_to_loopback_port(int fd, __u16 port)
 {
 	union {
 		struct sockaddr sa;
@@ -57,13 +57,13 @@ static int bind_to_loopback_any_port(int fd)
 	switch (get_so_domain(fd)) {
 	case AF_INET:
 		addr.v4.sin_family = AF_INET;
-		addr.v4.sin_port = htons(0);
+		addr.v4.sin_port = htons(port);
 		addr.v4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
 		addr_len = sizeof(addr.v4);
 		break;
 	case AF_INET6:
 		addr.v6.sin6_family = AF_INET6;
-		addr.v6.sin6_port = htons(0);
+		addr.v6.sin6_port = htons(port);
 		addr.v6.sin6_addr = in6addr_loopback;
 		addr_len = sizeof(addr.v6);
 		break;
@@ -74,6 +74,11 @@ static int bind_to_loopback_any_port(int fd)
 	return bind(fd, &addr.sa, addr_len);
 }
 
+static int bind_to_loopback_any_port(int fd)
+{
+	return bind_to_loopback_port(fd, 0);
+}
+
 static int get_sock_port(int fd)
 {
 	union {
@@ -301,6 +306,62 @@ TEST_F(ip_local_port_range, single_port_range)
 	}
 }
 
+/* Leave each port in turn as the only available one. An odd-sized range
+ * must not report exhaustion while a port at either end is still free.
+ */
+TEST_F(ip_local_port_range, odd_port_range)
+{
+	const struct {
+		__u16 low;
+		__u16 high;
+	} ranges[] = {
+		{ 40000, 40002 },
+		{ 40001, 40003 },
+		{ 40000, 40004 },
+		{ 40001, 40005 },
+	};
+	int i, j, port, free_port, fd, err;
+	__u32 range;
+	int fds[5];
+
+	for (i = 0; i < ARRAY_SIZE(ranges); i++) {
+		range = pack_port_range(ranges[i].low, ranges[i].high);
+		for (free_port = ranges[i].low; free_port <= ranges[i].high; free_port++) {
+			for (port = ranges[i].low; port <= ranges[i].high; port++) {
+				j = port - ranges[i].low;
+				fds[j] = -1;
+				if (port == free_port)
+					continue;
+				fd = socket(variant->so_domain, variant->so_type,
+					    variant->so_protocol);
+				ASSERT_GE(fd, 0) TH_LOG("socket failed");
+				fds[j] = fd;
+				err = bind_to_loopback_port(fd, port);
+				ASSERT_EQ(err, 0) TH_LOG("bind(%d) failed", port);
+			}
+
+			/* Exercise different random starting offsets. */
+			for (j = 0; j < 16; j++) {
+				fd = socket(variant->so_domain, variant->so_type,
+					    variant->so_protocol);
+				ASSERT_GE(fd, 0) TH_LOG("socket failed");
+				err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE,
+						 &range, sizeof(range));
+				ASSERT_EQ(err, 0) TH_LOG("setsockopt(IP_LOCAL_PORT_RANGE) failed");
+				err = bind_to_loopback_any_port(fd);
+				ASSERT_EQ(err, 0) TH_LOG("range %d-%d, free port %d",
+						       ranges[i].low, ranges[i].high, free_port);
+				ASSERT_EQ(get_sock_port(fd), free_port);
+				ASSERT_EQ(close(fd), 0);
+			}
+
+			for (j = 0; j <= ranges[i].high - ranges[i].low; j++)
+				if (fds[j] >= 0)
+					ASSERT_EQ(close(fds[j]), 0);
+		}
+	}
+}
+
 #define REUSEADDR	0x1
 #define REUSEPORT	0x2
 
Signature · 1 line
2.51.0
#2 lore raw

Re: [PATCH net-next v2 1/2] tcp: avoid false bind exhaustion with odd-sized port ranges

In reply to Florin Badita-Nistor
Quoted 8 lines · Florin Badita-Nistor

inet_csk_find_open_port() rounds the range length down to an even number but keeps the original exclusive upper bound for wrapping. For an odd-sized range, the two scans can therefore miss a valid port and return EADDRINUSE while an eligible port remains free.

For example, restrict a TCP socket to IP_LOCAL_PORT_RANGE [40000, 40002] and hold explicit binds on 40000 and 40001. bind(..., 0) always fails, although an explicit bind to 40002 succeeds. Both IPv4 and IPv6 TCP and

This is the reason of warning in set_local_port_range(), so kind of WAI to me.

The change should be fine, but we should remove the warning.

Quoted 49 lines

MPTCP are affected. A namespace-wide odd-sized ip_local_port_range can also trigger the failure without a per-socket range setting.

Keep the full length for the scan bound and wrapping. The two scans then cover every candidate in an odd-sized range, with at most one repeated candidate when exhausted. Even-sized candidate sequences remain unchanged.

For odd-sized ranges, subtracting an odd remaining value when wrapping flips parity. The first scan can therefore also select offsets of the parity preferred by __inet_hash_connect(). Namespace-wide ranges with same-parity endpoints already trigger a sysctl warning, while connect() uses step 1 for a per-socket IP_LOCAL_PORT_RANGE.

This only fixes bind() allocation. The rounding in __inet_hash_connect() for namespace-wide ranges is unchanged, so connect() can still miss a port in an odd-sized namespace range.

The issue was triggered while developing port-range selftests with Codex assistance, then confirmed using userspace reproducers on unmodified kernels. No kernel instrumentation or fault injection was needed. Booted x86-64 KVM kernels were tested against the regression selftest, the full ip_local_port_range suite, and a Go net.Listen reproducer. The Go reproducer fails 100/100 times per IP version before the fix and 0/100 afterwards with a three-port namespace range and two listeners occupying its first two ports.

Fixes ea8add2b1903 ("tcp/dccp: better use of ephemeral ports in bind()")
---
 net/ipv4/inet_connection_sock.c | 2 --
 1 file changed, 2 deletions(-)
net/ipv4/inet_connection_sock.c +0 -2
index e56beec43..755fcea35 100644
@@ -343,8 +343,6 @@ inet_csk_find_open_port(const struct sock *sk, struct inet_bind_bucket **tb_ret,
 			low = half;
 	}
 	remaining = high - low;
-	if (likely(remaining > 1))
-		remaining &= ~1U;
 
 	offset = get_random_u32_below(remaining);
 	/* __inet_hash_connect() favors ports having @low parity
Signature · 1 line
2.51.0
maintainer Reviewed-by
#3 lore raw

Re: [PATCH net-next v2 1/2] tcp: avoid false bind exhaustion with odd-sized port ranges

Quoted 7 lines · Kuniyuki Iwashima
Quoted 5 lines · Florin Badita-Nistor

inet_csk_find_open_port() rounds the range length down to an even number but keeps the original exclusive upper bound for wrapping. For an odd-sized range, the two scans can therefore miss a valid port and return EADDRINUSE while an eligible port remains free.

Quoted 8 lines
Quoted 3 lines

For example, restrict a TCP socket to IP_LOCAL_PORT_RANGE [40000, 40002] and hold explicit binds on 40000 and 40001. bind(..., 0) always fails, although an explicit bind to 40002 succeeds. Both IPv4 and IPv6 TCP and

This is the reason of warning in set_local_port_range(), so kind of WAI to me.

The change should be fine, but we should remove the warning.

I would keep the warning.

It was added in commit ed2dfd900992 ("tcp/dccp: warn user for preferred ip_local_port_range") because connect() wants an even number of ports. This is still the case: __inet_hash_connect() rounds an odd-sized netns range down to an even size, so connect() can still miss one port there.

The per-socket IP_LOCAL_PORT_RANGE case has no warning at all, and bind() can miss a free port there without any hint to the user. This patch fixes that.

#5 lore raw
In reply to Florin Badita-Nistor
This series was applied to netdev/net-next.git (main) by Jakub Kicinski <[email protected]>:

Hello:

This series was applied to netdev/net-next.git (main) by Jakub Kicinski <[email protected]>:

Quoted 5 lines · On Fri, 6 Nov 2026 19:14:40 +0200 you wrote:

Fix false bind() exhaustion when an odd-sized local port range still contains an eligible free port. The wrap can flip parity in odd-sized ranges; even-sized scan sequences are unchanged. The namespace-wide connect() allocator is not changed by this series.

Quoted 8 lines

Earlier x86-64 KVM validation of this unchanged allocator/test code:
- Regression test: four failures before, zero after (eight cases).
- Full port-range suite: four failures before, zero after (80 cases); two existing SCTP XPASS results unchanged.
- Go net.Listen, 100 attempts per IP version: 100 failures before, zero after; explicit free-port controls succeed in both kernels.

[...]

Here is the summary with links:
- [net-next,v2,1/2] tcp: avoid false bind exhaustion with odd-sized port ranges

    https://git.kernel.org/netdev/net-next/c/c7d11f97e8a2
  - [net-next,v2,2/2] selftests/net: cover odd-sized local port ranges with one free port
    https://git.kernel.org/netdev/net-next/c/ca133dd5fb20

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html