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