Random.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Peter Elliott <pelliott@ualberta.ca>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/Singleton.h>
  28. #include <Kernel/Arch/x86/CPU.h>
  29. #include <Kernel/Devices/RandomDevice.h>
  30. #include <Kernel/Random.h>
  31. #include <Kernel/Time/HPET.h>
  32. #include <Kernel/Time/RTC.h>
  33. #include <Kernel/Time/TimeManagement.h>
  34. namespace Kernel {
  35. static AK::Singleton<KernelRng> s_the;
  36. KernelRng& KernelRng::the()
  37. {
  38. return *s_the;
  39. }
  40. UNMAP_AFTER_INIT KernelRng::KernelRng()
  41. {
  42. bool supports_rdseed = Processor::current().has_feature(CPUFeature::RDSEED);
  43. bool supports_rdrand = Processor::current().has_feature(CPUFeature::RDRAND);
  44. if (supports_rdseed || supports_rdrand) {
  45. dmesgln("KernelRng: Using RDSEED or RDRAND as entropy source");
  46. for (size_t i = 0; i < resource().pool_count * resource().reseed_threshold; ++i) {
  47. u32 value = 0;
  48. if (supports_rdseed) {
  49. asm volatile(
  50. "1:\n"
  51. "rdseed %0\n"
  52. "jnc 1b\n"
  53. : "=r"(value));
  54. } else {
  55. asm volatile(
  56. "1:\n"
  57. "rdrand %0\n"
  58. "jnc 1b\n"
  59. : "=r"(value));
  60. }
  61. this->resource().add_random_event(value, i % 32);
  62. }
  63. } else if (TimeManagement::the().can_query_precise_time()) {
  64. // Add HPET as entropy source if we don't have anything better.
  65. dmesgln("KernelRng: Using HPET as entropy source");
  66. for (size_t i = 0; i < resource().pool_count * resource().reseed_threshold; ++i) {
  67. u64 hpet_time = HPET::the().read_main_counter_unsafe();
  68. this->resource().add_random_event(hpet_time, i % 32);
  69. }
  70. } else {
  71. // Fallback to RTC
  72. dmesgln("KernelRng: Using RTC as entropy source (bad!)");
  73. auto current_time = static_cast<u64>(RTC::now());
  74. for (size_t i = 0; i < resource().pool_count * resource().reseed_threshold; ++i) {
  75. this->resource().add_random_event(current_time, i % 32);
  76. current_time *= 0x574au;
  77. current_time += 0x40b2u;
  78. }
  79. }
  80. }
  81. void KernelRng::wait_for_entropy()
  82. {
  83. ScopedSpinLock lock(get_lock());
  84. if (!resource().is_ready()) {
  85. dbgln("Entropy starvation...");
  86. m_seed_queue.wait_forever("KernelRng");
  87. }
  88. }
  89. void KernelRng::wake_if_ready()
  90. {
  91. VERIFY(get_lock().is_locked());
  92. if (resource().is_ready()) {
  93. m_seed_queue.wake_all();
  94. }
  95. }
  96. size_t EntropySource::next_source { static_cast<size_t>(EntropySource::Static::MaxHardcodedSourceIndex) };
  97. static void do_get_fast_random_bytes(u8* buffer, size_t buffer_size)
  98. {
  99. static Atomic<u32, AK::MemoryOrder::memory_order_relaxed> next = 1;
  100. union {
  101. u8 bytes[4];
  102. u32 value;
  103. } u;
  104. size_t offset = 4;
  105. for (size_t i = 0; i < buffer_size; ++i) {
  106. if (offset >= 4) {
  107. auto current_next = next.load();
  108. for (;;) {
  109. auto new_next = current_next * 1103515245 + 12345;
  110. if (next.compare_exchange_strong(current_next, new_next)) {
  111. u.value = new_next;
  112. break;
  113. }
  114. }
  115. offset = 0;
  116. }
  117. buffer[i] = u.bytes[offset++];
  118. }
  119. }
  120. bool get_good_random_bytes(u8* buffer, size_t buffer_size, bool allow_wait, bool fallback_to_fast)
  121. {
  122. bool result = false;
  123. auto& kernel_rng = KernelRng::the();
  124. // FIXME: What if interrupts are disabled because we're in an interrupt?
  125. bool can_wait = are_interrupts_enabled();
  126. if (!can_wait && allow_wait) {
  127. // If we can't wait but the caller would be ok with it, then we
  128. // need to definitely fallback to *something*, even if it's less
  129. // secure...
  130. fallback_to_fast = true;
  131. }
  132. if (can_wait && allow_wait) {
  133. for (;;) {
  134. {
  135. LOCKER(KernelRng::the().lock());
  136. if (kernel_rng.resource().get_random_bytes(buffer, buffer_size)) {
  137. result = true;
  138. break;
  139. }
  140. }
  141. kernel_rng.wait_for_entropy();
  142. }
  143. } else {
  144. // We can't wait/block here, or we are not allowed to block/wait
  145. if (kernel_rng.resource().get_random_bytes(buffer, buffer_size)) {
  146. result = true;
  147. } else if (fallback_to_fast) {
  148. // If interrupts are disabled
  149. do_get_fast_random_bytes(buffer, buffer_size);
  150. result = true;
  151. }
  152. }
  153. // NOTE: The only case where this function should ever return false and
  154. // not actually return random data is if fallback_to_fast == false and
  155. // allow_wait == false and interrupts are enabled!
  156. VERIFY(result || !fallback_to_fast);
  157. return result;
  158. }
  159. void get_fast_random_bytes(u8* buffer, size_t buffer_size)
  160. {
  161. // Try to get good randomness, but don't block if we can't right now
  162. // and allow falling back to fast randomness
  163. auto result = get_good_random_bytes(buffer, buffer_size, false, true);
  164. VERIFY(result);
  165. }
  166. }