rand/noise.c (noise_devrandom): Handle Linux's broken `/dev/urandom'.
[catacomb] / rand / noise.c
1 /* -*-c-*-
2 *
3 * Acquisition of environmental noise (Unix-specific)
4 *
5 * (c) 1998 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Catacomb.
11 *
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
16 *
17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
21 *
22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25 * MA 02111-1307, USA.
26 */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include "config.h"
31
32 #include <setjmp.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37
38 #include <sys/types.h>
39 #include <sys/time.h>
40 #include <sys/wait.h>
41
42 #include <fcntl.h>
43 #include <unistd.h>
44
45 #ifdef HAVE_SETGROUPS
46 # include <grp.h>
47 #endif
48
49 #include <mLib/bits.h>
50 #include <mLib/mdup.h>
51 #include <mLib/sel.h>
52 #include <mLib/tv.h>
53
54 #include "noise.h"
55 #include "paranoia.h"
56 #include "rand.h"
57
58 /*----- Magical numbers ---------------------------------------------------*/
59
60 #define NOISE_KIDLIFE 100000 /* @noise_filter@ child lifetime */
61 #define MILLION 1000000 /* One million */
62
63 /*----- Noise source definition -------------------------------------------*/
64
65 const rand_source noise_source = { noise_acquire, noise_timer };
66
67 /*----- Static variables --------------------------------------------------*/
68
69 /* --- Timer differences --- */
70
71 static unsigned long noise_last; /* Last time recorded */
72 static unsigned long noise_diff; /* Last first order difference */
73
74 /* --- Setuid program handling --- */
75
76 static uid_t noise_uid = NOISE_NOSETUID; /* Uid to set to spawn processes */
77 static gid_t noise_gid = NOISE_NOSETGID; /* Gid to set to spawn processes */
78
79 /*----- Main code ---------------------------------------------------------*/
80
81 /* --- @bitcount@ --- *
82 *
83 * Arguments: @unsigned long x@ = a word containing bits
84 *
85 * Returns: The number of bits set in the word.
86 */
87
88 static int bitcount(unsigned long x)
89 {
90 static const char ctab[] = { 0, 1, 1, 2, 1, 2, 2, 3,
91 1, 2, 2, 3, 2, 3, 3, 4 };
92 int count = 0;
93 while (x) {
94 count += ctab[x & 0xfu];
95 x >>= 4;
96 }
97 return (count);
98 }
99
100 /* --- @timer@ --- *
101 *
102 * Arguments: @rand_pool *r@ = pointer to randomness pool
103 * @struct timeval *tv@ = pointer to time block
104 *
105 * Returns: Nonzero if some randomness was contributed.
106 *
107 * Use: Low-level timer contributor.
108 */
109
110 static int timer(rand_pool *r, struct timeval *tv)
111 {
112 unsigned long x, d, dd;
113 int de, dde;
114 int ret;
115
116 x = tv->tv_usec + MILLION * tv->tv_sec;
117 d = x ^ noise_last;
118 dd = d ^ noise_diff;
119 noise_last = x;
120 noise_diff = d;
121 de = bitcount(d);
122 dde = bitcount(dd);
123 rand_add(r, tv, sizeof(*tv), de <= dde ? de : dde);
124 ret = (de || dde);
125 BURN(tv); x = d = dd = de = dde = 0;
126 return (ret);
127 }
128
129 /* --- @noise_timer@ --- *
130 *
131 * Arguments: @rand_pool *r@ = pointer to a randomness pool
132 *
133 * Returns: Nonzero if some randomness was contributed.
134 *
135 * Use: Contributes the current time to the randomness pool.
136 * A guess at the number of useful bits contributed is made,
137 * based on first and second order bit differences. This isn't
138 * ever-so reliable, but it's better than nothing.
139 */
140
141 int noise_timer(rand_pool *r)
142 {
143 struct timeval tv;
144 gettimeofday(&tv, 0);
145 return (timer(r, &tv));
146 }
147
148 /* --- @noise_devrandom@ --- *
149 *
150 * Arguments: @rand_pool *r@ = pointer to a randomness pool
151 *
152 * Returns: Nonzero if some randomness was contributed.
153 *
154 * Use: Attempts to obtain some randomness from the system entropy
155 * pool. All bits from the device are assumed to be good.
156 */
157
158 int noise_devrandom(rand_pool *r)
159 {
160 int fd = -1;
161 octet buf[RAND_POOLSZ];
162 ssize_t len;
163 size_t n = 0;
164 int ret = 0;
165 #ifdef __linux__
166 fd_set infd;
167 struct timeval tv = { 0, 0 };
168 #endif
169
170 #ifdef __linux__
171 /* --- Don't take from `/dev/urandom' if `/dev/random' would block --- */
172
173 if ((fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) < 0) goto done;
174 FD_ZERO(&infd);
175 FD_SET(fd, &infd);
176 if (select(fd + 1, &infd, 0, 0, &tv) < 0 || !FD_ISSET(fd, &infd))
177 goto done;
178 close(fd); fd = -1;
179 #endif
180
181 /* --- Be nice to other clients of the random device --- *
182 *
183 * Attempt to open the device nonblockingly. If that works, take up to
184 * one bufferful and then close again. If there's no data to be read,
185 * then that's tough and we go away again, on the grounds that the device
186 * needs to get some more entropy from somewhere.
187 */
188
189 if (fd >= 0 ||
190 (fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
191 (fd = open("/dev/arandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
192 (fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) >= 0) {
193 while (n < sizeof(buf)) {
194 if ((len = read(fd, buf + n, sizeof(buf) - n)) <= 0) break;
195 n += len;
196 }
197 if (n == sizeof(buf)) goto win;
198 }
199 goto done;
200
201 win:
202 ret = 1;
203 done:
204 if (fd >= 0) close(fd);
205 rand_add(r, buf, n, 8*n);
206 BURN(buf);
207 noise_timer(r);
208 return (ret);
209 }
210
211 /* --- @noise_setid@ --- *
212 *
213 * Arguments: @uid_t uid@ = uid to set
214 * @gid_t gid@ = gid to set
215 *
216 * Returns: ---
217 *
218 * Use: Sets the user and group ids to be used by @noise_filter@
219 * when running child processes. This is useful to avoid
220 * giving shell commands (even carefully written ones) undue
221 * privileges. This interface is Unix-specific
222 */
223
224 void noise_setid(uid_t uid, gid_t gid)
225 {
226 noise_uid = uid;
227 noise_gid = gid;
228 }
229
230 /* --- @noise_filter@ --- *
231 *
232 * Arguments: @rand_pool *r@ = pointer to a randomness pool
233 * @int good@ = number of good bits per 1024 bits
234 * @const char *c@ = shell command to run
235 *
236 * Returns: Nonzero if some randomness was contributed.
237 *
238 * Use: Attempts to execute a shell command, and dump it into the
239 * randomness pool. A very rough estimate of the number of
240 * good bits is made, based on the size of the command's output.
241 * This function calls @waitpid@, so be careful. Before execing
242 * the command, the process uid and gid are set to the values
243 * given to @noise_setid@, and an attempt is made to reset the
244 * list of supplementary groups. The environment passed to
245 * the command has been severly lobotimized. If the command
246 * fails to complete within a short time period, it is killed.
247 * Paranoid use of close-on-exec flags for file descriptors is
248 * recommended.
249 *
250 * This interface is Unix-specific.
251 */
252
253 struct noisekid {
254 rand_pool *r;
255 int good;
256 char buf[4096];
257 int donep;
258 int ret;
259 };
260
261 static void kid_read(int fd, unsigned mode, void *p)
262 {
263 struct noisekid *nk = p;
264 ssize_t sz;
265 int goodbits;
266
267 noise_timer(nk->r);
268 if ((sz = read(fd, nk->buf, sizeof(nk->buf))) <= 0)
269 nk->donep = 1;
270 else {
271 goodbits = (sz * nk->good) / 128;
272 rand_add(nk->r, nk->buf, sz, goodbits);
273 nk->ret = 1;
274 }
275 }
276
277 static void kid_dead(struct timeval *tv, void *p)
278 { struct noisekid *nk = p; nk->donep = 1; }
279
280 int noise_filter(rand_pool *r, int good, const char *c)
281 {
282 pid_t kid;
283 int fd[2];
284 struct timeval dead;
285 int ret = 0;
286 struct noisekid nk = { 0 };
287 sel_state sel;
288 sel_file sf;
289 sel_timer st;
290 const char *env[] = {
291 "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/etc",
292 0
293 };
294
295 /* --- Remember when this business started --- */
296
297 gettimeofday(&dead, 0);
298 timer(r, &dead);
299
300 /* --- Create a pipe --- */
301
302 if (pipe(fd))
303 return (ret);
304
305 /* --- Fork a child off --- */
306
307 fflush(0);
308 kid = fork();
309 if (kid < 0) {
310 close(fd[0]);
311 close(fd[1]);
312 return (ret);
313 }
314
315 /* --- Handle the child end of the deal --- */
316
317 if (kid == 0) {
318 mdup_fd mfd[3];
319 int f, i = 0;
320
321 /* --- Set the pipe as standard output, close standard input --- */
322
323 if ((f = open("/dev/null", O_RDONLY)) < 0) _exit(127);
324 mfd[i].cur = f; mfd[i].want = 0; i++;
325 mfd[i].cur = fd[1]; mfd[i].want = 1; i++;
326 mfd[i].cur = f; mfd[i].want = 2; i++;
327 if (mdup(mfd, i)) _exit(127);
328
329 /* --- Play games with uids --- */
330
331 if (noise_gid != NOISE_NOSETGID) {
332 setgid(noise_gid);
333 setegid(noise_gid);
334 #ifdef HAVE_SETGROUPS
335 setgroups(1, &noise_gid);
336 #endif
337 }
338
339 if (noise_uid != NOISE_NOSETUID) {
340 setuid(noise_uid);
341 seteuid(noise_uid);
342 }
343
344 /* --- Start the process up --- */
345
346 execle("/bin/sh", "sh", "-c", c, (char *)0, env);
347 _exit(127);
348 }
349
350 /* --- Sort out my end of the deal --- */
351
352 close(fd[1]);
353 sel_init(&sel);
354 nk.r = r; nk.good = good;
355 TV_ADDL(&dead, &dead, 0, NOISE_KIDLIFE);
356 sel_initfile(&sel, &sf, fd[0], SEL_READ, kid_read, &nk);
357 sel_addfile(&sf);
358 sel_addtimer(&sel, &st, &dead, kid_dead, &nk);
359 while (!nk.donep && !sel_select(&sel));
360
361 /* --- We've finished with it: kill the child process --- *
362 *
363 * This is morally questionable. On the other hand, I don't want to be
364 * held up in the @waitpid@ call if I can possibly help it. Maybe a
365 * double-fork is worth doing here.
366 */
367
368 close(fd[0]);
369 BURN(nk.buf);
370 noise_timer(r);
371 kill(kid, SIGKILL);
372 waitpid(kid, 0, 0);
373 return (nk.ret);
374 }
375
376 /* --- @noise_freewheel@ --- *
377 *
378 * Arguments: @rand_pool *r@ = pointer to a randomness pool
379 *
380 * Returns: Nonzero if some randomness was contributed.
381 *
382 * Use: Runs a free counter for a short while as a desparate attempt
383 * to get randomness from somewhere. This is actually quite
384 * effective.
385 */
386
387 #ifdef USE_FREEWHEEL
388
389 static sigjmp_buf fwjmp;
390
391 static void fwalarm(int sig)
392 {
393 siglongjmp(fwjmp, 1);
394 }
395
396 int noise_freewheel(rand_pool *r)
397 {
398 void (*sigal)(int) = 0;
399 struct itimerval oitv, itv = { { 0, 0 }, { 0, 5000 } };
400 int rc = 0;
401 volatile uint32 fwcount = 0;
402
403 if (!sigsetjmp(fwjmp, 1)) {
404 if ((sigal = signal(SIGALRM, fwalarm)) == SIG_ERR)
405 return (0);
406 if (setitimer(ITIMER_REAL, &itv, &oitv))
407 goto done;
408 for (;;)
409 fwcount++;
410 } else {
411 octet buf[4];
412 STORE32(buf, fwcount);
413 rand_add(r, buf, sizeof(buf), 16);
414 rc = 1;
415 }
416
417 done:
418 signal(SIGALRM, sigal);
419 if (oitv.it_value.tv_sec || oitv.it_value.tv_usec)
420 TV_SUB(&oitv.it_value, &oitv.it_value, &itv.it_value);
421 setitimer(ITIMER_REAL, &oitv, 0);
422 return (rc);
423 }
424
425 #else
426
427 int noise_freewheel(rand_pool *r)
428 {
429 return (0);
430 }
431
432 #endif
433
434 /* --- @noise_enquire@ --- *
435 *
436 * Arguments: @rand_pool *r@ = pointer to a randomness pool
437 *
438 * Returns: Nonzero if some randomness was contributed.
439 *
440 * Use: Runs some shell commands to enquire about the prevailing
441 * environment. This can gather quite a lot of low-quality
442 * entropy.
443 */
444
445 int noise_enquire(rand_pool *r)
446 {
447 struct tab {
448 const char *cmd;
449 unsigned rate;
450 } tab[] = {
451 { "ps alxww || ps -elf", 16 },
452 { "netstat -n", 6 },
453 { "ifconfig -a", 8 },
454 { "df", 20 },
455 { "w", 6 },
456 { "ls -align /tmp/.", 10 },
457 { 0, 0 }
458 };
459 int i;
460
461 for (i = 0; tab[i].cmd; i++)
462 noise_filter(r, tab[i].rate, tab[i].cmd);
463 return (1);
464 }
465
466 /* --- @noise_acquire@ --- *
467 *
468 * Arguments: @rand_pool *r@ = pointer to a randomness pool
469 *
470 * Returns: ---
471 *
472 * Use: Acquires some randomness from somewhere.
473 */
474
475 void noise_acquire(rand_pool *r)
476 {
477 unsigned i;
478 for (i = 0; i < 8; i++)
479 noise_freewheel(r);
480 if (!noise_devrandom(r) || getenv("CATACOMB_FORCE_ESOTERIC_SOURCES")) {
481 noise_enquire(r);
482 for (i = 0; i < 8; i++)
483 noise_freewheel(r);
484 }
485 }
486
487 /*----- That's all, folks -------------------------------------------------*/