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 ------------------------------------------------------*/
40 #include <sys/types.h>
51 #if defined(HAVE_LINUX_RANDOM_H)
52 # include <linux/random.h>
53 # include <sys/syscall.h>
56 #include <mLib/bits.h>
57 #include <mLib/mdup.h>
65 /*----- Magical numbers ---------------------------------------------------*/
67 #define NOISE_KIDLIFE 100000 /* @noise_filter@ child lifetime */
69 #if HAVE_CLOCK_GETTIME && _POSIX_TIMERS > 0
70 # define TIMESTRUCT timespec
71 # define tv_SEC tv_sec
72 # define tv_FRAC tv_nsec
73 # define TIMERES 1000000000
74 # if _POSIX_MONOTONIC_CLOCK > 0
75 # define GETTIME(tv) (clock_gettime(CLOCK_MONOTONIC, (tv)))
77 # define GETTIME(tv) (clock_gettime(CLOCK_REALTIME, (tv)))
79 # define TOTIMEVAL(tv, xx) \
80 ((tv)->tv_sec = (xx)->tv_sec, \
81 (tv)->tv_usec = ((xx)->tv_nsec + 500)/1000)
83 # define TIMESTRUCT timeval
84 # define tv_SEC tv_sec
85 # define tv_FRAC tv_usec
86 # define TIMERES 1000000
87 # define GETTIME(tv) (gettimeofday((tv), 0))
88 # define TOTIMEVAL(tv, xx) (*(tv) = *(xx))
91 /*----- Noise source definition -------------------------------------------*/
93 const rand_source noise_source = { noise_acquire, noise_timer };
95 /*----- Static variables --------------------------------------------------*/
97 /* --- Timer differences --- */
99 static unsigned long noise_last; /* Last time recorded */
100 static unsigned long noise_diff; /* Last first order difference */
102 /* --- Setuid program handling --- */
104 static uid_t noise_uid = NOISE_NOSETUID; /* Uid to set to spawn processes */
105 static gid_t noise_gid = NOISE_NOSETGID; /* Gid to set to spawn processes */
107 /*----- Main code ---------------------------------------------------------*/
109 /* --- @bitcount@ --- *
111 * Arguments: @unsigned long x@ = a word containing bits
113 * Returns: The number of bits set in the word.
116 static int bitcount(unsigned long x)
118 static const char ctab[] = { 0, 1, 1, 2, 1, 2, 2, 3,
119 1, 2, 2, 3, 2, 3, 3, 4 };
122 count += ctab[x & 0xfu];
130 * Arguments: @rand_pool *r@ = pointer to randomness pool
131 * @const struct TIMESTRUCT *tv@ = pointer to time block
133 * Returns: Nonzero if some randomness was contributed.
135 * Use: Low-level timer contributor.
138 static int timer(rand_pool *r, const struct TIMESTRUCT *tv)
140 unsigned long x, d, dd;
144 x = tv->tv_FRAC + TIMERES*tv->tv_SEC;
151 rand_add(r, tv, sizeof(*tv), de <= dde ? de : dde);
153 BURN(tv); x = d = dd = de = dde = 0;
157 /* --- @noise_timer@ --- *
159 * Arguments: @rand_pool *r@ = pointer to a randomness pool
161 * Returns: Nonzero if some randomness was contributed.
163 * Use: Contributes the current time to the randomness pool.
164 * A guess at the number of useful bits contributed is made,
165 * based on first and second order bit differences. This isn't
166 * ever-so reliable, but it's better than nothing.
169 int noise_timer(rand_pool *r)
171 struct TIMESTRUCT tv;
172 GETTIME(&tv); return (timer(r, &tv));
175 /* --- @noise_devrandom@ --- *
177 * Arguments: @rand_pool *r@ = pointer to a randomness pool
179 * Returns: Nonzero if some randomness was contributed.
181 * Use: Attempts to obtain some randomness from the system entropy
182 * pool. All bits from the device are assumed to be good.
185 int noise_devrandom(rand_pool *r)
188 octet buf[RAND_POOLSZ];
194 struct timeval tv = { 0, 0 };
196 #ifdef HAVE_GETENTROPY
200 #if defined(HAVE_LINUX_RANDOM_H) && \
201 defined(GRND_NONBLOCK) && \
202 defined(SYS_getrandom)
203 /* --- Use the new shinies if available --- */
205 while (n < sizeof(buf)) {
206 if ((len = syscall(SYS_getrandom, buf + n, sizeof(buf) - n,
207 GRND_NONBLOCK)) <= 0) {
208 if (errno == ENOSYS) break;
213 if (n == sizeof(buf)) goto win;
216 #ifdef HAVE_GETENTROPY
217 /* --- OpenBSD-flavoured shinies --- */
219 while (n < sizeof(buf)) {
220 nn = sizeof(buf) - n;
221 if (nn > 256) nn = 256;
222 if (getentropy(buf + n, nn)) break;
225 if (n == sizeof(buf)) goto win;
229 /* --- Don't take from `/dev/urandom' if `/dev/random' would block --- */
231 if ((fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) < 0) goto done;
234 if (select(fd + 1, &infd, 0, 0, &tv) < 0 || !FD_ISSET(fd, &infd))
239 /* --- Be nice to other clients of the random device --- *
241 * Attempt to open the device nonblockingly. If that works, take up to
242 * one bufferful and then close again. If there's no data to be read,
243 * then that's tough and we go away again, on the grounds that the device
244 * needs to get some more entropy from somewhere.
248 (fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
249 (fd = open("/dev/arandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
250 (fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) >= 0) {
251 while (n < sizeof(buf)) {
252 if ((len = read(fd, buf + n, sizeof(buf) - n)) <= 0) break;
255 if (n == sizeof(buf)) goto win;
262 if (fd >= 0) close(fd);
263 rand_add(r, buf, n, 8*n);
269 /* --- @noise_setid@ --- *
271 * Arguments: @uid_t uid@ = uid to set
272 * @gid_t gid@ = gid to set
276 * Use: Sets the user and group ids to be used by @noise_filter@
277 * when running child processes. This is useful to avoid
278 * giving shell commands (even carefully written ones) undue
279 * privileges. This interface is Unix-specific
282 void noise_setid(uid_t uid, gid_t gid)
288 /* --- @noise_filter@ --- *
290 * Arguments: @rand_pool *r@ = pointer to a randomness pool
291 * @int good@ = number of good bits per 1024 bits
292 * @const char *c@ = shell command to run
294 * Returns: Nonzero if some randomness was contributed.
296 * Use: Attempts to execute a shell command, and dump it into the
297 * randomness pool. A very rough estimate of the number of
298 * good bits is made, based on the size of the command's output.
299 * This function calls @waitpid@, so be careful. Before execing
300 * the command, the process uid and gid are set to the values
301 * given to @noise_setid@, and an attempt is made to reset the
302 * list of supplementary groups. The environment passed to
303 * the command has been severly lobotimized. If the command
304 * fails to complete within a short time period, it is killed.
305 * Paranoid use of close-on-exec flags for file descriptors is
308 * This interface is Unix-specific.
319 static void kid_read(int fd, unsigned mode, void *p)
321 struct noisekid *nk = p;
326 if ((sz = read(fd, nk->buf, sizeof(nk->buf))) <= 0)
329 goodbits = (sz * nk->good) / 128;
330 rand_add(nk->r, nk->buf, sz, goodbits);
335 static void kid_dead(struct timeval *tv, void *p)
336 { struct noisekid *nk = p; nk->donep = 1; }
338 int noise_filter(rand_pool *r, int good, const char *c)
343 struct TIMESTRUCT now;
345 struct noisekid nk = { 0 };
349 const char *env[] = {
350 "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/etc",
354 /* --- Remember when this business started --- */
356 GETTIME(&now); timer(r, &now);
357 TOTIMEVAL(&dead, &now);
359 /* --- Create a pipe --- */
364 /* --- Fork a child off --- */
374 /* --- Handle the child end of the deal --- */
380 /* --- Set the pipe as standard output, close standard input --- */
382 if ((f = open("/dev/null", O_RDONLY)) < 0) _exit(127);
383 mfd[i].cur = f; mfd[i].want = 0; i++;
384 mfd[i].cur = fd[1]; mfd[i].want = 1; i++;
385 mfd[i].cur = f; mfd[i].want = 2; i++;
386 if (mdup(mfd, i)) _exit(127);
388 /* --- Play games with uids --- */
390 if (noise_gid != NOISE_NOSETGID) {
391 if (setgid(noise_gid) || setegid(noise_gid)
392 #ifdef HAVE_SETGROUPS
393 || setgroups(1, &noise_gid)
398 if (noise_uid != NOISE_NOSETUID) {
399 if (setuid(noise_uid) || seteuid(noise_uid)) _exit(127);
402 /* --- Start the process up --- */
404 execle("/bin/sh", "sh", "-c", c, (char *)0, env);
408 /* --- Sort out my end of the deal --- */
412 nk.r = r; nk.good = good;
413 TV_ADDL(&dead, &dead, 0, NOISE_KIDLIFE);
414 sel_initfile(&sel, &sf, fd[0], SEL_READ, kid_read, &nk);
416 sel_addtimer(&sel, &st, &dead, kid_dead, &nk);
417 while (!nk.donep && !sel_select(&sel));
419 /* --- We've finished with it: kill the child process --- *
421 * This is morally questionable. On the other hand, I don't want to be
422 * held up in the @waitpid@ call if I can possibly help it. Maybe a
423 * double-fork is worth doing here.
434 /* --- @noise_freewheel@ --- *
436 * Arguments: @rand_pool *r@ = pointer to a randomness pool
438 * Returns: Nonzero if some randomness was contributed.
440 * Use: Runs a free counter for a short while as a desparate attempt
441 * to get randomness from somewhere. This is actually quite
447 static sigjmp_buf fwjmp;
449 static void fwalarm(int sig)
451 siglongjmp(fwjmp, 1);
454 int noise_freewheel(rand_pool *r)
456 void (*sigal)(int) = 0;
457 struct itimerval oitv, itv = { { 0, 0 }, { 0, 5000 } };
459 volatile uint32 fwcount = 0;
461 if (!sigsetjmp(fwjmp, 1)) {
462 if ((sigal = signal(SIGALRM, fwalarm)) == SIG_ERR)
464 if (setitimer(ITIMER_REAL, &itv, &oitv))
470 STORE32(buf, fwcount);
471 rand_add(r, buf, sizeof(buf), 16);
476 signal(SIGALRM, sigal);
477 if (oitv.it_value.tv_sec || oitv.it_value.tv_usec)
478 TV_SUB(&oitv.it_value, &oitv.it_value, &itv.it_value);
479 setitimer(ITIMER_REAL, &oitv, 0);
485 int noise_freewheel(rand_pool *r)
492 /* --- @noise_enquire@ --- *
494 * Arguments: @rand_pool *r@ = pointer to a randomness pool
496 * Returns: Nonzero if some randomness was contributed.
498 * Use: Runs some shell commands to enquire about the prevailing
499 * environment. This can gather quite a lot of low-quality
503 int noise_enquire(rand_pool *r)
509 { "ps alxww || ps -elf", 16 },
511 { "ifconfig -a", 8 },
514 { "ls -align /tmp/.", 10 },
519 for (i = 0; tab[i].cmd; i++)
520 noise_filter(r, tab[i].rate, tab[i].cmd);
524 /* --- @noise_acquire@ --- *
526 * Arguments: @rand_pool *r@ = pointer to a randomness pool
530 * Use: Acquires some randomness from somewhere.
533 void noise_acquire(rand_pool *r)
536 for (i = 0; i < 8; i++)
538 if (!noise_devrandom(r) || getenv("CATACOMB_FORCE_ESOTERIC_SOURCES")) {
540 for (i = 0; i < 8; i++)
545 /*----- That's all, folks -------------------------------------------------*/