nmsg  0.9.0
random.c
1 /*
2  * Copyright (c) 2011 by Farsight Security, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /*
18  * Copyright (c) 1996, David Mazieres <dm@uun.org>
19  * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
20  *
21  * Permission to use, copy, modify, and distribute this software for any
22  * purpose with or without fee is hereby granted, provided that the above
23  * copyright notice and this permission notice appear in all copies.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
26  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
27  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
28  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
29  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
30  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
31  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
32  */
33 
34 /*
35  * Arc4 random number generator for OpenBSD.
36  *
37  * This code is derived from section 17.1 of Applied Cryptography,
38  * second edition, which describes a stream cipher allegedly
39  * compatible with RSA Labs "RC4" cipher (the actual description of
40  * which is a trade secret). The same algorithm is used as a stream
41  * cipher called "arcfour" in Tatu Ylonen's ssh package.
42  *
43  * Here the stream cipher has been modified always to include the time
44  * when initializing the state. That makes it impossible to
45  * regenerate the same random sequence twice, so this can't be used
46  * for encryption, but will generate good random numbers.
47  *
48  * RC4 is a registered trademark of RSA Laboratories.
49  */
50 
51 /* Import. */
52 
53 #include "private.h"
54 
55 /* Macros. */
56 
57 #define RANDOMDEV "/dev/urandom"
58 #define KEYSIZE 128
59 
60 /* Data structures. */
61 
62 struct nmsg_random {
63  uint8_t i;
64  uint8_t j;
65  uint8_t s[256];
66  int arc4_count;
67 };
68 
69 /* Forward. */
70 
71 static void _nmsg_random_addrandom(nmsg_random_t, uint8_t *, size_t);
72 static void _nmsg_random_check_stir(nmsg_random_t r);
73 static void _nmsg_random_stir(nmsg_random_t);
74 static uint8_t _nmsg_random_getbyte(nmsg_random_t r);
75 static uint32_t _nmsg_random_getuint32(nmsg_random_t r);
76 
77 /* Functions. */
78 
79 nmsg_random_t
80 nmsg_random_init(void) {
81  struct nmsg_random *r;
82  int n;
83 
84  r = calloc(1, sizeof(*r));
85  if (r == NULL)
86  return (NULL);
87 
88  for (n = 0; n < 256; n++)
89  r->s[n] = n;
90  r->i = 0;
91  r->j = 0;
92 
93  _nmsg_random_stir(r);
94 
95  return (r);
96 }
97 
98 void
99 nmsg_random_destroy(nmsg_random_t *r) {
100  free(*r);
101  *r = NULL;
102 }
103 
104 static void
105 _nmsg_random_addrandom(nmsg_random_t r, uint8_t *dat, size_t datlen) {
106  int n;
107  uint8_t si;
108 
109  r->i--;
110  for (n = 0; n < 256; n++) {
111  r->i = (r->i + 1);
112  si = r->s[r->i];
113  r->j = (r->j + si + dat[n % datlen]);
114  r->s[r->i] = r->s[r->j];
115  r->s[r->j] = si;
116  }
117  r->j = r->i;
118 }
119 
120 static void
121 _nmsg_random_check_stir(nmsg_random_t r) {
122  if (r->arc4_count <= 0)
123  _nmsg_random_stir(r);
124 }
125 
126 static void
127 _nmsg_random_stir(nmsg_random_t r) {
128  int done, fd, n;
129  struct {
130  struct timeval tv;
131  pid_t pid;
132  uint8_t rnd[KEYSIZE];
133  } rdat;
134 
135  fd = open(RANDOMDEV, O_RDONLY, 0);
136  done = 0;
137  if (fd >= 0) {
138  if (read(fd, &rdat.rnd, KEYSIZE) == KEYSIZE)
139  done = 1;
140  (void)close(fd);
141  _nmsg_random_addrandom(r, rdat.rnd, sizeof(rdat.rnd));
142  }
143  if (!done) {
144  (void)gettimeofday(&rdat.tv, NULL);
145  rdat.pid = getpid();
146  /* We'll just take whatever was on the stack too... */
147  _nmsg_random_addrandom(r, (uint8_t *)&rdat, sizeof(rdat));
148  }
149 
150  /*
151  * Throw away the first N bytes of output, as suggested in the
152  * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
153  * by Fluher, Mantin, and Shamir. N=1024 is based on
154  * suggestions in the paper "(Not So) Random Shuffles of RC4"
155  * by Ilya Mironov.
156  */
157  for (n = 0; n < 1024; n++)
158  (void)_nmsg_random_getbyte(r);
159  r->arc4_count = 1600000;
160 }
161 
162 static uint8_t
163 _nmsg_random_getbyte(nmsg_random_t r) {
164  uint8_t si, sj;
165 
166  r->i = (r->i + 1);
167  si = r->s[r->i];
168  r->j = (r->j + si);
169  sj = r->s[r->j];
170  r->s[r->i] = sj;
171  r->s[r->j] = si;
172 
173  return (r->s[(si + sj) & 0xff]);
174 }
175 
176 static uint32_t
177 _nmsg_random_getuint32(nmsg_random_t r) {
178  uint32_t val;
179 
180  val = _nmsg_random_getbyte(r) << 24;
181  val |= _nmsg_random_getbyte(r) << 16;
182  val |= _nmsg_random_getbyte(r) << 8;
183  val |= _nmsg_random_getbyte(r);
184 
185  return (val);
186 }
187 
188 uint32_t
189 nmsg_random_uint32(nmsg_random_t r) {
190  uint32_t rnd;
191 
192  _nmsg_random_check_stir(r);
193  rnd = _nmsg_random_getuint32(r);
194  r->arc4_count -= 4;
195 
196  return (rnd);
197 }
198 
199 void
200 nmsg_random_buf(nmsg_random_t r, uint8_t *buf, size_t n) {
201  while (n--) {
202  _nmsg_random_check_stir(r);
203  buf[n] = _nmsg_random_getbyte(r);
204  r->arc4_count--;
205  }
206 }
207 
208 /*
209  * Calculate a uniformly distributed random number less than upper_bound
210  * avoiding "modulo bias".
211  *
212  * Uniformity is achieved by generating new random numbers until the one
213  * returned is outside the range [0, 2**32 % upper_bound). This
214  * guarantees the selected random number will be inside
215  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
216  * after reduction modulo upper_bound.
217  */
218 uint32_t
219 nmsg_random_uniform(nmsg_random_t r, uint32_t upper_bound) {
220  uint32_t rnd, min;
221 
222  if (upper_bound < 2)
223  return (0);
224 
225 #if (ULONG_MAX > 0xffffffffUL)
226  min = 0x100000000UL % upper_bound;
227 #else
228  /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
229  if (upper_bound > 0x80000000)
230  min = 1 + ~upper_bound; /* 2**32 - upper_bound */
231  else {
232  /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
233  min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
234  }
235 #endif
236 
237  /*
238  * This could theoretically loop forever but each retry has
239  * p > 0.5 (worst case, usually far better) of selecting a
240  * number inside the range we need, so it should rarely need
241  * to re-roll.
242  */
243  for (;;) {
244  rnd = nmsg_random_uint32(r);
245  if (rnd >= min)
246  break;
247  }
248 
249  return (rnd % upper_bound);
250 }