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