1 /* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include <openssl/rand.h>
16
17 #include <assert.h>
18 #include <limits.h>
19 #include <string.h>
20
21 #if defined(BORINGSSL_FIPS)
22 #include <unistd.h>
23 #endif
24
25 #include <openssl/chacha.h>
26 #include <openssl/ctrdrbg.h>
27 #include <openssl/mem.h>
28
29 #include "internal.h"
30 #include "fork_detect.h"
31 #include "../../internal.h"
32 #include "../delocate.h"
33
34
35 // It's assumed that the operating system always has an unfailing source of
36 // entropy which is accessed via |CRYPTO_sysrand[_for_seed]|. (If the operating
37 // system entropy source fails, it's up to |CRYPTO_sysrand| to abort the
38 // process—we don't try to handle it.)
39 //
40 // In addition, the hardware may provide a low-latency RNG. Intel's rdrand
41 // instruction is the canonical example of this. When a hardware RNG is
42 // available we don't need to worry about an RNG failure arising from fork()ing
43 // the process or moving a VM, so we can keep thread-local RNG state and use it
44 // as an additional-data input to CTR-DRBG.
45 //
46 // (We assume that the OS entropy is safe from fork()ing and VM duplication.
47 // This might be a bit of a leap of faith, esp on Windows, but there's nothing
48 // that we can do about it.)
49
50 // kReseedInterval is the number of generate calls made to CTR-DRBG before
51 // reseeding.
52 static const unsigned kReseedInterval = 4096;
53
54 // CRNGT_BLOCK_SIZE is the number of bytes in a “block” for the purposes of the
55 // continuous random number generator test in FIPS 140-2, section 4.9.2.
56 #define CRNGT_BLOCK_SIZE 16
57
58 // rand_thread_state contains the per-thread state for the RNG.
59 struct rand_thread_state {
60 CTR_DRBG_STATE drbg;
61 uint64_t fork_generation;
62 // calls is the number of generate calls made on |drbg| since it was last
63 // (re)seeded. This is bound by |kReseedInterval|.
64 unsigned calls;
65 // last_block_valid is non-zero iff |last_block| contains data from
66 // |get_seed_entropy|.
67 int last_block_valid;
68 // fork_unsafe_buffering is non-zero iff, when |drbg| was last (re)seeded,
69 // fork-unsafe buffering was enabled.
70 int fork_unsafe_buffering;
71
72 #if defined(BORINGSSL_FIPS)
73 // last_block contains the previous block from |get_seed_entropy|.
74 uint8_t last_block[CRNGT_BLOCK_SIZE];
75 // next and prev form a NULL-terminated, double-linked list of all states in
76 // a process.
77 struct rand_thread_state *next, *prev;
78 // clear_drbg_lock synchronizes between uses of |drbg| and
79 // |rand_thread_state_clear_all| clearing it. This lock should be uncontended
80 // in the common case, except on shutdown.
81 CRYPTO_MUTEX clear_drbg_lock;
82 #endif
83 };
84
85 #if defined(BORINGSSL_FIPS)
86 // thread_states_list is the head of a linked-list of all |rand_thread_state|
87 // objects in the process, one per thread. This is needed because FIPS requires
88 // that they be zeroed on process exit, but thread-local destructors aren't
89 // called when the whole process is exiting.
90 DEFINE_BSS_GET(struct rand_thread_state *, thread_states_list);
91 DEFINE_STATIC_MUTEX(thread_states_list_lock);
92
93 static void rand_thread_state_clear_all(void) __attribute__((destructor));
rand_thread_state_clear_all(void)94 static void rand_thread_state_clear_all(void) {
95 CRYPTO_MUTEX_lock_write(thread_states_list_lock_bss_get());
96 for (struct rand_thread_state *cur = *thread_states_list_bss_get();
97 cur != NULL; cur = cur->next) {
98 CRYPTO_MUTEX_lock_write(&cur->clear_drbg_lock);
99 CTR_DRBG_clear(&cur->drbg);
100 }
101 // The locks are deliberately left locked so that any threads that are still
102 // running will hang if they try to call |RAND_bytes|. It also ensures
103 // |rand_thread_state_free| cannot free any thread state while we've taken the
104 // lock.
105 }
106 #endif
107
108 // rand_thread_state_free frees a |rand_thread_state|. This is called when a
109 // thread exits.
rand_thread_state_free(void * state_in)110 static void rand_thread_state_free(void *state_in) {
111 struct rand_thread_state *state = state_in;
112
113 if (state_in == NULL) {
114 return;
115 }
116
117 #if defined(BORINGSSL_FIPS)
118 CRYPTO_MUTEX_lock_write(thread_states_list_lock_bss_get());
119
120 if (state->prev != NULL) {
121 state->prev->next = state->next;
122 } else {
123 *thread_states_list_bss_get() = state->next;
124 }
125
126 if (state->next != NULL) {
127 state->next->prev = state->prev;
128 }
129
130 CRYPTO_MUTEX_unlock_write(thread_states_list_lock_bss_get());
131
132 CTR_DRBG_clear(&state->drbg);
133 #endif
134
135 OPENSSL_free(state);
136 }
137
138 #if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \
139 !defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
140 // rdrand should only be called if either |have_rdrand| or |have_fast_rdrand|
141 // returned true.
rdrand(uint8_t * buf,const size_t len)142 static int rdrand(uint8_t *buf, const size_t len) {
143 const size_t len_multiple8 = len & ~7;
144 if (!CRYPTO_rdrand_multiple8_buf(buf, len_multiple8)) {
145 return 0;
146 }
147 const size_t remainder = len - len_multiple8;
148
149 if (remainder != 0) {
150 assert(remainder < 8);
151
152 uint8_t rand_buf[8];
153 if (!CRYPTO_rdrand(rand_buf)) {
154 return 0;
155 }
156 OPENSSL_memcpy(buf + len_multiple8, rand_buf, remainder);
157 }
158
159 return 1;
160 }
161
162 #else
163
rdrand(uint8_t * buf,size_t len)164 static int rdrand(uint8_t *buf, size_t len) {
165 return 0;
166 }
167
168 #endif
169
170 #if defined(BORINGSSL_FIPS)
171
CRYPTO_get_seed_entropy(uint8_t * out_entropy,size_t out_entropy_len,int * out_want_additional_input)172 void CRYPTO_get_seed_entropy(uint8_t *out_entropy, size_t out_entropy_len,
173 int *out_want_additional_input) {
174 *out_want_additional_input = 0;
175 if (have_rdrand() && rdrand(out_entropy, out_entropy_len)) {
176 *out_want_additional_input = 1;
177 } else {
178 CRYPTO_sysrand_for_seed(out_entropy, out_entropy_len);
179 }
180 }
181
182 // In passive entropy mode, entropy is supplied from outside of the module via
183 // |RAND_load_entropy| and is stored in global instance of the following
184 // structure.
185
186 struct entropy_buffer {
187 // bytes contains entropy suitable for seeding a DRBG.
188 uint8_t
189 bytes[CRNGT_BLOCK_SIZE + CTR_DRBG_ENTROPY_LEN * BORINGSSL_FIPS_OVERREAD];
190 // bytes_valid indicates the number of bytes of |bytes| that contain valid
191 // data.
192 size_t bytes_valid;
193 // want_additional_input is true if any of the contents of |bytes| were
194 // obtained via a method other than from the kernel. In these cases entropy
195 // from the kernel is also provided via an additional input to the DRBG.
196 int want_additional_input;
197 };
198
199 DEFINE_BSS_GET(struct entropy_buffer, entropy_buffer);
200 DEFINE_STATIC_MUTEX(entropy_buffer_lock);
201
RAND_load_entropy(const uint8_t * entropy,size_t entropy_len,int want_additional_input)202 void RAND_load_entropy(const uint8_t *entropy, size_t entropy_len,
203 int want_additional_input) {
204 struct entropy_buffer *const buffer = entropy_buffer_bss_get();
205
206 CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get());
207 const size_t space = sizeof(buffer->bytes) - buffer->bytes_valid;
208 if (entropy_len > space) {
209 entropy_len = space;
210 }
211
212 OPENSSL_memcpy(&buffer->bytes[buffer->bytes_valid], entropy, entropy_len);
213 buffer->bytes_valid += entropy_len;
214 buffer->want_additional_input |=
215 want_additional_input && (entropy_len != 0);
216 CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get());
217 }
218
219 // get_seed_entropy fills |out_entropy_len| bytes of |out_entropy| from the
220 // global |entropy_buffer|.
get_seed_entropy(uint8_t * out_entropy,size_t out_entropy_len,int * out_want_additional_input)221 static void get_seed_entropy(uint8_t *out_entropy, size_t out_entropy_len,
222 int *out_want_additional_input) {
223 struct entropy_buffer *const buffer = entropy_buffer_bss_get();
224 if (out_entropy_len > sizeof(buffer->bytes)) {
225 abort();
226 }
227
228 CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get());
229 while (buffer->bytes_valid < out_entropy_len) {
230 CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get());
231 RAND_need_entropy(out_entropy_len - buffer->bytes_valid);
232 CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get());
233 }
234
235 *out_want_additional_input = buffer->want_additional_input;
236 OPENSSL_memcpy(out_entropy, buffer->bytes, out_entropy_len);
237 OPENSSL_memmove(buffer->bytes, &buffer->bytes[out_entropy_len],
238 buffer->bytes_valid - out_entropy_len);
239 buffer->bytes_valid -= out_entropy_len;
240 if (buffer->bytes_valid == 0) {
241 buffer->want_additional_input = 0;
242 }
243
244 CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get());
245 }
246
247 // rand_get_seed fills |seed| with entropy. In some cases, it will additionally
248 // fill |additional_input| with entropy to supplement |seed|. It sets
249 // |*out_additional_input_len| to the number of extra bytes.
rand_get_seed(struct rand_thread_state * state,uint8_t seed[CTR_DRBG_ENTROPY_LEN],uint8_t additional_input[CTR_DRBG_ENTROPY_LEN],size_t * out_additional_input_len)250 static void rand_get_seed(struct rand_thread_state *state,
251 uint8_t seed[CTR_DRBG_ENTROPY_LEN],
252 uint8_t additional_input[CTR_DRBG_ENTROPY_LEN],
253 size_t *out_additional_input_len) {
254 uint8_t entropy_bytes[sizeof(state->last_block) +
255 CTR_DRBG_ENTROPY_LEN * BORINGSSL_FIPS_OVERREAD];
256 uint8_t *entropy = entropy_bytes;
257 size_t entropy_len = sizeof(entropy_bytes);
258
259 if (state->last_block_valid) {
260 // No need to fill |state->last_block| with entropy from the read.
261 entropy += sizeof(state->last_block);
262 entropy_len -= sizeof(state->last_block);
263 }
264
265 int want_additional_input;
266 get_seed_entropy(entropy, entropy_len, &want_additional_input);
267
268 if (!state->last_block_valid) {
269 OPENSSL_memcpy(state->last_block, entropy, sizeof(state->last_block));
270 entropy += sizeof(state->last_block);
271 entropy_len -= sizeof(state->last_block);
272 }
273
274 // See FIPS 140-2, section 4.9.2. This is the “continuous random number
275 // generator test” which causes the program to randomly abort. Hopefully the
276 // rate of failure is small enough not to be a problem in practice.
277 if (CRYPTO_memcmp(state->last_block, entropy, sizeof(state->last_block)) ==
278 0) {
279 fprintf(stderr, "CRNGT failed.\n");
280 BORINGSSL_FIPS_abort();
281 }
282
283 assert(entropy_len % CRNGT_BLOCK_SIZE == 0);
284 for (size_t i = CRNGT_BLOCK_SIZE; i < entropy_len; i += CRNGT_BLOCK_SIZE) {
285 if (CRYPTO_memcmp(entropy + i - CRNGT_BLOCK_SIZE, entropy + i,
286 CRNGT_BLOCK_SIZE) == 0) {
287 fprintf(stderr, "CRNGT failed.\n");
288 BORINGSSL_FIPS_abort();
289 }
290 }
291 OPENSSL_memcpy(state->last_block, entropy + entropy_len - CRNGT_BLOCK_SIZE,
292 CRNGT_BLOCK_SIZE);
293
294 assert(entropy_len == BORINGSSL_FIPS_OVERREAD * CTR_DRBG_ENTROPY_LEN);
295 OPENSSL_memcpy(seed, entropy, CTR_DRBG_ENTROPY_LEN);
296
297 for (size_t i = 1; i < BORINGSSL_FIPS_OVERREAD; i++) {
298 for (size_t j = 0; j < CTR_DRBG_ENTROPY_LEN; j++) {
299 seed[j] ^= entropy[CTR_DRBG_ENTROPY_LEN * i + j];
300 }
301 }
302
303 // If we used something other than system entropy then also
304 // opportunistically read from the system. This avoids solely relying on the
305 // hardware once the entropy pool has been initialized.
306 *out_additional_input_len = 0;
307 if (want_additional_input &&
308 CRYPTO_sysrand_if_available(additional_input, CTR_DRBG_ENTROPY_LEN)) {
309 *out_additional_input_len = CTR_DRBG_ENTROPY_LEN;
310 }
311 }
312
313 #else
314
315 // rand_get_seed fills |seed| with entropy. In some cases, it will additionally
316 // fill |additional_input| with entropy to supplement |seed|. It sets
317 // |*out_additional_input_len| to the number of extra bytes.
rand_get_seed(struct rand_thread_state * state,uint8_t seed[CTR_DRBG_ENTROPY_LEN],uint8_t additional_input[CTR_DRBG_ENTROPY_LEN],size_t * out_additional_input_len)318 static void rand_get_seed(struct rand_thread_state *state,
319 uint8_t seed[CTR_DRBG_ENTROPY_LEN],
320 uint8_t additional_input[CTR_DRBG_ENTROPY_LEN],
321 size_t *out_additional_input_len) {
322 // If not in FIPS mode, we don't overread from the system entropy source and
323 // we don't depend only on the hardware RDRAND.
324 CRYPTO_sysrand_for_seed(seed, CTR_DRBG_ENTROPY_LEN);
325 *out_additional_input_len = 0;
326 }
327
328 #endif
329
RAND_bytes_with_additional_data(uint8_t * out,size_t out_len,const uint8_t user_additional_data[32])330 void RAND_bytes_with_additional_data(uint8_t *out, size_t out_len,
331 const uint8_t user_additional_data[32]) {
332 if (out_len == 0) {
333 return;
334 }
335
336 const uint64_t fork_generation = CRYPTO_get_fork_generation();
337 const int fork_unsafe_buffering = rand_fork_unsafe_buffering_enabled();
338
339 // Additional data is mixed into every CTR-DRBG call to protect, as best we
340 // can, against forks & VM clones. We do not over-read this information and
341 // don't reseed with it so, from the point of view of FIPS, this doesn't
342 // provide “prediction resistance”. But, in practice, it does.
343 uint8_t additional_data[32];
344 // Intel chips have fast RDRAND instructions while, in other cases, RDRAND can
345 // be _slower_ than a system call.
346 if (!have_fast_rdrand() ||
347 !rdrand(additional_data, sizeof(additional_data))) {
348 // Without a hardware RNG to save us from address-space duplication, the OS
349 // entropy is used. This can be expensive (one read per |RAND_bytes| call)
350 // and so is disabled when we have fork detection, or if the application has
351 // promised not to fork.
352 if (fork_generation != 0 || fork_unsafe_buffering) {
353 OPENSSL_memset(additional_data, 0, sizeof(additional_data));
354 } else if (!have_rdrand()) {
355 // No alternative so block for OS entropy.
356 CRYPTO_sysrand(additional_data, sizeof(additional_data));
357 } else if (!CRYPTO_sysrand_if_available(additional_data,
358 sizeof(additional_data)) &&
359 !rdrand(additional_data, sizeof(additional_data))) {
360 // RDRAND failed: block for OS entropy.
361 CRYPTO_sysrand(additional_data, sizeof(additional_data));
362 }
363 }
364
365 for (size_t i = 0; i < sizeof(additional_data); i++) {
366 additional_data[i] ^= user_additional_data[i];
367 }
368
369 struct rand_thread_state stack_state;
370 struct rand_thread_state *state =
371 CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_RAND);
372
373 if (state == NULL) {
374 state = OPENSSL_malloc(sizeof(struct rand_thread_state));
375 if (state == NULL ||
376 !CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_RAND, state,
377 rand_thread_state_free)) {
378 // If the system is out of memory, use an ephemeral state on the
379 // stack.
380 state = &stack_state;
381 }
382
383 state->last_block_valid = 0;
384 uint8_t seed[CTR_DRBG_ENTROPY_LEN];
385 uint8_t personalization[CTR_DRBG_ENTROPY_LEN] = {0};
386 size_t personalization_len = 0;
387 rand_get_seed(state, seed, personalization, &personalization_len);
388
389 if (!CTR_DRBG_init(&state->drbg, seed, personalization,
390 personalization_len)) {
391 abort();
392 }
393 state->calls = 0;
394 state->fork_generation = fork_generation;
395 state->fork_unsafe_buffering = fork_unsafe_buffering;
396
397 #if defined(BORINGSSL_FIPS)
398 CRYPTO_MUTEX_init(&state->clear_drbg_lock);
399 if (state != &stack_state) {
400 CRYPTO_MUTEX_lock_write(thread_states_list_lock_bss_get());
401 struct rand_thread_state **states_list = thread_states_list_bss_get();
402 state->next = *states_list;
403 if (state->next != NULL) {
404 state->next->prev = state;
405 }
406 state->prev = NULL;
407 *states_list = state;
408 CRYPTO_MUTEX_unlock_write(thread_states_list_lock_bss_get());
409 }
410 #endif
411 }
412
413 if (state->calls >= kReseedInterval ||
414 // If we've forked since |state| was last seeded, reseed.
415 state->fork_generation != fork_generation ||
416 // If |state| was seeded from a state with different fork-safety
417 // preferences, reseed. Suppose |state| was fork-safe, then forked into
418 // two children, but each of the children never fork and disable fork
419 // safety. The children must reseed to avoid working from the same PRNG
420 // state.
421 state->fork_unsafe_buffering != fork_unsafe_buffering) {
422 uint8_t seed[CTR_DRBG_ENTROPY_LEN];
423 uint8_t reseed_additional_data[CTR_DRBG_ENTROPY_LEN] = {0};
424 size_t reseed_additional_data_len = 0;
425 rand_get_seed(state, seed, reseed_additional_data,
426 &reseed_additional_data_len);
427 #if defined(BORINGSSL_FIPS)
428 // Take a read lock around accesses to |state->drbg|. This is needed to
429 // avoid returning bad entropy if we race with
430 // |rand_thread_state_clear_all|.
431 CRYPTO_MUTEX_lock_read(&state->clear_drbg_lock);
432 #endif
433 if (!CTR_DRBG_reseed(&state->drbg, seed, reseed_additional_data,
434 reseed_additional_data_len)) {
435 abort();
436 }
437 state->calls = 0;
438 state->fork_generation = fork_generation;
439 state->fork_unsafe_buffering = fork_unsafe_buffering;
440 } else {
441 #if defined(BORINGSSL_FIPS)
442 CRYPTO_MUTEX_lock_read(&state->clear_drbg_lock);
443 #endif
444 }
445
446 int first_call = 1;
447 while (out_len > 0) {
448 size_t todo = out_len;
449 if (todo > CTR_DRBG_MAX_GENERATE_LENGTH) {
450 todo = CTR_DRBG_MAX_GENERATE_LENGTH;
451 }
452
453 if (!CTR_DRBG_generate(&state->drbg, out, todo, additional_data,
454 first_call ? sizeof(additional_data) : 0)) {
455 abort();
456 }
457
458 out += todo;
459 out_len -= todo;
460 // Though we only check before entering the loop, this cannot add enough to
461 // overflow a |size_t|.
462 state->calls++;
463 first_call = 0;
464 }
465
466 if (state == &stack_state) {
467 CTR_DRBG_clear(&state->drbg);
468 }
469
470 #if defined(BORINGSSL_FIPS)
471 CRYPTO_MUTEX_unlock_read(&state->clear_drbg_lock);
472 #endif
473 }
474
RAND_bytes(uint8_t * out,size_t out_len)475 int RAND_bytes(uint8_t *out, size_t out_len) {
476 static const uint8_t kZeroAdditionalData[32] = {0};
477 RAND_bytes_with_additional_data(out, out_len, kZeroAdditionalData);
478 return 1;
479 }
480
RAND_pseudo_bytes(uint8_t * buf,size_t len)481 int RAND_pseudo_bytes(uint8_t *buf, size_t len) {
482 return RAND_bytes(buf, len);
483 }
484
RAND_get_system_entropy_for_custom_prng(uint8_t * buf,size_t len)485 void RAND_get_system_entropy_for_custom_prng(uint8_t *buf, size_t len) {
486 if (len > 256) {
487 abort();
488 }
489 CRYPTO_sysrand_for_seed(buf, len);
490 }
491