blob: ebee90014d3cbb42ae9d8cd744fde27c711aa74b [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
Damien Millera1738e42006-07-10 21:33:04 +100039#include <fcntl.h>
Damien Miller9f2abc42006-07-10 20:53:08 +100040#include <pwd.h>
Damien Miller3717cda2006-03-15 14:02:36 +110041#include <signal.h>
42
Damien Miller62116dc2001-12-24 01:41:47 +110043#include <openssl/rand.h>
44#include <openssl/sha.h>
45#include <openssl/crypto.h>
46
47/* SunOS 4.4.4 needs this */
48#ifdef HAVE_FLOATINGPOINT_H
49# include <floatingpoint.h>
50#endif /* HAVE_FLOATINGPOINT_H */
51
52#include "misc.h"
53#include "xmalloc.h"
54#include "atomicio.h"
55#include "pathnames.h"
56#include "log.h"
57
Damien Miller7b10ef42002-01-21 23:44:12 +110058/* Number of bytes we write out */
59#define OUTPUT_SEED_SIZE 48
60
61/* Length of on-disk seedfiles */
62#define SEED_FILE_SIZE 1024
63
64/* Maximum number of command-line arguments to read from file */
65#define NUM_ARGS 10
66
67/* Minimum number of usable commands to be considered sufficient */
68#define MIN_ENTROPY_SOURCES 16
69
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
74
75/* Path to PRNG commands list */
76#ifndef SSH_PRNG_COMMAND_FILE
Damien Miller05eda432002-02-10 18:32:28 +110077# define SSH_PRNG_COMMAND_FILE SSHDIR "/ssh_prng_cmds"
Damien Miller7b10ef42002-01-21 23:44:12 +110078#endif
79
Kevin Steves94435082001-12-25 04:32:58 +000080extern char *__progname;
Kevin Steves94435082001-12-25 04:32:58 +000081
Damien Miller62116dc2001-12-24 01:41:47 +110082#define WHITESPACE " \t\n"
83
84#ifndef RUSAGE_SELF
85# define RUSAGE_SELF 0
86#endif
87#ifndef RUSAGE_CHILDREN
88# define RUSAGE_CHILDREN 0
89#endif
90
Damien Millerc46cc542002-01-22 21:58:27 +110091#if !defined(PRNGD_SOCKET) && !defined(PRNGD_PORT)
Damien Miller7b10ef42002-01-21 23:44:12 +110092# define USE_SEED_FILES
Damien Miller62116dc2001-12-24 01:41:47 +110093#endif
94
Damien Miller7b10ef42002-01-21 23:44:12 +110095typedef 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;
109
110/* slow command timeouts (all in milliseconds) */
111/* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
112static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
113
114/* this is initialised from a file, by prng_read_commands() */
115static entropy_cmd_t *entropy_cmds = NULL;
116
117/* Prototypes */
118double stir_from_system(void);
119double stir_from_programs(void);
120double stir_gettimeofday(double entropy_estimate);
121double stir_clock(double entropy_estimate);
122double stir_rusage(int who, double entropy_estimate);
Kevin Steves4bdb5472002-07-28 20:42:23 +0000123double hash_command_output(entropy_cmd_t *src, unsigned char *hash);
Damien Millera8e06ce2003-11-21 23:48:55 +1100124int get_random_bytes_prngd(unsigned char *buf, int len,
Damien Miller7b10ef42002-01-21 23:44:12 +1100125 unsigned short tcp_port, char *socket_path);
126
127/*
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'.
Damien Millera8e06ce2003-11-21 23:48:55 +1100131 * Either a non-zero tcp_port or a non-null socket_path must be
Damien Miller7b10ef42002-01-21 23:44:12 +1100132 * supplied.
133 * Returns 0 on success, -1 on error
134 */
Damien Miller62116dc2001-12-24 01:41:47 +1100135int
Damien Millera8e06ce2003-11-21 23:48:55 +1100136get_random_bytes_prngd(unsigned char *buf, int len,
Damien Miller7b10ef42002-01-21 23:44:12 +1100137 unsigned short tcp_port, char *socket_path)
Damien Miller62116dc2001-12-24 01:41:47 +1100138{
Damien Miller7b10ef42002-01-21 23:44:12 +1100139 int fd, addr_len, rval, errors;
Damien Miller52c8afe2005-06-19 10:19:43 +1000140 u_char msg[2];
Damien Miller7b10ef42002-01-21 23:44:12 +1100141 struct sockaddr_storage addr;
142 struct sockaddr_in *addr_in = (struct sockaddr_in *)&addr;
143 struct sockaddr_un *addr_un = (struct sockaddr_un *)&addr;
Damien Miller62116dc2001-12-24 01:41:47 +1100144 mysig_t old_sigpipe;
145
Damien Miller7b10ef42002-01-21 23:44:12 +1100146 /* 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");
Damien Miller52c8afe2005-06-19 10:19:43 +1000152 if (len <= 0 || len > 255)
153 fatal("Too many bytes (%d) to read from PRNGD", len);
Damien Miller62116dc2001-12-24 01:41:47 +1100154
155 memset(&addr, '\0', sizeof(addr));
156
Damien Miller7b10ef42002-01-21 23:44:12 +1100157 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;
168 }
Damien Miller62116dc2001-12-24 01:41:47 +1100169
170 old_sigpipe = mysignal(SIGPIPE, SIG_IGN);
171
Damien Miller7b10ef42002-01-21 23:44:12 +1100172 errors = 0;
173 rval = -1;
Damien Miller62116dc2001-12-24 01:41:47 +1100174reopen:
Damien Miller7b10ef42002-01-21 23:44:12 +1100175 fd = socket(addr.ss_family, SOCK_STREAM, 0);
Damien Miller62116dc2001-12-24 01:41:47 +1100176 if (fd == -1) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100177 error("Couldn't create socket: %s", strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100178 goto done;
179 }
Damien Miller62116dc2001-12-24 01:41:47 +1100180
181 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100182 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));
188 }
Damien Miller62116dc2001-12-24 01:41:47 +1100189 goto done;
190 }
191
192 /* Send blocking read request to PRNGD */
193 msg[0] = 0x02;
194 msg[1] = len;
195
Darren Tucker8661b562003-07-06 15:20:46 +1000196 if (atomicio(vwrite, fd, msg, sizeof(msg)) != sizeof(msg)) {
Damien Miller62116dc2001-12-24 01:41:47 +1100197 if (errno == EPIPE && errors < 10) {
198 close(fd);
199 errors++;
200 goto reopen;
201 }
202 error("Couldn't write to PRNGD socket: %s",
203 strerror(errno));
204 goto done;
205 }
206
Damien Miller52c8afe2005-06-19 10:19:43 +1000207 if (atomicio(read, fd, buf, len) != (size_t)len) {
Damien Miller62116dc2001-12-24 01:41:47 +1100208 if (errno == EPIPE && errors < 10) {
209 close(fd);
210 errors++;
211 goto reopen;
212 }
213 error("Couldn't read from PRNGD socket: %s",
214 strerror(errno));
215 goto done;
216 }
217
Damien Miller7b10ef42002-01-21 23:44:12 +1100218 rval = 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100219done:
220 mysignal(SIGPIPE, old_sigpipe);
221 if (fd != -1)
222 close(fd);
Damien Miller7b10ef42002-01-21 23:44:12 +1100223 return rval;
Damien Miller62116dc2001-12-24 01:41:47 +1100224}
225
Darren Tucker8686ed72004-12-20 12:05:08 +1100226static int
227seed_from_prngd(unsigned char *buf, size_t bytes)
228{
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;
240}
241
Damien Miller62116dc2001-12-24 01:41:47 +1100242double
243stir_gettimeofday(double entropy_estimate)
244{
245 struct timeval tv;
246
247 if (gettimeofday(&tv, NULL) == -1)
248 fatal("Couldn't gettimeofday: %s", strerror(errno));
249
250 RAND_add(&tv, sizeof(tv), entropy_estimate);
251
Damien Miller7b10ef42002-01-21 23:44:12 +1100252 return entropy_estimate;
Damien Miller62116dc2001-12-24 01:41:47 +1100253}
254
255double
256stir_clock(double entropy_estimate)
257{
258#ifdef HAVE_CLOCK
259 clock_t c;
260
261 c = clock();
262 RAND_add(&c, sizeof(c), entropy_estimate);
263
Damien Miller7b10ef42002-01-21 23:44:12 +1100264 return entropy_estimate;
Damien Miller62116dc2001-12-24 01:41:47 +1100265#else /* _HAVE_CLOCK */
Damien Miller7b10ef42002-01-21 23:44:12 +1100266 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100267#endif /* _HAVE_CLOCK */
268}
269
270double
271stir_rusage(int who, double entropy_estimate)
272{
273#ifdef HAVE_GETRUSAGE
274 struct rusage ru;
275
276 if (getrusage(who, &ru) == -1)
Damien Miller7b10ef42002-01-21 23:44:12 +1100277 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100278
279 RAND_add(&ru, sizeof(ru), entropy_estimate);
280
Damien Miller7b10ef42002-01-21 23:44:12 +1100281 return entropy_estimate;
Damien Miller62116dc2001-12-24 01:41:47 +1100282#else /* _HAVE_GETRUSAGE */
Damien Miller7b10ef42002-01-21 23:44:12 +1100283 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100284#endif /* _HAVE_GETRUSAGE */
285}
286
Damien Miller62116dc2001-12-24 01:41:47 +1100287static int
Damien Miller7b10ef42002-01-21 23:44:12 +1100288timeval_diff(struct timeval *t1, struct timeval *t2)
289{
Damien Miller62116dc2001-12-24 01:41:47 +1100290 int secdiff, usecdiff;
291
292 secdiff = t2->tv_sec - t1->tv_sec;
293 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
294 return (int)(usecdiff / 1000);
295}
296
297double
Kevin Steves4bdb5472002-07-28 20:42:23 +0000298hash_command_output(entropy_cmd_t *src, unsigned char *hash)
Damien Miller62116dc2001-12-24 01:41:47 +1100299{
Damien Miller7b10ef42002-01-21 23:44:12 +1100300 char buf[8192];
Damien Miller62116dc2001-12-24 01:41:47 +1100301 fd_set rdset;
Damien Miller7b10ef42002-01-21 23:44:12 +1100302 int bytes_read, cmd_eof, error_abort, msec_elapsed, p[2];
303 int status, total_bytes_read;
304 static int devnull = -1;
Damien Miller62116dc2001-12-24 01:41:47 +1100305 pid_t pid;
Damien Miller62116dc2001-12-24 01:41:47 +1100306 SHA_CTX sha;
Damien Miller7b10ef42002-01-21 23:44:12 +1100307 struct timeval tv_start, tv_current;
Damien Miller62116dc2001-12-24 01:41:47 +1100308
309 debug3("Reading output from \'%s\'", src->cmdstring);
310
311 if (devnull == -1) {
312 devnull = open("/dev/null", O_RDWR);
313 if (devnull == -1)
Damien Millera8e06ce2003-11-21 23:48:55 +1100314 fatal("Couldn't open /dev/null: %s",
Damien Miller7b10ef42002-01-21 23:44:12 +1100315 strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100316 }
317
318 if (pipe(p) == -1)
319 fatal("Couldn't open pipe: %s", strerror(errno));
320
321 (void)gettimeofday(&tv_start, NULL); /* record start time */
322
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);
336
337 execv(src->path, (char**)(src->args));
Damien Miller7b10ef42002-01-21 23:44:12 +1100338
Damien Millera8e06ce2003-11-21 23:48:55 +1100339 debug("(child) Couldn't exec '%s': %s",
Damien Miller7b10ef42002-01-21 23:44:12 +1100340 src->cmdstring, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100341 _exit(-1);
342 default: /* Parent */
343 break;
344 }
345
346 RAND_add(&pid, sizeof(&pid), 0.0);
347
348 close(p[1]);
349
350 /* Hash output from child */
351 SHA1_Init(&sha);
Damien Miller62116dc2001-12-24 01:41:47 +1100352
Damien Miller7b10ef42002-01-21 23:44:12 +1100353 cmd_eof = error_abort = msec_elapsed = total_bytes_read = 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100354 while (!error_abort && !cmd_eof) {
355 int ret;
356 struct timeval tv;
357 int msec_remaining;
358
359 (void) gettimeofday(&tv_current, 0);
Damien Miller7b10ef42002-01-21 23:44:12 +1100360 msec_elapsed = timeval_diff(&tv_start, &tv_current);
Damien Miller62116dc2001-12-24 01:41:47 +1100361 if (msec_elapsed >= entropy_timeout_current) {
362 error_abort=1;
363 continue;
364 }
365 msec_remaining = entropy_timeout_current - msec_elapsed;
366
367 FD_ZERO(&rdset);
368 FD_SET(p[0], &rdset);
Damien Miller7b10ef42002-01-21 23:44:12 +1100369 tv.tv_sec = msec_remaining / 1000;
Damien Miller62116dc2001-12-24 01:41:47 +1100370 tv.tv_usec = (msec_remaining % 1000) * 1000;
371
Damien Miller7b10ef42002-01-21 23:44:12 +1100372 ret = select(p[0] + 1, &rdset, NULL, NULL, &tv);
Damien Miller62116dc2001-12-24 01:41:47 +1100373
374 RAND_add(&tv, sizeof(tv), 0.0);
375
376 switch (ret) {
377 case 0:
378 /* timer expired */
379 error_abort = 1;
Damien Miller5a5da882002-10-21 10:13:35 +1000380 kill(pid, SIGINT);
Damien Miller62116dc2001-12-24 01:41:47 +1100381 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;
396 }
397 break;
398 case -1:
399 default:
400 /* error */
Damien Millera8e06ce2003-11-21 23:48:55 +1100401 debug("Command '%s': select() failed: %s",
Damien Miller7b10ef42002-01-21 23:44:12 +1100402 src->cmdstring, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100403 error_abort = 1;
404 break;
405 }
406 }
407
408 SHA1_Final(hash, &sha);
409
410 close(p[0]);
411
412 debug3("Time elapsed: %d msec", msec_elapsed);
413
414 if (waitpid(pid, &status, 0) == -1) {
Damien Millerb6f72f52005-07-17 17:26:43 +1000415 error("Couldn't wait for child '%s' completion: %s",
416 src->cmdstring, strerror(errno));
Damien Miller7b10ef42002-01-21 23:44:12 +1100417 return 0.0;
Damien Miller62116dc2001-12-24 01:41:47 +1100418 }
419
420 RAND_add(&status, sizeof(&status), 0.0);
421
422 if (error_abort) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100423 /*
424 * Closing p[0] on timeout causes the entropy command to
Damien Millera8e06ce2003-11-21 23:48:55 +1100425 * SIGPIPE. Take whatever output we got, and mark this
426 * command as slow
Damien Miller7b10ef42002-01-21 23:44:12 +1100427 */
Damien Miller62116dc2001-12-24 01:41:47 +1100428 debug2("Command '%s' timed out", src->cmdstring);
429 src->sticky_badness *= 2;
430 src->badness = src->sticky_badness;
Damien Miller7b10ef42002-01-21 23:44:12 +1100431 return total_bytes_read;
Damien Miller62116dc2001-12-24 01:41:47 +1100432 }
433
434 if (WIFEXITED(status)) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100435 if (WEXITSTATUS(status) == 0) {
436 return total_bytes_read;
Damien Miller62116dc2001-12-24 01:41:47 +1100437 } else {
Damien Miller7b10ef42002-01-21 23:44:12 +1100438 debug2("Command '%s' exit status was %d",
439 src->cmdstring, WEXITSTATUS(status));
Damien Miller62116dc2001-12-24 01:41:47 +1100440 src->badness = src->sticky_badness = 128;
Damien Miller7b10ef42002-01-21 23:44:12 +1100441 return 0.0;
Damien Miller62116dc2001-12-24 01:41:47 +1100442 }
443 } else if (WIFSIGNALED(status)) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100444 debug2("Command '%s' returned on uncaught signal %d !",
445 src->cmdstring, status);
Damien Miller62116dc2001-12-24 01:41:47 +1100446 src->badness = src->sticky_badness = 128;
Damien Miller7b10ef42002-01-21 23:44:12 +1100447 return 0.0;
Damien Miller62116dc2001-12-24 01:41:47 +1100448 } else
Damien Miller7b10ef42002-01-21 23:44:12 +1100449 return 0.0;
450}
451
452double
453stir_from_system(void)
454{
455 double total_entropy_estimate;
456 long int i;
457
458 total_entropy_estimate = 0;
459
460 i = getpid();
461 RAND_add(&i, sizeof(i), 0.5);
462 total_entropy_estimate += 0.1;
463
464 i = getppid();
465 RAND_add(&i, sizeof(i), 0.5);
466 total_entropy_estimate += 0.1;
467
468 i = getuid();
469 RAND_add(&i, sizeof(i), 0.0);
470 i = getgid();
471 RAND_add(&i, sizeof(i), 0.0);
472
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);
476
477 return total_entropy_estimate;
478}
479
480double
481stir_from_programs(void)
482{
483 int c;
484 double entropy, total_entropy;
Kevin Steves4bdb5472002-07-28 20:42:23 +0000485 unsigned char hash[SHA_DIGEST_LENGTH];
Damien Miller7b10ef42002-01-21 23:44:12 +1100486
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);
493
494 /* Scale back estimate by command's rate */
495 entropy *= entropy_cmds[c].rate;
496
497 /* Upper bound of entropy is SHA_DIGEST_LENGTH */
498 if (entropy > SHA_DIGEST_LENGTH)
499 entropy = SHA_DIGEST_LENGTH;
500
501 /* Stir it in */
502 RAND_add(hash, sizeof(hash), entropy);
503
Damien Millera8e06ce2003-11-21 23:48:55 +1100504 debug3("Got %0.2f bytes of entropy from '%s'",
Damien Miller7b10ef42002-01-21 23:44:12 +1100505 entropy, entropy_cmds[c].cmdstring);
506
507 total_entropy += entropy;
508
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)",
Damien Millera8e06ce2003-11-21 23:48:55 +1100516 entropy_cmds[c].cmdstring,
Damien Miller7b10ef42002-01-21 23:44:12 +1100517 entropy_cmds[c].badness);
518
519 if (entropy_cmds[c].badness > 0)
520 entropy_cmds[c].badness--;
521 }
522 }
523
524 return total_entropy;
Damien Miller62116dc2001-12-24 01:41:47 +1100525}
526
527/*
528 * prng seedfile functions
529 */
530int
Damien Miller7b10ef42002-01-21 23:44:12 +1100531prng_check_seedfile(char *filename)
532{
Damien Miller62116dc2001-12-24 01:41:47 +1100533 struct stat st;
534
Damien Miller7b10ef42002-01-21 23:44:12 +1100535 /*
Damien Millera8e06ce2003-11-21 23:48:55 +1100536 * XXX raceable: eg replace seed between this stat and subsequent
537 * open. Not such a problem because we don't really trust the
Damien Miller7b10ef42002-01-21 23:44:12 +1100538 * seed file anyway.
539 * XXX: use secure path checking as elsewhere in OpenSSH
540 */
Damien Miller62116dc2001-12-24 01:41:47 +1100541 if (lstat(filename, &st) == -1) {
542 /* Give up on hard errors */
543 if (errno != ENOENT)
Damien Miller7b10ef42002-01-21 23:44:12 +1100544 debug("WARNING: Couldn't stat random seed file "
545 "\"%.100s\": %s", filename, strerror(errno));
546 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100547 }
548
549 /* regular file? */
550 if (!S_ISREG(st.st_mode))
Damien Miller7b10ef42002-01-21 23:44:12 +1100551 fatal("PRNG seedfile %.100s is not a regular file",
552 filename);
Damien Miller62116dc2001-12-24 01:41:47 +1100553
554 /* mode 0600, owned by root or the current user? */
555 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid())) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100556 debug("WARNING: PRNG seedfile %.100s must be mode 0600, "
Damien Millerc46b6bc2003-05-16 15:51:44 +1000557 "owned by uid %li", filename, (long int)getuid());
Damien Miller7b10ef42002-01-21 23:44:12 +1100558 return 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100559 }
560
Damien Miller7b10ef42002-01-21 23:44:12 +1100561 return 1;
Damien Miller62116dc2001-12-24 01:41:47 +1100562}
563
564void
Damien Miller7b10ef42002-01-21 23:44:12 +1100565prng_write_seedfile(void)
566{
Damien Millered462d92005-02-16 13:02:45 +1100567 int fd, save_errno;
Kevin Steves4bdb5472002-07-28 20:42:23 +0000568 unsigned char seed[SEED_FILE_SIZE];
Damien Millered462d92005-02-16 13:02:45 +1100569 char filename[MAXPATHLEN], tmpseed[MAXPATHLEN];
Damien Miller62116dc2001-12-24 01:41:47 +1100570 struct passwd *pw;
Damien Millered462d92005-02-16 13:02:45 +1100571 mode_t old_umask;
Damien Miller62116dc2001-12-24 01:41:47 +1100572
573 pw = getpwuid(getuid());
574 if (pw == NULL)
Damien Miller7b10ef42002-01-21 23:44:12 +1100575 fatal("Couldn't get password entry for current user "
Damien Millerc46b6bc2003-05-16 15:51:44 +1000576 "(%li): %s", (long int)getuid(), strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100577
578 /* Try to ensure that the parent directory is there */
579 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
Damien Miller7b10ef42002-01-21 23:44:12 +1100580 _PATH_SSH_USER_DIR);
Darren Tuckerdaf6ff42006-07-05 21:35:48 +1000581 if (mkdir(filename, 0700) < 0 && errno != EEXIST)
582 fatal("mkdir %.200s: %s", filename, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100583
584 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
Damien Miller7b10ef42002-01-21 23:44:12 +1100585 SSH_PRNG_SEED_FILE);
Damien Miller62116dc2001-12-24 01:41:47 +1100586
Damien Millered462d92005-02-16 13:02:45 +1100587 strlcpy(tmpseed, filename, sizeof(tmpseed));
588 if (strlcat(tmpseed, ".XXXXXXXXXX", sizeof(tmpseed)) >=
589 sizeof(tmpseed))
590 fatal("PRNG seed filename too long");
Damien Miller62116dc2001-12-24 01:41:47 +1100591
Damien Millercafbcc72003-03-17 16:13:53 +1100592 if (RAND_bytes(seed, sizeof(seed)) <= 0)
Ben Lindstromda4d9cf2003-09-22 15:36:15 +0000593 fatal("PRNG seed extraction failed");
Damien Miller62116dc2001-12-24 01:41:47 +1100594
595 /* Don't care if the seed doesn't exist */
596 prng_check_seedfile(filename);
597
Damien Millered462d92005-02-16 13:02:45 +1100598 old_umask = umask(0177);
599
600 if ((fd = mkstemp(tmpseed)) == -1) {
601 debug("WARNING: couldn't make temporary PRNG seedfile %.100s "
602 "(%.100s)", tmpseed, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100603 } else {
Damien Millered462d92005-02-16 13:02:45 +1100604 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);
Damien Miller7b10ef42002-01-21 23:44:12 +1100609 fatal("problem writing PRNG seedfile %.100s "
Damien Millered462d92005-02-16 13:02:45 +1100610 "(%.100s)", filename, strerror(save_errno));
611 }
Damien Miller62116dc2001-12-24 01:41:47 +1100612 close(fd);
Damien Millered462d92005-02-16 13:02:45 +1100613 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 "
Damien Miller94cf4c82005-07-17 17:04:47 +1000618 "to %.100s (%.100s)", tmpseed, filename,
Damien Millered462d92005-02-16 13:02:45 +1100619 strerror(save_errno));
620 }
Damien Miller62116dc2001-12-24 01:41:47 +1100621 }
Damien Millered462d92005-02-16 13:02:45 +1100622 umask(old_umask);
Damien Miller62116dc2001-12-24 01:41:47 +1100623}
624
625void
Damien Miller7b10ef42002-01-21 23:44:12 +1100626prng_read_seedfile(void)
627{
Damien Miller62116dc2001-12-24 01:41:47 +1100628 int fd;
Damien Miller7b10ef42002-01-21 23:44:12 +1100629 char seed[SEED_FILE_SIZE], filename[MAXPATHLEN];
Damien Miller62116dc2001-12-24 01:41:47 +1100630 struct passwd *pw;
631
632 pw = getpwuid(getuid());
633 if (pw == NULL)
Damien Miller7b10ef42002-01-21 23:44:12 +1100634 fatal("Couldn't get password entry for current user "
Damien Millerc46b6bc2003-05-16 15:51:44 +1000635 "(%li): %s", (long int)getuid(), strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100636
637 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
638 SSH_PRNG_SEED_FILE);
639
640 debug("loading PRNG seed from file %.100s", filename);
641
642 if (!prng_check_seedfile(filename)) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100643 verbose("Random seed file not found or invalid, ignoring.");
Damien Miller62116dc2001-12-24 01:41:47 +1100644 return;
645 }
646
647 /* open the file and read in the seed */
648 fd = open(filename, O_RDONLY);
649 if (fd == -1)
Damien Miller7b10ef42002-01-21 23:44:12 +1100650 fatal("could not open PRNG seedfile %.100s (%.100s)",
651 filename, strerror(errno));
Damien Miller62116dc2001-12-24 01:41:47 +1100652
Damien Miller7b10ef42002-01-21 23:44:12 +1100653 if (atomicio(read, fd, &seed, sizeof(seed)) < sizeof(seed)) {
654 verbose("invalid or short read from PRNG seedfile "
655 "%.100s - ignoring", filename);
Damien Miller62116dc2001-12-24 01:41:47 +1100656 memset(seed, '\0', sizeof(seed));
657 }
658 close(fd);
659
660 /* stir in the seed, with estimated entropy zero */
661 RAND_add(&seed, sizeof(seed), 0.0);
662}
663
664
665/*
666 * entropy command initialisation functions
667 */
668int
669prng_read_commands(char *cmdfilename)
670{
Damien Miller7b10ef42002-01-21 23:44:12 +1100671 char cmd[SEED_FILE_SIZE], *cp, line[1024], path[SEED_FILE_SIZE];
Damien Miller62116dc2001-12-24 01:41:47 +1100672 double est;
Damien Miller7b10ef42002-01-21 23:44:12 +1100673 entropy_cmd_t *entcmd;
674 FILE *f;
675 int cur_cmd, linenum, num_cmds, arg;
Damien Miller62116dc2001-12-24 01:41:47 +1100676
Damien Miller7b10ef42002-01-21 23:44:12 +1100677 if ((f = fopen(cmdfilename, "r")) == NULL) {
Damien Miller62116dc2001-12-24 01:41:47 +1100678 fatal("couldn't read entropy commands file %.100s: %.100s",
679 cmdfilename, strerror(errno));
680 }
681
Damien Miller7b10ef42002-01-21 23:44:12 +1100682 num_cmds = 64;
Darren Tuckerd8093e42006-05-04 16:24:34 +1000683 entcmd = xcalloc(num_cmds, sizeof(entropy_cmd_t));
Damien Miller62116dc2001-12-24 01:41:47 +1100684
685 /* Read in file */
Damien Miller7b10ef42002-01-21 23:44:12 +1100686 cur_cmd = linenum = 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100687 while (fgets(line, sizeof(line), f)) {
Damien Miller62116dc2001-12-24 01:41:47 +1100688 linenum++;
689
Damien Miller7b10ef42002-01-21 23:44:12 +1100690 /* Skip leading whitespace, blank lines and comments */
Damien Miller62116dc2001-12-24 01:41:47 +1100691 cp = line + strspn(line, WHITESPACE);
692 if ((*cp == 0) || (*cp == '#'))
693 continue; /* done with this line */
694
Damien Miller7b10ef42002-01-21 23:44:12 +1100695 /*
Damien Millera8e06ce2003-11-21 23:48:55 +1100696 * The first non-whitespace char should be a double quote
Damien Miller7b10ef42002-01-21 23:44:12 +1100697 * delimiting the commandline
698 */
Damien Miller62116dc2001-12-24 01:41:47 +1100699 if (*cp != '"') {
Damien Miller7b10ef42002-01-21 23:44:12 +1100700 error("bad entropy command, %.100s line %d",
701 cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100702 continue;
703 }
704
Damien Miller7b10ef42002-01-21 23:44:12 +1100705 /*
706 * First token, command args (incl. argv[0]) in double
707 * quotes
708 */
Damien Miller62116dc2001-12-24 01:41:47 +1100709 cp = strtok(cp, "\"");
710 if (cp == NULL) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100711 error("missing or bad command string, %.100s "
712 "line %d -- ignored", cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100713 continue;
714 }
715 strlcpy(cmd, cp, sizeof(cmd));
716
Damien Miller7b10ef42002-01-21 23:44:12 +1100717 /* Second token, full command path */
Damien Miller62116dc2001-12-24 01:41:47 +1100718 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100719 error("missing command path, %.100s "
720 "line %d -- ignored", cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100721 continue;
722 }
723
Damien Miller7b10ef42002-01-21 23:44:12 +1100724 /* Did configure mark this as dead? */
Damien Miller62116dc2001-12-24 01:41:47 +1100725 if (strncmp("undef", cp, 5) == 0)
726 continue;
727
728 strlcpy(path, cp, sizeof(path));
729
Damien Miller7b10ef42002-01-21 23:44:12 +1100730 /* Third token, entropy rate estimate for this command */
Damien Miller62116dc2001-12-24 01:41:47 +1100731 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100732 error("missing entropy estimate, %.100s "
733 "line %d -- ignored", cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100734 continue;
735 }
Damien Miller7b10ef42002-01-21 23:44:12 +1100736 est = strtod(cp, NULL);
Damien Miller62116dc2001-12-24 01:41:47 +1100737
738 /* end of line */
739 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
Damien Miller7b10ef42002-01-21 23:44:12 +1100740 error("garbage at end of line %d in %.100s "
741 "-- ignored", linenum, cmdfilename);
Damien Miller62116dc2001-12-24 01:41:47 +1100742 continue;
743 }
744
745 /* save the command for debug messages */
746 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
747
748 /* split the command args */
749 cp = strtok(cmd, WHITESPACE);
750 arg = 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100751 do {
Damien Miller7b10ef42002-01-21 23:44:12 +1100752 entcmd[cur_cmd].args[arg] = xstrdup(cp);
Damien Miller62116dc2001-12-24 01:41:47 +1100753 arg++;
Damien Miller7b10ef42002-01-21 23:44:12 +1100754 } while(arg < NUM_ARGS && (cp = strtok(NULL, WHITESPACE)));
Damien Miller62116dc2001-12-24 01:41:47 +1100755
756 if (strtok(NULL, WHITESPACE))
Damien Miller7b10ef42002-01-21 23:44:12 +1100757 error("ignored extra commands (max %d), %.100s "
758 "line %d", NUM_ARGS, cmdfilename, linenum);
Damien Miller62116dc2001-12-24 01:41:47 +1100759
760 /* Copy the command path and rate estimate */
761 entcmd[cur_cmd].path = xstrdup(path);
762 entcmd[cur_cmd].rate = est;
763
764 /* Initialise other values */
765 entcmd[cur_cmd].sticky_badness = 1;
766
767 cur_cmd++;
768
Damien Miller7b10ef42002-01-21 23:44:12 +1100769 /*
770 * If we've filled the array, reallocate it twice the size
Damien Millera8e06ce2003-11-21 23:48:55 +1100771 * Do this now because even if this we're on the last
Damien Miller7b10ef42002-01-21 23:44:12 +1100772 * command we need another slot to mark the last entry
773 */
Damien Miller62116dc2001-12-24 01:41:47 +1100774 if (cur_cmd == num_cmds) {
775 num_cmds *= 2;
Damien Miller36812092006-03-26 14:22:47 +1100776 entcmd = xrealloc(entcmd, num_cmds,
Damien Miller7b10ef42002-01-21 23:44:12 +1100777 sizeof(entropy_cmd_t));
Damien Miller62116dc2001-12-24 01:41:47 +1100778 }
779 }
780
781 /* zero the last entry */
Damien Miller7b10ef42002-01-21 23:44:12 +1100782 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_cmd_t));
Damien Miller62116dc2001-12-24 01:41:47 +1100783
784 /* trim to size */
Damien Miller36812092006-03-26 14:22:47 +1100785 entropy_cmds = xrealloc(entcmd, (cur_cmd + 1),
Damien Miller7b10ef42002-01-21 23:44:12 +1100786 sizeof(entropy_cmd_t));
Damien Miller62116dc2001-12-24 01:41:47 +1100787
Damien Miller7b10ef42002-01-21 23:44:12 +1100788 debug("Loaded %d entropy commands from %.100s", cur_cmd,
789 cmdfilename);
Damien Miller62116dc2001-12-24 01:41:47 +1100790
Darren Tuckerf58b29d2006-05-17 22:24:56 +1000791 fclose(f);
Damien Miller7b10ef42002-01-21 23:44:12 +1100792 return cur_cmd < MIN_ENTROPY_SOURCES ? -1 : 0;
Damien Miller62116dc2001-12-24 01:41:47 +1100793}
794
Damien Miller32e48182002-04-14 19:27:12 +1000795void
796usage(void)
797{
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");
Damien Miller7daf0442004-08-23 21:52:08 +1000801 fprintf(stderr, " -x Force output in hexadecimal (for debugging)\n");
Damien Miller32e48182002-04-14 19:27:12 +1000802 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);
805}
806
Damien Millera8e06ce2003-11-21 23:48:55 +1100807int
Damien Miller62116dc2001-12-24 01:41:47 +1100808main(int argc, char **argv)
809{
Damien Miller32e48182002-04-14 19:27:12 +1000810 unsigned char *buf;
811 int ret, ch, debug_level, output_hex, bytes;
812 extern char *optarg;
813 LogLevel ll;
Damien Miller62116dc2001-12-24 01:41:47 +1100814
Damien Miller59d3d5b2003-08-22 09:34:41 +1000815 __progname = ssh_get_progname(argv[0]);
Damien Miller62116dc2001-12-24 01:41:47 +1100816 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
817
Damien Miller32e48182002-04-14 19:27:12 +1000818 ll = SYSLOG_LEVEL_INFO;
819 debug_level = output_hex = 0;
820 bytes = OUTPUT_SEED_SIZE;
821
822 /* Don't write binary data to a tty, unless we are forced to */
823 if (isatty(STDOUT_FILENO))
824 output_hex = 1;
Damien Miller787b2ec2003-11-21 23:56:47 +1100825
Damien Miller32e48182002-04-14 19:27:12 +1000826 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();
848 }
849 }
850
851 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
Damien Miller787b2ec2003-11-21 23:56:47 +1100852
Damien Miller7b10ef42002-01-21 23:44:12 +1100853#ifdef USE_SEED_FILES
854 prng_read_seedfile();
855#endif
856
Damien Miller32e48182002-04-14 19:27:12 +1000857 buf = xmalloc(bytes);
858
Damien Miller7b10ef42002-01-21 23:44:12 +1100859 /*
860 * Seed the RNG from wherever we can
861 */
Damien Miller787b2ec2003-11-21 23:56:47 +1100862
Damien Miller7b10ef42002-01-21 23:44:12 +1100863 /* Take whatever is on the stack, but don't credit it */
Damien Miller32e48182002-04-14 19:27:12 +1000864 RAND_add(buf, bytes, 0);
Damien Miller7b10ef42002-01-21 23:44:12 +1100865
Damien Millera8e06ce2003-11-21 23:48:55 +1100866 debug("Seeded RNG with %i bytes from system calls",
Damien Miller7b10ef42002-01-21 23:44:12 +1100867 (int)stir_from_system());
868
Darren Tucker8686ed72004-12-20 12:05:08 +1100869 /* 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());
878 }
Damien Miller7b10ef42002-01-21 23:44:12 +1100879
880#ifdef USE_SEED_FILES
881 prng_write_seedfile();
882#endif
883
884 /*
885 * Write the seed to stdout
886 */
Damien Miller62116dc2001-12-24 01:41:47 +1100887
888 if (!RAND_status())
889 fatal("Not enough entropy in RNG");
890
Damien Millercafbcc72003-03-17 16:13:53 +1100891 if (RAND_bytes(buf, bytes) <= 0)
892 fatal("Couldn't extract entropy from PRNG");
Damien Miller62116dc2001-12-24 01:41:47 +1100893
Damien Miller32e48182002-04-14 19:27:12 +1000894 if (output_hex) {
895 for(ret = 0; ret < bytes; ret++)
896 printf("%02x", (unsigned char)(buf[ret]));
897 printf("\n");
898 } else
Darren Tucker8661b562003-07-06 15:20:46 +1000899 ret = atomicio(vwrite, STDOUT_FILENO, buf, bytes);
Damien Miller787b2ec2003-11-21 23:56:47 +1100900
Damien Miller32e48182002-04-14 19:27:12 +1000901 memset(buf, '\0', bytes);
902 xfree(buf);
Damien Miller787b2ec2003-11-21 23:56:47 +1100903
Damien Miller32e48182002-04-14 19:27:12 +1000904 return ret == bytes ? 0 : 1;
Damien Miller62116dc2001-12-24 01:41:47 +1100905}
Darren Tucker7b48d252005-02-16 13:20:07 +1100906
907/*
908 * We may attempt to re-seed during mkstemp if we are using the one in the
Darren Tucker7a8619a2005-02-16 13:32:30 +1100909 * 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.
Darren Tucker7b48d252005-02-16 13:20:07 +1100911 */
912void
913seed_rng(void)
914{
915 if (!RAND_status())
916 fatal("Not enough entropy in RNG");
917}