X-Git-Url: http://andersk.mit.edu/gitweb/openssh.git/blobdiff_plain/b5b3f75db5e7e0b73c75ca3940a4ce29ab1e1e6c..d5c4c52e91bae71bda9a1beab2a1a6d8ddbe6760:/entropy.c diff --git a/entropy.c b/entropy.c index 1857e7c8..850bd17b 100644 --- a/entropy.c +++ b/entropy.c @@ -9,11 +9,6 @@ * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by Markus Friedl. - * 4. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES @@ -29,11 +24,21 @@ #include "includes.h" -#include "ssh.h" -#include "xmalloc.h" - #include #include +#include + +/* SunOS 4.4.4 needs this */ +#ifdef HAVE_FLOATINGPOINT_H +# include +#endif /* HAVE_FLOATINGPOINT_H */ + +#include "ssh.h" +#include "misc.h" +#include "xmalloc.h" +#include "atomicio.h" +#include "pathnames.h" +#include "log.h" RCSID("$Id$"); @@ -41,9 +46,6 @@ RCSID("$Id$"); # define offsetof(type, member) ((size_t) &((type *)0)->member) #endif -/* Print lots of detail */ -/* #define DEBUG_ENTROPY */ - /* Number of times to pass through command list gathering entropy */ #define NUM_ENTROPY_RUNS 1 @@ -62,6 +64,18 @@ RCSID("$Id$"); # define RUSAGE_CHILDREN 0 #endif +#if defined(_POSIX_SAVED_IDS) && !defined(BROKEN_SAVED_UIDS) +# define SAVED_IDS_WORK_WITH_SETEUID +#endif + +void check_openssl_version(void) +{ + if (SSLeay() != OPENSSL_VERSION_NUMBER) + fatal("OpenSSL version mismatch. Built against %x, you " + "have %x", OPENSSL_VERSION_NUMBER, SSLeay()); +} + + #if defined(EGD_SOCKET) || defined(RANDOM_POOL) #ifdef EGD_SOCKET @@ -71,7 +85,8 @@ int get_random_bytes(unsigned char *buf, int len) int fd; char msg[2]; struct sockaddr_un addr; - int addr_len; + int addr_len, rval, errors; + mysig_t old_sigpipe; /* Sanity checks */ if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path)) @@ -83,18 +98,21 @@ int get_random_bytes(unsigned char *buf, int len) addr.sun_family = AF_UNIX; strlcpy(addr.sun_path, EGD_SOCKET, sizeof(addr.sun_path)); addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET); - + + old_sigpipe = mysignal(SIGPIPE, SIG_IGN); + + errors = rval = 0; +reopen: fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { error("Couldn't create AF_UNIX socket: %s", strerror(errno)); - return(0); + goto done; } if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) { - error("Couldn't connect to EGD socket \"%s\": %s", + error("Couldn't connect to EGD socket \"%s\": %s", addr.sun_path, strerror(errno)); - close(fd); - return(0); + goto done; } /* Send blocking read request to EGD */ @@ -102,22 +120,33 @@ int get_random_bytes(unsigned char *buf, int len) msg[1] = len; if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) { - error("Couldn't write to EGD socket \"%s\": %s", + if (errno == EPIPE && errors < 10) { + close(fd); + errors++; + goto reopen; + } + error("Couldn't write to EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno)); - close(fd); - return(0); + goto done; } if (atomicio(read, fd, buf, len) != len) { - error("Couldn't read from EGD socket \"%s\": %s", + if (errno == EPIPE && errors < 10) { + close(fd); + errors++; + goto reopen; + } + error("Couldn't read from EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno)); - close(fd); - return(0); + goto done; } - - close(fd); - - return(1); + + rval = 1; +done: + mysignal(SIGPIPE, old_sigpipe); + if (fd != -1) + close(fd); + return(rval); } #else /* !EGD_SOCKET */ #ifdef RANDOM_POOL @@ -128,20 +157,20 @@ int get_random_bytes(unsigned char *buf, int len) random_pool = open(RANDOM_POOL, O_RDONLY); if (random_pool == -1) { - error("Couldn't open random pool \"%s\": %s", + error("Couldn't open random pool \"%s\": %s", RANDOM_POOL, strerror(errno)); return(0); } - + if (atomicio(read, random_pool, buf, len) != len) { - error("Couldn't read from random pool \"%s\": %s", + error("Couldn't read from random pool \"%s\": %s", RANDOM_POOL, strerror(errno)); close(random_pool); return(0); } - + close(random_pool); - + return(1); } #endif /* RANDOM_POOL */ @@ -155,7 +184,7 @@ void seed_rng(void) { char buf[32]; - + debug("Seeding random number generator"); if (!get_random_bytes(buf, sizeof(buf))) { @@ -164,13 +193,18 @@ seed_rng(void) } else { RAND_add(buf, sizeof(buf), sizeof(buf)); } - + memset(buf, '\0', sizeof(buf)); } +void init_rng(void) +{ + check_openssl_version(); +} + #else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */ -/* +/* * FIXME: proper entropy estimations. All current values are guesses * FIXME: (ATL) do estimates at compile time? * FIXME: More entropy sources @@ -180,9 +214,9 @@ seed_rng(void) /* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */ static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC; -static int prng_seed_loaded = 0; static int prng_seed_saved = 0; -static int prng_commands_loaded = 0; +static int prng_initialised = 0; +uid_t original_uid; typedef struct { @@ -210,18 +244,18 @@ double hash_output_from_command(entropy_source_t *src, char *hash); /* this is initialised from a file, by prng_read_commands() */ entropy_source_t *entropy_sources = NULL; -double +double stir_from_system(void) { double total_entropy_estimate; long int i; - + total_entropy_estimate = 0; - + i = getpid(); RAND_add(&i, sizeof(i), 0.5); total_entropy_estimate += 0.1; - + i = getppid(); RAND_add(&i, sizeof(i), 0.5); total_entropy_estimate += 0.1; @@ -238,7 +272,7 @@ stir_from_system(void) return(total_entropy_estimate); } -double +double stir_from_programs(void) { int i; @@ -258,21 +292,19 @@ stir_from_programs(void) /* Scale back entropy estimate according to command's rate */ entropy_estimate *= entropy_sources[c].rate; - + /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */ if (entropy_estimate > SHA_DIGEST_LENGTH) entropy_estimate = SHA_DIGEST_LENGTH; - /* Scale back estimates for subsequent passes through list */ + /* Scale back estimates for subsequent passes through list */ entropy_estimate /= SCALE_PER_RUN * (i + 1.0); - + /* Stir it in */ RAND_add(hash, sizeof(hash), entropy_estimate); -#ifdef DEBUG_ENTROPY - debug("Got %0.2f bytes of entropy from '%s'", entropy_estimate, + debug3("Got %0.2f bytes of entropy from '%s'", entropy_estimate, entropy_sources[c].cmdstring); -#endif total_entropy_estimate += entropy_estimate; @@ -282,10 +314,8 @@ stir_from_programs(void) total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1); total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1); } else { -#ifdef DEBUG_ENTROPY - debug("Command '%s' disabled (badness %d)", + debug2("Command '%s' disabled (badness %d)", entropy_sources[c].cmdstring, entropy_sources[c].badness); -#endif if (entropy_sources[c].badness > 0) entropy_sources[c].badness--; @@ -294,7 +324,7 @@ stir_from_programs(void) c++; } } - + return(total_entropy_estimate); } @@ -302,12 +332,12 @@ double stir_gettimeofday(double entropy_estimate) { struct timeval tv; - + if (gettimeofday(&tv, NULL) == -1) fatal("Couldn't gettimeofday: %s", strerror(errno)); RAND_add(&tv, sizeof(tv), entropy_estimate); - + return(entropy_estimate); } @@ -316,10 +346,10 @@ stir_clock(double entropy_estimate) { #ifdef HAVE_CLOCK clock_t c; - + c = clock(); RAND_add(&c, sizeof(c), entropy_estimate); - + return(entropy_estimate); #else /* _HAVE_CLOCK */ return(0); @@ -331,7 +361,7 @@ stir_rusage(int who, double entropy_estimate) { #ifdef HAVE_GETRUSAGE struct rusage ru; - + if (getrusage(who, &ru) == -1) return(0); @@ -369,13 +399,15 @@ hash_output_from_command(entropy_source_t *src, char *hash) int bytes_read; int total_bytes_read; SHA_CTX sha; - + + debug3("Reading output from \'%s\'", src->cmdstring); + if (devnull == -1) { devnull = open("/dev/null", O_RDWR); if (devnull == -1) fatal("Couldn't open /dev/null: %s", strerror(errno)); } - + if (pipe(p) == -1) fatal("Couldn't open pipe: %s", strerror(errno)); @@ -395,10 +427,10 @@ hash_output_from_command(entropy_source_t *src, char *hash) close(p[1]); close(devnull); + setuid(original_uid); execv(src->path, (char**)(src->args)); debug("(child) Couldn't exec '%s': %s", src->cmdstring, strerror(errno)); - src->badness = src->sticky_badness = 128; _exit(-1); default: /* Parent */ break; @@ -432,49 +464,45 @@ hash_output_from_command(entropy_source_t *src, char *hash) ret = select(p[0]+1, &rdset, NULL, NULL, &tv); + RAND_add(&tv, sizeof(tv), 0.0); + switch (ret) { case 0: /* timer expired */ error_abort = 1; break; - case 1: /* command input */ bytes_read = read(p[0], buf, sizeof(buf)); + RAND_add(&bytes_read, sizeof(&bytes_read), 0.0); if (bytes_read == -1) { error_abort = 1; break; - } - if (bytes_read) { + } else if (bytes_read) { SHA1_Update(&sha, buf, bytes_read); total_bytes_read += bytes_read; - RAND_add(&bytes_read, sizeof(&bytes_read), 0.0); - } else + } else { cmd_eof = 1; - + } break; - case -1: default: + /* error */ debug("Command '%s': select() failed: %s", src->cmdstring, strerror(errno)); error_abort = 1; break; - } /* switch ret */ - - RAND_add(&tv, sizeof(&tv), 0.0); - } /* while !error_abort && !cmd_eof */ + } + } SHA1_Final(hash, &sha); close(p[0]); -#ifdef DEBUG_ENTROPY - debug("Time elapsed: %d msec", msec_elapsed); -#endif - + debug3("Time elapsed: %d msec", msec_elapsed); + if (waitpid(pid, &status, 0) == -1) { - debug("Couldn't wait for child '%s' completion: %s", src->cmdstring, + error("Couldn't wait for child '%s' completion: %s", src->cmdstring, strerror(errno)); return(0.0); } @@ -485,7 +513,7 @@ hash_output_from_command(entropy_source_t *src, char *hash) /* closing p[0] on timeout causes the entropy command to * SIGPIPE. Take whatever output we got, and mark this command * as slow */ - debug("Command '%s' timed out", src->cmdstring); + debug2("Command '%s' timed out", src->cmdstring); src->sticky_badness *= 2; src->badness = src->sticky_badness; return(total_bytes_read); @@ -495,13 +523,13 @@ hash_output_from_command(entropy_source_t *src, char *hash) if (WEXITSTATUS(status)==0) { return(total_bytes_read); } else { - debug("Command '%s' exit status was %d", src->cmdstring, + debug2("Command '%s' exit status was %d", src->cmdstring, WEXITSTATUS(status)); src->badness = src->sticky_badness = 128; return (0.0); } } else if (WIFSIGNALED(status)) { - debug("Command '%s' returned on uncaught signal %d !", src->cmdstring, + debug2("Command '%s' returned on uncaught signal %d !", src->cmdstring, status); src->badness = src->sticky_badness = 128; return(0.0); @@ -520,10 +548,10 @@ prng_check_seedfile(char *filename) { /* FIXME raceable: eg replace seed between this stat and subsequent open */ /* Not such a problem because we don't trust the seed file anyway */ if (lstat(filename, &st) == -1) { - /* Fail on hard errors */ + /* Give up on hard errors */ if (errno != ENOENT) - fatal("Couldn't stat random seed file \"%s\": %s", filename, - strerror(errno)); + debug("WARNING: Couldn't stat random seed file \"%s\": %s", + filename, strerror(errno)); return(0); } @@ -533,9 +561,11 @@ prng_check_seedfile(char *filename) { fatal("PRNG seedfile %.100s is not a regular file", filename); /* mode 0600, owned by root or the current user? */ - if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid())) - fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d", + if (((st.st_mode & 0177) != 0) || !(st.st_uid == original_uid)) { + debug("WARNING: PRNG seedfile %.100s must be mode 0600, owned by uid %d", filename, getuid()); + return(0); + } return(1); } @@ -550,20 +580,22 @@ prng_write_seedfile(void) { /* Don't bother if we have already saved a seed */ if (prng_seed_saved) return; - + + setuid(original_uid); + prng_seed_saved = 1; - - pw = getpwuid(getuid()); + + pw = getpwuid(original_uid); if (pw == NULL) - fatal("Couldn't get password entry for current user (%i): %s", - getuid(), strerror(errno)); - + fatal("Couldn't get password entry for current user (%i): %s", + original_uid, strerror(errno)); + /* Try to ensure that the parent directory is there */ - snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, - SSH_USER_DIR); + snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, + _PATH_SSH_USER_DIR); mkdir(filename, 0700); - snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, + snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, SSH_PRNG_SEED_FILE); debug("writing PRNG seed to file %.100s", filename); @@ -572,16 +604,17 @@ prng_write_seedfile(void) { /* Don't care if the seed doesn't exist */ prng_check_seedfile(filename); - - if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) - fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename, - strerror(errno)); - - if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed)) - fatal("problem writing PRNG seedfile %.100s (%.100s)", filename, - strerror(errno)); - close(fd); + if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) { + debug("WARNING: couldn't access PRNG seedfile %.100s (%.100s)", + filename, strerror(errno)); + } else { + if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed)) + fatal("problem writing PRNG seedfile %.100s (%.100s)", filename, + strerror(errno)); + + close(fd); + } } void @@ -590,31 +623,26 @@ prng_read_seedfile(void) { char seed[1024]; char filename[1024]; struct passwd *pw; - - pw = getpwuid(getuid()); + + pw = getpwuid(original_uid); if (pw == NULL) - fatal("Couldn't get password entry for current user (%i): %s", - getuid(), strerror(errno)); - - snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, + fatal("Couldn't get password entry for current user (%i): %s", + original_uid, strerror(errno)); + + snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, SSH_PRNG_SEED_FILE); debug("loading PRNG seed from file %.100s", filename); if (!prng_check_seedfile(filename)) { - verbose("Random seed file not found, creating new"); - prng_write_seedfile(); - - /* Reseed immediatly */ - (void)stir_from_system(); - (void)stir_from_programs(); + verbose("Random seed file not found or not valid, ignoring."); return; } /* open the file and read in the seed */ fd = open(filename, O_RDONLY); if (fd == -1) - fatal("could not open PRNG seedfile %.100s (%.100s)", filename, + fatal("could not open PRNG seedfile %.100s (%.100s)", filename, strerror(errno)); if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) { @@ -674,7 +702,7 @@ prng_read_commands(char *cmdfilename) error("bad entropy command, %.100s line %d", cmdfilename, linenum); continue; - } + } /* first token, command args (incl. argv[0]) in double quotes */ cp = strtok(cp, "\""); @@ -684,7 +712,7 @@ prng_read_commands(char *cmdfilename) continue; } strlcpy(cmd, cp, sizeof(cmd)); - + /* second token, full command path */ if ((cp = strtok(NULL, WHITESPACE)) == NULL) { error("missing command path, %.100s line %d -- ignored", @@ -696,7 +724,7 @@ prng_read_commands(char *cmdfilename) if (strncmp("undef", cp, 5) == 0) continue; - strlcpy(path, cp, sizeof(path)); + strlcpy(path, cp, sizeof(path)); /* third token, entropy rate estimate for this command */ if ((cp = strtok(NULL, WHITESPACE)) == NULL) { @@ -708,14 +736,14 @@ prng_read_commands(char *cmdfilename) /* end of line */ if ((cp = strtok(NULL, WHITESPACE)) != NULL) { - error("garbage at end of line %d in %.100s -- ignored", linenum, + error("garbage at end of line %d in %.100s -- ignored", linenum, cmdfilename); continue; } /* save the command for debug messages */ entcmd[cur_cmd].cmdstring = xstrdup(cmd); - + /* split the command args */ cp = strtok(cmd, WHITESPACE); arg = 0; @@ -726,7 +754,7 @@ prng_read_commands(char *cmdfilename) entcmd[cur_cmd].args[arg] = s; arg++; } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE))); - + if (strtok(NULL, WHITESPACE)) error("ignored extra command elements (max 5), %.100s line %d", cmdfilename, linenum); @@ -755,14 +783,14 @@ prng_read_commands(char *cmdfilename) /* trim to size */ entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t)); - debug("loaded %d entropy commands from %.100s", cur_cmd, cmdfilename); + debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename); return (cur_cmd >= MIN_ENTROPY_SOURCES); } /* * Write a keyfile at exit - */ + */ void prng_seed_cleanup(void *junk) { @@ -776,36 +804,77 @@ prng_seed_cleanup(void *junk) void seed_rng(void) { - void *old_sigchld_handler; - - if (!prng_commands_loaded) { - if (!prng_read_commands(SSH_PRNG_COMMAND_FILE)) - fatal("PRNG initialisation failed -- exiting."); - prng_commands_loaded = 1; - } + mysig_t old_sigchld_handler; + + if (!prng_initialised) + fatal("RNG not initialised"); /* Make sure some other sigchld handler doesn't reap our entropy */ /* commands */ - old_sigchld_handler = signal(SIGCHLD, SIG_DFL); + old_sigchld_handler = mysignal(SIGCHLD, SIG_DFL); - debug("Seeding random number generator."); - debug("OpenSSL random status is now %i\n", RAND_status()); - debug("%i bytes from system calls", (int)stir_from_system()); - debug("%i bytes from programs", (int)stir_from_programs()); - debug("OpenSSL random status is now %i\n", RAND_status()); + debug("Seeded RNG with %i bytes from programs", (int)stir_from_programs()); + debug("Seeded RNG with %i bytes from system calls", (int)stir_from_system()); - signal(SIGCHLD, old_sigchld_handler); + if (!RAND_status()) + fatal("Not enough entropy in RNG"); + + mysignal(SIGCHLD, old_sigchld_handler); if (!RAND_status()) fatal("Couldn't initialise builtin random number generator -- exiting."); +} - if (!prng_seed_loaded) - { - prng_seed_loaded = 1; - prng_seed_saved = 0; - prng_read_seedfile(); - fatal_add_cleanup(prng_seed_cleanup, NULL); - atexit(prng_write_seedfile); - } +void init_rng(void) +{ + int original_euid; + + check_openssl_version(); + + original_uid = getuid(); + original_euid = geteuid(); + + /* Read in collection commands */ + if (!prng_read_commands(SSH_PRNG_COMMAND_FILE)) + fatal("PRNG initialisation failed -- exiting."); + + /* Set ourselves up to save a seed upon exit */ + prng_seed_saved = 0; + + /* Give up privs while reading seed file */ +#ifdef SAVED_IDS_WORK_WITH_SETEUID + if ((original_uid != original_euid) && (seteuid(original_uid) == -1)) + fatal("Couldn't give up privileges"); +#else /* SAVED_IDS_WORK_WITH_SETEUID */ + /* + * Propagate the privileged uid to all of our uids. + * Set the effective uid to the given (unprivileged) uid. + */ + if (original_uid != original_euid && (setuid(original_euid) == -1 || + seteuid(original_uid) == -1)) + fatal("Couldn't give up privileges"); +#endif /* SAVED_IDS_WORK_WITH_SETEUID */ + + prng_read_seedfile(); + +#ifdef SAVED_IDS_WORK_WITH_SETEUID + if ((original_uid != original_euid) && (seteuid(original_euid) == -1)) + fatal("Couldn't restore privileges"); +#else /* SAVED_IDS_WORK_WITH_SETEUID */ + /* + * We are unable to restore the real uid to its unprivileged value. + * Propagate the real uid (usually more privileged) to effective uid + * as well. + */ + if (original_uid != original_euid && (seteuid(original_euid) == -1 || + setuid(original_uid) == -1)) + fatal("Couldn't restore privileges"); +#endif /* SAVED_IDS_WORK_WITH_SETEUID */ + + fatal_add_cleanup(prng_seed_cleanup, NULL); + atexit(prng_write_seedfile); + + prng_initialised = 1; } + #endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */