[RFC PATCH 2/5] net: Implement source port randomization

Jules Maselbas jmaselbas at kalray.eu
Tue Aug 9 06:20:18 PDT 2022


The source port can now be randomized for UDP connections in the range
32768 to 65535. The port number selection follows the Algorithm 1 as
described by the RFC6056, and goes as follow: A random port number is
generated, if the port is already taken then it search forward for the
next available port.

Note from the RFC6056:
      random() is a function that returns a 32-bit pseudo-random
      unsigned integer number.  Note that the output needs to be
      unpredictable, and typical implementations of POSIX random()
      function do not necessarily meet this requirement.  See [RFC4086]
      for randomness requirements for security.

This implementation uses random32 which might not meet the randomness
requirements. The random32 call can be easily replaced by a better
suited pseudo-random number generator when availabe.

Signed-off-by: Jules Maselbas <jmaselbas at kalray.eu>
---
 net/net.c | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)

diff --git a/net/net.c b/net/net.c
index c01bf49b92..9f799f252d 100644
--- a/net/net.c
+++ b/net/net.c
@@ -310,18 +310,31 @@ static int init_net_poll(void)
 }
 device_initcall(init_net_poll);
 
-static uint16_t net_udp_new_localport(void)
+static uint16_t net_new_localport(int proto)
 {
-	static uint16_t localport;
+	const uint16_t min_port = 32768;
+	const uint16_t max_port = 65535;
+	const uint16_t num_port = max_port - min_port + 1;
+	uint16_t localport;
 
-	localport++;
+	/* port randomization with the Algorithm 1 as defined in RFC6056 */
+	localport = min_port + random32() % num_port;
 
-	if (localport < 1024)
-		localport = 1024;
+	while (net_ip_get_con(proto, localport) != NULL) {
+		if (localport == max_port)
+			localport = min_port;
+		else
+			localport++;
+	}
 
 	return localport;
 }
 
+static uint16_t net_udp_new_localport(void)
+{
+	return net_new_localport(IPPROTO_UDP);
+}
+
 IPaddr_t net_get_serverip(void)
 {
 	IPaddr_t ip;
-- 
2.17.1




More information about the barebox mailing list