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