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