blob: 85dd535f9c099c2d09866dc5b3868809d90ffa07 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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
15#include "absl/random/internal/seed_material.h"
16
17#include <fcntl.h>
18
19#ifndef _WIN32
20#include <unistd.h>
21#else
22#include <io.h>
23#endif
24
25#include <algorithm>
26#include <cerrno>
27#include <cstdint>
28#include <cstdlib>
29#include <cstring>
30
31#include "absl/base/internal/raw_logging.h"
32#include "absl/strings/ascii.h"
33#include "absl/strings/escaping.h"
34#include "absl/strings/string_view.h"
35#include "absl/strings/strip.h"
36
37#if defined(__native_client__)
38
39#include <nacl/nacl_random.h>
40#define ABSL_RANDOM_USE_NACL_SECURE_RANDOM 1
41
42#elif defined(_WIN32)
43
44#include <windows.h>
45#define ABSL_RANDOM_USE_BCRYPT 1
46#pragma comment(lib, "bcrypt.lib")
47
48#endif
49
50#if defined(ABSL_RANDOM_USE_BCRYPT)
51#include <bcrypt.h>
52
53#ifndef BCRYPT_SUCCESS
54#define BCRYPT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
55#endif
56// Also link bcrypt; this can be done via linker options or:
57// #pragma comment(lib, "bcrypt.lib")
58#endif
59
60namespace absl {
61namespace random_internal {
62namespace {
63
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
68#if defined(ABSL_RANDOM_USE_BCRYPT)
69
70// On Windows potentially use the BCRYPT CNG API to read available entropy.
71bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
72 BCRYPT_ALG_HANDLE hProvider;
73 NTSTATUS ret;
74 ret = BCryptOpenAlgorithmProvider(&hProvider, BCRYPT_RNG_ALGORITHM,
75 MS_PRIMITIVE_PROVIDER, 0);
76 if (!(BCRYPT_SUCCESS(ret))) {
77 ABSL_RAW_LOG(ERROR, "Failed to open crypto provider.");
78 return false;
79 }
80 ret = BCryptGenRandom(
81 hProvider, // provider
82 reinterpret_cast<UCHAR*>(values.data()), // buffer
83 static_cast<ULONG>(sizeof(uint32_t) * values.size()), // bytes
84 0); // flags
85 BCryptCloseAlgorithmProvider(hProvider, 0);
86 return BCRYPT_SUCCESS(ret);
87}
88
89#elif defined(ABSL_RANDOM_USE_NACL_SECURE_RANDOM)
90
91// On NaCL use nacl_secure_random to acquire bytes.
92bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
93 auto buffer = reinterpret_cast<uint8_t*>(values.data());
94 size_t buffer_size = sizeof(uint32_t) * values.size();
95
96 uint8_t* output_ptr = buffer;
97 while (buffer_size > 0) {
98 size_t nread = 0;
99 const int error = nacl_secure_random(output_ptr, buffer_size, &nread);
100 if (error != 0 || nread > buffer_size) {
101 ABSL_RAW_LOG(ERROR, "Failed to read secure_random seed data: %d", error);
102 return false;
103 }
104 output_ptr += nread;
105 buffer_size -= nread;
106 }
107 return true;
108}
109
110#else
111
112// On *nix, read entropy from /dev/urandom.
113bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
114 const char kEntropyFile[] = "/dev/urandom";
115
116 auto buffer = reinterpret_cast<uint8_t*>(values.data());
117 size_t buffer_size = sizeof(uint32_t) * values.size();
118
119 int dev_urandom = open(kEntropyFile, O_RDONLY);
120 bool success = (-1 != dev_urandom);
121 if (!success) {
122 return false;
123 }
124
125 while (success && buffer_size > 0) {
126 int bytes_read = read(dev_urandom, buffer, buffer_size);
127 int read_error = errno;
128 success = (bytes_read > 0);
129 if (success) {
130 buffer += bytes_read;
131 buffer_size -= bytes_read;
132 } else if (bytes_read == -1 && read_error == EINTR) {
133 success = true; // Need to try again.
134 }
135 }
136 close(dev_urandom);
137 return success;
138}
139
140#endif
141
142} // namespace
143
144bool ReadSeedMaterialFromOSEntropy(absl::Span<uint32_t> values) {
145 assert(values.data() != nullptr);
146 if (values.data() == nullptr) {
147 return false;
148 }
149 if (values.empty()) {
150 return true;
151 }
152 return ReadSeedMaterialFromOSEntropyImpl(values);
153}
154
155void MixIntoSeedMaterial(absl::Span<const uint32_t> sequence,
156 absl::Span<uint32_t> seed_material) {
157 // Algorithm is based on code available at
158 // https://gist.github.com/imneme/540829265469e673d045
159 constexpr uint32_t kInitVal = 0x43b0d7e5;
160 constexpr uint32_t kHashMul = 0x931e8875;
161 constexpr uint32_t kMixMulL = 0xca01f9dd;
162 constexpr uint32_t kMixMulR = 0x4973f715;
163 constexpr uint32_t kShiftSize = sizeof(uint32_t) * 8 / 2;
164
165 uint32_t hash_const = kInitVal;
166 auto hash = [&](uint32_t value) {
167 value ^= hash_const;
168 hash_const *= kHashMul;
169 value *= hash_const;
170 value ^= value >> kShiftSize;
171 return value;
172 };
173
174 auto mix = [&](uint32_t x, uint32_t y) {
175 uint32_t result = kMixMulL * x - kMixMulR * y;
176 result ^= result >> kShiftSize;
177 return result;
178 };
179
180 for (const auto& seq_val : sequence) {
181 for (auto& elem : seed_material) {
182 elem = mix(elem, hash(seq_val));
183 }
184 }
185}
186
187absl::optional<uint32_t> GetSaltMaterial() {
188 // Salt must be common for all generators within the same process so read it
189 // only once and store in static variable.
190 static const auto salt_material = []() -> absl::optional<uint32_t> {
191 uint32_t salt_value = 0;
192
193 if (random_internal::ReadSeedMaterialFromOSEntropy(
194 MakeSpan(&salt_value, 1))) {
195 return salt_value;
196 }
197
198 return absl::nullopt;
199 }();
200
201 return salt_material;
202}
203
204} // namespace random_internal
205} // namespace absl