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 <limits.h>
18#include <string.h>
19
20#include <openssl/mem.h>
21
22#include "internal.h"
23#include "../internal.h"
24
25
26/* It's assumed that the operating system always has an unfailing source of
27 * entropy which is accessed via |CRYPTO_sysrand|. (If the operating system
28 * entropy source fails, it's up to |CRYPTO_sysrand| to abort the process—we
29 * don't try to handle it.)
30 *
31 * In addition, the hardware may provide a low-latency RNG. Intel's rdrand
32 * instruction is the canonical example of this. When a hardware RNG is
33 * available we don't need to worry about an RNG failure arising from fork()ing
34 * the process or moving a VM, so we can keep thread-local RNG state and XOR
35 * the hardware entropy in.
36 *
37 * (We assume that the OS entropy is safe from fork()ing and VM duplication.
38 * This might be a bit of a leap of faith, esp on Windows, but there's nothing
39 * that we can do about it.) */
40
41/* rand_thread_state contains the per-thread state for the RNG. This is only
42 * used if the system has support for a hardware RNG. */
43struct rand_thread_state {
44  uint8_t key[32];
45  uint64_t calls_used;
46  size_t bytes_used;
47  uint8_t partial_block[64];
48  unsigned partial_block_used;
49};
50
51/* kMaxCallsPerRefresh is the maximum number of |RAND_bytes| calls that we'll
52 * serve before reading a new key from the operating system. This only applies
53 * if we have a hardware RNG. */
54static const unsigned kMaxCallsPerRefresh = 1024;
55
56/* kMaxBytesPerRefresh is the maximum number of bytes that we'll return from
57 * |RAND_bytes| before reading a new key from the operating system. This only
58 * applies if we have a hardware RNG. */
59static const uint64_t kMaxBytesPerRefresh = 1024 * 1024;
60
61/* rand_thread_state_free frees a |rand_thread_state|. This is called when a
62 * thread exits. */
63static void rand_thread_state_free(void *state) {
64  if (state == NULL) {
65    return;
66  }
67
68  OPENSSL_cleanse(state, sizeof(struct rand_thread_state));
69  OPENSSL_free(state);
70}
71
72extern void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
73                             const uint8_t key[32], const uint8_t nonce[8],
74                             size_t counter);
75
76int RAND_bytes(uint8_t *buf, size_t len) {
77  if (len == 0) {
78    return 1;
79  }
80
81  if (!CRYPTO_have_hwrand()) {
82    /* Without a hardware RNG to save us from address-space duplication, the OS
83     * entropy is used directly. */
84    CRYPTO_sysrand(buf, len);
85    return 1;
86  }
87
88  struct rand_thread_state *state =
89      CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_RAND);
90  if (state == NULL) {
91    state = OPENSSL_malloc(sizeof(struct rand_thread_state));
92    if (state == NULL ||
93        !CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_RAND, state,
94                                 rand_thread_state_free)) {
95      CRYPTO_sysrand(buf, len);
96      return 1;
97    }
98
99    memset(state->partial_block, 0, sizeof(state->partial_block));
100    state->calls_used = kMaxCallsPerRefresh;
101  }
102
103  if (state->calls_used >= kMaxCallsPerRefresh ||
104      state->bytes_used >= kMaxBytesPerRefresh) {
105    CRYPTO_sysrand(state->key, sizeof(state->key));
106    state->calls_used = 0;
107    state->bytes_used = 0;
108    state->partial_block_used = sizeof(state->partial_block);
109  }
110
111  CRYPTO_hwrand(buf, len);
112
113  if (len >= sizeof(state->partial_block)) {
114    size_t remaining = len;
115    while (remaining > 0) {
116      // kMaxBytesPerCall is only 2GB, while ChaCha can handle 256GB. But this
117      // is sufficient and easier on 32-bit.
118      static const size_t kMaxBytesPerCall = 0x80000000;
119      size_t todo = remaining;
120      if (todo > kMaxBytesPerCall) {
121        todo = kMaxBytesPerCall;
122      }
123      CRYPTO_chacha_20(buf, buf, todo, state->key,
124                       (uint8_t *)&state->calls_used, 0);
125      buf += todo;
126      remaining -= todo;
127      state->calls_used++;
128    }
129  } else {
130    if (sizeof(state->partial_block) - state->partial_block_used < len) {
131      CRYPTO_chacha_20(state->partial_block, state->partial_block,
132                       sizeof(state->partial_block), state->key,
133                       (uint8_t *)&state->calls_used, 0);
134      state->partial_block_used = 0;
135    }
136
137    unsigned i;
138    for (i = 0; i < len; i++) {
139      buf[i] ^= state->partial_block[state->partial_block_used++];
140    }
141    state->calls_used++;
142  }
143  state->bytes_used += len;
144
145  return 1;
146}
147
148int RAND_pseudo_bytes(uint8_t *buf, size_t len) {
149  return RAND_bytes(buf, len);
150}
151
152void RAND_seed(const void *buf, int num) {}
153
154int RAND_load_file(const char *path, long num) {
155  if (num < 0) {  /* read the "whole file" */
156    return 1;
157  } else if (num <= INT_MAX) {
158    return (int) num;
159  } else {
160    return INT_MAX;
161  }
162}
163
164void RAND_add(const void *buf, int num, double entropy) {}
165
166int RAND_poll(void) {
167  return 1;
168}
169
170int RAND_status(void) {
171  return 1;
172}
173