xref: /openbsd-src/lib/libc/crypt/arc4random.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: arc4random.c,v 1.20 2008/10/03 18:46:04 otto 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 static inline u_int32_t
139 arc4_getword(void)
140 {
141 	u_int32_t val;
142 	val = arc4_getbyte() << 24;
143 	val |= arc4_getbyte() << 16;
144 	val |= arc4_getbyte() << 8;
145 	val |= arc4_getbyte();
146 	return val;
147 }
148 
149 void
150 arc4random_stir(void)
151 {
152 	_ARC4_LOCK();
153 	arc4_stir();
154 	_ARC4_UNLOCK();
155 }
156 
157 void
158 arc4random_addrandom(u_char *dat, int datlen)
159 {
160 	_ARC4_LOCK();
161 	if (!rs_initialized)
162 		arc4_stir();
163 	arc4_addrandom(dat, datlen);
164 	_ARC4_UNLOCK();
165 }
166 
167 u_int32_t
168 arc4random(void)
169 {
170 	u_int32_t val;
171 	_ARC4_LOCK();
172 	arc4_count -= 4;
173 	if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != getpid())
174 		arc4_stir();
175 	val = arc4_getword();
176 	_ARC4_UNLOCK();
177 	return val;
178 }
179 
180 void
181 arc4random_buf(void *_buf, size_t n)
182 {
183 	u_char *buf = (u_char *)_buf;
184 	_ARC4_LOCK();
185 	if (!rs_initialized || arc4_stir_pid != getpid())
186 		arc4_stir();
187 	while (n--) {
188 		if (--arc4_count <= 0)
189 			arc4_stir();
190 		buf[n] = arc4_getbyte();
191 	}
192 	_ARC4_UNLOCK();
193 }
194 
195 /*
196  * Calculate a uniformly distributed random number less than upper_bound
197  * avoiding "modulo bias".
198  *
199  * Uniformity is achieved by generating new random numbers until the one
200  * returned is outside the range [0, 2**32 % upper_bound).  This
201  * guarantees the selected random number will be inside
202  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
203  * after reduction modulo upper_bound.
204  */
205 u_int32_t
206 arc4random_uniform(u_int32_t upper_bound)
207 {
208 	u_int32_t r, min;
209 
210 	if (upper_bound < 2)
211 		return 0;
212 
213 #if (ULONG_MAX > 0xffffffffUL)
214 	min = 0x100000000UL % upper_bound;
215 #else
216 	/* Calculate (2**32 % upper_bound) avoiding 64-bit math */
217 	if (upper_bound > 0x80000000)
218 		min = 1 + ~upper_bound;		/* 2**32 - upper_bound */
219 	else {
220 		/* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
221 		min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
222 	}
223 #endif
224 
225 	/*
226 	 * This could theoretically loop forever but each retry has
227 	 * p > 0.5 (worst case, usually far better) of selecting a
228 	 * number inside the range we need, so it should rarely need
229 	 * to re-roll.
230 	 */
231 	for (;;) {
232 		r = arc4random();
233 		if (r >= min)
234 			break;
235 	}
236 
237 	return r % upper_bound;
238 }
239 
240 #if 0
241 /*-------- Test code for i386 --------*/
242 #include <stdio.h>
243 #include <machine/pctr.h>
244 int
245 main(int argc, char **argv)
246 {
247 	const int iter = 1000000;
248 	int     i;
249 	pctrval v;
250 
251 	v = rdtsc();
252 	for (i = 0; i < iter; i++)
253 		arc4random();
254 	v = rdtsc() - v;
255 	v /= iter;
256 
257 	printf("%qd cycles\n", v);
258 }
259 #endif
260