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