]> andersk Git - openssh.git/blob - openbsd-compat/bsd-arc4random.c
- (djm) [acss.c auth-krb5.c auth-options.c auth-pam.c auth-shadow.c]
[openssh.git] / openbsd-compat / bsd-arc4random.c
1 /*
2  * Copyright (c) 1999,2000,2004 Damien Miller <djm@mindrot.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include "includes.h"
18
19 #include <sys/types.h>
20 #include <string.h>
21
22 #include "log.h"
23
24 #ifndef HAVE_ARC4RANDOM
25
26 #include <openssl/rand.h>
27 #include <openssl/rc4.h>
28 #include <openssl/err.h>
29
30 /* Size of key to use */
31 #define SEED_SIZE 20
32
33 /* Number of bytes to reseed after */
34 #define REKEY_BYTES     (1 << 24)
35
36 static int rc4_ready = 0;
37 static RC4_KEY rc4;
38
39 unsigned int
40 arc4random(void)
41 {
42         unsigned int r = 0;
43         static int first_time = 1;
44
45         if (rc4_ready <= 0) {
46                 if (first_time)
47                         seed_rng();
48                 first_time = 0;
49                 arc4random_stir();
50         }
51
52         RC4(&rc4, sizeof(r), (unsigned char *)&r, (unsigned char *)&r);
53
54         rc4_ready -= sizeof(r);
55         
56         return(r);
57 }
58
59 void
60 arc4random_stir(void)
61 {
62         unsigned char rand_buf[SEED_SIZE];
63         int i;
64
65         memset(&rc4, 0, sizeof(rc4));
66         if (RAND_bytes(rand_buf, sizeof(rand_buf)) <= 0)
67                 fatal("Couldn't obtain random bytes (error %ld)",
68                     ERR_get_error());
69         RC4_set_key(&rc4, sizeof(rand_buf), rand_buf);
70
71         /*
72          * Discard early keystream, as per recommendations in:
73          * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
74          */
75         for(i = 0; i <= 256; i += sizeof(rand_buf))
76                 RC4(&rc4, sizeof(rand_buf), rand_buf, rand_buf);
77
78         memset(rand_buf, 0, sizeof(rand_buf));
79
80         rc4_ready = REKEY_BYTES;
81 }
82 #endif /* !HAVE_ARC4RANDOM */
This page took 0.042162 seconds and 5 git commands to generate.