new upstream release (3.3.0); modify package compatibility for Stretch
[ossec-hids.git] / src / shared / randombytes.c
1 #ifndef WIN32
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #endif
5
6 #include <stdio.h>
7 #include <stdlib.h>
8
9 #include "shared.h"
10
11
12 void randombytes(void *ptr, size_t length)
13 {
14     char failed = 0;
15
16 #ifdef WIN32
17     static HCRYPTPROV prov = 0;
18     if (prov == 0) {
19         if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) {
20             failed = 1;
21         }
22     }
23     if (!failed && !CryptGenRandom(prov, length, ptr)) {
24         failed = 1;
25     }
26 #else
27     static int fh = -1;
28
29     if (fh >= 0 || (fh = open("/dev/urandom", O_RDONLY)) >= 0 || (fh = open("/dev/random", O_RDONLY)) >= 0) {
30         const ssize_t ret = read(fh, ptr, length);
31         if (ret < 0 || (size_t) ret != length) {
32             failed = 1;
33         }
34     } else {
35         failed = 1;
36     }
37 #endif
38
39     if (failed) {
40         ErrorExit("%s: ERROR: randombytes failed for all possible methods for accessing random data", __local_name);
41     }
42 }
43
44 void srandom_init(void)
45 {
46 #ifndef WIN32
47 #ifdef __OpenBSD__
48     srandomdev();
49 #else
50     unsigned int seed;
51     randombytes(&seed, sizeof seed);
52     srandom(seed);
53 #endif /* !__OpenBSD__ */
54 #endif /* !WIN32 */
55 }
56