]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/gen/arc4random.c
MFV r306669:
[FreeBSD/FreeBSD.git] / lib / libc / gen / arc4random.c
1 /*      $OpenBSD: arc4random.c,v 1.24 2013/06/11 16:59:50 deraadt 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  * RC4 is a registered trademark of RSA Laboratories.
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include "namespace.h"
36 #include <fcntl.h>
37 #include <limits.h>
38 #include <stdlib.h>
39 #include <unistd.h>
40 #include <sys/param.h>
41 #include <sys/sysctl.h>
42 #include <sys/time.h>
43 #include <pthread.h>
44
45 #include "libc_private.h"
46 #include "un-namespace.h"
47
48 #ifdef __GNUC__
49 #define inline __inline
50 #else                           /* !__GNUC__ */
51 #define inline
52 #endif                          /* !__GNUC__ */
53
54 struct arc4_stream {
55         u_int8_t i;
56         u_int8_t j;
57         u_int8_t s[256];
58 };
59
60 static pthread_mutex_t  arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
61
62 #define RANDOMDEV       "/dev/random"
63 #define KEYSIZE         128
64 #define _ARC4_LOCK()                                            \
65         do {                                                    \
66                 if (__isthreaded)                               \
67                         _pthread_mutex_lock(&arc4random_mtx);   \
68         } while (0)
69
70 #define _ARC4_UNLOCK()                                          \
71         do {                                                    \
72                 if (__isthreaded)                               \
73                         _pthread_mutex_unlock(&arc4random_mtx); \
74         } while (0)
75
76 static int rs_initialized;
77 static struct arc4_stream rs;
78 static pid_t arc4_stir_pid;
79 static int arc4_count;
80
81 extern int __sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp,
82     void *newp, size_t newlen);
83
84 static inline u_int8_t arc4_getbyte(void);
85 static void arc4_stir(void);
86
87 static inline void
88 arc4_init(void)
89 {
90         int     n;
91
92         for (n = 0; n < 256; n++)
93                 rs.s[n] = n;
94         rs.i = 0;
95         rs.j = 0;
96 }
97
98 static inline void
99 arc4_addrandom(u_char *dat, int datlen)
100 {
101         int     n;
102         u_int8_t si;
103
104         rs.i--;
105         for (n = 0; n < 256; n++) {
106                 rs.i = (rs.i + 1);
107                 si = rs.s[rs.i];
108                 rs.j = (rs.j + si + dat[n % datlen]);
109                 rs.s[rs.i] = rs.s[rs.j];
110                 rs.s[rs.j] = si;
111         }
112         rs.j = rs.i;
113 }
114
115 static size_t
116 arc4_sysctl(u_char *buf, size_t size)
117 {
118         int mib[2];
119         size_t len, done;
120
121         mib[0] = CTL_KERN;
122         mib[1] = KERN_ARND;
123         done = 0;
124
125         do {
126                 len = size;
127                 if (__sysctl(mib, 2, buf, &len, NULL, 0) == -1)
128                         return (done);
129                 done += len;
130                 buf += len;
131                 size -= len;
132         } while (size > 0);
133
134         return (done);
135 }
136
137 static void
138 arc4_stir(void)
139 {
140         u_char rdat[KEYSIZE];
141         int i;
142
143         if (!rs_initialized) {
144                 arc4_init();
145                 rs_initialized = 1;
146         }
147         if (arc4_sysctl(rdat, KEYSIZE) != KEYSIZE)
148                 abort(); /* Random sysctl cannot fail. */
149
150         arc4_addrandom(rdat, KEYSIZE);
151
152         /*
153          * Discard early keystream, as per recommendations in:
154          * "(Not So) Random Shuffles of RC4" by Ilya Mironov.
155          */
156         for (i = 0; i < 1024; i++)
157                 (void)arc4_getbyte();
158         arc4_count = 1600000;
159 }
160
161 static void
162 arc4_stir_if_needed(void)
163 {
164         pid_t pid = getpid();
165
166         if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid) {
167                 arc4_stir_pid = pid;
168                 arc4_stir();
169         }
170 }
171
172 static inline u_int8_t
173 arc4_getbyte(void)
174 {
175         u_int8_t si, sj;
176
177         rs.i = (rs.i + 1);
178         si = rs.s[rs.i];
179         rs.j = (rs.j + si);
180         sj = rs.s[rs.j];
181         rs.s[rs.i] = sj;
182         rs.s[rs.j] = si;
183         return (rs.s[(si + sj) & 0xff]);
184 }
185
186 static inline u_int32_t
187 arc4_getword(void)
188 {
189         u_int32_t val;
190         val = arc4_getbyte() << 24;
191         val |= arc4_getbyte() << 16;
192         val |= arc4_getbyte() << 8;
193         val |= arc4_getbyte();
194         return val;
195 }
196
197 void
198 arc4random_stir(void)
199 {
200         _ARC4_LOCK();
201         arc4_stir();
202         _ARC4_UNLOCK();
203 }
204
205 void
206 arc4random_addrandom(u_char *dat, int datlen)
207 {
208         _ARC4_LOCK();
209         if (!rs_initialized)
210                 arc4_stir();
211         arc4_addrandom(dat, datlen);
212         _ARC4_UNLOCK();
213 }
214
215 u_int32_t
216 arc4random(void)
217 {
218         u_int32_t val;
219         _ARC4_LOCK();
220         arc4_count -= 4;
221         arc4_stir_if_needed();
222         val = arc4_getword();
223         _ARC4_UNLOCK();
224         return val;
225 }
226
227 void
228 arc4random_buf(void *_buf, size_t n)
229 {
230         u_char *buf = (u_char *)_buf;
231         _ARC4_LOCK();
232         arc4_stir_if_needed();
233         while (n--) {
234                 if (--arc4_count <= 0)
235                         arc4_stir();
236                 buf[n] = arc4_getbyte();
237         }
238         _ARC4_UNLOCK();
239 }
240
241 /*
242  * Calculate a uniformly distributed random number less than upper_bound
243  * avoiding "modulo bias".
244  *
245  * Uniformity is achieved by generating new random numbers until the one
246  * returned is outside the range [0, 2**32 % upper_bound).  This
247  * guarantees the selected random number will be inside
248  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
249  * after reduction modulo upper_bound.
250  */
251 u_int32_t
252 arc4random_uniform(u_int32_t upper_bound)
253 {
254         u_int32_t r, min;
255
256         if (upper_bound < 2)
257                 return 0;
258
259         /* 2**32 % x == (2**32 - x) % x */
260         min = -upper_bound % upper_bound;
261         /*
262          * This could theoretically loop forever but each retry has
263          * p > 0.5 (worst case, usually far better) of selecting a
264          * number inside the range we need, so it should rarely need
265          * to re-roll.
266          */
267         for (;;) {
268                 r = arc4random();
269                 if (r >= min)
270                         break;
271         }
272
273         return r % upper_bound;
274 }
275
276 #if 0
277 /*-------- Test code for i386 --------*/
278 #include <stdio.h>
279 #include <machine/pctr.h>
280 int
281 main(int argc, char **argv)
282 {
283         const int iter = 1000000;
284         int     i;
285         pctrval v;
286
287         v = rdtsc();
288         for (i = 0; i < iter; i++)
289                 arc4random();
290         v = rdtsc() - v;
291         v /= iter;
292
293         printf("%qd cycles\n", v);
294 }
295 #endif