xref: /titanic_50/usr/src/cmd/ssh/libopenbsd-compat/common/bsd-arc4random.c (revision 1c5bc425cc346c6844d58e1fdd8794e9553dd289)
1 /*
2  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 /*
6  * Copyright (c) 1999-2000 Damien Miller.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include "includes.h"
30 #include "log.h"
31 
32 RCSID("$Id: bsd-arc4random.c,v 1.5 2002/05/08 22:57:18 tim Exp $");
33 
34 #pragma ident	"%Z%%M%	%I%	%E% SMI"
35 
36 #ifndef HAVE_ARC4RANDOM
37 
38 #include <openssl/rand.h>
39 #include <openssl/rc4.h>
40 #include <openssl/err.h>
41 
42 /* Size of key to use */
43 #define SEED_SIZE 20
44 
45 /* Number of bytes to reseed after */
46 #define REKEY_BYTES	(1 << 24)
47 
48 static int rc4_ready = 0;
49 static RC4_KEY rc4;
50 
51 unsigned int arc4random(void)
52 {
53 	unsigned int r = 0;
54 	static int first_time = 1;
55 
56 	if (rc4_ready <= 0) {
57 		if (first_time)
58 			seed_rng();
59 		first_time = 0;
60 		arc4random_stir();
61 	}
62 
63 	RC4(&rc4, sizeof(r), (unsigned char *)&r, (unsigned char *)&r);
64 
65 	rc4_ready -= sizeof(r);
66 
67 	return(r);
68 }
69 
70 void arc4random_stir(void)
71 {
72 	unsigned char rand_buf[SEED_SIZE];
73 
74 	memset(&rc4, 0, sizeof(rc4));
75 	if (!RAND_bytes(rand_buf, sizeof(rand_buf)))
76 		fatal("Couldn't obtain random bytes (error %ld)",
77 		    ERR_get_error());
78 	RC4_set_key(&rc4, sizeof(rand_buf), rand_buf);
79 	memset(rand_buf, 0, sizeof(rand_buf));
80 
81 	rc4_ready = REKEY_BYTES;
82 }
83 #endif /* !HAVE_ARC4RANDOM */
84