xref: /freebsd/lib/libc/gen/arc4random.c (revision f7c4bd95ba735bd6a5454b4953945a99cefbb80c)
1 /*
2  * Copyright (c) 1996, David Mazieres <dm@uun.org>
3  * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 /*
19  * Arc4 random number generator for OpenBSD.
20  *
21  * This code is derived from section 17.1 of Applied Cryptography,
22  * second edition, which describes a stream cipher allegedly
23  * compatible with RSA Labs "RC4" cipher (the actual description of
24  * which is a trade secret).  The same algorithm is used as a stream
25  * cipher called "arcfour" in Tatu Ylonen's ssh package.
26  *
27  * Here the stream cipher has been modified always to include the time
28  * when initializing the state.  That makes it impossible to
29  * regenerate the same random sequence twice, so this can't be used
30  * for encryption, but will generate good random numbers.
31  *
32  * RC4 is a registered trademark of RSA Laboratories.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "namespace.h"
39 #include <sys/types.h>
40 #include <sys/time.h>
41 #include <stdlib.h>
42 #include <fcntl.h>
43 #include <unistd.h>
44 #include <pthread.h>
45 
46 #include "libc_private.h"
47 #include "un-namespace.h"
48 
49 struct arc4_stream {
50 	u_int8_t i;
51 	u_int8_t j;
52 	u_int8_t s[256];
53 };
54 
55 static pthread_mutex_t	arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
56 
57 #define	RANDOMDEV	"/dev/urandom"
58 #define	THREAD_LOCK()						\
59 	do {							\
60 		if (__isthreaded)				\
61 			_pthread_mutex_lock(&arc4random_mtx);	\
62 	} while (0)
63 
64 #define	THREAD_UNLOCK()						\
65 	do {							\
66 		if (__isthreaded)				\
67 			_pthread_mutex_unlock(&arc4random_mtx);	\
68 	} while (0)
69 
70 static struct arc4_stream rs;
71 static int rs_initialized;
72 static int rs_stired;
73 static int arc4_count;
74 
75 static inline u_int8_t arc4_getbyte(void);
76 static void arc4_stir(void);
77 
78 static inline void
79 arc4_init(void)
80 {
81 	int     n;
82 
83 	for (n = 0; n < 256; n++)
84 		rs.s[n] = n;
85 	rs.i = 0;
86 	rs.j = 0;
87 }
88 
89 static inline void
90 arc4_addrandom(u_char *dat, int datlen)
91 {
92 	int     n;
93 	u_int8_t si;
94 
95 	rs.i--;
96 	for (n = 0; n < 256; n++) {
97 		rs.i = (rs.i + 1);
98 		si = rs.s[rs.i];
99 		rs.j = (rs.j + si + dat[n % datlen]);
100 		rs.s[rs.i] = rs.s[rs.j];
101 		rs.s[rs.j] = si;
102 	}
103 	rs.j = rs.i;
104 }
105 
106 static void
107 arc4_stir(void)
108 {
109 	int     fd, n;
110 	struct {
111 		struct timeval tv;
112 		pid_t pid;
113 		u_int8_t rnd[128 - sizeof(struct timeval) - sizeof(pid_t)];
114 	}       rdat;
115 
116 	gettimeofday(&rdat.tv, NULL);
117 	rdat.pid = getpid();
118 	fd = _open(RANDOMDEV, O_RDONLY, 0);
119 	if (fd >= 0) {
120 		(void) _read(fd, rdat.rnd, sizeof(rdat.rnd));
121 		_close(fd);
122 	}
123 	/* fd < 0?  Ah, what the heck. We'll just take whatever was on the
124 	 * stack... */
125 
126 	arc4_addrandom((void *) &rdat, sizeof(rdat));
127 
128 	/*
129 	 * Throw away the first N bytes of output, as suggested in the
130 	 * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
131 	 * by Fluher, Mantin, and Shamir.  N=1024 is based on
132 	 * suggestions in the paper "(Not So) Random Shuffles of RC4"
133 	 * by Ilya Mironov.
134 	 */
135 	for (n = 0; n < 1024; n++)
136 		(void) arc4_getbyte();
137 	arc4_count = 1600000;
138 }
139 
140 static inline u_int8_t
141 arc4_getbyte(void)
142 {
143 	u_int8_t si, sj;
144 
145 	rs.i = (rs.i + 1);
146 	si = rs.s[rs.i];
147 	rs.j = (rs.j + si);
148 	sj = rs.s[rs.j];
149 	rs.s[rs.i] = sj;
150 	rs.s[rs.j] = si;
151 
152 	return (rs.s[(si + sj) & 0xff]);
153 }
154 
155 static inline u_int32_t
156 arc4_getword(void)
157 {
158 	u_int32_t val;
159 
160 	val = arc4_getbyte() << 24;
161 	val |= arc4_getbyte() << 16;
162 	val |= arc4_getbyte() << 8;
163 	val |= arc4_getbyte();
164 
165 	return (val);
166 }
167 
168 static void
169 arc4_check_init(void)
170 {
171 	if (!rs_initialized) {
172 		arc4_init();
173 		rs_initialized = 1;
174 	}
175 }
176 
177 static inline void
178 arc4_check_stir(void)
179 {
180 	if (!rs_stired || arc4_count <= 0) {
181 		arc4_stir();
182 		rs_stired = 1;
183 	}
184 }
185 
186 void
187 arc4random_stir(void)
188 {
189 	THREAD_LOCK();
190 	arc4_check_init();
191 	arc4_stir();
192 	THREAD_UNLOCK();
193 }
194 
195 void
196 arc4random_addrandom(u_char *dat, int datlen)
197 {
198 	THREAD_LOCK();
199 	arc4_check_init();
200 	arc4_check_stir();
201 	arc4_addrandom(dat, datlen);
202 	THREAD_UNLOCK();
203 }
204 
205 u_int32_t
206 arc4random(void)
207 {
208 	u_int32_t rnd;
209 
210 	THREAD_LOCK();
211 	arc4_check_init();
212 	arc4_check_stir();
213 	rnd = arc4_getword();
214 	arc4_count -= 4;
215 	THREAD_UNLOCK();
216 
217 	return (rnd);
218 }
219 
220 void
221 arc4random_buf(void *_buf, size_t n)
222 {
223 	u_char *buf = (u_char *)_buf;
224 
225 	THREAD_LOCK();
226 	arc4_check_init();
227 	while (n--) {
228 		arc4_check_stir();
229 		buf[n] = arc4_getbyte();
230 		arc4_count--;
231 	}
232 	THREAD_UNLOCK();
233 }
234 
235 /*
236  * Calculate a uniformly distributed random number less than upper_bound
237  * avoiding "modulo bias".
238  *
239  * Uniformity is achieved by generating new random numbers until the one
240  * returned is outside the range [0, 2**32 % upper_bound).  This
241  * guarantees the selected random number will be inside
242  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
243  * after reduction modulo upper_bound.
244  */
245 u_int32_t
246 arc4random_uniform(u_int32_t upper_bound)
247 {
248 	u_int32_t r, min;
249 
250 	if (upper_bound < 2)
251 		return (0);
252 
253 #if (ULONG_MAX > 0xffffffffUL)
254 	min = 0x100000000UL % upper_bound;
255 #else
256 	/* Calculate (2**32 % upper_bound) avoiding 64-bit math */
257 	if (upper_bound > 0x80000000)
258 		min = 1 + ~upper_bound;		/* 2**32 - upper_bound */
259 	else {
260 		/* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
261 		min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
262 	}
263 #endif
264 
265 	/*
266 	 * This could theoretically loop forever but each retry has
267 	 * p > 0.5 (worst case, usually far better) of selecting a
268 	 * number inside the range we need, so it should rarely need
269 	 * to re-roll.
270 	 */
271 	for (;;) {
272 		r = arc4random();
273 		if (r >= min)
274 			break;
275 	}
276 
277 	return (r % upper_bound);
278 }
279 
280 #if 0
281 /*-------- Test code for i386 --------*/
282 #include <stdio.h>
283 #include <machine/pctr.h>
284 int
285 main(int argc, char **argv)
286 {
287 	const int iter = 1000000;
288 	int     i;
289 	pctrval v;
290 
291 	v = rdtsc();
292 	for (i = 0; i < iter; i++)
293 		arc4random();
294 	v = rdtsc() - v;
295 	v /= iter;
296 
297 	printf("%qd cycles\n", v);
298 }
299 #endif
300