arc4random.c revision 181261
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: head/lib/libc/gen/arc4random.c 181261 2008-08-03 20:15:22Z ache $"); 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 49struct arc4_stream { 50 u_int8_t i; 51 u_int8_t j; 52 u_int8_t s[256]; 53}; 54 55static pthread_mutex_t arc4random_mtx = PTHREAD_MUTEX_INITIALIZER; 56 57#define RANDOMDEV "/dev/urandom" 58#define KEYSIZE 128 59#define THREAD_LOCK() \ 60 do { \ 61 if (__isthreaded) \ 62 _pthread_mutex_lock(&arc4random_mtx); \ 63 } while (0) 64 65#define THREAD_UNLOCK() \ 66 do { \ 67 if (__isthreaded) \ 68 _pthread_mutex_unlock(&arc4random_mtx); \ 69 } while (0) 70 71static struct arc4_stream rs; 72static int rs_initialized; 73static int rs_stired; 74static int arc4_count; 75 76static inline u_int8_t arc4_getbyte(void); 77static void arc4_stir(void); 78 79static inline void 80arc4_init(void) 81{ 82 int n; 83 84 for (n = 0; n < 256; n++) 85 rs.s[n] = n; 86 rs.i = 0; 87 rs.j = 0; 88} 89 90static inline void 91arc4_addrandom(u_char *dat, int datlen) 92{ 93 int n; 94 u_int8_t si; 95 96 rs.i--; 97 for (n = 0; n < 256; n++) { 98 rs.i = (rs.i + 1); 99 si = rs.s[rs.i]; 100 rs.j = (rs.j + si + dat[n % datlen]); 101 rs.s[rs.i] = rs.s[rs.j]; 102 rs.s[rs.j] = si; 103 } 104 rs.j = rs.i; 105} 106 107static void 108arc4_stir(void) 109{ 110 int done, fd, n; 111 struct { 112 struct timeval tv; 113 pid_t pid; 114 u_int8_t rnd[KEYSIZE]; 115 } rdat; 116 117 fd = _open(RANDOMDEV, O_RDONLY, 0); 118 done = 0; 119 if (fd >= 0) { 120 if (_read(fd, &rdat, KEYSIZE) == KEYSIZE) 121 done = 1; 122 (void)_close(fd); 123 } 124 if (!done) { 125 (void)gettimeofday(&rdat.tv, NULL); 126 rdat.pid = getpid(); 127 /* We'll just take whatever was on the stack too... */ 128 } 129 130 arc4_addrandom((u_char *)&rdat, KEYSIZE); 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=1024 is based on 136 * suggestions in the paper "(Not So) Random Shuffles of RC4" 137 * by Ilya Mironov. 138 */ 139 for (n = 0; n < 1024; n++) 140 (void) arc4_getbyte(); 141 arc4_count = 1600000; 142} 143 144static inline u_int8_t 145arc4_getbyte(void) 146{ 147 u_int8_t si, sj; 148 149 rs.i = (rs.i + 1); 150 si = rs.s[rs.i]; 151 rs.j = (rs.j + si); 152 sj = rs.s[rs.j]; 153 rs.s[rs.i] = sj; 154 rs.s[rs.j] = si; 155 156 return (rs.s[(si + sj) & 0xff]); 157} 158 159static inline u_int32_t 160arc4_getword(void) 161{ 162 u_int32_t val; 163 164 val = arc4_getbyte() << 24; 165 val |= arc4_getbyte() << 16; 166 val |= arc4_getbyte() << 8; 167 val |= arc4_getbyte(); 168 169 return (val); 170} 171 172static void 173arc4_check_init(void) 174{ 175 if (!rs_initialized) { 176 arc4_init(); 177 rs_initialized = 1; 178 } 179} 180 181static inline void 182arc4_check_stir(void) 183{ 184 if (!rs_stired || arc4_count <= 0) { 185 arc4_stir(); 186 rs_stired = 1; 187 } 188} 189 190void 191arc4random_stir(void) 192{ 193 THREAD_LOCK(); 194 arc4_check_init(); 195 arc4_stir(); 196 THREAD_UNLOCK(); 197} 198 199void 200arc4random_addrandom(u_char *dat, int datlen) 201{ 202 THREAD_LOCK(); 203 arc4_check_init(); 204 arc4_check_stir(); 205 arc4_addrandom(dat, datlen); 206 THREAD_UNLOCK(); 207} 208 209u_int32_t 210arc4random(void) 211{ 212 u_int32_t rnd; 213 214 THREAD_LOCK(); 215 arc4_check_init(); 216 arc4_check_stir(); 217 rnd = arc4_getword(); 218 arc4_count -= 4; 219 THREAD_UNLOCK(); 220 221 return (rnd); 222} 223 224void 225arc4random_buf(void *_buf, size_t n) 226{ 227 u_char *buf = (u_char *)_buf; 228 229 THREAD_LOCK(); 230 arc4_check_init(); 231 while (n--) { 232 arc4_check_stir(); 233 buf[n] = arc4_getbyte(); 234 arc4_count--; 235 } 236 THREAD_UNLOCK(); 237} 238 239/* 240 * Calculate a uniformly distributed random number less than upper_bound 241 * avoiding "modulo bias". 242 * 243 * Uniformity is achieved by generating new random numbers until the one 244 * returned is outside the range [0, 2**32 % upper_bound). This 245 * guarantees the selected random number will be inside 246 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound) 247 * after reduction modulo upper_bound. 248 */ 249u_int32_t 250arc4random_uniform(u_int32_t upper_bound) 251{ 252 u_int32_t r, min; 253 254 if (upper_bound < 2) 255 return (0); 256 257#if (ULONG_MAX > 0xffffffffUL) 258 min = 0x100000000UL % upper_bound; 259#else 260 /* Calculate (2**32 % upper_bound) avoiding 64-bit math */ 261 if (upper_bound > 0x80000000) 262 min = 1 + ~upper_bound; /* 2**32 - upper_bound */ 263 else { 264 /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */ 265 min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound; 266 } 267#endif 268 269 /* 270 * This could theoretically loop forever but each retry has 271 * p > 0.5 (worst case, usually far better) of selecting a 272 * number inside the range we need, so it should rarely need 273 * to re-roll. 274 */ 275 for (;;) { 276 r = arc4random(); 277 if (r >= min) 278 break; 279 } 280 281 return (r % upper_bound); 282} 283 284#if 0 285/*-------- Test code for i386 --------*/ 286#include <stdio.h> 287#include <machine/pctr.h> 288int 289main(int argc, char **argv) 290{ 291 const int iter = 1000000; 292 int i; 293 pctrval v; 294 295 v = rdtsc(); 296 for (i = 0; i < iter; i++) 297 arc4random(); 298 v = rdtsc() - v; 299 v /= iter; 300 301 printf("%qd cycles\n", v); 302} 303#endif 304