blob: 83759ca657413e11b9bffaba3876776b78844f96 [file] [log] [blame]
Damien Miller040f3832000-04-03 14:50:43 +10001/*
2 * Copyright (c) 2000 Damien Miller. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. All advertising materials mentioning features or use of this software
13 * must display the following acknowledgement:
14 * This product includes software developed by Markus Friedl.
15 * 4. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#include "includes.h"
31
32#include "ssh.h"
33#include "xmalloc.h"
34
Damien Miller5f056372000-04-16 12:31:48 +100035#include <openssl/rand.h>
36#include <openssl/sha.h>
Damien Miller040f3832000-04-03 14:50:43 +100037
Damien Miller64681252000-06-26 13:01:33 +100038RCSID("$Id: entropy.c,v 1.15 2000/06/26 03:01:33 djm Exp $");
Damien Miller040f3832000-04-03 14:50:43 +100039
Damien Miller040f3832000-04-03 14:50:43 +100040#ifndef offsetof
41# define offsetof(type, member) ((size_t) &((type *)0)->member)
42#endif
Damien Miller14c12cb2000-06-07 22:20:23 +100043
44/* Print lots of detail */
45/* #define DEBUG_ENTROPY */
46
47/* Number of times to pass through command list gathering entropy */
48#define NUM_ENTROPY_RUNS 1
49
50/* Scale entropy estimates back by this amount on subsequent runs */
51#define SCALE_PER_RUN 10.0
52
53/* Minimum number of commands to be considered valid */
54#define MIN_ENTROPY_SOURCES 16
55
56#define WHITESPACE " \t\n"
57
Damien Miller7b22d652000-06-18 14:07:04 +100058#ifndef RUSAGE_SELF
59# define RUSAGE_SELF 0
60#endif
61#ifndef RUSAGE_CHILDREN
62# define RUSAGE_CHILDREN 0
63#endif
64
Damien Miller14c12cb2000-06-07 22:20:23 +100065#if defined(EGD_SOCKET) || defined(RANDOM_POOL)
66
67#ifdef EGD_SOCKET
Damien Miller040f3832000-04-03 14:50:43 +100068/* Collect entropy from EGD */
Damien Miller64681252000-06-26 13:01:33 +100069int get_random_bytes(unsigned char *buf, int len)
Damien Miller040f3832000-04-03 14:50:43 +100070{
Damien Miller64681252000-06-26 13:01:33 +100071 int fd;
72 char msg[2];
Damien Miller040f3832000-04-03 14:50:43 +100073 struct sockaddr_un addr;
74 int addr_len;
75
Damien Miller64681252000-06-26 13:01:33 +100076 /* Sanity checks */
Damien Miller040f3832000-04-03 14:50:43 +100077 if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
78 fatal("Random pool path is too long");
Damien Miller040f3832000-04-03 14:50:43 +100079 if (len > 255)
80 fatal("Too many bytes to read from EGD");
Damien Miller64681252000-06-26 13:01:33 +100081
82 memset(&addr, '\0', sizeof(addr));
83 addr.sun_family = AF_UNIX;
84 strlcpy(addr.sun_path, EGD_SOCKET, sizeof(addr.sun_path));
85 addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
Damien Miller040f3832000-04-03 14:50:43 +100086
Damien Miller64681252000-06-26 13:01:33 +100087 fd = socket(AF_UNIX, SOCK_STREAM, 0);
88 if (fd == -1) {
89 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
90 return(0);
91 }
92
93 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
94 error("Couldn't connect to EGD socket \"%s\": %s",
95 addr.sun_path, strerror(errno));
96 close(fd);
97 return(0);
98 }
99
Damien Miller040f3832000-04-03 14:50:43 +1000100 /* Send blocking read request to EGD */
Damien Miller64681252000-06-26 13:01:33 +1000101 msg[0] = 0x02;
102 msg[1] = len;
Damien Miller040f3832000-04-03 14:50:43 +1000103
Damien Miller64681252000-06-26 13:01:33 +1000104 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
105 error("Couldn't write to EGD socket \"%s\": %s",
106 EGD_SOCKET, strerror(errno));
107 close(fd);
108 return(0);
109 }
Damien Miller040f3832000-04-03 14:50:43 +1000110
Damien Miller64681252000-06-26 13:01:33 +1000111 if (atomicio(read, fd, buf, len) != len) {
112 error("Couldn't read from EGD socket \"%s\": %s",
113 EGD_SOCKET, strerror(errno));
114 close(fd);
115 return(0);
116 }
117
118 close(fd);
119
120 return(1);
Damien Miller040f3832000-04-03 14:50:43 +1000121}
122#else /* !EGD_SOCKET */
123#ifdef RANDOM_POOL
124/* Collect entropy from /dev/urandom or pipe */
Damien Miller64681252000-06-26 13:01:33 +1000125int get_random_bytes(unsigned char *buf, int len)
Damien Miller040f3832000-04-03 14:50:43 +1000126{
Damien Miller64681252000-06-26 13:01:33 +1000127 int random_pool;
Damien Miller040f3832000-04-03 14:50:43 +1000128
Damien Miller64681252000-06-26 13:01:33 +1000129 random_pool = open(RANDOM_POOL, O_RDONLY);
Damien Miller040f3832000-04-03 14:50:43 +1000130 if (random_pool == -1) {
Damien Miller64681252000-06-26 13:01:33 +1000131 error("Couldn't open random pool \"%s\": %s",
132 RANDOM_POOL, strerror(errno));
133 return(0);
Damien Miller040f3832000-04-03 14:50:43 +1000134 }
135
Damien Miller64681252000-06-26 13:01:33 +1000136 if (atomicio(read, random_pool, buf, len) != len) {
137 error("Couldn't read from random pool \"%s\": %s",
138 RANDOM_POOL, strerror(errno));
139 close(random_pool);
140 return(0);
141 }
142
143 close(random_pool);
144
145 return(1);
Damien Miller040f3832000-04-03 14:50:43 +1000146}
147#endif /* RANDOM_POOL */
148#endif /* EGD_SOCKET */
149
Damien Miller14c12cb2000-06-07 22:20:23 +1000150/*
151 * Seed OpenSSL's random number pool from Kernel random number generator
152 * or EGD
153 */
154void
155seed_rng(void)
156{
157 char buf[32];
158
159 debug("Seeding random number generator");
Damien Miller64681252000-06-26 13:01:33 +1000160
161 if (!get_random_bytes(buf, sizeof(buf)) && !RAND_status())
162 fatal("Entropy collection failed and entropy exhausted");
163
Damien Miller14c12cb2000-06-07 22:20:23 +1000164 RAND_add(buf, sizeof(buf), sizeof(buf));
Damien Miller64681252000-06-26 13:01:33 +1000165
Damien Miller14c12cb2000-06-07 22:20:23 +1000166 memset(buf, '\0', sizeof(buf));
167}
168
169#else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
170
Damien Miller040f3832000-04-03 14:50:43 +1000171/*
172 * FIXME: proper entropy estimations. All current values are guesses
Damien Miller4018c192000-04-30 09:30:44 +1000173 * FIXME: (ATL) do estimates at compile time?
Damien Miller040f3832000-04-03 14:50:43 +1000174 * FIXME: More entropy sources
175 */
176
Damien Miller4018c192000-04-30 09:30:44 +1000177/* slow command timeouts (all in milliseconds) */
178/* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
179static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
180
181static int prng_seed_loaded = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000182static int prng_seed_saved = 0;
183static int prng_commands_loaded = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000184
185typedef struct
186{
187 /* Proportion of data that is entropy */
188 double rate;
Damien Miller4018c192000-04-30 09:30:44 +1000189 /* Counter goes positive if this command times out */
190 unsigned int badness;
191 /* Increases by factor of two each timeout */
192 unsigned int sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000193 /* Path to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000194 char *path;
Damien Miller040f3832000-04-03 14:50:43 +1000195 /* argv to pass to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000196 char *args[5];
Damien Miller8d1fd572000-05-17 21:34:07 +1000197 /* full command string (debug) */
198 char *cmdstring;
Damien Miller040f3832000-04-03 14:50:43 +1000199} entropy_source_t;
200
Damien Miller4018c192000-04-30 09:30:44 +1000201double stir_from_system(void);
202double stir_from_programs(void);
203double stir_gettimeofday(double entropy_estimate);
204double stir_clock(double entropy_estimate);
205double stir_rusage(int who, double entropy_estimate);
206double hash_output_from_command(entropy_source_t *src, char *hash);
207
Damien Miller0437b332000-05-02 09:56:41 +1000208/* this is initialised from a file, by prng_read_commands() */
209entropy_source_t *entropy_sources = NULL;
Damien Miller040f3832000-04-03 14:50:43 +1000210
Damien Miller040f3832000-04-03 14:50:43 +1000211double
212stir_from_system(void)
213{
214 double total_entropy_estimate;
215 long int i;
216
217 total_entropy_estimate = 0;
218
219 i = getpid();
Damien Miller7b22d652000-06-18 14:07:04 +1000220 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000221 total_entropy_estimate += 0.1;
222
223 i = getppid();
Damien Miller7b22d652000-06-18 14:07:04 +1000224 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000225 total_entropy_estimate += 0.1;
226
227 i = getuid();
228 RAND_add(&i, sizeof(i), 0.0);
229 i = getgid();
230 RAND_add(&i, sizeof(i), 0.0);
231
232 total_entropy_estimate += stir_gettimeofday(1.0);
Damien Miller7b22d652000-06-18 14:07:04 +1000233 total_entropy_estimate += stir_clock(0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000234 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
235
236 return(total_entropy_estimate);
237}
238
239double
240stir_from_programs(void)
241{
242 int i;
243 int c;
244 double entropy_estimate;
245 double total_entropy_estimate;
246 char hash[SHA_DIGEST_LENGTH];
247
Damien Miller040f3832000-04-03 14:50:43 +1000248 total_entropy_estimate = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000249 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
Damien Miller040f3832000-04-03 14:50:43 +1000250 c = 0;
251 while (entropy_sources[c].path != NULL) {
Damien Miller040f3832000-04-03 14:50:43 +1000252
Damien Miller4018c192000-04-30 09:30:44 +1000253 if (!entropy_sources[c].badness) {
254 /* Hash output from command */
255 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
256
257 /* Scale back entropy estimate according to command's rate */
258 entropy_estimate *= entropy_sources[c].rate;
Damien Miller040f3832000-04-03 14:50:43 +1000259
Damien Miller4018c192000-04-30 09:30:44 +1000260 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
261 if (entropy_estimate > SHA_DIGEST_LENGTH)
262 entropy_estimate = SHA_DIGEST_LENGTH;
Damien Miller040f3832000-04-03 14:50:43 +1000263
Damien Miller14c12cb2000-06-07 22:20:23 +1000264 /* Scale back estimates for subsequent passes through list */
265 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
Damien Miller040f3832000-04-03 14:50:43 +1000266
Damien Miller4018c192000-04-30 09:30:44 +1000267 /* Stir it in */
268 RAND_add(hash, sizeof(hash), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000269
Damien Miller14c12cb2000-06-07 22:20:23 +1000270#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000271 debug("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
272 entropy_sources[c].cmdstring);
Damien Miller040f3832000-04-03 14:50:43 +1000273#endif
274
Damien Miller4018c192000-04-30 09:30:44 +1000275 total_entropy_estimate += entropy_estimate;
Damien Miller040f3832000-04-03 14:50:43 +1000276
277 /* Execution times should be a little unpredictable */
Damien Miller4018c192000-04-30 09:30:44 +1000278 total_entropy_estimate += stir_gettimeofday(0.05);
279 total_entropy_estimate += stir_clock(0.05);
280 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
281 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
282 } else {
Damien Miller14c12cb2000-06-07 22:20:23 +1000283#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000284 debug("Command '%s' disabled (badness %d)",
285 entropy_sources[c].cmdstring, entropy_sources[c].badness);
Damien Miller4018c192000-04-30 09:30:44 +1000286#endif
287
288 if (entropy_sources[c].badness > 0)
289 entropy_sources[c].badness--;
290 }
291
Damien Miller040f3832000-04-03 14:50:43 +1000292 c++;
293 }
294 }
295
296 return(total_entropy_estimate);
297}
298
299double
300stir_gettimeofday(double entropy_estimate)
301{
302 struct timeval tv;
303
304 if (gettimeofday(&tv, NULL) == -1)
305 fatal("Couldn't gettimeofday: %s", strerror(errno));
306
307 RAND_add(&tv, sizeof(tv), entropy_estimate);
308
309 return(entropy_estimate);
310}
311
312double
313stir_clock(double entropy_estimate)
314{
315#ifdef HAVE_CLOCK
316 clock_t c;
317
318 c = clock();
319 RAND_add(&c, sizeof(c), entropy_estimate);
320
321 return(entropy_estimate);
322#else /* _HAVE_CLOCK */
323 return(0);
324#endif /* _HAVE_CLOCK */
325}
326
327double
328stir_rusage(int who, double entropy_estimate)
329{
330#ifdef HAVE_GETRUSAGE
331 struct rusage ru;
332
Damien Miller4018c192000-04-30 09:30:44 +1000333 if (getrusage(who, &ru) == -1)
Damien Miller7b22d652000-06-18 14:07:04 +1000334 return(0);
Damien Miller040f3832000-04-03 14:50:43 +1000335
Damien Miller7b22d652000-06-18 14:07:04 +1000336 RAND_add(&ru, sizeof(ru), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000337
338 return(entropy_estimate);
339#else /* _HAVE_GETRUSAGE */
340 return(0);
341#endif /* _HAVE_GETRUSAGE */
342}
343
Damien Miller8d1fd572000-05-17 21:34:07 +1000344
345static
346int
347_get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
348 int secdiff, usecdiff;
349
350 secdiff = t2->tv_sec - t1->tv_sec;
351 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
352 return (int)(usecdiff / 1000);
353}
354
Damien Miller040f3832000-04-03 14:50:43 +1000355double
Damien Miller4018c192000-04-30 09:30:44 +1000356hash_output_from_command(entropy_source_t *src, char *hash)
Damien Miller040f3832000-04-03 14:50:43 +1000357{
358 static int devnull = -1;
359 int p[2];
Damien Miller4018c192000-04-30 09:30:44 +1000360 fd_set rdset;
361 int cmd_eof = 0, error_abort = 0;
Damien Miller8d1fd572000-05-17 21:34:07 +1000362 struct timeval tv_start, tv_current;
363 int msec_elapsed = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000364 pid_t pid;
365 int status;
Damien Miller8d1fd572000-05-17 21:34:07 +1000366 char buf[16384];
Damien Miller040f3832000-04-03 14:50:43 +1000367 int bytes_read;
368 int total_bytes_read;
369 SHA_CTX sha;
370
371 if (devnull == -1) {
372 devnull = open("/dev/null", O_RDWR);
373 if (devnull == -1)
374 fatal("Couldn't open /dev/null: %s", strerror(errno));
375 }
376
377 if (pipe(p) == -1)
378 fatal("Couldn't open pipe: %s", strerror(errno));
379
Damien Miller8d1fd572000-05-17 21:34:07 +1000380 (void)gettimeofday(&tv_start, NULL); /* record start time */
381
Damien Miller040f3832000-04-03 14:50:43 +1000382 switch (pid = fork()) {
383 case -1: /* Error */
384 close(p[0]);
385 close(p[1]);
386 fatal("Couldn't fork: %s", strerror(errno));
387 /* NOTREACHED */
388 case 0: /* Child */
Damien Miller4018c192000-04-30 09:30:44 +1000389 dup2(devnull, STDIN_FILENO);
390 dup2(p[1], STDOUT_FILENO);
391 dup2(p[1], STDERR_FILENO);
Damien Miller040f3832000-04-03 14:50:43 +1000392 close(p[0]);
393 close(p[1]);
394 close(devnull);
395
Damien Miller4018c192000-04-30 09:30:44 +1000396 execv(src->path, (char**)(src->args));
Damien Miller8d1fd572000-05-17 21:34:07 +1000397 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
398 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000399 src->badness = src->sticky_badness = 128;
Damien Miller040f3832000-04-03 14:50:43 +1000400 _exit(-1);
401 default: /* Parent */
402 break;
403 }
404
405 RAND_add(&pid, sizeof(&pid), 0.0);
406
407 close(p[1]);
408
409 /* Hash output from child */
410 SHA1_Init(&sha);
411 total_bytes_read = 0;
Damien Miller4018c192000-04-30 09:30:44 +1000412
413 while (!error_abort && !cmd_eof) {
414 int ret;
415 struct timeval tv;
Damien Miller8d1fd572000-05-17 21:34:07 +1000416 int msec_remaining;
417
418 (void) gettimeofday(&tv_current, 0);
Damien Miller14c12cb2000-06-07 22:20:23 +1000419 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
Damien Miller8d1fd572000-05-17 21:34:07 +1000420 if (msec_elapsed >= entropy_timeout_current) {
421 error_abort=1;
422 continue;
423 }
424 msec_remaining = entropy_timeout_current - msec_elapsed;
Damien Miller4018c192000-04-30 09:30:44 +1000425
426 FD_ZERO(&rdset);
427 FD_SET(p[0], &rdset);
Damien Miller8d1fd572000-05-17 21:34:07 +1000428 tv.tv_sec = msec_remaining / 1000;
429 tv.tv_usec = (msec_remaining % 1000) * 1000;
Damien Miller4018c192000-04-30 09:30:44 +1000430
431 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
Damien Miller8d1fd572000-05-17 21:34:07 +1000432
Damien Miller4018c192000-04-30 09:30:44 +1000433 switch (ret) {
434 case 0:
435 /* timer expired */
436 error_abort = 1;
437 break;
438
439 case 1:
440 /* command input */
441 bytes_read = read(p[0], buf, sizeof(buf));
442 if (bytes_read == -1) {
443 error_abort = 1;
444 break;
445 }
Damien Miller8d1fd572000-05-17 21:34:07 +1000446 if (bytes_read) {
447 SHA1_Update(&sha, buf, bytes_read);
448 total_bytes_read += bytes_read;
449 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
450 } else
451 cmd_eof = 1;
Damien Miller4018c192000-04-30 09:30:44 +1000452
453 break;
454
455 case -1:
456 default:
Damien Miller8d1fd572000-05-17 21:34:07 +1000457 debug("Command '%s': select() failed: %s", src->cmdstring,
458 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000459 error_abort = 1;
460 break;
461 } /* switch ret */
462
463 RAND_add(&tv, sizeof(&tv), 0.0);
464 } /* while !error_abort && !cmd_eof */
465
Damien Miller040f3832000-04-03 14:50:43 +1000466 SHA1_Final(hash, &sha);
467
468 close(p[0]);
Damien Miller8d1fd572000-05-17 21:34:07 +1000469
Damien Miller14c12cb2000-06-07 22:20:23 +1000470#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000471 debug("Time elapsed: %d msec", msec_elapsed);
Damien Miller14c12cb2000-06-07 22:20:23 +1000472#endif
Damien Miller040f3832000-04-03 14:50:43 +1000473
474 if (waitpid(pid, &status, 0) == -1) {
Damien Miller8d1fd572000-05-17 21:34:07 +1000475 debug("Couldn't wait for child '%s' completion: %s", src->cmdstring,
476 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000477 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000478 }
479
480 RAND_add(&status, sizeof(&status), 0.0);
481
Damien Miller4018c192000-04-30 09:30:44 +1000482 if (error_abort) {
483 /* closing p[0] on timeout causes the entropy command to
484 * SIGPIPE. Take whatever output we got, and mark this command
485 * as slow */
Damien Miller8d1fd572000-05-17 21:34:07 +1000486 debug("Command '%s' timed out", src->cmdstring);
Damien Miller4018c192000-04-30 09:30:44 +1000487 src->sticky_badness *= 2;
488 src->badness = src->sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000489 return(total_bytes_read);
Damien Miller4018c192000-04-30 09:30:44 +1000490 }
491
492 if (WIFEXITED(status)) {
493 if (WEXITSTATUS(status)==0) {
494 return(total_bytes_read);
495 } else {
Damien Miller14c12cb2000-06-07 22:20:23 +1000496 debug("Command '%s' exit status was %d", src->cmdstring,
497 WEXITSTATUS(status));
Damien Miller4018c192000-04-30 09:30:44 +1000498 src->badness = src->sticky_badness = 128;
499 return (0.0);
500 }
501 } else if (WIFSIGNALED(status)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000502 debug("Command '%s' returned on uncaught signal %d !", src->cmdstring,
503 status);
Damien Miller4018c192000-04-30 09:30:44 +1000504 src->badness = src->sticky_badness = 128;
505 return(0.0);
506 } else
507 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000508}
Damien Miller4018c192000-04-30 09:30:44 +1000509
510/*
511 * prng seedfile functions
512 */
513int
514prng_check_seedfile(char *filename) {
515
516 struct stat st;
517
518 /* FIXME raceable: eg replace seed between this stat and subsequent open */
519 /* Not such a problem because we don't trust the seed file anyway */
520 if (lstat(filename, &st) == -1) {
521 /* Fail on hard errors */
522 if (errno != ENOENT)
523 fatal("Couldn't stat random seed file \"%s\": %s", filename,
524 strerror(errno));
525
526 return(0);
527 }
528
529 /* regular file? */
530 if (!S_ISREG(st.st_mode))
531 fatal("PRNG seedfile %.100s is not a regular file", filename);
532
533 /* mode 0600, owned by root or the current user? */
Damien Milleraccfeb32000-05-11 19:10:58 +1000534 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid()))
Damien Miller4018c192000-04-30 09:30:44 +1000535 fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d",
536 filename, getuid());
537
538 return(1);
539}
540
541void
542prng_write_seedfile(void) {
543 int fd;
544 char seed[1024];
545 char filename[1024];
546 struct passwd *pw;
547
548 /* Don't bother if we have already saved a seed */
549 if (prng_seed_saved)
550 return;
551
Damien Millerfc0b11b2000-05-02 00:03:55 +1000552 prng_seed_saved = 1;
553
Damien Miller4018c192000-04-30 09:30:44 +1000554 pw = getpwuid(getuid());
555 if (pw == NULL)
556 fatal("Couldn't get password entry for current user (%i): %s",
557 getuid(), strerror(errno));
558
559 /* Try to ensure that the parent directory is there */
560 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
561 SSH_USER_DIR);
562 mkdir(filename, 0700);
563
564 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
565 SSH_PRNG_SEED_FILE);
566
567 debug("writing PRNG seed to file %.100s", filename);
568
569 RAND_bytes(seed, sizeof(seed));
570
571 /* Don't care if the seed doesn't exist */
572 prng_check_seedfile(filename);
573
574 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1)
575 fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename,
576 strerror(errno));
577
578 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
579 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
580 strerror(errno));
581
582 close(fd);
583}
584
585void
586prng_read_seedfile(void) {
587 int fd;
588 char seed[1024];
589 char filename[1024];
590 struct passwd *pw;
591
592 pw = getpwuid(getuid());
593 if (pw == NULL)
594 fatal("Couldn't get password entry for current user (%i): %s",
595 getuid(), strerror(errno));
596
597 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
598 SSH_PRNG_SEED_FILE);
599
600 debug("loading PRNG seed from file %.100s", filename);
601
602 if (!prng_check_seedfile(filename)) {
603 verbose("Random seed file not found, creating new");
604 prng_write_seedfile();
605
606 /* Reseed immediatly */
607 (void)stir_from_system();
608 (void)stir_from_programs();
609 return;
610 }
611
612 /* open the file and read in the seed */
613 fd = open(filename, O_RDONLY);
614 if (fd == -1)
615 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
616 strerror(errno));
617
618 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
619 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
620 filename);
621 memset(seed, '\0', sizeof(seed));
622 }
623 close(fd);
624
625 /* stir in the seed, with estimated entropy zero */
626 RAND_add(&seed, sizeof(seed), 0.0);
627}
628
Damien Miller0437b332000-05-02 09:56:41 +1000629
630/*
631 * entropy command initialisation functions
632 */
Damien Miller0437b332000-05-02 09:56:41 +1000633int
634prng_read_commands(char *cmdfilename)
635{
636 FILE *f;
Damien Miller0437b332000-05-02 09:56:41 +1000637 char *cp;
Damien Miller14c12cb2000-06-07 22:20:23 +1000638 char line[1024];
639 char cmd[1024];
640 char path[256];
Damien Miller0437b332000-05-02 09:56:41 +1000641 int linenum;
Damien Miller0437b332000-05-02 09:56:41 +1000642 int num_cmds = 64;
643 int cur_cmd = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000644 double est;
645 entropy_source_t *entcmd;
Damien Miller0437b332000-05-02 09:56:41 +1000646
647 f = fopen(cmdfilename, "r");
648 if (!f) {
649 fatal("couldn't read entropy commands file %.100s: %.100s",
650 cmdfilename, strerror(errno));
651 }
652
Damien Miller0437b332000-05-02 09:56:41 +1000653 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
654 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
655
Damien Miller14c12cb2000-06-07 22:20:23 +1000656 /* Read in file */
657 linenum = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000658 while (fgets(line, sizeof(line), f)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000659 int arg;
660 char *argv;
661
Damien Miller0437b332000-05-02 09:56:41 +1000662 linenum++;
663
664 /* skip leading whitespace, test for blank line or comment */
665 cp = line + strspn(line, WHITESPACE);
666 if ((*cp == 0) || (*cp == '#'))
667 continue; /* done with this line */
668
Damien Miller14c12cb2000-06-07 22:20:23 +1000669 /* First non-whitespace char should be double quote delimiting */
670 /* commandline */
671 if (*cp != '"') {
Damien Miller0437b332000-05-02 09:56:41 +1000672 error("bad entropy command, %.100s line %d", cmdfilename,
673 linenum);
674 continue;
Damien Miller14c12cb2000-06-07 22:20:23 +1000675 }
676
677 /* first token, command args (incl. argv[0]) in double quotes */
678 cp = strtok(cp, "\"");
679 if (cp == NULL) {
680 error("missing or bad command string, %.100s line %d -- ignored",
681 cmdfilename, linenum);
682 continue;
683 }
684 strlcpy(cmd, cp, sizeof(cmd));
685
686 /* second token, full command path */
687 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
688 error("missing command path, %.100s line %d -- ignored",
689 cmdfilename, linenum);
690 continue;
691 }
692
693 /* did configure mark this as dead? */
694 if (strncmp("undef", cp, 5) == 0)
695 continue;
696
697 strlcpy(path, cp, sizeof(path));
698
699 /* third token, entropy rate estimate for this command */
700 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
701 error("missing entropy estimate, %.100s line %d -- ignored",
702 cmdfilename, linenum);
703 continue;
704 }
705 est = strtod(cp, &argv);
706
707 /* end of line */
708 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
709 error("garbage at end of line %d in %.100s -- ignored", linenum,
710 cmdfilename);
711 continue;
712 }
713
714 /* save the command for debug messages */
715 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
716
717 /* split the command args */
718 cp = strtok(cmd, WHITESPACE);
719 arg = 0;
720 argv = NULL;
721 do {
722 char *s = (char*)xmalloc(strlen(cp) + 1);
723 strncpy(s, cp, strlen(cp) + 1);
724 entcmd[cur_cmd].args[arg] = s;
725 arg++;
726 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
727
728 if (strtok(NULL, WHITESPACE))
729 error("ignored extra command elements (max 5), %.100s line %d",
730 cmdfilename, linenum);
731
732 /* Copy the command path and rate estimate */
733 entcmd[cur_cmd].path = xstrdup(path);
734 entcmd[cur_cmd].rate = est;
735
736 /* Initialise other values */
737 entcmd[cur_cmd].sticky_badness = 1;
738
739 cur_cmd++;
740
741 /* If we've filled the array, reallocate it twice the size */
742 /* Do this now because even if this we're on the last command,
743 we need another slot to mark the last entry */
744 if (cur_cmd == num_cmds) {
745 num_cmds *= 2;
746 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
Damien Miller0437b332000-05-02 09:56:41 +1000747 }
748 }
749
750 /* zero the last entry */
751 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
Damien Miller14c12cb2000-06-07 22:20:23 +1000752
Damien Miller0437b332000-05-02 09:56:41 +1000753 /* trim to size */
754 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
755
756 debug("loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
757
758 return (cur_cmd >= MIN_ENTROPY_SOURCES);
759}
760
Damien Miller040f3832000-04-03 14:50:43 +1000761/*
Damien Miller4018c192000-04-30 09:30:44 +1000762 * Write a keyfile at exit
763 */
764void
765prng_seed_cleanup(void *junk)
766{
767 prng_write_seedfile();
768}
769
770/*
771 * Conditionally Seed OpenSSL's random number pool from
772 * syscalls and program output
Damien Miller040f3832000-04-03 14:50:43 +1000773 */
774void
775seed_rng(void)
776{
Damien Millerf3c6cf12000-05-17 22:08:29 +1000777 void *old_sigchld_handler;
778
Damien Miller0437b332000-05-02 09:56:41 +1000779 if (!prng_commands_loaded) {
780 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
781 fatal("PRNG initialisation failed -- exiting.");
782 prng_commands_loaded = 1;
783 }
784
Damien Millerf3c6cf12000-05-17 22:08:29 +1000785 /* Make sure some other sigchld handler doesn't reap our entropy */
786 /* commands */
787 old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
788
Damien Miller74a333b2000-04-04 15:04:09 +1000789 debug("Seeding random number generator.");
790 debug("OpenSSL random status is now %i\n", RAND_status());
791 debug("%i bytes from system calls", (int)stir_from_system());
792 debug("%i bytes from programs", (int)stir_from_programs());
793 debug("OpenSSL random status is now %i\n", RAND_status());
Damien Miller4018c192000-04-30 09:30:44 +1000794
Damien Millerf3c6cf12000-05-17 22:08:29 +1000795 signal(SIGCHLD, old_sigchld_handler);
796
Damien Miller8d1fd572000-05-17 21:34:07 +1000797 if (!RAND_status())
798 fatal("Couldn't initialise builtin random number generator -- exiting.");
799
Damien Miller4018c192000-04-30 09:30:44 +1000800 if (!prng_seed_loaded)
801 {
802 prng_seed_loaded = 1;
803 prng_seed_saved = 0;
804 prng_read_seedfile();
805 fatal_add_cleanup(prng_seed_cleanup, NULL);
806 atexit(prng_write_seedfile);
807 }
Damien Miller040f3832000-04-03 14:50:43 +1000808}
809#endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */