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