From 670ea1e5fb310fb5c835d08b662b5e5bc2116602 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=94=B0=E6=98=95?= Date: Tue, 26 Apr 2022 19:59:07 +0800 Subject: [PATCH] net/tcp:make initial tcp port more random MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 田昕 --- net/tcp/tcp_conn.c | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/net/tcp/tcp_conn.c b/net/tcp/tcp_conn.c index b74f7620c7e..bb93d0d43de 100644 --- a/net/tcp/tcp_conn.c +++ b/net/tcp/tcp_conn.c @@ -49,6 +49,7 @@ #include #include #include +#include #include @@ -201,12 +202,26 @@ static int tcp_selectport(uint8_t domain, uint16_t portno) { static uint16_t g_last_tcp_port; + ssize_t ret; /* Generate port base dynamically */ if (g_last_tcp_port == 0) { - g_last_tcp_port = clock_systime_ticks() % 32000; + ret = getrandom(&g_last_tcp_port, sizeof(uint16_t), 0); + if (ret < 0) + { + ret = getrandom(&g_last_tcp_port, sizeof(uint16_t), GRND_RANDOM); + } + + if (ret != sizeof(uint16_t)) + { + g_last_tcp_port = clock_systime_ticks() % 32000; + } + else + { + g_last_tcp_port = g_last_tcp_port % 32000; + } if (g_last_tcp_port < 4096) {