3 * Acquisition of environmental noise (Unix-specific)
5 * (c) 1998 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Catacomb.
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.
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.
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,
28 /*----- Header files ------------------------------------------------------*/
39 #include <sys/types.h>
50 #if defined(HAVE_LINUX_RANDOM_H)
51 # include <linux/random.h>
52 # include <sys/syscall.h>
55 #include <mLib/bits.h>
56 #include <mLib/mdup.h>
64 /*----- Magical numbers ---------------------------------------------------*/
66 #define NOISE_KIDLIFE 100000 /* @noise_filter@ child lifetime */
67 #define MILLION 1000000 /* One million */
69 /*----- Noise source definition -------------------------------------------*/
71 const rand_source noise_source = { noise_acquire, noise_timer };
73 /*----- Static variables --------------------------------------------------*/
75 /* --- Timer differences --- */
77 static unsigned long noise_last; /* Last time recorded */
78 static unsigned long noise_diff; /* Last first order difference */
80 /* --- Setuid program handling --- */
82 static uid_t noise_uid = NOISE_NOSETUID; /* Uid to set to spawn processes */
83 static gid_t noise_gid = NOISE_NOSETGID; /* Gid to set to spawn processes */
85 /*----- Main code ---------------------------------------------------------*/
87 /* --- @bitcount@ --- *
89 * Arguments: @unsigned long x@ = a word containing bits
91 * Returns: The number of bits set in the word.
94 static int bitcount(unsigned long x)
96 static const char ctab[] = { 0, 1, 1, 2, 1, 2, 2, 3,
97 1, 2, 2, 3, 2, 3, 3, 4 };
100 count += ctab[x & 0xfu];
108 * Arguments: @rand_pool *r@ = pointer to randomness pool
109 * @struct timeval *tv@ = pointer to time block
111 * Returns: Nonzero if some randomness was contributed.
113 * Use: Low-level timer contributor.
116 static int timer(rand_pool *r, struct timeval *tv)
118 unsigned long x, d, dd;
122 x = tv->tv_usec + MILLION * tv->tv_sec;
129 rand_add(r, tv, sizeof(*tv), de <= dde ? de : dde);
131 BURN(tv); x = d = dd = de = dde = 0;
135 /* --- @noise_timer@ --- *
137 * Arguments: @rand_pool *r@ = pointer to a randomness pool
139 * Returns: Nonzero if some randomness was contributed.
141 * Use: Contributes the current time to the randomness pool.
142 * A guess at the number of useful bits contributed is made,
143 * based on first and second order bit differences. This isn't
144 * ever-so reliable, but it's better than nothing.
147 int noise_timer(rand_pool *r)
150 gettimeofday(&tv, 0);
151 return (timer(r, &tv));
154 /* --- @noise_devrandom@ --- *
156 * Arguments: @rand_pool *r@ = pointer to a randomness pool
158 * Returns: Nonzero if some randomness was contributed.
160 * Use: Attempts to obtain some randomness from the system entropy
161 * pool. All bits from the device are assumed to be good.
164 int noise_devrandom(rand_pool *r)
167 octet buf[RAND_POOLSZ];
173 struct timeval tv = { 0, 0 };
175 #ifdef HAVE_GETENTROPY
179 #if defined(HAVE_LINUX_RANDOM_H) && \
180 defined(GRND_NONBLOCK) && \
181 defined(SYS_getrandom)
182 /* --- Use the new shinies if available --- */
184 while (n < sizeof(buf)) {
185 if ((len = syscall(SYS_getrandom, buf + n, sizeof(buf) - n,
186 GRND_NONBLOCK)) <= 0) {
187 if (errno == ENOSYS) break;
192 if (n == sizeof(buf)) goto win;
195 #ifdef HAVE_GETENTROPY
196 /* --- OpenBSD-flavoured shinies --- */
198 while (n < sizeof(buf)) {
199 nn = sizeof(buf) - nn;
200 if (nn > 256) nn = 256;
201 if (getentropy(buf + n, nn)) break;
204 if (n == sizeof(buf)) goto win;
208 /* --- Don't take from `/dev/urandom' if `/dev/random' would block --- */
210 if ((fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) < 0) goto done;
213 if (select(fd + 1, &infd, 0, 0, &tv) < 0 || !FD_ISSET(fd, &infd))
218 /* --- Be nice to other clients of the random device --- *
220 * Attempt to open the device nonblockingly. If that works, take up to
221 * one bufferful and then close again. If there's no data to be read,
222 * then that's tough and we go away again, on the grounds that the device
223 * needs to get some more entropy from somewhere.
227 (fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
228 (fd = open("/dev/arandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
229 (fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) >= 0) {
230 while (n < sizeof(buf)) {
231 if ((len = read(fd, buf + n, sizeof(buf) - n)) <= 0) break;
234 if (n == sizeof(buf)) goto win;
241 if (fd >= 0) close(fd);
242 rand_add(r, buf, n, 8*n);
248 /* --- @noise_setid@ --- *
250 * Arguments: @uid_t uid@ = uid to set
251 * @gid_t gid@ = gid to set
255 * Use: Sets the user and group ids to be used by @noise_filter@
256 * when running child processes. This is useful to avoid
257 * giving shell commands (even carefully written ones) undue
258 * privileges. This interface is Unix-specific
261 void noise_setid(uid_t uid, gid_t gid)
267 /* --- @noise_filter@ --- *
269 * Arguments: @rand_pool *r@ = pointer to a randomness pool
270 * @int good@ = number of good bits per 1024 bits
271 * @const char *c@ = shell command to run
273 * Returns: Nonzero if some randomness was contributed.
275 * Use: Attempts to execute a shell command, and dump it into the
276 * randomness pool. A very rough estimate of the number of
277 * good bits is made, based on the size of the command's output.
278 * This function calls @waitpid@, so be careful. Before execing
279 * the command, the process uid and gid are set to the values
280 * given to @noise_setid@, and an attempt is made to reset the
281 * list of supplementary groups. The environment passed to
282 * the command has been severly lobotimized. If the command
283 * fails to complete within a short time period, it is killed.
284 * Paranoid use of close-on-exec flags for file descriptors is
287 * This interface is Unix-specific.
298 static void kid_read(int fd, unsigned mode, void *p)
300 struct noisekid *nk = p;
305 if ((sz = read(fd, nk->buf, sizeof(nk->buf))) <= 0)
308 goodbits = (sz * nk->good) / 128;
309 rand_add(nk->r, nk->buf, sz, goodbits);
314 static void kid_dead(struct timeval *tv, void *p)
315 { struct noisekid *nk = p; nk->donep = 1; }
317 int noise_filter(rand_pool *r, int good, const char *c)
323 struct noisekid nk = { 0 };
327 const char *env[] = {
328 "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/etc",
332 /* --- Remember when this business started --- */
334 gettimeofday(&dead, 0);
337 /* --- Create a pipe --- */
342 /* --- Fork a child off --- */
352 /* --- Handle the child end of the deal --- */
358 /* --- Set the pipe as standard output, close standard input --- */
360 if ((f = open("/dev/null", O_RDONLY)) < 0) _exit(127);
361 mfd[i].cur = f; mfd[i].want = 0; i++;
362 mfd[i].cur = fd[1]; mfd[i].want = 1; i++;
363 mfd[i].cur = f; mfd[i].want = 2; i++;
364 if (mdup(mfd, i)) _exit(127);
366 /* --- Play games with uids --- */
368 if (noise_gid != NOISE_NOSETGID) {
371 #ifdef HAVE_SETGROUPS
372 setgroups(1, &noise_gid);
376 if (noise_uid != NOISE_NOSETUID) {
381 /* --- Start the process up --- */
383 execle("/bin/sh", "sh", "-c", c, (char *)0, env);
387 /* --- Sort out my end of the deal --- */
391 nk.r = r; nk.good = good;
392 TV_ADDL(&dead, &dead, 0, NOISE_KIDLIFE);
393 sel_initfile(&sel, &sf, fd[0], SEL_READ, kid_read, &nk);
395 sel_addtimer(&sel, &st, &dead, kid_dead, &nk);
396 while (!nk.donep && !sel_select(&sel));
398 /* --- We've finished with it: kill the child process --- *
400 * This is morally questionable. On the other hand, I don't want to be
401 * held up in the @waitpid@ call if I can possibly help it. Maybe a
402 * double-fork is worth doing here.
413 /* --- @noise_freewheel@ --- *
415 * Arguments: @rand_pool *r@ = pointer to a randomness pool
417 * Returns: Nonzero if some randomness was contributed.
419 * Use: Runs a free counter for a short while as a desparate attempt
420 * to get randomness from somewhere. This is actually quite
426 static sigjmp_buf fwjmp;
428 static void fwalarm(int sig)
430 siglongjmp(fwjmp, 1);
433 int noise_freewheel(rand_pool *r)
435 void (*sigal)(int) = 0;
436 struct itimerval oitv, itv = { { 0, 0 }, { 0, 5000 } };
438 volatile uint32 fwcount = 0;
440 if (!sigsetjmp(fwjmp, 1)) {
441 if ((sigal = signal(SIGALRM, fwalarm)) == SIG_ERR)
443 if (setitimer(ITIMER_REAL, &itv, &oitv))
449 STORE32(buf, fwcount);
450 rand_add(r, buf, sizeof(buf), 16);
455 signal(SIGALRM, sigal);
456 if (oitv.it_value.tv_sec || oitv.it_value.tv_usec)
457 TV_SUB(&oitv.it_value, &oitv.it_value, &itv.it_value);
458 setitimer(ITIMER_REAL, &oitv, 0);
464 int noise_freewheel(rand_pool *r)
471 /* --- @noise_enquire@ --- *
473 * Arguments: @rand_pool *r@ = pointer to a randomness pool
475 * Returns: Nonzero if some randomness was contributed.
477 * Use: Runs some shell commands to enquire about the prevailing
478 * environment. This can gather quite a lot of low-quality
482 int noise_enquire(rand_pool *r)
488 { "ps alxww || ps -elf", 16 },
490 { "ifconfig -a", 8 },
493 { "ls -align /tmp/.", 10 },
498 for (i = 0; tab[i].cmd; i++)
499 noise_filter(r, tab[i].rate, tab[i].cmd);
503 /* --- @noise_acquire@ --- *
505 * Arguments: @rand_pool *r@ = pointer to a randomness pool
509 * Use: Acquires some randomness from somewhere.
512 void noise_acquire(rand_pool *r)
515 for (i = 0; i < 8; i++)
517 if (!noise_devrandom(r) || getenv("CATACOMB_FORCE_ESOTERIC_SOURCES")) {
519 for (i = 0; i < 8; i++)
524 /*----- That's all, folks -------------------------------------------------*/