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