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