blob: d8eba654704a7efb22f182a6fddbdf8ce0c3dbbb [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 Miller08006472000-06-26 13:55:31 +100038RCSID("$Id: entropy.c,v 1.16 2000/06/26 03:55:31 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
Damien Miller08006472000-06-26 13:55:31 +1000161 if (!get_random_bytes(buf, sizeof(buf))) {
162 if (!RAND_status())
163 fatal("Entropy collection failed and entropy exhausted");
164 } else {
165 RAND_add(buf, sizeof(buf), sizeof(buf));
166 }
167
Damien Miller14c12cb2000-06-07 22:20:23 +1000168 memset(buf, '\0', sizeof(buf));
169}
170
171#else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
172
Damien Miller040f3832000-04-03 14:50:43 +1000173/*
174 * FIXME: proper entropy estimations. All current values are guesses
Damien Miller4018c192000-04-30 09:30:44 +1000175 * FIXME: (ATL) do estimates at compile time?
Damien Miller040f3832000-04-03 14:50:43 +1000176 * FIXME: More entropy sources
177 */
178
Damien Miller4018c192000-04-30 09:30:44 +1000179/* slow command timeouts (all in milliseconds) */
180/* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
181static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
182
183static int prng_seed_loaded = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000184static int prng_seed_saved = 0;
185static int prng_commands_loaded = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000186
187typedef struct
188{
189 /* Proportion of data that is entropy */
190 double rate;
Damien Miller4018c192000-04-30 09:30:44 +1000191 /* Counter goes positive if this command times out */
192 unsigned int badness;
193 /* Increases by factor of two each timeout */
194 unsigned int sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000195 /* Path to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000196 char *path;
Damien Miller040f3832000-04-03 14:50:43 +1000197 /* argv to pass to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000198 char *args[5];
Damien Miller8d1fd572000-05-17 21:34:07 +1000199 /* full command string (debug) */
200 char *cmdstring;
Damien Miller040f3832000-04-03 14:50:43 +1000201} entropy_source_t;
202
Damien Miller4018c192000-04-30 09:30:44 +1000203double stir_from_system(void);
204double stir_from_programs(void);
205double stir_gettimeofday(double entropy_estimate);
206double stir_clock(double entropy_estimate);
207double stir_rusage(int who, double entropy_estimate);
208double hash_output_from_command(entropy_source_t *src, char *hash);
209
Damien Miller0437b332000-05-02 09:56:41 +1000210/* this is initialised from a file, by prng_read_commands() */
211entropy_source_t *entropy_sources = NULL;
Damien Miller040f3832000-04-03 14:50:43 +1000212
Damien Miller040f3832000-04-03 14:50:43 +1000213double
214stir_from_system(void)
215{
216 double total_entropy_estimate;
217 long int i;
218
219 total_entropy_estimate = 0;
220
221 i = getpid();
Damien Miller7b22d652000-06-18 14:07:04 +1000222 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000223 total_entropy_estimate += 0.1;
224
225 i = getppid();
Damien Miller7b22d652000-06-18 14:07:04 +1000226 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000227 total_entropy_estimate += 0.1;
228
229 i = getuid();
230 RAND_add(&i, sizeof(i), 0.0);
231 i = getgid();
232 RAND_add(&i, sizeof(i), 0.0);
233
234 total_entropy_estimate += stir_gettimeofday(1.0);
Damien Miller7b22d652000-06-18 14:07:04 +1000235 total_entropy_estimate += stir_clock(0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000236 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
237
238 return(total_entropy_estimate);
239}
240
241double
242stir_from_programs(void)
243{
244 int i;
245 int c;
246 double entropy_estimate;
247 double total_entropy_estimate;
248 char hash[SHA_DIGEST_LENGTH];
249
Damien Miller040f3832000-04-03 14:50:43 +1000250 total_entropy_estimate = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000251 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
Damien Miller040f3832000-04-03 14:50:43 +1000252 c = 0;
253 while (entropy_sources[c].path != NULL) {
Damien Miller040f3832000-04-03 14:50:43 +1000254
Damien Miller4018c192000-04-30 09:30:44 +1000255 if (!entropy_sources[c].badness) {
256 /* Hash output from command */
257 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
258
259 /* Scale back entropy estimate according to command's rate */
260 entropy_estimate *= entropy_sources[c].rate;
Damien Miller040f3832000-04-03 14:50:43 +1000261
Damien Miller4018c192000-04-30 09:30:44 +1000262 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
263 if (entropy_estimate > SHA_DIGEST_LENGTH)
264 entropy_estimate = SHA_DIGEST_LENGTH;
Damien Miller040f3832000-04-03 14:50:43 +1000265
Damien Miller14c12cb2000-06-07 22:20:23 +1000266 /* Scale back estimates for subsequent passes through list */
267 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
Damien Miller040f3832000-04-03 14:50:43 +1000268
Damien Miller4018c192000-04-30 09:30:44 +1000269 /* Stir it in */
270 RAND_add(hash, sizeof(hash), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000271
Damien Miller14c12cb2000-06-07 22:20:23 +1000272#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000273 debug("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
274 entropy_sources[c].cmdstring);
Damien Miller040f3832000-04-03 14:50:43 +1000275#endif
276
Damien Miller4018c192000-04-30 09:30:44 +1000277 total_entropy_estimate += entropy_estimate;
Damien Miller040f3832000-04-03 14:50:43 +1000278
279 /* Execution times should be a little unpredictable */
Damien Miller4018c192000-04-30 09:30:44 +1000280 total_entropy_estimate += stir_gettimeofday(0.05);
281 total_entropy_estimate += stir_clock(0.05);
282 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
283 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
284 } else {
Damien Miller14c12cb2000-06-07 22:20:23 +1000285#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000286 debug("Command '%s' disabled (badness %d)",
287 entropy_sources[c].cmdstring, entropy_sources[c].badness);
Damien Miller4018c192000-04-30 09:30:44 +1000288#endif
289
290 if (entropy_sources[c].badness > 0)
291 entropy_sources[c].badness--;
292 }
293
Damien Miller040f3832000-04-03 14:50:43 +1000294 c++;
295 }
296 }
297
298 return(total_entropy_estimate);
299}
300
301double
302stir_gettimeofday(double entropy_estimate)
303{
304 struct timeval tv;
305
306 if (gettimeofday(&tv, NULL) == -1)
307 fatal("Couldn't gettimeofday: %s", strerror(errno));
308
309 RAND_add(&tv, sizeof(tv), entropy_estimate);
310
311 return(entropy_estimate);
312}
313
314double
315stir_clock(double entropy_estimate)
316{
317#ifdef HAVE_CLOCK
318 clock_t c;
319
320 c = clock();
321 RAND_add(&c, sizeof(c), entropy_estimate);
322
323 return(entropy_estimate);
324#else /* _HAVE_CLOCK */
325 return(0);
326#endif /* _HAVE_CLOCK */
327}
328
329double
330stir_rusage(int who, double entropy_estimate)
331{
332#ifdef HAVE_GETRUSAGE
333 struct rusage ru;
334
Damien Miller4018c192000-04-30 09:30:44 +1000335 if (getrusage(who, &ru) == -1)
Damien Miller7b22d652000-06-18 14:07:04 +1000336 return(0);
Damien Miller040f3832000-04-03 14:50:43 +1000337
Damien Miller7b22d652000-06-18 14:07:04 +1000338 RAND_add(&ru, sizeof(ru), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000339
340 return(entropy_estimate);
341#else /* _HAVE_GETRUSAGE */
342 return(0);
343#endif /* _HAVE_GETRUSAGE */
344}
345
Damien Miller8d1fd572000-05-17 21:34:07 +1000346
347static
348int
349_get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
350 int secdiff, usecdiff;
351
352 secdiff = t2->tv_sec - t1->tv_sec;
353 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
354 return (int)(usecdiff / 1000);
355}
356
Damien Miller040f3832000-04-03 14:50:43 +1000357double
Damien Miller4018c192000-04-30 09:30:44 +1000358hash_output_from_command(entropy_source_t *src, char *hash)
Damien Miller040f3832000-04-03 14:50:43 +1000359{
360 static int devnull = -1;
361 int p[2];
Damien Miller4018c192000-04-30 09:30:44 +1000362 fd_set rdset;
363 int cmd_eof = 0, error_abort = 0;
Damien Miller8d1fd572000-05-17 21:34:07 +1000364 struct timeval tv_start, tv_current;
365 int msec_elapsed = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000366 pid_t pid;
367 int status;
Damien Miller8d1fd572000-05-17 21:34:07 +1000368 char buf[16384];
Damien Miller040f3832000-04-03 14:50:43 +1000369 int bytes_read;
370 int total_bytes_read;
371 SHA_CTX sha;
372
373 if (devnull == -1) {
374 devnull = open("/dev/null", O_RDWR);
375 if (devnull == -1)
376 fatal("Couldn't open /dev/null: %s", strerror(errno));
377 }
378
379 if (pipe(p) == -1)
380 fatal("Couldn't open pipe: %s", strerror(errno));
381
Damien Miller8d1fd572000-05-17 21:34:07 +1000382 (void)gettimeofday(&tv_start, NULL); /* record start time */
383
Damien Miller040f3832000-04-03 14:50:43 +1000384 switch (pid = fork()) {
385 case -1: /* Error */
386 close(p[0]);
387 close(p[1]);
388 fatal("Couldn't fork: %s", strerror(errno));
389 /* NOTREACHED */
390 case 0: /* Child */
Damien Miller4018c192000-04-30 09:30:44 +1000391 dup2(devnull, STDIN_FILENO);
392 dup2(p[1], STDOUT_FILENO);
393 dup2(p[1], STDERR_FILENO);
Damien Miller040f3832000-04-03 14:50:43 +1000394 close(p[0]);
395 close(p[1]);
396 close(devnull);
397
Damien Miller4018c192000-04-30 09:30:44 +1000398 execv(src->path, (char**)(src->args));
Damien Miller8d1fd572000-05-17 21:34:07 +1000399 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
400 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000401 src->badness = src->sticky_badness = 128;
Damien Miller040f3832000-04-03 14:50:43 +1000402 _exit(-1);
403 default: /* Parent */
404 break;
405 }
406
407 RAND_add(&pid, sizeof(&pid), 0.0);
408
409 close(p[1]);
410
411 /* Hash output from child */
412 SHA1_Init(&sha);
413 total_bytes_read = 0;
Damien Miller4018c192000-04-30 09:30:44 +1000414
415 while (!error_abort && !cmd_eof) {
416 int ret;
417 struct timeval tv;
Damien Miller8d1fd572000-05-17 21:34:07 +1000418 int msec_remaining;
419
420 (void) gettimeofday(&tv_current, 0);
Damien Miller14c12cb2000-06-07 22:20:23 +1000421 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
Damien Miller8d1fd572000-05-17 21:34:07 +1000422 if (msec_elapsed >= entropy_timeout_current) {
423 error_abort=1;
424 continue;
425 }
426 msec_remaining = entropy_timeout_current - msec_elapsed;
Damien Miller4018c192000-04-30 09:30:44 +1000427
428 FD_ZERO(&rdset);
429 FD_SET(p[0], &rdset);
Damien Miller8d1fd572000-05-17 21:34:07 +1000430 tv.tv_sec = msec_remaining / 1000;
431 tv.tv_usec = (msec_remaining % 1000) * 1000;
Damien Miller4018c192000-04-30 09:30:44 +1000432
433 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
Damien Miller8d1fd572000-05-17 21:34:07 +1000434
Damien Miller4018c192000-04-30 09:30:44 +1000435 switch (ret) {
436 case 0:
437 /* timer expired */
438 error_abort = 1;
439 break;
440
441 case 1:
442 /* command input */
443 bytes_read = read(p[0], buf, sizeof(buf));
444 if (bytes_read == -1) {
445 error_abort = 1;
446 break;
447 }
Damien Miller8d1fd572000-05-17 21:34:07 +1000448 if (bytes_read) {
449 SHA1_Update(&sha, buf, bytes_read);
450 total_bytes_read += bytes_read;
451 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
452 } else
453 cmd_eof = 1;
Damien Miller4018c192000-04-30 09:30:44 +1000454
455 break;
456
457 case -1:
458 default:
Damien Miller8d1fd572000-05-17 21:34:07 +1000459 debug("Command '%s': select() failed: %s", src->cmdstring,
460 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000461 error_abort = 1;
462 break;
463 } /* switch ret */
464
465 RAND_add(&tv, sizeof(&tv), 0.0);
466 } /* while !error_abort && !cmd_eof */
467
Damien Miller040f3832000-04-03 14:50:43 +1000468 SHA1_Final(hash, &sha);
469
470 close(p[0]);
Damien Miller8d1fd572000-05-17 21:34:07 +1000471
Damien Miller14c12cb2000-06-07 22:20:23 +1000472#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000473 debug("Time elapsed: %d msec", msec_elapsed);
Damien Miller14c12cb2000-06-07 22:20:23 +1000474#endif
Damien Miller040f3832000-04-03 14:50:43 +1000475
476 if (waitpid(pid, &status, 0) == -1) {
Damien Miller8d1fd572000-05-17 21:34:07 +1000477 debug("Couldn't wait for child '%s' completion: %s", src->cmdstring,
478 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000479 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000480 }
481
482 RAND_add(&status, sizeof(&status), 0.0);
483
Damien Miller4018c192000-04-30 09:30:44 +1000484 if (error_abort) {
485 /* closing p[0] on timeout causes the entropy command to
486 * SIGPIPE. Take whatever output we got, and mark this command
487 * as slow */
Damien Miller8d1fd572000-05-17 21:34:07 +1000488 debug("Command '%s' timed out", src->cmdstring);
Damien Miller4018c192000-04-30 09:30:44 +1000489 src->sticky_badness *= 2;
490 src->badness = src->sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000491 return(total_bytes_read);
Damien Miller4018c192000-04-30 09:30:44 +1000492 }
493
494 if (WIFEXITED(status)) {
495 if (WEXITSTATUS(status)==0) {
496 return(total_bytes_read);
497 } else {
Damien Miller14c12cb2000-06-07 22:20:23 +1000498 debug("Command '%s' exit status was %d", src->cmdstring,
499 WEXITSTATUS(status));
Damien Miller4018c192000-04-30 09:30:44 +1000500 src->badness = src->sticky_badness = 128;
501 return (0.0);
502 }
503 } else if (WIFSIGNALED(status)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000504 debug("Command '%s' returned on uncaught signal %d !", src->cmdstring,
505 status);
Damien Miller4018c192000-04-30 09:30:44 +1000506 src->badness = src->sticky_badness = 128;
507 return(0.0);
508 } else
509 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000510}
Damien Miller4018c192000-04-30 09:30:44 +1000511
512/*
513 * prng seedfile functions
514 */
515int
516prng_check_seedfile(char *filename) {
517
518 struct stat st;
519
520 /* FIXME raceable: eg replace seed between this stat and subsequent open */
521 /* Not such a problem because we don't trust the seed file anyway */
522 if (lstat(filename, &st) == -1) {
523 /* Fail on hard errors */
524 if (errno != ENOENT)
525 fatal("Couldn't stat random seed file \"%s\": %s", filename,
526 strerror(errno));
527
528 return(0);
529 }
530
531 /* regular file? */
532 if (!S_ISREG(st.st_mode))
533 fatal("PRNG seedfile %.100s is not a regular file", filename);
534
535 /* mode 0600, owned by root or the current user? */
Damien Milleraccfeb32000-05-11 19:10:58 +1000536 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid()))
Damien Miller4018c192000-04-30 09:30:44 +1000537 fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d",
538 filename, getuid());
539
540 return(1);
541}
542
543void
544prng_write_seedfile(void) {
545 int fd;
546 char seed[1024];
547 char filename[1024];
548 struct passwd *pw;
549
550 /* Don't bother if we have already saved a seed */
551 if (prng_seed_saved)
552 return;
553
Damien Millerfc0b11b2000-05-02 00:03:55 +1000554 prng_seed_saved = 1;
555
Damien Miller4018c192000-04-30 09:30:44 +1000556 pw = getpwuid(getuid());
557 if (pw == NULL)
558 fatal("Couldn't get password entry for current user (%i): %s",
559 getuid(), strerror(errno));
560
561 /* Try to ensure that the parent directory is there */
562 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
563 SSH_USER_DIR);
564 mkdir(filename, 0700);
565
566 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
567 SSH_PRNG_SEED_FILE);
568
569 debug("writing PRNG seed to file %.100s", filename);
570
571 RAND_bytes(seed, sizeof(seed));
572
573 /* Don't care if the seed doesn't exist */
574 prng_check_seedfile(filename);
575
576 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1)
577 fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename,
578 strerror(errno));
579
580 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
581 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
582 strerror(errno));
583
584 close(fd);
585}
586
587void
588prng_read_seedfile(void) {
589 int fd;
590 char seed[1024];
591 char filename[1024];
592 struct passwd *pw;
593
594 pw = getpwuid(getuid());
595 if (pw == NULL)
596 fatal("Couldn't get password entry for current user (%i): %s",
597 getuid(), strerror(errno));
598
599 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
600 SSH_PRNG_SEED_FILE);
601
602 debug("loading PRNG seed from file %.100s", filename);
603
604 if (!prng_check_seedfile(filename)) {
605 verbose("Random seed file not found, creating new");
606 prng_write_seedfile();
607
608 /* Reseed immediatly */
609 (void)stir_from_system();
610 (void)stir_from_programs();
611 return;
612 }
613
614 /* open the file and read in the seed */
615 fd = open(filename, O_RDONLY);
616 if (fd == -1)
617 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
618 strerror(errno));
619
620 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
621 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
622 filename);
623 memset(seed, '\0', sizeof(seed));
624 }
625 close(fd);
626
627 /* stir in the seed, with estimated entropy zero */
628 RAND_add(&seed, sizeof(seed), 0.0);
629}
630
Damien Miller0437b332000-05-02 09:56:41 +1000631
632/*
633 * entropy command initialisation functions
634 */
Damien Miller0437b332000-05-02 09:56:41 +1000635int
636prng_read_commands(char *cmdfilename)
637{
638 FILE *f;
Damien Miller0437b332000-05-02 09:56:41 +1000639 char *cp;
Damien Miller14c12cb2000-06-07 22:20:23 +1000640 char line[1024];
641 char cmd[1024];
642 char path[256];
Damien Miller0437b332000-05-02 09:56:41 +1000643 int linenum;
Damien Miller0437b332000-05-02 09:56:41 +1000644 int num_cmds = 64;
645 int cur_cmd = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000646 double est;
647 entropy_source_t *entcmd;
Damien Miller0437b332000-05-02 09:56:41 +1000648
649 f = fopen(cmdfilename, "r");
650 if (!f) {
651 fatal("couldn't read entropy commands file %.100s: %.100s",
652 cmdfilename, strerror(errno));
653 }
654
Damien Miller0437b332000-05-02 09:56:41 +1000655 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
656 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
657
Damien Miller14c12cb2000-06-07 22:20:23 +1000658 /* Read in file */
659 linenum = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000660 while (fgets(line, sizeof(line), f)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000661 int arg;
662 char *argv;
663
Damien Miller0437b332000-05-02 09:56:41 +1000664 linenum++;
665
666 /* skip leading whitespace, test for blank line or comment */
667 cp = line + strspn(line, WHITESPACE);
668 if ((*cp == 0) || (*cp == '#'))
669 continue; /* done with this line */
670
Damien Miller14c12cb2000-06-07 22:20:23 +1000671 /* First non-whitespace char should be double quote delimiting */
672 /* commandline */
673 if (*cp != '"') {
Damien Miller0437b332000-05-02 09:56:41 +1000674 error("bad entropy command, %.100s line %d", cmdfilename,
675 linenum);
676 continue;
Damien Miller14c12cb2000-06-07 22:20:23 +1000677 }
678
679 /* first token, command args (incl. argv[0]) in double quotes */
680 cp = strtok(cp, "\"");
681 if (cp == NULL) {
682 error("missing or bad command string, %.100s line %d -- ignored",
683 cmdfilename, linenum);
684 continue;
685 }
686 strlcpy(cmd, cp, sizeof(cmd));
687
688 /* second token, full command path */
689 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
690 error("missing command path, %.100s line %d -- ignored",
691 cmdfilename, linenum);
692 continue;
693 }
694
695 /* did configure mark this as dead? */
696 if (strncmp("undef", cp, 5) == 0)
697 continue;
698
699 strlcpy(path, cp, sizeof(path));
700
701 /* third token, entropy rate estimate for this command */
702 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
703 error("missing entropy estimate, %.100s line %d -- ignored",
704 cmdfilename, linenum);
705 continue;
706 }
707 est = strtod(cp, &argv);
708
709 /* end of line */
710 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
711 error("garbage at end of line %d in %.100s -- ignored", linenum,
712 cmdfilename);
713 continue;
714 }
715
716 /* save the command for debug messages */
717 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
718
719 /* split the command args */
720 cp = strtok(cmd, WHITESPACE);
721 arg = 0;
722 argv = NULL;
723 do {
724 char *s = (char*)xmalloc(strlen(cp) + 1);
725 strncpy(s, cp, strlen(cp) + 1);
726 entcmd[cur_cmd].args[arg] = s;
727 arg++;
728 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
729
730 if (strtok(NULL, WHITESPACE))
731 error("ignored extra command elements (max 5), %.100s line %d",
732 cmdfilename, linenum);
733
734 /* Copy the command path and rate estimate */
735 entcmd[cur_cmd].path = xstrdup(path);
736 entcmd[cur_cmd].rate = est;
737
738 /* Initialise other values */
739 entcmd[cur_cmd].sticky_badness = 1;
740
741 cur_cmd++;
742
743 /* If we've filled the array, reallocate it twice the size */
744 /* Do this now because even if this we're on the last command,
745 we need another slot to mark the last entry */
746 if (cur_cmd == num_cmds) {
747 num_cmds *= 2;
748 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
Damien Miller0437b332000-05-02 09:56:41 +1000749 }
750 }
751
752 /* zero the last entry */
753 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
Damien Miller14c12cb2000-06-07 22:20:23 +1000754
Damien Miller0437b332000-05-02 09:56:41 +1000755 /* trim to size */
756 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
757
758 debug("loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
759
760 return (cur_cmd >= MIN_ENTROPY_SOURCES);
761}
762
Damien Miller040f3832000-04-03 14:50:43 +1000763/*
Damien Miller4018c192000-04-30 09:30:44 +1000764 * Write a keyfile at exit
765 */
766void
767prng_seed_cleanup(void *junk)
768{
769 prng_write_seedfile();
770}
771
772/*
773 * Conditionally Seed OpenSSL's random number pool from
774 * syscalls and program output
Damien Miller040f3832000-04-03 14:50:43 +1000775 */
776void
777seed_rng(void)
778{
Damien Millerf3c6cf12000-05-17 22:08:29 +1000779 void *old_sigchld_handler;
780
Damien Miller0437b332000-05-02 09:56:41 +1000781 if (!prng_commands_loaded) {
782 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
783 fatal("PRNG initialisation failed -- exiting.");
784 prng_commands_loaded = 1;
785 }
786
Damien Millerf3c6cf12000-05-17 22:08:29 +1000787 /* Make sure some other sigchld handler doesn't reap our entropy */
788 /* commands */
789 old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
790
Damien Miller74a333b2000-04-04 15:04:09 +1000791 debug("Seeding random number generator.");
792 debug("OpenSSL random status is now %i\n", RAND_status());
793 debug("%i bytes from system calls", (int)stir_from_system());
794 debug("%i bytes from programs", (int)stir_from_programs());
795 debug("OpenSSL random status is now %i\n", RAND_status());
Damien Miller4018c192000-04-30 09:30:44 +1000796
Damien Millerf3c6cf12000-05-17 22:08:29 +1000797 signal(SIGCHLD, old_sigchld_handler);
798
Damien Miller8d1fd572000-05-17 21:34:07 +1000799 if (!RAND_status())
800 fatal("Couldn't initialise builtin random number generator -- exiting.");
801
Damien Miller4018c192000-04-30 09:30:44 +1000802 if (!prng_seed_loaded)
803 {
804 prng_seed_loaded = 1;
805 prng_seed_saved = 0;
806 prng_read_seedfile();
807 fatal_add_cleanup(prng_seed_cleanup, NULL);
808 atexit(prng_write_seedfile);
809 }
Damien Miller040f3832000-04-03 14:50:43 +1000810}
811#endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */