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