Coverage Report

Created: 2026-03-19 06:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/fipsmodule/rand/rand.cc.inc
Line
Count
Source
1
// Copyright 2014 The BoringSSL Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <assert.h>
16
#include <limits.h>
17
#include <string.h>
18
19
#if defined(BORINGSSL_FIPS)
20
#include <unistd.h>
21
#endif
22
23
#include <openssl/chacha.h>
24
#include <openssl/ctrdrbg.h>
25
#include <openssl/mem.h>
26
#include <openssl/rand.h>
27
28
#include "../../bcm_support.h"
29
#include "../../mem_internal.h"
30
#include "../bcm_interface.h"
31
#include "../delocate.h"
32
#include "internal.h"
33
34
35
using namespace bssl;
36
37
// It's assumed that the operating system always has an unfailing source of
38
// entropy which is accessed via |CRYPTO_sysrand|. (If the operating system
39
// entropy source fails, it's up to |CRYPTO_sysrand| to abort the process—we
40
// don't try to handle it.)
41
//
42
// In addition, the hardware may provide a low-latency RNG. Intel's rdrand
43
// instruction is the canonical example of this. When a hardware RNG is
44
// available we don't need to worry about an RNG failure arising from fork()ing
45
// the process or moving a VM, so we can keep thread-local RNG state and use it
46
// as an additional-data input to CTR-DRBG.
47
//
48
// (We assume that the OS entropy is safe from fork()ing and VM duplication.
49
// This might be a bit of a leap of faith, esp on Windows, but there's nothing
50
// that we can do about it.)
51
52
// kReseedInterval is the number of generate calls made to CTR-DRBG before
53
// reseeding.
54
static const unsigned kReseedInterval = 4096;
55
56
// CRNGT_BLOCK_SIZE is the number of bytes in a “block” for the purposes of the
57
// continuous random number generator test in FIPS 140-2, section 4.9.2.
58
#define CRNGT_BLOCK_SIZE 16
59
60
namespace {
61
// rand_thread_state contains the per-thread state for the RNG.
62
struct rand_thread_state {
63
  CTR_DRBG_STATE drbg;
64
  uint64_t fork_generation;
65
  // calls is the number of generate calls made on |drbg| since it was last
66
  // (re)seeded. This is bound by |kReseedInterval|.
67
  unsigned calls;
68
  // last_block_valid is non-zero iff |last_block| contains data from
69
  // |get_seed_entropy|.
70
  int last_block_valid;
71
  // fork_unsafe_buffering is non-zero iff, when |drbg| was last (re)seeded,
72
  // fork-unsafe buffering was enabled.
73
  int fork_unsafe_buffering;
74
75
#if defined(BORINGSSL_FIPS)
76
  // last_block contains the previous block from |get_seed_entropy|.
77
  uint8_t last_block[CRNGT_BLOCK_SIZE];
78
  // next and prev form a nullptr-terminated, double-linked list of all states
79
  // in a process.
80
  struct rand_thread_state *next, *prev;
81
  // clear_drbg_lock synchronizes between uses of |drbg| and
82
  // |rand_thread_state_clear_all| clearing it. This lock should be uncontended
83
  // in the common case, except on shutdown.
84
  Mutex clear_drbg_lock;
85
#endif
86
};
87
}  // namespace
88
89
#if defined(BORINGSSL_FIPS)
90
// thread_states_list is the head of a linked-list of all |rand_thread_state|
91
// objects in the process, one per thread. This is needed because FIPS requires
92
// that they be zeroed on process exit, but thread-local destructors aren't
93
// called when the whole process is exiting.
94
DEFINE_BSS_GET(struct rand_thread_state *, thread_states_list, = nullptr)
95
DEFINE_STATIC_MUTEX(thread_states_list_lock)
96
97
static void rand_thread_state_clear_all() __attribute__((destructor));
98
static void rand_thread_state_clear_all() {
99
  thread_states_list_lock_bss_get()->LockWrite();
100
  for (struct rand_thread_state *cur = *thread_states_list_bss_get();
101
       cur != nullptr; cur = cur->next) {
102
    cur->clear_drbg_lock.LockWrite();
103
    CTR_DRBG_clear(&cur->drbg);
104
  }
105
  // The locks are deliberately left locked so that any threads that are still
106
  // running will hang if they try to call |BCM_rand_bytes|. It also ensures
107
  // |rand_thread_state_free| cannot free any thread state while we've taken the
108
  // lock.
109
}
110
#endif
111
112
// rand_thread_state_free frees a |rand_thread_state|. This is called when a
113
// thread exits.
114
0
static void rand_thread_state_free(void *state_in) {
115
0
  struct rand_thread_state *state =
116
0
      reinterpret_cast<rand_thread_state *>(state_in);
117
118
0
  if (state_in == nullptr) {
119
0
    return;
120
0
  }
121
122
#if defined(BORINGSSL_FIPS)
123
  thread_states_list_lock_bss_get()->LockWrite();
124
125
  if (state->prev != nullptr) {
126
    state->prev->next = state->next;
127
  } else if (*thread_states_list_bss_get() == state) {
128
    // |state->prev| may be nullptr either if it is the head of the list,
129
    // or if |state| is freed before it was added to the list at all.
130
    // Compare against the head of the list to distinguish these cases.
131
    *thread_states_list_bss_get() = state->next;
132
  }
133
134
  if (state->next != nullptr) {
135
    state->next->prev = state->prev;
136
  }
137
138
  thread_states_list_lock_bss_get()->UnlockWrite();
139
140
  CTR_DRBG_clear(&state->drbg);
141
#endif
142
143
0
  Delete(state);
144
0
}
145
146
#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \
147
    !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
