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.
27 #include <openssl/rand.h>
28 #include <openssl/sha.h>
29 #include <openssl/crypto.h>
31 /* SunOS 4.4.4 needs this */
32 #ifdef HAVE_FLOATINGPOINT_H
33 # include <floatingpoint.h>
34 #endif /* HAVE_FLOATINGPOINT_H */
40 #include "pathnames.h"
46 # define offsetof(type, member) ((size_t) &((type *)0)->member)
49 /* Number of times to pass through command list gathering entropy */
50 #define NUM_ENTROPY_RUNS 1
52 /* Scale entropy estimates back by this amount on subsequent runs */
53 #define SCALE_PER_RUN 10.0
55 /* Minimum number of commands to be considered valid */
56 #define MIN_ENTROPY_SOURCES 16
58 #define WHITESPACE " \t\n"
61 # define RUSAGE_SELF 0
63 #ifndef RUSAGE_CHILDREN
64 # define RUSAGE_CHILDREN 0
67 #if defined(_POSIX_SAVED_IDS) && !defined(BROKEN_SAVED_UIDS)
68 # define SAVED_IDS_WORK_WITH_SETEUID
72 check_openssl_version(void)
74 if (SSLeay() != OPENSSL_VERSION_NUMBER)
75 fatal("OpenSSL version mismatch. Built against %lx, you "
76 "have %lx", OPENSSL_VERSION_NUMBER, SSLeay());
79 #if defined(PRNGD_SOCKET) || defined(PRNGD_PORT)
83 #if defined(USE_PRNGD) || defined(RANDOM_POOL)
86 /* Collect entropy from PRNGD/EGD */
88 get_random_bytes(unsigned char *buf, int len)
93 struct sockaddr_in addr;
95 struct sockaddr_un addr;
97 int addr_len, rval, errors;
100 memset(&addr, '\0', sizeof(addr));
103 addr.sin_family = AF_INET;
104 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
105 addr.sin_port = htons(PRNGD_PORT);
106 addr_len = sizeof(struct sockaddr_in);
107 #else /* use IP socket PRNGD_SOCKET instead */
109 if (sizeof(PRNGD_SOCKET) > sizeof(addr.sun_path))
110 fatal("Random pool path is too long");
112 fatal("Too many bytes to read from PRNGD");
114 addr.sun_family = AF_UNIX;
115 strlcpy(addr.sun_path, PRNGD_SOCKET, sizeof(addr.sun_path));
116 addr_len = offsetof(struct sockaddr_un, sun_path) +
117 sizeof(PRNGD_SOCKET);
120 old_sigpipe = mysignal(SIGPIPE, SIG_IGN);
125 fd = socket(addr.sin_family, SOCK_STREAM, 0);
127 error("Couldn't create AF_INET socket: %s", strerror(errno));
131 fd = socket(addr.sun_family, SOCK_STREAM, 0);
133 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
138 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
140 error("Couldn't connect to PRNGD port %d: %s",
141 PRNGD_PORT, strerror(errno));
143 error("Couldn't connect to PRNGD socket \"%s\": %s",
144 addr.sun_path, strerror(errno));
149 /* Send blocking read request to PRNGD */
153 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
154 if (errno == EPIPE && errors < 10) {
159 error("Couldn't write to PRNGD socket: %s",
164 if (atomicio(read, fd, buf, len) != len) {
165 if (errno == EPIPE && errors < 10) {
170 error("Couldn't read from PRNGD socket: %s",
177 mysignal(SIGPIPE, old_sigpipe);
182 #else /* !USE_PRNGD */
184 /* Collect entropy from /dev/urandom or pipe */
186 get_random_bytes(unsigned char *buf, int len)
190 random_pool = open(RANDOM_POOL, O_RDONLY);
191 if (random_pool == -1) {
192 error("Couldn't open random pool \"%s\": %s",
193 RANDOM_POOL, strerror(errno));
197 if (atomicio(read, random_pool, buf, len) != len) {
198 error("Couldn't read from random pool \"%s\": %s",
199 RANDOM_POOL, strerror(errno));
208 #endif /* RANDOM_POOL */
209 #endif /* USE_PRNGD */
212 * Seed OpenSSL's random number pool from Kernel random number generator
218 unsigned char buf[32];
220 debug("Seeding random number generator");
222 if (!get_random_bytes(buf, sizeof(buf))) {
224 fatal("Entropy collection failed and entropy exhausted");
226 RAND_add(buf, sizeof(buf), sizeof(buf));
229 memset(buf, '\0', sizeof(buf));
235 check_openssl_version();
238 #else /* defined(USE_PRNGD) || defined(RANDOM_POOL) */
241 * FIXME: proper entropy estimations. All current values are guesses
242 * FIXME: (ATL) do estimates at compile time?
243 * FIXME: More entropy sources
246 /* slow command timeouts (all in milliseconds) */
247 /* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
248 static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
250 static int prng_seed_saved = 0;
251 static int prng_initialised = 0;
256 /* Proportion of data that is entropy */
258 /* Counter goes positive if this command times out */
259 unsigned int badness;
260 /* Increases by factor of two each timeout */
261 unsigned int sticky_badness;
262 /* Path to executable */
264 /* argv to pass to executable */
266 /* full command string (debug) */
270 double stir_from_system(void);
271 double stir_from_programs(void);
272 double stir_gettimeofday(double entropy_estimate);
273 double stir_clock(double entropy_estimate);
274 double stir_rusage(int who, double entropy_estimate);
275 double hash_output_from_command(entropy_source_t *src, char *hash);
277 /* this is initialised from a file, by prng_read_commands() */
278 entropy_source_t *entropy_sources = NULL;
281 stir_from_system(void)
283 double total_entropy_estimate;
286 total_entropy_estimate = 0;
289 RAND_add(&i, sizeof(i), 0.5);
290 total_entropy_estimate += 0.1;
293 RAND_add(&i, sizeof(i), 0.5);
294 total_entropy_estimate += 0.1;
297 RAND_add(&i, sizeof(i), 0.0);
299 RAND_add(&i, sizeof(i), 0.0);
301 total_entropy_estimate += stir_gettimeofday(1.0);
302 total_entropy_estimate += stir_clock(0.5);
303 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
305 return(total_entropy_estimate);
309 stir_from_programs(void)
313 double entropy_estimate;
314 double total_entropy_estimate;
315 char hash[SHA_DIGEST_LENGTH];
317 total_entropy_estimate = 0;
318 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
320 while (entropy_sources[c].path != NULL) {
322 if (!entropy_sources[c].badness) {
323 /* Hash output from command */
324 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
326 /* Scale back entropy estimate according to command's rate */
327 entropy_estimate *= entropy_sources[c].rate;
329 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
330 if (entropy_estimate > SHA_DIGEST_LENGTH)
331 entropy_estimate = SHA_DIGEST_LENGTH;
333 /* Scale back estimates for subsequent passes through list */
334 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
337 RAND_add(hash, sizeof(hash), entropy_estimate);
339 debug3("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
340 entropy_sources[c].cmdstring);
342 total_entropy_estimate += entropy_estimate;
344 /* Execution times should be a little unpredictable */
345 total_entropy_estimate += stir_gettimeofday(0.05);
346 total_entropy_estimate += stir_clock(0.05);
347 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
348 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
350 debug2("Command '%s' disabled (badness %d)",
351 entropy_sources[c].cmdstring, entropy_sources[c].badness);
353 if (entropy_sources[c].badness > 0)
354 entropy_sources[c].badness--;
361 return(total_entropy_estimate);
365 stir_gettimeofday(double entropy_estimate)
369 if (gettimeofday(&tv, NULL) == -1)
370 fatal("Couldn't gettimeofday: %s", strerror(errno));
372 RAND_add(&tv, sizeof(tv), entropy_estimate);
374 return(entropy_estimate);
378 stir_clock(double entropy_estimate)
384 RAND_add(&c, sizeof(c), entropy_estimate);
386 return(entropy_estimate);
387 #else /* _HAVE_CLOCK */
389 #endif /* _HAVE_CLOCK */
393 stir_rusage(int who, double entropy_estimate)
395 #ifdef HAVE_GETRUSAGE
398 if (getrusage(who, &ru) == -1)
401 RAND_add(&ru, sizeof(ru), entropy_estimate);
403 return(entropy_estimate);
404 #else /* _HAVE_GETRUSAGE */
406 #endif /* _HAVE_GETRUSAGE */
411 _get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
412 int secdiff, usecdiff;
414 secdiff = t2->tv_sec - t1->tv_sec;
415 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
416 return (int)(usecdiff / 1000);
420 hash_output_from_command(entropy_source_t *src, char *hash)
422 static int devnull = -1;
425 int cmd_eof = 0, error_abort = 0;
426 struct timeval tv_start, tv_current;
427 int msec_elapsed = 0;
432 int total_bytes_read;
435 debug3("Reading output from \'%s\'", src->cmdstring);
438 devnull = open("/dev/null", O_RDWR);
440 fatal("Couldn't open /dev/null: %s", strerror(errno));
444 fatal("Couldn't open pipe: %s", strerror(errno));
446 (void)gettimeofday(&tv_start, NULL); /* record start time */
448 switch (pid = fork()) {
452 fatal("Couldn't fork: %s", strerror(errno));
455 dup2(devnull, STDIN_FILENO);
456 dup2(p[1], STDOUT_FILENO);
457 dup2(p[1], STDERR_FILENO);
462 setuid(original_uid);
463 execv(src->path, (char**)(src->args));
464 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
467 default: /* Parent */
471 RAND_add(&pid, sizeof(&pid), 0.0);
475 /* Hash output from child */
477 total_bytes_read = 0;
479 while (!error_abort && !cmd_eof) {
484 (void) gettimeofday(&tv_current, 0);
485 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
486 if (msec_elapsed >= entropy_timeout_current) {
490 msec_remaining = entropy_timeout_current - msec_elapsed;
493 FD_SET(p[0], &rdset);
494 tv.tv_sec = msec_remaining / 1000;
495 tv.tv_usec = (msec_remaining % 1000) * 1000;
497 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
499 RAND_add(&tv, sizeof(tv), 0.0);
508 bytes_read = read(p[0], buf, sizeof(buf));
509 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
510 if (bytes_read == -1) {
513 } else if (bytes_read) {
514 SHA1_Update(&sha, buf, bytes_read);
515 total_bytes_read += bytes_read;
523 debug("Command '%s': select() failed: %s", src->cmdstring,
530 SHA1_Final(hash, &sha);
534 debug3("Time elapsed: %d msec", msec_elapsed);
536 if (waitpid(pid, &status, 0) == -1) {
537 error("Couldn't wait for child '%s' completion: %s", src->cmdstring,
542 RAND_add(&status, sizeof(&status), 0.0);
545 /* closing p[0] on timeout causes the entropy command to
546 * SIGPIPE. Take whatever output we got, and mark this command
548 debug2("Command '%s' timed out", src->cmdstring);
549 src->sticky_badness *= 2;
550 src->badness = src->sticky_badness;
551 return(total_bytes_read);
554 if (WIFEXITED(status)) {
555 if (WEXITSTATUS(status)==0) {
556 return(total_bytes_read);
558 debug2("Command '%s' exit status was %d", src->cmdstring,
559 WEXITSTATUS(status));
560 src->badness = src->sticky_badness = 128;
563 } else if (WIFSIGNALED(status)) {
564 debug2("Command '%s' returned on uncaught signal %d !", src->cmdstring,
566 src->badness = src->sticky_badness = 128;
573 * prng seedfile functions
576 prng_check_seedfile(char *filename) {
580 /* FIXME raceable: eg replace seed between this stat and subsequent open */
581 /* Not such a problem because we don't trust the seed file anyway */
582 if (lstat(filename, &st) == -1) {
583 /* Give up on hard errors */
585 debug("WARNING: Couldn't stat random seed file \"%s\": %s",
586 filename, strerror(errno));
592 if (!S_ISREG(st.st_mode))
593 fatal("PRNG seedfile %.100s is not a regular file", filename);
595 /* mode 0600, owned by root or the current user? */
596 if (((st.st_mode & 0177) != 0) || !(st.st_uid == original_uid)) {
597 debug("WARNING: PRNG seedfile %.100s must be mode 0600, owned by uid %d",
606 prng_write_seedfile(void) {
612 /* Don't bother if we have already saved a seed */
616 setuid(original_uid);
620 pw = getpwuid(original_uid);
622 fatal("Couldn't get password entry for current user (%i): %s",
623 original_uid, strerror(errno));
625 /* Try to ensure that the parent directory is there */
626 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
628 mkdir(filename, 0700);
630 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
633 debug("writing PRNG seed to file %.100s", filename);
635 RAND_bytes(seed, sizeof(seed));
637 /* Don't care if the seed doesn't exist */
638 prng_check_seedfile(filename);
640 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) {
641 debug("WARNING: couldn't access PRNG seedfile %.100s (%.100s)",
642 filename, strerror(errno));
644 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
645 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
653 prng_read_seedfile(void) {
659 pw = getpwuid(original_uid);
661 fatal("Couldn't get password entry for current user (%i): %s",
662 original_uid, strerror(errno));
664 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
667 debug("loading PRNG seed from file %.100s", filename);
669 if (!prng_check_seedfile(filename)) {
670 verbose("Random seed file not found or not valid, ignoring.");
674 /* open the file and read in the seed */
675 fd = open(filename, O_RDONLY);
677 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
680 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
681 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
683 memset(seed, '\0', sizeof(seed));
687 /* stir in the seed, with estimated entropy zero */
688 RAND_add(&seed, sizeof(seed), 0.0);
693 * entropy command initialisation functions
696 prng_read_commands(char *cmdfilename)
707 entropy_source_t *entcmd;
709 f = fopen(cmdfilename, "r");
711 fatal("couldn't read entropy commands file %.100s: %.100s",
712 cmdfilename, strerror(errno));
715 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
716 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
720 while (fgets(line, sizeof(line), f)) {
726 /* skip leading whitespace, test for blank line or comment */
727 cp = line + strspn(line, WHITESPACE);
728 if ((*cp == 0) || (*cp == '#'))
729 continue; /* done with this line */
731 /* First non-whitespace char should be double quote delimiting */
734 error("bad entropy command, %.100s line %d", cmdfilename,
739 /* first token, command args (incl. argv[0]) in double quotes */
740 cp = strtok(cp, "\"");
742 error("missing or bad command string, %.100s line %d -- ignored",
743 cmdfilename, linenum);
746 strlcpy(cmd, cp, sizeof(cmd));
748 /* second token, full command path */
749 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
750 error("missing command path, %.100s line %d -- ignored",
751 cmdfilename, linenum);
755 /* did configure mark this as dead? */
756 if (strncmp("undef", cp, 5) == 0)
759 strlcpy(path, cp, sizeof(path));
761 /* third token, entropy rate estimate for this command */
762 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
763 error("missing entropy estimate, %.100s line %d -- ignored",
764 cmdfilename, linenum);
767 est = strtod(cp, &argv);
770 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
771 error("garbage at end of line %d in %.100s -- ignored", linenum,
776 /* save the command for debug messages */
777 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
779 /* split the command args */
780 cp = strtok(cmd, WHITESPACE);
784 char *s = (char*)xmalloc(strlen(cp) + 1);
785 strncpy(s, cp, strlen(cp) + 1);
786 entcmd[cur_cmd].args[arg] = s;
788 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
790 if (strtok(NULL, WHITESPACE))
791 error("ignored extra command elements (max 5), %.100s line %d",
792 cmdfilename, linenum);
794 /* Copy the command path and rate estimate */
795 entcmd[cur_cmd].path = xstrdup(path);
796 entcmd[cur_cmd].rate = est;
798 /* Initialise other values */
799 entcmd[cur_cmd].sticky_badness = 1;
803 /* If we've filled the array, reallocate it twice the size */
804 /* Do this now because even if this we're on the last command,
805 we need another slot to mark the last entry */
806 if (cur_cmd == num_cmds) {
808 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
812 /* zero the last entry */
813 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
816 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
818 debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
820 return (cur_cmd >= MIN_ENTROPY_SOURCES);
824 * Write a keyfile at exit
827 prng_seed_cleanup(void *junk)
829 prng_write_seedfile();
833 * Conditionally Seed OpenSSL's random number pool from
834 * syscalls and program output
839 mysig_t old_sigchld_handler;
841 if (!prng_initialised)
842 fatal("RNG not initialised");
844 /* Make sure some other sigchld handler doesn't reap our entropy */
846 old_sigchld_handler = mysignal(SIGCHLD, SIG_DFL);
848 debug("Seeded RNG with %i bytes from programs",
849 (int)stir_from_programs());
850 debug("Seeded RNG with %i bytes from system calls",
851 (int)stir_from_system());
854 fatal("Not enough entropy in RNG");
856 mysignal(SIGCHLD, old_sigchld_handler);
859 fatal("Couldn't initialise builtin random number generator -- exiting.");
867 check_openssl_version();
869 original_uid = getuid();
870 original_euid = geteuid();
872 /* Read in collection commands */
873 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
874 fatal("PRNG initialisation failed -- exiting.");
876 /* Set ourselves up to save a seed upon exit */
879 /* Give up privs while reading seed file */
880 #ifdef SAVED_IDS_WORK_WITH_SETEUID
881 if ((original_uid != original_euid) && (seteuid(original_uid) == -1))
882 fatal("Couldn't give up privileges");
883 #else /* SAVED_IDS_WORK_WITH_SETEUID */
885 * Propagate the privileged uid to all of our uids.
886 * Set the effective uid to the given (unprivileged) uid.
888 if (original_uid != original_euid && (setuid(original_euid) == -1 ||
889 seteuid(original_uid) == -1))
890 fatal("Couldn't give up privileges");
891 #endif /* SAVED_IDS_WORK_WITH_SETEUID */
893 prng_read_seedfile();
895 #ifdef SAVED_IDS_WORK_WITH_SETEUID
896 if ((original_uid != original_euid) && (seteuid(original_euid) == -1))
897 fatal("Couldn't restore privileges");
898 #else /* SAVED_IDS_WORK_WITH_SETEUID */
900 * We are unable to restore the real uid to its unprivileged value.
901 * Propagate the real uid (usually more privileged) to effective uid
904 if (original_uid != original_euid && (seteuid(original_euid) == -1 ||
905 setuid(original_uid) == -1))
906 fatal("Couldn't restore privileges");
907 #endif /* SAVED_IDS_WORK_WITH_SETEUID */
909 fatal_add_cleanup(prng_seed_cleanup, NULL);
910 atexit(prng_write_seedfile);
912 prng_initialised = 1;
915 #endif /* defined(USE_PRNGD) || defined(RANDOM_POOL) */