blob: 3a2903669c14cc64a4376ccad78a65370f7f1350 [file] [log] [blame]
Damien Miller62116dc2001-12-24 01:41:47 +11001/*
Damien Miller7b10ef42002-01-21 23:44:12 +11002 * Copyright (c) 2001-2002 Damien Miller. All rights reserved.
Damien Miller62116dc2001-12-24 01:41:47 +11003 *
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
Damien Miller3717cda2006-03-15 14:02:36 +110027#include <sys/types.h>
28#include <sys/resource.h>
29#include <sys/stat.h>
30#include <sys/wait.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100031#include <sys/socket.h>
32
33#include <netinet/in.h>
Damien Miller3717cda2006-03-15 14:02:36 +110034
35#ifdef HAVE_SYS_UN_H
36# include <sys/un.h>
37#endif
38
Darren Tuckerdeecec92006-07-12 22:44:34 +100039#include <errno.h>
Damien Millera1738e42006-07-10 21:33:04 +100040#include <fcntl.h>
Damien Miller9f2abc42006-07-10 20:53:08 +100041#include <pwd.h>
Damien Miller3717cda2006-03-15 14:02:36 +110042#include <signal.h>
43
Damien Miller62116dc2001-12-24 01:41:47 +110044#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
Damien Miller7b10ef42002-01-21 23:44:12 +110059/* 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
Damien Miller05eda432002-02-10 18:32:28 +110078# define SSH_PRNG_COMMAND_FILE SSHDIR "/ssh_prng_cmds"
Damien Miller7b10ef42002-01-21 23:44:12 +110079#endif
80
Kevin Steves94435082001-12-25 04:32:58 +000081extern char *__progname;
Kevin Steves94435082001-12-25 04:32:58 +000082
Damien Miller62116dc2001-12-24 01:41:47 +110083#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
Damien Millerc46cc542002-01-22 21:58:27 +110092#if !defined(PRNGD_SOCKET) && !defined(PRNGD_PORT)
Damien Miller7b10ef42002-01-21 23:44:12 +110093# define USE_SEED_FILES
Damien Miller62116dc2001-12-24 01:41:47 +110094#endif
95
Damien Miller7b10ef42002-01-21 23:44:12 +110096typedef 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);
Kevin Steves4bdb5472002-07-28 20:42:23 +0000124double hash_command_output(entropy_cmd_t *src, unsigned char *hash);
Damien Millera8e06ce2003-11-21 23:48:55 +1100125int get_random_bytes_prngd(unsigned char *buf, int len,
Damien Miller7b10ef42002-01-21 23:44:12 +1100126 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'.
Damien Millera8e06ce2003-11-21 23:48:55 +1100132 * Either a non-zero tcp_port or a non-null socket_path must be
Damien Miller7b10ef42002-01-21 23:44:12 +1100133 * supplied.
134 * Returns 0 on success, -1 on error
135 */
Damien Miller62116dc2001-12-24 01:41:47 +1100136int
Damien Millera8e06ce2003-11-21 23:48:55 +1100137get_random_bytes_prngd(unsigned char *buf, int len,
Damien Miller7b10ef42002-01-21 23:44:12 +1100138 unsigned short tcp_port, char *socket_path)
Damien Miller62116dc2001-12-24 01:41:47 +1100139{
Damien Miller7b10ef42002-01-21 23:44:12 +1100140 int fd, addr_len, rval, errors;
Damien Miller52c8afe2005-06-19 10:19:43 +1000141 u_char msg[2];
Damien Miller7b10ef42002-01-21 23:44:12 +1100142 struct sockaddr_storage addr;
143 struct sockaddr_in *addr_in = (struct sockaddr_in *)&addr;
144 struct sockaddr_un *addr_un = (struct sockaddr_un *)&addr;
Damien Miller62116dc2001-12-24 01:41:47 +1100145 mysig_t old_sigpipe;
146
Damien Miller7b10ef42002-01-21 23:44:12 +1100147 /* 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");
Damien Miller52c8afe2005-06-19 10:19:43 +1000153 if (len <= 0 || len > 255)
154 fatal("Too many bytes (%d) to read from PRNGD", len);
Damien Miller62116dc2001-12-24 01:41:47 +1100155
156 memset(&addr, '\0', sizeof(addr));
157
Damien Miller7b10ef42002-01-21 23:44:12 +1100158 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 }
Damien Miller62116dc2001-12-24 01:41:47 +1100170
171 old_sigpipe = mysignal(SIGPIPE, SIG_IGN);
172
Damien Miller7b10ef42002-01-21 23:44:12 +1100173 errors = 0;
174 rval = -1;
Damien Miller62116dc2001-12-24 01:41:47 +1100175reopen:
Damien Miller7b10ef42002-01-21 23:44:12 +1100176 fd = socket(addr.ss_family, SOCK_STREAM, 0);
Damien Miller62116dc2001-12-24 01:41:47 +1100177 if (fd == -1) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100178 error("Couldn't create socket: %s", strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100179 goto done;
180 }
Damien Miller62116dc2001-12-24 01:41:47 +1100181
182 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100183 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 }
Damien Miller62116dc2001-12-24 01:41:47 +1100190 goto done;
191 }
192
193 /* Send blocking read request to PRNGD */
194 msg[0] = 0x02;
195 msg[1] = len;
196
Darren Tucker8661b562003-07-06 15:20:46 +1000197 if (atomicio(vwrite, fd, msg, sizeof(msg)) != sizeof(msg)) {
Damien Miller62116dc2001-12-24 01:41:47 +1100198 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
Damien Miller52c8afe2005-06-19 10:19:43 +1000208 if (atomicio(read, fd, buf, len) != (size_t)len) {
Damien Miller62116dc2001-12-24 01:41:47 +1100209 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
Damien Miller7b10ef42002-01-21 23:44:12 +1100219 rval = 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100220done:
221 mysignal(SIGPIPE, old_sigpipe);
222 if (fd != -1)
223 close(fd);
Damien Miller7b10ef42002-01-21 23:44:12 +1100224 return rval;
Damien Miller62116dc2001-12-24 01:41:47 +1100225}
226
Darren Tucker8686ed72004-12-20 12:05:08 +1100227static 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
Damien Miller62116dc2001-12-24 01:41:47 +1100243double
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
Damien Miller7b10ef42002-01-21 23:44:12 +1100253 return entropy_estimate;
Damien Miller62116dc2001-12-24 01:41:47 +1100254}
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
Damien Miller7b10ef42002-01-21 23:44:12 +1100265 return entropy_estimate;
Damien Miller62116dc2001-12-24 01:41:47 +1100266#else /* _HAVE_CLOCK */
Damien Miller7b10ef42002-01-21 23:44:12 +1100267 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100268#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)
Damien Miller7b10ef42002-01-21 23:44:12 +1100278 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100279
280 RAND_add(&ru, sizeof(ru), entropy_estimate);
281
Damien Miller7b10ef42002-01-21 23:44:12 +1100282 return entropy_estimate;
Damien Miller62116dc2001-12-24 01:41:47 +1100283#else /* _HAVE_GETRUSAGE */
Damien Miller7b10ef42002-01-21 23:44:12 +1100284 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100285#endif /* _HAVE_GETRUSAGE */
286}
287
Damien Miller62116dc2001-12-24 01:41:47 +1100288static int
Damien Miller7b10ef42002-01-21 23:44:12 +1100289timeval_diff(struct timeval *t1, struct timeval *t2)
290{
Damien Miller62116dc2001-12-24 01:41:47 +1100291 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
Kevin Steves4bdb5472002-07-28 20:42:23 +0000299hash_command_output(entropy_cmd_t *src, unsigned char *hash)
Damien Miller62116dc2001-12-24 01:41:47 +1100300{
Damien Miller7b10ef42002-01-21 23:44:12 +1100301 char buf[8192];
Damien Miller62116dc2001-12-24 01:41:47 +1100302 fd_set rdset;
Damien Miller7b10ef42002-01-21 23:44:12 +1100303 int bytes_read, cmd_eof, error_abort, msec_elapsed, p[2];
304 int status, total_bytes_read;
305 static int devnull = -1;
Damien Miller62116dc2001-12-24 01:41:47 +1100306 pid_t pid;
Damien Miller62116dc2001-12-24 01:41:47 +1100307 SHA_CTX sha;
Damien Miller7b10ef42002-01-21 23:44:12 +1100308 struct timeval tv_start, tv_current;
Damien Miller62116dc2001-12-24 01:41:47 +1100309
310 debug3("Reading output from \'%s\'", src->cmdstring);
311
312 if (devnull == -1) {
313 devnull = open("/dev/null", O_RDWR);
314 if (devnull == -1)
Damien Millera8e06ce2003-11-21 23:48:55 +1100315 fatal("Couldn't open /dev/null: %s",
Damien Miller7b10ef42002-01-21 23:44:12 +1100316 strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100317 }
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));
Damien Miller7b10ef42002-01-21 23:44:12 +1100339
Damien Millera8e06ce2003-11-21 23:48:55 +1100340 debug("(child) Couldn't exec '%s': %s",
Damien Miller7b10ef42002-01-21 23:44:12 +1100341 src->cmdstring, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100342 _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);
Damien Miller62116dc2001-12-24 01:41:47 +1100353
Damien Miller7b10ef42002-01-21 23:44:12 +1100354 cmd_eof = error_abort = msec_elapsed = total_bytes_read = 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100355 while (!error_abort && !cmd_eof) {
356 int ret;
357 struct timeval tv;
358 int msec_remaining;
359
360 (void) gettimeofday(&tv_current, 0);
Damien Miller7b10ef42002-01-21 23:44:12 +1100361 msec_elapsed = timeval_diff(&tv_start, &tv_current);
Damien Miller62116dc2001-12-24 01:41:47 +1100362 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);
Damien Miller7b10ef42002-01-21 23:44:12 +1100370 tv.tv_sec = msec_remaining / 1000;
Damien Miller62116dc2001-12-24 01:41:47 +1100371 tv.tv_usec = (msec_remaining % 1000) * 1000;
372
Damien Miller7b10ef42002-01-21 23:44:12 +1100373 ret = select(p[0] + 1, &rdset, NULL, NULL, &tv);
Damien Miller62116dc2001-12-24 01:41:47 +1100374
375 RAND_add(&tv, sizeof(tv), 0.0);
376
377 switch (ret) {
378 case 0:
379 /* timer expired */
380 error_abort = 1;
Damien Miller5a5da882002-10-21 10:13:35 +1000381 kill(pid, SIGINT);
Damien Miller62116dc2001-12-24 01:41:47 +1100382 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 */
Damien Millera8e06ce2003-11-21 23:48:55 +1100402 debug("Command '%s': select() failed: %s",
Damien Miller7b10ef42002-01-21 23:44:12 +1100403 src->cmdstring, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100404 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) {
Damien Millerb6f72f52005-07-17 17:26:43 +1000416 error("Couldn't wait for child '%s' completion: %s",
417 src->cmdstring, strerror(errno));
Damien Miller7b10ef42002-01-21 23:44:12 +1100418 return 0.0;
Damien Miller62116dc2001-12-24 01:41:47 +1100419 }
420
421 RAND_add(&status, sizeof(&status), 0.0);
422
423 if (error_abort) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100424 /*
425 * Closing p[0] on timeout causes the entropy command to
Damien Millera8e06ce2003-11-21 23:48:55 +1100426 * SIGPIPE. Take whatever output we got, and mark this
427 * command as slow
Damien Miller7b10ef42002-01-21 23:44:12 +1100428 */
Damien Miller62116dc2001-12-24 01:41:47 +1100429 debug2("Command '%s' timed out", src->cmdstring);
430 src->sticky_badness *= 2;
431 src->badness = src->sticky_badness;
Damien Miller7b10ef42002-01-21 23:44:12 +1100432 return total_bytes_read;
Damien Miller62116dc2001-12-24 01:41:47 +1100433 }
434
435 if (WIFEXITED(status)) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100436 if (WEXITSTATUS(status) == 0) {
437 return total_bytes_read;
Damien Miller62116dc2001-12-24 01:41:47 +1100438 } else {
Damien Miller7b10ef42002-01-21 23:44:12 +1100439 debug2("Command '%s' exit status was %d",
440 src->cmdstring, WEXITSTATUS(status));
Damien Miller62116dc2001-12-24 01:41:47 +1100441 src->badness = src->sticky_badness = 128;
Damien Miller7b10ef42002-01-21 23:44:12 +1100442 return 0.0;
Damien Miller62116dc2001-12-24 01:41:47 +1100443 }
444 } else if (WIFSIGNALED(status)) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100445 debug2("Command '%s' returned on uncaught signal %d !",
446 src->cmdstring, status);
Damien Miller62116dc2001-12-24 01:41:47 +1100447 src->badness = src->sticky_badness = 128;
Damien Miller7b10ef42002-01-21 23:44:12 +1100448 return 0.0;
Damien Miller62116dc2001-12-24 01:41:47 +1100449 } else
Damien Miller7b10ef42002-01-21 23:44:12 +1100450 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;
Kevin Steves4bdb5472002-07-28 20:42:23 +0000486 unsigned char hash[SHA_DIGEST_LENGTH];
Damien Miller7b10ef42002-01-21 23:44:12 +1100487
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
Damien Millera8e06ce2003-11-21 23:48:55 +1100505 debug3("Got %0.2f bytes of entropy from '%s'",
Damien Miller7b10ef42002-01-21 23:44:12 +1100506 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)",
Damien Millera8e06ce2003-11-21 23:48:55 +1100517 entropy_cmds[c].cmdstring,
Damien Miller7b10ef42002-01-21 23:44:12 +1100518 entropy_cmds[c].badness);
519
520 if (entropy_cmds[c].badness > 0)
521 entropy_cmds[c].badness--;
522 }
523 }
524
525 return total_entropy;
Damien Miller62116dc2001-12-24 01:41:47 +1100526}
527
528/*
529 * prng seedfile functions
530 */
531int
Damien Miller7b10ef42002-01-21 23:44:12 +1100532prng_check_seedfile(char *filename)
533{
Damien Miller62116dc2001-12-24 01:41:47 +1100534 struct stat st;
535
Damien Miller7b10ef42002-01-21 23:44:12 +1100536 /*
Damien Millera8e06ce2003-11-21 23:48:55 +1100537 * XXX raceable: eg replace seed between this stat and subsequent
538 * open. Not such a problem because we don't really trust the
Damien Miller7b10ef42002-01-21 23:44:12 +1100539 * seed file anyway.
540 * XXX: use secure path checking as elsewhere in OpenSSH
541 */
Damien Miller62116dc2001-12-24 01:41:47 +1100542 if (lstat(filename, &st) == -1) {
543 /* Give up on hard errors */
544 if (errno != ENOENT)
Damien Miller7b10ef42002-01-21 23:44:12 +1100545 debug("WARNING: Couldn't stat random seed file "
546 "\"%.100s\": %s", filename, strerror(errno));
547 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100548 }
549
550 /* regular file? */
551 if (!S_ISREG(st.st_mode))
Damien Miller7b10ef42002-01-21 23:44:12 +1100552 fatal("PRNG seedfile %.100s is not a regular file",
553 filename);
Damien Miller62116dc2001-12-24 01:41:47 +1100554
555 /* mode 0600, owned by root or the current user? */
556 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid())) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100557 debug("WARNING: PRNG seedfile %.100s must be mode 0600, "
Damien Millerc46b6bc2003-05-16 15:51:44 +1000558 "owned by uid %li", filename, (long int)getuid());
Damien Miller7b10ef42002-01-21 23:44:12 +1100559 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100560 }
561
Damien Miller7b10ef42002-01-21 23:44:12 +1100562 return 1;
Damien Miller62116dc2001-12-24 01:41:47 +1100563}
564
565void
Damien Miller7b10ef42002-01-21 23:44:12 +1100566prng_write_seedfile(void)
567{
Damien Millered462d92005-02-16 13:02:45 +1100568 int fd, save_errno;
Kevin Steves4bdb5472002-07-28 20:42:23 +0000569 unsigned char seed[SEED_FILE_SIZE];
Damien Millered462d92005-02-16 13:02:45 +1100570 char filename[MAXPATHLEN], tmpseed[MAXPATHLEN];
Damien Miller62116dc2001-12-24 01:41:47 +1100571 struct passwd *pw;
Damien Millered462d92005-02-16 13:02:45 +1100572 mode_t old_umask;
Damien Miller62116dc2001-12-24 01:41:47 +1100573
574 pw = getpwuid(getuid());
575 if (pw == NULL)
Damien Miller7b10ef42002-01-21 23:44:12 +1100576 fatal("Couldn't get password entry for current user "
Damien Millerc46b6bc2003-05-16 15:51:44 +1000577 "(%li): %s", (long int)getuid(), strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100578
579 /* Try to ensure that the parent directory is there */
580 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
Damien Miller7b10ef42002-01-21 23:44:12 +1100581 _PATH_SSH_USER_DIR);
Darren Tuckerdaf6ff42006-07-05 21:35:48 +1000582 if (mkdir(filename, 0700) < 0 && errno != EEXIST)
583 fatal("mkdir %.200s: %s", filename, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100584
585 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
Damien Miller7b10ef42002-01-21 23:44:12 +1100586 SSH_PRNG_SEED_FILE);
Damien Miller62116dc2001-12-24 01:41:47 +1100587
Damien Millered462d92005-02-16 13:02:45 +1100588 strlcpy(tmpseed, filename, sizeof(tmpseed));
589 if (strlcat(tmpseed, ".XXXXXXXXXX", sizeof(tmpseed)) >=
590 sizeof(tmpseed))
591 fatal("PRNG seed filename too long");
Damien Miller62116dc2001-12-24 01:41:47 +1100592
Damien Millercafbcc72003-03-17 16:13:53 +1100593 if (RAND_bytes(seed, sizeof(seed)) <= 0)
Ben Lindstromda4d9cf2003-09-22 15:36:15 +0000594 fatal("PRNG seed extraction failed");
Damien Miller62116dc2001-12-24 01:41:47 +1100595
596 /* Don't care if the seed doesn't exist */
597 prng_check_seedfile(filename);
598
Damien Millered462d92005-02-16 13:02:45 +1100599 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));
Damien Miller62116dc2001-12-24 01:41:47 +1100604 } else {
Damien Millered462d92005-02-16 13:02:45 +1100605 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);
Damien Miller7b10ef42002-01-21 23:44:12 +1100610 fatal("problem writing PRNG seedfile %.100s "
Damien Millered462d92005-02-16 13:02:45 +1100611 "(%.100s)", filename, strerror(save_errno));
612 }
Damien Miller62116dc2001-12-24 01:41:47 +1100613 close(fd);
Damien Millered462d92005-02-16 13:02:45 +1100614 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 "
Damien Miller94cf4c82005-07-17 17:04:47 +1000619 "to %.100s (%.100s)", tmpseed, filename,
Damien Millered462d92005-02-16 13:02:45 +1100620 strerror(save_errno));
621 }
Damien Miller62116dc2001-12-24 01:41:47 +1100622 }
Damien Millered462d92005-02-16 13:02:45 +1100623 umask(old_umask);
Damien Miller62116dc2001-12-24 01:41:47 +1100624}
625
626void
Damien Miller7b10ef42002-01-21 23:44:12 +1100627prng_read_seedfile(void)
628{
Damien Miller62116dc2001-12-24 01:41:47 +1100629 int fd;
Damien Miller7b10ef42002-01-21 23:44:12 +1100630 char seed[SEED_FILE_SIZE], filename[MAXPATHLEN];
Damien Miller62116dc2001-12-24 01:41:47 +1100631 struct passwd *pw;
632
633 pw = getpwuid(getuid());
634 if (pw == NULL)
Damien Miller7b10ef42002-01-21 23:44:12 +1100635 fatal("Couldn't get password entry for current user "
Damien Millerc46b6bc2003-05-16 15:51:44 +1000636 "(%li): %s", (long int)getuid(), strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100637
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)) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100644 verbose("Random seed file not found or invalid, ignoring.");
Damien Miller62116dc2001-12-24 01:41:47 +1100645 return;
646 }
647
648 /* open the file and read in the seed */
649 fd = open(filename, O_RDONLY);
650 if (fd == -1)
Damien Miller7b10ef42002-01-21 23:44:12 +1100651 fatal("could not open PRNG seedfile %.100s (%.100s)",
652 filename, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100653
Damien Miller7b10ef42002-01-21 23:44:12 +1100654 if (atomicio(read, fd, &seed, sizeof(seed)) < sizeof(seed)) {
655 verbose("invalid or short read from PRNG seedfile "
656 "%.100s - ignoring", filename);
Damien Miller62116dc2001-12-24 01:41:47 +1100657 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{
Damien Miller7b10ef42002-01-21 23:44:12 +1100672 char cmd[SEED_FILE_SIZE], *cp, line[1024], path[SEED_FILE_SIZE];
Damien Miller62116dc2001-12-24 01:41:47 +1100673 double est;
Damien Miller7b10ef42002-01-21 23:44:12 +1100674 entropy_cmd_t *entcmd;
675 FILE *f;
676 int cur_cmd, linenum, num_cmds, arg;
Damien Miller62116dc2001-12-24 01:41:47 +1100677
Damien Miller7b10ef42002-01-21 23:44:12 +1100678 if ((f = fopen(cmdfilename, "r")) == NULL) {
Damien Miller62116dc2001-12-24 01:41:47 +1100679 fatal("couldn't read entropy commands file %.100s: %.100s",
680 cmdfilename, strerror(errno));
681 }
682
Damien Miller7b10ef42002-01-21 23:44:12 +1100683 num_cmds = 64;
Darren Tuckerd8093e42006-05-04 16:24:34 +1000684 entcmd = xcalloc(num_cmds, sizeof(entropy_cmd_t));
Damien Miller62116dc2001-12-24 01:41:47 +1100685
686 /* Read in file */
Damien Miller7b10ef42002-01-21 23:44:12 +1100687 cur_cmd = linenum = 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100688 while (fgets(line, sizeof(line), f)) {
Damien Miller62116dc2001-12-24 01:41:47 +1100689 linenum++;
690
Damien Miller7b10ef42002-01-21 23:44:12 +1100691 /* Skip leading whitespace, blank lines and comments */
Damien Miller62116dc2001-12-24 01:41:47 +1100692 cp = line + strspn(line, WHITESPACE);
693 if ((*cp == 0) || (*cp == '#'))
694 continue; /* done with this line */
695
Damien Miller7b10ef42002-01-21 23:44:12 +1100696 /*
Damien Millera8e06ce2003-11-21 23:48:55 +1100697 * The first non-whitespace char should be a double quote
Damien Miller7b10ef42002-01-21 23:44:12 +1100698 * delimiting the commandline
699 */
Damien Miller62116dc2001-12-24 01:41:47 +1100700 if (*cp != '"') {
Damien Miller7b10ef42002-01-21 23:44:12 +1100701 error("bad entropy command, %.100s line %d",
702 cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100703 continue;
704 }
705
Damien Miller7b10ef42002-01-21 23:44:12 +1100706 /*
707 * First token, command args (incl. argv[0]) in double
708 * quotes
709 */
Damien Miller62116dc2001-12-24 01:41:47 +1100710 cp = strtok(cp, "\"");
711 if (cp == NULL) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100712 error("missing or bad command string, %.100s "
713 "line %d -- ignored", cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100714 continue;
715 }
716 strlcpy(cmd, cp, sizeof(cmd));
717
Damien Miller7b10ef42002-01-21 23:44:12 +1100718 /* Second token, full command path */
Damien Miller62116dc2001-12-24 01:41:47 +1100719 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100720 error("missing command path, %.100s "
721 "line %d -- ignored", cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100722 continue;
723 }
724
Damien Miller7b10ef42002-01-21 23:44:12 +1100725 /* Did configure mark this as dead? */
Damien Miller62116dc2001-12-24 01:41:47 +1100726 if (strncmp("undef", cp, 5) == 0)
727 continue;
728
729 strlcpy(path, cp, sizeof(path));
730
Damien Miller7b10ef42002-01-21 23:44:12 +1100731 /* Third token, entropy rate estimate for this command */
Damien Miller62116dc2001-12-24 01:41:47 +1100732 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100733 error("missing entropy estimate, %.100s "
734 "line %d -- ignored", cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100735 continue;
736 }
Damien Miller7b10ef42002-01-21 23:44:12 +1100737 est = strtod(cp, NULL);
Damien Miller62116dc2001-12-24 01:41:47 +1100738
739 /* end of line */
740 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100741 error("garbage at end of line %d in %.100s "
742 "-- ignored", linenum, cmdfilename);
Damien Miller62116dc2001-12-24 01:41:47 +1100743 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;
Damien Miller62116dc2001-12-24 01:41:47 +1100752 do {
Damien Miller7b10ef42002-01-21 23:44:12 +1100753 entcmd[cur_cmd].args[arg] = xstrdup(cp);
Damien Miller62116dc2001-12-24 01:41:47 +1100754 arg++;
Damien Miller7b10ef42002-01-21 23:44:12 +1100755 } while(arg < NUM_ARGS && (cp = strtok(NULL, WHITESPACE)));
Damien Miller62116dc2001-12-24 01:41:47 +1100756
757 if (strtok(NULL, WHITESPACE))
Damien Miller7b10ef42002-01-21 23:44:12 +1100758 error("ignored extra commands (max %d), %.100s "
759 "line %d", NUM_ARGS, cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100760
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
Damien Miller7b10ef42002-01-21 23:44:12 +1100770 /*
771 * If we've filled the array, reallocate it twice the size
Damien Millera8e06ce2003-11-21 23:48:55 +1100772 * Do this now because even if this we're on the last
Damien Miller7b10ef42002-01-21 23:44:12 +1100773 * command we need another slot to mark the last entry
774 */
Damien Miller62116dc2001-12-24 01:41:47 +1100775 if (cur_cmd == num_cmds) {
776 num_cmds *= 2;
Damien Miller36812092006-03-26 14:22:47 +1100777 entcmd = xrealloc(entcmd, num_cmds,
Damien Miller7b10ef42002-01-21 23:44:12 +1100778 sizeof(entropy_cmd_t));
Damien Miller62116dc2001-12-24 01:41:47 +1100779 }
780 }
781
782 /* zero the last entry */
Damien Miller7b10ef42002-01-21 23:44:12 +1100783 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_cmd_t));
Damien Miller62116dc2001-12-24 01:41:47 +1100784
785 /* trim to size */
Damien Miller36812092006-03-26 14:22:47 +1100786 entropy_cmds = xrealloc(entcmd, (cur_cmd + 1),
Damien Miller7b10ef42002-01-21 23:44:12 +1100787 sizeof(entropy_cmd_t));
Damien Miller62116dc2001-12-24 01:41:47 +1100788
Damien Miller7b10ef42002-01-21 23:44:12 +1100789 debug("Loaded %d entropy commands from %.100s", cur_cmd,
790 cmdfilename);
Damien Miller62116dc2001-12-24 01:41:47 +1100791
Darren Tuckerf58b29d2006-05-17 22:24:56 +1000792 fclose(f);
Damien Miller7b10ef42002-01-21 23:44:12 +1100793 return cur_cmd < MIN_ENTROPY_SOURCES ? -1 : 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100794}
795
Damien Miller32e48182002-04-14 19:27:12 +1000796void
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");
Damien Miller7daf0442004-08-23 21:52:08 +1000802 fprintf(stderr, " -x Force output in hexadecimal (for debugging)\n");
Damien Miller32e48182002-04-14 19:27:12 +1000803 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
Damien Millera8e06ce2003-11-21 23:48:55 +1100808int
Damien Miller62116dc2001-12-24 01:41:47 +1100809main(int argc, char **argv)
810{
Damien Miller32e48182002-04-14 19:27:12 +1000811 unsigned char *buf;
812 int ret, ch, debug_level, output_hex, bytes;
813 extern char *optarg;
814 LogLevel ll;
Damien Miller62116dc2001-12-24 01:41:47 +1100815
Damien Miller59d3d5b2003-08-22 09:34:41 +1000816 __progname = ssh_get_progname(argv[0]);
Damien Miller62116dc2001-12-24 01:41:47 +1100817 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
818
Damien Miller32e48182002-04-14 19:27:12 +1000819 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;
Damien Miller787b2ec2003-11-21 23:56:47 +1100826
Damien Miller32e48182002-04-14 19:27:12 +1000827 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);
Damien Miller787b2ec2003-11-21 23:56:47 +1100853
Damien Miller7b10ef42002-01-21 23:44:12 +1100854#ifdef USE_SEED_FILES
855 prng_read_seedfile();
856#endif
857
Damien Miller32e48182002-04-14 19:27:12 +1000858 buf = xmalloc(bytes);
859
Damien Miller7b10ef42002-01-21 23:44:12 +1100860 /*
861 * Seed the RNG from wherever we can
862 */
Damien Miller787b2ec2003-11-21 23:56:47 +1100863
Damien Miller7b10ef42002-01-21 23:44:12 +1100864 /* Take whatever is on the stack, but don't credit it */
Damien Miller32e48182002-04-14 19:27:12 +1000865 RAND_add(buf, bytes, 0);
Damien Miller7b10ef42002-01-21 23:44:12 +1100866
Damien Millera8e06ce2003-11-21 23:48:55 +1100867 debug("Seeded RNG with %i bytes from system calls",
Damien Miller7b10ef42002-01-21 23:44:12 +1100868 (int)stir_from_system());
869
Darren Tucker8686ed72004-12-20 12:05:08 +1100870 /* 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 }
Damien Miller7b10ef42002-01-21 23:44:12 +1100880
881#ifdef USE_SEED_FILES
882 prng_write_seedfile();
883#endif
884
885 /*
886 * Write the seed to stdout
887 */
Damien Miller62116dc2001-12-24 01:41:47 +1100888
889 if (!RAND_status())
890 fatal("Not enough entropy in RNG");
891
Damien Millercafbcc72003-03-17 16:13:53 +1100892 if (RAND_bytes(buf, bytes) <= 0)
893 fatal("Couldn't extract entropy from PRNG");
Damien Miller62116dc2001-12-24 01:41:47 +1100894
Damien Miller32e48182002-04-14 19:27:12 +1000895 if (output_hex) {
896 for(ret = 0; ret < bytes; ret++)
897 printf("%02x", (unsigned char)(buf[ret]));
898 printf("\n");
899 } else
Darren Tucker8661b562003-07-06 15:20:46 +1000900 ret = atomicio(vwrite, STDOUT_FILENO, buf, bytes);
Damien Miller787b2ec2003-11-21 23:56:47 +1100901
Damien Miller32e48182002-04-14 19:27:12 +1000902 memset(buf, '\0', bytes);
903 xfree(buf);
Damien Miller787b2ec2003-11-21 23:56:47 +1100904
Damien Miller32e48182002-04-14 19:27:12 +1000905 return ret == bytes ? 0 : 1;
Damien Miller62116dc2001-12-24 01:41:47 +1100906}
Darren Tucker7b48d252005-02-16 13:20:07 +1100907
908/*
909 * We may attempt to re-seed during mkstemp if we are using the one in the
Darren Tucker7a8619a2005-02-16 13:32:30 +1100910 * 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.
Darren Tucker7b48d252005-02-16 13:20:07 +1100912 */
913void
914seed_rng(void)
915{
916 if (!RAND_status())
917 fatal("Not enough entropy in RNG");
918}