xref: /openbsd-src/lib/libc/net/res_random.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
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  * 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 #define RU_OUT  	180	/* Time after wich will be reseeded */
72 #define RU_MAX		30000	/* Uniq cycle, avoid blackjack prediction */
73 #define RU_GEN		2	/* Starting generator */
74 #define RU_N		32749	/* RU_N-1 = 2*2*3*2729 */
75 #define RU_AGEN		7	/* determine ru_a as RU_AGEN^(2*rand) */
76 #define RU_M		31104	/* RU_M = 2^7*3^5 - don't change */
77 #define RU_ROUNDS	11	/* Number of rounds for permute (odd) */
78 
79 struct prf_ctx {
80 	/* PRF lookup table for odd rounds (7 bits input to 8 bits output) */
81 	u_char prf7[(RU_ROUNDS / 2) * (1 << 7)];
82 
83 	/* PRF lookup table for even rounds (8 bits input to 7 bits output) */
84 	u_char prf8[((RU_ROUNDS + 1) / 2) * (1 << 8)];
85 };
86 
87 #define PFAC_N 3
88 const static u_int16_t pfacts[PFAC_N] = {
89 	2,
90 	3,
91 	2729
92 };
93 
94 static u_int16_t ru_x;
95 static u_int16_t ru_seed, ru_seed2;
96 static u_int16_t ru_a, ru_b;
97 static u_int16_t ru_g;
98 static u_int16_t ru_counter = 0;
99 static u_int16_t ru_msb = 0;
100 static struct prf_ctx *ru_prf = NULL;
101 static long ru_reseed;
102 
103 static u_int16_t pmod(u_int16_t, u_int16_t, u_int16_t);
104 static void res_initid(void);
105 
106 /*
107  * Do a fast modular exponation, returned value will be in the range
108  * of 0 - (mod-1)
109  */
110 static u_int16_t
111 pmod(u_int16_t gen, u_int16_t exp, u_int16_t mod)
112 {
113 	u_int16_t s, t, u;
114 
115 	s = 1;
116 	t = gen;
117 	u = exp;
118 
119 	while (u) {
120 		if (u & 1)
121 			s = (s * t) % mod;
122 		u >>= 1;
123 		t = (t * t) % mod;
124 	}
125 	return (s);
126 }
127 
128 /*
129  * 15-bit permutation based on Luby-Rackoff block cipher
130  */
131 u_int
132 permute15(u_int in)
133 {
134 	int i;
135 	u_int left, right, tmp;
136 
137 	if (ru_prf == NULL)
138 		return in;
139 
140 	left = (in >> 8) & 0x7f;
141 	right = in & 0xff;
142 
143 	/*
144 	 * Each round swaps the width of left and right. Even rounds have
145 	 * a 7-bit left, odd rounds have an 8-bit left.	Since this uses an
146 	 * odd number of rounds, left is always 8 bits wide at the end.
147 	 */
148 	for (i = 0; i < RU_ROUNDS; i++) {
149 		if ((i & 1) == 0)
150 			tmp = ru_prf->prf8[(i << (8 - 1)) | right] & 0x7f;
151 		else
152 			tmp = ru_prf->prf7[((i - 1) << (7 - 1)) | right];
153 		tmp ^= left;
154 		left = right;
155 		right = tmp;
156 	}
157 
158 	return (right << 8) | left;
159 }
160 
161 /*
162  * Initializes the seed and chooses a suitable generator. Also toggles
163  * the msb flag. The msb flag is used to generate two distinct
164  * cycles of random numbers and thus avoiding reuse of ids.
165  *
166  * This function is called from res_randomid() when needed, an
167  * application does not have to worry about it.
168  */
169 static void
170 res_initid(void)
171 {
172 	u_int16_t j, i;
173 	u_int32_t tmp;
174 	int noprime = 1;
175 	struct timeval tv;
176 
177 	ru_x = arc4random_uniform(RU_M);
178 
179 	/* 15 bits of random seed */
180 	tmp = arc4random();
181 	ru_seed = (tmp >> 16) & 0x7FFF;
182 	ru_seed2 = tmp & 0x7FFF;
183 
184 	/* Determine the LCG we use */
185 	tmp = arc4random();
186 	ru_b = (tmp & 0xfffe) | 1;
187 	ru_a = pmod(RU_AGEN, (tmp >> 16) & 0xfffe, RU_M);
188 	while (ru_b % 3 == 0)
189 		ru_b += 2;
190 
191 	j = arc4random_uniform(RU_N);
192 
193 	/*
194 	 * Do a fast gcd(j,RU_N-1), so we can find a j with
195 	 * gcd(j, RU_N-1) == 1, giving a new generator for
196 	 * RU_GEN^j mod RU_N
197 	 */
198 
199 	while (noprime) {
200 		for (i = 0; i < PFAC_N; i++)
201 			if (j % pfacts[i] == 0)
202 				break;
203 
204 		if (i >= PFAC_N)
205 			noprime = 0;
206 		else
207 			j = (j + 1) % RU_N;
208 	}
209 
210 	ru_g = pmod(RU_GEN, j, RU_N);
211 	ru_counter = 0;
212 
213 	/* Initialise PRF for Luby-Rackoff permutation */
214 	if (ru_prf == NULL)
215 		ru_prf = malloc(sizeof(*ru_prf));
216 	if (ru_prf != NULL)
217 		arc4random_buf(ru_prf, sizeof(*ru_prf));
218 
219 	gettimeofday(&tv, NULL);
220 	ru_reseed = tv.tv_sec + RU_OUT;
221 	ru_msb = ru_msb == 0x8000 ? 0 : 0x8000;
222 }
223 
224 u_int
225 res_randomid(void)
226 {
227 	struct timeval tv;
228 
229 	gettimeofday(&tv, NULL);
230 	if (ru_counter >= RU_MAX || tv.tv_sec > ru_reseed)
231 		res_initid();
232 
233 	/* Linear Congruential Generator */
234 	ru_x = (ru_a * ru_x + ru_b) % RU_M;
235 	ru_counter++;
236 
237 	return permute15(ru_seed ^ pmod(ru_g, ru_seed2 + ru_x, RU_N)) | ru_msb;
238 }
239 
240 #if 0
241 int
242 main(int argc, char **argv)
243 {
244 	int i, n;
245 	u_int16_t wert;
246 
247 	res_initid();
248 
249 	printf("Generator: %u\n", ru_g);
250 	printf("Seed: %u\n", ru_seed);
251 	printf("Reseed at %ld\n", ru_reseed);
252 	printf("Ru_X: %u\n", ru_x);
253 	printf("Ru_A: %u\n", ru_a);
254 	printf("Ru_B: %u\n", ru_b);
255 
256 	n = argc > 1 ? atoi(argv[1]) : 60001;
257 	for (i=0;i<n;i++) {
258 		wert = res_randomid();
259 		printf("%u\n", wert);
260 	}
261 	return 0;
262 }
263 #endif
264 
265