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