On Sat, 28 Jan 2023 19:41:13 +0100
Hauke Mehrtens <[email protected]> wrote:

> Instead of keeping a file descriptor open just use the getrandom syscall
> to get random data. This is supported by the musl, glibc and Linux for
> some time now.
> 
> This also improves the error handling in case this function returns not
> as many bytes as expected.
> 
> Signed-off-by: Hauke Mehrtens <[email protected]>
> ---
>  ustream-mbedtls.c | 23 +++++------------------
>  1 file changed, 5 insertions(+), 18 deletions(-)
> 
> diff --git a/ustream-mbedtls.c b/ustream-mbedtls.c
> index e79e37b..51ba2fa 100644
> --- a/ustream-mbedtls.c
> +++ b/ustream-mbedtls.c
> @@ -17,6 +17,7 @@
>   */
>  
>  #include <sys/types.h>
> +#include <sys/random.h>
>  #include <fcntl.h>
>  #include <unistd.h>
>  #include <stdlib.h>
> @@ -25,8 +26,6 @@
>  #include "ustream-ssl.h"
>  #include "ustream-internal.h"
>  
> -static int urandom_fd = -1;
> -
>  static int s_ustream_read(void *ctx, unsigned char *buf, size_t len)
>  {
>       struct ustream *s = ctx;
> @@ -66,21 +65,12 @@ __hidden void ustream_set_io(struct ustream_ssl_ctx *ctx, 
> void *ssl, struct ustr
>       mbedtls_ssl_set_bio(ssl, conn, s_ustream_write, s_ustream_read, NULL);
>  }
>  
> -static bool urandom_init(void)
> -{
> -     if (urandom_fd > -1)
> -             return true;
> -
> -     urandom_fd = open("/dev/urandom", O_RDONLY);
> -     if (urandom_fd < 0)
> -             return false;
> -
> -     return true;
> -}
> -
>  static int _urandom(void *ctx, unsigned char *out, size_t len)
>  {
> -     if (read(urandom_fd, out, len) < 0)
> +     ssize_t ret;
> +
> +     ret = getrandom(out, len, 0);
> +     if (ret < 0 || (size_t)ret != len)
>               return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
[...]

drivers/char/random.c lines 1240- ...
 * Reading from /dev/urandom has the same functionality as calling
 * getrandom(2) with flags=GRND_INSECURE. Because it does not block
 * waiting for the RNG to be ready, it should not be used.

Haven't audited mbedtls, but I assume it reads urandom for "lesser"
entropy when needed. In any case, getrandom(out, len, GRND_INSECURE)
would be the proper replacement.

        Torsten

_______________________________________________
openwrt-devel mailing list
[email protected]
https://lists.openwrt.org/mailman/listinfo/openwrt-devel

Reply via email to