Random.h 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Assertions.h>
  9. #include <AK/ByteBuffer.h>
  10. #include <AK/Types.h>
  11. #include <Kernel/Locking/Mutex.h>
  12. #include <Kernel/StdLib.h>
  13. #include <LibCrypto/Cipher/AES.h>
  14. #include <LibCrypto/Cipher/Cipher.h>
  15. #include <LibCrypto/Hash/SHA2.h>
  16. namespace Kernel {
  17. template<typename CipherT, typename HashT, int KeySize>
  18. class FortunaPRNG {
  19. public:
  20. constexpr static size_t pool_count = 32;
  21. constexpr static size_t reseed_threshold = 16;
  22. using CipherType = CipherT;
  23. using BlockType = typename CipherT::BlockType;
  24. using HashType = HashT;
  25. using DigestType = typename HashT::DigestType;
  26. // FIXME: Do something other than VERIFY()'ing inside Optional in case of OOM.
  27. FortunaPRNG()
  28. : m_counter(ByteBuffer::create_zeroed(BlockType::block_size()).release_value())
  29. {
  30. }
  31. bool get_random_bytes(Bytes buffer)
  32. {
  33. SpinlockLocker lock(m_lock);
  34. if (!is_ready())
  35. return false;
  36. if (m_p0_len >= reseed_threshold) {
  37. this->reseed();
  38. }
  39. VERIFY(is_seeded());
  40. // FIXME: More than 2^20 bytes cannot be generated without refreshing the key.
  41. VERIFY(buffer.size() < (1 << 20));
  42. typename CipherType::CTRMode cipher(m_key, KeySize, Crypto::Cipher::Intent::Encryption);
  43. auto counter_span = m_counter.bytes();
  44. cipher.key_stream(buffer, counter_span, &counter_span);
  45. // Extract a new key from the prng stream.
  46. Bytes key_span = m_key.bytes();
  47. cipher.key_stream(key_span, counter_span, &counter_span);
  48. return true;
  49. }
  50. template<typename T>
  51. void add_random_event(const T& event_data, size_t pool)
  52. {
  53. pool %= pool_count;
  54. if (pool == 0) {
  55. m_p0_len++;
  56. }
  57. m_pools[pool].update(reinterpret_cast<const u8*>(&event_data), sizeof(T));
  58. }
  59. [[nodiscard]] bool is_seeded() const
  60. {
  61. return m_reseed_number > 0;
  62. }
  63. [[nodiscard]] bool is_ready() const
  64. {
  65. VERIFY(m_lock.is_locked());
  66. return is_seeded() || m_p0_len >= reseed_threshold;
  67. }
  68. Spinlock& get_lock() { return m_lock; }
  69. private:
  70. void reseed()
  71. {
  72. HashType new_key;
  73. new_key.update(m_key);
  74. for (size_t i = 0; i < pool_count; ++i) {
  75. if (m_reseed_number % (1u << i) == 0) {
  76. DigestType digest = m_pools[i].digest();
  77. new_key.update(digest.immutable_data(), digest.data_length());
  78. }
  79. }
  80. DigestType digest = new_key.digest();
  81. if (m_key.size() == digest.data_length()) {
  82. // Avoid reallocating, just overwrite the key.
  83. m_key.overwrite(0, digest.immutable_data(), digest.data_length());
  84. } else {
  85. auto buffer_result = ByteBuffer::copy(digest.immutable_data(), digest.data_length());
  86. // If there's no memory left to copy this into, bail out.
  87. if (!buffer_result.has_value())
  88. return;
  89. m_key = buffer_result.release_value();
  90. }
  91. m_reseed_number++;
  92. m_p0_len = 0;
  93. }
  94. ByteBuffer m_counter;
  95. size_t m_reseed_number { 0 };
  96. size_t m_p0_len { 0 };
  97. ByteBuffer m_key;
  98. HashType m_pools[pool_count];
  99. Spinlock m_lock;
  100. };
  101. class KernelRng : public FortunaPRNG<Crypto::Cipher::AESCipher, Crypto::Hash::SHA256, 256> {
  102. public:
  103. KernelRng();
  104. static KernelRng& the();
  105. void wait_for_entropy();
  106. void wake_if_ready();
  107. private:
  108. WaitQueue m_seed_queue;
  109. };
  110. class EntropySource {
  111. template<typename T>
  112. struct Event {
  113. u64 timestamp;
  114. size_t source;
  115. T event_data;
  116. };
  117. public:
  118. enum class Static : size_t {
  119. Interrupts,
  120. MaxHardcodedSourceIndex,
  121. };
  122. EntropySource()
  123. : m_source(next_source++)
  124. {
  125. }
  126. EntropySource(Static hardcoded_source)
  127. : m_source(static_cast<size_t>(hardcoded_source))
  128. {
  129. }
  130. template<typename T>
  131. void add_random_event(const T& event_data)
  132. {
  133. auto& kernel_rng = KernelRng::the();
  134. SpinlockLocker lock(kernel_rng.get_lock());
  135. // We don't lock this because on the off chance a pool is corrupted, entropy isn't lost.
  136. Event<T> event = { read_tsc(), m_source, event_data };
  137. kernel_rng.add_random_event(event, m_pool);
  138. m_pool++;
  139. kernel_rng.wake_if_ready();
  140. }
  141. private:
  142. static size_t next_source;
  143. size_t m_pool { 0 };
  144. size_t m_source;
  145. };
  146. // NOTE: These API's are primarily about expressing intent/needs in the calling code.
  147. // The only difference is that get_fast_random is guaranteed not to block.
  148. void get_fast_random_bytes(Bytes);
  149. bool get_good_random_bytes(Bytes bytes, bool allow_wait = true, bool fallback_to_fast = true);
  150. template<typename T>
  151. inline T get_fast_random()
  152. {
  153. T value;
  154. Bytes bytes { reinterpret_cast<u8*>(&value), sizeof(T) };
  155. get_fast_random_bytes(bytes);
  156. return value;
  157. }
  158. template<typename T>
  159. inline T get_good_random()
  160. {
  161. T value;
  162. Bytes bytes { reinterpret_cast<u8*>(&value), sizeof(T) };
  163. get_good_random_bytes(bytes);
  164. return value;
  165. }
  166. }