2 * Copyright (c) 2001 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 */
39 #include "pathnames.h"
42 #ifdef HAVE___PROGNAME
43 extern char *__progname;
50 #define RANDOM_SEED_SIZE 48
52 #ifndef SSH_PRNG_SEED_FILE
53 # define SSH_PRNG_SEED_FILE _PATH_SSH_USER_DIR"/prng_seed"
54 #endif /* SSH_PRNG_SEED_FILE */
55 #ifndef SSH_PRNG_COMMAND_FILE
56 # define SSH_PRNG_COMMAND_FILE ETCDIR "/ssh_prng_cmds"
57 #endif /* SSH_PRNG_COMMAND_FILE */
61 # define offsetof(type, member) ((size_t) &((type *)0)->member)
64 /* Number of times to pass through command list gathering entropy */
65 #define NUM_ENTROPY_RUNS 1
67 /* Scale entropy estimates back by this amount on subsequent runs */
68 #define SCALE_PER_RUN 10.0
70 /* Minimum number of commands to be considered valid */
71 #define MIN_ENTROPY_SOURCES 16
73 #define WHITESPACE " \t\n"
76 # define RUSAGE_SELF 0
78 #ifndef RUSAGE_CHILDREN
79 # define RUSAGE_CHILDREN 0
82 #if defined(PRNGD_SOCKET) || defined(PRNGD_PORT)
87 /* Collect entropy from PRNGD/EGD */
89 get_random_bytes(unsigned char *buf, int len)
94 struct sockaddr_in addr;
96 struct sockaddr_un addr;
98 int addr_len, rval, errors;
102 fatal("Too many bytes to read from PRNGD");
104 memset(&addr, '\0', sizeof(addr));
107 addr.sin_family = AF_INET;
108 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
109 addr.sin_port = htons(PRNGD_PORT);
110 addr_len = sizeof(struct sockaddr_in);
111 #else /* use IP socket PRNGD_SOCKET instead */
113 if (sizeof(PRNGD_SOCKET) > sizeof(addr.sun_path))
114 fatal("Random pool path is too long");
116 addr.sun_family = AF_UNIX;
117 strlcpy(addr.sun_path, PRNGD_SOCKET, sizeof(addr.sun_path));
118 addr_len = offsetof(struct sockaddr_un, sun_path) +
119 sizeof(PRNGD_SOCKET);
122 old_sigpipe = mysignal(SIGPIPE, SIG_IGN);
127 fd = socket(addr.sin_family, SOCK_STREAM, 0);
129 error("Couldn't create AF_INET socket: %s", strerror(errno));
133 fd = socket(addr.sun_family, SOCK_STREAM, 0);
135 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
140 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
142 error("Couldn't connect to PRNGD port %d: %s",
143 PRNGD_PORT, strerror(errno));
145 error("Couldn't connect to PRNGD socket \"%s\": %s",
146 addr.sun_path, strerror(errno));
151 /* Send blocking read request to PRNGD */
155 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
156 if (errno == EPIPE && errors < 10) {
161 error("Couldn't write to PRNGD socket: %s",
166 if (atomicio(read, fd, buf, len) != len) {
167 if (errno == EPIPE && errors < 10) {
172 error("Couldn't read from PRNGD socket: %s",
179 mysignal(SIGPIPE, old_sigpipe);
186 seed_openssl_rng(void)
188 unsigned char buf[RANDOM_SEED_SIZE];
190 if (!get_random_bytes(buf, sizeof(buf)))
191 fatal("Entropy collection failed");
193 RAND_add(buf, sizeof(buf), sizeof(buf));
194 memset(buf, '\0', sizeof(buf));
197 #else /* USE_PRNGD */
200 * FIXME: proper entropy estimations. All current values are guesses
201 * FIXME: (ATL) do estimates at compile time?
202 * FIXME: More entropy sources
205 /* slow command timeouts (all in milliseconds) */
206 /* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
207 static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
211 /* Proportion of data that is entropy */
213 /* Counter goes positive if this command times out */
214 unsigned int badness;
215 /* Increases by factor of two each timeout */
216 unsigned int sticky_badness;
217 /* Path to executable */
219 /* argv to pass to executable */
221 /* full command string (debug) */
225 double stir_from_system(void);
226 double stir_from_programs(void);
227 double stir_gettimeofday(double entropy_estimate);
228 double stir_clock(double entropy_estimate);
229 double stir_rusage(int who, double entropy_estimate);
230 double hash_output_from_command(entropy_source_t *src, char *hash);
232 /* this is initialised from a file, by prng_read_commands() */
233 entropy_source_t *entropy_sources = NULL;
236 stir_from_system(void)
238 double total_entropy_estimate;
241 total_entropy_estimate = 0;
244 RAND_add(&i, sizeof(i), 0.5);
245 total_entropy_estimate += 0.1;
248 RAND_add(&i, sizeof(i), 0.5);
249 total_entropy_estimate += 0.1;
252 RAND_add(&i, sizeof(i), 0.0);
254 RAND_add(&i, sizeof(i), 0.0);
256 total_entropy_estimate += stir_gettimeofday(1.0);
257 total_entropy_estimate += stir_clock(0.5);
258 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
260 return(total_entropy_estimate);
264 stir_from_programs(void)
268 double entropy_estimate;
269 double total_entropy_estimate;
270 char hash[SHA_DIGEST_LENGTH];
272 total_entropy_estimate = 0;
273 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
275 while (entropy_sources[c].path != NULL) {
277 if (!entropy_sources[c].badness) {
278 /* Hash output from command */
279 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
281 /* Scale back entropy estimate according to command's rate */
282 entropy_estimate *= entropy_sources[c].rate;
284 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
285 if (entropy_estimate > SHA_DIGEST_LENGTH)
286 entropy_estimate = SHA_DIGEST_LENGTH;
288 /* Scale back estimates for subsequent passes through list */
289 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
292 RAND_add(hash, sizeof(hash), entropy_estimate);
294 debug3("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
295 entropy_sources[c].cmdstring);
297 total_entropy_estimate += entropy_estimate;
299 /* Execution times should be a little unpredictable */
300 total_entropy_estimate += stir_gettimeofday(0.05);
301 total_entropy_estimate += stir_clock(0.05);
302 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
303 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
305 debug2("Command '%s' disabled (badness %d)",
306 entropy_sources[c].cmdstring, entropy_sources[c].badness);
308 if (entropy_sources[c].badness > 0)
309 entropy_sources[c].badness--;
316 return(total_entropy_estimate);
320 stir_gettimeofday(double entropy_estimate)
324 if (gettimeofday(&tv, NULL) == -1)
325 fatal("Couldn't gettimeofday: %s", strerror(errno));
327 RAND_add(&tv, sizeof(tv), entropy_estimate);
329 return(entropy_estimate);
333 stir_clock(double entropy_estimate)
339 RAND_add(&c, sizeof(c), entropy_estimate);
341 return(entropy_estimate);
342 #else /* _HAVE_CLOCK */
344 #endif /* _HAVE_CLOCK */
348 stir_rusage(int who, double entropy_estimate)
350 #ifdef HAVE_GETRUSAGE
353 if (getrusage(who, &ru) == -1)
356 RAND_add(&ru, sizeof(ru), entropy_estimate);
358 return(entropy_estimate);
359 #else /* _HAVE_GETRUSAGE */
361 #endif /* _HAVE_GETRUSAGE */
366 _get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
367 int secdiff, usecdiff;
369 secdiff = t2->tv_sec - t1->tv_sec;
370 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
371 return (int)(usecdiff / 1000);
375 hash_output_from_command(entropy_source_t *src, char *hash)
377 static int devnull = -1;
380 int cmd_eof = 0, error_abort = 0;
381 struct timeval tv_start, tv_current;
382 int msec_elapsed = 0;
387 int total_bytes_read;
390 debug3("Reading output from \'%s\'", src->cmdstring);
393 devnull = open("/dev/null", O_RDWR);
395 fatal("Couldn't open /dev/null: %s", strerror(errno));
399 fatal("Couldn't open pipe: %s", strerror(errno));
401 (void)gettimeofday(&tv_start, NULL); /* record start time */
403 switch (pid = fork()) {
407 fatal("Couldn't fork: %s", strerror(errno));
410 dup2(devnull, STDIN_FILENO);
411 dup2(p[1], STDOUT_FILENO);
412 dup2(p[1], STDERR_FILENO);
417 execv(src->path, (char**)(src->args));
418 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
421 default: /* Parent */
425 RAND_add(&pid, sizeof(&pid), 0.0);
429 /* Hash output from child */
431 total_bytes_read = 0;
433 while (!error_abort && !cmd_eof) {
438 (void) gettimeofday(&tv_current, 0);
439 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
440 if (msec_elapsed >= entropy_timeout_current) {
444 msec_remaining = entropy_timeout_current - msec_elapsed;
447 FD_SET(p[0], &rdset);
448 tv.tv_sec = msec_remaining / 1000;
449 tv.tv_usec = (msec_remaining % 1000) * 1000;
451 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
453 RAND_add(&tv, sizeof(tv), 0.0);
463 bytes_read = read(p[0], buf, sizeof(buf));
464 } while (bytes_read == -1 && errno == EINTR);
465 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
466 if (bytes_read == -1) {
469 } else if (bytes_read) {
470 SHA1_Update(&sha, buf, bytes_read);
471 total_bytes_read += bytes_read;
479 debug("Command '%s': select() failed: %s", src->cmdstring,
486 SHA1_Final(hash, &sha);
490 debug3("Time elapsed: %d msec", msec_elapsed);
492 if (waitpid(pid, &status, 0) == -1) {
493 error("Couldn't wait for child '%s' completion: %s", src->cmdstring,
498 RAND_add(&status, sizeof(&status), 0.0);
501 /* closing p[0] on timeout causes the entropy command to
502 * SIGPIPE. Take whatever output we got, and mark this command
504 debug2("Command '%s' timed out", src->cmdstring);
505 src->sticky_badness *= 2;
506 src->badness = src->sticky_badness;
507 return(total_bytes_read);
510 if (WIFEXITED(status)) {
511 if (WEXITSTATUS(status)==0) {
512 return(total_bytes_read);
514 debug2("Command '%s' exit status was %d", src->cmdstring,
515 WEXITSTATUS(status));
516 src->badness = src->sticky_badness = 128;
519 } else if (WIFSIGNALED(status)) {
520 debug2("Command '%s' returned on uncaught signal %d !", src->cmdstring,
522 src->badness = src->sticky_badness = 128;
529 * prng seedfile functions
532 prng_check_seedfile(char *filename) {
536 /* FIXME raceable: eg replace seed between this stat and subsequent open */
537 /* Not such a problem because we don't trust the seed file anyway */
538 if (lstat(filename, &st) == -1) {
539 /* Give up on hard errors */
541 debug("WARNING: Couldn't stat random seed file \"%s\": %s",
542 filename, strerror(errno));
548 if (!S_ISREG(st.st_mode))
549 fatal("PRNG seedfile %.100s is not a regular file", filename);
551 /* mode 0600, owned by root or the current user? */
552 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid())) {
553 debug("WARNING: PRNG seedfile %.100s must be mode 0600, owned by uid %d",
562 prng_write_seedfile(void) {
568 pw = getpwuid(getuid());
570 fatal("Couldn't get password entry for current user (%i): %s",
571 getuid(), strerror(errno));
573 /* Try to ensure that the parent directory is there */
574 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
576 mkdir(filename, 0700);
578 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
581 debug("writing PRNG seed to file %.100s", filename);
583 RAND_bytes(seed, sizeof(seed));
585 /* Don't care if the seed doesn't exist */
586 prng_check_seedfile(filename);
588 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) {
589 debug("WARNING: couldn't access PRNG seedfile %.100s (%.100s)",
590 filename, strerror(errno));
592 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
593 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
600 prng_read_seedfile(void) {
606 pw = getpwuid(getuid());
608 fatal("Couldn't get password entry for current user (%i): %s",
609 getuid(), strerror(errno));
611 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
614 debug("loading PRNG seed from file %.100s", filename);
616 if (!prng_check_seedfile(filename)) {
617 verbose("Random seed file not found or not valid, ignoring.");
621 /* open the file and read in the seed */
622 fd = open(filename, O_RDONLY);
624 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
627 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
628 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
630 memset(seed, '\0', sizeof(seed));
634 /* stir in the seed, with estimated entropy zero */
635 RAND_add(&seed, sizeof(seed), 0.0);
640 * entropy command initialisation functions
643 prng_read_commands(char *cmdfilename)
654 entropy_source_t *entcmd;
656 f = fopen(cmdfilename, "r");
658 fatal("couldn't read entropy commands file %.100s: %.100s",
659 cmdfilename, strerror(errno));
662 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
663 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
667 while (fgets(line, sizeof(line), f)) {
673 /* skip leading whitespace, test for blank line or comment */
674 cp = line + strspn(line, WHITESPACE);
675 if ((*cp == 0) || (*cp == '#'))
676 continue; /* done with this line */
678 /* First non-whitespace char should be double quote delimiting */
681 error("bad entropy command, %.100s line %d", cmdfilename,
686 /* first token, command args (incl. argv[0]) in double quotes */
687 cp = strtok(cp, "\"");
689 error("missing or bad command string, %.100s line %d -- ignored",
690 cmdfilename, linenum);
693 strlcpy(cmd, cp, sizeof(cmd));
695 /* second token, full command path */
696 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
697 error("missing command path, %.100s line %d -- ignored",
698 cmdfilename, linenum);
702 /* did configure mark this as dead? */
703 if (strncmp("undef", cp, 5) == 0)
706 strlcpy(path, cp, sizeof(path));
708 /* third token, entropy rate estimate for this command */
709 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
710 error("missing entropy estimate, %.100s line %d -- ignored",
711 cmdfilename, linenum);
714 est = strtod(cp, &argv);
717 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
718 error("garbage at end of line %d in %.100s -- ignored", linenum,
723 /* save the command for debug messages */
724 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
726 /* split the command args */
727 cp = strtok(cmd, WHITESPACE);
731 char *s = (char*)xmalloc(strlen(cp) + 1);
732 strncpy(s, cp, strlen(cp) + 1);
733 entcmd[cur_cmd].args[arg] = s;
735 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
737 if (strtok(NULL, WHITESPACE))
738 error("ignored extra command elements (max 5), %.100s line %d",
739 cmdfilename, linenum);
741 /* Copy the command path and rate estimate */
742 entcmd[cur_cmd].path = xstrdup(path);
743 entcmd[cur_cmd].rate = est;
745 /* Initialise other values */
746 entcmd[cur_cmd].sticky_badness = 1;
750 /* If we've filled the array, reallocate it twice the size */
751 /* Do this now because even if this we're on the last command,
752 we need another slot to mark the last entry */
753 if (cur_cmd == num_cmds) {
755 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
759 /* zero the last entry */
760 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
763 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
765 debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
767 return (cur_cmd >= MIN_ENTROPY_SOURCES);
771 seed_openssl_rng(void)
773 /* Read in collection commands */
774 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
775 fatal("PRNG initialisation failed -- exiting.");
777 prng_read_seedfile();
779 debug("Seeded RNG with %i bytes from programs",
780 (int)stir_from_programs());
781 debug("Seeded RNG with %i bytes from system calls",
782 (int)stir_from_system());
784 prng_write_seedfile();
787 #endif /* USE_PRNGD */
790 main(int argc, char **argv)
792 unsigned char buf[48];
795 __progname = get_progname(argv[0]);
796 /* XXX: need some debugging mode */
797 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
802 fatal("Not enough entropy in RNG");
804 RAND_bytes(buf, sizeof(buf));
806 ret = atomicio(write, STDOUT_FILENO, buf, sizeof(buf));
808 memset(buf, '\0', sizeof(buf));
810 return ret == sizeof(buf) ? 0 : 1;