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