1/*-
2 * Copyright (c) 2017 The FreeBSD Foundation
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 *
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD$");
30
31#include <sys/types.h>
32#include <sys/param.h>
33#include <sys/kernel.h>
34#include <sys/libkern.h>
35#include <sys/linker.h>
36#include <sys/lock.h>
37#include <sys/malloc.h>
38#include <sys/mutex.h>
39#include <sys/random.h>
40#include <sys/smp.h>
41#include <sys/time.h>
42
43#include <crypto/chacha20/chacha.h>
44
45#define	CHACHA20_RESEED_BYTES	65536
46#define	CHACHA20_RESEED_SECONDS	300
47#define	CHACHA20_KEYBYTES	32
48#define	CHACHA20_BUFFER_SIZE	64
49
50CTASSERT(CHACHA20_KEYBYTES*8 >= CHACHA_MINKEYLEN);
51
52int arc4rand_iniseed_state = ARC4_ENTR_NONE;
53
54MALLOC_DEFINE(M_CHACHA20RANDOM, "chacha20random", "chacha20random structures");
55
56struct chacha20_s {
57	struct mtx mtx;
58	int numbytes;
59	int first_time_done;
60	time_t t_reseed;
61	u_int8_t m_buffer[CHACHA20_BUFFER_SIZE];
62	struct chacha_ctx ctx;
63} __aligned(CACHE_LINE_SIZE);
64
65static struct chacha20_s *chacha20inst = NULL;
66
67#define CHACHA20_FOREACH(_chacha20) \
68	for (_chacha20 = &chacha20inst[0]; \
69	     _chacha20 <= &chacha20inst[mp_maxid]; \
70	     _chacha20++)
71
72/*
73 * Mix up the current context.
74 */
75static void
76chacha20_randomstir(struct chacha20_s* chacha20)
77{
78	struct timeval tv_now;
79	size_t n, size;
80	u_int8_t key[CHACHA20_KEYBYTES], *data;
81	caddr_t keyfile;
82
83	/*
84	 * This is making the best of what may be an insecure
85	 * Situation. If the loader(8) did not have an entropy
86	 * stash from the previous shutdown to load, then we will
87	 * be improperly seeded. The answer is to make sure there
88	 * is an entropy stash at shutdown time.
89	 */
90	(void)read_random(key, CHACHA20_KEYBYTES);
91	if (!chacha20->first_time_done) {
92		keyfile = preload_search_by_type(RANDOM_CACHED_BOOT_ENTROPY_MODULE);
93		if (keyfile != NULL) {
94			data = preload_fetch_addr(keyfile);
95			size = MIN(preload_fetch_size(keyfile), CHACHA20_KEYBYTES);
96			for (n = 0; n < size; n++)
97				key[n] ^= data[n];
98			explicit_bzero(data, size);
99			if (bootverbose)
100				printf("arc4random: read %zu bytes from preloaded cache\n", size);
101		} else
102			printf("arc4random: no preloaded entropy cache\n");
103		chacha20->first_time_done = 1;
104	}
105	getmicrouptime(&tv_now);
106	mtx_lock(&chacha20->mtx);
107	chacha_keysetup(&chacha20->ctx, key, CHACHA20_KEYBYTES*8);
108	chacha_ivsetup(&chacha20->ctx, (u_char *)&tv_now.tv_sec, (u_char *)&tv_now.tv_usec);
109	/* Reset for next reseed cycle. */
110	chacha20->t_reseed = tv_now.tv_sec + CHACHA20_RESEED_SECONDS;
111	chacha20->numbytes = 0;
112	mtx_unlock(&chacha20->mtx);
113}
114
115/*
116 * Initialize the contexts.
117 */
118static void
119chacha20_init(void)
120{
121	struct chacha20_s *chacha20;
122
123	chacha20inst = malloc((mp_maxid + 1) * sizeof(struct chacha20_s),
124			M_CHACHA20RANDOM, M_NOWAIT | M_ZERO);
125	KASSERT(chacha20inst != NULL, ("chacha20_init: memory allocation error"));
126
127	CHACHA20_FOREACH(chacha20) {
128		mtx_init(&chacha20->mtx, "chacha20_mtx", NULL, MTX_DEF);
129		chacha20->t_reseed = -1;
130		chacha20->numbytes = 0;
131		chacha20->first_time_done = 0;
132		explicit_bzero(chacha20->m_buffer, CHACHA20_BUFFER_SIZE);
133		explicit_bzero(&chacha20->ctx, sizeof(chacha20->ctx));
134	}
135}
136SYSINIT(chacha20, SI_SUB_LOCK, SI_ORDER_ANY, chacha20_init, NULL);
137
138
139static void
140chacha20_uninit(void)
141{
142	struct chacha20_s *chacha20;
143
144	CHACHA20_FOREACH(chacha20)
145		mtx_destroy(&chacha20->mtx);
146	free(chacha20inst, M_CHACHA20RANDOM);
147}
148SYSUNINIT(chacha20, SI_SUB_LOCK, SI_ORDER_ANY, chacha20_uninit, NULL);
149
150
151/*
152 * MPSAFE
153 */
154void
155arc4rand(void *ptr, u_int len, int reseed)
156{
157	struct chacha20_s *chacha20;
158	struct timeval tv;
159	u_int length;
160	u_int8_t *p;
161
162	if (reseed || atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_HAVE, ARC4_ENTR_SEED))
163		CHACHA20_FOREACH(chacha20)
164			chacha20_randomstir(chacha20);
165
166	chacha20 = &chacha20inst[curcpu];
167	getmicrouptime(&tv);
168	/* We may get unlucky and be migrated off this CPU, but that is expected to be infrequent */
169	if ((chacha20->numbytes > CHACHA20_RESEED_BYTES) || (tv.tv_sec > chacha20->t_reseed))
170		chacha20_randomstir(chacha20);
171
172	mtx_lock(&chacha20->mtx);
173	p = ptr;
174	while (len) {
175		length = MIN(CHACHA20_BUFFER_SIZE, len);
176		chacha_encrypt_bytes(&chacha20->ctx, chacha20->m_buffer, p, length);
177		p += length;
178		len -= length;
179		chacha20->numbytes += length;
180		if (chacha20->numbytes > CHACHA20_RESEED_BYTES) {
181			mtx_unlock(&chacha20->mtx);
182			chacha20_randomstir(chacha20);
183			mtx_lock(&chacha20->mtx);
184		}
185	}
186	mtx_unlock(&chacha20->mtx);
187}
188
189uint32_t
190arc4random(void)
191{
192	uint32_t ret;
193
194	arc4rand(&ret, sizeof(ret), 0);
195	return ret;
196}
197
198void
199arc4random_buf(void *ptr, size_t len)
200{
201
202	arc4rand(ptr, len, 0);
203}
204