]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/libkern/arc4random.c
Remove "All Rights Reserved" from FreeBSD Foundation sys/ copyrights
[FreeBSD/FreeBSD.git] / sys / libkern / arc4random.c
1 /*-
2  * Copyright (c) 2017 The FreeBSD Foundation
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer
9  *    in this position and unchanged.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  *
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <sys/kernel.h>
33 #include <sys/libkern.h>
34 #include <sys/linker.h>
35 #include <sys/lock.h>
36 #include <sys/malloc.h>
37 #include <sys/mutex.h>
38 #include <sys/random.h>
39 #include <sys/smp.h>
40 #include <sys/time.h>
41
42 #include <machine/cpu.h>
43
44 #include <crypto/chacha20/chacha.h>
45 #include <crypto/sha2/sha256.h>
46 #include <dev/random/randomdev.h>
47 #ifdef RANDOM_FENESTRASX
48 #include <dev/random/fenestrasX/fx_pub.h>
49 #endif
50
51 #define CHACHA20_RESEED_BYTES   65536
52 #define CHACHA20_RESEED_SECONDS 300
53 #define CHACHA20_KEYBYTES       32
54 #define CHACHA20_BUFFER_SIZE    64
55
56 CTASSERT(CHACHA20_KEYBYTES*8 >= CHACHA_MINKEYLEN);
57
58 #ifndef RANDOM_FENESTRASX
59 int arc4rand_iniseed_state = ARC4_ENTR_NONE;
60 #endif
61
62 MALLOC_DEFINE(M_CHACHA20RANDOM, "chacha20random", "chacha20random structures");
63
64 struct chacha20_s {
65         struct mtx mtx;
66         int numbytes;
67         time_t t_reseed;
68         u_int8_t m_buffer[CHACHA20_BUFFER_SIZE];
69         struct chacha_ctx ctx;
70 #ifdef RANDOM_FENESTRASX
71         uint64_t seed_version;
72 #endif
73 } __aligned(CACHE_LINE_SIZE);
74
75 static struct chacha20_s *chacha20inst = NULL;
76
77 #define CHACHA20_FOREACH(_chacha20) \
78         for (_chacha20 = &chacha20inst[0]; \
79              _chacha20 <= &chacha20inst[mp_maxid]; \
80              _chacha20++)
81
82 /*
83  * Mix up the current context.
84  */
85 static void
86 chacha20_randomstir(struct chacha20_s *chacha20)
87 {
88         struct timeval tv_now;
89         u_int8_t key[CHACHA20_KEYBYTES];
90 #ifdef RANDOM_FENESTRASX
91         uint64_t seed_version;
92
93 #else
94         if (__predict_false(random_bypass_before_seeding && !is_random_seeded())) {
95                 SHA256_CTX ctx;
96                 uint64_t cc;
97                 uint32_t fver;
98
99                 if (!arc4random_bypassed_before_seeding) {
100                         arc4random_bypassed_before_seeding = true;
101                         if (!random_bypass_disable_warnings)
102                                 printf("arc4random: WARNING: initial seeding "
103                                     "bypassed the cryptographic random device "
104                                     "because it was not yet seeded and the "
105                                     "knob 'bypass_before_seeding' was "
106                                     "enabled.\n");
107                 }
108
109                 /* Last ditch effort to inject something in a bad condition. */
110                 cc = get_cyclecount();
111                 SHA256_Init(&ctx);
112                 SHA256_Update(&ctx, key, sizeof(key));
113                 SHA256_Update(&ctx, &cc, sizeof(cc));
114                 fver = __FreeBSD_version;
115                 SHA256_Update(&ctx, &fver, sizeof(fver));
116                 _Static_assert(sizeof(key) == SHA256_DIGEST_LENGTH,
117                     "make sure 256 bits is still 256 bits");
118                 SHA256_Final(key, &ctx);
119         } else {
120 #endif
121 #ifdef RANDOM_FENESTRASX
122                 read_random_key(key, CHACHA20_KEYBYTES, &seed_version);
123 #else
124                 /*
125                 * If the loader(8) did not have an entropy stash from the
126                 * previous shutdown to load, then we will block.  The answer is
127                 * to make sure there is an entropy stash at shutdown time.
128                 *
129                 * On the other hand, if the random_bypass_before_seeding knob
130                 * was set and we landed in this branch, we know this won't
131                 * block because we know the random device is seeded.
132                 */
133                 read_random(key, CHACHA20_KEYBYTES);
134         }
135 #endif
136         getmicrouptime(&tv_now);
137         mtx_lock(&chacha20->mtx);
138         chacha_keysetup(&chacha20->ctx, key, CHACHA20_KEYBYTES*8);
139         chacha_ivsetup(&chacha20->ctx, (u_char *)&tv_now.tv_sec, (u_char *)&tv_now.tv_usec);
140         /* Reset for next reseed cycle. */
141         chacha20->t_reseed = tv_now.tv_sec + CHACHA20_RESEED_SECONDS;
142         chacha20->numbytes = 0;
143 #ifdef RANDOM_FENESTRASX
144         chacha20->seed_version = seed_version;
145 #endif
146         mtx_unlock(&chacha20->mtx);
147 }
148
149 /*
150  * Initialize the contexts.
151  */
152 static void
153 chacha20_init(void)
154 {
155         struct chacha20_s *chacha20;
156
157         chacha20inst = malloc((mp_maxid + 1) * sizeof(struct chacha20_s),
158                         M_CHACHA20RANDOM, M_NOWAIT | M_ZERO);
159         KASSERT(chacha20inst != NULL, ("chacha20_init: memory allocation error"));
160
161         CHACHA20_FOREACH(chacha20) {
162                 mtx_init(&chacha20->mtx, "chacha20_mtx", NULL, MTX_DEF);
163                 chacha20->t_reseed = -1;
164                 chacha20->numbytes = 0;
165                 explicit_bzero(chacha20->m_buffer, CHACHA20_BUFFER_SIZE);
166                 explicit_bzero(&chacha20->ctx, sizeof(chacha20->ctx));
167         }
168 }
169 SYSINIT(chacha20, SI_SUB_LOCK, SI_ORDER_ANY, chacha20_init, NULL);
170
171
172 static void
173 chacha20_uninit(void)
174 {
175         struct chacha20_s *chacha20;
176
177         CHACHA20_FOREACH(chacha20)
178                 mtx_destroy(&chacha20->mtx);
179         free(chacha20inst, M_CHACHA20RANDOM);
180 }
181 SYSUNINIT(chacha20, SI_SUB_LOCK, SI_ORDER_ANY, chacha20_uninit, NULL);
182
183
184 /*
185  * MPSAFE
186  */
187 void
188 arc4rand(void *ptr, u_int len, int reseed)
189 {
190         struct chacha20_s *chacha20;
191         struct timeval tv;
192         u_int length;
193         u_int8_t *p;
194
195 #ifdef RANDOM_FENESTRASX
196         if (__predict_false(reseed))
197 #else
198         if (__predict_false(reseed ||
199             (arc4rand_iniseed_state == ARC4_ENTR_HAVE &&
200             atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_HAVE, ARC4_ENTR_SEED))))
201 #endif
202                 CHACHA20_FOREACH(chacha20)
203                         chacha20_randomstir(chacha20);
204
205         getmicrouptime(&tv);
206         chacha20 = &chacha20inst[curcpu];
207         /* We may get unlucky and be migrated off this CPU, but that is expected to be infrequent */
208         if ((chacha20->numbytes > CHACHA20_RESEED_BYTES) || (tv.tv_sec > chacha20->t_reseed))
209                 chacha20_randomstir(chacha20);
210
211         mtx_lock(&chacha20->mtx);
212 #ifdef RANDOM_FENESTRASX
213         if (__predict_false(
214             atomic_load_acq_64(&fxrng_root_generation) != chacha20->seed_version
215             )) {
216                 mtx_unlock(&chacha20->mtx);
217                 chacha20_randomstir(chacha20);
218                 mtx_lock(&chacha20->mtx);
219         }
220 #endif
221
222         p = ptr;
223         while (len) {
224                 length = MIN(CHACHA20_BUFFER_SIZE, len);
225                 chacha_encrypt_bytes(&chacha20->ctx, chacha20->m_buffer, p, length);
226                 p += length;
227                 len -= length;
228                 chacha20->numbytes += length;
229                 if (chacha20->numbytes > CHACHA20_RESEED_BYTES) {
230                         mtx_unlock(&chacha20->mtx);
231                         chacha20_randomstir(chacha20);
232                         mtx_lock(&chacha20->mtx);
233                 }
234         }
235         mtx_unlock(&chacha20->mtx);
236 }
237
238 uint32_t
239 arc4random(void)
240 {
241         uint32_t ret;
242
243         arc4rand(&ret, sizeof(ret), 0);
244         return ret;
245 }
246
247 void
248 arc4random_buf(void *ptr, size_t len)
249 {
250
251         arc4rand(ptr, len, 0);
252 }