blob: ffadd32c7fa6b0a40cdb91c2882118f0e8355a26 [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 Miller1ea8ac72000-05-31 11:24:34 +100038RCSID("$Id: entropy.c,v 1.12 2000/05/31 01:24:34 damien Exp $");
Damien Miller040f3832000-04-03 14:50:43 +100039
40#ifdef EGD_SOCKET
41#ifndef offsetof
42# define offsetof(type, member) ((size_t) &((type *)0)->member)
43#endif
44/* Collect entropy from EGD */
45void get_random_bytes(unsigned char *buf, int len)
46{
47 static int egd_socket = -1;
48 int c;
49 char egd_message[2] = { 0x02, 0x00 };
50 struct sockaddr_un addr;
51 int addr_len;
52
53 memset(&addr, '\0', sizeof(addr));
54 addr.sun_family = AF_UNIX;
55
56 /* FIXME: compile time check? */
57 if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
58 fatal("Random pool path is too long");
59
60 strcpy(addr.sun_path, EGD_SOCKET);
61
62 addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
63
64 if (egd_socket == -1) {
65 egd_socket = socket(AF_UNIX, SOCK_STREAM, 0);
66 if (egd_socket == -1)
67 fatal("Couldn't create AF_UNIX socket: %s", strerror(errno));
68 if (connect(egd_socket, (struct sockaddr*)&addr, addr_len) == -1)
69 fatal("Couldn't connect to EGD socket \"%s\": %s", addr.sun_path, strerror(errno));
70 }
71
72 if (len > 255)
73 fatal("Too many bytes to read from EGD");
74
75 /* Send blocking read request to EGD */
76 egd_message[1] = len;
77
78 c = atomicio(write, egd_socket, egd_message, sizeof(egd_message));
79 if (c == -1)
80 fatal("Couldn't write to EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno));
81
82 c = atomicio(read, egd_socket, buf, len);
83 if (c <= 0)
84 fatal("Couldn't read from EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno));
Damien Miller040f3832000-04-03 14:50:43 +100085}
86#else /* !EGD_SOCKET */
87#ifdef RANDOM_POOL
88/* Collect entropy from /dev/urandom or pipe */
89void get_random_bytes(unsigned char *buf, int len)
90{
91 static int random_pool = -1;
92 int c;
93
94 if (random_pool == -1) {
95 random_pool = open(RANDOM_POOL, O_RDONLY);
96 if (random_pool == -1)
97 fatal("Couldn't open random pool \"%s\": %s", RANDOM_POOL, strerror(errno));
98 }
99
Damien Miller040f3832000-04-03 14:50:43 +1000100 c = atomicio(read, random_pool, buf, len);
101 if (c <= 0)
102 fatal("Couldn't read from random pool \"%s\": %s", RANDOM_POOL, strerror(errno));
103}
104#endif /* RANDOM_POOL */
105#endif /* EGD_SOCKET */
106
107#if !defined(EGD_SOCKET) && !defined(RANDOM_POOL)
108/*
109 * FIXME: proper entropy estimations. All current values are guesses
Damien Miller4018c192000-04-30 09:30:44 +1000110 * FIXME: (ATL) do estimates at compile time?
Damien Miller040f3832000-04-03 14:50:43 +1000111 * FIXME: More entropy sources
112 */
113
Damien Miller4018c192000-04-30 09:30:44 +1000114/* slow command timeouts (all in milliseconds) */
115/* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
116static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
117
118static int prng_seed_loaded = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000119static int prng_seed_saved = 0;
120static int prng_commands_loaded = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000121
122typedef struct
123{
124 /* Proportion of data that is entropy */
125 double rate;
Damien Miller4018c192000-04-30 09:30:44 +1000126 /* Counter goes positive if this command times out */
127 unsigned int badness;
128 /* Increases by factor of two each timeout */
129 unsigned int sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000130 /* Path to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000131 char *path;
Damien Miller040f3832000-04-03 14:50:43 +1000132 /* argv to pass to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000133 char *args[5];
Damien Miller8d1fd572000-05-17 21:34:07 +1000134 /* full command string (debug) */
135 char *cmdstring;
Damien Miller040f3832000-04-03 14:50:43 +1000136} entropy_source_t;
137
Damien Miller4018c192000-04-30 09:30:44 +1000138double stir_from_system(void);
139double stir_from_programs(void);
140double stir_gettimeofday(double entropy_estimate);
141double stir_clock(double entropy_estimate);
142double stir_rusage(int who, double entropy_estimate);
143double hash_output_from_command(entropy_source_t *src, char *hash);
144
Damien Miller0437b332000-05-02 09:56:41 +1000145/* this is initialised from a file, by prng_read_commands() */
146entropy_source_t *entropy_sources = NULL;
147#define MIN_ENTROPY_SOURCES 16
148
Damien Miller040f3832000-04-03 14:50:43 +1000149
Damien Miller040f3832000-04-03 14:50:43 +1000150double
151stir_from_system(void)
152{
153 double total_entropy_estimate;
154 long int i;
155
156 total_entropy_estimate = 0;
157
158 i = getpid();
159 RAND_add(&i, sizeof(i), 0.1);
160 total_entropy_estimate += 0.1;
161
162 i = getppid();
163 RAND_add(&i, sizeof(i), 0.1);
164 total_entropy_estimate += 0.1;
165
166 i = getuid();
167 RAND_add(&i, sizeof(i), 0.0);
168 i = getgid();
169 RAND_add(&i, sizeof(i), 0.0);
170
171 total_entropy_estimate += stir_gettimeofday(1.0);
172 total_entropy_estimate += stir_clock(0.2);
173 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
174
175 return(total_entropy_estimate);
176}
177
178double
179stir_from_programs(void)
180{
181 int i;
182 int c;
183 double entropy_estimate;
184 double total_entropy_estimate;
185 char hash[SHA_DIGEST_LENGTH];
186
187 /*
188 * Run through list of programs twice to catch differences
189 */
190 total_entropy_estimate = 0;
191 for(i = 0; i < 2; i++) {
192 c = 0;
193 while (entropy_sources[c].path != NULL) {
Damien Miller040f3832000-04-03 14:50:43 +1000194
Damien Miller4018c192000-04-30 09:30:44 +1000195 if (!entropy_sources[c].badness) {
196 /* Hash output from command */
197 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
198
199 /* Scale back entropy estimate according to command's rate */
200 entropy_estimate *= entropy_sources[c].rate;
Damien Miller040f3832000-04-03 14:50:43 +1000201
Damien Miller4018c192000-04-30 09:30:44 +1000202 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
203 if (entropy_estimate > SHA_DIGEST_LENGTH)
204 entropy_estimate = SHA_DIGEST_LENGTH;
Damien Miller040f3832000-04-03 14:50:43 +1000205
206 /* * Scale back estimates for subsequent passes through list */
Damien Miller4018c192000-04-30 09:30:44 +1000207 entropy_estimate /= 10.0 * (i + 1.0);
Damien Miller040f3832000-04-03 14:50:43 +1000208
Damien Miller4018c192000-04-30 09:30:44 +1000209 /* Stir it in */
210 RAND_add(hash, sizeof(hash), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000211
212/* FIXME: turn this off later */
213#if 1
Damien Miller8d1fd572000-05-17 21:34:07 +1000214 debug("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
215 entropy_sources[c].cmdstring);
Damien Miller040f3832000-04-03 14:50:43 +1000216#endif
217
Damien Miller4018c192000-04-30 09:30:44 +1000218 total_entropy_estimate += entropy_estimate;
Damien Miller040f3832000-04-03 14:50:43 +1000219
220 /* Execution times should be a little unpredictable */
Damien Miller4018c192000-04-30 09:30:44 +1000221 total_entropy_estimate += stir_gettimeofday(0.05);
222 total_entropy_estimate += stir_clock(0.05);
223 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
224 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
225 } else {
226/* FIXME: turn this off later */
227#if 1
Damien Miller8d1fd572000-05-17 21:34:07 +1000228 debug("Command '%s' disabled (badness %d)",
229 entropy_sources[c].cmdstring, entropy_sources[c].badness);
Damien Miller4018c192000-04-30 09:30:44 +1000230#endif
231
232 if (entropy_sources[c].badness > 0)
233 entropy_sources[c].badness--;
234 }
235
Damien Miller040f3832000-04-03 14:50:43 +1000236 c++;
237 }
238 }
239
240 return(total_entropy_estimate);
241}
242
243double
244stir_gettimeofday(double entropy_estimate)
245{
246 struct timeval tv;
247
248 if (gettimeofday(&tv, NULL) == -1)
249 fatal("Couldn't gettimeofday: %s", strerror(errno));
250
251 RAND_add(&tv, sizeof(tv), entropy_estimate);
252
253 return(entropy_estimate);
254}
255
256double
257stir_clock(double entropy_estimate)
258{
259#ifdef HAVE_CLOCK
260 clock_t c;
261
262 c = clock();
263 RAND_add(&c, sizeof(c), entropy_estimate);
264
265 return(entropy_estimate);
266#else /* _HAVE_CLOCK */
267 return(0);
268#endif /* _HAVE_CLOCK */
269}
270
271double
272stir_rusage(int who, double entropy_estimate)
273{
274#ifdef HAVE_GETRUSAGE
275 struct rusage ru;
276
Damien Miller4018c192000-04-30 09:30:44 +1000277 if (getrusage(who, &ru) == -1)
Damien Miller040f3832000-04-03 14:50:43 +1000278 fatal("Couldn't getrusage: %s", strerror(errno));
279
280 RAND_add(&ru, sizeof(ru), 0.1);
281
282 return(entropy_estimate);
283#else /* _HAVE_GETRUSAGE */
284 return(0);
285#endif /* _HAVE_GETRUSAGE */
286}
287
Damien Miller8d1fd572000-05-17 21:34:07 +1000288
289static
290int
291_get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
292 int secdiff, usecdiff;
293
294 secdiff = t2->tv_sec - t1->tv_sec;
295 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
296 return (int)(usecdiff / 1000);
297}
298
Damien Miller040f3832000-04-03 14:50:43 +1000299double
Damien Miller4018c192000-04-30 09:30:44 +1000300hash_output_from_command(entropy_source_t *src, char *hash)
Damien Miller040f3832000-04-03 14:50:43 +1000301{
302 static int devnull = -1;
303 int p[2];
Damien Miller4018c192000-04-30 09:30:44 +1000304 fd_set rdset;
305 int cmd_eof = 0, error_abort = 0;
Damien Miller8d1fd572000-05-17 21:34:07 +1000306 struct timeval tv_start, tv_current;
307 int msec_elapsed = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000308 pid_t pid;
309 int status;
Damien Miller8d1fd572000-05-17 21:34:07 +1000310 char buf[16384];
Damien Miller040f3832000-04-03 14:50:43 +1000311 int bytes_read;
312 int total_bytes_read;
313 SHA_CTX sha;
314
315 if (devnull == -1) {
316 devnull = open("/dev/null", O_RDWR);
317 if (devnull == -1)
318 fatal("Couldn't open /dev/null: %s", strerror(errno));
319 }
320
321 if (pipe(p) == -1)
322 fatal("Couldn't open pipe: %s", strerror(errno));
323
Damien Miller8d1fd572000-05-17 21:34:07 +1000324 (void)gettimeofday(&tv_start, NULL); /* record start time */
325
Damien Miller040f3832000-04-03 14:50:43 +1000326 switch (pid = fork()) {
327 case -1: /* Error */
328 close(p[0]);
329 close(p[1]);
330 fatal("Couldn't fork: %s", strerror(errno));
331 /* NOTREACHED */
332 case 0: /* Child */
Damien Miller4018c192000-04-30 09:30:44 +1000333 dup2(devnull, STDIN_FILENO);
334 dup2(p[1], STDOUT_FILENO);
335 dup2(p[1], STDERR_FILENO);
Damien Miller040f3832000-04-03 14:50:43 +1000336 close(p[0]);
337 close(p[1]);
338 close(devnull);
339
Damien Miller4018c192000-04-30 09:30:44 +1000340 execv(src->path, (char**)(src->args));
Damien Miller8d1fd572000-05-17 21:34:07 +1000341 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
342 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000343 src->badness = src->sticky_badness = 128;
Damien Miller040f3832000-04-03 14:50:43 +1000344 _exit(-1);
345 default: /* Parent */
346 break;
347 }
348
349 RAND_add(&pid, sizeof(&pid), 0.0);
350
351 close(p[1]);
352
353 /* Hash output from child */
354 SHA1_Init(&sha);
355 total_bytes_read = 0;
Damien Miller4018c192000-04-30 09:30:44 +1000356
357 while (!error_abort && !cmd_eof) {
358 int ret;
359 struct timeval tv;
Damien Miller8d1fd572000-05-17 21:34:07 +1000360 int msec_remaining;
361
362 (void) gettimeofday(&tv_current, 0);
363 msec_elapsed = _get_timeval_msec_difference(
364 &tv_start, &tv_current);
365 if (msec_elapsed >= entropy_timeout_current) {
366 error_abort=1;
367 continue;
368 }
369 msec_remaining = entropy_timeout_current - msec_elapsed;
Damien Miller4018c192000-04-30 09:30:44 +1000370
371 FD_ZERO(&rdset);
372 FD_SET(p[0], &rdset);
Damien Miller8d1fd572000-05-17 21:34:07 +1000373 tv.tv_sec = msec_remaining / 1000;
374 tv.tv_usec = (msec_remaining % 1000) * 1000;
Damien Miller4018c192000-04-30 09:30:44 +1000375
376 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
Damien Miller8d1fd572000-05-17 21:34:07 +1000377
Damien Miller4018c192000-04-30 09:30:44 +1000378 switch (ret) {
379 case 0:
380 /* timer expired */
381 error_abort = 1;
382 break;
383
384 case 1:
385 /* command input */
386 bytes_read = read(p[0], buf, sizeof(buf));
387 if (bytes_read == -1) {
388 error_abort = 1;
389 break;
390 }
Damien Miller8d1fd572000-05-17 21:34:07 +1000391 if (bytes_read) {
392 SHA1_Update(&sha, buf, bytes_read);
393 total_bytes_read += bytes_read;
394 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
395 } else
396 cmd_eof = 1;
Damien Miller4018c192000-04-30 09:30:44 +1000397
398 break;
399
400 case -1:
401 default:
Damien Miller8d1fd572000-05-17 21:34:07 +1000402 debug("Command '%s': select() failed: %s", src->cmdstring,
403 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000404 error_abort = 1;
405 break;
406 } /* switch ret */
407
408 RAND_add(&tv, sizeof(&tv), 0.0);
409 } /* while !error_abort && !cmd_eof */
410
Damien Miller040f3832000-04-03 14:50:43 +1000411 SHA1_Final(hash, &sha);
412
413 close(p[0]);
Damien Miller8d1fd572000-05-17 21:34:07 +1000414
415 debug("Time elapsed: %d msec", msec_elapsed);
Damien Miller040f3832000-04-03 14:50:43 +1000416
417 if (waitpid(pid, &status, 0) == -1) {
Damien Miller8d1fd572000-05-17 21:34:07 +1000418 debug("Couldn't wait for child '%s' completion: %s", src->cmdstring,
419 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000420 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000421 }
422
423 RAND_add(&status, sizeof(&status), 0.0);
424
Damien Miller4018c192000-04-30 09:30:44 +1000425 if (error_abort) {
426 /* closing p[0] on timeout causes the entropy command to
427 * SIGPIPE. Take whatever output we got, and mark this command
428 * as slow */
Damien Miller8d1fd572000-05-17 21:34:07 +1000429 debug("Command '%s' timed out", src->cmdstring);
Damien Miller4018c192000-04-30 09:30:44 +1000430 src->sticky_badness *= 2;
431 src->badness = src->sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000432 return(total_bytes_read);
Damien Miller4018c192000-04-30 09:30:44 +1000433 }
434
435 if (WIFEXITED(status)) {
436 if (WEXITSTATUS(status)==0) {
437 return(total_bytes_read);
438 } else {
439 debug("Exit status was %d", WEXITSTATUS(status));
440 src->badness = src->sticky_badness = 128;
441 return (0.0);
442 }
443 } else if (WIFSIGNALED(status)) {
444 debug("Returned on uncaught signal %d !", status);
445 src->badness = src->sticky_badness = 128;
446 return(0.0);
447 } else
448 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000449}
Damien Miller4018c192000-04-30 09:30:44 +1000450
451/*
452 * prng seedfile functions
453 */
454int
455prng_check_seedfile(char *filename) {
456
457 struct stat st;
458
459 /* FIXME raceable: eg replace seed between this stat and subsequent open */
460 /* Not such a problem because we don't trust the seed file anyway */
461 if (lstat(filename, &st) == -1) {
462 /* Fail on hard errors */
463 if (errno != ENOENT)
464 fatal("Couldn't stat random seed file \"%s\": %s", filename,
465 strerror(errno));
466
467 return(0);
468 }
469
470 /* regular file? */
471 if (!S_ISREG(st.st_mode))
472 fatal("PRNG seedfile %.100s is not a regular file", filename);
473
474 /* mode 0600, owned by root or the current user? */
Damien Milleraccfeb32000-05-11 19:10:58 +1000475 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid()))
Damien Miller4018c192000-04-30 09:30:44 +1000476 fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d",
477 filename, getuid());
478
479 return(1);
480}
481
482void
483prng_write_seedfile(void) {
484 int fd;
485 char seed[1024];
486 char filename[1024];
487 struct passwd *pw;
488
489 /* Don't bother if we have already saved a seed */
490 if (prng_seed_saved)
491 return;
492
Damien Millerfc0b11b2000-05-02 00:03:55 +1000493 prng_seed_saved = 1;
494
Damien Miller4018c192000-04-30 09:30:44 +1000495 pw = getpwuid(getuid());
496 if (pw == NULL)
497 fatal("Couldn't get password entry for current user (%i): %s",
498 getuid(), strerror(errno));
499
500 /* Try to ensure that the parent directory is there */
501 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
502 SSH_USER_DIR);
503 mkdir(filename, 0700);
504
505 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
506 SSH_PRNG_SEED_FILE);
507
508 debug("writing PRNG seed to file %.100s", filename);
509
510 RAND_bytes(seed, sizeof(seed));
511
512 /* Don't care if the seed doesn't exist */
513 prng_check_seedfile(filename);
514
515 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1)
516 fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename,
517 strerror(errno));
518
519 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
520 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
521 strerror(errno));
522
523 close(fd);
524}
525
526void
527prng_read_seedfile(void) {
528 int fd;
529 char seed[1024];
530 char filename[1024];
531 struct passwd *pw;
532
533 pw = getpwuid(getuid());
534 if (pw == NULL)
535 fatal("Couldn't get password entry for current user (%i): %s",
536 getuid(), strerror(errno));
537
538 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
539 SSH_PRNG_SEED_FILE);
540
541 debug("loading PRNG seed from file %.100s", filename);
542
543 if (!prng_check_seedfile(filename)) {
544 verbose("Random seed file not found, creating new");
545 prng_write_seedfile();
546
547 /* Reseed immediatly */
548 (void)stir_from_system();
549 (void)stir_from_programs();
550 return;
551 }
552
553 /* open the file and read in the seed */
554 fd = open(filename, O_RDONLY);
555 if (fd == -1)
556 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
557 strerror(errno));
558
559 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
560 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
561 filename);
562 memset(seed, '\0', sizeof(seed));
563 }
564 close(fd);
565
566 /* stir in the seed, with estimated entropy zero */
567 RAND_add(&seed, sizeof(seed), 0.0);
568}
569
Damien Miller0437b332000-05-02 09:56:41 +1000570
571/*
572 * entropy command initialisation functions
573 */
574#define WHITESPACE " \t\n"
575
576int
577prng_read_commands(char *cmdfilename)
578{
579 FILE *f;
580 char line[1024];
581 char cmd[1024], path[256];
582 double est;
583 char *cp;
584 int linenum;
585 entropy_source_t *entcmd;
586 int num_cmds = 64;
587 int cur_cmd = 0;
588
589 f = fopen(cmdfilename, "r");
590 if (!f) {
591 fatal("couldn't read entropy commands file %.100s: %.100s",
592 cmdfilename, strerror(errno));
593 }
594
595 linenum = 0;
596
597 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
598 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
599
600 while (fgets(line, sizeof(line), f)) {
601 linenum++;
602
603 /* skip leading whitespace, test for blank line or comment */
604 cp = line + strspn(line, WHITESPACE);
605 if ((*cp == 0) || (*cp == '#'))
606 continue; /* done with this line */
607
608 switch (*cp) {
609 int arg;
610 char *argv;
611
612 case '"':
613 /* first token, command args (incl. argv[0]) in double quotes */
614 cp = strtok(cp, "\"");
615 if (cp==NULL) {
616 error("missing or bad command string, %.100s line %d -- ignored",
617 cmdfilename, linenum);
618 continue;
619 }
620 strncpy(cmd, cp, sizeof(cmd));
621 /* second token, full command path */
622 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
623 error("missing command path, %.100s line %d -- ignored",
624 cmdfilename, linenum);
625 continue;
626 }
627 if (strncmp("undef", cp, 5)==0) /* did configure mark this as dead? */
628 continue;
629
630 strncpy(path, cp, sizeof(path));
631 /* third token, entropy rate estimate for this command */
632 if ( (cp = strtok(NULL, WHITESPACE)) == NULL) {
633 error("missing entropy estimate, %.100s line %d -- ignored",
634 cmdfilename, linenum);
635 continue;
636 }
637 est = strtod(cp, &argv);/* FIXME: (ATL) no error checking here */
638
639 /* end of line */
640 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
641 error("garbage at end of line %d in %.100s -- ignored",
642 linenum, cmdfilename);
643 continue;
644 }
645
Damien Miller8d1fd572000-05-17 21:34:07 +1000646 /* save the command for debug messages */
647 entcmd[cur_cmd].cmdstring = (char*) xmalloc(strlen(cmd)+1);
648 strncpy(entcmd[cur_cmd].cmdstring, cmd, strlen(cmd)+1);
649
Damien Miller0437b332000-05-02 09:56:41 +1000650 /* split the command args */
651 cp = strtok(cmd, WHITESPACE);
652 arg = 0; argv = NULL;
653 do {
654 char *s = (char*)xmalloc(strlen(cp)+1);
655 strncpy(s, cp, strlen(cp)+1);
656 entcmd[cur_cmd].args[arg] = s;
657 arg++;
658 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
659 if (strtok(NULL, WHITESPACE))
660 error("ignored extra command elements (max 5), %.100s line %d",
661 cmdfilename, linenum);
662
663 /* copy the command path and rate estimate */
664 entcmd[cur_cmd].path = (char *)xmalloc(strlen(path)+1);
665 strncpy(entcmd[cur_cmd].path, path, strlen(path)+1);
666 entcmd[cur_cmd].rate = est;
667 /* initialise other values */
668 entcmd[cur_cmd].sticky_badness = 1;
669
670 cur_cmd++;
671
672 /* If we've filled the array, reallocate it twice the size */
673 /* Do this now because even if this we're on the last command,
674 we need another slot to mark the last entry */
675 if (cur_cmd == num_cmds) {
676 num_cmds *= 2;
677 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
678 }
679 break;
680
681 default:
682 error("bad entropy command, %.100s line %d", cmdfilename,
683 linenum);
684 continue;
685 }
686 }
687
688 /* zero the last entry */
689 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
690 /* trim to size */
691 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
692
693 debug("loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
694
695 return (cur_cmd >= MIN_ENTROPY_SOURCES);
696}
697
698
Damien Miller040f3832000-04-03 14:50:43 +1000699#endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
700
701#if defined(EGD_SOCKET) || defined(RANDOM_POOL)
Damien Miller4018c192000-04-30 09:30:44 +1000702
Damien Miller040f3832000-04-03 14:50:43 +1000703/*
704 * Seed OpenSSL's random number pool from Kernel random number generator
705 * or EGD
706 */
707void
708seed_rng(void)
709{
710 char buf[32];
711
712 debug("Seeding random number generator");
713 get_random_bytes(buf, sizeof(buf));
714 RAND_add(buf, sizeof(buf), sizeof(buf));
715 memset(buf, '\0', sizeof(buf));
716}
Damien Miller4018c192000-04-30 09:30:44 +1000717
Damien Miller040f3832000-04-03 14:50:43 +1000718#else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
Damien Miller4018c192000-04-30 09:30:44 +1000719
Damien Miller040f3832000-04-03 14:50:43 +1000720/*
Damien Miller4018c192000-04-30 09:30:44 +1000721 * Write a keyfile at exit
722 */
723void
724prng_seed_cleanup(void *junk)
725{
726 prng_write_seedfile();
727}
728
729/*
730 * Conditionally Seed OpenSSL's random number pool from
731 * syscalls and program output
Damien Miller040f3832000-04-03 14:50:43 +1000732 */
733void
734seed_rng(void)
735{
Damien Millerf3c6cf12000-05-17 22:08:29 +1000736 void *old_sigchld_handler;
737
Damien Miller0437b332000-05-02 09:56:41 +1000738 if (!prng_commands_loaded) {
739 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
740 fatal("PRNG initialisation failed -- exiting.");
741 prng_commands_loaded = 1;
742 }
743
Damien Millerf3c6cf12000-05-17 22:08:29 +1000744 /* Make sure some other sigchld handler doesn't reap our entropy */
745 /* commands */
746 old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
747
Damien Miller74a333b2000-04-04 15:04:09 +1000748 debug("Seeding random number generator.");
749 debug("OpenSSL random status is now %i\n", RAND_status());
750 debug("%i bytes from system calls", (int)stir_from_system());
751 debug("%i bytes from programs", (int)stir_from_programs());
752 debug("OpenSSL random status is now %i\n", RAND_status());
Damien Miller4018c192000-04-30 09:30:44 +1000753
Damien Millerf3c6cf12000-05-17 22:08:29 +1000754 signal(SIGCHLD, old_sigchld_handler);
755
Damien Miller8d1fd572000-05-17 21:34:07 +1000756 if (!RAND_status())
757 fatal("Couldn't initialise builtin random number generator -- exiting.");
758
Damien Miller4018c192000-04-30 09:30:44 +1000759 if (!prng_seed_loaded)
760 {
761 prng_seed_loaded = 1;
762 prng_seed_saved = 0;
763 prng_read_seedfile();
764 fatal_add_cleanup(prng_seed_cleanup, NULL);
765 atexit(prng_write_seedfile);
766 }
Damien Miller040f3832000-04-03 14:50:43 +1000767}
768#endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */