Add support machinery for ARM hosts.
[catacomb] / rand / noise.c
1 /* -*-c-*-
2 *
3 * Acquisition of environmental noise (Unix-specific)
4 *
5 * (c) 1998 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
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.
16 *
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.
21 *
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
28 /*----- Header files ------------------------------------------------------*/
29
30 #include "config.h"
31
32 #include <setjmp.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
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>
50 #include <mLib/mdup.h>
51 #include <mLib/sel.h>
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
65 const rand_source noise_source = { noise_acquire, noise_timer };
66
67 /*----- Static variables --------------------------------------------------*/
68
69 /* --- Timer differences --- */
70
71 static unsigned long noise_last; /* Last time recorded */
72 static unsigned long noise_diff; /* Last first order difference */
73
74 /* --- Setuid program handling --- */
75
76 static uid_t noise_uid = NOISE_NOSETUID; /* Uid to set to spawn processes */
77 static gid_t noise_gid = NOISE_NOSETGID; /* Gid to set to spawn processes */
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
88 static int bitcount(unsigned long x)
89 {
90 char ctab[] = { 0, 1, 1, 2, 1, 2, 2, 3,
91 1, 2, 2, 3, 2, 3, 3, 4 };
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 *
105 * Returns: Nonzero if some randomness was contributed.
106 *
107 * Use: Low-level timer contributor.
108 */
109
110 static int timer(rand_pool *r, struct timeval *tv)
111 {
112 unsigned long x, d, dd;
113 int de, dde;
114 int ret;
115
116 x = tv->tv_usec + MILLION * tv->tv_sec;
117 d = x ^ noise_last;
118 dd = d ^ noise_diff;
119 noise_last = x;
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
141 int 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
158 int noise_devrandom(rand_pool *r)
159 {
160 int fd;
161 octet buf[RAND_POOLSZ];
162 ssize_t len;
163 size_t n = 0;
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
174 if ((fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
175 (fd = open("/dev/arandom", O_RDONLY | O_NONBLOCK)) >= 0 ||
176 (fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) >= 0) {
177 while (n < sizeof(buf)) {
178 if ((len = read(fd, buf + n, sizeof(buf) - n)) <= 0) break;
179 n += len;
180 }
181 rand_add(r, buf, n, n * 8);
182 BURN(buf);
183 if (n == sizeof(buf)) ret = 1;
184 close(fd);
185 }
186 noise_timer(r);
187 return (ret);
188 }
189
190 /* --- @noise_setid@ --- *
191 *
192 * Arguments: @uid_t uid@ = uid to set
193 * @gid_t gid@ = gid to set
194 *
195 * Returns: ---
196 *
197 * Use: Sets the user and group ids to be used by @noise_filter@
198 * when running child processes. This is useful to avoid
199 * giving shell commands (even carefully written ones) undue
200 * privileges. This interface is Unix-specific
201 */
202
203 void noise_setid(uid_t uid, gid_t gid)
204 {
205 noise_uid = uid;
206 noise_gid = gid;
207 }
208
209 /* --- @noise_filter@ --- *
210 *
211 * Arguments: @rand_pool *r@ = pointer to a randomness pool
212 * @int good@ = number of good bits per 1024 bits
213 * @const char *c@ = shell command to run
214 *
215 * Returns: Nonzero if some randomness was contributed.
216 *
217 * Use: Attempts to execute a shell command, and dump it into the
218 * randomness pool. A very rough estimate of the number of
219 * good bits is made, based on the size of the command's output.
220 * This function calls @waitpid@, so be careful. Before execing
221 * the command, the process uid and gid are set to the values
222 * given to @noise_setid@, and an attempt is made to reset the
223 * list of supplementary groups. The environment passed to
224 * the command has been severly lobotimized. If the command
225 * fails to complete within a short time period, it is killed.
226 * Paranoid use of close-on-exec flags for file descriptors is
227 * recommended.
228 *
229 * This interface is Unix-specific.
230 */
231
232 struct noisekid {
233 rand_pool *r;
234 int good;
235 char buf[4096];
236 int donep;
237 int ret;
238 };
239
240 static void kid_read(int fd, unsigned mode, void *p)
241 {
242 struct noisekid *nk = p;
243 ssize_t sz;
244 int goodbits;
245
246 noise_timer(nk->r);
247 if ((sz = read(fd, nk->buf, sizeof(nk->buf))) <= 0)
248 nk->donep = 1;
249 else {
250 goodbits = (sz * nk->good) / 128;
251 rand_add(nk->r, nk->buf, sz, goodbits);
252 nk->ret = 1;
253 }
254 }
255
256 static void kid_dead(struct timeval *tv, void *p)
257 { struct noisekid *nk = p; nk->donep = 1; }
258
259 int noise_filter(rand_pool *r, int good, const char *c)
260 {
261 pid_t kid;
262 int fd[2];
263 struct timeval dead;
264 int ret = 0;
265 struct noisekid nk = { 0 };
266 sel_state sel;
267 sel_file sf;
268 sel_timer st;
269 const char *env[] = {
270 "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/etc",
271 0
272 };
273
274 /* --- Remember when this business started --- */
275
276 gettimeofday(&dead, 0);
277 timer(r, &dead);
278
279 /* --- Create a pipe --- */
280
281 if (pipe(fd))
282 return (ret);
283
284 /* --- Fork a child off --- */
285
286 fflush(0);
287 kid = fork();
288 if (kid < 0) {
289 close(fd[0]);
290 close(fd[1]);
291 return (ret);
292 }
293
294 /* --- Handle the child end of the deal --- */
295
296 if (kid == 0) {
297 mdup_fd mfd[3];
298 int f, i = 0;
299
300 /* --- Set the pipe as standard output, close standard input --- */
301
302 if ((f = open("/dev/null", O_RDONLY)) < 0) _exit(127);
303 mfd[i].cur = f; mfd[i].want = 0; i++;
304 mfd[i].cur = fd[1]; mfd[i].want = 1; i++;
305 mfd[i].cur = f; mfd[i].want = 2; i++;
306 if (mdup(mfd, i)) _exit(127);
307
308 /* --- Play games with uids --- */
309
310 if (noise_gid != NOISE_NOSETGID) {
311 setgid(noise_gid);
312 setegid(noise_gid);
313 #ifdef HAVE_SETGROUPS
314 setgroups(1, &noise_gid);
315 #endif
316 }
317
318 if (noise_uid != NOISE_NOSETUID) {
319 setuid(noise_uid);
320 seteuid(noise_uid);
321 }
322
323 /* --- Start the process up --- */
324
325 execle("/bin/sh", "sh", "-c", c, (char *)0, env);
326 _exit(127);
327 }
328
329 /* --- Sort out my end of the deal --- */
330
331 close(fd[1]);
332 sel_init(&sel);
333 nk.r = r; nk.good = good;
334 TV_ADDL(&dead, &dead, 0, NOISE_KIDLIFE);
335 sel_initfile(&sel, &sf, fd[0], SEL_READ, kid_read, &nk);
336 sel_addfile(&sf);
337 sel_addtimer(&sel, &st, &dead, kid_dead, &nk);
338 while (!nk.donep && !sel_select(&sel));
339
340 /* --- We've finished with it: kill the child process --- *
341 *
342 * This is morally questionable. On the other hand, I don't want to be
343 * held up in the @waitpid@ call if I can possibly help it. Maybe a
344 * double-fork is worth doing here.
345 */
346
347 close(fd[0]);
348 BURN(nk.buf);
349 noise_timer(r);
350 kill(kid, SIGKILL);
351 waitpid(kid, 0, 0);
352 return (nk.ret);
353 }
354
355 /* --- @noise_freewheel@ --- *
356 *
357 * Arguments: @rand_pool *r@ = pointer to a randomness pool
358 *
359 * Returns: Nonzero if some randomness was contributed.
360 *
361 * Use: Runs a free counter for a short while as a desparate attempt
362 * to get randomness from somewhere. This is actually quite
363 * effective.
364 */
365
366 #ifdef USE_FREEWHEEL
367
368 static jmp_buf fwjmp;
369
370 static void fwalarm(int sig)
371 {
372 siglongjmp(fwjmp, 1);
373 }
374
375 int noise_freewheel(rand_pool *r)
376 {
377 void (*sigal)(int) = 0;
378 struct itimerval oitv, itv = { { 0, 0 }, { 0, 5000 } };
379 int rc = 0;
380 volatile uint32 fwcount = 0;
381
382 if (!sigsetjmp(fwjmp, 1)) {
383 if ((sigal = signal(SIGALRM, fwalarm)) == SIG_ERR)
384 return (0);
385 if (setitimer(ITIMER_REAL, &itv, &oitv))
386 goto done;
387 for (;;)
388 fwcount++;
389 } else {
390 octet buf[4];
391 STORE32(buf, fwcount);
392 rand_add(r, buf, sizeof(buf), 16);
393 rc = 1;
394 }
395
396 done:
397 signal(SIGALRM, sigal);
398 if (oitv.it_value.tv_sec || oitv.it_value.tv_usec)
399 TV_SUB(&oitv.it_value, &oitv.it_value, &itv.it_value);
400 setitimer(ITIMER_REAL, &oitv, 0);
401 return (rc);
402 }
403
404 #else
405
406 int noise_freewheel(rand_pool *r)
407 {
408 return (0);
409 }
410
411 #endif
412
413 /* --- @noise_enquire@ --- *
414 *
415 * Arguments: @rand_pool *r@ = pointer to a randomness pool
416 *
417 * Returns: Nonzero if some randomness was contributed.
418 *
419 * Use: Runs some shell commands to enquire about the prevailing
420 * environment. This can gather quite a lot of low-quality
421 * entropy.
422 */
423
424 int noise_enquire(rand_pool *r)
425 {
426 struct tab {
427 const char *cmd;
428 unsigned rate;
429 } tab[] = {
430 { "ps alxww || ps -elf", 16 },
431 { "netstat -n", 6 },
432 { "ifconfig -a", 8 },
433 { "df", 20 },
434 { "w", 6 },
435 { "ls -align /tmp/.", 10 },
436 { 0, 0 }
437 };
438 int i;
439
440 for (i = 0; tab[i].cmd; i++)
441 noise_filter(r, tab[i].rate, tab[i].cmd);
442 return (1);
443 }
444
445 /* --- @noise_acquire@ --- *
446 *
447 * Arguments: @rand_pool *r@ = pointer to a randomness pool
448 *
449 * Returns: ---
450 *
451 * Use: Acquires some randomness from somewhere.
452 */
453
454 void noise_acquire(rand_pool *r)
455 {
456 unsigned i;
457 for (i = 0; i < 8; i++)
458 noise_freewheel(r);
459 if (!noise_devrandom(r) || getenv("CATACOMB_FORCE_ESOTERIC_SOURCES")) {
460 noise_enquire(r);
461 for (i = 0; i < 8; i++)
462 noise_freewheel(r);
463 }
464 }
465
466 /*----- That's all, folks -------------------------------------------------*/