From 4a8e681a5fa82d59544fbdb8026f1606c41504e2 Mon Sep 17 00:00:00 2001 From: Raphael Robatsch Date: Thu, 11 Nov 2021 17:26:27 +0100 Subject: [PATCH] util/token: don't leak /dev/urandom fd to children Closes #3324. --- util/token.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/util/token.c b/util/token.c index cf6034a32..1b839aaa6 100644 --- a/util/token.c +++ b/util/token.c @@ -1,20 +1,31 @@ +#define _POSIX_C_SOURCE 200809L #include "util/token.h" #include "wlr/util/log.h" +#include #include #include #include #include +#include +#include +#include bool generate_token(char out[static TOKEN_STRLEN]) { static FILE *urandom = NULL; uint64_t data[2]; if (!urandom) { - if (!(urandom = fopen("/dev/urandom", "r"))) { + int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); + if (fd < 0) { wlr_log_errno(WLR_ERROR, "Failed to open random device"); return false; } + if (!(urandom = fdopen(fd, "r"))) { + wlr_log_errno(WLR_ERROR, "fdopen failed"); + close(fd); + return false; + } } if (fread(data, sizeof(data), 1, urandom) != 1) { wlr_log_errno(WLR_ERROR, "Failed to read from random device");