seed_material.cc 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/random/internal/seed_material.h"
  15. #include <fcntl.h>
  16. #ifndef _WIN32
  17. #include <unistd.h>
  18. #else
  19. #include <io.h>
  20. #endif
  21. #include <algorithm>
  22. #include <cerrno>
  23. #include <cstdint>
  24. #include <cstdlib>
  25. #include <cstring>
  26. #include "absl/base/dynamic_annotations.h"
  27. #include "absl/base/internal/raw_logging.h"
  28. #include "absl/strings/ascii.h"
  29. #include "absl/strings/escaping.h"
  30. #include "absl/strings/string_view.h"
  31. #include "absl/strings/strip.h"
  32. #if defined(__native_client__)
  33. #include <nacl/nacl_random.h>
  34. #define ABSL_RANDOM_USE_NACL_SECURE_RANDOM 1
  35. #elif defined(_WIN32)
  36. #include <windows.h>
  37. #define ABSL_RANDOM_USE_BCRYPT 1
  38. #pragma comment(lib, "bcrypt.lib")
  39. #elif defined(__Fuchsia__)
  40. #include <zircon/syscalls.h>
  41. #endif
  42. #if defined(__GLIBC__) && \
  43. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 25))
  44. // glibc >= 2.25 has getentropy()
  45. #define ABSL_RANDOM_USE_GET_ENTROPY 1
  46. #endif
  47. #if defined(__EMSCRIPTEN__)
  48. #include <sys/random.h>
  49. // Emscripten has getentropy, but it resides in a different header.
  50. #define ABSL_RANDOM_USE_GET_ENTROPY 1
  51. #endif
  52. #if defined(ABSL_RANDOM_USE_BCRYPT)
  53. #include <bcrypt.h>
  54. #ifndef BCRYPT_SUCCESS
  55. #define BCRYPT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
  56. #endif
  57. // Also link bcrypt; this can be done via linker options or:
  58. // #pragma comment(lib, "bcrypt.lib")
  59. #endif
  60. namespace absl {
  61. ABSL_NAMESPACE_BEGIN
  62. namespace random_internal {
  63. namespace {
  64. // Read OS Entropy for random number seeds.
  65. // TODO(absl-team): Possibly place a cap on how much entropy may be read at a
  66. // time.
  67. #if defined(ABSL_RANDOM_USE_BCRYPT)
  68. // On Windows potentially use the BCRYPT CNG API to read available entropy.
  69. bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
  70. BCRYPT_ALG_HANDLE hProvider;
  71. NTSTATUS ret;
  72. ret = BCryptOpenAlgorithmProvider(&hProvider, BCRYPT_RNG_ALGORITHM,
  73. MS_PRIMITIVE_PROVIDER, 0);
  74. if (!(BCRYPT_SUCCESS(ret))) {
  75. ABSL_RAW_LOG(ERROR, "Failed to open crypto provider.");
  76. return false;
  77. }
  78. ret = BCryptGenRandom(
  79. hProvider, // provider
  80. reinterpret_cast<UCHAR*>(values.data()), // buffer
  81. static_cast<ULONG>(sizeof(uint32_t) * values.size()), // bytes
  82. 0); // flags
  83. BCryptCloseAlgorithmProvider(hProvider, 0);
  84. return BCRYPT_SUCCESS(ret);
  85. }
  86. #elif defined(ABSL_RANDOM_USE_NACL_SECURE_RANDOM)
  87. // On NaCL use nacl_secure_random to acquire bytes.
  88. bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
  89. auto buffer = reinterpret_cast<uint8_t*>(values.data());
  90. size_t buffer_size = sizeof(uint32_t) * values.size();
  91. uint8_t* output_ptr = buffer;
  92. while (buffer_size > 0) {
  93. size_t nread = 0;
  94. const int error = nacl_secure_random(output_ptr, buffer_size, &nread);
  95. if (error != 0 || nread > buffer_size) {
  96. ABSL_RAW_LOG(ERROR, "Failed to read secure_random seed data: %d", error);
  97. return false;
  98. }
  99. output_ptr += nread;
  100. buffer_size -= nread;
  101. }
  102. return true;
  103. }
  104. #elif defined(__Fuchsia__)
  105. bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
  106. auto buffer = reinterpret_cast<uint8_t*>(values.data());
  107. size_t buffer_size = sizeof(uint32_t) * values.size();
  108. zx_cprng_draw(buffer, buffer_size);
  109. return true;
  110. }
  111. #else
  112. #if defined(ABSL_RANDOM_USE_GET_ENTROPY)
  113. // On *nix, use getentropy() if supported. Note that libc may support
  114. // getentropy(), but the kernel may not, in which case this function will return
  115. // false.
  116. bool ReadSeedMaterialFromGetEntropy(absl::Span<uint32_t> values) {
  117. auto buffer = reinterpret_cast<uint8_t*>(values.data());
  118. size_t buffer_size = sizeof(uint32_t) * values.size();
  119. while (buffer_size > 0) {
  120. // getentropy() has a maximum permitted length of 256.
  121. size_t to_read = std::min<size_t>(buffer_size, 256);
  122. int result = getentropy(buffer, to_read);
  123. if (result < 0) {
  124. return false;
  125. }
  126. // https://github.com/google/sanitizers/issues/1173
  127. // MemorySanitizer can't see through getentropy().
  128. ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(buffer, to_read);
  129. buffer += to_read;
  130. buffer_size -= to_read;
  131. }
  132. return true;
  133. }
  134. #endif // defined(ABSL_RANDOM_GETENTROPY)
  135. // On *nix, read entropy from /dev/urandom.
  136. bool ReadSeedMaterialFromDevURandom(absl::Span<uint32_t> values) {
  137. const char kEntropyFile[] = "/dev/urandom";
  138. auto buffer = reinterpret_cast<uint8_t*>(values.data());
  139. size_t buffer_size = sizeof(uint32_t) * values.size();
  140. int dev_urandom = open(kEntropyFile, O_RDONLY);
  141. bool success = (-1 != dev_urandom);
  142. if (!success) {
  143. return false;
  144. }
  145. while (success && buffer_size > 0) {
  146. ssize_t bytes_read = read(dev_urandom, buffer, buffer_size);
  147. int read_error = errno;
  148. success = (bytes_read > 0);
  149. if (success) {
  150. buffer += bytes_read;
  151. buffer_size -= static_cast<size_t>(bytes_read);
  152. } else if (bytes_read == -1 && read_error == EINTR) {
  153. success = true; // Need to try again.
  154. }
  155. }
  156. close(dev_urandom);
  157. return success;
  158. }
  159. bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
  160. #if defined(ABSL_RANDOM_USE_GET_ENTROPY)
  161. if (ReadSeedMaterialFromGetEntropy(values)) {
  162. return true;
  163. }
  164. #endif
  165. // Libc may support getentropy, but the kernel may not, so we still have
  166. // to fallback to ReadSeedMaterialFromDevURandom().
  167. return ReadSeedMaterialFromDevURandom(values);
  168. }
  169. #endif
  170. } // namespace
  171. bool ReadSeedMaterialFromOSEntropy(absl::Span<uint32_t> values) {
  172. assert(values.data() != nullptr);
  173. if (values.data() == nullptr) {
  174. return false;
  175. }
  176. if (values.empty()) {
  177. return true;
  178. }
  179. return ReadSeedMaterialFromOSEntropyImpl(values);
  180. }
  181. void MixIntoSeedMaterial(absl::Span<const uint32_t> sequence,
  182. absl::Span<uint32_t> seed_material) {
  183. // Algorithm is based on code available at
  184. // https://gist.github.com/imneme/540829265469e673d045
  185. constexpr uint32_t kInitVal = 0x43b0d7e5;
  186. constexpr uint32_t kHashMul = 0x931e8875;
  187. constexpr uint32_t kMixMulL = 0xca01f9dd;
  188. constexpr uint32_t kMixMulR = 0x4973f715;
  189. constexpr uint32_t kShiftSize = sizeof(uint32_t) * 8 / 2;
  190. uint32_t hash_const = kInitVal;
  191. auto hash = [&](uint32_t value) {
  192. value ^= hash_const;
  193. hash_const *= kHashMul;
  194. value *= hash_const;
  195. value ^= value >> kShiftSize;
  196. return value;
  197. };
  198. auto mix = [&](uint32_t x, uint32_t y) {
  199. uint32_t result = kMixMulL * x - kMixMulR * y;
  200. result ^= result >> kShiftSize;
  201. return result;
  202. };
  203. for (const auto& seq_val : sequence) {
  204. for (auto& elem : seed_material) {
  205. elem = mix(elem, hash(seq_val));
  206. }
  207. }
  208. }
  209. absl::optional<uint32_t> GetSaltMaterial() {
  210. // Salt must be common for all generators within the same process so read it
  211. // only once and store in static variable.
  212. static const auto salt_material = []() -> absl::optional<uint32_t> {
  213. uint32_t salt_value = 0;
  214. if (random_internal::ReadSeedMaterialFromOSEntropy(
  215. MakeSpan(&salt_value, 1))) {
  216. return salt_value;
  217. }
  218. return absl::nullopt;
  219. }();
  220. return salt_material;
  221. }
  222. } // namespace random_internal
  223. ABSL_NAMESPACE_END
  224. } // namespace absl