diff --git a/modules/ice_lite/rtpp_ice_lite.c b/modules/ice_lite/rtpp_ice_lite.c index 948dd19fd..5934b2aac 100644 --- a/modules/ice_lite/rtpp_ice_lite.c +++ b/modules/ice_lite/rtpp_ice_lite.c @@ -38,6 +38,8 @@ #include #include +#include + #include "config_pp.h" #include "rtpp_types.h" @@ -291,6 +293,38 @@ udp_local_get(const struct udp_sock *us, struct sa *local) return (0); } +static inline uint8_t +encode6(unsigned x) +{ + x &= 63u; + unsigned k = x & 31u; + + if (k == 0) + return x ? '+' : '/'; + + if (k <= 26) + return x | ('A' - 1); + + return 0x30u | ((~x & 7u) << 1) | (x >> 5); +} + +/* + * RFC 8445 section 5.3: ufrag needs at least 24 and pwd at least 128 bits + * of randomness. Each byte gives 6 bits via encode6(). + */ +static int +ice_random_string(char *buffer, int length) +{ + unsigned char *rb = (unsigned char *)buffer; + + if (RAND_bytes(rb, length) != 1) + return (-1); + for (int i = 0; i < length; i++) + buffer[i] = encode6(rb[i]); + buffer[length] = '\0'; + return (0); +} + static struct ice_lite_agent_cfg * ice_lite_data_ctor(int lufrag_len, int lpwd_len, struct rtpp_minfo *mself) { @@ -307,9 +341,11 @@ ice_lite_data_ctor(int lufrag_len, int lpwd_len, struct rtpp_minfo *mself) if (lufrag.s == NULL || lpwd.s == NULL) goto e1; lufrag.len = lufrag_len; - generate_random_string(lufrag.s, lufrag.len); + if (ice_random_string(lufrag.s, lufrag.len) != 0) + goto e1; lpwd.len = lpwd_len; - generate_random_string(lpwd.s, lpwd.len); + if (ice_random_string(lpwd.s, lpwd.len) != 0) + goto e1; if (icem_alloc(&ila_c->icem, ICE_MODE_LITE, ICE_ROLE_CONTROLLED, IPPROTO_UDP, 0, tiebrk, lufrag.s, lpwd.s, NULL, NULL) != 0) goto e1; diff --git a/src/rtpp_util.c b/src/rtpp_util.c index 1b123f3c0..02d822a10 100644 --- a/src/rtpp_util.c +++ b/src/rtpp_util.c @@ -597,19 +597,3 @@ rtpp_strsplit(char *ibuf, char *mbuf, size_t dlen, size_t blen) cp += 1; } } - -void -generate_random_string(char *buffer, int length) -{ - const char charset[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789" - "+/"; - int charset_size = sizeof(charset) - 1; - - for (int i = 0; i < length; i++) { - int key = random() % charset_size; - buffer[i] = charset[key]; - } - buffer[length] = '\0'; -} diff --git a/src/rtpp_util.h b/src/rtpp_util.h index c8d5b6113..bded73c3d 100644 --- a/src/rtpp_util.h +++ b/src/rtpp_util.h @@ -65,7 +65,6 @@ enum atoi_rval rtpp_parse_rtp_rtcp_val(const char *, int *, int *, int); enum atoi_rval strtol_saferange(const char *, long *, long, long, const char **) RTPP_EXPORT; void rtpp_strsplit(char *, char *, size_t, size_t); -void generate_random_string(char *, int) RTPP_EXPORT; /* Some handy/compat macros */ #if !defined(INFTIM)