Random.h 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Peter Elliott <pelliott@ualberta.ca>
  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(u8* buffer, size_t n)
  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(n < (1 << 20));
  42. typename CipherType::CTRMode cipher(m_key, KeySize, Crypto::Cipher::Intent::Encryption);
  43. Bytes buffer_span { buffer, n };
  44. auto counter_span = m_counter.bytes();
  45. cipher.key_stream(buffer_span, counter_span, &counter_span);
  46. // Extract a new key from the prng stream.
  47. Bytes key_span = m_key.bytes();
  48. cipher.key_stream(key_span, counter_span, &counter_span);
  49. return true;
  50. }
  51. template<typename T>
  52. void add_random_event(const T& event_data, size_t pool)
  53. {
  54. pool %= pool_count;
  55. if (pool == 0) {
  56. m_p0_len++;
  57. }
  58. m_pools[pool].update(reinterpret_cast<const u8*>(&event_data), sizeof(T));
  59. }
  60. [[nodiscard]] bool is_seeded() const
  61. {
  62. return m_reseed_number > 0;
  63. }
  64. [[nodiscard]] bool is_ready() const
  65. {
  66. VERIFY(m_lock.is_locked());
  67. return is_seeded() || m_p0_len >= reseed_threshold;
  68. }
  69. Spinlock<u8>& get_lock() { return m_lock; }
  70. private:
  71. void reseed()
  72. {
  73. HashType new_key;
  74. new_key.update(m_key);
  75. for (size_t i = 0; i < pool_count; ++i) {
  76. if (m_reseed_number % (1u << i) == 0) {
  77. DigestType digest = m_pools[i].digest();
  78. new_key.update(digest.immutable_data(), digest.data_length());
  79. }
  80. }
  81. DigestType digest = new_key.digest();
  82. m_key = ByteBuffer::copy(digest.immutable_data(),
  83. digest.data_length());
  84. m_reseed_number++;
  85. m_p0_len = 0;
  86. }
  87. ByteBuffer m_counter;
  88. size_t m_reseed_number { 0 };
  89. size_t m_p0_len { 0 };
  90. ByteBuffer m_key;
  91. HashType m_pools[pool_count];
  92. Spinlock<u8> m_lock;
  93. };
  94. class KernelRng : public Lockable<FortunaPRNG<Crypto::Cipher::AESCipher, Crypto::Hash::SHA256, 256>> {
  95. AK_MAKE_ETERNAL;
  96. public:
  97. KernelRng();
  98. static KernelRng& the();
  99. void wait_for_entropy();
  100. void wake_if_ready();
  101. Spinlock<u8>& get_lock() { return resource().get_lock(); }
  102. private:
  103. WaitQueue m_seed_queue;
  104. };
  105. class EntropySource {
  106. template<typename T>
  107. struct Event {
  108. u64 timestamp;
  109. size_t source;
  110. T event_data;
  111. };
  112. public:
  113. enum class Static : size_t {
  114. Interrupts,
  115. MaxHardcodedSourceIndex,
  116. };
  117. EntropySource()
  118. : m_source(next_source++)
  119. {
  120. }
  121. EntropySource(Static hardcoded_source)
  122. : m_source(static_cast<size_t>(hardcoded_source))
  123. {
  124. }
  125. template<typename T>
  126. void add_random_event(const T& event_data)
  127. {
  128. auto& kernel_rng = KernelRng::the();
  129. SpinlockLocker lock(kernel_rng.get_lock());
  130. // We don't lock this because on the off chance a pool is corrupted, entropy isn't lost.
  131. Event<T> event = { read_tsc(), m_source, event_data };
  132. kernel_rng.resource().add_random_event(event, m_pool);
  133. m_pool++;
  134. kernel_rng.wake_if_ready();
  135. }
  136. private:
  137. static size_t next_source;
  138. size_t m_pool { 0 };
  139. size_t m_source;
  140. };
  141. // NOTE: These API's are primarily about expressing intent/needs in the calling code.
  142. // The only difference is that get_fast_random is guaranteed not to block.
  143. void get_fast_random_bytes(u8*, size_t);
  144. bool get_good_random_bytes(u8*, size_t, bool allow_wait = true, bool fallback_to_fast = true);
  145. template<typename T>
  146. inline T get_fast_random()
  147. {
  148. T value;
  149. get_fast_random_bytes(reinterpret_cast<u8*>(&value), sizeof(T));
  150. return value;
  151. }
  152. template<typename T>
  153. inline T get_good_random()
  154. {
  155. T value;
  156. get_good_random_bytes(reinterpret_cast<u8*>(&value), sizeof(T));
  157. return value;
  158. }
  159. }