1 /* $OpenBSD: arc4random.c,v 1.21 2009/12/15 18:19:06 guenther 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_addrandom(rnd, sizeof(rnd)); 113 114 /* 115 * Discard early keystream, as per recommendations in: 116 * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps 117 */ 118 for (i = 0; i < 256; i++) 119 (void)arc4_getbyte(); 120 arc4_count = 1600000; 121 } 122 123 static void 124 arc4_stir_if_needed(void) 125 { 126 pid_t pid = getpid(); 127 128 if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid) 129 { 130 arc4_stir_pid = pid; 131 arc4_stir(); 132 } 133 } 134 135 static inline u_int8_t 136 arc4_getbyte(void) 137 { 138 u_int8_t si, sj; 139 140 rs.i = (rs.i + 1); 141 si = rs.s[rs.i]; 142 rs.j = (rs.j + si); 143 sj = rs.s[rs.j]; 144 rs.s[rs.i] = sj; 145 rs.s[rs.j] = si; 146 return (rs.s[(si + sj) & 0xff]); 147 } 148 149 static inline u_int32_t 150 arc4_getword(void) 151 { 152 u_int32_t val; 153 val = arc4_getbyte() << 24; 154 val |= arc4_getbyte() << 16; 155 val |= arc4_getbyte() << 8; 156 val |= arc4_getbyte(); 157 return val; 158 } 159 160 void 161 arc4random_stir(void) 162 { 163 _ARC4_LOCK(); 164 arc4_stir(); 165 _ARC4_UNLOCK(); 166 } 167 168 void 169 arc4random_addrandom(u_char *dat, int datlen) 170 { 171 _ARC4_LOCK(); 172 if (!rs_initialized) 173 arc4_stir(); 174 arc4_addrandom(dat, datlen); 175 _ARC4_UNLOCK(); 176 } 177 178 u_int32_t 179 arc4random(void) 180 { 181 u_int32_t val; 182 _ARC4_LOCK(); 183 arc4_count -= 4; 184 arc4_stir_if_needed(); 185 val = arc4_getword(); 186 _ARC4_UNLOCK(); 187 return val; 188 } 189 190 void 191 arc4random_buf(void *_buf, size_t n) 192 { 193 u_char *buf = (u_char *)_buf; 194 _ARC4_LOCK(); 195 arc4_stir_if_needed(); 196 while (n--) { 197 if (--arc4_count <= 0) 198 arc4_stir(); 199 buf[n] = arc4_getbyte(); 200 } 201 _ARC4_UNLOCK(); 202 } 203 204 /* 205 * Calculate a uniformly distributed random number less than upper_bound 206 * avoiding "modulo bias". 207 * 208 * Uniformity is achieved by generating new random numbers until the one 209 * returned is outside the range [0, 2**32 % upper_bound). This 210 * guarantees the selected random number will be inside 211 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound) 212 * after reduction modulo upper_bound. 213 */ 214 u_int32_t 215 arc4random_uniform(u_int32_t upper_bound) 216 { 217 u_int32_t r, min; 218 219 if (upper_bound < 2) 220 return 0; 221 222 #if (ULONG_MAX > 0xffffffffUL) 223 min = 0x100000000UL % upper_bound; 224 #else 225 /* Calculate (2**32 % upper_bound) avoiding 64-bit math */ 226 if (upper_bound > 0x80000000) 227 min = 1 + ~upper_bound; /* 2**32 - upper_bound */ 228 else { 229 /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */ 230 min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound; 231 } 232 #endif 233 234 /* 235 * This could theoretically loop forever but each retry has 236 * p > 0.5 (worst case, usually far better) of selecting a 237 * number inside the range we need, so it should rarely need 238 * to re-roll. 239 */ 240 for (;;) { 241 r = arc4random(); 242 if (r >= min) 243 break; 244 } 245 246 return r % upper_bound; 247 } 248 249 #if 0 250 /*-------- Test code for i386 --------*/ 251 #include <stdio.h> 252 #include <machine/pctr.h> 253 int 254 main(int argc, char **argv) 255 { 256 const int iter = 1000000; 257 int i; 258 pctrval v; 259 260 v = rdtsc(); 261 for (i = 0; i < iter; i++) 262 arc4random(); 263 v = rdtsc() - v; 264 v /= iter; 265 266 printf("%qd cycles\n", v); 267 } 268 #endif 269