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 if (*thread_states_list_bss_get() == state) {
123 // |state->prev| may be NULL either if it is the head of the list,
124 // or if |state| is freed before it was added to the list at all.
125 // Compare against the head of the list to distinguish these cases.
126 *thread_states_list_bss_get() = state->next;
127 }
128
129 if (state->next != NULL) {
130 state->next->prev = state->prev;
131 }
132
133 CRYPTO_MUTEX_unlock_write(thread_states_list_lock_bss_get());
134
135 CTR_DRBG_clear(&state->drbg);
136 #endif
137
138 OPENSSL_free(state);
139 }
140
141 #if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \
142 !defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
143 // rdrand should only be called if either |have_rdrand| or |have_fast_rdrand|
144 // returned true.
rdrand(uint8_t * buf,const size_t len)145 static int rdrand(uint8_t *buf, const size_t len) {
146 const size_t len_multiple8 = len & ~7;
147 if (!CRYPTO_rdrand_multiple8_buf(buf, len_multiple8)) {
148 return 0;
149 }
150 const size_t remainder = len - len_multiple8;
151
152 if (remainder != 0) {
153 assert(remainder < 8);
154
155 uint8_t rand_buf[8];
156 if (!CRYPTO_rdrand(rand_buf)) {
157 return 0;
158 }
159 OPENSSL_memcpy(buf + len_multiple8, rand_buf, remainder);
160 }
161
162 return 1;
163 }
164
165 #else
166
rdrand(uint8_t * buf,size_t len)167 static int rdrand(uint8_t *buf, size_t len) {
168 return 0;
169 }
170
171 #endif
172
173 #if defined(BORINGSSL_FIPS)
174
CRYPTO_get_seed_entropy(uint8_t * out_entropy,size_t out_entropy_len,int * out_want_additional_input)175 void CRYPTO_get_seed_entropy(uint8_t *out_entropy, size_t out_entropy_len,
176 int *out_want_additional_input) {
177 *out_want_additional_input = 0;
178 if (have_rdrand() && rdrand(out_entropy, out_entropy_len)) {
179 *out_want_additional_input = 1;
180 } else {
181 CRYPTO_sysrand_for_seed(out_entropy, out_entropy_len);
182 }
183 }
184
185 // In passive entropy mode, entropy is supplied from outside of the module via
186 // |RAND_load_entropy| and is stored in global instance of the following
187 // structure.
188
189 struct entropy_buffer {
190 // bytes contains entropy suitable for seeding a DRBG.
191 uint8_t
192 bytes[CRNGT_BLOCK_SIZE + CTR_DRBG_ENTROPY_LEN * BORINGSSL_FIPS_OVERREAD];
193 // bytes_valid indicates the number of bytes of |bytes| that contain valid
194 // data.
195 size_t bytes_valid;
196 // want_additional_input is true if any of the contents of |bytes| were
197 // obtained via a method other than from the kernel. In these cases entropy
198 // from the kernel is also provided via an additional input to the DRBG.
199 int want_additional_input;
200 };
201
202 DEFINE_BSS_GET(struct entropy_buffer, entropy_buffer);
203 DEFINE_STATIC_MUTEX(entropy_buffer_lock);
204
RAND_load_entropy(const uint8_t * entropy,size_t entropy_len,int want_additional_input)205 void RAND_load_entropy(const uint8_t *entropy, size_t entropy_len,
206 int want_additional_input) {
207 struct entropy_buffer *const buffer = entropy_buffer_bss_get();
208
209 CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get());
210 const size_t space = sizeof(buffer->bytes) - buffer->bytes_valid;
211 if (entropy_len > space) {
212 entropy_len = space;
213 }
214
215 OPENSSL_memcpy(&buffer->bytes[buffer->bytes_valid], entropy, entropy_len);
216 buffer->bytes_valid += entropy_len;
217 buffer->want_additional_input |=
218 want_additional_input && (entropy_len != 0);
219 CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get());
220 }
221
222 // get_seed_entropy fills |out_entropy_len| bytes of |out_entropy| from the
223 // global |entropy_buffer|.
get_seed_entropy(uint8_t * out_entropy,size_t out_entropy_len,int * out_want_additional_input)224 static void get_seed_entropy(uint8_t *out_entropy, size_t out_entropy_len,
225 int *out_want_additional_input) {
226 struct entropy_buffer *const buffer = entropy_buffer_bss_get();
227 if (out_entropy_len > sizeof(buffer->bytes)) {
228 abort();
229 }
230
231 CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get());
232 while (buffer->bytes_valid < out_entropy_len) {
233 CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get());
234 RAND_need_entropy(out_entropy_len - buffer->bytes_valid);
235 CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get());
236 }
237
238 *out_want_additional_input = buffer->want_additional_input;
239 OPENSSL_memcpy(out_entropy, buffer->bytes, out_entropy_len);
240 OPENSSL_memmove(buffer->bytes, &buffer->bytes[out_entropy_len],
241 buffer->bytes_valid - out_entropy_len);
242 buffer->bytes_valid -= out_entropy_len;
243 if (buffer->bytes_valid == 0) {
244 buffer->want_additional_input = 0;
245 }
246
247 CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get());
248 }
249
250 // rand_get_seed fills |seed| with entropy. In some cases, it will additionally
251 // fill |additional_input| with entropy to supplement |seed|. It sets
252 // |*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)253 static void rand_get_seed(struct rand_thread_state *state,
254 uint8_t seed[CTR_DRBG_ENTROPY_LEN],
255 uint8_t additional_input[CTR_DRBG_ENTROPY_LEN],
256 size_t *out_additional_input_len) {
257 uint8_t entropy_bytes[sizeof(state->last_block) +
258 CTR_DRBG_ENTROPY_LEN * BORINGSSL_FIPS_OVERREAD];
259 uint8_t *entropy = entropy_bytes;
260 size_t entropy_len = sizeof(entropy_bytes);
261
262 if (state->last_block_valid) {
263 // No need to fill |state->last_block| with entropy from the read.
264 entropy += sizeof(state->last_block);
265 entropy_len -= sizeof(state->last_block);
266 }
267
268 int want_additional_input;
269 get_seed_entropy(entropy, entropy_len, &want_additional_input);
270
271 if (!state->last_block_valid) {
272 OPENSSL_memcpy(state->last_block, entropy, sizeof(state->last_block));
273 entropy += sizeof(state->last_block);
274 entropy_len -= sizeof(state->last_block);
275 }
276
277 // See FIPS 140-2, section 4.9.2. This is the “continuous random number
278 // generator test” which causes the program to randomly abort. Hopefully the
279 // rate of failure is small enough not to be a problem in practice.
280 if (CRYPTO_memcmp(state->last_block, entropy, sizeof(state->last_block)) ==
281 0) {
282 fprintf(stderr, "CRNGT failed.\n");
283 BORINGSSL_FIPS_abort();
284 }
285
286 assert(entropy_len % CRNGT_BLOCK_SIZE == 0);
287 for (size_t i = CRNGT_BLOCK_SIZE; i < entropy_len; i += CRNGT_BLOCK_SIZE) {
288 if (CRYPTO_memcmp(entropy + i - CRNGT_BLOCK_SIZE, entropy + i,
289 CRNGT_BLOCK_SIZE) == 0) {
290 fprintf(stderr, "CRNGT failed.\n");
291 BORINGSSL_FIPS_abort();
292 }
293 }
294 OPENSSL_memcpy(state->last_block, entropy + entropy_len - CRNGT_BLOCK_SIZE,
295 CRNGT_BLOCK_SIZE);
296
297 assert(entropy_len == BORINGSSL_FIPS_OVERREAD * CTR_DRBG_ENTROPY_LEN);
298 OPENSSL_memcpy(seed, entropy, CTR_DRBG_ENTROPY_LEN);
299
300 for (size_t i = 1; i < BORINGSSL_FIPS_OVERREAD; i++) {
301 for (size_t j = 0; j < CTR_DRBG_ENTROPY_LEN; j++) {
302 seed[j] ^= entropy[CTR_DRBG_ENTROPY_LEN * i + j];
303 }
304 }
305
306 // If we used something other than system entropy then also
307 // opportunistically read from the system. This avoids solely relying on the
308 // hardware once the entropy pool has been initialized.
309 *out_additional_input_len = 0;
310 if (want_additional_input &&
311 CRYPTO_sysrand_if_available(additional_input, CTR_DRBG_ENTROPY_LEN)) {
312 *out_additional_input_len = CTR_DRBG_ENTROPY_LEN;
313 }
314 }
315
316 #else
317
318 // rand_get_seed fills |seed| with entropy. In some cases, it will additionally
319 // fill |additional_input| with entropy to supplement |seed|. It sets
320 // |*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)321 static void rand_get_seed(struct rand_thread_state *state,
322 uint8_t seed[CTR_DRBG_ENTROPY_LEN],
323 uint8_t additional_input[CTR_DRBG_ENTROPY_LEN],
324 size_t *out_additional_input_len) {
325 // If not in FIPS mode, we don't overread from the system entropy source and
326 // we don't depend only on the hardware RDRAND.
327 CRYPTO_sysrand_for_seed(seed, CTR_DRBG_ENTROPY_LEN);
328 *out_additional_input_len = 0;
329 }
330
331 #endif
332
RAND_bytes_with_additional_data(uint8_t * out,size_t out_len,const uint8_t user_additional_data[32])333 void RAND_bytes_with_additional_data(uint8_t *out, size_t out_len,
334 const uint8_t user_additional_data[32]) {
335 if (out_len == 0) {
336 return;
337 }
338
339 const uint64_t fork_generation = CRYPTO_get_fork_generation();
340 const int fork_unsafe_buffering = rand_fork_unsafe_buffering_enabled();
341
342 // Additional data is mixed into every CTR-DRBG call to protect, as best we
343 // can, against forks & VM clones. We do not over-read this information and
344 // don't reseed with it so, from the point of view of FIPS, this doesn't
345 // provide “prediction resistance”. But, in practice, it does.
346 uint8_t additional_data[32];
347 // Intel chips have fast RDRAND instructions while, in other cases, RDRAND can
348 // be _slower_ than a system call.
349 if (!have_fast_rdrand() ||
350 !rdrand(additional_data, sizeof(additional_data))) {
351 // Without a hardware RNG to save us from address-space duplication, the OS
352 // entropy is used. This can be expensive (one read per |RAND_bytes| call)
353 // and so is disabled when we have fork detection, or if the application has
354 // promised not to fork.
355 if (fork_generation != 0 || fork_unsafe_buffering) {
356 OPENSSL_memset(additional_data, 0, sizeof(additional_data));
357 } else if (!have_rdrand()) {
358 // No alternative so block for OS entropy.
359 CRYPTO_sysrand(additional_data, sizeof(additional_data));
360 } else if (!CRYPTO_sysrand_if_available(additional_data,
361 sizeof(additional_data)) &&
362 !rdrand(additional_data, sizeof(additional_data))) {
363 // RDRAND failed: block for OS entropy.
364 CRYPTO_sysrand(additional_data, sizeof(additional_data));
365 }
366 }
367
368 for (size_t i = 0; i < sizeof(additional_data); i++) {
369 additional_data[i] ^= user_additional_data[i];
370 }
371
372 struct rand_thread_state stack_state;
373 struct rand_thread_state *state =
374 CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_RAND);
375
376 if (state == NULL) {
377 state = OPENSSL_zalloc(sizeof(struct rand_thread_state));
378 if (state == NULL ||
379 !CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_RAND, state,
380 rand_thread_state_free)) {
381 // If the system is out of memory, use an ephemeral state on the
382 // stack.
383 state = &stack_state;
384 }
385
386 state->last_block_valid = 0;
387 uint8_t seed[CTR_DRBG_ENTROPY_LEN];
388 uint8_t personalization[CTR_DRBG_ENTROPY_LEN] = {0};
389 size_t personalization_len = 0;
390 rand_get_seed(state, seed, personalization, &personalization_len);
391
392 if (!CTR_DRBG_init(&state->drbg, seed, personalization,
393 personalization_len)) {
394 abort();
395 }
396 state->calls = 0;
397 state->fork_generation = fork_generation;
398 state->fork_unsafe_buffering = fork_unsafe_buffering;
399
400 #if defined(BORINGSSL_FIPS)
401 CRYPTO_MUTEX_init(&state->clear_drbg_lock);
402 if (state != &stack_state) {
403 CRYPTO_MUTEX_lock_write(thread_states_list_lock_bss_get());
404 struct rand_thread_state **states_list = thread_states_list_bss_get();
405 state->next = *states_list;
406 if (state->next != NULL) {
407 state->next->prev = state;
408 }
409 state->prev = NULL;
410 *states_list = state;
411 CRYPTO_MUTEX_unlock_write(thread_states_list_lock_bss_get());
412 }
413 #endif
414 }
415
416 if (state->calls >= kReseedInterval ||
417 // If we've forked since |state| was last seeded, reseed.
418 state->fork_generation != fork_generation ||
419 // If |state| was seeded from a state with different fork-safety
420 // preferences, reseed. Suppose |state| was fork-safe, then forked into
421 // two children, but each of the children never fork and disable fork
422 // safety. The children must reseed to avoid working from the same PRNG
423 // state.
424 state->fork_unsafe_buffering != fork_unsafe_buffering) {
425 uint8_t seed[CTR_DRBG_ENTROPY_LEN];
426 uint8_t reseed_additional_data[CTR_DRBG_ENTROPY_LEN] = {0};
427 size_t reseed_additional_data_len = 0;
428 rand_get_seed(state, seed, reseed_additional_data,
429 &reseed_additional_data_len);
430 #if defined(BORINGSSL_FIPS)
431 // Take a read lock around accesses to |state->drbg|. This is needed to
432 // avoid returning bad entropy if we race with
433 // |rand_thread_state_clear_all|.
434 CRYPTO_MUTEX_lock_read(&state->clear_drbg_lock);
435 #endif
436 if (!CTR_DRBG_reseed(&state->drbg, seed, reseed_additional_data,
437 reseed_additional_data_len)) {
438 abort();
439 }
440 state->calls = 0;
441 state->fork_generation = fork_generation;
442 state->fork_unsafe_buffering = fork_unsafe_buffering;
443 } else {
444 #if defined(BORINGSSL_FIPS)
445 CRYPTO_MUTEX_lock_read(&state->clear_drbg_lock);
446 #endif
447 }
448
449 int first_call = 1;
450 while (out_len > 0) {
451 size_t todo = out_len;
452 if (todo > CTR_DRBG_MAX_GENERATE_LENGTH) {
453 todo = CTR_DRBG_MAX_GENERATE_LENGTH;
454 }
455
456 if (!CTR_DRBG_generate(&state->drbg, out, todo, additional_data,
457 first_call ? sizeof(additional_data) : 0)) {
458 abort();
459 }
460
461 out += todo;
462 out_len -= todo;
463 // Though we only check before entering the loop, this cannot add enough to
464 // overflow a |size_t|.
465 state->calls++;
466 first_call = 0;
467 }
468
469 if (state == &stack_state) {
470 CTR_DRBG_clear(&state->drbg);
471 }
472
473 #if defined(BORINGSSL_FIPS)
474 CRYPTO_MUTEX_unlock_read(&state->clear_drbg_lock);
475 #endif
476 }
477
RAND_bytes(uint8_t * out,size_t out_len)478 int RAND_bytes(uint8_t *out, size_t out_len) {
479 static const uint8_t kZeroAdditionalData[32] = {0};
480 RAND_bytes_with_additional_data(out, out_len, kZeroAdditionalData);
481 return 1;
482 }
483
RAND_pseudo_bytes(uint8_t * buf,size_t len)484 int RAND_pseudo_bytes(uint8_t *buf, size_t len) {
485 return RAND_bytes(buf, len);
486 }
487
RAND_get_system_entropy_for_custom_prng(uint8_t * buf,size_t len)488 void RAND_get_system_entropy_for_custom_prng(uint8_t *buf, size_t len) {
489 if (len > 256) {
490 abort();
491 }
492 CRYPTO_sysrand_for_seed(buf, len);
493 }
494