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