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