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