Coverage Report

Created: 2023-06-29 07:25

/src/boringssl/crypto/fipsmodule/rand/rand.c
Line
Count
Source (jump to first uncovered line)
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));
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.
110
0
static void rand_thread_state_free(void *state_in) {
111
0
  struct rand_thread_state *state = state_in;
112
113
0
  if (state_in == NULL) {
114
0
    return;
115
0
  }
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
0
  OPENSSL_free(state);
136
0
}
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.
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
164
595k
static int rdrand(uint8_t *buf, size_t len) {
165
595k
  return 0;
166
595k
}
167
168
#endif
169
170
#if defined(BORINGSSL_FIPS)
171
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
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|.
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.
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.
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
149
                          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
149
  CRYPTO_sysrand_for_seed(seed, CTR_DRBG_ENTROPY_LEN);
325
149
  *out_additional_input_len = 0;
326
149
}
327
328
#endif
329
330
void RAND_bytes_with_additional_data(uint8_t *out, size_t out_len,
331
595k
                                     const uint8_t user_additional_data[32]) {
332
595k
  if (out_len == 0) {
333
0
    return;
334
0
  }
335
336
595k
  const uint64_t fork_generation = CRYPTO_get_fork_generation();
337
595k
  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
595k
  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
595k
  if (!have_fast_rdrand() ||
347
595k
      !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
595k
    if (fork_generation != 0 || fork_unsafe_buffering) {
353
595k
      OPENSSL_memset(additional_data, 0, sizeof(additional_data));
354
595k
    } else if (!have_rdrand()) {
355
      // No alternative so block for OS entropy.
356
0
      CRYPTO_sysrand(additional_data, sizeof(additional_data));
357
0
    } else if (!CRYPTO_sysrand_if_available(additional_data,
358
0
                                            sizeof(additional_data)) &&
359
0
               !rdrand(additional_data, sizeof(additional_data))) {
360
      // RDRAND failed: block for OS entropy.
361
0
      CRYPTO_sysrand(additional_data, sizeof(additional_data));
362
0
    }
363
595k
  }
364
365
19.6M
  for (size_t i = 0; i < sizeof(additional_data); i++) {
366
19.0M
    additional_data[i] ^= user_additional_data[i];
367
19.0M
  }
368
369
595k
  struct rand_thread_state stack_state;
370
595k
  struct rand_thread_state *state =
371
595k
      CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_RAND);
372
373
595k
  if (state == NULL) {
374
6
    state = OPENSSL_malloc(sizeof(struct rand_thread_state));
375
6
    if (state == NULL ||
376
6
        !CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_RAND, state,
377
6
                                 rand_thread_state_free)) {
378
      // If the system is out of memory, use an ephemeral state on the
379
      // stack.
380
0
      state = &stack_state;
381
0
    }
382
383
6
    state->last_block_valid = 0;
384
6
    uint8_t seed[CTR_DRBG_ENTROPY_LEN];
385
6
    uint8_t personalization[CTR_DRBG_ENTROPY_LEN] = {0};
386
6
    size_t personalization_len = 0;
387
6
    rand_get_seed(state, seed, personalization, &personalization_len);
388
389
6
    if (!CTR_DRBG_init(&state->drbg, seed, personalization,
390
6
                       personalization_len)) {
391
0
      abort();
392
0
    }
393
6
    state->calls = 0;
394
6
    state->fork_generation = fork_generation;
395
6
    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
6
  }
412
413
595k
  if (state->calls >= kReseedInterval ||
414
      // If we've forked since |state| was last seeded, reseed.
415
595k
      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
595k
      state->fork_unsafe_buffering != fork_unsafe_buffering) {
422
143
    uint8_t seed[CTR_DRBG_ENTROPY_LEN];
423
143
    uint8_t reseed_additional_data[CTR_DRBG_ENTROPY_LEN] = {0};
424
143
    size_t reseed_additional_data_len = 0;
425
143
    rand_get_seed(state, seed, reseed_additional_data,
426
143
                  &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
143
    if (!CTR_DRBG_reseed(&state->drbg, seed, reseed_additional_data,
434
143
                         reseed_additional_data_len)) {
435
0
      abort();
436
0
    }
437
143
    state->calls = 0;
438
143
    state->fork_generation = fork_generation;
439
143
    state->fork_unsafe_buffering = fork_unsafe_buffering;
440
595k
  } else {
441
#if defined(BORINGSSL_FIPS)
442
    CRYPTO_MUTEX_lock_read(&state->clear_drbg_lock);
443
#endif
444
595k
  }
445
446
595k
  int first_call = 1;
447
1.19M
  while (out_len > 0) {
448
595k
    size_t todo = out_len;
449
595k
    if (todo > CTR_DRBG_MAX_GENERATE_LENGTH) {
450
0
      todo = CTR_DRBG_MAX_GENERATE_LENGTH;
451
0
    }
452
453
595k
    if (!CTR_DRBG_generate(&state->drbg, out, todo, additional_data,
454
595k
                           first_call ? sizeof(additional_data) : 0)) {
455
0
      abort();
456
0
    }
457
458
595k
    out += todo;
459
595k
    out_len -= todo;
460
    // Though we only check before entering the loop, this cannot add enough to
461
    // overflow a |size_t|.
462
595k
    state->calls++;
463
595k
    first_call = 0;
464
595k
  }
465
466
595k
  if (state == &stack_state) {
467
0
    CTR_DRBG_clear(&state->drbg);
468
0
  }
469
470
#if defined(BORINGSSL_FIPS)
471
  CRYPTO_MUTEX_unlock_read(&state->clear_drbg_lock);
472
#endif
473
595k
}
474
475
552k
int RAND_bytes(uint8_t *out, size_t out_len) {
476
552k
  static const uint8_t kZeroAdditionalData[32] = {0};
477
552k
  RAND_bytes_with_additional_data(out, out_len, kZeroAdditionalData);
478
552k
  return 1;
479
552k
}
480
481
0
int RAND_pseudo_bytes(uint8_t *buf, size_t len) {
482
0
  return RAND_bytes(buf, len);
483
0
}
484
485
0
void RAND_get_system_entropy_for_custom_prng(uint8_t *buf, size_t len) {
486
0
  if (len > 256) {
487
0
    abort();
488
0
  }
489
0
  CRYPTO_sysrand_for_seed(buf, len);
490
0
}