2 * Copyright (c) 2000 Damien Miller. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
35 #include <openssl/rand.h>
36 #include <openssl/sha.h>
41 # define offsetof(type, member) ((size_t) &((type *)0)->member)
44 /* Print lots of detail */
45 /* #define DEBUG_ENTROPY */
47 /* Number of times to pass through command list gathering entropy */
48 #define NUM_ENTROPY_RUNS 1
50 /* Scale entropy estimates back by this amount on subsequent runs */
51 #define SCALE_PER_RUN 10.0
53 /* Minimum number of commands to be considered valid */
54 #define MIN_ENTROPY_SOURCES 16
56 #define WHITESPACE " \t\n"
59 # define RUSAGE_SELF 0
61 #ifndef RUSAGE_CHILDREN
62 # define RUSAGE_CHILDREN 0
65 #if defined(EGD_SOCKET) || defined(RANDOM_POOL)
68 /* Collect entropy from EGD */
69 int get_random_bytes(unsigned char *buf, int len)
73 struct sockaddr_un addr;
77 if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
78 fatal("Random pool path is too long");
80 fatal("Too many bytes to read from EGD");
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);
87 fd = socket(AF_UNIX, SOCK_STREAM, 0);
89 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
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));
100 /* Send blocking read request to EGD */
104 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
105 error("Couldn't write to EGD socket \"%s\": %s",
106 EGD_SOCKET, strerror(errno));
111 if (atomicio(read, fd, buf, len) != len) {
112 error("Couldn't read from EGD socket \"%s\": %s",
113 EGD_SOCKET, strerror(errno));
122 #else /* !EGD_SOCKET */
124 /* Collect entropy from /dev/urandom or pipe */
125 int get_random_bytes(unsigned char *buf, int len)
129 random_pool = open(RANDOM_POOL, O_RDONLY);
130 if (random_pool == -1) {
131 error("Couldn't open random pool \"%s\": %s",
132 RANDOM_POOL, strerror(errno));
136 if (atomicio(read, random_pool, buf, len) != len) {
137 error("Couldn't read from random pool \"%s\": %s",
138 RANDOM_POOL, strerror(errno));
147 #endif /* RANDOM_POOL */
148 #endif /* EGD_SOCKET */
151 * Seed OpenSSL's random number pool from Kernel random number generator
159 debug("Seeding random number generator");
161 if (!get_random_bytes(buf, sizeof(buf))) {
163 fatal("Entropy collection failed and entropy exhausted");
165 RAND_add(buf, sizeof(buf), sizeof(buf));
168 memset(buf, '\0', sizeof(buf));
171 #else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
174 * FIXME: proper entropy estimations. All current values are guesses
175 * FIXME: (ATL) do estimates at compile time?
176 * FIXME: More entropy sources
179 /* slow command timeouts (all in milliseconds) */
180 /* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
181 static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
183 static int prng_seed_loaded = 0;
184 static int prng_seed_saved = 0;
185 static int prng_commands_loaded = 0;
189 /* Proportion of data that is entropy */
191 /* 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;
195 /* Path to executable */
197 /* argv to pass to executable */
199 /* full command string (debug) */
203 double stir_from_system(void);
204 double stir_from_programs(void);
205 double stir_gettimeofday(double entropy_estimate);
206 double stir_clock(double entropy_estimate);
207 double stir_rusage(int who, double entropy_estimate);
208 double hash_output_from_command(entropy_source_t *src, char *hash);
210 /* this is initialised from a file, by prng_read_commands() */
211 entropy_source_t *entropy_sources = NULL;
214 stir_from_system(void)
216 double total_entropy_estimate;
219 total_entropy_estimate = 0;
222 RAND_add(&i, sizeof(i), 0.5);
223 total_entropy_estimate += 0.1;
226 RAND_add(&i, sizeof(i), 0.5);
227 total_entropy_estimate += 0.1;
230 RAND_add(&i, sizeof(i), 0.0);
232 RAND_add(&i, sizeof(i), 0.0);
234 total_entropy_estimate += stir_gettimeofday(1.0);
235 total_entropy_estimate += stir_clock(0.5);
236 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
238 return(total_entropy_estimate);
242 stir_from_programs(void)
246 double entropy_estimate;
247 double total_entropy_estimate;
248 char hash[SHA_DIGEST_LENGTH];
250 total_entropy_estimate = 0;
251 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
253 while (entropy_sources[c].path != NULL) {
255 if (!entropy_sources[c].badness) {
256 /* Hash output from command */
257 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
259 /* Scale back entropy estimate according to command's rate */
260 entropy_estimate *= entropy_sources[c].rate;
262 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
263 if (entropy_estimate > SHA_DIGEST_LENGTH)
264 entropy_estimate = SHA_DIGEST_LENGTH;
266 /* Scale back estimates for subsequent passes through list */
267 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
270 RAND_add(hash, sizeof(hash), entropy_estimate);
273 debug("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
274 entropy_sources[c].cmdstring);
277 total_entropy_estimate += entropy_estimate;
279 /* Execution times should be a little unpredictable */
280 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);
286 debug("Command '%s' disabled (badness %d)",
287 entropy_sources[c].cmdstring, entropy_sources[c].badness);
290 if (entropy_sources[c].badness > 0)
291 entropy_sources[c].badness--;
298 return(total_entropy_estimate);
302 stir_gettimeofday(double entropy_estimate)
306 if (gettimeofday(&tv, NULL) == -1)
307 fatal("Couldn't gettimeofday: %s", strerror(errno));
309 RAND_add(&tv, sizeof(tv), entropy_estimate);
311 return(entropy_estimate);
315 stir_clock(double entropy_estimate)
321 RAND_add(&c, sizeof(c), entropy_estimate);
323 return(entropy_estimate);
324 #else /* _HAVE_CLOCK */
326 #endif /* _HAVE_CLOCK */
330 stir_rusage(int who, double entropy_estimate)
332 #ifdef HAVE_GETRUSAGE
335 if (getrusage(who, &ru) == -1)
338 RAND_add(&ru, sizeof(ru), entropy_estimate);
340 return(entropy_estimate);
341 #else /* _HAVE_GETRUSAGE */
343 #endif /* _HAVE_GETRUSAGE */
349 _get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
350 int secdiff, usecdiff;
352 secdiff = t2->tv_sec - t1->tv_sec;
353 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
354 return (int)(usecdiff / 1000);
358 hash_output_from_command(entropy_source_t *src, char *hash)
360 static int devnull = -1;
363 int cmd_eof = 0, error_abort = 0;
364 struct timeval tv_start, tv_current;
365 int msec_elapsed = 0;
370 int total_bytes_read;
374 devnull = open("/dev/null", O_RDWR);
376 fatal("Couldn't open /dev/null: %s", strerror(errno));
380 fatal("Couldn't open pipe: %s", strerror(errno));
382 (void)gettimeofday(&tv_start, NULL); /* record start time */
384 switch (pid = fork()) {
388 fatal("Couldn't fork: %s", strerror(errno));
391 dup2(devnull, STDIN_FILENO);
392 dup2(p[1], STDOUT_FILENO);
393 dup2(p[1], STDERR_FILENO);
398 execv(src->path, (char**)(src->args));
399 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
401 src->badness = src->sticky_badness = 128;
403 default: /* Parent */
407 RAND_add(&pid, sizeof(&pid), 0.0);
411 /* Hash output from child */
413 total_bytes_read = 0;
415 while (!error_abort && !cmd_eof) {
420 (void) gettimeofday(&tv_current, 0);
421 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
422 if (msec_elapsed >= entropy_timeout_current) {
426 msec_remaining = entropy_timeout_current - msec_elapsed;
429 FD_SET(p[0], &rdset);
430 tv.tv_sec = msec_remaining / 1000;
431 tv.tv_usec = (msec_remaining % 1000) * 1000;
433 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
443 bytes_read = read(p[0], buf, sizeof(buf));
444 if (bytes_read == -1) {
449 SHA1_Update(&sha, buf, bytes_read);
450 total_bytes_read += bytes_read;
451 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
459 debug("Command '%s': select() failed: %s", src->cmdstring,
465 RAND_add(&tv, sizeof(&tv), 0.0);
466 } /* while !error_abort && !cmd_eof */
468 SHA1_Final(hash, &sha);
473 debug("Time elapsed: %d msec", msec_elapsed);
476 if (waitpid(pid, &status, 0) == -1) {
477 debug("Couldn't wait for child '%s' completion: %s", src->cmdstring,
482 RAND_add(&status, sizeof(&status), 0.0);
485 /* closing p[0] on timeout causes the entropy command to
486 * SIGPIPE. Take whatever output we got, and mark this command
488 debug("Command '%s' timed out", src->cmdstring);
489 src->sticky_badness *= 2;
490 src->badness = src->sticky_badness;
491 return(total_bytes_read);
494 if (WIFEXITED(status)) {
495 if (WEXITSTATUS(status)==0) {
496 return(total_bytes_read);
498 debug("Command '%s' exit status was %d", src->cmdstring,
499 WEXITSTATUS(status));
500 src->badness = src->sticky_badness = 128;
503 } else if (WIFSIGNALED(status)) {
504 debug("Command '%s' returned on uncaught signal %d !", src->cmdstring,
506 src->badness = src->sticky_badness = 128;
513 * prng seedfile functions
516 prng_check_seedfile(char *filename) {
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 */
525 fatal("Couldn't stat random seed file \"%s\": %s", filename,
532 if (!S_ISREG(st.st_mode))
533 fatal("PRNG seedfile %.100s is not a regular file", filename);
535 /* mode 0600, owned by root or the current user? */
536 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid()))
537 fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d",
544 prng_write_seedfile(void) {
550 /* Don't bother if we have already saved a seed */
556 pw = getpwuid(getuid());
558 fatal("Couldn't get password entry for current user (%i): %s",
559 getuid(), strerror(errno));
561 /* Try to ensure that the parent directory is there */
562 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
564 mkdir(filename, 0700);
566 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
569 debug("writing PRNG seed to file %.100s", filename);
571 RAND_bytes(seed, sizeof(seed));
573 /* Don't care if the seed doesn't exist */
574 prng_check_seedfile(filename);
576 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1)
577 fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename,
580 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
581 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
588 prng_read_seedfile(void) {
594 pw = getpwuid(getuid());
596 fatal("Couldn't get password entry for current user (%i): %s",
597 getuid(), strerror(errno));
599 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
602 debug("loading PRNG seed from file %.100s", filename);
604 if (!prng_check_seedfile(filename)) {
605 verbose("Random seed file not found, creating new");
606 prng_write_seedfile();
608 /* Reseed immediatly */
609 (void)stir_from_system();
610 (void)stir_from_programs();
614 /* open the file and read in the seed */
615 fd = open(filename, O_RDONLY);
617 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
620 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
621 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
623 memset(seed, '\0', sizeof(seed));
627 /* stir in the seed, with estimated entropy zero */
628 RAND_add(&seed, sizeof(seed), 0.0);
633 * entropy command initialisation functions
636 prng_read_commands(char *cmdfilename)
647 entropy_source_t *entcmd;
649 f = fopen(cmdfilename, "r");
651 fatal("couldn't read entropy commands file %.100s: %.100s",
652 cmdfilename, strerror(errno));
655 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
656 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
660 while (fgets(line, sizeof(line), f)) {
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 */
671 /* First non-whitespace char should be double quote delimiting */
674 error("bad entropy command, %.100s line %d", cmdfilename,
679 /* first token, command args (incl. argv[0]) in double quotes */
680 cp = strtok(cp, "\"");
682 error("missing or bad command string, %.100s line %d -- ignored",
683 cmdfilename, linenum);
686 strlcpy(cmd, cp, sizeof(cmd));
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);
695 /* did configure mark this as dead? */
696 if (strncmp("undef", cp, 5) == 0)
699 strlcpy(path, cp, sizeof(path));
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);
707 est = strtod(cp, &argv);
710 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
711 error("garbage at end of line %d in %.100s -- ignored", linenum,
716 /* save the command for debug messages */
717 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
719 /* split the command args */
720 cp = strtok(cmd, WHITESPACE);
724 char *s = (char*)xmalloc(strlen(cp) + 1);
725 strncpy(s, cp, strlen(cp) + 1);
726 entcmd[cur_cmd].args[arg] = s;
728 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
730 if (strtok(NULL, WHITESPACE))
731 error("ignored extra command elements (max 5), %.100s line %d",
732 cmdfilename, linenum);
734 /* Copy the command path and rate estimate */
735 entcmd[cur_cmd].path = xstrdup(path);
736 entcmd[cur_cmd].rate = est;
738 /* Initialise other values */
739 entcmd[cur_cmd].sticky_badness = 1;
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) {
748 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
752 /* zero the last entry */
753 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
756 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
758 debug("loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
760 return (cur_cmd >= MIN_ENTROPY_SOURCES);
764 * Write a keyfile at exit
767 prng_seed_cleanup(void *junk)
769 prng_write_seedfile();
773 * Conditionally Seed OpenSSL's random number pool from
774 * syscalls and program output
779 void *old_sigchld_handler;
781 if (!prng_commands_loaded) {
782 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
783 fatal("PRNG initialisation failed -- exiting.");
784 prng_commands_loaded = 1;
787 /* Make sure some other sigchld handler doesn't reap our entropy */
789 old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
791 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());
797 signal(SIGCHLD, old_sigchld_handler);
800 fatal("Couldn't initialise builtin random number generator -- exiting.");
802 if (!prng_seed_loaded)
804 prng_seed_loaded = 1;
806 prng_read_seedfile();
807 fatal_add_cleanup(prng_seed_cleanup, NULL);
808 atexit(prng_write_seedfile);
811 #endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */