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