[tcp/udp] fix port generation not in range

(port % max + min)may overflow uint16

Signed-off-by: meijian <meijian@xiaomi.com>
This commit is contained in:
meijian 2024-03-01 11:30:22 +08:00 committed by Xiang Xiao
parent b446a002db
commit 93beeeeab0
4 changed files with 22 additions and 16 deletions

View File

@ -59,12 +59,14 @@ config NET_PROMISCUOUS
config NET_DEFAULT_MIN_PORT
int "Net Default Min Port"
range 1 65535
default 4096
---help---
Default Network min port
config NET_DEFAULT_MAX_PORT
int "Net Default Max Port"
range NET_DEFAULT_MIN_PORT 65535
default 32000
---help---
Default Network max port

View File

@ -110,7 +110,9 @@ static uint16_t ipv4_nat_select_port_without_stack(
uint16_t hport = NTOHS(portno);
while (ipv4_nat_port_inuse(protocol, ip, portno))
{
if (++hport >= CONFIG_NET_DEFAULT_MAX_PORT)
++hport;
if (hport >= CONFIG_NET_DEFAULT_MAX_PORT ||
hport < CONFIG_NET_DEFAULT_MIN_PORT)
{
hport = CONFIG_NET_DEFAULT_MIN_PORT;
}
@ -200,7 +202,9 @@ static uint16_t ipv4_nat_select_port(FAR struct net_driver_s *dev,
while (icmp_findconn(dev, id) ||
ipv4_nat_port_inuse(IP_PROTO_ICMP, dev->d_ipaddr, id))
{
if (++hid >= CONFIG_NET_DEFAULT_MAX_PORT)
++hid;
if (hid >= CONFIG_NET_DEFAULT_MAX_PORT ||
hid < CONFIG_NET_DEFAULT_MIN_PORT)
{
hid = CONFIG_NET_DEFAULT_MIN_PORT;
}

View File

@ -585,13 +585,11 @@ int tcp_selectport(uint8_t domain,
{
net_getrandom(&g_last_tcp_port, sizeof(uint16_t));
g_last_tcp_port = g_last_tcp_port % CONFIG_NET_DEFAULT_MAX_PORT;
if (g_last_tcp_port < CONFIG_NET_DEFAULT_MIN_PORT)
{
g_last_tcp_port = g_last_tcp_port %
(CONFIG_NET_DEFAULT_MAX_PORT -
CONFIG_NET_DEFAULT_MIN_PORT + 1);
g_last_tcp_port += CONFIG_NET_DEFAULT_MIN_PORT;
}
}
if (portno == 0)
{
@ -608,7 +606,10 @@ int tcp_selectport(uint8_t domain,
* is within range.
*/
if (++g_last_tcp_port >= CONFIG_NET_DEFAULT_MAX_PORT)
++g_last_tcp_port;
if (g_last_tcp_port > CONFIG_NET_DEFAULT_MAX_PORT ||
g_last_tcp_port < CONFIG_NET_DEFAULT_MIN_PORT)
{
g_last_tcp_port = CONFIG_NET_DEFAULT_MIN_PORT;
}

View File

@ -540,13 +540,11 @@ uint16_t udp_select_port(uint8_t domain, FAR union ip_binding_u *u)
if (g_last_udp_port == 0)
{
g_last_udp_port = clock_systime_ticks() % CONFIG_NET_DEFAULT_MAX_PORT;
if (g_last_udp_port < CONFIG_NET_DEFAULT_MIN_PORT)
{
g_last_udp_port = clock_systime_ticks() %
(CONFIG_NET_DEFAULT_MAX_PORT -
CONFIG_NET_DEFAULT_MIN_PORT + 1);
g_last_udp_port += CONFIG_NET_DEFAULT_MIN_PORT;
}
}
/* Find an unused local port number. Loop until we find a valid
* listen port number that is not being used by any other connection.
@ -562,7 +560,8 @@ uint16_t udp_select_port(uint8_t domain, FAR union ip_binding_u *u)
/* Make sure that the port number is within range */
if (g_last_udp_port >= CONFIG_NET_DEFAULT_MAX_PORT)
if (g_last_udp_port > CONFIG_NET_DEFAULT_MAX_PORT ||
g_last_udp_port < CONFIG_NET_DEFAULT_MIN_PORT)
{
g_last_udp_port = CONFIG_NET_DEFAULT_MIN_PORT;
}