• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1  /* $OpenBSD: res_random.c,v 1.17 2008/04/13 00:28:35 djm Exp $ */
2  
3  /*
4   * Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
5   * Copyright 2008 Damien Miller <djm@openbsd.org>
6   * Copyright 2008 Android Open Source Project (thread-safety)
7   * All rights reserved.
8   *
9   * Theo de Raadt <deraadt@openbsd.org> came up with the idea of using
10   * such a mathematical system to generate more random (yet non-repeating)
11   * ids to solve the resolver/named problem.  But Niels designed the
12   * actual system based on the constraints.
13   *
14   * Later modified by Damien Miller to wrap the LCG output in a 15-bit
15   * permutation generator based on a Luby-Rackoff block cipher. This
16   * ensures the output is non-repeating and preserves the MSB twiddle
17   * trick, but makes it more resistant to LCG prediction.
18   *
19   * Redistribution and use in source and binary forms, with or without
20   * modification, are permitted provided that the following conditions
21   * are met:
22   * 1. Redistributions of source code must retain the above copyright
23   *    notice, this list of conditions and the following disclaimer.
24   * 2. Redistributions in binary form must reproduce the above copyright
25   *    notice, this list of conditions and the following disclaimer in the
26   *    documentation and/or other materials provided with the distribution.
27   *
28   * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29   * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31   * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32   * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34   * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35   * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37   * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38   */
39  
40  /*
41   * seed = random 15bit
42   * n = prime, g0 = generator to n,
43   * j = random so that gcd(j,n-1) == 1
44   * g = g0^j mod n will be a generator again.
45   *
46   * X[0] = random seed.
47   * X[n] = a*X[n-1]+b mod m is a Linear Congruential Generator
48   * with a = 7^(even random) mod m,
49   *      b = random with gcd(b,m) == 1
50   *      m = 31104 and a maximal period of m-1.
51   *
52   * The transaction id is determined by:
53   * id[n] = seed xor (g^X[n] mod n)
54   *
55   * Effectivly the id is restricted to the lower 15 bits, thus
56   * yielding two different cycles by toggling the msb on and off.
57   * This avoids reuse issues caused by reseeding.
58   *
59   * The output of this generator is then randomly permuted though a
60   * custom 15 bit Luby-Rackoff block cipher.
61   */
62  
63  #include <sys/types.h>
64  #include <netinet/in.h>
65  #include <sys/time.h>
66  #include "resolv_private.h"
67  
68  #include <unistd.h>
69  #include <stdlib.h>
70  #include <string.h>
71  
72  /* BIONIC-BEGIN */
73  static pthread_mutex_t         _res_random_lock = PTHREAD_MUTEX_INITIALIZER;
74  #define  _RES_RANDOM_LOCK()    pthread_mutex_lock(&_res_random_lock)
75  #define  _RES_RANDOM_UNLOCK()  pthread_mutex_unlock(&_res_random_lock)
76  /* BIONIC-END */
77  
78  #define RU_OUT  	180	/* Time after wich will be reseeded */
79  #define RU_MAX		30000	/* Uniq cycle, avoid blackjack prediction */
80  #define RU_GEN		2	/* Starting generator */
81  #define RU_N		32749	/* RU_N-1 = 2*2*3*2729 */
82  #define RU_AGEN		7	/* determine ru_a as RU_AGEN^(2*rand) */
83  #define RU_M		31104	/* RU_M = 2^7*3^5 - don't change */
84  #define RU_ROUNDS	11	/* Number of rounds for permute (odd) */
85  
86  struct prf_ctx {
87  	/* PRF lookup table for odd rounds (7 bits input to 8 bits output) */
88  	u_char prf7[(RU_ROUNDS / 2) * (1 << 7)];
89  
90  	/* PRF lookup table for even rounds (8 bits input to 7 bits output) */
91  	u_char prf8[((RU_ROUNDS + 1) / 2) * (1 << 8)];
92  };
93  
94  #define PFAC_N 3
95  const static u_int16_t pfacts[PFAC_N] = {
96  	2,
97  	3,
98  	2729
99  };
100  
101  static u_int16_t ru_x;
102  static u_int16_t ru_seed, ru_seed2;
103  static u_int16_t ru_a, ru_b;
104  static u_int16_t ru_g;
105  static u_int16_t ru_counter = 0;
106  static u_int16_t ru_msb = 0;
107  static struct prf_ctx *ru_prf = NULL;
108  static long ru_reseed;
109  
110  static u_int16_t pmod(u_int16_t, u_int16_t, u_int16_t);
111  static void res_initid(void);
112  
113  /*
114   * Do a fast modular exponation, returned value will be in the range
115   * of 0 - (mod-1)
116   */
117  static u_int16_t
pmod(u_int16_t gen,u_int16_t exp,u_int16_t mod)118  pmod(u_int16_t gen, u_int16_t exp, u_int16_t mod)
119  {
120  	u_int16_t s, t, u;
121  
122  	s = 1;
123  	t = gen;
124  	u = exp;
125  
126  	while (u) {
127  		if (u & 1)
128  			s = (s * t) % mod;
129  		u >>= 1;
130  		t = (t * t) % mod;
131  	}
132  	return (s);
133  }
134  
135  /*
136   * 15-bit permutation based on Luby-Rackoff block cipher
137   */
138  u_int
permute15(u_int in)139  permute15(u_int in)
140  {
141  	int i;
142  	u_int left, right, tmp;
143  
144  	if (ru_prf == NULL)
145  		return in;
146  
147  	left = (in >> 8) & 0x7f;
148  	right = in & 0xff;
149  
150  	/*
151  	 * Each round swaps the width of left and right. Even rounds have
152  	 * a 7-bit left, odd rounds have an 8-bit left.	Since this uses an
153  	 * odd number of rounds, left is always 8 bits wide at the end.
154  	 */
155  	for (i = 0; i < RU_ROUNDS; i++) {
156  		if ((i & 1) == 0)
157  			tmp = ru_prf->prf8[(i << (8 - 1)) | right] & 0x7f;
158  		else
159  			tmp = ru_prf->prf7[((i - 1) << (7 - 1)) | right];
160  		tmp ^= left;
161  		left = right;
162  		right = tmp;
163  	}
164  
165  	return (right << 8) | left;
166  }
167  
168  /*
169   * Initializes the seed and chooses a suitable generator. Also toggles
170   * the msb flag. The msb flag is used to generate two distinct
171   * cycles of random numbers and thus avoiding reuse of ids.
172   *
173   * This function is called from res_randomid() when needed, an
174   * application does not have to worry about it.
175   */
176  static void
res_initid(void)177  res_initid(void)
178  {
179  	u_int16_t j, i;
180  	u_int32_t tmp;
181  	int noprime = 1;
182  	struct timeval tv;
183  
184  	ru_x = arc4random_uniform(RU_M);
185  
186  	/* 15 bits of random seed */
187  	tmp = arc4random();
188  	ru_seed = (tmp >> 16) & 0x7FFF;
189  	ru_seed2 = tmp & 0x7FFF;
190  
191  	/* Determine the LCG we use */
192  	tmp = arc4random();
193  	ru_b = (tmp & 0xfffe) | 1;
194  	ru_a = pmod(RU_AGEN, (tmp >> 16) & 0xfffe, RU_M);
195  	while (ru_b % 3 == 0)
196  		ru_b += 2;
197  
198  	j = arc4random_uniform(RU_N);
199  
200  	/*
201  	 * Do a fast gcd(j,RU_N-1), so we can find a j with
202  	 * gcd(j, RU_N-1) == 1, giving a new generator for
203  	 * RU_GEN^j mod RU_N
204  	 */
205  
206  	while (noprime) {
207  		for (i = 0; i < PFAC_N; i++)
208  			if (j % pfacts[i] == 0)
209  				break;
210  
211  		if (i >= PFAC_N)
212  			noprime = 0;
213  		else
214  			j = (j + 1) % RU_N;
215  	}
216  
217  	ru_g = pmod(RU_GEN, j, RU_N);
218  	ru_counter = 0;
219  
220  	/* Initialise PRF for Luby-Rackoff permutation */
221  	if (ru_prf == NULL)
222  		ru_prf = malloc(sizeof(*ru_prf));
223  	if (ru_prf != NULL)
224  		arc4random_buf(ru_prf, sizeof(*ru_prf));
225  
226  	gettimeofday(&tv, NULL);
227  	ru_reseed = tv.tv_sec + RU_OUT;
228  	ru_msb = ru_msb == 0x8000 ? 0 : 0x8000;
229  }
230  
231  u_int
res_randomid(void)232  res_randomid(void)
233  {
234  	struct timeval tv;
235          u_int  result;
236  
237          _RES_RANDOM_LOCK()
238  	gettimeofday(&tv, NULL);
239  	if (ru_counter >= RU_MAX || tv.tv_sec > ru_reseed)
240  		res_initid();
241  
242  	/* Linear Congruential Generator */
243  	ru_x = (ru_a * ru_x + ru_b) % RU_M;
244  	ru_counter++;
245  
246  	result = permute15(ru_seed ^ pmod(ru_g, ru_seed2 + ru_x, RU_N)) | ru_msb;
247          _RES_RANDOM_UNLOCK()
248          return result;
249  }
250  
251  #if 0
252  int
253  main(int argc, char **argv)
254  {
255  	int i, n;
256  	u_int16_t wert;
257  
258  	res_initid();
259  
260  	printf("Generator: %u\n", ru_g);
261  	printf("Seed: %u\n", ru_seed);
262  	printf("Reseed at %ld\n", ru_reseed);
263  	printf("Ru_X: %u\n", ru_x);
264  	printf("Ru_A: %u\n", ru_a);
265  	printf("Ru_B: %u\n", ru_b);
266  
267  	n = argc > 1 ? atoi(argv[1]) : 60001;
268  	for (i=0;i<n;i++) {
269  		wert = res_randomid();
270  		printf("%u\n", wert);
271  	}
272  	return 0;
273  }
274  #endif
275  
276