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