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.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include <openssl/rand.h>
31 #include <openssl/sha.h>
33 /* SunOS 4.4.4 needs this */
34 #ifdef HAVE_FLOATINGPOINT_H
35 # include <floatingpoint.h>
36 #endif /* HAVE_FLOATINGPOINT_H */
41 # define offsetof(type, member) ((size_t) &((type *)0)->member)
44 /* Number of times to pass through command list gathering entropy */
45 #define NUM_ENTROPY_RUNS 1
47 /* Scale entropy estimates back by this amount on subsequent runs */
48 #define SCALE_PER_RUN 10.0
50 /* Minimum number of commands to be considered valid */
51 #define MIN_ENTROPY_SOURCES 16
53 #define WHITESPACE " \t\n"
56 # define RUSAGE_SELF 0
58 #ifndef RUSAGE_CHILDREN
59 # define RUSAGE_CHILDREN 0
62 #if defined(EGD_SOCKET) || defined(RANDOM_POOL)
65 /* Collect entropy from EGD */
66 int get_random_bytes(unsigned char *buf, int len)
70 struct sockaddr_un addr;
74 if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
75 fatal("Random pool path is too long");
77 fatal("Too many bytes to read from EGD");
79 memset(&addr, '\0', sizeof(addr));
80 addr.sun_family = AF_UNIX;
81 strlcpy(addr.sun_path, EGD_SOCKET, sizeof(addr.sun_path));
82 addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
84 fd = socket(AF_UNIX, SOCK_STREAM, 0);
86 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
90 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
91 error("Couldn't connect to EGD socket \"%s\": %s",
92 addr.sun_path, strerror(errno));
97 /* Send blocking read request to EGD */
101 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
102 error("Couldn't write to EGD socket \"%s\": %s",
103 EGD_SOCKET, strerror(errno));
108 if (atomicio(read, fd, buf, len) != len) {
109 error("Couldn't read from EGD socket \"%s\": %s",
110 EGD_SOCKET, strerror(errno));
119 #else /* !EGD_SOCKET */
121 /* Collect entropy from /dev/urandom or pipe */
122 int get_random_bytes(unsigned char *buf, int len)
126 random_pool = open(RANDOM_POOL, O_RDONLY);
127 if (random_pool == -1) {
128 error("Couldn't open random pool \"%s\": %s",
129 RANDOM_POOL, strerror(errno));
133 if (atomicio(read, random_pool, buf, len) != len) {
134 error("Couldn't read from random pool \"%s\": %s",
135 RANDOM_POOL, strerror(errno));
144 #endif /* RANDOM_POOL */
145 #endif /* EGD_SOCKET */
148 * Seed OpenSSL's random number pool from Kernel random number generator
156 debug("Seeding random number generator");
158 if (!get_random_bytes(buf, sizeof(buf))) {
160 fatal("Entropy collection failed and entropy exhausted");
162 RAND_add(buf, sizeof(buf), sizeof(buf));
165 memset(buf, '\0', sizeof(buf));
169 void init_rng(void) {}
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_saved = 0;
184 static int prng_initialised = 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);
272 debug3("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
273 entropy_sources[c].cmdstring);
275 total_entropy_estimate += entropy_estimate;
277 /* Execution times should be a little unpredictable */
278 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);
283 debug2("Command '%s' disabled (badness %d)",
284 entropy_sources[c].cmdstring, entropy_sources[c].badness);
286 if (entropy_sources[c].badness > 0)
287 entropy_sources[c].badness--;
294 return(total_entropy_estimate);
298 stir_gettimeofday(double entropy_estimate)
302 if (gettimeofday(&tv, NULL) == -1)
303 fatal("Couldn't gettimeofday: %s", strerror(errno));
305 RAND_add(&tv, sizeof(tv), entropy_estimate);
307 return(entropy_estimate);
311 stir_clock(double entropy_estimate)
317 RAND_add(&c, sizeof(c), entropy_estimate);
319 return(entropy_estimate);
320 #else /* _HAVE_CLOCK */
322 #endif /* _HAVE_CLOCK */
326 stir_rusage(int who, double entropy_estimate)
328 #ifdef HAVE_GETRUSAGE
331 if (getrusage(who, &ru) == -1)
334 RAND_add(&ru, sizeof(ru), entropy_estimate);
336 return(entropy_estimate);
337 #else /* _HAVE_GETRUSAGE */
339 #endif /* _HAVE_GETRUSAGE */
345 _get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
346 int secdiff, usecdiff;
348 secdiff = t2->tv_sec - t1->tv_sec;
349 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
350 return (int)(usecdiff / 1000);
354 hash_output_from_command(entropy_source_t *src, char *hash)
356 static int devnull = -1;
359 int cmd_eof = 0, error_abort = 0;
360 struct timeval tv_start, tv_current;
361 int msec_elapsed = 0;
366 int total_bytes_read;
369 debug3("Reading output from \'%s\'", src->cmdstring);
372 devnull = open("/dev/null", O_RDWR);
374 fatal("Couldn't open /dev/null: %s", strerror(errno));
378 fatal("Couldn't open pipe: %s", strerror(errno));
380 (void)gettimeofday(&tv_start, NULL); /* record start time */
382 switch (pid = fork()) {
386 fatal("Couldn't fork: %s", strerror(errno));
389 dup2(devnull, STDIN_FILENO);
390 dup2(p[1], STDOUT_FILENO);
391 dup2(p[1], STDERR_FILENO);
396 setuid(original_uid);
397 execv(src->path, (char**)(src->args));
398 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
401 default: /* Parent */
405 RAND_add(&pid, sizeof(&pid), 0.0);
409 /* Hash output from child */
411 total_bytes_read = 0;
413 while (!error_abort && !cmd_eof) {
418 (void) gettimeofday(&tv_current, 0);
419 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
420 if (msec_elapsed >= entropy_timeout_current) {
424 msec_remaining = entropy_timeout_current - msec_elapsed;
427 FD_SET(p[0], &rdset);
428 tv.tv_sec = msec_remaining / 1000;
429 tv.tv_usec = (msec_remaining % 1000) * 1000;
431 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
433 RAND_add(&tv, sizeof(tv), 0.0);
442 bytes_read = read(p[0], buf, sizeof(buf));
443 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
444 if (bytes_read == -1) {
447 } else if (bytes_read) {
448 SHA1_Update(&sha, buf, bytes_read);
449 total_bytes_read += bytes_read;
457 debug("Command '%s': select() failed: %s", src->cmdstring,
464 SHA1_Final(hash, &sha);
468 debug3("Time elapsed: %d msec", msec_elapsed);
470 if (waitpid(pid, &status, 0) == -1) {
471 error("Couldn't wait for child '%s' completion: %s", src->cmdstring,
476 RAND_add(&status, sizeof(&status), 0.0);
479 /* closing p[0] on timeout causes the entropy command to
480 * SIGPIPE. Take whatever output we got, and mark this command
482 debug2("Command '%s' timed out", src->cmdstring);
483 src->sticky_badness *= 2;
484 src->badness = src->sticky_badness;
485 return(total_bytes_read);
488 if (WIFEXITED(status)) {
489 if (WEXITSTATUS(status)==0) {
490 return(total_bytes_read);
492 debug2("Command '%s' exit status was %d", src->cmdstring,
493 WEXITSTATUS(status));
494 src->badness = src->sticky_badness = 128;
497 } else if (WIFSIGNALED(status)) {
498 debug2("Command '%s' returned on uncaught signal %d !", src->cmdstring,
500 src->badness = src->sticky_badness = 128;
507 * prng seedfile functions
510 prng_check_seedfile(char *filename) {
514 /* FIXME raceable: eg replace seed between this stat and subsequent open */
515 /* Not such a problem because we don't trust the seed file anyway */
516 if (lstat(filename, &st) == -1) {
517 /* Give up on hard errors */
519 debug("WARNING: Couldn't stat random seed file \"%s\": %s",
520 filename, strerror(errno));
526 if (!S_ISREG(st.st_mode))
527 fatal("PRNG seedfile %.100s is not a regular file", filename);
529 /* mode 0600, owned by root or the current user? */
530 if (((st.st_mode & 0177) != 0) || !(st.st_uid == original_uid)) {
531 debug("WARNING: PRNG seedfile %.100s must be mode 0600, owned by uid %d",
540 prng_write_seedfile(void) {
546 /* Don't bother if we have already saved a seed */
550 setuid(original_uid);
554 pw = getpwuid(original_uid);
556 fatal("Couldn't get password entry for current user (%i): %s",
557 original_uid, strerror(errno));
559 /* Try to ensure that the parent directory is there */
560 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
562 mkdir(filename, 0700);
564 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
567 debug("writing PRNG seed to file %.100s", filename);
569 RAND_bytes(seed, sizeof(seed));
571 /* Don't care if the seed doesn't exist */
572 prng_check_seedfile(filename);
574 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) {
575 debug("WARNING: couldn't access PRNG seedfile %.100s (%.100s)",
576 filename, strerror(errno));
578 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
579 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
587 prng_read_seedfile(void) {
593 pw = getpwuid(original_uid);
595 fatal("Couldn't get password entry for current user (%i): %s",
596 original_uid, strerror(errno));
598 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
601 debug("loading PRNG seed from file %.100s", filename);
603 if (!prng_check_seedfile(filename)) {
604 verbose("Random seed file not found or not valid, ignoring.");
608 /* open the file and read in the seed */
609 fd = open(filename, O_RDONLY);
611 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
614 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
615 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
617 memset(seed, '\0', sizeof(seed));
621 /* stir in the seed, with estimated entropy zero */
622 RAND_add(&seed, sizeof(seed), 0.0);
627 * entropy command initialisation functions
630 prng_read_commands(char *cmdfilename)
641 entropy_source_t *entcmd;
643 f = fopen(cmdfilename, "r");
645 fatal("couldn't read entropy commands file %.100s: %.100s",
646 cmdfilename, strerror(errno));
649 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
650 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
654 while (fgets(line, sizeof(line), f)) {
660 /* skip leading whitespace, test for blank line or comment */
661 cp = line + strspn(line, WHITESPACE);
662 if ((*cp == 0) || (*cp == '#'))
663 continue; /* done with this line */
665 /* First non-whitespace char should be double quote delimiting */
668 error("bad entropy command, %.100s line %d", cmdfilename,
673 /* first token, command args (incl. argv[0]) in double quotes */
674 cp = strtok(cp, "\"");
676 error("missing or bad command string, %.100s line %d -- ignored",
677 cmdfilename, linenum);
680 strlcpy(cmd, cp, sizeof(cmd));
682 /* second token, full command path */
683 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
684 error("missing command path, %.100s line %d -- ignored",
685 cmdfilename, linenum);
689 /* did configure mark this as dead? */
690 if (strncmp("undef", cp, 5) == 0)
693 strlcpy(path, cp, sizeof(path));
695 /* third token, entropy rate estimate for this command */
696 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
697 error("missing entropy estimate, %.100s line %d -- ignored",
698 cmdfilename, linenum);
701 est = strtod(cp, &argv);
704 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
705 error("garbage at end of line %d in %.100s -- ignored", linenum,
710 /* save the command for debug messages */
711 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
713 /* split the command args */
714 cp = strtok(cmd, WHITESPACE);
718 char *s = (char*)xmalloc(strlen(cp) + 1);
719 strncpy(s, cp, strlen(cp) + 1);
720 entcmd[cur_cmd].args[arg] = s;
722 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
724 if (strtok(NULL, WHITESPACE))
725 error("ignored extra command elements (max 5), %.100s line %d",
726 cmdfilename, linenum);
728 /* Copy the command path and rate estimate */
729 entcmd[cur_cmd].path = xstrdup(path);
730 entcmd[cur_cmd].rate = est;
732 /* Initialise other values */
733 entcmd[cur_cmd].sticky_badness = 1;
737 /* If we've filled the array, reallocate it twice the size */
738 /* Do this now because even if this we're on the last command,
739 we need another slot to mark the last entry */
740 if (cur_cmd == num_cmds) {
742 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
746 /* zero the last entry */
747 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
750 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
752 debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
754 return (cur_cmd >= MIN_ENTROPY_SOURCES);
758 * Write a keyfile at exit
761 prng_seed_cleanup(void *junk)
763 prng_write_seedfile();
767 * Conditionally Seed OpenSSL's random number pool from
768 * syscalls and program output
773 void *old_sigchld_handler;
775 if (!prng_initialised)
776 fatal("RNG not initialised");
778 /* Make sure some other sigchld handler doesn't reap our entropy */
780 old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
782 debug("Seeded RNG with %i bytes from programs", (int)stir_from_programs());
783 debug("Seeded RNG with %i bytes from system calls", (int)stir_from_system());
786 fatal("Not enough entropy in RNG");
788 signal(SIGCHLD, old_sigchld_handler);
791 fatal("Couldn't initialise builtin random number generator -- exiting.");
798 original_uid = getuid();
799 original_euid = geteuid();
801 /* Read in collection commands */
802 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
803 fatal("PRNG initialisation failed -- exiting.");
805 /* Set ourselves up to save a seed upon exit */
808 /* Give up privs while reading seed file */
809 if ((original_uid != original_euid) && (seteuid(original_uid) == -1))
810 fatal("Couldn't give up privileges");
812 prng_read_seedfile();
814 if ((original_uid != original_euid) && (seteuid(original_euid) == -1))
815 fatal("Couldn't restore privileges");
817 fatal_add_cleanup(prng_seed_cleanup, NULL);
818 atexit(prng_write_seedfile);
820 prng_initialised = 1;
823 #endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */