Subject: tcp: ip_local_reserved_ports impact on inet_csk_get_port()

From: Erik Hugne <[email-masked]>
Date: Tue, 5 May 2015 14:47:59 +0200

Defining a port range in net.ipv4.ip_local_reserved_ports can cause a linear
and predictable behavior of inet_csk_get_port().
This occurs when smallest_rover = rover = prandom_u32() % remaining + low;
hits a value in the reserved range. The algorithm will then try the next
consecutive port number until a free port is found.

Example:
net.ipv4.ip_local_port_range = 32768	61000
net.ipv4.ip_local_reserved_ports = 35000-61000

This will give ~92% chance that the initial random port will be in the
reserved range, and that the port selection will be done linearly
starting from 32768.
Section 3.3 in RFC6056[1] describes several port selection algorithms, and Linux
seems to follow #1. This does not seem to be the best alternative since
e3826f1e946e ("net: reserve ports for applications using fixed port numbers")

If the local port range is set not to overlap with the reserved ports,
inet_csk_get_port will give a better randomness in the port selection.

//E

[1] https://tools.ietf.org/html/rfc6056