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