Random.h 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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/Lockable.h>
  12. #include <Kernel/Locking/Mutex.h>
  13. #include <Kernel/StdLib.h>
  14. #include <LibCrypto/Cipher/AES.h>
  15. #include <LibCrypto/Cipher/Cipher.h>
  16. #include <LibCrypto/Hash/SHA2.h>
  17. namespace Kernel {
  18. template<typename CipherT, typename HashT, int KeySize>
  19. class FortunaPRNG {
  20. public:
  21. constexpr static size_t pool_count = 32;
  22. constexpr static size_t reseed_threshold = 16;
  23. using CipherType = CipherT;
  24. using BlockType = typename CipherT::BlockType;
  25. using HashType = HashT;
  26. using DigestType = typename HashT::DigestType;
  27. FortunaPRNG()
  28. : m_counter(ByteBuffer::create_zeroed(BlockType::block_size()))
  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<u8>& 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. m_key = ByteBuffer::copy(digest.immutable_data(),
  82. digest.data_length());
  83. m_reseed_number++;
  84. m_p0_len = 0;
  85. }
  86. ByteBuffer m_counter;
  87. size_t m_reseed_number { 0 };
  88. size_t m_p0_len { 0 };
  89. ByteBuffer m_key;
  90. HashType m_pools[pool_count];
  91. Spinlock<u8> m_lock;
  92. };
  93. class KernelRng : public Lockable<FortunaPRNG<Crypto::Cipher::AESCipher, Crypto::Hash::SHA256, 256>> {
  94. AK_MAKE_ETERNAL;
  95. public:
  96. KernelRng();
  97. static KernelRng& the();
  98. void wait_for_entropy();
  99. void wake_if_ready();
  100. Spinlock<u8>& get_lock() { return resource().get_lock(); }
  101. private:
  102. WaitQueue m_seed_queue;
  103. };
  104. class EntropySource {
  105. template<typename T>
  106. struct Event {
  107. u64 timestamp;
  108. size_t source;
  109. T event_data;
  110. };
  111. public:
  112. enum class Static : size_t {
  113. Interrupts,
  114. MaxHardcodedSourceIndex,
  115. };
  116. EntropySource()
  117. : m_source(next_source++)
  118. {
  119. }
  120. EntropySource(Static hardcoded_source)
  121. : m_source(static_cast<size_t>(hardcoded_source))
  122. {
  123. }
  124. template<typename T>
  125. void add_random_event(const T& event_data)
  126. {
  127. auto& kernel_rng = KernelRng::the();
  128. SpinlockLocker lock(kernel_rng.get_lock());
  129. // We don't lock this because on the off chance a pool is corrupted, entropy isn't lost.
  130. Event<T> event = { read_tsc(), m_source, event_data };
  131. kernel_rng.resource().add_random_event(event, m_pool);
  132. m_pool++;
  133. kernel_rng.wake_if_ready();
  134. }
  135. private:
  136. static size_t next_source;
  137. size_t m_pool { 0 };
  138. size_t m_source;
  139. };
  140. // NOTE: These API's are primarily about expressing intent/needs in the calling code.
  141. // The only difference is that get_fast_random is guaranteed not to block.
  142. void get_fast_random_bytes(Bytes);
  143. bool get_good_random_bytes(Bytes bytes, bool allow_wait = true, bool fallback_to_fast = true);
  144. template<typename T>
  145. inline T get_fast_random()
  146. {
  147. T value;
  148. Bytes bytes { reinterpret_cast<u8*>(&value), sizeof(T) };
  149. get_fast_random_bytes(bytes);
  150. return value;
  151. }
  152. template<typename T>
  153. inline T get_good_random()
  154. {
  155. T value;
  156. Bytes bytes { reinterpret_cast<u8*>(&value), sizeof(T) };
  157. get_good_random_bytes(bytes);
  158. return value;
  159. }
  160. }