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