rand/noise.c (noise_devrandom): Use new Linux system call `getrandom'.
[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
175
baf5b59c
MW
176#if defined(HAVE_LINUX_RANDOM_H) && \
177 defined(GRND_NONBLOCK) && \
178 defined(SYS_getrandom)
179 /* --- Use the new shinies if available --- */
180
181 while (n < sizeof(buf)) {
182 if ((len = syscall(SYS_getrandom, buf + n, sizeof(buf) - n,
183 GRND_NONBLOCK)) <= 0) {
184 if (errno == ENOSYS) break;
185 else goto done;
186 }
187 n += len;
188 }
189 if (n == sizeof(buf)) goto win;
190#endif
191
ecc296eb
MW
192#ifdef __linux__
193 /* --- Don't take from `/dev/urandom' if `/dev/random' would block --- */
194
195 if ((fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) < 0) goto done;
196 FD_ZERO(&infd);
197 FD_SET(fd, &infd);
198 if (select(fd + 1, &infd, 0, 0, &tv) < 0 || !FD_ISSET(fd, &infd))
199 goto done;
200 close(fd); fd = -1;
201#endif
d03ab969 202
203 /* --- Be nice to other clients of the random device --- *
204 *
205 * Attempt to open the device nonblockingly. If that works, take up to
206 * one bufferful and then close again. If there's no data to be read,
207 * then that's tough and we go away again, on the grounds that the device
208 * needs to get some more entropy from somewhere.
209 */
210
c22fa0c9
MW
211 if (fd >= 0 ||
212 (fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
25f654a7 213 (fd = open("/dev/arandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
214 (fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) >= 0) {
57354275
MW
215 while (n < sizeof(buf)) {
216 if ((len = read(fd, buf + n, sizeof(buf) - n)) <= 0) break;
217 n += len;
d03ab969 218 }
c22fa0c9 219 if (n == sizeof(buf)) goto win;
d03ab969 220 }
c22fa0c9
MW
221 goto done;
222
223win:
224 ret = 1;
225done:
226 if (fd >= 0) close(fd);
227 rand_add(r, buf, n, 8*n);
228 BURN(buf);
d03ab969 229 noise_timer(r);
230 return (ret);
231}
232
233/* --- @noise_setid@ --- *
234 *
235 * Arguments: @uid_t uid@ = uid to set
236 * @gid_t gid@ = gid to set
237 *
238 * Returns: ---
239 *
240 * Use: Sets the user and group ids to be used by @noise_filter@
241 * when running child processes. This is useful to avoid
242 * giving shell commands (even carefully written ones) undue
099355bc 243 * privileges. This interface is Unix-specific
d03ab969 244 */
245
246void noise_setid(uid_t uid, gid_t gid)
247{
248 noise_uid = uid;
249 noise_gid = gid;
250}
251
252/* --- @noise_filter@ --- *
253 *
254 * Arguments: @rand_pool *r@ = pointer to a randomness pool
255 * @int good@ = number of good bits per 1024 bits
256 * @const char *c@ = shell command to run
257 *
258 * Returns: Nonzero if some randomness was contributed.
259 *
260 * Use: Attempts to execute a shell command, and dump it into the
261 * randomness pool. A very rough estimate of the number of
262 * good bits is made, based on the size of the command's output.
263 * This function calls @waitpid@, so be careful. Before execing
264 * the command, the process uid and gid are set to the values
265 * given to @noise_setid@, and an attempt is made to reset the
266 * list of supplementary groups. The environment passed to
267 * the command has been severly lobotimized. If the command
268 * fails to complete within a short time period, it is killed.
269 * Paranoid use of close-on-exec flags for file descriptors is
270 * recommended.
099355bc 271 *
272 * This interface is Unix-specific.
d03ab969 273 */
274
6b837b22
MW
275struct noisekid {
276 rand_pool *r;
277 int good;
278 char buf[4096];
279 int donep;
280 int ret;
281};
282
283static void kid_read(int fd, unsigned mode, void *p)
284{
285 struct noisekid *nk = p;
286 ssize_t sz;
287 int goodbits;
288
289 noise_timer(nk->r);
290 if ((sz = read(fd, nk->buf, sizeof(nk->buf))) <= 0)
291 nk->donep = 1;
292 else {
293 goodbits = (sz * nk->good) / 128;
294 rand_add(nk->r, nk->buf, sz, goodbits);
295 nk->ret = 1;
296 }
297}
298
299static void kid_dead(struct timeval *tv, void *p)
300 { struct noisekid *nk = p; nk->donep = 1; }
301
d03ab969 302int noise_filter(rand_pool *r, int good, const char *c)
303{
d03ab969 304 pid_t kid;
305 int fd[2];
306 struct timeval dead;
307 int ret = 0;
6b837b22
MW
308 struct noisekid nk = { 0 };
309 sel_state sel;
310 sel_file sf;
311 sel_timer st;
d03ab969 312 const char *env[] = {
313 "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/etc",
314 0
315 };
316
317 /* --- Remember when this business started --- */
318
319 gettimeofday(&dead, 0);
320 timer(r, &dead);
321
322 /* --- Create a pipe --- */
323
324 if (pipe(fd))
325 return (ret);
326
327 /* --- Fork a child off --- */
328
028b34c6 329 fflush(0);
d03ab969 330 kid = fork();
331 if (kid < 0) {
332 close(fd[0]);
333 close(fd[1]);
334 return (ret);
335 }
336
337 /* --- Handle the child end of the deal --- */
338
d03ab969 339 if (kid == 0) {
cbc993ef
MW
340 mdup_fd mfd[3];
341 int f, i = 0;
d03ab969 342
343 /* --- Set the pipe as standard output, close standard input --- */
344
cbc993ef
MW
345 if ((f = open("/dev/null", O_RDONLY)) < 0) _exit(127);
346 mfd[i].cur = f; mfd[i].want = 0; i++;
347 mfd[i].cur = fd[1]; mfd[i].want = 1; i++;
348 mfd[i].cur = f; mfd[i].want = 2; i++;
349 if (mdup(mfd, i)) _exit(127);
d03ab969 350
351 /* --- Play games with uids --- */
352
353 if (noise_gid != NOISE_NOSETGID) {
354 setgid(noise_gid);
355 setegid(noise_gid);
356#ifdef HAVE_SETGROUPS
357 setgroups(1, &noise_gid);
358#endif
359 }
360
361 if (noise_uid != NOISE_NOSETUID) {
362 setuid(noise_uid);
363 seteuid(noise_uid);
364 }
365
366 /* --- Start the process up --- */
367
65e14862 368 execle("/bin/sh", "sh", "-c", c, (char *)0, env);
d03ab969 369 _exit(127);
370 }
371
372 /* --- Sort out my end of the deal --- */
373
374 close(fd[1]);
6b837b22
MW
375 sel_init(&sel);
376 nk.r = r; nk.good = good;
d03ab969 377 TV_ADDL(&dead, &dead, 0, NOISE_KIDLIFE);
6b837b22
MW
378 sel_initfile(&sel, &sf, fd[0], SEL_READ, kid_read, &nk);
379 sel_addfile(&sf);
380 sel_addtimer(&sel, &st, &dead, kid_dead, &nk);
381 while (!nk.donep && !sel_select(&sel));
d03ab969 382
383 /* --- We've finished with it: kill the child process --- *
384 *
385 * This is morally questionable. On the other hand, I don't want to be
386 * held up in the @waitpid@ call if I can possibly help it. Maybe a
387 * double-fork is worth doing here.
388 */
389
390 close(fd[0]);
6b837b22 391 BURN(nk.buf);
d03ab969 392 noise_timer(r);
393 kill(kid, SIGKILL);
394 waitpid(kid, 0, 0);
6b837b22 395 return (nk.ret);
d03ab969 396}
397
25f654a7 398/* --- @noise_freewheel@ --- *
399 *
400 * Arguments: @rand_pool *r@ = pointer to a randomness pool
401 *
402 * Returns: Nonzero if some randomness was contributed.
403 *
404 * Use: Runs a free counter for a short while as a desparate attempt
405 * to get randomness from somewhere. This is actually quite
406 * effective.
407 */
408
409#ifdef USE_FREEWHEEL
410
3a5a9d7d 411static sigjmp_buf fwjmp;
25f654a7 412
413static void fwalarm(int sig)
414{
415 siglongjmp(fwjmp, 1);
416}
417
418int noise_freewheel(rand_pool *r)
419{
420 void (*sigal)(int) = 0;
421 struct itimerval oitv, itv = { { 0, 0 }, { 0, 5000 } };
422 int rc = 0;
423 volatile uint32 fwcount = 0;
424
425 if (!sigsetjmp(fwjmp, 1)) {
426 if ((sigal = signal(SIGALRM, fwalarm)) == SIG_ERR)
427 return (0);
428 if (setitimer(ITIMER_REAL, &itv, &oitv))
429 goto done;
430 for (;;)
431 fwcount++;
432 } else {
433 octet buf[4];
434 STORE32(buf, fwcount);
435 rand_add(r, buf, sizeof(buf), 16);
436 rc = 1;
437 }
438
439done:
440 signal(SIGALRM, sigal);
ff98dc94
MW
441 if (oitv.it_value.tv_sec || oitv.it_value.tv_usec)
442 TV_SUB(&oitv.it_value, &oitv.it_value, &itv.it_value);
25f654a7 443 setitimer(ITIMER_REAL, &oitv, 0);
444 return (rc);
445}
446
447#else
448
449int noise_freewheel(rand_pool *r)
450{
451 return (0);
452}
453
454#endif
455
456/* --- @noise_enquire@ --- *
457 *
458 * Arguments: @rand_pool *r@ = pointer to a randomness pool
459 *
460 * Returns: Nonzero if some randomness was contributed.
461 *
462 * Use: Runs some shell commands to enquire about the prevailing
463 * environment. This can gather quite a lot of low-quality
464 * entropy.
465 */
466
467int noise_enquire(rand_pool *r)
468{
469 struct tab {
470 const char *cmd;
471 unsigned rate;
472 } tab[] = {
473 { "ps alxww || ps -elf", 16 },
474 { "netstat -n", 6 },
4108c8d2 475 { "ifconfig -a", 8 },
25f654a7 476 { "df", 20 },
477 { "w", 6 },
478 { "ls -align /tmp/.", 10 },
479 { 0, 0 }
480 };
481 int i;
482
483 for (i = 0; tab[i].cmd; i++)
484 noise_filter(r, tab[i].rate, tab[i].cmd);
485 return (1);
486}
487
d03ab969 488/* --- @noise_acquire@ --- *
489 *
490 * Arguments: @rand_pool *r@ = pointer to a randomness pool
491 *
492 * Returns: ---
493 *
494 * Use: Acquires some randomness from somewhere.
495 */
496
497void noise_acquire(rand_pool *r)
498{
25f654a7 499 unsigned i;
500 for (i = 0; i < 8; i++)
501 noise_freewheel(r);
df40b082 502 if (!noise_devrandom(r) || getenv("CATACOMB_FORCE_ESOTERIC_SOURCES")) {
25f654a7 503 noise_enquire(r);
504 for (i = 0; i < 8; i++)
505 noise_freewheel(r);
d03ab969 506 }
507}
508
509/*----- That's all, folks -------------------------------------------------*/