From 869743a7427f33e8e61fa9c4429b040ab0bf2561 Mon Sep 17 00:00:00 2001 From: Oxan van Leeuwen Date: Tue, 18 Jan 2022 02:29:57 +0100 Subject: [PATCH] Fail hard if no random bytes available for encryption (#3067) --- esphome/components/api/api_frame_helper.cpp | 8 +++++++- esphome/core/helpers.cpp | 7 +++---- esphome/core/helpers.h | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/esphome/components/api/api_frame_helper.cpp b/esphome/components/api/api_frame_helper.cpp index 094dd67e33..d9eadb2aaa 100644 --- a/esphome/components/api/api_frame_helper.cpp +++ b/esphome/components/api/api_frame_helper.cpp @@ -1,6 +1,7 @@ #include "api_frame_helper.h" #include "esphome/core/log.h" +#include "esphome/core/hal.h" #include "esphome/core/helpers.h" #include "proto.h" #include @@ -721,7 +722,12 @@ APIError APINoiseFrameHelper::shutdown(int how) { } extern "C" { // declare how noise generates random bytes (here with a good HWRNG based on the RF system) -void noise_rand_bytes(void *output, size_t len) { esphome::random_bytes(reinterpret_cast(output), len); } +void noise_rand_bytes(void *output, size_t len) { + if (!esphome::random_bytes(reinterpret_cast(output), len)) { + ESP_LOGE(TAG, "Failed to acquire random bytes, rebooting!"); + arch_restart(); + } +} } #endif // USE_API_NOISE diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index e15e3a8ea3..5f29abe579 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -287,13 +287,12 @@ uint32_t random_uint32() { #endif } float random_float() { return static_cast(random_uint32()) / static_cast(UINT32_MAX); } -void random_bytes(uint8_t *data, size_t len) { +bool random_bytes(uint8_t *data, size_t len) { #ifdef USE_ESP32 esp_fill_random(data, len); + return true; #elif defined(USE_ESP8266) - if (os_get_random(data, len) != 0) { - ESP_LOGE(TAG, "Failed to generate random bytes!"); - } + return os_get_random(data, len) == 0; #else #error "No random source available for this configuration." #endif diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index f071b4a814..c9a27a2fab 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -311,7 +311,7 @@ uint32_t random_uint32(); /// Return a random float between 0 and 1. float random_float(); /// Generate \p len number of random bytes. -void random_bytes(uint8_t *data, size_t len); +bool random_bytes(uint8_t *data, size_t len); ///@}