1 /* $OpenBSD: res_random.c,v 1.23 2015/10/05 02:57:16 guenther 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 static const 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 static pid_t ru_pid;
105 
106 static u_int16_t pmod(u_int16_t, u_int16_t, u_int16_t);
107 static void res_initid(void);
108 
109 /*
110  * Do a fast modular exponation, returned value will be in the range
111  * of 0 - (mod-1)
112  */
113 static u_int16_t
pmod(u_int16_t gen,u_int16_t exp,u_int16_t mod)114 pmod(u_int16_t gen, u_int16_t exp, u_int16_t mod)
115 {
116 	u_int16_t s, t, u;
117 
118 	s = 1;
119 	t = gen;
120 	u = exp;
121 
122 	while (u) {
123 		if (u & 1)
124 			s = (s * t) % mod;
125 		u >>= 1;
126 		t = (t * t) % mod;
127 	}
128 	return (s);
129 }
130 
131 /*
132  * 15-bit permutation based on Luby-Rackoff block cipher
133  */
134 static u_int
permute15(u_int in)135 permute15(u_int in)
136 {
137 	int i;
138 	u_int left, right, tmp;
139 
140 	if (ru_prf == NULL)
141 		return in;
142 
143 	left = (in >> 8) & 0x7f;
144 	right = in & 0xff;
145 
146 	/*
147 	 * Each round swaps the width of left and right. Even rounds have
148 	 * a 7-bit left, odd rounds have an 8-bit left.	Since this uses an
149 	 * odd number of rounds, left is always 8 bits wide at the end.
150 	 */
151 	for (i = 0; i < RU_ROUNDS; i++) {
152 		if ((i & 1) == 0)
153 			tmp = ru_prf->prf8[(i << (8 - 1)) | right] & 0x7f;
154 		else
155 			tmp = ru_prf->prf7[((i - 1) << (7 - 1)) | right];
156 		tmp ^= left;
157 		left = right;
158 		right = tmp;
159 	}
160 
161 	return (right << 8) | left;
162 }
163 
164 /*
165  * Initializes the seed and chooses a suitable generator. Also toggles
166  * the msb flag. The msb flag is used to generate two distinct
167  * cycles of random numbers and thus avoiding reuse of ids.
168  *
169  * This function is called from res_randomid() when needed, an
170  * application does not have to worry about it.
171  */
172 static void
res_initid(void)173 res_initid(void)
174 {
175 	u_int16_t j, i;
176 	u_int32_t tmp;
177 	int noprime = 1;
178 	struct timespec ts;
179 
180 	ru_x = arc4random_uniform(RU_M);
181 
182 	/* 15 bits of random seed */
183 	tmp = arc4random();
184 	ru_seed = (tmp >> 16) & 0x7FFF;
185 	ru_seed2 = tmp & 0x7FFF;
186 
187 	/* Determine the LCG we use */
188 	tmp = arc4random();
189 	ru_b = (tmp & 0xfffe) | 1;
190 	ru_a = pmod(RU_AGEN, (tmp >> 16) & 0xfffe, RU_M);
191 	while (ru_b % 3 == 0)
192 		ru_b += 2;
193 
194 	j = arc4random_uniform(RU_N);
195 
196 	/*
197 	 * Do a fast gcd(j,RU_N-1), so we can find a j with
198 	 * gcd(j, RU_N-1) == 1, giving a new generator for
199 	 * RU_GEN^j mod RU_N
200 	 */
201 
202 	while (noprime) {
203 		for (i = 0; i < PFAC_N; i++)
204 			if (j % pfacts[i] == 0)
205 				break;
206 
207 		if (i >= PFAC_N)
208 			noprime = 0;
209 		else
210 			j = (j + 1) % RU_N;
211 	}
212 
213 	ru_g = pmod(RU_GEN, j, RU_N);
214 	ru_counter = 0;
215 
216 	/* Initialise PRF for Luby-Rackoff permutation */
217 	if (ru_prf == NULL)
218 		ru_prf = malloc(sizeof(*ru_prf));
219 	if (ru_prf != NULL)
220 		arc4random_buf(ru_prf, sizeof(*ru_prf));
221 
222 	clock_gettime(CLOCK_MONOTONIC, &ts);
223 	ru_reseed = ts.tv_sec + RU_OUT;
224 	ru_msb = ru_msb == 0x8000 ? 0 : 0x8000;
225 }
226 
227 u_int
__res_randomid(void)228 __res_randomid(void)
229 {
230 	struct timespec ts;
231 	pid_t pid;
232 	u_int r;
233 	_THREAD_PRIVATE_MUTEX(random);
234 
235 	clock_gettime(CLOCK_MONOTONIC, &ts);
236 	pid = getpid();
237 
238 	_THREAD_PRIVATE_MUTEX_LOCK(random);
239 
240 	if (ru_counter >= RU_MAX || ts.tv_sec > ru_reseed || pid != ru_pid) {
241 		res_initid();
242 		ru_pid = pid;
243 	}
244 
245 	/* Linear Congruential Generator */
246 	ru_x = (ru_a * ru_x + ru_b) % RU_M;
247 	ru_counter++;
248 
249 	r = permute15(ru_seed ^ pmod(ru_g, ru_seed2 + ru_x, RU_N)) | ru_msb;
250 
251 	_THREAD_PRIVATE_MUTEX_UNLOCK(random);
252 
253 	return (r);
254 }
255 DEF_STRONG(__res_randomid);
256 
257 #if 0
258 int
259 main(int argc, char **argv)
260 {
261 	int i, n;
262 	u_int16_t wert;
263 
264 	res_initid();
265 
266 	printf("Generator: %u\n", ru_g);
267 	printf("Seed: %u\n", ru_seed);
268 	printf("Reseed at %ld\n", ru_reseed);
269 	printf("Ru_X: %u\n", ru_x);
270 	printf("Ru_A: %u\n", ru_a);
271 	printf("Ru_B: %u\n", ru_b);
272 
273 	n = argc > 1 ? atoi(argv[1]) : 60001;
274 	for (i=0;i<n;i++) {
275 		wert = res_randomid();
276 		printf("%u\n", wert);
277 	}
278 	return 0;
279 }
280 #endif
281 
282