- (djm) [loginrec.c ssh-rand-helper.c sshd.c openbsd-compat/glob.c]
[openssh-git.git] / ssh-rand-helper.c
blobebee90014d3cbb42ae9d8cd744fde27c711aa74b
1 /*
2 * Copyright (c) 2001-2002 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
6 * are met:
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.
25 #include "includes.h"
27 #include <sys/types.h>
28 #include <sys/resource.h>
29 #include <sys/stat.h>
30 #include <sys/wait.h>
31 #include <sys/socket.h>
33 #include <netinet/in.h>
35 #ifdef HAVE_SYS_UN_H
36 # include <sys/un.h>
37 #endif
39 #include <fcntl.h>
40 #include <pwd.h>
41 #include <signal.h>
43 #include <openssl/rand.h>
44 #include <openssl/sha.h>
45 #include <openssl/crypto.h>
47 /* SunOS 4.4.4 needs this */
48 #ifdef HAVE_FLOATINGPOINT_H
49 # include <floatingpoint.h>
50 #endif /* HAVE_FLOATINGPOINT_H */
52 #include "misc.h"
53 #include "xmalloc.h"
54 #include "atomicio.h"
55 #include "pathnames.h"
56 #include "log.h"
58 /* Number of bytes we write out */
59 #define OUTPUT_SEED_SIZE 48
61 /* Length of on-disk seedfiles */
62 #define SEED_FILE_SIZE 1024
64 /* Maximum number of command-line arguments to read from file */
65 #define NUM_ARGS 10
67 /* Minimum number of usable commands to be considered sufficient */
68 #define MIN_ENTROPY_SOURCES 16
70 /* Path to on-disk seed file (relative to user's home directory */
71 #ifndef SSH_PRNG_SEED_FILE
72 # define SSH_PRNG_SEED_FILE _PATH_SSH_USER_DIR"/prng_seed"
73 #endif
75 /* Path to PRNG commands list */
76 #ifndef SSH_PRNG_COMMAND_FILE
77 # define SSH_PRNG_COMMAND_FILE SSHDIR "/ssh_prng_cmds"
78 #endif
80 extern char *__progname;
82 #define WHITESPACE " \t\n"
84 #ifndef RUSAGE_SELF
85 # define RUSAGE_SELF 0
86 #endif
87 #ifndef RUSAGE_CHILDREN
88 # define RUSAGE_CHILDREN 0
89 #endif
91 #if !defined(PRNGD_SOCKET) && !defined(PRNGD_PORT)
92 # define USE_SEED_FILES
93 #endif
95 typedef struct {
96 /* Proportion of data that is entropy */
97 double rate;
98 /* Counter goes positive if this command times out */
99 unsigned int badness;
100 /* Increases by factor of two each timeout */
101 unsigned int sticky_badness;
102 /* Path to executable */
103 char *path;
104 /* argv to pass to executable */
105 char *args[NUM_ARGS]; /* XXX: arbitrary limit */
106 /* full command string (debug) */
107 char *cmdstring;
108 } entropy_cmd_t;
110 /* slow command timeouts (all in milliseconds) */
111 /* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
112 static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
114 /* this is initialised from a file, by prng_read_commands() */
115 static entropy_cmd_t *entropy_cmds = NULL;
117 /* Prototypes */
118 double stir_from_system(void);
119 double stir_from_programs(void);
120 double stir_gettimeofday(double entropy_estimate);
121 double stir_clock(double entropy_estimate);
122 double stir_rusage(int who, double entropy_estimate);
123 double hash_command_output(entropy_cmd_t *src, unsigned char *hash);
124 int get_random_bytes_prngd(unsigned char *buf, int len,
125 unsigned short tcp_port, char *socket_path);
128 * Collect 'len' bytes of entropy into 'buf' from PRNGD/EGD daemon
129 * listening either on 'tcp_port', or via Unix domain socket at *
130 * 'socket_path'.
131 * Either a non-zero tcp_port or a non-null socket_path must be
132 * supplied.
133 * Returns 0 on success, -1 on error
136 get_random_bytes_prngd(unsigned char *buf, int len,
137 unsigned short tcp_port, char *socket_path)
139 int fd, addr_len, rval, errors;
140 u_char msg[2];
141 struct sockaddr_storage addr;
142 struct sockaddr_in *addr_in = (struct sockaddr_in *)&addr;
143 struct sockaddr_un *addr_un = (struct sockaddr_un *)&addr;
144 mysig_t old_sigpipe;
146 /* Sanity checks */
147 if (socket_path == NULL && tcp_port == 0)
148 fatal("You must specify a port or a socket");
149 if (socket_path != NULL &&
150 strlen(socket_path) >= sizeof(addr_un->sun_path))
151 fatal("Random pool path is too long");
152 if (len <= 0 || len > 255)
153 fatal("Too many bytes (%d) to read from PRNGD", len);
155 memset(&addr, '\0', sizeof(addr));
157 if (tcp_port != 0) {
158 addr_in->sin_family = AF_INET;
159 addr_in->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
160 addr_in->sin_port = htons(tcp_port);
161 addr_len = sizeof(*addr_in);
162 } else {
163 addr_un->sun_family = AF_UNIX;
164 strlcpy(addr_un->sun_path, socket_path,
165 sizeof(addr_un->sun_path));
166 addr_len = offsetof(struct sockaddr_un, sun_path) +
167 strlen(socket_path) + 1;
170 old_sigpipe = mysignal(SIGPIPE, SIG_IGN);
172 errors = 0;
173 rval = -1;
174 reopen:
175 fd = socket(addr.ss_family, SOCK_STREAM, 0);
176 if (fd == -1) {
177 error("Couldn't create socket: %s", strerror(errno));
178 goto done;
181 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
182 if (tcp_port != 0) {
183 error("Couldn't connect to PRNGD port %d: %s",
184 tcp_port, strerror(errno));
185 } else {
186 error("Couldn't connect to PRNGD socket \"%s\": %s",
187 addr_un->sun_path, strerror(errno));
189 goto done;
192 /* Send blocking read request to PRNGD */
193 msg[0] = 0x02;
194 msg[1] = len;
196 if (atomicio(vwrite, fd, msg, sizeof(msg)) != sizeof(msg)) {
197 if (errno == EPIPE && errors < 10) {
198 close(fd);
199 errors++;
200 goto reopen;
202 error("Couldn't write to PRNGD socket: %s",
203 strerror(errno));
204 goto done;
207 if (atomicio(read, fd, buf, len) != (size_t)len) {
208 if (errno == EPIPE && errors < 10) {
209 close(fd);
210 errors++;
211 goto reopen;
213 error("Couldn't read from PRNGD socket: %s",
214 strerror(errno));
215 goto done;
218 rval = 0;
219 done:
220 mysignal(SIGPIPE, old_sigpipe);
221 if (fd != -1)
222 close(fd);
223 return rval;
226 static int
227 seed_from_prngd(unsigned char *buf, size_t bytes)
229 #ifdef PRNGD_PORT
230 debug("trying egd/prngd port %d", PRNGD_PORT);
231 if (get_random_bytes_prngd(buf, bytes, PRNGD_PORT, NULL) == 0)
232 return 0;
233 #endif
234 #ifdef PRNGD_SOCKET
235 debug("trying egd/prngd socket %s", PRNGD_SOCKET);
236 if (get_random_bytes_prngd(buf, bytes, 0, PRNGD_SOCKET) == 0)
237 return 0;
238 #endif
239 return -1;
242 double
243 stir_gettimeofday(double entropy_estimate)
245 struct timeval tv;
247 if (gettimeofday(&tv, NULL) == -1)
248 fatal("Couldn't gettimeofday: %s", strerror(errno));
250 RAND_add(&tv, sizeof(tv), entropy_estimate);
252 return entropy_estimate;
255 double
256 stir_clock(double entropy_estimate)
258 #ifdef HAVE_CLOCK
259 clock_t c;
261 c = clock();
262 RAND_add(&c, sizeof(c), entropy_estimate);
264 return entropy_estimate;
265 #else /* _HAVE_CLOCK */
266 return 0;
267 #endif /* _HAVE_CLOCK */
270 double
271 stir_rusage(int who, double entropy_estimate)
273 #ifdef HAVE_GETRUSAGE
274 struct rusage ru;
276 if (getrusage(who, &ru) == -1)
277 return 0;
279 RAND_add(&ru, sizeof(ru), entropy_estimate);
281 return entropy_estimate;
282 #else /* _HAVE_GETRUSAGE */
283 return 0;
284 #endif /* _HAVE_GETRUSAGE */
287 static int
288 timeval_diff(struct timeval *t1, struct timeval *t2)
290 int secdiff, usecdiff;
292 secdiff = t2->tv_sec - t1->tv_sec;
293 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
294 return (int)(usecdiff / 1000);
297 double
298 hash_command_output(entropy_cmd_t *src, unsigned char *hash)
300 char buf[8192];
301 fd_set rdset;
302 int bytes_read, cmd_eof, error_abort, msec_elapsed, p[2];
303 int status, total_bytes_read;
304 static int devnull = -1;
305 pid_t pid;
306 SHA_CTX sha;
307 struct timeval tv_start, tv_current;
309 debug3("Reading output from \'%s\'", src->cmdstring);
311 if (devnull == -1) {
312 devnull = open("/dev/null", O_RDWR);
313 if (devnull == -1)
314 fatal("Couldn't open /dev/null: %s",
315 strerror(errno));
318 if (pipe(p) == -1)
319 fatal("Couldn't open pipe: %s", strerror(errno));
321 (void)gettimeofday(&tv_start, NULL); /* record start time */
323 switch (pid = fork()) {
324 case -1: /* Error */
325 close(p[0]);
326 close(p[1]);
327 fatal("Couldn't fork: %s", strerror(errno));
328 /* NOTREACHED */
329 case 0: /* Child */
330 dup2(devnull, STDIN_FILENO);
331 dup2(p[1], STDOUT_FILENO);
332 dup2(p[1], STDERR_FILENO);
333 close(p[0]);
334 close(p[1]);
335 close(devnull);
337 execv(src->path, (char**)(src->args));
339 debug("(child) Couldn't exec '%s': %s",
340 src->cmdstring, strerror(errno));
341 _exit(-1);
342 default: /* Parent */
343 break;
346 RAND_add(&pid, sizeof(&pid), 0.0);
348 close(p[1]);
350 /* Hash output from child */
351 SHA1_Init(&sha);
353 cmd_eof = error_abort = msec_elapsed = total_bytes_read = 0;
354 while (!error_abort && !cmd_eof) {
355 int ret;
356 struct timeval tv;
357 int msec_remaining;
359 (void) gettimeofday(&tv_current, 0);
360 msec_elapsed = timeval_diff(&tv_start, &tv_current);
361 if (msec_elapsed >= entropy_timeout_current) {
362 error_abort=1;
363 continue;
365 msec_remaining = entropy_timeout_current - msec_elapsed;
367 FD_ZERO(&rdset);
368 FD_SET(p[0], &rdset);
369 tv.tv_sec = msec_remaining / 1000;
370 tv.tv_usec = (msec_remaining % 1000) * 1000;
372 ret = select(p[0] + 1, &rdset, NULL, NULL, &tv);
374 RAND_add(&tv, sizeof(tv), 0.0);
376 switch (ret) {
377 case 0:
378 /* timer expired */
379 error_abort = 1;
380 kill(pid, SIGINT);
381 break;
382 case 1:
383 /* command input */
384 do {
385 bytes_read = read(p[0], buf, sizeof(buf));
386 } while (bytes_read == -1 && errno == EINTR);
387 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
388 if (bytes_read == -1) {
389 error_abort = 1;
390 break;
391 } else if (bytes_read) {
392 SHA1_Update(&sha, buf, bytes_read);
393 total_bytes_read += bytes_read;
394 } else {
395 cmd_eof = 1;
397 break;
398 case -1:
399 default:
400 /* error */
401 debug("Command '%s': select() failed: %s",
402 src->cmdstring, strerror(errno));
403 error_abort = 1;
404 break;
408 SHA1_Final(hash, &sha);
410 close(p[0]);
412 debug3("Time elapsed: %d msec", msec_elapsed);
414 if (waitpid(pid, &status, 0) == -1) {
415 error("Couldn't wait for child '%s' completion: %s",
416 src->cmdstring, strerror(errno));
417 return 0.0;
420 RAND_add(&status, sizeof(&status), 0.0);
422 if (error_abort) {
424 * Closing p[0] on timeout causes the entropy command to
425 * SIGPIPE. Take whatever output we got, and mark this
426 * command as slow
428 debug2("Command '%s' timed out", src->cmdstring);
429 src->sticky_badness *= 2;
430 src->badness = src->sticky_badness;
431 return total_bytes_read;
434 if (WIFEXITED(status)) {
435 if (WEXITSTATUS(status) == 0) {
436 return total_bytes_read;
437 } else {
438 debug2("Command '%s' exit status was %d",
439 src->cmdstring, WEXITSTATUS(status));
440 src->badness = src->sticky_badness = 128;
441 return 0.0;
443 } else if (WIFSIGNALED(status)) {
444 debug2("Command '%s' returned on uncaught signal %d !",
445 src->cmdstring, status);
446 src->badness = src->sticky_badness = 128;
447 return 0.0;
448 } else
449 return 0.0;
452 double
453 stir_from_system(void)
455 double total_entropy_estimate;
456 long int i;
458 total_entropy_estimate = 0;
460 i = getpid();
461 RAND_add(&i, sizeof(i), 0.5);
462 total_entropy_estimate += 0.1;
464 i = getppid();
465 RAND_add(&i, sizeof(i), 0.5);
466 total_entropy_estimate += 0.1;
468 i = getuid();
469 RAND_add(&i, sizeof(i), 0.0);
470 i = getgid();
471 RAND_add(&i, sizeof(i), 0.0);
473 total_entropy_estimate += stir_gettimeofday(1.0);
474 total_entropy_estimate += stir_clock(0.5);
475 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
477 return total_entropy_estimate;
480 double
481 stir_from_programs(void)
483 int c;
484 double entropy, total_entropy;
485 unsigned char hash[SHA_DIGEST_LENGTH];
487 total_entropy = 0;
488 for(c = 0; entropy_cmds[c].path != NULL; c++) {
489 if (!entropy_cmds[c].badness) {
490 /* Hash output from command */
491 entropy = hash_command_output(&entropy_cmds[c],
492 hash);
494 /* Scale back estimate by command's rate */
495 entropy *= entropy_cmds[c].rate;
497 /* Upper bound of entropy is SHA_DIGEST_LENGTH */
498 if (entropy > SHA_DIGEST_LENGTH)
499 entropy = SHA_DIGEST_LENGTH;
501 /* Stir it in */
502 RAND_add(hash, sizeof(hash), entropy);
504 debug3("Got %0.2f bytes of entropy from '%s'",
505 entropy, entropy_cmds[c].cmdstring);
507 total_entropy += entropy;
509 /* Execution time should be a bit unpredictable */
510 total_entropy += stir_gettimeofday(0.05);
511 total_entropy += stir_clock(0.05);
512 total_entropy += stir_rusage(RUSAGE_SELF, 0.1);
513 total_entropy += stir_rusage(RUSAGE_CHILDREN, 0.1);
514 } else {
515 debug2("Command '%s' disabled (badness %d)",
516 entropy_cmds[c].cmdstring,
517 entropy_cmds[c].badness);
519 if (entropy_cmds[c].badness > 0)
520 entropy_cmds[c].badness--;
524 return total_entropy;
528 * prng seedfile functions
531 prng_check_seedfile(char *filename)
533 struct stat st;
536 * XXX raceable: eg replace seed between this stat and subsequent
537 * open. Not such a problem because we don't really trust the
538 * seed file anyway.
539 * XXX: use secure path checking as elsewhere in OpenSSH
541 if (lstat(filename, &st) == -1) {
542 /* Give up on hard errors */
543 if (errno != ENOENT)
544 debug("WARNING: Couldn't stat random seed file "
545 "\"%.100s\": %s", filename, strerror(errno));
546 return 0;
549 /* regular file? */
550 if (!S_ISREG(st.st_mode))
551 fatal("PRNG seedfile %.100s is not a regular file",
552 filename);
554 /* mode 0600, owned by root or the current user? */
555 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid())) {
556 debug("WARNING: PRNG seedfile %.100s must be mode 0600, "
557 "owned by uid %li", filename, (long int)getuid());
558 return 0;
561 return 1;
564 void
565 prng_write_seedfile(void)
567 int fd, save_errno;
568 unsigned char seed[SEED_FILE_SIZE];
569 char filename[MAXPATHLEN], tmpseed[MAXPATHLEN];
570 struct passwd *pw;
571 mode_t old_umask;
573 pw = getpwuid(getuid());
574 if (pw == NULL)
575 fatal("Couldn't get password entry for current user "
576 "(%li): %s", (long int)getuid(), strerror(errno));
578 /* Try to ensure that the parent directory is there */
579 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
580 _PATH_SSH_USER_DIR);
581 if (mkdir(filename, 0700) < 0 && errno != EEXIST)
582 fatal("mkdir %.200s: %s", filename, strerror(errno));
584 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
585 SSH_PRNG_SEED_FILE);
587 strlcpy(tmpseed, filename, sizeof(tmpseed));
588 if (strlcat(tmpseed, ".XXXXXXXXXX", sizeof(tmpseed)) >=
589 sizeof(tmpseed))
590 fatal("PRNG seed filename too long");
592 if (RAND_bytes(seed, sizeof(seed)) <= 0)
593 fatal("PRNG seed extraction failed");
595 /* Don't care if the seed doesn't exist */
596 prng_check_seedfile(filename);
598 old_umask = umask(0177);
600 if ((fd = mkstemp(tmpseed)) == -1) {
601 debug("WARNING: couldn't make temporary PRNG seedfile %.100s "
602 "(%.100s)", tmpseed, strerror(errno));
603 } else {
604 debug("writing PRNG seed to file %.100s", tmpseed);
605 if (atomicio(vwrite, fd, &seed, sizeof(seed)) < sizeof(seed)) {
606 save_errno = errno;
607 close(fd);
608 unlink(tmpseed);
609 fatal("problem writing PRNG seedfile %.100s "
610 "(%.100s)", filename, strerror(save_errno));
612 close(fd);
613 debug("moving temporary PRNG seed to file %.100s", filename);
614 if (rename(tmpseed, filename) == -1) {
615 save_errno = errno;
616 unlink(tmpseed);
617 fatal("problem renaming PRNG seedfile from %.100s "
618 "to %.100s (%.100s)", tmpseed, filename,
619 strerror(save_errno));
622 umask(old_umask);
625 void
626 prng_read_seedfile(void)
628 int fd;
629 char seed[SEED_FILE_SIZE], filename[MAXPATHLEN];
630 struct passwd *pw;
632 pw = getpwuid(getuid());
633 if (pw == NULL)
634 fatal("Couldn't get password entry for current user "
635 "(%li): %s", (long int)getuid(), strerror(errno));
637 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
638 SSH_PRNG_SEED_FILE);
640 debug("loading PRNG seed from file %.100s", filename);
642 if (!prng_check_seedfile(filename)) {
643 verbose("Random seed file not found or invalid, ignoring.");
644 return;
647 /* open the file and read in the seed */
648 fd = open(filename, O_RDONLY);
649 if (fd == -1)
650 fatal("could not open PRNG seedfile %.100s (%.100s)",
651 filename, strerror(errno));
653 if (atomicio(read, fd, &seed, sizeof(seed)) < sizeof(seed)) {
654 verbose("invalid or short read from PRNG seedfile "
655 "%.100s - ignoring", filename);
656 memset(seed, '\0', sizeof(seed));
658 close(fd);
660 /* stir in the seed, with estimated entropy zero */
661 RAND_add(&seed, sizeof(seed), 0.0);
666 * entropy command initialisation functions
669 prng_read_commands(char *cmdfilename)
671 char cmd[SEED_FILE_SIZE], *cp, line[1024], path[SEED_FILE_SIZE];
672 double est;
673 entropy_cmd_t *entcmd;
674 FILE *f;
675 int cur_cmd, linenum, num_cmds, arg;
677 if ((f = fopen(cmdfilename, "r")) == NULL) {
678 fatal("couldn't read entropy commands file %.100s: %.100s",
679 cmdfilename, strerror(errno));
682 num_cmds = 64;
683 entcmd = xcalloc(num_cmds, sizeof(entropy_cmd_t));
685 /* Read in file */
686 cur_cmd = linenum = 0;
687 while (fgets(line, sizeof(line), f)) {
688 linenum++;
690 /* Skip leading whitespace, blank lines and comments */
691 cp = line + strspn(line, WHITESPACE);
692 if ((*cp == 0) || (*cp == '#'))
693 continue; /* done with this line */
696 * The first non-whitespace char should be a double quote
697 * delimiting the commandline
699 if (*cp != '"') {
700 error("bad entropy command, %.100s line %d",
701 cmdfilename, linenum);
702 continue;
706 * First token, command args (incl. argv[0]) in double
707 * quotes
709 cp = strtok(cp, "\"");
710 if (cp == NULL) {
711 error("missing or bad command string, %.100s "
712 "line %d -- ignored", cmdfilename, linenum);
713 continue;
715 strlcpy(cmd, cp, sizeof(cmd));
717 /* Second token, full command path */
718 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
719 error("missing command path, %.100s "
720 "line %d -- ignored", cmdfilename, linenum);
721 continue;
724 /* Did configure mark this as dead? */
725 if (strncmp("undef", cp, 5) == 0)
726 continue;
728 strlcpy(path, cp, sizeof(path));
730 /* Third token, entropy rate estimate for this command */
731 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
732 error("missing entropy estimate, %.100s "
733 "line %d -- ignored", cmdfilename, linenum);
734 continue;
736 est = strtod(cp, NULL);
738 /* end of line */
739 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
740 error("garbage at end of line %d in %.100s "
741 "-- ignored", linenum, cmdfilename);
742 continue;
745 /* save the command for debug messages */
746 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
748 /* split the command args */
749 cp = strtok(cmd, WHITESPACE);
750 arg = 0;
751 do {
752 entcmd[cur_cmd].args[arg] = xstrdup(cp);
753 arg++;
754 } while(arg < NUM_ARGS && (cp = strtok(NULL, WHITESPACE)));
756 if (strtok(NULL, WHITESPACE))
757 error("ignored extra commands (max %d), %.100s "
758 "line %d", NUM_ARGS, cmdfilename, linenum);
760 /* Copy the command path and rate estimate */
761 entcmd[cur_cmd].path = xstrdup(path);
762 entcmd[cur_cmd].rate = est;
764 /* Initialise other values */
765 entcmd[cur_cmd].sticky_badness = 1;
767 cur_cmd++;
770 * If we've filled the array, reallocate it twice the size
771 * Do this now because even if this we're on the last
772 * command we need another slot to mark the last entry
774 if (cur_cmd == num_cmds) {
775 num_cmds *= 2;
776 entcmd = xrealloc(entcmd, num_cmds,
777 sizeof(entropy_cmd_t));
781 /* zero the last entry */
782 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_cmd_t));
784 /* trim to size */
785 entropy_cmds = xrealloc(entcmd, (cur_cmd + 1),
786 sizeof(entropy_cmd_t));
788 debug("Loaded %d entropy commands from %.100s", cur_cmd,
789 cmdfilename);
791 fclose(f);
792 return cur_cmd < MIN_ENTROPY_SOURCES ? -1 : 0;
795 void
796 usage(void)
798 fprintf(stderr, "Usage: %s [options]\n", __progname);
799 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
800 fprintf(stderr, " Multiple -v increases verbosity.\n");
801 fprintf(stderr, " -x Force output in hexadecimal (for debugging)\n");
802 fprintf(stderr, " -X Force output in binary\n");
803 fprintf(stderr, " -b bytes Number of bytes to output (default %d)\n",
804 OUTPUT_SEED_SIZE);
808 main(int argc, char **argv)
810 unsigned char *buf;
811 int ret, ch, debug_level, output_hex, bytes;
812 extern char *optarg;
813 LogLevel ll;
815 __progname = ssh_get_progname(argv[0]);
816 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
818 ll = SYSLOG_LEVEL_INFO;
819 debug_level = output_hex = 0;
820 bytes = OUTPUT_SEED_SIZE;
822 /* Don't write binary data to a tty, unless we are forced to */
823 if (isatty(STDOUT_FILENO))
824 output_hex = 1;
826 while ((ch = getopt(argc, argv, "vxXhb:")) != -1) {
827 switch (ch) {
828 case 'v':
829 if (debug_level < 3)
830 ll = SYSLOG_LEVEL_DEBUG1 + debug_level++;
831 break;
832 case 'x':
833 output_hex = 1;
834 break;
835 case 'X':
836 output_hex = 0;
837 break;
838 case 'b':
839 if ((bytes = atoi(optarg)) <= 0)
840 fatal("Invalid number of output bytes");
841 break;
842 case 'h':
843 usage();
844 exit(0);
845 default:
846 error("Invalid commandline option");
847 usage();
851 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
853 #ifdef USE_SEED_FILES
854 prng_read_seedfile();
855 #endif
857 buf = xmalloc(bytes);
860 * Seed the RNG from wherever we can
863 /* Take whatever is on the stack, but don't credit it */
864 RAND_add(buf, bytes, 0);
866 debug("Seeded RNG with %i bytes from system calls",
867 (int)stir_from_system());
869 /* try prngd, fall back to commands if prngd fails or not configured */
870 if (seed_from_prngd(buf, bytes) == 0) {
871 RAND_add(buf, bytes, bytes);
872 } else {
873 /* Read in collection commands */
874 if (prng_read_commands(SSH_PRNG_COMMAND_FILE) == -1)
875 fatal("PRNG initialisation failed -- exiting.");
876 debug("Seeded RNG with %i bytes from programs",
877 (int)stir_from_programs());
880 #ifdef USE_SEED_FILES
881 prng_write_seedfile();
882 #endif
885 * Write the seed to stdout
888 if (!RAND_status())
889 fatal("Not enough entropy in RNG");
891 if (RAND_bytes(buf, bytes) <= 0)
892 fatal("Couldn't extract entropy from PRNG");
894 if (output_hex) {
895 for(ret = 0; ret < bytes; ret++)
896 printf("%02x", (unsigned char)(buf[ret]));
897 printf("\n");
898 } else
899 ret = atomicio(vwrite, STDOUT_FILENO, buf, bytes);
901 memset(buf, '\0', bytes);
902 xfree(buf);
904 return ret == bytes ? 0 : 1;
908 * We may attempt to re-seed during mkstemp if we are using the one in the
909 * compat library (via mkstemp -> _gettemp -> arc4random -> seed_rng) so we
910 * need our own seed_rng(). We must also check that we have enough entropy.
912 void
913 seed_rng(void)
915 if (!RAND_status())
916 fatal("Not enough entropy in RNG");