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.
12 * 3. All advertising materials mentioning features or use of this software
13 * must display the following acknowledgement:
14 * This product includes software developed by Markus Friedl.
15 * 4. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 #include <openssl/rand.h>
36 #include <openssl/sha.h>
42 # define offsetof(type, member) ((size_t) &((type *)0)->member)
44 /* Collect entropy from EGD */
45 void get_random_bytes(unsigned char *buf, int len)
47 static int egd_socket = -1;
49 char egd_message[2] = { 0x02, 0x00 };
50 struct sockaddr_un addr;
53 memset(&addr, '\0', sizeof(addr));
54 addr.sun_family = AF_UNIX;
56 /* FIXME: compile time check? */
57 if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
58 fatal("Random pool path is too long");
60 strcpy(addr.sun_path, EGD_SOCKET);
62 addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
64 if (egd_socket == -1) {
65 egd_socket = socket(AF_UNIX, SOCK_STREAM, 0);
67 fatal("Couldn't create AF_UNIX socket: %s", strerror(errno));
68 if (connect(egd_socket, (struct sockaddr*)&addr, addr_len) == -1)
69 fatal("Couldn't connect to EGD socket \"%s\": %s", addr.sun_path, strerror(errno));
73 fatal("Too many bytes to read from EGD");
75 /* Send blocking read request to EGD */
78 c = atomicio(write, egd_socket, egd_message, sizeof(egd_message));
80 fatal("Couldn't write to EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno));
82 c = atomicio(read, egd_socket, buf, len);
84 fatal("Couldn't read from EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno));
88 #else /* !EGD_SOCKET */
90 /* Collect entropy from /dev/urandom or pipe */
91 void get_random_bytes(unsigned char *buf, int len)
93 static int random_pool = -1;
96 if (random_pool == -1) {
97 random_pool = open(RANDOM_POOL, O_RDONLY);
98 if (random_pool == -1)
99 fatal("Couldn't open random pool \"%s\": %s", RANDOM_POOL, strerror(errno));
102 c = atomicio(read, random_pool, buf, len);
104 fatal("Couldn't read from random pool \"%s\": %s", RANDOM_POOL, strerror(errno));
106 #endif /* RANDOM_POOL */
107 #endif /* EGD_SOCKET */
109 #if !defined(EGD_SOCKET) && !defined(RANDOM_POOL)
111 * FIXME: proper entropy estimations. All current values are guesses
112 * FIXME: (ATL) do estimates at compile time?
113 * FIXME: More entropy sources
116 /* slow command timeouts (all in milliseconds) */
117 /* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
118 static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
120 static int prng_seed_loaded = 0;
121 static int prng_seed_saved = 0;
122 static int prng_commands_loaded = 0;
126 /* Proportion of data that is entropy */
128 /* Counter goes positive if this command times out */
129 unsigned int badness;
130 /* Increases by factor of two each timeout */
131 unsigned int sticky_badness;
132 /* Path to executable */
134 /* argv to pass to executable */
138 double stir_from_system(void);
139 double stir_from_programs(void);
140 double stir_gettimeofday(double entropy_estimate);
141 double stir_clock(double entropy_estimate);
142 double stir_rusage(int who, double entropy_estimate);
143 double hash_output_from_command(entropy_source_t *src, char *hash);
145 /* this is initialised from a file, by prng_read_commands() */
146 entropy_source_t *entropy_sources = NULL;
147 #define MIN_ENTROPY_SOURCES 16
151 stir_from_system(void)
153 double total_entropy_estimate;
156 total_entropy_estimate = 0;
159 RAND_add(&i, sizeof(i), 0.1);
160 total_entropy_estimate += 0.1;
163 RAND_add(&i, sizeof(i), 0.1);
164 total_entropy_estimate += 0.1;
167 RAND_add(&i, sizeof(i), 0.0);
169 RAND_add(&i, sizeof(i), 0.0);
171 total_entropy_estimate += stir_gettimeofday(1.0);
172 total_entropy_estimate += stir_clock(0.2);
173 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
175 return(total_entropy_estimate);
179 stir_from_programs(void)
183 double entropy_estimate;
184 double total_entropy_estimate;
185 char hash[SHA_DIGEST_LENGTH];
188 * Run through list of programs twice to catch differences
190 total_entropy_estimate = 0;
191 for(i = 0; i < 2; i++) {
193 while (entropy_sources[c].path != NULL) {
195 if (!entropy_sources[c].badness) {
196 /* Hash output from command */
197 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
199 /* Scale back entropy estimate according to command's rate */
200 entropy_estimate *= entropy_sources[c].rate;
202 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
203 if (entropy_estimate > SHA_DIGEST_LENGTH)
204 entropy_estimate = SHA_DIGEST_LENGTH;
206 /* * Scale back estimates for subsequent passes through list */
207 entropy_estimate /= 10.0 * (i + 1.0);
210 RAND_add(hash, sizeof(hash), entropy_estimate);
212 /* FIXME: turn this off later */
214 debug("Got %0.2f bytes of entropy from %s", entropy_estimate,
215 entropy_sources[c].path);
218 total_entropy_estimate += entropy_estimate;
220 /* Execution times should be a little unpredictable */
221 total_entropy_estimate += stir_gettimeofday(0.05);
222 total_entropy_estimate += stir_clock(0.05);
223 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
224 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
226 /* FIXME: turn this off later */
228 debug("Command '%s %s %s' disabled (badness %d)",
229 entropy_sources[c].path, entropy_sources[c].args[1],
230 entropy_sources[c].args[2], entropy_sources[c].badness);
233 if (entropy_sources[c].badness > 0)
234 entropy_sources[c].badness--;
241 return(total_entropy_estimate);
245 stir_gettimeofday(double entropy_estimate)
249 if (gettimeofday(&tv, NULL) == -1)
250 fatal("Couldn't gettimeofday: %s", strerror(errno));
252 RAND_add(&tv, sizeof(tv), entropy_estimate);
254 return(entropy_estimate);
258 stir_clock(double entropy_estimate)
264 RAND_add(&c, sizeof(c), entropy_estimate);
266 return(entropy_estimate);
267 #else /* _HAVE_CLOCK */
269 #endif /* _HAVE_CLOCK */
273 stir_rusage(int who, double entropy_estimate)
275 #ifdef HAVE_GETRUSAGE
278 if (getrusage(who, &ru) == -1)
279 fatal("Couldn't getrusage: %s", strerror(errno));
281 RAND_add(&ru, sizeof(ru), 0.1);
283 return(entropy_estimate);
284 #else /* _HAVE_GETRUSAGE */
286 #endif /* _HAVE_GETRUSAGE */
290 hash_output_from_command(entropy_source_t *src, char *hash)
292 static int devnull = -1;
295 int cmd_eof = 0, error_abort = 0;
300 int total_bytes_read;
304 devnull = open("/dev/null", O_RDWR);
306 fatal("Couldn't open /dev/null: %s", strerror(errno));
310 fatal("Couldn't open pipe: %s", strerror(errno));
312 switch (pid = fork()) {
316 fatal("Couldn't fork: %s", strerror(errno));
319 dup2(devnull, STDIN_FILENO);
320 dup2(p[1], STDOUT_FILENO);
321 dup2(p[1], STDERR_FILENO);
326 execv(src->path, (char**)(src->args));
327 debug("(child) Couldn't exec '%s %s %s': %s", src->path,
328 src->args[1], src->args[2], strerror(errno));
329 src->badness = src->sticky_badness = 128;
331 default: /* Parent */
335 RAND_add(&pid, sizeof(&pid), 0.0);
339 /* Hash output from child */
341 total_bytes_read = 0;
343 while (!error_abort && !cmd_eof) {
348 FD_SET(p[0], &rdset);
349 tv.tv_sec = entropy_timeout_current / 1000;
350 tv.tv_usec = (entropy_timeout_current % 1000) * 1000;
352 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
361 bytes_read = read(p[0], buf, sizeof(buf));
362 if (bytes_read == -1) {
366 SHA1_Update(&sha, buf, bytes_read);
367 total_bytes_read += bytes_read;
368 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
369 cmd_eof = bytes_read ? 0 : 1;
375 error("Command '%s %s': select() failed: %s", src->path, src->args[1],
381 RAND_add(&tv, sizeof(&tv), 0.0);
382 } /* while !error_abort && !cmd_eof */
384 SHA1_Final(hash, &sha);
388 if (waitpid(pid, &status, 0) == -1) {
389 error("Couldn't wait for child '%s %s' completion: %s", src->path,
390 src->args[1], strerror(errno));
391 /* return(-1); */ /* FIXME: (ATL) this doesn't feel right */
395 RAND_add(&status, sizeof(&status), 0.0);
398 /* closing p[0] on timeout causes the entropy command to
399 * SIGPIPE. Take whatever output we got, and mark this command
401 debug("Command %s %s timed out", src->path, src->args[1]);
402 src->sticky_badness *= 2;
403 src->badness = src->sticky_badness;
404 return(total_bytes_read);
407 if (WIFEXITED(status)) {
408 if (WEXITSTATUS(status)==0) {
409 return(total_bytes_read);
411 debug("Exit status was %d", WEXITSTATUS(status));
412 src->badness = src->sticky_badness = 128;
415 } else if (WIFSIGNALED(status)) {
416 debug("Returned on uncaught signal %d !", status);
417 src->badness = src->sticky_badness = 128;
424 * prng seedfile functions
427 prng_check_seedfile(char *filename) {
431 /* FIXME raceable: eg replace seed between this stat and subsequent open */
432 /* Not such a problem because we don't trust the seed file anyway */
433 if (lstat(filename, &st) == -1) {
434 /* Fail on hard errors */
436 fatal("Couldn't stat random seed file \"%s\": %s", filename,
443 if (!S_ISREG(st.st_mode))
444 fatal("PRNG seedfile %.100s is not a regular file", filename);
446 /* mode 0600, owned by root or the current user? */
447 if (((st.st_mode & 0177) != 0) || !(st.st_uid == geteuid()))
448 fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d",
455 prng_write_seedfile(void) {
461 /* Don't bother if we have already saved a seed */
467 pw = getpwuid(getuid());
469 fatal("Couldn't get password entry for current user (%i): %s",
470 getuid(), strerror(errno));
472 /* Try to ensure that the parent directory is there */
473 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
475 mkdir(filename, 0700);
477 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
480 debug("writing PRNG seed to file %.100s", filename);
482 RAND_bytes(seed, sizeof(seed));
484 /* Don't care if the seed doesn't exist */
485 prng_check_seedfile(filename);
487 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1)
488 fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename,
491 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
492 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
499 prng_read_seedfile(void) {
505 pw = getpwuid(getuid());
507 fatal("Couldn't get password entry for current user (%i): %s",
508 getuid(), strerror(errno));
510 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
513 debug("loading PRNG seed from file %.100s", filename);
515 if (!prng_check_seedfile(filename)) {
516 verbose("Random seed file not found, creating new");
517 prng_write_seedfile();
519 /* Reseed immediatly */
520 (void)stir_from_system();
521 (void)stir_from_programs();
525 /* open the file and read in the seed */
526 fd = open(filename, O_RDONLY);
528 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
531 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
532 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
534 memset(seed, '\0', sizeof(seed));
538 /* stir in the seed, with estimated entropy zero */
539 RAND_add(&seed, sizeof(seed), 0.0);
544 * entropy command initialisation functions
546 #define WHITESPACE " \t\n"
549 prng_read_commands(char *cmdfilename)
553 char cmd[1024], path[256];
557 entropy_source_t *entcmd;
561 f = fopen(cmdfilename, "r");
563 fatal("couldn't read entropy commands file %.100s: %.100s",
564 cmdfilename, strerror(errno));
569 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
570 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
572 while (fgets(line, sizeof(line), f)) {
575 /* skip leading whitespace, test for blank line or comment */
576 cp = line + strspn(line, WHITESPACE);
577 if ((*cp == 0) || (*cp == '#'))
578 continue; /* done with this line */
585 /* first token, command args (incl. argv[0]) in double quotes */
586 cp = strtok(cp, "\"");
588 error("missing or bad command string, %.100s line %d -- ignored",
589 cmdfilename, linenum);
592 strncpy(cmd, cp, sizeof(cmd));
593 /* second token, full command path */
594 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
595 error("missing command path, %.100s line %d -- ignored",
596 cmdfilename, linenum);
599 if (strncmp("undef", cp, 5)==0) /* did configure mark this as dead? */
602 strncpy(path, cp, sizeof(path));
603 /* third token, entropy rate estimate for this command */
604 if ( (cp = strtok(NULL, WHITESPACE)) == NULL) {
605 error("missing entropy estimate, %.100s line %d -- ignored",
606 cmdfilename, linenum);
609 est = strtod(cp, &argv);/* FIXME: (ATL) no error checking here */
612 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
613 error("garbage at end of line %d in %.100s -- ignored",
614 linenum, cmdfilename);
618 /* split the command args */
619 cp = strtok(cmd, WHITESPACE);
620 arg = 0; argv = NULL;
622 char *s = (char*)xmalloc(strlen(cp)+1);
623 strncpy(s, cp, strlen(cp)+1);
624 entcmd[cur_cmd].args[arg] = s;
626 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
627 if (strtok(NULL, WHITESPACE))
628 error("ignored extra command elements (max 5), %.100s line %d",
629 cmdfilename, linenum);
631 /* copy the command path and rate estimate */
632 entcmd[cur_cmd].path = (char *)xmalloc(strlen(path)+1);
633 strncpy(entcmd[cur_cmd].path, path, strlen(path)+1);
634 entcmd[cur_cmd].rate = est;
635 /* initialise other values */
636 entcmd[cur_cmd].sticky_badness = 1;
640 /* If we've filled the array, reallocate it twice the size */
641 /* Do this now because even if this we're on the last command,
642 we need another slot to mark the last entry */
643 if (cur_cmd == num_cmds) {
645 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
650 error("bad entropy command, %.100s line %d", cmdfilename,
656 /* zero the last entry */
657 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
659 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
661 debug("loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
663 return (cur_cmd >= MIN_ENTROPY_SOURCES);
667 #endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
669 #if defined(EGD_SOCKET) || defined(RANDOM_POOL)
672 * Seed OpenSSL's random number pool from Kernel random number generator
680 debug("Seeding random number generator");
681 get_random_bytes(buf, sizeof(buf));
682 RAND_add(buf, sizeof(buf), sizeof(buf));
683 memset(buf, '\0', sizeof(buf));
686 #else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
689 * Write a keyfile at exit
692 prng_seed_cleanup(void *junk)
694 prng_write_seedfile();
698 * Conditionally Seed OpenSSL's random number pool from
699 * syscalls and program output
704 if (!prng_commands_loaded) {
705 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
706 fatal("PRNG initialisation failed -- exiting.");
707 prng_commands_loaded = 1;
710 debug("Seeding random number generator.");
711 debug("OpenSSL random status is now %i\n", RAND_status());
712 debug("%i bytes from system calls", (int)stir_from_system());
713 debug("%i bytes from programs", (int)stir_from_programs());
714 debug("OpenSSL random status is now %i\n", RAND_status());
716 if (!prng_seed_loaded)
718 prng_seed_loaded = 1;
720 prng_read_seedfile();
721 fatal_add_cleanup(prng_seed_cleanup, NULL);
722 atexit(prng_write_seedfile);
725 #endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */