Skip to contentSkip to conversation

Add IP_LOCAL_PORT_RANGE socket option

PATCH Applied Jakub Sitnicki 4 participants 6 messages Jan 24, 2023 – Jan 26, 2023

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

v6 cover Add IP_LOCAL_PORT_RANGE socket option

This patch set is a follow up to the "How to share IPv4 addresses by partitioning the port space" talk given at LPC 2022 [1].

Please see patch #1 for the motivation & the use case description. Patch #2 adds tests exercising the new option in various scenarios.

Documentation
-------------

Proposed update to the ip(7) man-page:

IP_LOCAL_PORT_RANGE (since Linux X.Y)
Set or get the per-socket default local port range. This option can be used to clamp down the global local port range, defined by the ip_local_port_range /proc interface described below, for a given socket.

The option takes an uint32_t value with the high 16 bits set to the upper range bound, and the low 16 bits set to the lower range bound. Range bounds are inclusive. The 16-bit values should be in host byte order.

The lower bound has to be less than the upper bound when both bounds are not zero. Otherwise, setting the option fails with EINVAL.

If either bound is outside of the global local port range, or is zero, then that bound has no effect.

To reset the setting, pass zero as both the upper and the lower bound.

Interaction with SELinux bind() hook
------------------------------------

SELinux bind() hook - selinux_socket_bind() - performs a permission check if the requested local port number lies outside of the netns ephemeral port range.

The proposed socket option cannot be used change the ephemeral port range to extend beyond the per-netns port range, as set by net.ipv4.ip_local_port_range.

Hence, there is no interaction with SELinux, AFAICT.

Changelog:
---------

v5 -> v6:
v5: https://lore.kernel.org/r/[email protected]

* Move changelog in individual patches below the trailer. (Leon)

v4 -> v5:
v4: https://lore.kernel.org/r/[email protected]

* Code changes called out in individual patches.

v3 -> v4:
v3: https://lore.kernel.org/r/[email protected]

* Highlight that port bounds should be in host byte order. (Neal)

v2 -> v3:
v2: https://lore.kernel.org/r/[email protected]

* Describe interaction considerations with SELinux.
* Code changes called out in individual patches.

v1 -> v2:
v1: https://lore.kernel.org/netdev/[email protected]/

* Fix the corner case when the per-socket range doesn't overlap with the per-netns range. Fallback correctly to the per-netns range. (Kuniyuki)

* selftests: Instead of iterating over socket families (ip4, ip6) and types (tcp, udp), generate tests for each combo from a template. This keeps the code indentation level down and makes tests more granular.

* Rewrite man-page prose:
- explain how to unset the option,
- document when EINVAL is returned.

RFC -> v1
RFC: https://lore.kernel.org/netdev/[email protected]/

* Allow either the high bound or the low bound, or both, to be zero
* Add getsockopt support
* Add selftests

Links:
------

[1]: https://lpc.events/event/16/contributions/1349/

To: [email protected]

Cc "David S. Miller" <[email protected]>
Cc Eric Dumazet <[email protected]>
Cc Jakub Kicinski <[email protected]>
Cc Paolo Abeni <[email protected]>
Cc Kuniyuki Iwashima <[email protected]>
Cc Neal Cardwell <[email protected]>
Cc Leon Romanovsky <[email protected]>
Cc Paul Moore <[email protected]>
Cc Stephen Smalley <[email protected]>
Cc Eric Paris <[email protected]>

---
Jakub Sitnicki (2):
inet: Add IP_LOCAL_PORT_RANGE socket option selftests/net: Cover the IP_LOCAL_PORT_RANGE socket option

 include/net/inet_sock.h                            |   4 +
 include/net/ip.h                                   |   3 +-
 include/uapi/linux/in.h                            |   1 +
 net/ipv4/inet_connection_sock.c                    |  25 +-
 net/ipv4/inet_hashtables.c                         |   2 +-
 net/ipv4/ip_sockglue.c                             |  18 +
 net/ipv4/udp.c                                     |   2 +-
 net/sctp/socket.c                                  |   2 +-
 tools/testing/selftests/net/Makefile               |   2 +
 tools/testing/selftests/net/ip_local_port_range.c  | 447 +++++++++++++++++++++
 tools/testing/selftests/net/ip_local_port_range.sh |   5 +
 11 files changed, 505 insertions(+), 6 deletions(-)
#1 lore raw

PATCH v6 1/2 inet: Add IP_LOCAL_PORT_RANGE socket option

Users who want to share a single public IP address for outgoing connections between several hosts traditionally reach for SNAT. However, SNAT requires state keeping on the node(s) performing the NAT.

A stateless alternative exists, where a single IP address used for egress can be shared between several hosts by partitioning the available ephemeral port range. In such a setup:

1. Each host gets assigned a disjoint range of ephemeral ports.
2. Applications open connections from the host-assigned port range.
3. Return traffic gets routed to the host based on both, the destination IP and the destination port.

An application which wants to open an outgoing connection (connect) from a given port range today can choose between two solutions:

1. Manually pick the source port by bind()'ing to it before connect()'ing the socket.

This approach has a couple of downsides:

a) Search for a free port has to be implemented in the user-space. If the chosen 4-tuple happens to be busy, the application needs to retry from a different local port number.

Detecting if 4-tuple is busy can be either easy (TCP) or hard (UDP). In TCP case, the application simply has to check if connect() returned an error (EADDRNOTAVAIL). That is assuming that the local port sharing was enabled (REUSEADDR) by all the sockets.

# Assume desired local port range is 60_000-60_511 s = socket(AF_INET, SOCK_STREAM) s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) s.bind(("192.0.2.1", 60_000)) s.connect(("1.1.1.1", 53))
# Fails only if 192.0.2.1:60000 -> 1.1.1.1:53 is busy # Application must retry with another local port

In case of UDP, the network stack allows binding more than one socket to the same 4-tuple, when local port sharing is enabled (REUSEADDR). Hence detecting the conflict is much harder and involves querying sock_diag and toggling the REUSEADDR flag [1].

b) For TCP, bind()-ing to a port within the ephemeral port range means that no connecting sockets, that is those which leave it to the network stack to find a free local port at connect() time, can use the this port.

IOW, the bind hash bucket tb->fastreuse will be 0 or 1, and the port will be skipped during the free port search at connect() time.

2. Isolate the app in a dedicated netns and use the use the per-netns ip_local_port_range sysctl to adjust the ephemeral port range bounds.

The per-netns setting affects all sockets, so this approach can be used only if:

- there is just one egress IP address, or
- the desired egress port range is the same for all egress IP addresses used by the application.

For TCP, this approach avoids the downsides of (1). Free port search and 4-tuple conflict detection is done by the network stack:

     system("sysctl -w net.ipv4.ip_local_port_range='60000 60511'")

     s = socket(AF_INET, SOCK_STREAM)
     s.setsockopt(SOL_IP, IP_BIND_ADDRESS_NO_PORT, 1)
     s.bind(("192.0.2.1", 0))
     s.connect(("1.1.1.1", 53))
     # Fails if all 4-tuples 192.0.2.1:60000-60511 -> 1.1.1.1:53 are busy

For UDP this approach has limited applicability. Setting the IP_BIND_ADDRESS_NO_PORT socket option does not result in local source port being shared with other connected UDP sockets.

Hence relying on the network stack to find a free source port, limits the number of outgoing UDP flows from a single IP address down to the number of available ephemeral ports.

To put it another way, partitioning the ephemeral port range between hosts using the existing Linux networking API is cumbersome.

To address this use case, add a new socket option at the SOL_IP level, named IP_LOCAL_PORT_RANGE. The new option can be used to clamp down the ephemeral port range for each socket individually.

The option can be used only to narrow down the per-netns local port range. If the per-socket range lies outside of the per-netns range, the latter takes precedence.

UAPI-wise, the low and high range bounds are passed to the kernel as a pair of u16 values in host byte order packed into a u32. This avoids pointer passing.

PORT_LO = 40_000
PORT_HI = 40_511

s = socket(AF_INET, SOCK_STREAM)
v = struct.pack("I", PORT_HI << 16 | PORT_LO) s.setsockopt(SOL_IP, IP_LOCAL_PORT_RANGE, v) s.bind(("127.0.0.1", 0))
s.getsockname()
# Local address between ("127.0.0.1", 40_000) and ("127.0.0.1", 40_511),

  # if there is a free port. EADDRINUSE otherwise.

[1] https://github.com/cloudflare/cloudflare-blog/blob/232b432c1d57/2022-02-connectx/connectx.py#L116

---
v4 -> v5:
* Use the fact that netns port range starts at 1 when clamping. (Kuniyuki)

v3 -> v4:
* Clarify that u16 values are in host byte order (Neal)

v2 -> v3:
* Make SCTP bind()/bind_add() respect IP_LOCAL_PORT_RANGE option (Eric)

v1 -> v2:
* Fix the corner case when the per-socket range doesn't overlap with the per-netns range. Fallback correctly to the per-netns range. (Kuniyuki)

---
 include/net/inet_sock.h         |  4 ++++
 include/net/ip.h                |  3 ++-
 include/uapi/linux/in.h         |  1 +
 net/ipv4/inet_connection_sock.c | 25 +++++++++++++++++++++++--
 net/ipv4/inet_hashtables.c      |  2 +-
 net/ipv4/ip_sockglue.c          | 18 ++++++++++++++++++
 net/ipv4/udp.c                  |  2 +-
 net/sctp/socket.c               |  2 +-
 8 files changed, 51 insertions(+), 6 deletions(-)
include/net/inet_sock.h +4 -0
index bf5654ce711e..51857117ac09 100644
@@ -249,6 +249,10 @@ struct inet_sock {
 	__be32			mc_addr;
 	struct ip_mc_socklist __rcu	*mc_list;
 	struct inet_cork_full	cork;
+	struct {
+		__u16 lo;
+		__u16 hi;
+	}			local_port_range;
 };
 
 #define IPCORK_OPT	1	/* ip-options has been held in ipcork.opt */
include/net/ip.h +2 -1
index 144bdfbb25af..c3fffaa92d6e 100644
@@ -340,7 +340,8 @@ static inline u64 snmp_fold_field64(void __percpu *mib, int offt, size_t syncp_o
 	} \
 }
 
-void inet_get_local_port_range(struct net *net, int *low, int *high);
+void inet_get_local_port_range(const struct net *net, int *low, int *high);
+void inet_sk_get_local_port_range(const struct sock *sk, int *low, int *high);
 
 #ifdef CONFIG_SYSCTL
 static inline bool inet_is_local_reserved_port(struct net *net, unsigned short port)
include/uapi/linux/in.h +1 -0
index 07a4cb149305..4b7f2df66b99 100644
@@ -162,6 +162,7 @@ struct in_addr {
 #define MCAST_MSFILTER			48
 #define IP_MULTICAST_ALL		49
 #define IP_UNICAST_IF			50
+#define IP_LOCAL_PORT_RANGE		51
 
 #define MCAST_EXCLUDE	0
 #define MCAST_INCLUDE	1
net/ipv4/inet_connection_sock.c +23 -2
index d1f837579398..6ed7e65de494 100644
@@ -117,7 +117,7 @@ bool inet_rcv_saddr_any(const struct sock *sk)
 	return !sk->sk_rcv_saddr;
 }
 
-void inet_get_local_port_range(struct net *net, int *low, int *high)
+void inet_get_local_port_range(const struct net *net, int *low, int *high)
 {
 	unsigned int seq;
 
@@ -130,6 +130,27 @@ void inet_get_local_port_range(struct net *net, int *low, int *high)
 }
 EXPORT_SYMBOL(inet_get_local_port_range);
 
+void inet_sk_get_local_port_range(const struct sock *sk, int *low, int *high)
+{
+	const struct inet_sock *inet = inet_sk(sk);
+	const struct net *net = sock_net(sk);
+	int lo, hi, sk_lo, sk_hi;
+
+	inet_get_local_port_range(net, &lo, &hi);
+
+	sk_lo = inet->local_port_range.lo;
+	sk_hi = inet->local_port_range.hi;
+
+	if (unlikely(lo <= sk_lo && sk_lo <= hi))
+		lo = sk_lo;
+	if (unlikely(lo <= sk_hi && sk_hi <= hi))
+		hi = sk_hi;
+
+	*low = lo;
+	*high = hi;
+}
+EXPORT_SYMBOL(inet_sk_get_local_port_range);
+
 static bool inet_use_bhash2_on_bind(const struct sock *sk)
 {
 #if IS_ENABLED(CONFIG_IPV6)
@@ -316,7 +337,7 @@ inet_csk_find_open_port(const struct sock *sk, struct inet_bind_bucket **tb_ret,
 ports_exhausted:
 	attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
 other_half_scan:
-	inet_get_local_port_range(net, &low, &high);
+	inet_sk_get_local_port_range(sk, &low, &high);
 	high++; /* [32768, 60999] -> [32768, 61000[ */
 	if (high - low < 4)
 		attempt_half = 0;
net/ipv4/inet_hashtables.c +1 -1
index 7a13dd7f546b..e41fdc38ce19 100644
@@ -1016,7 +1016,7 @@ int __inet_hash_connect(struct inet_timewait_death_row *death_row,
 
 	l3mdev = inet_sk_bound_l3mdev(sk);
 
-	inet_get_local_port_range(net, &low, &high);
+	inet_sk_get_local_port_range(sk, &low, &high);
 	high++; /* [32768, 60999] -> [32768, 61000[ */
 	remaining = high - low;
 	if (likely(remaining > 1))
net/ipv4/ip_sockglue.c +18 -0
index 9f92ae35bb01..b511ff0adc0a 100644
@@ -923,6 +923,7 @@ int do_ip_setsockopt(struct sock *sk, int level, int optname,
 	case IP_CHECKSUM:
 	case IP_RECVFRAGSIZE:
 	case IP_RECVERR_RFC4884:
+	case IP_LOCAL_PORT_RANGE:
 		if (optlen >= sizeof(int)) {
 			if (copy_from_sockptr(&val, optval, sizeof(val)))
 				return -EFAULT;
@@ -1365,6 +1366,20 @@ int do_ip_setsockopt(struct sock *sk, int level, int optname,
 		WRITE_ONCE(inet->min_ttl, val);
 		break;
 
+	case IP_LOCAL_PORT_RANGE:
+	{
+		const __u16 lo = val;
+		const __u16 hi = val >> 16;
+
+		if (optlen != sizeof(__u32))
+			goto e_inval;
+		if (lo != 0 && hi != 0 && lo > hi)
+			goto e_inval;
+
+		inet->local_port_range.lo = lo;
+		inet->local_port_range.hi = hi;
+		break;
+	}
 	default:
 		err = -ENOPROTOOPT;
 		break;
@@ -1743,6 +1758,9 @@ int do_ip_getsockopt(struct sock *sk, int level, int optname,
 	case IP_MINTTL:
 		val = inet->min_ttl;
 		break;
+	case IP_LOCAL_PORT_RANGE:
+		val = inet->local_port_range.hi << 16 | inet->local_port_range.lo;
+		break;
 	default:
 		sockopt_release_sock(sk);
 		return -ENOPROTOOPT;
net/ipv4/udp.c +1 -1
index 9592fe3e444a..c605d171eb2d 100644
@@ -248,7 +248,7 @@ int udp_lib_get_port(struct sock *sk, unsigned short snum,
 		int low, high, remaining;
 		unsigned int rand;
 
-		inet_get_local_port_range(net, &low, &high);
+		inet_sk_get_local_port_range(sk, &low, &high);
 		remaining = (high - low) + 1;
 
 		rand = get_random_u32();
net/sctp/socket.c +1 -1
index a98511b676cd..b91616f819de 100644
@@ -8322,7 +8322,7 @@ static int sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
 		int low, high, remaining, index;
 		unsigned int rover;
 
-		inet_get_local_port_range(net, &low, &high);
+		inet_sk_get_local_port_range(sk, &low, &high);
 		remaining = (high - low) + 1;
 		rover = get_random_u32_below(remaining) + low;
 
Signature · 1 line
2.39.0
Reviewed-by on v6 1/2
#2 lore raw

Re: [PATCH net-next v6 1/2] inet: Add IP_LOCAL_PORT_RANGE socket option

Quoted 9 lines · Jakub Sitnicki

Users who want to share a single public IP address for outgoing connections between several hosts traditionally reach for SNAT. However, SNAT requires state keeping on the node(s) performing the NAT.

A stateless alternative exists, where a single IP address used for egress can be shared between several hosts by partitioning the available ephemeral port range. In such a setup:

Quoted 6 lines

[1] https://github.com/cloudflare/cloudflare-blog/blob/232b432c1d57/2022-02-connectx/connectx.py#L116

#3 lore raw

PATCH v6 2/2 selftests/net: Cover the IP_LOCAL_PORT_RANGE socket option

In reply to Jakub Sitnicki

Exercise IP_LOCAL_PORT_RANGE socket option in various scenarios:

1. pass invalid values to setsockopt
2. pass a range outside of the per-netns port range
3. configure a single-port range
4. exhaust a configured multi-port range
5. check interaction with late-bind (IP_BIND_ADDRESS_NO_PORT)
6. set then get the per-socket port range

---
v2 -> v3:
* Switch from CPP-based templates to FIXTURE_VARIANT. (Kuniyuki)
* Cover SOCK_STREAM/IPPROTO_SCTP where possible.

v1 -> v2:
* selftests: Instead of iterating over socket families (ip4, ip6) and types (tcp, udp), generate tests for each combo from a template. This keeps the code indentation level down and makes tests more granular.

---
 tools/testing/selftests/net/Makefile               |   2 +
 tools/testing/selftests/net/ip_local_port_range.c  | 447 +++++++++++++++++++++
 tools/testing/selftests/net/ip_local_port_range.sh |   5 +
 3 files changed, 454 insertions(+)
tools/testing/selftests/net/Makefile +2 -0
index 47314f0b3006..951bd5342bc6 100644
@@ -45,6 +45,7 @@ TEST_PROGS += arp_ndisc_untracked_subnets.sh
 TEST_PROGS += stress_reuseport_listen.sh
 TEST_PROGS += l2_tos_ttl_inherit.sh
 TEST_PROGS += bind_bhash.sh
+TEST_PROGS += ip_local_port_range.sh
 TEST_PROGS_EXTENDED := in_netns.sh setup_loopback.sh setup_veth.sh
 TEST_PROGS_EXTENDED += toeplitz_client.sh toeplitz.sh
 TEST_GEN_FILES =  socket nettest
@@ -76,6 +77,7 @@ TEST_PROGS += sctp_vrf.sh
 TEST_GEN_FILES += sctp_hello
 TEST_GEN_FILES += csum
 TEST_GEN_FILES += nat6to4.o
+TEST_GEN_FILES += ip_local_port_range
 
 TEST_FILES := settings
 
tools/testing/selftests/net/ip_local_port_range.c new file +447 -0

447 lines not on this page · raw message

tools/testing/selftests/net/ip_local_port_range.sh new file +5 -0
new file mode 100755
index 000000000000..6c6ad346eaa0
@@ -0,0 +1,5 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+./in_netns.sh \
+  sh -c 'sysctl -q -w net.ipv4.ip_local_port_range="40000 49999" && ./ip_local_port_range'
Signature · 1 line
2.39.0
#5 lore raw
In reply to Jakub Sitnicki
This series was applied to netdev/net-next.git (master) by Jakub Kicinski <[email protected]>:

Hello:

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

Quoted 9 lines · On Tue, 24 Jan 2023 14:36:43 +0100 you wrote:

This patch set is a follow up to the "How to share IPv4 addresses by partitioning the port space" talk given at LPC 2022 [1].

Please see patch #1 for the motivation & the use case description. Patch #2 adds tests exercising the new option in various scenarios.

Documentation

[...]

Here is the summary with links:
- [net-next,v6,1/2] inet: Add IP_LOCAL_PORT_RANGE socket option

    https://git.kernel.org/netdev/net-next/c/91d0b78c5177
  - [net-next,v6,2/2] selftests/net: Cover the IP_LOCAL_PORT_RANGE socket option
    https://git.kernel.org/netdev/net-next/c/ae5439658cce

You are awesome, thank you!

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