chiark / gitweb /
math/{mpbarrett,mpmont}.h: Provide correctness proofs for these methods.
[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 <errno.h>
33 #include <setjmp.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39
40 #include <sys/types.h>
41 #include <sys/time.h>
42 #include <sys/wait.h>
43
44 #include <fcntl.h>
45 #include <unistd.h>
46
47 #ifdef HAVE_SETGROUPS
48 #  include <grp.h>
49 #endif
50
51 #if defined(HAVE_LINUX_RANDOM_H)
52 #  include <linux/random.h>
53 #  include <sys/syscall.h>
54 #endif
55
56 #include <mLib/bits.h>
57 #include <mLib/mdup.h>
58 #include <mLib/sel.h>
59 #include <mLib/tv.h>
60
61 #include "noise.h"
62 #include "paranoia.h"
63 #include "rand.h"
64
65 /*----- Magical numbers ---------------------------------------------------*/
66
67 #define NOISE_KIDLIFE 100000            /* @noise_filter@ child lifetime */
68
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)))
76 #  else
77 #    define GETTIME(tv) (clock_gettime(CLOCK_REALTIME, (tv)))
78 #  endif
79 #  define TOTIMEVAL(tv, xx)                                             \
80         ((tv)->tv_sec = (xx)->tv_sec,                                   \
81          (tv)->tv_usec = ((xx)->tv_nsec + 500)/1000)
82 #else
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))
89 #endif
90
91 /*----- Noise source definition -------------------------------------------*/
92
93 const rand_source noise_source = { noise_acquire, noise_timer };
94
95 /*----- Static variables --------------------------------------------------*/
96
97 /* --- Timer differences --- */
98
99 static unsigned long noise_last;        /* Last time recorded */
100 static unsigned long noise_diff;        /* Last first order difference */
101
102 /* --- Setuid program handling --- */
103
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 */
106
107 /*----- Main code ---------------------------------------------------------*/
108
109 /* --- @bitcount@ --- *
110  *
111  * Arguments:   @unsigned long x@ = a word containing bits
112  *
113  * Returns:     The number of bits set in the word.
114  */
115
116 static int bitcount(unsigned long x)
117 {
118   static const char ctab[] = { 0, 1, 1, 2, 1, 2, 2, 3,
119                                1, 2, 2, 3, 2, 3, 3, 4 };
120   int count = 0;
121   while (x) {
122     count += ctab[x & 0xfu];
123     x >>= 4;
124   }
125   return (count);
126 }
127
128 /* --- @timer@ --- *
129  *
130  * Arguments:   @rand_pool *r@ = pointer to randomness pool
131  *              @const struct TIMESTRUCT *tv@ = pointer to time block
132  *
133  * Returns:     Nonzero if some randomness was contributed.
134  *
135  * Use:         Low-level timer contributor.
136  */
137
138 static int timer(rand_pool *r, const struct TIMESTRUCT *tv)
139 {
140   unsigned long x, d, dd;
141   int de, dde;
142   int ret;
143
144   x = tv->tv_FRAC + TIMERES*tv->tv_SEC;
145   d = x ^ noise_last;
146   dd = d ^ noise_diff;
147   noise_last = x;
148   noise_diff = d;
149   de = bitcount(d);
150   dde = bitcount(dd);
151   rand_add(r, tv, sizeof(*tv), de <= dde ? de : dde);
152   ret = (de || dde);
153   BURN(tv); x = d = dd = de = dde = 0;
154   return (ret);
155 }
156
157 /* --- @noise_timer@ --- *
158  *
159  * Arguments:   @rand_pool *r@ = pointer to a randomness pool
160  *
161  * Returns:     Nonzero if some randomness was contributed.
162  *
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.
167  */
168
169 int noise_timer(rand_pool *r)
170 {
171   struct TIMESTRUCT tv;
172   GETTIME(&tv); return (timer(r, &tv));
173 }
174
175 /* --- @noise_devrandom@ --- *
176  *
177  * Arguments:   @rand_pool *r@ = pointer to a randomness pool
178  *
179  * Returns:     Nonzero if some randomness was contributed.
180  *
181  * Use:         Attempts to obtain some randomness from the system entropy
182  *              pool.  All bits from the device are assumed to be good.
183  */
184
185 int noise_devrandom(rand_pool *r)
186 {
187   int fd = -1;
188   octet buf[RAND_POOLSZ];
189   ssize_t len;
190   size_t n = 0;
191   int ret = 0;
192 #ifdef __linux__
193   fd_set infd;
194   struct timeval tv = { 0, 0 };
195 #endif
196 #ifdef HAVE_GETENTROPY
197   size_t nn;
198 #endif
199
200 #if defined(HAVE_LINUX_RANDOM_H) &&                                     \
201     defined(GRND_NONBLOCK) &&                                           \
202     defined(SYS_getrandom)
203   /* --- Use the new shinies if available --- */
204
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;
209       else goto done;
210     }
211     n += len;
212   }
213   if (n == sizeof(buf)) goto win;
214 #endif
215
216 #ifdef HAVE_GETENTROPY
217   /* --- OpenBSD-flavoured shinies --- */
218
219   while (n < sizeof(buf)) {
220     nn = sizeof(buf) - nn;
221     if (nn > 256) nn = 256;
222     if (getentropy(buf + n, nn)) break;
223     n += nn;
224   }
225   if (n == sizeof(buf)) goto win;
226 #endif
227
228 #ifdef __linux__
229   /* --- Don't take from `/dev/urandom' if `/dev/random' would block --- */
230
231   if ((fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) < 0) goto done;
232   FD_ZERO(&infd);
233   FD_SET(fd, &infd);
234   if (select(fd + 1, &infd, 0, 0, &tv) < 0 || !FD_ISSET(fd, &infd))
235     goto done;
236   close(fd); fd = -1;
237 #endif
238
239   /* --- Be nice to other clients of the random device --- *
240    *
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.
245    */
246
247   if (fd >= 0 ||
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;
253       n += len;
254     }
255     if (n == sizeof(buf)) goto win;
256   }
257   goto done;
258
259 win:
260   ret = 1;
261 done:
262   if (fd >= 0) close(fd);
263   rand_add(r, buf, n, 8*n);
264   BURN(buf);
265   noise_timer(r);
266   return (ret);
267 }
268
269 /* --- @noise_setid@ --- *
270  *
271  * Arguments:   @uid_t uid@ = uid to set
272  *              @gid_t gid@ = gid to set
273  *
274  * Returns:     ---
275  *
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
280  */
281
282 void noise_setid(uid_t uid, gid_t gid)
283 {
284   noise_uid = uid;
285   noise_gid = gid;
286 }
287
288 /* --- @noise_filter@ --- *
289  *
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
293  *
294  * Returns:     Nonzero if some randomness was contributed.
295  *
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
306  *              recommended.
307  *
308  *              This interface is Unix-specific.
309  */
310
311 struct noisekid {
312   rand_pool *r;
313   int good;
314   char buf[4096];
315   int donep;
316   int ret;
317 };
318
319 static void kid_read(int fd, unsigned mode, void *p)
320 {
321   struct noisekid *nk = p;
322   ssize_t sz;
323   int goodbits;
324
325   noise_timer(nk->r);
326   if ((sz = read(fd, nk->buf, sizeof(nk->buf))) <= 0)
327     nk->donep = 1;
328   else {
329     goodbits = (sz * nk->good) / 128;
330     rand_add(nk->r, nk->buf, sz, goodbits);
331     nk->ret = 1;
332   }
333 }
334
335 static void kid_dead(struct timeval *tv, void *p)
336   { struct noisekid *nk = p; nk->donep = 1; }
337
338 int noise_filter(rand_pool *r, int good, const char *c)
339 {
340   pid_t kid;
341   int fd[2];
342   struct timeval dead;
343   struct TIMESTRUCT now;
344   int ret = 0;
345   struct noisekid nk = { 0 };
346   sel_state sel;
347   sel_file sf;
348   sel_timer st;
349   const char *env[] = {
350     "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/etc",
351     0
352   };
353
354   /* --- Remember when this business started --- */
355
356   GETTIME(&now); timer(r, &now);
357   TOTIMEVAL(&dead, &now);
358
359   /* --- Create a pipe --- */
360
361   if (pipe(fd))
362     return (ret);
363
364   /* --- Fork a child off --- */
365
366   fflush(0);
367   kid = fork();
368   if (kid < 0) {
369     close(fd[0]);
370     close(fd[1]);
371     return (ret);
372   }
373
374   /* --- Handle the child end of the deal --- */
375
376   if (kid == 0) {
377     mdup_fd mfd[3];
378     int f, i = 0;
379
380     /* --- Set the pipe as standard output, close standard input --- */
381
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);
387
388     /* --- Play games with uids --- */
389
390     if (noise_gid != NOISE_NOSETGID) {
391       setgid(noise_gid);
392       setegid(noise_gid);
393 #ifdef HAVE_SETGROUPS
394       setgroups(1, &noise_gid);
395 #endif
396     }
397
398     if (noise_uid != NOISE_NOSETUID) {
399       setuid(noise_uid);
400       seteuid(noise_uid);
401     }
402
403     /* --- Start the process up --- */
404
405     execle("/bin/sh", "sh", "-c", c, (char *)0, env);
406     _exit(127);
407   }
408
409   /* --- Sort out my end of the deal --- */
410
411   close(fd[1]);
412   sel_init(&sel);
413   nk.r = r; nk.good = good;
414   TV_ADDL(&dead, &dead, 0, NOISE_KIDLIFE);
415   sel_initfile(&sel, &sf, fd[0], SEL_READ, kid_read, &nk);
416   sel_addfile(&sf);
417   sel_addtimer(&sel, &st, &dead, kid_dead, &nk);
418   while (!nk.donep && !sel_select(&sel));
419
420   /* --- We've finished with it: kill the child process --- *
421    *
422    * This is morally questionable.  On the other hand, I don't want to be
423    * held up in the @waitpid@ call if I can possibly help it.  Maybe a
424    * double-fork is worth doing here.
425    */
426
427   close(fd[0]);
428   BURN(nk.buf);
429   noise_timer(r);
430   kill(kid, SIGKILL);
431   waitpid(kid, 0, 0);
432   return (nk.ret);
433 }
434
435 /* --- @noise_freewheel@ --- *
436  *
437  * Arguments:   @rand_pool *r@ = pointer to a randomness pool
438  *
439  * Returns:     Nonzero if some randomness was contributed.
440  *
441  * Use:         Runs a free counter for a short while as a desparate attempt
442  *              to get randomness from somewhere.  This is actually quite
443  *              effective.
444  */
445
446 #ifdef USE_FREEWHEEL
447
448 static sigjmp_buf fwjmp;
449
450 static void fwalarm(int sig)
451 {
452   siglongjmp(fwjmp, 1);
453 }
454
455 int noise_freewheel(rand_pool *r)
456 {
457   void (*sigal)(int) = 0;
458   struct itimerval oitv, itv = { { 0, 0 }, { 0, 5000 } };
459   int rc = 0;
460   volatile uint32 fwcount = 0;
461
462   if (!sigsetjmp(fwjmp, 1)) {
463     if ((sigal = signal(SIGALRM, fwalarm)) == SIG_ERR)
464       return (0);
465     if (setitimer(ITIMER_REAL, &itv, &oitv))
466       goto done;
467     for (;;)
468       fwcount++;
469   } else {
470     octet buf[4];
471     STORE32(buf, fwcount);
472     rand_add(r, buf, sizeof(buf), 16);
473     rc = 1;
474   }
475
476 done:
477   signal(SIGALRM, sigal);
478   if (oitv.it_value.tv_sec || oitv.it_value.tv_usec)
479     TV_SUB(&oitv.it_value, &oitv.it_value, &itv.it_value);
480   setitimer(ITIMER_REAL, &oitv, 0);
481   return (rc);
482 }
483
484 #else
485
486 int noise_freewheel(rand_pool *r)
487 {
488   return (0);
489 }
490
491 #endif
492
493 /* --- @noise_enquire@ --- *
494  *
495  * Arguments:   @rand_pool *r@ = pointer to a randomness pool
496  *
497  * Returns:     Nonzero if some randomness was contributed.
498  *
499  * Use:         Runs some shell commands to enquire about the prevailing
500  *              environment.  This can gather quite a lot of low-quality
501  *              entropy.
502  */
503
504 int noise_enquire(rand_pool *r)
505 {
506   struct tab {
507     const char *cmd;
508     unsigned rate;
509   } tab[] = {
510     { "ps alxww || ps -elf",    16 },
511     { "netstat -n",              6 },
512     { "ifconfig -a",             8 },
513     { "df",                     20 },
514     { "w",                       6 },
515     { "ls -align /tmp/.",       10 },
516     { 0,                         0 }
517   };
518   int i;
519
520   for (i = 0; tab[i].cmd; i++)
521     noise_filter(r, tab[i].rate, tab[i].cmd);
522   return (1);
523 }
524
525 /* --- @noise_acquire@ --- *
526  *
527  * Arguments:   @rand_pool *r@ = pointer to a randomness pool
528  *
529  * Returns:     ---
530  *
531  * Use:         Acquires some randomness from somewhere.
532  */
533
534 void noise_acquire(rand_pool *r)
535 {
536   unsigned i;
537   for (i = 0; i < 8; i++)
538     noise_freewheel(r);
539   if (!noise_devrandom(r) || getenv("CATACOMB_FORCE_ESOTERIC_SOURCES")) {
540     noise_enquire(r);
541     for (i = 0; i < 8; i++)
542       noise_freewheel(r);
543   }
544 }
545
546 /*----- That's all, folks -------------------------------------------------*/