Generic interface.
[u/mdw/catacomb] / noise.c
CommitLineData
d03ab969 1/* -*-c-*-
2 *
178220b3 3 * $Id: noise.c,v 1.2 1999/11/11 00:59:08 mdw Exp $
d03ab969 4 *
5 * Acquisition of environmental noise (Unix specific)
6 *
7 * (c) 1998 Straylight/Edgeware
8 */
9
10/*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of Catacomb.
13 *
14 * Catacomb is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU Library General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
18 *
19 * Catacomb is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Library General Public License for more details.
23 *
24 * You should have received a copy of the GNU Library General Public
25 * License along with Catacomb; if not, write to the Free
26 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27 * MA 02111-1307, USA.
28 */
29
30/*----- Revision history --------------------------------------------------*
31 *
32 * $Log: noise.c,v $
178220b3 33 * Revision 1.2 1999/11/11 00:59:08 mdw
34 * A bit of reformatting. Initialize the uid and gid correctly.
35 *
d03ab969 36 * Revision 1.1 1999/09/03 08:41:12 mdw
37 * Initial import.
38 *
39 */
40
41/*----- Header files ------------------------------------------------------*/
42
178220b3 43#include "config.h"
d03ab969 44
45#include <stdio.h>
46#include <string.h>
47#include <signal.h>
48
49#include <sys/types.h>
50#include <sys/time.h>
51#include <sys/wait.h>
52
53#include <fcntl.h>
54#include <unistd.h>
55
56#ifdef HAVE_SETGROUPS
57# include <grp.h>
58#endif
59
60#include <mLib/bits.h>
61#include <mLib/tv.h>
62
63#include "noise.h"
64#include "paranoia.h"
65#include "rand.h"
66
67/*----- Magical numbers ---------------------------------------------------*/
68
69#define NOISE_KIDLIFE 100000 /* @noise_filter@ child lifetime */
70#define MILLION 1000000 /* One million */
71
72/*----- Noise source definition -------------------------------------------*/
73
74rand_source noise_source = { noise_acquire, noise_timer };
75
76/*----- Static variables --------------------------------------------------*/
77
78/* --- Timer differences --- */
79
80static unsigned long noise_last; /* Last time recorded */
81static unsigned long noise_diff; /* Last first order difference */
82
83/* --- Setuid program handling --- */
84
178220b3 85static uid_t noise_uid = NOISE_NOSETUID; /* Uid to set to spawn processes */
86static gid_t noise_gid = NOISE_NOSETGID; /* Gid to set to spawn processes */
d03ab969 87
88/*----- Main code ---------------------------------------------------------*/
89
90/* --- @bitcount@ --- *
91 *
92 * Arguments: @unsigned long x@ = a word containing bits
93 *
94 * Returns: The number of bits set in the word.
95 */
96
97static int bitcount(unsigned long x)
98{
99 char ctab[] = { 0, 1, 1, 2, 1, 2, 2, 3,
100 1, 2, 2, 3, 2, 3, 3, 4 };
101 int count = 0;
102 while (x) {
103 count += ctab[x & 0xfu];
104 x >>= 4;
105 }
106 return (count);
107}
108
109/* --- @timer@ --- *
110 *
111 * Arguments: @rand_pool *r@ = pointer to randomness pool
112 * @struct timeval *tv@ = pointer to time block
113 *
114 * Returns: Nonzer if some randomness was contributed.
115 *
116 * Use: Low-level timer contributor.
117 */
118
119static int timer(rand_pool *r, struct timeval *tv)
120{
121 unsigned long x, d, dd;
122 int de, dde;
123 int ret;
124
125 x = tv->tv_usec + MILLION * tv->tv_sec;
126 d = x ^ noise_last;
127 dd = d ^ noise_diff;
128 noise_diff = d;
129 de = bitcount(d);
130 dde = bitcount(dd);
131 rand_add(r, tv, sizeof(*tv), de <= dde ? de : dde);
132 ret = (de || dde);
133 BURN(tv); x = d = dd = de = dde = 0;
134 return (ret);
135}
136
137/* --- @noise_timer@ --- *
138 *
139 * Arguments: @rand_pool *r@ = pointer to a randomness pool
140 *
141 * Returns: Nonzero if some randomness was contributed.
142 *
143 * Use: Contributes the current time to the randomness pool.
144 * A guess at the number of useful bits contributed is made,
145 * based on first and second order bit differences. This isn't
146 * ever-so reliable, but it's better than nothing.
147 */
148
149int noise_timer(rand_pool *r)
150{
151 struct timeval tv;
152 gettimeofday(&tv, 0);
153 return (timer(r, &tv));
154}
155
156/* --- @noise_devrandom@ --- *
157 *
158 * Arguments: @rand_pool *r@ = pointer to a randomness pool
159 *
160 * Returns: Nonzero if some randomness was contributed.
161 *
162 * Use: Attempts to obtain some randomness from the system entropy
163 * pool. All bits from the device are assumed to be good.
164 */
165
166int noise_devrandom(rand_pool *r)
167{
168 int fd;
169 octet buf[RAND_POOLSZ];
170 ssize_t len;
171 int ret = 0;
172
173 /* --- Be nice to other clients of the random device --- *
174 *
175 * Attempt to open the device nonblockingly. If that works, take up to
176 * one bufferful and then close again. If there's no data to be read,
177 * then that's tough and we go away again, on the grounds that the device
178 * needs to get some more entropy from somewhere.
179 */
180
181 if ((fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) >= 0) {
182 if ((len = read(fd, buf, sizeof(buf))) > 0) {
183 rand_add(r, buf, len, len * 8);
184 BURN(buf);
185 ret = 1;
186 }
187 close(fd);
188 }
189 noise_timer(r);
190 return (ret);
191}
192
193/* --- @noise_setid@ --- *
194 *
195 * Arguments: @uid_t uid@ = uid to set
196 * @gid_t gid@ = gid to set
197 *
198 * Returns: ---
199 *
200 * Use: Sets the user and group ids to be used by @noise_filter@
201 * when running child processes. This is useful to avoid
202 * giving shell commands (even carefully written ones) undue
203 * privileges.
204 */
205
206void noise_setid(uid_t uid, gid_t gid)
207{
208 noise_uid = uid;
209 noise_gid = gid;
210}
211
212/* --- @noise_filter@ --- *
213 *
214 * Arguments: @rand_pool *r@ = pointer to a randomness pool
215 * @int good@ = number of good bits per 1024 bits
216 * @const char *c@ = shell command to run
217 *
218 * Returns: Nonzero if some randomness was contributed.
219 *
220 * Use: Attempts to execute a shell command, and dump it into the
221 * randomness pool. A very rough estimate of the number of
222 * good bits is made, based on the size of the command's output.
223 * This function calls @waitpid@, so be careful. Before execing
224 * the command, the process uid and gid are set to the values
225 * given to @noise_setid@, and an attempt is made to reset the
226 * list of supplementary groups. The environment passed to
227 * the command has been severly lobotimized. If the command
228 * fails to complete within a short time period, it is killed.
229 * Paranoid use of close-on-exec flags for file descriptors is
230 * recommended.
231 */
232
233int noise_filter(rand_pool *r, int good, const char *c)
234{
235 char buf[4096];
236 pid_t kid;
237 int fd[2];
238 struct timeval dead;
239 int ret = 0;
240 const char *env[] = {
241 "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/etc",
242 0
243 };
244
245 /* --- Remember when this business started --- */
246
247 gettimeofday(&dead, 0);
248 timer(r, &dead);
249
250 /* --- Create a pipe --- */
251
252 if (pipe(fd))
253 return (ret);
254
255 /* --- Fork a child off --- */
256
257 kid = fork();
258 if (kid < 0) {
259 close(fd[0]);
260 close(fd[1]);
261 return (ret);
262 }
263
264 /* --- Handle the child end of the deal --- */
265
266 fflush(0);
267 if (kid == 0) {
268 int f;
269
270 /* --- Set the pipe as standard output, close standard input --- */
271
272 close(0); close(1); close(2);
273
274 if (fd[1] != 1) {
275 if (dup2(fd[1], 1) < 0) _exit(127);
276 close(fd[1]);
277 }
278
279 if ((f = open("/dev/null", O_RDONLY)) != 0 ||
280 (f = open("/dev/null", O_WRONLY)) != 2)
281 _exit(127);
282
283 /* --- Play games with uids --- */
284
285 if (noise_gid != NOISE_NOSETGID) {
286 setgid(noise_gid);
287 setegid(noise_gid);
288#ifdef HAVE_SETGROUPS
289 setgroups(1, &noise_gid);
290#endif
291 }
292
293 if (noise_uid != NOISE_NOSETUID) {
294 setuid(noise_uid);
295 seteuid(noise_uid);
296 }
297
298 /* --- Start the process up --- */
299
300 execle("/bin/sh", "-c", c, (char *)0, env);
301 _exit(127);
302 }
303
304 /* --- Sort out my end of the deal --- */
305
306 close(fd[1]);
307
308 /* --- Decide on the deadline --- */
309
310 TV_ADDL(&dead, &dead, 0, NOISE_KIDLIFE);
311
312 /* --- Now read, and think --- */
313
314 for (;;) {
315 struct timeval now, diff;
316 fd_set rd;
317
318 gettimeofday(&now, 0);
319 timer(r, &now);
320 if (TV_CMP(&now, >, &dead))
321 break;
322 TV_SUB(&diff, &dead, &now);
323
324 FD_ZERO(&rd);
325 FD_SET(fd[0], &rd);
326
327 if (select(fd[0] + 1, &rd, 0, 0, &diff) < 0)
328 break;
329 if (FD_ISSET(fd[0], &rd)) {
330 ssize_t sz;
331 int goodbits;
332
333 if ((sz = read(fd[0], buf, sizeof(buf))) <= 0)
334 break;
335 goodbits = (sz * good) / 128;
336 rand_add(r, buf, sz, goodbits);
337 ret = 1;
338 }
339 }
340
341 /* --- We've finished with it: kill the child process --- *
342 *
343 * This is morally questionable. On the other hand, I don't want to be
344 * held up in the @waitpid@ call if I can possibly help it. Maybe a
345 * double-fork is worth doing here.
346 */
347
348 close(fd[0]);
349 BURN(buf);
350 noise_timer(r);
351 kill(kid, SIGKILL);
352 waitpid(kid, 0, 0);
353 return (ret);
354}
355
356/* --- @noise_acquire@ --- *
357 *
358 * Arguments: @rand_pool *r@ = pointer to a randomness pool
359 *
360 * Returns: ---
361 *
362 * Use: Acquires some randomness from somewhere.
363 */
364
365void noise_acquire(rand_pool *r)
366{
367 if (!noise_devrandom(r)) {
368
369 /* --- Output of `ps' --- *
370 *
371 * This is a hopefully cheap way of getting a bit of noise. I'm guessing
372 * the good bit ratio based on about 90 bytes per line of output, and
373 * each line containing maybe 12 bits worth of interesting data. (Some
374 * quick experiments with gzip seem to bear this idea out.) So, 12 good
375 * bits per 90 bytes of output gives slightly more than 17 good bits per
376 * 1024 bits of output. So I'll be a pessimist and say 16 bits.
377 */
378
379 (void)
380 (noise_filter(r, 16, "ps alxww") ||
381 noise_filter(r, 16, "ps -elf"));
382
383 /* --- Output of `netstat' --- *
384 *
385 * Another possibly cheap way of getting noise. My output has about
386 * 72 bytes per line of output. My wild guesses are telling me that
387 * there are probably only about four good bits per line (gzip tells
388 * me there's six, but I want to underestimate). Four bits per 72 bytes
389 * is 7 good bits per 1024 bits of output. Pessimist that I am, I'll
390 * call it six.
391 */
392
393 noise_filter(r, 6, "netstat -n");
394 }
395}
396
397/*----- That's all, folks -------------------------------------------------*/