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
71 void check_openssl_version(void)
73 if (SSLeay() != OPENSSL_VERSION_NUMBER)
74 fatal("OpenSSL version mismatch. Built against %lx, you "
75 "have %lx", OPENSSL_VERSION_NUMBER, SSLeay());
78 #if defined(PRNGD_SOCKET) || defined(PRNGD_PORT)
82 #if defined(USE_PRNGD) || defined(RANDOM_POOL)
85 /* Collect entropy from PRNGD/EGD */
86 int get_random_bytes(unsigned char *buf, int len)
91 struct sockaddr_in addr;
93 struct sockaddr_un addr;
95 int addr_len, rval, errors;
98 memset(&addr, '\0', sizeof(addr));
101 addr.sin_family = AF_INET;
102 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
103 addr.sin_port = htons(PRNGD_PORT);
104 addr_len = sizeof(struct sockaddr_in);
105 #else /* use IP socket PRNGD_SOCKET instead */
107 if (sizeof(PRNGD_SOCKET) > sizeof(addr.sun_path))
108 fatal("Random pool path is too long");
110 fatal("Too many bytes to read from PRNGD");
112 addr.sun_family = AF_UNIX;
113 strlcpy(addr.sun_path, PRNGD_SOCKET, sizeof(addr.sun_path));
114 addr_len = offsetof(struct sockaddr_un, sun_path) +
115 sizeof(PRNGD_SOCKET);
118 old_sigpipe = mysignal(SIGPIPE, SIG_IGN);
123 fd = socket(addr.sin_family, SOCK_STREAM, 0);
125 error("Couldn't create AF_INET socket: %s", strerror(errno));
129 fd = socket(addr.sun_family, SOCK_STREAM, 0);
131 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
136 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
138 error("Couldn't connect to PRNGD port %d: %s",
139 PRNGD_PORT, strerror(errno));
141 error("Couldn't connect to PRNGD socket \"%s\": %s",
142 addr.sun_path, strerror(errno));
147 /* Send blocking read request to PRNGD */
151 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
152 if (errno == EPIPE && errors < 10) {
157 error("Couldn't write to PRNGD socket: %s",
162 if (atomicio(read, fd, buf, len) != len) {
163 if (errno == EPIPE && errors < 10) {
168 error("Couldn't read from PRNGD socket: %s",
175 mysignal(SIGPIPE, old_sigpipe);
180 #else /* !USE_PRNGD */
182 /* Collect entropy from /dev/urandom or pipe */
183 int get_random_bytes(unsigned char *buf, int len)
187 random_pool = open(RANDOM_POOL, O_RDONLY);
188 if (random_pool == -1) {
189 error("Couldn't open random pool \"%s\": %s",
190 RANDOM_POOL, strerror(errno));
194 if (atomicio(read, random_pool, buf, len) != len) {
195 error("Couldn't read from random pool \"%s\": %s",
196 RANDOM_POOL, strerror(errno));
205 #endif /* RANDOM_POOL */
206 #endif /* USE_PRNGD */
209 * Seed OpenSSL's random number pool from Kernel random number generator
215 unsigned char buf[32];
217 debug("Seeding random number generator");
219 if (!get_random_bytes(buf, sizeof(buf))) {
221 fatal("Entropy collection failed and entropy exhausted");
223 RAND_add(buf, sizeof(buf), sizeof(buf));
226 memset(buf, '\0', sizeof(buf));
231 check_openssl_version();
234 #else /* defined(USE_PRNGD) || defined(RANDOM_POOL) */
237 * FIXME: proper entropy estimations. All current values are guesses
238 * FIXME: (ATL) do estimates at compile time?
239 * FIXME: More entropy sources
242 /* slow command timeouts (all in milliseconds) */
243 /* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
244 static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
246 static int prng_seed_saved = 0;
247 static int prng_initialised = 0;
252 /* Proportion of data that is entropy */
254 /* Counter goes positive if this command times out */
255 unsigned int badness;
256 /* Increases by factor of two each timeout */
257 unsigned int sticky_badness;
258 /* Path to executable */
260 /* argv to pass to executable */
262 /* full command string (debug) */
266 double stir_from_system(void);
267 double stir_from_programs(void);
268 double stir_gettimeofday(double entropy_estimate);
269 double stir_clock(double entropy_estimate);
270 double stir_rusage(int who, double entropy_estimate);
271 double hash_output_from_command(entropy_source_t *src, char *hash);
273 /* this is initialised from a file, by prng_read_commands() */
274 entropy_source_t *entropy_sources = NULL;
277 stir_from_system(void)
279 double total_entropy_estimate;
282 total_entropy_estimate = 0;
285 RAND_add(&i, sizeof(i), 0.5);
286 total_entropy_estimate += 0.1;
289 RAND_add(&i, sizeof(i), 0.5);
290 total_entropy_estimate += 0.1;
293 RAND_add(&i, sizeof(i), 0.0);
295 RAND_add(&i, sizeof(i), 0.0);
297 total_entropy_estimate += stir_gettimeofday(1.0);
298 total_entropy_estimate += stir_clock(0.5);
299 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
301 return(total_entropy_estimate);
305 stir_from_programs(void)
309 double entropy_estimate;
310 double total_entropy_estimate;
311 char hash[SHA_DIGEST_LENGTH];
313 total_entropy_estimate = 0;
314 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
316 while (entropy_sources[c].path != NULL) {
318 if (!entropy_sources[c].badness) {
319 /* Hash output from command */
320 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
322 /* Scale back entropy estimate according to command's rate */
323 entropy_estimate *= entropy_sources[c].rate;
325 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
326 if (entropy_estimate > SHA_DIGEST_LENGTH)
327 entropy_estimate = SHA_DIGEST_LENGTH;
329 /* Scale back estimates for subsequent passes through list */
330 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
333 RAND_add(hash, sizeof(hash), entropy_estimate);
335 debug3("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
336 entropy_sources[c].cmdstring);
338 total_entropy_estimate += entropy_estimate;
340 /* Execution times should be a little unpredictable */
341 total_entropy_estimate += stir_gettimeofday(0.05);
342 total_entropy_estimate += stir_clock(0.05);
343 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
344 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
346 debug2("Command '%s' disabled (badness %d)",
347 entropy_sources[c].cmdstring, entropy_sources[c].badness);
349 if (entropy_sources[c].badness > 0)
350 entropy_sources[c].badness--;
357 return(total_entropy_estimate);
361 stir_gettimeofday(double entropy_estimate)
365 if (gettimeofday(&tv, NULL) == -1)
366 fatal("Couldn't gettimeofday: %s", strerror(errno));
368 RAND_add(&tv, sizeof(tv), entropy_estimate);
370 return(entropy_estimate);
374 stir_clock(double entropy_estimate)
380 RAND_add(&c, sizeof(c), entropy_estimate);
382 return(entropy_estimate);
383 #else /* _HAVE_CLOCK */
385 #endif /* _HAVE_CLOCK */
389 stir_rusage(int who, double entropy_estimate)
391 #ifdef HAVE_GETRUSAGE
394 if (getrusage(who, &ru) == -1)
397 RAND_add(&ru, sizeof(ru), entropy_estimate);
399 return(entropy_estimate);
400 #else /* _HAVE_GETRUSAGE */
402 #endif /* _HAVE_GETRUSAGE */
408 _get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
409 int secdiff, usecdiff;
411 secdiff = t2->tv_sec - t1->tv_sec;
412 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
413 return (int)(usecdiff / 1000);
417 hash_output_from_command(entropy_source_t *src, char *hash)
419 static int devnull = -1;
422 int cmd_eof = 0, error_abort = 0;
423 struct timeval tv_start, tv_current;
424 int msec_elapsed = 0;
429 int total_bytes_read;
432 debug3("Reading output from \'%s\'", src->cmdstring);
435 devnull = open("/dev/null", O_RDWR);
437 fatal("Couldn't open /dev/null: %s", strerror(errno));
441 fatal("Couldn't open pipe: %s", strerror(errno));
443 (void)gettimeofday(&tv_start, NULL); /* record start time */
445 switch (pid = fork()) {
449 fatal("Couldn't fork: %s", strerror(errno));
452 dup2(devnull, STDIN_FILENO);
453 dup2(p[1], STDOUT_FILENO);
454 dup2(p[1], STDERR_FILENO);
459 setuid(original_uid);
460 execv(src->path, (char**)(src->args));
461 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
464 default: /* Parent */
468 RAND_add(&pid, sizeof(&pid), 0.0);
472 /* Hash output from child */
474 total_bytes_read = 0;
476 while (!error_abort && !cmd_eof) {
481 (void) gettimeofday(&tv_current, 0);
482 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
483 if (msec_elapsed >= entropy_timeout_current) {
487 msec_remaining = entropy_timeout_current - msec_elapsed;
490 FD_SET(p[0], &rdset);
491 tv.tv_sec = msec_remaining / 1000;
492 tv.tv_usec = (msec_remaining % 1000) * 1000;
494 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
496 RAND_add(&tv, sizeof(tv), 0.0);
505 bytes_read = read(p[0], buf, sizeof(buf));
506 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
507 if (bytes_read == -1) {
510 } else if (bytes_read) {
511 SHA1_Update(&sha, buf, bytes_read);
512 total_bytes_read += bytes_read;
520 debug("Command '%s': select() failed: %s", src->cmdstring,
527 SHA1_Final(hash, &sha);
531 debug3("Time elapsed: %d msec", msec_elapsed);
533 if (waitpid(pid, &status, 0) == -1) {
534 error("Couldn't wait for child '%s' completion: %s", src->cmdstring,
539 RAND_add(&status, sizeof(&status), 0.0);
542 /* closing p[0] on timeout causes the entropy command to
543 * SIGPIPE. Take whatever output we got, and mark this command
545 debug2("Command '%s' timed out", src->cmdstring);
546 src->sticky_badness *= 2;
547 src->badness = src->sticky_badness;
548 return(total_bytes_read);
551 if (WIFEXITED(status)) {
552 if (WEXITSTATUS(status)==0) {
553 return(total_bytes_read);
555 debug2("Command '%s' exit status was %d", src->cmdstring,
556 WEXITSTATUS(status));
557 src->badness = src->sticky_badness = 128;
560 } else if (WIFSIGNALED(status)) {
561 debug2("Command '%s' returned on uncaught signal %d !", src->cmdstring,
563 src->badness = src->sticky_badness = 128;
570 * prng seedfile functions
573 prng_check_seedfile(char *filename) {
577 /* FIXME raceable: eg replace seed between this stat and subsequent open */
578 /* Not such a problem because we don't trust the seed file anyway */
579 if (lstat(filename, &st) == -1) {
580 /* Give up on hard errors */
582 debug("WARNING: Couldn't stat random seed file \"%s\": %s",
583 filename, strerror(errno));
589 if (!S_ISREG(st.st_mode))
590 fatal("PRNG seedfile %.100s is not a regular file", filename);
592 /* mode 0600, owned by root or the current user? */
593 if (((st.st_mode & 0177) != 0) || !(st.st_uid == original_uid)) {
594 debug("WARNING: PRNG seedfile %.100s must be mode 0600, owned by uid %d",
603 prng_write_seedfile(void) {
609 /* Don't bother if we have already saved a seed */
613 setuid(original_uid);
617 pw = getpwuid(original_uid);
619 fatal("Couldn't get password entry for current user (%i): %s",
620 original_uid, strerror(errno));
622 /* Try to ensure that the parent directory is there */
623 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
625 mkdir(filename, 0700);
627 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
630 debug("writing PRNG seed to file %.100s", filename);
632 RAND_bytes(seed, sizeof(seed));
634 /* Don't care if the seed doesn't exist */
635 prng_check_seedfile(filename);
637 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) {
638 debug("WARNING: couldn't access PRNG seedfile %.100s (%.100s)",
639 filename, strerror(errno));
641 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
642 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
650 prng_read_seedfile(void) {
656 pw = getpwuid(original_uid);
658 fatal("Couldn't get password entry for current user (%i): %s",
659 original_uid, strerror(errno));
661 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
664 debug("loading PRNG seed from file %.100s", filename);
666 if (!prng_check_seedfile(filename)) {
667 verbose("Random seed file not found or not valid, ignoring.");
671 /* open the file and read in the seed */
672 fd = open(filename, O_RDONLY);
674 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
677 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
678 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
680 memset(seed, '\0', sizeof(seed));
684 /* stir in the seed, with estimated entropy zero */
685 RAND_add(&seed, sizeof(seed), 0.0);
690 * entropy command initialisation functions
693 prng_read_commands(char *cmdfilename)
704 entropy_source_t *entcmd;
706 f = fopen(cmdfilename, "r");
708 fatal("couldn't read entropy commands file %.100s: %.100s",
709 cmdfilename, strerror(errno));
712 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
713 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
717 while (fgets(line, sizeof(line), f)) {
723 /* skip leading whitespace, test for blank line or comment */
724 cp = line + strspn(line, WHITESPACE);
725 if ((*cp == 0) || (*cp == '#'))
726 continue; /* done with this line */
728 /* First non-whitespace char should be double quote delimiting */
731 error("bad entropy command, %.100s line %d", cmdfilename,
736 /* first token, command args (incl. argv[0]) in double quotes */
737 cp = strtok(cp, "\"");
739 error("missing or bad command string, %.100s line %d -- ignored",
740 cmdfilename, linenum);
743 strlcpy(cmd, cp, sizeof(cmd));
745 /* second token, full command path */
746 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
747 error("missing command path, %.100s line %d -- ignored",
748 cmdfilename, linenum);
752 /* did configure mark this as dead? */
753 if (strncmp("undef", cp, 5) == 0)
756 strlcpy(path, cp, sizeof(path));
758 /* third token, entropy rate estimate for this command */
759 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
760 error("missing entropy estimate, %.100s line %d -- ignored",
761 cmdfilename, linenum);
764 est = strtod(cp, &argv);
767 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
768 error("garbage at end of line %d in %.100s -- ignored", linenum,
773 /* save the command for debug messages */
774 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
776 /* split the command args */
777 cp = strtok(cmd, WHITESPACE);
781 char *s = (char*)xmalloc(strlen(cp) + 1);
782 strncpy(s, cp, strlen(cp) + 1);
783 entcmd[cur_cmd].args[arg] = s;
785 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
787 if (strtok(NULL, WHITESPACE))
788 error("ignored extra command elements (max 5), %.100s line %d",
789 cmdfilename, linenum);
791 /* Copy the command path and rate estimate */
792 entcmd[cur_cmd].path = xstrdup(path);
793 entcmd[cur_cmd].rate = est;
795 /* Initialise other values */
796 entcmd[cur_cmd].sticky_badness = 1;
800 /* If we've filled the array, reallocate it twice the size */
801 /* Do this now because even if this we're on the last command,
802 we need another slot to mark the last entry */
803 if (cur_cmd == num_cmds) {
805 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
809 /* zero the last entry */
810 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
813 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
815 debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
817 return (cur_cmd >= MIN_ENTROPY_SOURCES);
821 * Write a keyfile at exit
824 prng_seed_cleanup(void *junk)
826 prng_write_seedfile();
830 * Conditionally Seed OpenSSL's random number pool from
831 * syscalls and program output
836 mysig_t old_sigchld_handler;
838 if (!prng_initialised)
839 fatal("RNG not initialised");
841 /* Make sure some other sigchld handler doesn't reap our entropy */
843 old_sigchld_handler = mysignal(SIGCHLD, SIG_DFL);
845 debug("Seeded RNG with %i bytes from programs", (int)stir_from_programs());
846 debug("Seeded RNG with %i bytes from system calls", (int)stir_from_system());
849 fatal("Not enough entropy in RNG");
851 mysignal(SIGCHLD, old_sigchld_handler);
854 fatal("Couldn't initialise builtin random number generator -- exiting.");
861 check_openssl_version();
863 original_uid = getuid();
864 original_euid = geteuid();
866 /* Read in collection commands */
867 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
868 fatal("PRNG initialisation failed -- exiting.");
870 /* Set ourselves up to save a seed upon exit */
873 /* Give up privs while reading seed file */
874 #ifdef SAVED_IDS_WORK_WITH_SETEUID
875 if ((original_uid != original_euid) && (seteuid(original_uid) == -1))
876 fatal("Couldn't give up privileges");
877 #else /* SAVED_IDS_WORK_WITH_SETEUID */
879 * Propagate the privileged uid to all of our uids.
880 * Set the effective uid to the given (unprivileged) uid.
882 if (original_uid != original_euid && (setuid(original_euid) == -1 ||
883 seteuid(original_uid) == -1))
884 fatal("Couldn't give up privileges");
885 #endif /* SAVED_IDS_WORK_WITH_SETEUID */
887 prng_read_seedfile();
889 #ifdef SAVED_IDS_WORK_WITH_SETEUID
890 if ((original_uid != original_euid) && (seteuid(original_euid) == -1))
891 fatal("Couldn't restore privileges");
892 #else /* SAVED_IDS_WORK_WITH_SETEUID */
894 * We are unable to restore the real uid to its unprivileged value.
895 * Propagate the real uid (usually more privileged) to effective uid
898 if (original_uid != original_euid && (seteuid(original_euid) == -1 ||
899 setuid(original_uid) == -1))
900 fatal("Couldn't restore privileges");
901 #endif /* SAVED_IDS_WORK_WITH_SETEUID */
903 fatal_add_cleanup(prng_seed_cleanup, NULL);
904 atexit(prng_write_seedfile);
906 prng_initialised = 1;
909 #endif /* defined(USE_PRNGD) || defined(RANDOM_POOL) */