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