From 144c9852279ef0219c72fe549f72a40f3a255edc Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Wed, 29 May 2019 16:00:35 +0200 Subject: [PATCH] Handle short reads from our random device Reported by Coverity (CID 1401626). --- pdns/dns_random.cc | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/pdns/dns_random.cc b/pdns/dns_random.cc index bb6e8e615..e2b8e4575 100644 --- a/pdns/dns_random.cc +++ b/pdns/dns_random.cc @@ -281,11 +281,21 @@ uint32_t dns_random(uint32_t upper_bound) { #endif case RNG_URANDOM: { uint32_t num = 0; + size_t attempts = 5; do { - if (read(urandom_fd, &num, sizeof(num)) < 0) { + ssize_t got = read(urandom_fd, &num, sizeof(num)); + if (got < 0) { (void)close(urandom_fd); throw std::runtime_error("Cannot read random device"); } + else if (static_cast(got) != sizeof(num)) { + /* short read, let's retry */ + if (attempts == 0) { + throw std::runtime_error("Too many short reads on random device"); + } + attempts--; + continue; + } } while(num < min); -- 2.40.0