148
// rdrand should only be called if either |have_rdrand| or |have_fast_rdrand|
149
// returned true.
150
static int rdrand(uint8_t *buf, const size_t len) {
151
  const size_t len_multiple8 = len & ~7;
152
  if (!CRYPTO_rdrand_multiple8_buf(buf, len_multiple8)) {
153
    return 0;
154
  }
155
  const size_t remainder = len - len_multiple8;
156
157
  if (remainder != 0) {
158
    assert(remainder < 8);
159
160
    uint8_t rand_buf[8];
161
    if (!CRYPTO_rdrand(rand_buf)) {
162
      return 0;
163
    }
164
    OPENSSL_memcpy(buf + len_multiple8, rand_buf, remainder);
165
  }
166
167
  return 1;
168
}
169
170
#else
171
172
0
static int rdrand(uint8_t *buf, size_t len) { return 0; }
173
174
#endif
175
176
0
bcm_status bssl::BCM_rand_bytes_hwrng(uint8_t *buf, const size_t len) {
177
0
  if (!have_rdrand()) {
178
0
    return bcm_status::failure;
179
0
  }
180
0
  if (rdrand(buf, len)) {
181
0
    return bcm_status::not_approved;
182
0
  }
183
0
  return bcm_status::failure;
184
0
}
185
186
#if defined(BORINGSSL_FIPS)
187
188
// In passive entropy mode, entropy is supplied from outside of the module via
189
// |BCM_rand_load_entropy| and is stored in global instance of the following
190
// structure.
191
192
struct entropy_buffer {
193
  // bytes contains entropy suitable for seeding a DRBG.
194
  uint8_t bytes[CRNGT_BLOCK_SIZE + CTR_DRBG_SEED_LEN * BORINGSSL_FIPS_OVERREAD];
195
  // bytes_valid indicates the number of bytes of |bytes| that contain valid
196
  // data.
197
  size_t bytes_valid;
198
  // want_additional_input is true if any of the contents of |bytes| were
199
  // obtained via a method other than from the kernel. In these cases entropy
200
  // from the kernel is also provided via an additional input to the DRBG.
201
  int want_additional_input;
202
};
203
204
DEFINE_BSS_GET(struct entropy_buffer, entropy_buffer, = {})
205
DEFINE_STATIC_MUTEX(entropy_buffer_lock)
206
207
bcm_infallible bssl::BCM_rand_load_entropy(const uint8_t *entropy,
208
                                           size_t entropy_len,
209
                                           int want_additional_input) {
210
  struct entropy_buffer *const buffer = entropy_buffer_bss_get();
211
212
  MutexWriteLock lock(entropy_buffer_lock_bss_get());
213
  const size_t space = sizeof(buffer->bytes) - buffer->bytes_valid;
214
  if (entropy_len > space) {
215
    entropy_len = space;
216
  }
217
218
  OPENSSL_memcpy(&buffer->bytes[buffer->bytes_valid], entropy, entropy_len);
219
  buffer->bytes_valid += entropy_len;
220
  buffer->want_additional_input |= want_additional_input && (entropy_len != 0);
221
  return bcm_infallible::not_approved;
222
}
223
224
// get_seed_entropy fills |out_entropy_len| bytes of |out_entropy| from the
225
// global |entropy_buffer|.
226
static void get_seed_entropy(uint8_t *out_entropy, size_t out_entropy_len,
227
                             int *out_want_additional_input) {
228
  struct entropy_buffer *const buffer = entropy_buffer_bss_get();
229
  if (out_entropy_len > sizeof(buffer->bytes)) {
230
    abort();
231
  }
232
233
  MutexWriteLock lock(entropy_buffer_lock_bss_get());
234
  while (buffer->bytes_valid < out_entropy_len) {
235
    MutexWriteUnlock unlock(entropy_buffer_lock_bss_get());
236
    RAND_need_entropy(out_entropy_len - buffer->bytes_valid);
237
  }
238
239
  *out_want_additional_input = buffer->want_additional_input;
240
  OPENSSL_memcpy(out_entropy, buffer->bytes, out_entropy_len);
241
  OPENSSL_memmove(buffer->bytes, &buffer->bytes[out_entropy_len],
242
                  buffer->bytes_valid - out_entropy_len);
243
  buffer->bytes_valid -= out_entropy_len;
244
  if (buffer->bytes_valid == 0) {
245
    buffer->want_additional_input = 0;
246
  }
247
}
248
249
// rand_get_seed fills |seed| with entropy. In some cases, it will additionally
250
// fill |additional_input| with entropy to supplement |seed|. It sets
251
// |*out_additional_input_len| to the number of extra bytes.
252
static void rand_get_seed(struct rand_thread_state *state,
253
                          uint8_t seed[CTR_DRBG_SEED_LEN],
254
                          uint8_t additional_input[CTR_DRBG_SEED_LEN],
255
                          size_t *out_additional_input_len) {
256
  uint8_t entropy_bytes[sizeof(state->last_block) +
257
                        CTR_DRBG_SEED_LEN * BORINGSSL_FIPS_OVERREAD];
258
  uint8_t *entropy = entropy_bytes;
259
  size_t entropy_len = sizeof(entropy_bytes);
260
261
  if (state->last_block_valid) {
262
    // No need to fill |state->last_block| with entropy from the read.
263
    entropy += sizeof(state->last_block);
264
    entropy_len -= sizeof(state->last_block);
265
  }
266
267
  int want_additional_input;
268
  get_seed_entropy(entropy, entropy_len, &want_additional_input);
269
270
  if (!state->last_block_valid) {
271
    OPENSSL_memcpy(state->last_block, entropy, sizeof(state->last_block));
272
    entropy += sizeof(state->last_block);
273
    entropy_len -= sizeof(state->last_block);
274
  }
275
276
  // See FIPS 140-2, section 4.9.2. This is the “continuous random number
277
  // generator test” which causes the program to randomly abort. Hopefully the
278
  // rate of failure is small enough not to be a problem in practice.
279
  if (CRYPTO_memcmp(state->last_block, entropy, sizeof(state->last_block)) ==
280
      0) {
281
    fprintf(CRYPTO_get_stderr(), "CRNGT failed.\n");
282
    BORINGSSL_FIPS_abort();
283
  }
284
285
  assert(entropy_len % CRNGT_BLOCK_SIZE == 0);
286
  for (size_t i = CRNGT_BLOCK_SIZE; i < entropy_len; i += CRNGT_BLOCK_SIZE) {
287
    if (CRYPTO_memcmp(entropy + i - CRNGT_BLOCK_SIZE, entropy + i,
288
                      CRNGT_BLOCK_SIZE) == 0) {
289
      fprintf(CRYPTO_get_stderr(), "CRNGT failed.\n");
290
      BORINGSSL_FIPS_abort();
291
    }
292
  }
293
  OPENSSL_memcpy(state->last_block, entropy + entropy_len - CRNGT_BLOCK_SIZE,
294
                 CRNGT_BLOCK_SIZE);
295
296
  assert(entropy_len == BORINGSSL_FIPS_OVERREAD * CTR_DRBG_SEED_LEN);
297
  OPENSSL_memcpy(seed, entropy, CTR_DRBG_SEED_LEN);
298
299
  for (size_t i = 1; i < BORINGSSL_FIPS_OVERREAD; i++) {
300
    for (size_t j = 0; j < CTR_DRBG_SEED_LEN; j++) {
301
      seed[j] ^= entropy[CTR_DRBG_SEED_LEN * i + j];
302
    }
303
  }
304
305
  // If we used something other than system entropy then also read from the
306
  // system. This avoids solely relying on the hardware.
307
  // TODO(crbug.com/446280903): Once this change sticks, switch
308
  // |get_seed_entropy| to draw from the OS instead of RDRAND.
309
  *out_additional_input_len = 0;
310
  if (want_additional_input) {
311
    CRYPTO_sysrand(additional_input, CTR_DRBG_SEED_LEN);
312
    *out_additional_input_len = CTR_DRBG_SEED_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.
321
static void rand_get_seed(struct rand_thread_state *state,
322
                          uint8_t seed[CTR_DRBG_SEED_LEN],
323
                          uint8_t additional_input[CTR_DRBG_SEED_LEN],
324
112
                          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
112
  CRYPTO_sysrand(seed, CTR_DRBG_SEED_LEN);
328
112
  *out_additional_input_len = 0;
329
112
}
330
331
#endif
332
333
bcm_infallible bssl::BCM_rand_bytes_with_additional_data(
334
441k
    uint8_t *out, size_t out_len, const uint8_t user_additional_data[32]) {
335
441k
  if (out_len == 0) {
336
267
    return bcm_infallible::approved;
337
267
  }
338
339
441k
  const uint64_t fork_generation = CRYPTO_get_fork_generation();
340
441k
  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
441k
  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
441k
  if (!have_fast_rdrand() ||
350
441k
      !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
441k
    if (fork_generation != 0 || fork_unsafe_buffering) {
356
441k
      OPENSSL_memset(additional_data, 0, sizeof(additional_data));
357
441k
    } else {
358
0
      CRYPTO_sysrand(additional_data, sizeof(additional_data));
359
0
    }
360
441k
  }
361
362
14.5M
  for (size_t i = 0; i < sizeof(additional_data); i++) {
363
14.1M
    additional_data[i] ^= user_additional_data[i];
364
14.1M
  }
365
366
441k
  struct rand_thread_state stack_state;
367
441k
  struct rand_thread_state *state = reinterpret_cast<rand_thread_state *>(
368
441k
      CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_RAND));
369
370
441k
  if (state == nullptr) {
371
8
    state = New<rand_thread_state>();
372
8
    if (state == nullptr ||
373
8
        !CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_RAND, state,
374
8
                                 rand_thread_state_free)) {
375
      // If the system is out of memory, use an ephemeral state on the
376
      // stack.
377
0
      state = &stack_state;
378
0
    }
379
380
8
    state->last_block_valid = 0;
381
8
    uint8_t seed[CTR_DRBG_SEED_LEN];
382
8
    uint8_t personalization[CTR_DRBG_SEED_LEN] = {0};
383
8
    size_t personalization_len = 0;
384
8
    rand_get_seed(state, seed, personalization, &personalization_len);
385
386
8
    if (!CTR_DRBG_init(&state->drbg, /*df=*/true, seed, 32u, seed + 32,
387
8
                       personalization, personalization_len)) {
388
0
      abort();
389
0
    }
390
8
    state->calls = 0;
391
8
    state->fork_generation = fork_generation;
392
8
    state->fork_unsafe_buffering = fork_unsafe_buffering;
393
394
#if defined(BORINGSSL_FIPS)
395
    if (state != &stack_state) {
396
      MutexWriteLock lock(thread_states_list_lock_bss_get());
397
      struct rand_thread_state **states_list = thread_states_list_bss_get();
398
      state->next = *states_list;
399
      if (state->next != nullptr) {
400
        state->next->prev = state;
401
      }
402
      state->prev = nullptr;
403
      *states_list = state;
404
    }
405
#endif
406
8
  }
407
408
441k
  if (state->calls >= kReseedInterval ||
409
      // If we've forked since |state| was last seeded, reseed.
410
440k
      state->fork_generation != fork_generation ||
411
      // If |state| was seeded from a state with different fork-safety
412
      // preferences, reseed. Suppose |state| was fork-safe, then forked into
413
      // two children, but each of the children never fork and disable fork
414
      // safety. The children must reseed to avoid working from the same PRNG
415
      // state.
416
440k
      state->fork_unsafe_buffering != fork_unsafe_buffering) {
417
104
    uint8_t seed[CTR_DRBG_SEED_LEN];
418
104
    uint8_t reseed_additional_data[CTR_DRBG_SEED_LEN] = {0};
419
104
    size_t reseed_additional_data_len = 0;
420
104
    rand_get_seed(state, seed, reseed_additional_data,
421
104
                  &reseed_additional_data_len);
422
#if defined(BORINGSSL_FIPS)
423
    // Take a read lock around accesses to |state->drbg|. This is needed to
424
    // avoid returning bad entropy if we race with
425
    // |rand_thread_state_clear_all|.
426
    state->clear_drbg_lock.LockRead();
427
#endif
428
104
    if (!CTR_DRBG_reseed_ex(&state->drbg, seed, sizeof(seed),
429
104
                            reseed_additional_data,
430
104
                            reseed_additional_data_len)) {
431
0
      abort();
432
0
    }
433
104
    state->calls = 0;
434
104
    state->fork_generation = fork_generation;
435
104
    state->fork_unsafe_buffering = fork_unsafe_buffering;
436
440k
  } else {
437
#if defined(BORINGSSL_FIPS)
438
    state->clear_drbg_lock.LockRead();
439
#endif
440
440k
  }
441
442
441k
  int first_call = 1;
443
882k
  while (out_len > 0) {
444
441k
    size_t todo = out_len;
445
441k
    if (todo > CTR_DRBG_MAX_GENERATE_LENGTH) {
446
0
      todo = CTR_DRBG_MAX_GENERATE_LENGTH;
447
0
    }
448
449
441k
    if (!CTR_DRBG_generate(&state->drbg, out, todo, additional_data,
450
441k
                           first_call ? sizeof(additional_data) : 0)) {
451
0
      abort();
452
0
    }
453
454
441k
    out += todo;
455
441k
    out_len -= todo;
456
    // Though we only check before entering the loop, this cannot add enough to
457
    // overflow a |size_t|.
458
441k
    state->calls++;
459
441k
    first_call = 0;
460
441k
  }
461
462
441k
  if (state == &stack_state) {
463
0
    CTR_DRBG_clear(&state->drbg);
464
0
  }
465
466
#if defined(BORINGSSL_FIPS)
467
  state->clear_drbg_lock.UnlockRead();
468
#endif
469
441k
  return bcm_infallible::approved;
470
441k
}
471
472
424k
bcm_infallible bssl::BCM_rand_bytes(uint8_t *out, size_t out_len) {
473
424k
  static const uint8_t kZeroAdditionalData[32] = {0};
474
424k
  BCM_rand_bytes_with_additional_data(out, out_len, kZeroAdditionalData);
475
424k
  return bcm_infallible::approved;
476
424k
}
477
478
0
int RAND_maybe_reseed() {
479
  // Currently does nothing since we don't use jitter entropy yet and so the
480
  // reseeding is quick.
481
0
  return 0;
482
0
}