]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/gen/arc4random.c
1) Use __packed attr on rdat structure to make it exact 128 bytes.
[FreeBSD/FreeBSD.git] / lib / libc / gen / arc4random.c
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, done;
110         struct {
111                 struct timeval tv;
112                 pid_t pid;
113                 u_int8_t rnd[128 - sizeof(struct timeval) - sizeof(pid_t)];
114         } __packed rdat;
115
116         fd = _open(RANDOMDEV, O_RDONLY, 0);
117         done = 0;
118         if (fd >= 0) {
119                 if (_read(fd, &rdat, sizeof(rdat)) == sizeof(rdat))
120                         done = 1;
121                 (void)_close(fd);
122         } 
123         /* !done?  Ah, what the heck. We'll just take whatever was on the
124          * stack... */
125         if (!done) {
126                 gettimeofday(&rdat.tv, NULL);
127                 rdat.pid = getpid();
128         }
129
130         arc4_addrandom((u_char *)&rdat, sizeof(rdat));
131
132         /*
133          * Throw away the first N bytes of output, as suggested in the
134          * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
135          * by Fluher, Mantin, and Shamir.  N=512 is based on
136          * suggestions in the paper "(Not So) Random Shuffles of RC4"
137          * by Ilya Mironov.
138          */
139         if (rs_initialized != 1) {
140                 for (n = 0; n < 512; n++)
141                         (void)arc4_getbyte();
142                 rs_initialized = 1;
143         }
144         arc4_count = 1600000;
145 }
146
147 static inline u_int8_t
148 arc4_getbyte(void)
149 {
150         u_int8_t si, sj;
151
152         rs.i = (rs.i + 1);
153         si = rs.s[rs.i];
154         rs.j = (rs.j + si);
155         sj = rs.s[rs.j];
156         rs.s[rs.i] = sj;
157         rs.s[rs.j] = si;
158
159         return (rs.s[(si + sj) & 0xff]);
160 }
161
162 static inline u_int32_t
163 arc4_getword(void)
164 {
165         u_int32_t val;
166
167         val = arc4_getbyte() << 24;
168         val |= arc4_getbyte() << 16;
169         val |= arc4_getbyte() << 8;
170         val |= arc4_getbyte();
171
172         return (val);
173 }
174
175 static void
176 arc4_check_init(void)
177 {
178         if (!rs_initialized) {
179                 arc4_init();
180                 rs_initialized = 2;
181         }
182 }
183
184 static inline void
185 arc4_check_stir(void)
186 {
187         if (!rs_stired || arc4_count <= 0) {
188                 arc4_stir();
189                 rs_stired = 1;
190         }
191 }
192
193 void
194 arc4random_stir(void)
195 {
196         THREAD_LOCK();
197         arc4_check_init();
198         arc4_stir();
199         rs_stired = 1;
200         THREAD_UNLOCK();
201 }
202
203 void
204 arc4random_addrandom(u_char *dat, int datlen)
205 {
206         THREAD_LOCK();
207         arc4_check_init();
208         arc4_check_stir();
209         arc4_addrandom(dat, datlen);
210         THREAD_UNLOCK();
211 }
212
213 u_int32_t
214 arc4random(void)
215 {
216         u_int32_t rnd;
217
218         THREAD_LOCK();
219         arc4_check_init();
220         arc4_check_stir();
221         rnd = arc4_getword();
222         arc4_count -= 4;
223         THREAD_UNLOCK();
224
225         return (rnd);
226 }
227
228 void
229 arc4random_buf(void *_buf, size_t n)
230 {
231         u_char *buf = (u_char *)_buf;
232
233         THREAD_LOCK();
234         arc4_check_init();
235         while (n--) {
236                 arc4_check_stir();
237                 buf[n] = arc4_getbyte();
238                 arc4_count--;
239         }
240         THREAD_UNLOCK();
241 }
242
243 #if 0
244 /*-------- Test code for i386 --------*/
245 #include <stdio.h>
246 #include <machine/pctr.h>
247 int
248 main(int argc, char **argv)
249 {
250         const int iter = 1000000;
251         int     i;
252         pctrval v;
253
254         v = rdtsc();
255         for (i = 0; i < iter; i++)
256                 arc4random();
257         v = rdtsc() - v;
258         v /= iter;
259
260         printf("%qd cycles\n", v);
261 }
262 #endif