blob: 842760992139b90d781205761e50e48131dfa4e0 [file] [log] [blame]
Damien Miller040f3832000-04-03 14:50:43 +10001/*
2 * Copyright (c) 2000 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 * 3. All advertising materials mentioning features or use of this software
13 * must display the following acknowledgement:
14 * This product includes software developed by Markus Friedl.
15 * 4. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#include "includes.h"
31
32#include "ssh.h"
33#include "xmalloc.h"
34
Damien Miller5f056372000-04-16 12:31:48 +100035#include <openssl/rand.h>
36#include <openssl/sha.h>
Damien Miller040f3832000-04-03 14:50:43 +100037
Damien Millerf9b625c2000-07-09 22:42:32 +100038RCSID("$Id: entropy.c,v 1.17 2000/07/09 12:42:33 djm Exp $");
Damien Miller040f3832000-04-03 14:50:43 +100039
Damien Miller040f3832000-04-03 14:50:43 +100040#ifndef offsetof
41# define offsetof(type, member) ((size_t) &((type *)0)->member)
42#endif
Damien Miller14c12cb2000-06-07 22:20:23 +100043
44/* Print lots of detail */
45/* #define DEBUG_ENTROPY */
46
47/* Number of times to pass through command list gathering entropy */
48#define NUM_ENTROPY_RUNS 1
49
50/* Scale entropy estimates back by this amount on subsequent runs */
51#define SCALE_PER_RUN 10.0
52
53/* Minimum number of commands to be considered valid */
54#define MIN_ENTROPY_SOURCES 16
55
56#define WHITESPACE " \t\n"
57
Damien Miller7b22d652000-06-18 14:07:04 +100058#ifndef RUSAGE_SELF
59# define RUSAGE_SELF 0
60#endif
61#ifndef RUSAGE_CHILDREN
62# define RUSAGE_CHILDREN 0
63#endif
64
Damien Miller14c12cb2000-06-07 22:20:23 +100065#if defined(EGD_SOCKET) || defined(RANDOM_POOL)
66
67#ifdef EGD_SOCKET
Damien Miller040f3832000-04-03 14:50:43 +100068/* Collect entropy from EGD */
Damien Miller64681252000-06-26 13:01:33 +100069int get_random_bytes(unsigned char *buf, int len)
Damien Miller040f3832000-04-03 14:50:43 +100070{
Damien Miller64681252000-06-26 13:01:33 +100071 int fd;
72 char msg[2];
Damien Miller040f3832000-04-03 14:50:43 +100073 struct sockaddr_un addr;
74 int addr_len;
75
Damien Miller64681252000-06-26 13:01:33 +100076 /* Sanity checks */
Damien Miller040f3832000-04-03 14:50:43 +100077 if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
78 fatal("Random pool path is too long");
Damien Miller040f3832000-04-03 14:50:43 +100079 if (len > 255)
80 fatal("Too many bytes to read from EGD");
Damien Miller64681252000-06-26 13:01:33 +100081
82 memset(&addr, '\0', sizeof(addr));
83 addr.sun_family = AF_UNIX;
84 strlcpy(addr.sun_path, EGD_SOCKET, sizeof(addr.sun_path));
85 addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
Damien Miller040f3832000-04-03 14:50:43 +100086
Damien Miller64681252000-06-26 13:01:33 +100087 fd = socket(AF_UNIX, SOCK_STREAM, 0);
88 if (fd == -1) {
89 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
90 return(0);
91 }
92
93 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
94 error("Couldn't connect to EGD socket \"%s\": %s",
95 addr.sun_path, strerror(errno));
96 close(fd);
97 return(0);
98 }
99
Damien Miller040f3832000-04-03 14:50:43 +1000100 /* Send blocking read request to EGD */
Damien Miller64681252000-06-26 13:01:33 +1000101 msg[0] = 0x02;
102 msg[1] = len;
Damien Miller040f3832000-04-03 14:50:43 +1000103
Damien Miller64681252000-06-26 13:01:33 +1000104 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
105 error("Couldn't write to EGD socket \"%s\": %s",
106 EGD_SOCKET, strerror(errno));
107 close(fd);
108 return(0);
109 }
Damien Miller040f3832000-04-03 14:50:43 +1000110
Damien Miller64681252000-06-26 13:01:33 +1000111 if (atomicio(read, fd, buf, len) != len) {
112 error("Couldn't read from EGD socket \"%s\": %s",
113 EGD_SOCKET, strerror(errno));
114 close(fd);
115 return(0);
116 }
117
118 close(fd);
119
120 return(1);
Damien Miller040f3832000-04-03 14:50:43 +1000121}
122#else /* !EGD_SOCKET */
123#ifdef RANDOM_POOL
124/* Collect entropy from /dev/urandom or pipe */
Damien Miller64681252000-06-26 13:01:33 +1000125int get_random_bytes(unsigned char *buf, int len)
Damien Miller040f3832000-04-03 14:50:43 +1000126{
Damien Miller64681252000-06-26 13:01:33 +1000127 int random_pool;
Damien Miller040f3832000-04-03 14:50:43 +1000128
Damien Miller64681252000-06-26 13:01:33 +1000129 random_pool = open(RANDOM_POOL, O_RDONLY);
Damien Miller040f3832000-04-03 14:50:43 +1000130 if (random_pool == -1) {
Damien Miller64681252000-06-26 13:01:33 +1000131 error("Couldn't open random pool \"%s\": %s",
132 RANDOM_POOL, strerror(errno));
133 return(0);
Damien Miller040f3832000-04-03 14:50:43 +1000134 }
135
Damien Miller64681252000-06-26 13:01:33 +1000136 if (atomicio(read, random_pool, buf, len) != len) {
137 error("Couldn't read from random pool \"%s\": %s",
138 RANDOM_POOL, strerror(errno));
139 close(random_pool);
140 return(0);
141 }
142
143 close(random_pool);
144
145 return(1);
Damien Miller040f3832000-04-03 14:50:43 +1000146}
147#endif /* RANDOM_POOL */
148#endif /* EGD_SOCKET */
149
Damien Miller14c12cb2000-06-07 22:20:23 +1000150/*
151 * Seed OpenSSL's random number pool from Kernel random number generator
152 * or EGD
153 */
154void
155seed_rng(void)
156{
157 char buf[32];
158
159 debug("Seeding random number generator");
Damien Miller64681252000-06-26 13:01:33 +1000160
Damien Miller08006472000-06-26 13:55:31 +1000161 if (!get_random_bytes(buf, sizeof(buf))) {
162 if (!RAND_status())
163 fatal("Entropy collection failed and entropy exhausted");
164 } else {
165 RAND_add(buf, sizeof(buf), sizeof(buf));
166 }
167
Damien Miller14c12cb2000-06-07 22:20:23 +1000168 memset(buf, '\0', sizeof(buf));
169}
170
Damien Millerf9b625c2000-07-09 22:42:32 +1000171/* No-op */
172void init_rng(void) {}
173
Damien Miller14c12cb2000-06-07 22:20:23 +1000174#else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
175
Damien Miller040f3832000-04-03 14:50:43 +1000176/*
177 * FIXME: proper entropy estimations. All current values are guesses
Damien Miller4018c192000-04-30 09:30:44 +1000178 * FIXME: (ATL) do estimates at compile time?
Damien Miller040f3832000-04-03 14:50:43 +1000179 * FIXME: More entropy sources
180 */
181
Damien Miller4018c192000-04-30 09:30:44 +1000182/* slow command timeouts (all in milliseconds) */
183/* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
184static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
185
Damien Miller0437b332000-05-02 09:56:41 +1000186static int prng_seed_saved = 0;
Damien Millerf9b625c2000-07-09 22:42:32 +1000187static int prng_initialised = 0;
188uid_t original_uid;
Damien Miller040f3832000-04-03 14:50:43 +1000189
190typedef struct
191{
192 /* Proportion of data that is entropy */
193 double rate;
Damien Miller4018c192000-04-30 09:30:44 +1000194 /* Counter goes positive if this command times out */
195 unsigned int badness;
196 /* Increases by factor of two each timeout */
197 unsigned int sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000198 /* Path to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000199 char *path;
Damien Miller040f3832000-04-03 14:50:43 +1000200 /* argv to pass to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000201 char *args[5];
Damien Miller8d1fd572000-05-17 21:34:07 +1000202 /* full command string (debug) */
203 char *cmdstring;
Damien Miller040f3832000-04-03 14:50:43 +1000204} entropy_source_t;
205
Damien Miller4018c192000-04-30 09:30:44 +1000206double stir_from_system(void);
207double stir_from_programs(void);
208double stir_gettimeofday(double entropy_estimate);
209double stir_clock(double entropy_estimate);
210double stir_rusage(int who, double entropy_estimate);
211double hash_output_from_command(entropy_source_t *src, char *hash);
212
Damien Miller0437b332000-05-02 09:56:41 +1000213/* this is initialised from a file, by prng_read_commands() */
214entropy_source_t *entropy_sources = NULL;
Damien Miller040f3832000-04-03 14:50:43 +1000215
Damien Miller040f3832000-04-03 14:50:43 +1000216double
217stir_from_system(void)
218{
219 double total_entropy_estimate;
220 long int i;
221
222 total_entropy_estimate = 0;
223
224 i = getpid();
Damien Miller7b22d652000-06-18 14:07:04 +1000225 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000226 total_entropy_estimate += 0.1;
227
228 i = getppid();
Damien Miller7b22d652000-06-18 14:07:04 +1000229 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000230 total_entropy_estimate += 0.1;
231
232 i = getuid();
233 RAND_add(&i, sizeof(i), 0.0);
234 i = getgid();
235 RAND_add(&i, sizeof(i), 0.0);
236
237 total_entropy_estimate += stir_gettimeofday(1.0);
Damien Miller7b22d652000-06-18 14:07:04 +1000238 total_entropy_estimate += stir_clock(0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000239 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
240
241 return(total_entropy_estimate);
242}
243
244double
245stir_from_programs(void)
246{
247 int i;
248 int c;
249 double entropy_estimate;
250 double total_entropy_estimate;
251 char hash[SHA_DIGEST_LENGTH];
252
Damien Miller040f3832000-04-03 14:50:43 +1000253 total_entropy_estimate = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000254 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
Damien Miller040f3832000-04-03 14:50:43 +1000255 c = 0;
256 while (entropy_sources[c].path != NULL) {
Damien Miller040f3832000-04-03 14:50:43 +1000257
Damien Miller4018c192000-04-30 09:30:44 +1000258 if (!entropy_sources[c].badness) {
259 /* Hash output from command */
260 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
261
262 /* Scale back entropy estimate according to command's rate */
263 entropy_estimate *= entropy_sources[c].rate;
Damien Miller040f3832000-04-03 14:50:43 +1000264
Damien Miller4018c192000-04-30 09:30:44 +1000265 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
266 if (entropy_estimate > SHA_DIGEST_LENGTH)
267 entropy_estimate = SHA_DIGEST_LENGTH;
Damien Miller040f3832000-04-03 14:50:43 +1000268
Damien Miller14c12cb2000-06-07 22:20:23 +1000269 /* Scale back estimates for subsequent passes through list */
270 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
Damien Miller040f3832000-04-03 14:50:43 +1000271
Damien Miller4018c192000-04-30 09:30:44 +1000272 /* Stir it in */
273 RAND_add(hash, sizeof(hash), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000274
Damien Miller14c12cb2000-06-07 22:20:23 +1000275#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000276 debug("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
277 entropy_sources[c].cmdstring);
Damien Miller040f3832000-04-03 14:50:43 +1000278#endif
279
Damien Miller4018c192000-04-30 09:30:44 +1000280 total_entropy_estimate += entropy_estimate;
Damien Miller040f3832000-04-03 14:50:43 +1000281
282 /* Execution times should be a little unpredictable */
Damien Miller4018c192000-04-30 09:30:44 +1000283 total_entropy_estimate += stir_gettimeofday(0.05);
284 total_entropy_estimate += stir_clock(0.05);
285 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
286 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
287 } else {
Damien Miller14c12cb2000-06-07 22:20:23 +1000288#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000289 debug("Command '%s' disabled (badness %d)",
290 entropy_sources[c].cmdstring, entropy_sources[c].badness);
Damien Miller4018c192000-04-30 09:30:44 +1000291#endif
292
293 if (entropy_sources[c].badness > 0)
294 entropy_sources[c].badness--;
295 }
296
Damien Miller040f3832000-04-03 14:50:43 +1000297 c++;
298 }
299 }
300
301 return(total_entropy_estimate);
302}
303
304double
305stir_gettimeofday(double entropy_estimate)
306{
307 struct timeval tv;
308
309 if (gettimeofday(&tv, NULL) == -1)
310 fatal("Couldn't gettimeofday: %s", strerror(errno));
311
312 RAND_add(&tv, sizeof(tv), entropy_estimate);
313
314 return(entropy_estimate);
315}
316
317double
318stir_clock(double entropy_estimate)
319{
320#ifdef HAVE_CLOCK
321 clock_t c;
322
323 c = clock();
324 RAND_add(&c, sizeof(c), entropy_estimate);
325
326 return(entropy_estimate);
327#else /* _HAVE_CLOCK */
328 return(0);
329#endif /* _HAVE_CLOCK */
330}
331
332double
333stir_rusage(int who, double entropy_estimate)
334{
335#ifdef HAVE_GETRUSAGE
336 struct rusage ru;
337
Damien Miller4018c192000-04-30 09:30:44 +1000338 if (getrusage(who, &ru) == -1)
Damien Miller7b22d652000-06-18 14:07:04 +1000339 return(0);
Damien Miller040f3832000-04-03 14:50:43 +1000340
Damien Miller7b22d652000-06-18 14:07:04 +1000341 RAND_add(&ru, sizeof(ru), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000342
343 return(entropy_estimate);
344#else /* _HAVE_GETRUSAGE */
345 return(0);
346#endif /* _HAVE_GETRUSAGE */
347}
348
Damien Miller8d1fd572000-05-17 21:34:07 +1000349
350static
351int
352_get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
353 int secdiff, usecdiff;
354
355 secdiff = t2->tv_sec - t1->tv_sec;
356 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
357 return (int)(usecdiff / 1000);
358}
359
Damien Miller040f3832000-04-03 14:50:43 +1000360double
Damien Miller4018c192000-04-30 09:30:44 +1000361hash_output_from_command(entropy_source_t *src, char *hash)
Damien Miller040f3832000-04-03 14:50:43 +1000362{
363 static int devnull = -1;
364 int p[2];
Damien Miller4018c192000-04-30 09:30:44 +1000365 fd_set rdset;
366 int cmd_eof = 0, error_abort = 0;
Damien Miller8d1fd572000-05-17 21:34:07 +1000367 struct timeval tv_start, tv_current;
368 int msec_elapsed = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000369 pid_t pid;
370 int status;
Damien Miller8d1fd572000-05-17 21:34:07 +1000371 char buf[16384];
Damien Miller040f3832000-04-03 14:50:43 +1000372 int bytes_read;
373 int total_bytes_read;
374 SHA_CTX sha;
375
376 if (devnull == -1) {
377 devnull = open("/dev/null", O_RDWR);
378 if (devnull == -1)
379 fatal("Couldn't open /dev/null: %s", strerror(errno));
380 }
381
382 if (pipe(p) == -1)
383 fatal("Couldn't open pipe: %s", strerror(errno));
384
Damien Miller8d1fd572000-05-17 21:34:07 +1000385 (void)gettimeofday(&tv_start, NULL); /* record start time */
386
Damien Miller040f3832000-04-03 14:50:43 +1000387 switch (pid = fork()) {
388 case -1: /* Error */
389 close(p[0]);
390 close(p[1]);
391 fatal("Couldn't fork: %s", strerror(errno));
392 /* NOTREACHED */
393 case 0: /* Child */
Damien Miller4018c192000-04-30 09:30:44 +1000394 dup2(devnull, STDIN_FILENO);
395 dup2(p[1], STDOUT_FILENO);
396 dup2(p[1], STDERR_FILENO);
Damien Miller040f3832000-04-03 14:50:43 +1000397 close(p[0]);
398 close(p[1]);
399 close(devnull);
400
Damien Millerf9b625c2000-07-09 22:42:32 +1000401 setuid(original_uid);
Damien Miller4018c192000-04-30 09:30:44 +1000402 execv(src->path, (char**)(src->args));
Damien Miller8d1fd572000-05-17 21:34:07 +1000403 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
404 strerror(errno));
Damien Miller040f3832000-04-03 14:50:43 +1000405 _exit(-1);
406 default: /* Parent */
407 break;
408 }
409
410 RAND_add(&pid, sizeof(&pid), 0.0);
411
412 close(p[1]);
413
414 /* Hash output from child */
415 SHA1_Init(&sha);
416 total_bytes_read = 0;
Damien Miller4018c192000-04-30 09:30:44 +1000417
418 while (!error_abort && !cmd_eof) {
419 int ret;
420 struct timeval tv;
Damien Miller8d1fd572000-05-17 21:34:07 +1000421 int msec_remaining;
422
423 (void) gettimeofday(&tv_current, 0);
Damien Miller14c12cb2000-06-07 22:20:23 +1000424 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
Damien Miller8d1fd572000-05-17 21:34:07 +1000425 if (msec_elapsed >= entropy_timeout_current) {
426 error_abort=1;
427 continue;
428 }
429 msec_remaining = entropy_timeout_current - msec_elapsed;
Damien Miller4018c192000-04-30 09:30:44 +1000430
431 FD_ZERO(&rdset);
432 FD_SET(p[0], &rdset);
Damien Miller8d1fd572000-05-17 21:34:07 +1000433 tv.tv_sec = msec_remaining / 1000;
434 tv.tv_usec = (msec_remaining % 1000) * 1000;
Damien Miller4018c192000-04-30 09:30:44 +1000435
436 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
Damien Miller8d1fd572000-05-17 21:34:07 +1000437
Damien Millerf9b625c2000-07-09 22:42:32 +1000438 RAND_add(&tv, sizeof(tv), 0.0);
439
Damien Miller4018c192000-04-30 09:30:44 +1000440 switch (ret) {
441 case 0:
442 /* timer expired */
443 error_abort = 1;
444 break;
Damien Miller4018c192000-04-30 09:30:44 +1000445 case 1:
446 /* command input */
447 bytes_read = read(p[0], buf, sizeof(buf));
Damien Millerf9b625c2000-07-09 22:42:32 +1000448 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
Damien Miller4018c192000-04-30 09:30:44 +1000449 if (bytes_read == -1) {
450 error_abort = 1;
451 break;
Damien Millerf9b625c2000-07-09 22:42:32 +1000452 } else if (bytes_read) {
Damien Miller8d1fd572000-05-17 21:34:07 +1000453 SHA1_Update(&sha, buf, bytes_read);
454 total_bytes_read += bytes_read;
Damien Millerf9b625c2000-07-09 22:42:32 +1000455 } else {
Damien Miller8d1fd572000-05-17 21:34:07 +1000456 cmd_eof = 1;
Damien Millerf9b625c2000-07-09 22:42:32 +1000457 }
Damien Miller4018c192000-04-30 09:30:44 +1000458 break;
Damien Miller4018c192000-04-30 09:30:44 +1000459 case -1:
460 default:
Damien Millerf9b625c2000-07-09 22:42:32 +1000461 /* error */
Damien Miller8d1fd572000-05-17 21:34:07 +1000462 debug("Command '%s': select() failed: %s", src->cmdstring,
463 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000464 error_abort = 1;
465 break;
Damien Millerf9b625c2000-07-09 22:42:32 +1000466 }
467 }
Damien Miller4018c192000-04-30 09:30:44 +1000468
Damien Miller040f3832000-04-03 14:50:43 +1000469 SHA1_Final(hash, &sha);
470
471 close(p[0]);
Damien Miller8d1fd572000-05-17 21:34:07 +1000472
Damien Miller14c12cb2000-06-07 22:20:23 +1000473#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000474 debug("Time elapsed: %d msec", msec_elapsed);
Damien Miller14c12cb2000-06-07 22:20:23 +1000475#endif
Damien Miller040f3832000-04-03 14:50:43 +1000476
477 if (waitpid(pid, &status, 0) == -1) {
Damien Miller8d1fd572000-05-17 21:34:07 +1000478 debug("Couldn't wait for child '%s' completion: %s", src->cmdstring,
479 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000480 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000481 }
482
483 RAND_add(&status, sizeof(&status), 0.0);
484
Damien Miller4018c192000-04-30 09:30:44 +1000485 if (error_abort) {
486 /* closing p[0] on timeout causes the entropy command to
487 * SIGPIPE. Take whatever output we got, and mark this command
488 * as slow */
Damien Miller8d1fd572000-05-17 21:34:07 +1000489 debug("Command '%s' timed out", src->cmdstring);
Damien Miller4018c192000-04-30 09:30:44 +1000490 src->sticky_badness *= 2;
491 src->badness = src->sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000492 return(total_bytes_read);
Damien Miller4018c192000-04-30 09:30:44 +1000493 }
494
495 if (WIFEXITED(status)) {
496 if (WEXITSTATUS(status)==0) {
497 return(total_bytes_read);
498 } else {
Damien Miller14c12cb2000-06-07 22:20:23 +1000499 debug("Command '%s' exit status was %d", src->cmdstring,
500 WEXITSTATUS(status));
Damien Miller4018c192000-04-30 09:30:44 +1000501 src->badness = src->sticky_badness = 128;
502 return (0.0);
503 }
504 } else if (WIFSIGNALED(status)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000505 debug("Command '%s' returned on uncaught signal %d !", src->cmdstring,
506 status);
Damien Miller4018c192000-04-30 09:30:44 +1000507 src->badness = src->sticky_badness = 128;
508 return(0.0);
509 } else
510 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000511}
Damien Miller4018c192000-04-30 09:30:44 +1000512
513/*
514 * prng seedfile functions
515 */
516int
517prng_check_seedfile(char *filename) {
518
519 struct stat st;
520
521 /* FIXME raceable: eg replace seed between this stat and subsequent open */
522 /* Not such a problem because we don't trust the seed file anyway */
523 if (lstat(filename, &st) == -1) {
524 /* Fail on hard errors */
525 if (errno != ENOENT)
526 fatal("Couldn't stat random seed file \"%s\": %s", filename,
527 strerror(errno));
528
529 return(0);
530 }
531
532 /* regular file? */
533 if (!S_ISREG(st.st_mode))
534 fatal("PRNG seedfile %.100s is not a regular file", filename);
535
536 /* mode 0600, owned by root or the current user? */
Damien Millerf9b625c2000-07-09 22:42:32 +1000537 if (((st.st_mode & 0177) != 0) || !(st.st_uid == original_uid))
Damien Miller4018c192000-04-30 09:30:44 +1000538 fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d",
539 filename, getuid());
540
541 return(1);
542}
543
544void
545prng_write_seedfile(void) {
546 int fd;
547 char seed[1024];
548 char filename[1024];
549 struct passwd *pw;
550
551 /* Don't bother if we have already saved a seed */
552 if (prng_seed_saved)
553 return;
554
Damien Millerf9b625c2000-07-09 22:42:32 +1000555 setuid(original_uid);
556
Damien Millerfc0b11b2000-05-02 00:03:55 +1000557 prng_seed_saved = 1;
558
Damien Millerf9b625c2000-07-09 22:42:32 +1000559 pw = getpwuid(original_uid);
Damien Miller4018c192000-04-30 09:30:44 +1000560 if (pw == NULL)
561 fatal("Couldn't get password entry for current user (%i): %s",
Damien Millerf9b625c2000-07-09 22:42:32 +1000562 original_uid, strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000563
564 /* Try to ensure that the parent directory is there */
565 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
566 SSH_USER_DIR);
567 mkdir(filename, 0700);
568
569 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
570 SSH_PRNG_SEED_FILE);
571
572 debug("writing PRNG seed to file %.100s", filename);
573
574 RAND_bytes(seed, sizeof(seed));
575
576 /* Don't care if the seed doesn't exist */
577 prng_check_seedfile(filename);
578
579 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1)
580 fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename,
581 strerror(errno));
582
583 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
584 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
585 strerror(errno));
586
587 close(fd);
588}
589
590void
591prng_read_seedfile(void) {
592 int fd;
593 char seed[1024];
594 char filename[1024];
595 struct passwd *pw;
596
Damien Millerf9b625c2000-07-09 22:42:32 +1000597 pw = getpwuid(original_uid);
Damien Miller4018c192000-04-30 09:30:44 +1000598 if (pw == NULL)
599 fatal("Couldn't get password entry for current user (%i): %s",
Damien Millerf9b625c2000-07-09 22:42:32 +1000600 original_uid, strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000601
602 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
603 SSH_PRNG_SEED_FILE);
604
605 debug("loading PRNG seed from file %.100s", filename);
606
607 if (!prng_check_seedfile(filename)) {
608 verbose("Random seed file not found, creating new");
609 prng_write_seedfile();
610
611 /* Reseed immediatly */
612 (void)stir_from_system();
613 (void)stir_from_programs();
614 return;
615 }
616
617 /* open the file and read in the seed */
618 fd = open(filename, O_RDONLY);
619 if (fd == -1)
620 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
621 strerror(errno));
622
623 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
624 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
625 filename);
626 memset(seed, '\0', sizeof(seed));
627 }
628 close(fd);
629
630 /* stir in the seed, with estimated entropy zero */
631 RAND_add(&seed, sizeof(seed), 0.0);
632}
633
Damien Miller0437b332000-05-02 09:56:41 +1000634
635/*
636 * entropy command initialisation functions
637 */
Damien Miller0437b332000-05-02 09:56:41 +1000638int
639prng_read_commands(char *cmdfilename)
640{
641 FILE *f;
Damien Miller0437b332000-05-02 09:56:41 +1000642 char *cp;
Damien Miller14c12cb2000-06-07 22:20:23 +1000643 char line[1024];
644 char cmd[1024];
645 char path[256];
Damien Miller0437b332000-05-02 09:56:41 +1000646 int linenum;
Damien Miller0437b332000-05-02 09:56:41 +1000647 int num_cmds = 64;
648 int cur_cmd = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000649 double est;
650 entropy_source_t *entcmd;
Damien Miller0437b332000-05-02 09:56:41 +1000651
652 f = fopen(cmdfilename, "r");
653 if (!f) {
654 fatal("couldn't read entropy commands file %.100s: %.100s",
655 cmdfilename, strerror(errno));
656 }
657
Damien Miller0437b332000-05-02 09:56:41 +1000658 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
659 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
660
Damien Miller14c12cb2000-06-07 22:20:23 +1000661 /* Read in file */
662 linenum = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000663 while (fgets(line, sizeof(line), f)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000664 int arg;
665 char *argv;
666
Damien Miller0437b332000-05-02 09:56:41 +1000667 linenum++;
668
669 /* skip leading whitespace, test for blank line or comment */
670 cp = line + strspn(line, WHITESPACE);
671 if ((*cp == 0) || (*cp == '#'))
672 continue; /* done with this line */
673
Damien Miller14c12cb2000-06-07 22:20:23 +1000674 /* First non-whitespace char should be double quote delimiting */
675 /* commandline */
676 if (*cp != '"') {
Damien Miller0437b332000-05-02 09:56:41 +1000677 error("bad entropy command, %.100s line %d", cmdfilename,
678 linenum);
679 continue;
Damien Miller14c12cb2000-06-07 22:20:23 +1000680 }
681
682 /* first token, command args (incl. argv[0]) in double quotes */
683 cp = strtok(cp, "\"");
684 if (cp == NULL) {
685 error("missing or bad command string, %.100s line %d -- ignored",
686 cmdfilename, linenum);
687 continue;
688 }
689 strlcpy(cmd, cp, sizeof(cmd));
690
691 /* second token, full command path */
692 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
693 error("missing command path, %.100s line %d -- ignored",
694 cmdfilename, linenum);
695 continue;
696 }
697
698 /* did configure mark this as dead? */
699 if (strncmp("undef", cp, 5) == 0)
700 continue;
701
702 strlcpy(path, cp, sizeof(path));
703
704 /* third token, entropy rate estimate for this command */
705 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
706 error("missing entropy estimate, %.100s line %d -- ignored",
707 cmdfilename, linenum);
708 continue;
709 }
710 est = strtod(cp, &argv);
711
712 /* end of line */
713 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
714 error("garbage at end of line %d in %.100s -- ignored", linenum,
715 cmdfilename);
716 continue;
717 }
718
719 /* save the command for debug messages */
720 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
721
722 /* split the command args */
723 cp = strtok(cmd, WHITESPACE);
724 arg = 0;
725 argv = NULL;
726 do {
727 char *s = (char*)xmalloc(strlen(cp) + 1);
728 strncpy(s, cp, strlen(cp) + 1);
729 entcmd[cur_cmd].args[arg] = s;
730 arg++;
731 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
732
733 if (strtok(NULL, WHITESPACE))
734 error("ignored extra command elements (max 5), %.100s line %d",
735 cmdfilename, linenum);
736
737 /* Copy the command path and rate estimate */
738 entcmd[cur_cmd].path = xstrdup(path);
739 entcmd[cur_cmd].rate = est;
740
741 /* Initialise other values */
742 entcmd[cur_cmd].sticky_badness = 1;
743
744 cur_cmd++;
745
746 /* If we've filled the array, reallocate it twice the size */
747 /* Do this now because even if this we're on the last command,
748 we need another slot to mark the last entry */
749 if (cur_cmd == num_cmds) {
750 num_cmds *= 2;
751 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
Damien Miller0437b332000-05-02 09:56:41 +1000752 }
753 }
754
755 /* zero the last entry */
756 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
Damien Miller14c12cb2000-06-07 22:20:23 +1000757
Damien Miller0437b332000-05-02 09:56:41 +1000758 /* trim to size */
759 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
760
Damien Millerf9b625c2000-07-09 22:42:32 +1000761 debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
Damien Miller0437b332000-05-02 09:56:41 +1000762
763 return (cur_cmd >= MIN_ENTROPY_SOURCES);
764}
765
Damien Miller040f3832000-04-03 14:50:43 +1000766/*
Damien Miller4018c192000-04-30 09:30:44 +1000767 * Write a keyfile at exit
768 */
769void
770prng_seed_cleanup(void *junk)
771{
772 prng_write_seedfile();
773}
774
775/*
776 * Conditionally Seed OpenSSL's random number pool from
777 * syscalls and program output
Damien Miller040f3832000-04-03 14:50:43 +1000778 */
779void
780seed_rng(void)
781{
Damien Millerf3c6cf12000-05-17 22:08:29 +1000782 void *old_sigchld_handler;
Damien Miller0437b332000-05-02 09:56:41 +1000783
Damien Millerf9b625c2000-07-09 22:42:32 +1000784 if (!prng_initialised)
785 fatal("RNG not initialised");
786
Damien Millerf3c6cf12000-05-17 22:08:29 +1000787 /* Make sure some other sigchld handler doesn't reap our entropy */
788 /* commands */
789 old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
790
Damien Millerf9b625c2000-07-09 22:42:32 +1000791 debug("Seeded RNG with %i bytes from programs", (int)stir_from_programs());
792 debug("Seeded RNG with %i bytes from system calls", (int)stir_from_system());
793
794 if (!RAND_status())
795 fatal("Not enough entropy in RNG");
Damien Miller4018c192000-04-30 09:30:44 +1000796
Damien Millerf3c6cf12000-05-17 22:08:29 +1000797 signal(SIGCHLD, old_sigchld_handler);
798
Damien Miller8d1fd572000-05-17 21:34:07 +1000799 if (!RAND_status())
800 fatal("Couldn't initialise builtin random number generator -- exiting.");
Damien Miller040f3832000-04-03 14:50:43 +1000801}
Damien Millerf9b625c2000-07-09 22:42:32 +1000802
803void init_rng(void)
804{
805 original_uid = getuid();
806
807 /* Read in collection commands */
808 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
809 fatal("PRNG initialisation failed -- exiting.");
810
811 /* Set ourselves up to save a seed upon exit */
812 prng_seed_saved = 0;
813 prng_read_seedfile();
814 fatal_add_cleanup(prng_seed_cleanup, NULL);
815 atexit(prng_write_seedfile);
816
817 prng_initialised = 1;
818}
819
Damien Miller040f3832000-04-03 14:50:43 +1000820#endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */