Home | History | Annotate | Line # | Download | only in gen
randomid.c revision 1.10
      1 /*	$NetBSD: randomid.c,v 1.10 2003/12/10 05:22:18 itojun Exp $	*/
      2 /*	$KAME: ip6_id.c,v 1.8 2003/09/06 13:41:06 itojun Exp $	*/
      3 /*	$OpenBSD: ip_id.c,v 1.6 2002/03/15 18:19:52 millert Exp $	*/
      4 
      5 /*
      6  * Copyright (C) 2003 WIDE Project.
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. Neither the name of the project nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 /*
     35  * Copyright 1998 Niels Provos <provos (at) citi.umich.edu>
     36  * All rights reserved.
     37  *
     38  * Theo de Raadt <deraadt (at) openbsd.org> came up with the idea of using
     39  * such a mathematical system to generate more random (yet non-repeating)
     40  * ids to solve the resolver/named problem.  But Niels designed the
     41  * actual system based on the constraints.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. All advertising materials mentioning features or use of this software
     52  *    must display the following acknowledgement:
     53  *      This product includes software developed by Niels Provos.
     54  * 4. The name of the author may not be used to endorse or promote products
     55  *    derived from this software without specific prior written permission.
     56  *
     57  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     58  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     59  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     60  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     61  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     62  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     63  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     64  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     65  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     66  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     67  */
     68 
     69 /*
     70  * seed = random (bits - 1) bit
     71  * n = prime, g0 = generator to n,
     72  * j = random so that gcd(j,n-1) == 1
     73  * g = g0^j mod n will be a generator again.
     74  *
     75  * X[0] = random seed.
     76  * X[n] = a*X[n-1]+b mod m is a Linear Congruential Generator
     77  * with a = 7^(even random) mod m,
     78  *      b = random with gcd(b,m) == 1
     79  *      m = constant and a maximal period of m-1.
     80  *
     81  * The transaction id is determined by:
     82  * id[n] = seed xor (g^X[n] mod n)
     83  *
     84  * Effectivly the id is restricted to the lower (bits - 1) bits, thus
     85  * yielding two different cycles by toggling the msb on and off.
     86  * This avoids reuse issues caused by reseeding.
     87  */
     88 
     89 #include <sys/cdefs.h>
     90 #if defined(LIBC_SCCS) && !defined(lint)
     91 __RCSID("$NetBSD: randomid.c,v 1.10 2003/12/10 05:22:18 itojun Exp $");
     92 #endif
     93 
     94 #include "namespace.h"
     95 
     96 #include <sys/types.h>
     97 #include <sys/time.h>
     98 #include <stdlib.h>
     99 #include <string.h>
    100 #include <errno.h>
    101 #include <randomid.h>
    102 
    103 #ifdef __weak_alias
    104 __weak_alias(randomid,_randomid)
    105 __weak_alias(randomid_new,_randomid_new)
    106 __weak_alias(randomid_delete,_randomid_delete)
    107 #endif
    108 
    109 struct randomconf {
    110 	const int	rc_bits; /* resulting bits */
    111 	const u_int32_t rc_max;	/* Uniq cycle, avoid blackjack prediction */
    112 	const u_int32_t rc_gen;	/* Starting generator */
    113 	const u_int32_t rc_n;	/* ru_n: prime, ru_n - 1: product of pfacts[] */
    114 	const u_int32_t rc_agen; /* determine ru_a as ru_agen^(2*rand) */
    115 	const u_int32_t rc_m;	/* ru_m = 2^x*3^y */
    116 	const u_int32_t rc_pfacts[4];	/* factors of ru_n */
    117 	const int	rc_skip;	/* skip values */
    118 };
    119 
    120 struct randomid_ctx {
    121 	struct randomconf *ru_conf;
    122 #define ru_bits		ru_conf->rc_bits
    123 #define ru_max		ru_conf->rc_max
    124 #define ru_gen		ru_conf->rc_gen
    125 #define ru_n		ru_conf->rc_n
    126 #define ru_agen		ru_conf->rc_agen
    127 #define ru_m		ru_conf->rc_m
    128 #define ru_pfacts	ru_conf->rc_pfacts
    129 #define ru_skip		ru_conf->rc_skip
    130 	long ru_out;		/* Time after wich will be reseeded */
    131 	u_int32_t ru_counter;
    132 	u_int32_t ru_msb;
    133 
    134 	u_int32_t ru_x;
    135 	u_int32_t ru_seed, ru_seed2;
    136 	u_int32_t ru_a, ru_b;
    137 	u_int32_t ru_g;
    138 	long ru_reseed;
    139 };
    140 
    141 static struct randomconf randomconf[] = {
    142   {
    143 	32,			/* resulting bits */
    144 	1000000000,		/* Uniq cycle, avoid blackjack prediction */
    145 	2,			/* Starting generator */
    146 	2147483629,		/* RU_N-1 = 2^2*3^2*59652323 */
    147 	7,			/* determine ru_a as RU_AGEN^(2*rand) */
    148 	1836660096,		/* RU_M = 2^7*3^15 - don't change */
    149 	{ 2, 3, 59652323, 0 },	/* factors of ru_n */
    150 	3,			/* skip values */
    151   },
    152   {
    153 	20,			/* resulting bits */
    154 	200000,			/* Uniq cycle, avoid blackjack prediction */
    155 	2,			/* Starting generator */
    156 	524269,			/* RU_N-1 = 2^2*3^2*14563 */
    157 	7,			/* determine ru_a as RU_AGEN^(2*rand) */
    158 	279936,			/* RU_M = 2^7*3^7 - don't change */
    159 	{ 2, 3, 14563, 0 },	/* factors of ru_n */
    160 	3,			/* skip values */
    161   },
    162   {
    163 	16,			/* resulting bits */
    164 	30000,			/* Uniq cycle, avoid blackjack prediction */
    165 	2,			/* Starting generator */
    166 	32749,			/* RU_N-1 = 2^2*3*2729 */
    167 	7,			/* determine ru_a as RU_AGEN^(2*rand) */
    168 	31104,			/* RU_M = 2^7*3^5 - don't change */
    169 	{ 2, 3, 2729, 0 },	/* factors of ru_n */
    170 	0,			/* skip values */
    171   },
    172   {
    173 	-1,			/* termination */
    174   },
    175 };
    176 
    177 static u_int32_t pmod(u_int32_t, u_int32_t, u_int32_t);
    178 static void initid(struct randomid_ctx *);
    179 
    180 struct randomid_ctx *randomid_new(int, long);
    181 void randomid_delete(struct randomid_ctx *);
    182 u_int32_t randomid(struct randomid_ctx *);
    183 
    184 /*
    185  * Do a fast modular exponation, returned value will be in the range
    186  * of 0 - (mod-1)
    187  */
    188 
    189 static u_int32_t
    190 pmod(u_int32_t gen, u_int32_t expo, u_int32_t mod)
    191 {
    192 	u_int64_t s, t, u;
    193 
    194 	s = 1;
    195 	t = gen;
    196 	u = expo;
    197 
    198 	while (u) {
    199 		if (u & 1)
    200 			s = (s * t) % mod;
    201 		u >>= 1;
    202 		t = (t * t) % mod;
    203 	}
    204 	return ((u_int32_t)s & UINT32_MAX);
    205 }
    206 
    207 /*
    208  * Initalizes the seed and chooses a suitable generator. Also toggles
    209  * the msb flag. The msb flag is used to generate two distinct
    210  * cycles of random numbers and thus avoiding reuse of ids.
    211  *
    212  * This function is called from id_randomid() when needed, an
    213  * application does not have to worry about it.
    214  */
    215 static void
    216 initid(struct randomid_ctx *p)
    217 {
    218 	u_int32_t j, i;
    219 	int noprime = 1;
    220 	struct timeval tv;
    221 
    222 	p->ru_x = arc4random() % p->ru_m;
    223 
    224 	/* (bits - 1) bits of random seed */
    225 	p->ru_seed = arc4random() & (~0U >> (32 - p->ru_bits + 1));
    226 	p->ru_seed2 = arc4random() & (~0U >> (32 - p->ru_bits + 1));
    227 
    228 	/* Determine the LCG we use */
    229 	p->ru_b = (arc4random() & (~0U >> (32 - p->ru_bits))) | 1;
    230 	p->ru_a = pmod(p->ru_agen,
    231 	    (arc4random() & (~0U >> (32 - p->ru_bits))) & (~1U), p->ru_m);
    232 	while (p->ru_b % 3 == 0)
    233 		p->ru_b += 2;
    234 
    235 	j = arc4random() % p->ru_n;
    236 
    237 	/*
    238 	 * Do a fast gcd(j, RU_N - 1), so we can find a j with
    239 	 * gcd(j, RU_N - 1) == 1, giving a new generator for
    240 	 * RU_GEN^j mod RU_N
    241 	 */
    242 	while (noprime) {
    243 		for (i = 0; p->ru_pfacts[i] > 0; i++)
    244 			if (j % p->ru_pfacts[i] == 0)
    245 				break;
    246 
    247 		if (p->ru_pfacts[i] == 0)
    248 			noprime = 0;
    249 		else
    250 			j = (j + 1) % p->ru_n;
    251 	}
    252 
    253 	p->ru_g = pmod(p->ru_gen, j, p->ru_n);
    254 	p->ru_counter = 0;
    255 
    256 	gettimeofday(&tv, NULL);
    257 	p->ru_reseed = tv.tv_sec + p->ru_out;
    258 	p->ru_msb = p->ru_msb ? 0 : (1U << (p->ru_bits - 1));
    259 }
    260 
    261 struct randomid_ctx *
    262 randomid_new(int bits, long timeo)
    263 {
    264 	struct randomconf *conf;
    265 	struct randomid_ctx *ctx;
    266 
    267 	if (timeo < RANDOMID_TIMEO_MIN) {
    268 		errno = EINVAL;
    269 		return (NULL);
    270 	}
    271 
    272 	for (conf = randomconf; conf->rc_bits > 0; conf++) {
    273 		if (bits == conf->rc_bits)
    274 			break;
    275 	}
    276 
    277 	/* unsupported bits */
    278 	if (bits != conf->rc_bits) {
    279 		errno = ENOTSUP;
    280 		return (NULL);
    281 	}
    282 
    283 	ctx = malloc(sizeof(*ctx));
    284 	if (!ctx)
    285 		return (NULL);
    286 
    287 	memset(ctx, 0, sizeof(*ctx));
    288 	ctx->ru_conf = conf;
    289 	ctx->ru_out = timeo;
    290 
    291 	return (ctx);
    292 }
    293 
    294 void
    295 randomid_delete(struct randomid_ctx *ctx)
    296 {
    297 
    298 	memset(ctx, 0, sizeof(*ctx));
    299 	free(ctx);
    300 }
    301 
    302 u_int32_t
    303 randomid(struct randomid_ctx *p)
    304 {
    305 	int i, n;
    306 	struct timeval tv;
    307 
    308 	gettimeofday(&tv, NULL);
    309 	if (p->ru_counter >= p->ru_max || tv.tv_sec > p->ru_reseed)
    310 		initid(p);
    311 
    312 	/* Skip a random number of ids */
    313 	if (p->ru_skip) {
    314 		n = arc4random() & p->ru_skip;
    315 		if (p->ru_counter + n >= p->ru_max)
    316 			initid(p);
    317 	} else
    318 		n = 0;
    319 
    320 	for (i = 0; i <= n; i++) {
    321 		/* Linear Congruential Generator */
    322 		p->ru_x = (u_int32_t)(((u_int64_t)p->ru_a * p->ru_x + p->ru_b) % p->ru_m);
    323 	}
    324 
    325 	p->ru_counter += i;
    326 
    327 	return (p->ru_seed ^ pmod(p->ru_g, p->ru_seed2 + p->ru_x, p->ru_n)) |
    328 	    p->ru_msb;
    329 }
    330