1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2025-01-18 12:52:44 +01:00

gnrc_sock_udp: choose random ephemeral port

Implements a random ephemeral port selection as per the second algorithm
from RFC 6056, see https://tools.ietf.org/html/rfc6056#section-3.3.2.
This commit is contained in:
Sören Tempel 2020-01-31 17:44:37 +01:00
parent 342792a9d6
commit b37bed8a1d
2 changed files with 4 additions and 13 deletions

View File

@ -55,14 +55,6 @@ extern "C" {
*/
#define GNRC_SOCK_DYN_PORTRANGE_ERR (0)
/**
* @brief Offset for next dynamic port
*
* Currently set to a static (prime) offset, but could be random, too
* see https://tools.ietf.org/html/rfc6056#section-3.3.3
*/
#define GNRC_SOCK_DYN_PORTRANGE_OFF (17U)
/**
* @brief Internal helper functions for GNRC
* @internal

View File

@ -25,6 +25,7 @@
#include "net/gnrc/udp.h"
#include "net/sock/udp.h"
#include "net/udp.h"
#include "random.h"
#include "gnrc_sock_internal.h"
@ -32,8 +33,6 @@
static sock_udp_t *_udp_socks = NULL;
#endif
static uint16_t _dyn_port_next = 0;
/**
* @brief Checks if a given UDP port is already used by another sock
*/
@ -66,15 +65,15 @@ static bool _dyn_port_used(uint16_t port)
/**
* @brief returns a UDP port, and checks for reuse if required
*
* complies to RFC 6056, see https://tools.ietf.org/html/rfc6056#section-3.3.3
* implements "Another Simple Port Randomization Algorithm" as specified in
* RFC 6056, see https://tools.ietf.org/html/rfc6056#section-3.3.2
*/
static uint16_t _get_dyn_port(sock_udp_t *sock)
{
unsigned count = GNRC_SOCK_DYN_PORTRANGE_NUM;
do {
uint16_t port = GNRC_SOCK_DYN_PORTRANGE_MIN +
(_dyn_port_next * GNRC_SOCK_DYN_PORTRANGE_OFF) % GNRC_SOCK_DYN_PORTRANGE_NUM;
_dyn_port_next++;
(random_uint32() % GNRC_SOCK_DYN_PORTRANGE_NUM);
if ((sock == NULL) || (sock->flags & SOCK_FLAGS_REUSE_EP) ||
!_dyn_port_used(port)) {
return port;