[PATCH ustream-ssl] ustream-mbedtls: Use getrandom() instead of /dev/urandom

Rosen Penev rosenp at gmail.com
Sat Jan 28 16:56:12 PST 2023


On Sat, Jan 28, 2023 at 10:45 AM Hauke Mehrtens <hauke at hauke-m.de> 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 <hauke at hauke-m.de>
Acked-by: Rosen Penev <rosenp at gmail.com>
> ---
>  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;
>
>         return 0;
> @@ -134,9 +124,6 @@ __ustream_ssl_context_new(bool server)
>         mbedtls_ssl_config *conf;
>         int ep;
>
> -       if (!urandom_init())
> -               return NULL;
> -
>         ctx = calloc(1, sizeof(*ctx));
>         if (!ctx)
>                 return NULL;
> --
> 2.39.0
>
>
> _______________________________________________
> openwrt-devel mailing list
> openwrt-devel at lists.openwrt.org
> https://lists.openwrt.org/mailman/listinfo/openwrt-devel



More information about the openwrt-devel mailing list