[core] defer li_rand_init() until first use
[lighttpd.git] / src / rand.c
blob4297fbc71b5f3974bde0e27e29771dac7f9ac51a
1 #include "first.h"
3 #include "rand.h"
4 #include "base.h"
5 #include "fdevent.h"
6 #include "safe_memclear.h"
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <errno.h>
11 #include <fcntl.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <time.h>
16 #include <unistd.h>
18 #ifdef USE_OPENSSL
19 #include <openssl/rand.h>
20 #endif
21 #ifdef HAVE_LINUX_RANDOM_H
22 #include <sys/syscall.h>
23 #include <linux/random.h>
24 #endif
25 #ifdef RNDGETENTCNT
26 #include <sys/ioctl.h>
27 #endif
29 /* Take some reasonable steps to attempt to *seed* random number generators with
30 * cryptographically random data. Some of these initialization routines may
31 * block, and are intended to be called only at startup in lighttpd, or
32 * immediately after fork() to start lighttpd workers.
34 * Update: li_rand_init() is now deferred until first use so that installations
35 * that do not use modules which use these routines do need to potentially block
36 * at startup. Current use by core lighttpd modules is in mod_auth HTTP Digest
37 * auth and in mod_usertrack. Deferring collection of random data until first
38 * use may allow sufficient entropy to be collected by kernel before first use,
39 * helping reduce or avoid situations in low-entropy-generating embedded devices
40 * which might otherwise block lighttpd for minutes at device startup.
41 * Further discussion in https://redmine.lighttpd.net/boards/2/topics/6981
43 * Note: results from li_rand_pseudo_bytes() are not necessarily
44 * cryptographically random and must not be used for purposes such
45 * as key generation which require cryptographic randomness.
47 * https://wiki.openssl.org/index.php/Random_Numbers
48 * https://wiki.openssl.org/index.php/Random_fork-safety
50 * openssl random number generators are not thread-safe by default
51 * https://wiki.openssl.org/index.php/Manual:Threads(3)
53 * RFE: add more paranoid checks from the following to improve confidence:
54 * http://insanecoding.blogspot.co.uk/2014/05/a-good-idea-with-bad-usage-devurandom.html
55 * RFE: retry on EINTR
56 * RFE: check RAND_status()
59 static int li_getentropy (void *buf, size_t buflen)
61 #ifdef HAVE_GETENTROPY
62 return getentropy(buf, buflen);
63 #else
64 /*(see NOTES section in 'man getrandom' on Linux)*/
65 #if defined(HAVE_GETRANDOM) || defined(SYS_getrandom)
66 if (buflen <= 256) {
67 #ifdef HAVE_GETRANDOM /*(not implemented in glibc yet)*/
68 int num = getrandom(buf, buflen, 0);
69 #elif defined(SYS_getrandom)
70 /* https://lwn.net/Articles/605828/ */
71 /* https://bbs.archlinux.org/viewtopic.php?id=200039 */
72 int num = (int)syscall(SYS_getrandom, buf, buflen, 0);
73 #endif
74 if (num == (int)buflen) return 0;
75 if (num < 0) return num; /* -1 */
77 #else
78 UNUSED(buf);
79 UNUSED(buflen);
80 #endif
81 errno = EIO;
82 return -1;
83 #endif
86 static int li_rand_device_bytes (unsigned char *buf, int num)
88 /* randomness from these devices is cryptographically strong,
89 * unless /dev/urandom is low on entropy */
91 static const char * const devices[] = {
92 #ifdef __OpenBSD__
93 "/dev/arandom",
94 #endif
95 "/dev/urandom",
96 "/dev/random"
99 /* device files might not be available in chroot environment,
100 * so prefer syscall, if available */
101 if (0 == li_getentropy(buf, (size_t)num)) return 1;
103 for (unsigned int u = 0; u < sizeof(devices)/sizeof(devices[0]); ++u) {
104 /*(some systems might have symlink to another device; omit O_NOFOLLOW)*/
105 int fd = fdevent_open_cloexec(devices[u], O_RDONLY, 0);
106 if (fd >= 0) {
107 ssize_t rd = 0;
108 #ifdef RNDGETENTCNT
109 int entropy;
110 if (0 == ioctl(fd, RNDGETENTCNT, &entropy) && entropy >= num*8)
111 #endif
112 rd = read(fd, buf, (size_t)num);
113 close(fd);
114 if (rd == num) {
115 return 1;
120 return 0;
123 static int li_rand_inited;
124 static unsigned short xsubi[3];
126 static void li_rand_init (void)
128 /* (intended to be called at init and after fork() in order to re-seed PRNG
129 * so that forked children, grandchildren, etc do not share PRNG seed)
130 * https://github.com/ramsey/uuid/issues/80
131 * https://www.agwa.name/blog/post/libressls_prng_is_unsafe_on_linux
132 * (issue in early version of libressl has since been fixed)
133 * https://github.com/libressl-portable/portable/commit/32d9eeeecf4e951e1566d5f4a42b36ea37b60f35
135 unsigned int u;
136 li_rand_inited = 1;
137 if (1 == li_rand_device_bytes((unsigned char *)xsubi, (int)sizeof(xsubi))) {
138 u = ((unsigned int)xsubi[0] << 16) | xsubi[1];
140 else {
141 #ifdef HAVE_ARC4RANDOM_BUF
142 u = arc4random();
143 arc4random_buf(xsubi, sizeof(xsubi));
144 #else
145 /* NOTE: not cryptographically random !!! */
146 srand((unsigned int)(time(NULL) ^ getpid()));
147 for (u = 0; u < sizeof(unsigned short); ++u)
148 /* coverity[dont_call : FALSE] */
149 xsubi[u] = (unsigned short)(rand() & 0xFFFF);
150 u = ((unsigned int)xsubi[0] << 16) | xsubi[1];
151 #endif
153 srand(u); /*(initialize just in case rand() used elsewhere)*/
154 #ifdef HAVE_SRANDOM
155 srandom(u); /*(initialize just in case random() used elsewhere)*/
156 #endif
157 #ifdef USE_OPENSSL
158 RAND_poll();
159 RAND_seed(xsubi, (int)sizeof(xsubi));
160 #endif
163 void li_rand_reseed (void)
165 if (li_rand_inited) li_rand_init();
168 int li_rand_pseudo_bytes (void)
170 /* randomness *is not* cryptographically strong */
171 /* (attempt to use better mechanisms to replace the more portable rand()) */
172 #ifdef USE_OPENSSL /* (RAND_pseudo_bytes() is deprecated in openssl 1.1.0) */
173 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
174 int i;
175 if (-1 != RAND_pseudo_bytes((unsigned char *)&i, sizeof(i))) return i;
176 #endif
177 #endif
178 if (!li_rand_inited) li_rand_init();
179 #ifdef HAVE_ARC4RANDOM_BUF
180 return (int)arc4random();
181 #elif defined(HAVE_SRANDOM)
182 /* coverity[dont_call : FALSE] */
183 return (int)random();
184 #elif defined(HAVE_JRAND48)
185 /*(FYI: jrand48() reentrant, but use of file-scoped static xsubi[] is not)*/
186 /* coverity[dont_call : FALSE] */
187 return (int)jrand48(xsubi);
188 #else
189 /* coverity[dont_call : FALSE] */
190 return rand();
191 #endif
194 int li_rand_bytes (unsigned char *buf, int num)
196 #ifdef USE_OPENSSL
197 int rc = RAND_bytes(buf, num);
198 if (-1 != rc) {
199 return rc;
201 #endif
202 if (1 == li_rand_device_bytes(buf, num)) {
203 return 1;
205 else {
206 /* NOTE: not cryptographically random !!! */
207 for (int i = 0; i < num; ++i)
208 buf[i] = li_rand_pseudo_bytes() & 0xFF;
209 /*(openssl RAND_pseudo_bytes rc for non-cryptographically random data)*/
210 return 0;
214 void li_rand_cleanup (void)
216 #ifdef USE_OPENSSL
217 RAND_cleanup();
218 #endif
219 safe_memclear(xsubi, sizeof(xsubi));