blob: 09dcae3ba5a0a11c13f383fd1e78298ce4e09538 [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 Miller7b22d652000-06-18 14:07:04 +100038RCSID("$Id: entropy.c,v 1.14 2000/06/18 04:07:04 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 */
69void get_random_bytes(unsigned char *buf, int len)
70{
71 static int egd_socket = -1;
72 int c;
73 char egd_message[2] = { 0x02, 0x00 };
74 struct sockaddr_un addr;
75 int addr_len;
76
77 memset(&addr, '\0', sizeof(addr));
78 addr.sun_family = AF_UNIX;
79
80 /* FIXME: compile time check? */
81 if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
82 fatal("Random pool path is too long");
83
Damien Miller14c12cb2000-06-07 22:20:23 +100084 strlcpy(addr.sun_path, EGD_SOCKET, sizeof(addr.sun_path));
Damien Miller040f3832000-04-03 14:50:43 +100085
86 addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
87
88 if (egd_socket == -1) {
89 egd_socket = socket(AF_UNIX, SOCK_STREAM, 0);
90 if (egd_socket == -1)
91 fatal("Couldn't create AF_UNIX socket: %s", strerror(errno));
92 if (connect(egd_socket, (struct sockaddr*)&addr, addr_len) == -1)
93 fatal("Couldn't connect to EGD socket \"%s\": %s", addr.sun_path, strerror(errno));
94 }
95
96 if (len > 255)
97 fatal("Too many bytes to read from EGD");
98
99 /* Send blocking read request to EGD */
100 egd_message[1] = len;
101
102 c = atomicio(write, egd_socket, egd_message, sizeof(egd_message));
103 if (c == -1)
104 fatal("Couldn't write to EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno));
105
106 c = atomicio(read, egd_socket, buf, len);
107 if (c <= 0)
108 fatal("Couldn't read from EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno));
Damien Miller040f3832000-04-03 14:50:43 +1000109}
110#else /* !EGD_SOCKET */
111#ifdef RANDOM_POOL
112/* Collect entropy from /dev/urandom or pipe */
113void get_random_bytes(unsigned char *buf, int len)
114{
115 static int random_pool = -1;
116 int c;
117
118 if (random_pool == -1) {
119 random_pool = open(RANDOM_POOL, O_RDONLY);
120 if (random_pool == -1)
121 fatal("Couldn't open random pool \"%s\": %s", RANDOM_POOL, strerror(errno));
122 }
123
Damien Miller040f3832000-04-03 14:50:43 +1000124 c = atomicio(read, random_pool, buf, len);
125 if (c <= 0)
126 fatal("Couldn't read from random pool \"%s\": %s", RANDOM_POOL, strerror(errno));
127}
128#endif /* RANDOM_POOL */
129#endif /* EGD_SOCKET */
130
Damien Miller14c12cb2000-06-07 22:20:23 +1000131/*
132 * Seed OpenSSL's random number pool from Kernel random number generator
133 * or EGD
134 */
135void
136seed_rng(void)
137{
138 char buf[32];
139
140 debug("Seeding random number generator");
141 get_random_bytes(buf, sizeof(buf));
142 RAND_add(buf, sizeof(buf), sizeof(buf));
143 memset(buf, '\0', sizeof(buf));
144}
145
146#else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
147
Damien Miller040f3832000-04-03 14:50:43 +1000148/*
149 * FIXME: proper entropy estimations. All current values are guesses
Damien Miller4018c192000-04-30 09:30:44 +1000150 * FIXME: (ATL) do estimates at compile time?
Damien Miller040f3832000-04-03 14:50:43 +1000151 * FIXME: More entropy sources
152 */
153
Damien Miller4018c192000-04-30 09:30:44 +1000154/* slow command timeouts (all in milliseconds) */
155/* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
156static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
157
158static int prng_seed_loaded = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000159static int prng_seed_saved = 0;
160static int prng_commands_loaded = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000161
162typedef struct
163{
164 /* Proportion of data that is entropy */
165 double rate;
Damien Miller4018c192000-04-30 09:30:44 +1000166 /* Counter goes positive if this command times out */
167 unsigned int badness;
168 /* Increases by factor of two each timeout */
169 unsigned int sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000170 /* Path to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000171 char *path;
Damien Miller040f3832000-04-03 14:50:43 +1000172 /* argv to pass to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000173 char *args[5];
Damien Miller8d1fd572000-05-17 21:34:07 +1000174 /* full command string (debug) */
175 char *cmdstring;
Damien Miller040f3832000-04-03 14:50:43 +1000176} entropy_source_t;
177
Damien Miller4018c192000-04-30 09:30:44 +1000178double stir_from_system(void);
179double stir_from_programs(void);
180double stir_gettimeofday(double entropy_estimate);
181double stir_clock(double entropy_estimate);
182double stir_rusage(int who, double entropy_estimate);
183double hash_output_from_command(entropy_source_t *src, char *hash);
184
Damien Miller0437b332000-05-02 09:56:41 +1000185/* this is initialised from a file, by prng_read_commands() */
186entropy_source_t *entropy_sources = NULL;
Damien Miller040f3832000-04-03 14:50:43 +1000187
Damien Miller040f3832000-04-03 14:50:43 +1000188double
189stir_from_system(void)
190{
191 double total_entropy_estimate;
192 long int i;
193
194 total_entropy_estimate = 0;
195
196 i = getpid();
Damien Miller7b22d652000-06-18 14:07:04 +1000197 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000198 total_entropy_estimate += 0.1;
199
200 i = getppid();
Damien Miller7b22d652000-06-18 14:07:04 +1000201 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000202 total_entropy_estimate += 0.1;
203
204 i = getuid();
205 RAND_add(&i, sizeof(i), 0.0);
206 i = getgid();
207 RAND_add(&i, sizeof(i), 0.0);
208
209 total_entropy_estimate += stir_gettimeofday(1.0);
Damien Miller7b22d652000-06-18 14:07:04 +1000210 total_entropy_estimate += stir_clock(0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000211 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
212
213 return(total_entropy_estimate);
214}
215
216double
217stir_from_programs(void)
218{
219 int i;
220 int c;
221 double entropy_estimate;
222 double total_entropy_estimate;
223 char hash[SHA_DIGEST_LENGTH];
224
Damien Miller040f3832000-04-03 14:50:43 +1000225 total_entropy_estimate = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000226 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
Damien Miller040f3832000-04-03 14:50:43 +1000227 c = 0;
228 while (entropy_sources[c].path != NULL) {
Damien Miller040f3832000-04-03 14:50:43 +1000229
Damien Miller4018c192000-04-30 09:30:44 +1000230 if (!entropy_sources[c].badness) {
231 /* Hash output from command */
232 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
233
234 /* Scale back entropy estimate according to command's rate */
235 entropy_estimate *= entropy_sources[c].rate;
Damien Miller040f3832000-04-03 14:50:43 +1000236
Damien Miller4018c192000-04-30 09:30:44 +1000237 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
238 if (entropy_estimate > SHA_DIGEST_LENGTH)
239 entropy_estimate = SHA_DIGEST_LENGTH;
Damien Miller040f3832000-04-03 14:50:43 +1000240
Damien Miller14c12cb2000-06-07 22:20:23 +1000241 /* Scale back estimates for subsequent passes through list */
242 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
Damien Miller040f3832000-04-03 14:50:43 +1000243
Damien Miller4018c192000-04-30 09:30:44 +1000244 /* Stir it in */
245 RAND_add(hash, sizeof(hash), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000246
Damien Miller14c12cb2000-06-07 22:20:23 +1000247#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000248 debug("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
249 entropy_sources[c].cmdstring);
Damien Miller040f3832000-04-03 14:50:43 +1000250#endif
251
Damien Miller4018c192000-04-30 09:30:44 +1000252 total_entropy_estimate += entropy_estimate;
Damien Miller040f3832000-04-03 14:50:43 +1000253
254 /* Execution times should be a little unpredictable */
Damien Miller4018c192000-04-30 09:30:44 +1000255 total_entropy_estimate += stir_gettimeofday(0.05);
256 total_entropy_estimate += stir_clock(0.05);
257 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
258 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
259 } else {
Damien Miller14c12cb2000-06-07 22:20:23 +1000260#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000261 debug("Command '%s' disabled (badness %d)",
262 entropy_sources[c].cmdstring, entropy_sources[c].badness);
Damien Miller4018c192000-04-30 09:30:44 +1000263#endif
264
265 if (entropy_sources[c].badness > 0)
266 entropy_sources[c].badness--;
267 }
268
Damien Miller040f3832000-04-03 14:50:43 +1000269 c++;
270 }
271 }
272
273 return(total_entropy_estimate);
274}
275
276double
277stir_gettimeofday(double entropy_estimate)
278{
279 struct timeval tv;
280
281 if (gettimeofday(&tv, NULL) == -1)
282 fatal("Couldn't gettimeofday: %s", strerror(errno));
283
284 RAND_add(&tv, sizeof(tv), entropy_estimate);
285
286 return(entropy_estimate);
287}
288
289double
290stir_clock(double entropy_estimate)
291{
292#ifdef HAVE_CLOCK
293 clock_t c;
294
295 c = clock();
296 RAND_add(&c, sizeof(c), entropy_estimate);
297
298 return(entropy_estimate);
299#else /* _HAVE_CLOCK */
300 return(0);
301#endif /* _HAVE_CLOCK */
302}
303
304double
305stir_rusage(int who, double entropy_estimate)
306{
307#ifdef HAVE_GETRUSAGE
308 struct rusage ru;
309
Damien Miller4018c192000-04-30 09:30:44 +1000310 if (getrusage(who, &ru) == -1)
Damien Miller7b22d652000-06-18 14:07:04 +1000311 return(0);
Damien Miller040f3832000-04-03 14:50:43 +1000312
Damien Miller7b22d652000-06-18 14:07:04 +1000313 RAND_add(&ru, sizeof(ru), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000314
315 return(entropy_estimate);
316#else /* _HAVE_GETRUSAGE */
317 return(0);
318#endif /* _HAVE_GETRUSAGE */
319}
320
Damien Miller8d1fd572000-05-17 21:34:07 +1000321
322static
323int
324_get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
325 int secdiff, usecdiff;
326
327 secdiff = t2->tv_sec - t1->tv_sec;
328 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
329 return (int)(usecdiff / 1000);
330}
331
Damien Miller040f3832000-04-03 14:50:43 +1000332double
Damien Miller4018c192000-04-30 09:30:44 +1000333hash_output_from_command(entropy_source_t *src, char *hash)
Damien Miller040f3832000-04-03 14:50:43 +1000334{
335 static int devnull = -1;
336 int p[2];
Damien Miller4018c192000-04-30 09:30:44 +1000337 fd_set rdset;
338 int cmd_eof = 0, error_abort = 0;
Damien Miller8d1fd572000-05-17 21:34:07 +1000339 struct timeval tv_start, tv_current;
340 int msec_elapsed = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000341 pid_t pid;
342 int status;
Damien Miller8d1fd572000-05-17 21:34:07 +1000343 char buf[16384];
Damien Miller040f3832000-04-03 14:50:43 +1000344 int bytes_read;
345 int total_bytes_read;
346 SHA_CTX sha;
347
348 if (devnull == -1) {
349 devnull = open("/dev/null", O_RDWR);
350 if (devnull == -1)
351 fatal("Couldn't open /dev/null: %s", strerror(errno));
352 }
353
354 if (pipe(p) == -1)
355 fatal("Couldn't open pipe: %s", strerror(errno));
356
Damien Miller8d1fd572000-05-17 21:34:07 +1000357 (void)gettimeofday(&tv_start, NULL); /* record start time */
358
Damien Miller040f3832000-04-03 14:50:43 +1000359 switch (pid = fork()) {
360 case -1: /* Error */
361 close(p[0]);
362 close(p[1]);
363 fatal("Couldn't fork: %s", strerror(errno));
364 /* NOTREACHED */
365 case 0: /* Child */
Damien Miller4018c192000-04-30 09:30:44 +1000366 dup2(devnull, STDIN_FILENO);
367 dup2(p[1], STDOUT_FILENO);
368 dup2(p[1], STDERR_FILENO);
Damien Miller040f3832000-04-03 14:50:43 +1000369 close(p[0]);
370 close(p[1]);
371 close(devnull);
372
Damien Miller4018c192000-04-30 09:30:44 +1000373 execv(src->path, (char**)(src->args));
Damien Miller8d1fd572000-05-17 21:34:07 +1000374 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
375 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000376 src->badness = src->sticky_badness = 128;
Damien Miller040f3832000-04-03 14:50:43 +1000377 _exit(-1);
378 default: /* Parent */
379 break;
380 }
381
382 RAND_add(&pid, sizeof(&pid), 0.0);
383
384 close(p[1]);
385
386 /* Hash output from child */
387 SHA1_Init(&sha);
388 total_bytes_read = 0;
Damien Miller4018c192000-04-30 09:30:44 +1000389
390 while (!error_abort && !cmd_eof) {
391 int ret;
392 struct timeval tv;
Damien Miller8d1fd572000-05-17 21:34:07 +1000393 int msec_remaining;
394
395 (void) gettimeofday(&tv_current, 0);
Damien Miller14c12cb2000-06-07 22:20:23 +1000396 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
Damien Miller8d1fd572000-05-17 21:34:07 +1000397 if (msec_elapsed >= entropy_timeout_current) {
398 error_abort=1;
399 continue;
400 }
401 msec_remaining = entropy_timeout_current - msec_elapsed;
Damien Miller4018c192000-04-30 09:30:44 +1000402
403 FD_ZERO(&rdset);
404 FD_SET(p[0], &rdset);
Damien Miller8d1fd572000-05-17 21:34:07 +1000405 tv.tv_sec = msec_remaining / 1000;
406 tv.tv_usec = (msec_remaining % 1000) * 1000;
Damien Miller4018c192000-04-30 09:30:44 +1000407
408 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
Damien Miller8d1fd572000-05-17 21:34:07 +1000409
Damien Miller4018c192000-04-30 09:30:44 +1000410 switch (ret) {
411 case 0:
412 /* timer expired */
413 error_abort = 1;
414 break;
415
416 case 1:
417 /* command input */
418 bytes_read = read(p[0], buf, sizeof(buf));
419 if (bytes_read == -1) {
420 error_abort = 1;
421 break;
422 }
Damien Miller8d1fd572000-05-17 21:34:07 +1000423 if (bytes_read) {
424 SHA1_Update(&sha, buf, bytes_read);
425 total_bytes_read += bytes_read;
426 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
427 } else
428 cmd_eof = 1;
Damien Miller4018c192000-04-30 09:30:44 +1000429
430 break;
431
432 case -1:
433 default:
Damien Miller8d1fd572000-05-17 21:34:07 +1000434 debug("Command '%s': select() failed: %s", src->cmdstring,
435 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000436 error_abort = 1;
437 break;
438 } /* switch ret */
439
440 RAND_add(&tv, sizeof(&tv), 0.0);
441 } /* while !error_abort && !cmd_eof */
442
Damien Miller040f3832000-04-03 14:50:43 +1000443 SHA1_Final(hash, &sha);
444
445 close(p[0]);
Damien Miller8d1fd572000-05-17 21:34:07 +1000446
Damien Miller14c12cb2000-06-07 22:20:23 +1000447#ifdef DEBUG_ENTROPY
Damien Miller8d1fd572000-05-17 21:34:07 +1000448 debug("Time elapsed: %d msec", msec_elapsed);
Damien Miller14c12cb2000-06-07 22:20:23 +1000449#endif
Damien Miller040f3832000-04-03 14:50:43 +1000450
451 if (waitpid(pid, &status, 0) == -1) {
Damien Miller8d1fd572000-05-17 21:34:07 +1000452 debug("Couldn't wait for child '%s' completion: %s", src->cmdstring,
453 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000454 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000455 }
456
457 RAND_add(&status, sizeof(&status), 0.0);
458
Damien Miller4018c192000-04-30 09:30:44 +1000459 if (error_abort) {
460 /* closing p[0] on timeout causes the entropy command to
461 * SIGPIPE. Take whatever output we got, and mark this command
462 * as slow */
Damien Miller8d1fd572000-05-17 21:34:07 +1000463 debug("Command '%s' timed out", src->cmdstring);
Damien Miller4018c192000-04-30 09:30:44 +1000464 src->sticky_badness *= 2;
465 src->badness = src->sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000466 return(total_bytes_read);
Damien Miller4018c192000-04-30 09:30:44 +1000467 }
468
469 if (WIFEXITED(status)) {
470 if (WEXITSTATUS(status)==0) {
471 return(total_bytes_read);
472 } else {
Damien Miller14c12cb2000-06-07 22:20:23 +1000473 debug("Command '%s' exit status was %d", src->cmdstring,
474 WEXITSTATUS(status));
Damien Miller4018c192000-04-30 09:30:44 +1000475 src->badness = src->sticky_badness = 128;
476 return (0.0);
477 }
478 } else if (WIFSIGNALED(status)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000479 debug("Command '%s' returned on uncaught signal %d !", src->cmdstring,
480 status);
Damien Miller4018c192000-04-30 09:30:44 +1000481 src->badness = src->sticky_badness = 128;
482 return(0.0);
483 } else
484 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000485}
Damien Miller4018c192000-04-30 09:30:44 +1000486
487/*
488 * prng seedfile functions
489 */
490int
491prng_check_seedfile(char *filename) {
492
493 struct stat st;
494
495 /* FIXME raceable: eg replace seed between this stat and subsequent open */
496 /* Not such a problem because we don't trust the seed file anyway */
497 if (lstat(filename, &st) == -1) {
498 /* Fail on hard errors */
499 if (errno != ENOENT)
500 fatal("Couldn't stat random seed file \"%s\": %s", filename,
501 strerror(errno));
502
503 return(0);
504 }
505
506 /* regular file? */
507 if (!S_ISREG(st.st_mode))
508 fatal("PRNG seedfile %.100s is not a regular file", filename);
509
510 /* mode 0600, owned by root or the current user? */
Damien Milleraccfeb32000-05-11 19:10:58 +1000511 if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid()))
Damien Miller4018c192000-04-30 09:30:44 +1000512 fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d",
513 filename, getuid());
514
515 return(1);
516}
517
518void
519prng_write_seedfile(void) {
520 int fd;
521 char seed[1024];
522 char filename[1024];
523 struct passwd *pw;
524
525 /* Don't bother if we have already saved a seed */
526 if (prng_seed_saved)
527 return;
528
Damien Millerfc0b11b2000-05-02 00:03:55 +1000529 prng_seed_saved = 1;
530
Damien Miller4018c192000-04-30 09:30:44 +1000531 pw = getpwuid(getuid());
532 if (pw == NULL)
533 fatal("Couldn't get password entry for current user (%i): %s",
534 getuid(), strerror(errno));
535
536 /* Try to ensure that the parent directory is there */
537 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
538 SSH_USER_DIR);
539 mkdir(filename, 0700);
540
541 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
542 SSH_PRNG_SEED_FILE);
543
544 debug("writing PRNG seed to file %.100s", filename);
545
546 RAND_bytes(seed, sizeof(seed));
547
548 /* Don't care if the seed doesn't exist */
549 prng_check_seedfile(filename);
550
551 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1)
552 fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename,
553 strerror(errno));
554
555 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
556 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
557 strerror(errno));
558
559 close(fd);
560}
561
562void
563prng_read_seedfile(void) {
564 int fd;
565 char seed[1024];
566 char filename[1024];
567 struct passwd *pw;
568
569 pw = getpwuid(getuid());
570 if (pw == NULL)
571 fatal("Couldn't get password entry for current user (%i): %s",
572 getuid(), strerror(errno));
573
574 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
575 SSH_PRNG_SEED_FILE);
576
577 debug("loading PRNG seed from file %.100s", filename);
578
579 if (!prng_check_seedfile(filename)) {
580 verbose("Random seed file not found, creating new");
581 prng_write_seedfile();
582
583 /* Reseed immediatly */
584 (void)stir_from_system();
585 (void)stir_from_programs();
586 return;
587 }
588
589 /* open the file and read in the seed */
590 fd = open(filename, O_RDONLY);
591 if (fd == -1)
592 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
593 strerror(errno));
594
595 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
596 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
597 filename);
598 memset(seed, '\0', sizeof(seed));
599 }
600 close(fd);
601
602 /* stir in the seed, with estimated entropy zero */
603 RAND_add(&seed, sizeof(seed), 0.0);
604}
605
Damien Miller0437b332000-05-02 09:56:41 +1000606
607/*
608 * entropy command initialisation functions
609 */
Damien Miller0437b332000-05-02 09:56:41 +1000610int
611prng_read_commands(char *cmdfilename)
612{
613 FILE *f;
Damien Miller0437b332000-05-02 09:56:41 +1000614 char *cp;
Damien Miller14c12cb2000-06-07 22:20:23 +1000615 char line[1024];
616 char cmd[1024];
617 char path[256];
Damien Miller0437b332000-05-02 09:56:41 +1000618 int linenum;
Damien Miller0437b332000-05-02 09:56:41 +1000619 int num_cmds = 64;
620 int cur_cmd = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000621 double est;
622 entropy_source_t *entcmd;
Damien Miller0437b332000-05-02 09:56:41 +1000623
624 f = fopen(cmdfilename, "r");
625 if (!f) {
626 fatal("couldn't read entropy commands file %.100s: %.100s",
627 cmdfilename, strerror(errno));
628 }
629
Damien Miller0437b332000-05-02 09:56:41 +1000630 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
631 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
632
Damien Miller14c12cb2000-06-07 22:20:23 +1000633 /* Read in file */
634 linenum = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000635 while (fgets(line, sizeof(line), f)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000636 int arg;
637 char *argv;
638
Damien Miller0437b332000-05-02 09:56:41 +1000639 linenum++;
640
641 /* skip leading whitespace, test for blank line or comment */
642 cp = line + strspn(line, WHITESPACE);
643 if ((*cp == 0) || (*cp == '#'))
644 continue; /* done with this line */
645
Damien Miller14c12cb2000-06-07 22:20:23 +1000646 /* First non-whitespace char should be double quote delimiting */
647 /* commandline */
648 if (*cp != '"') {
Damien Miller0437b332000-05-02 09:56:41 +1000649 error("bad entropy command, %.100s line %d", cmdfilename,
650 linenum);
651 continue;
Damien Miller14c12cb2000-06-07 22:20:23 +1000652 }
653
654 /* first token, command args (incl. argv[0]) in double quotes */
655 cp = strtok(cp, "\"");
656 if (cp == NULL) {
657 error("missing or bad command string, %.100s line %d -- ignored",
658 cmdfilename, linenum);
659 continue;
660 }
661 strlcpy(cmd, cp, sizeof(cmd));
662
663 /* second token, full command path */
664 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
665 error("missing command path, %.100s line %d -- ignored",
666 cmdfilename, linenum);
667 continue;
668 }
669
670 /* did configure mark this as dead? */
671 if (strncmp("undef", cp, 5) == 0)
672 continue;
673
674 strlcpy(path, cp, sizeof(path));
675
676 /* third token, entropy rate estimate for this command */
677 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
678 error("missing entropy estimate, %.100s line %d -- ignored",
679 cmdfilename, linenum);
680 continue;
681 }
682 est = strtod(cp, &argv);
683
684 /* end of line */
685 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
686 error("garbage at end of line %d in %.100s -- ignored", linenum,
687 cmdfilename);
688 continue;
689 }
690
691 /* save the command for debug messages */
692 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
693
694 /* split the command args */
695 cp = strtok(cmd, WHITESPACE);
696 arg = 0;
697 argv = NULL;
698 do {
699 char *s = (char*)xmalloc(strlen(cp) + 1);
700 strncpy(s, cp, strlen(cp) + 1);
701 entcmd[cur_cmd].args[arg] = s;
702 arg++;
703 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
704
705 if (strtok(NULL, WHITESPACE))
706 error("ignored extra command elements (max 5), %.100s line %d",
707 cmdfilename, linenum);
708
709 /* Copy the command path and rate estimate */
710 entcmd[cur_cmd].path = xstrdup(path);
711 entcmd[cur_cmd].rate = est;
712
713 /* Initialise other values */
714 entcmd[cur_cmd].sticky_badness = 1;
715
716 cur_cmd++;
717
718 /* If we've filled the array, reallocate it twice the size */
719 /* Do this now because even if this we're on the last command,
720 we need another slot to mark the last entry */
721 if (cur_cmd == num_cmds) {
722 num_cmds *= 2;
723 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
Damien Miller0437b332000-05-02 09:56:41 +1000724 }
725 }
726
727 /* zero the last entry */
728 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
Damien Miller14c12cb2000-06-07 22:20:23 +1000729
Damien Miller0437b332000-05-02 09:56:41 +1000730 /* trim to size */
731 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
732
733 debug("loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
734
735 return (cur_cmd >= MIN_ENTROPY_SOURCES);
736}
737
Damien Miller040f3832000-04-03 14:50:43 +1000738/*
Damien Miller4018c192000-04-30 09:30:44 +1000739 * Write a keyfile at exit
740 */
741void
742prng_seed_cleanup(void *junk)
743{
744 prng_write_seedfile();
745}
746
747/*
748 * Conditionally Seed OpenSSL's random number pool from
749 * syscalls and program output
Damien Miller040f3832000-04-03 14:50:43 +1000750 */
751void
752seed_rng(void)
753{
Damien Millerf3c6cf12000-05-17 22:08:29 +1000754 void *old_sigchld_handler;
755
Damien Miller0437b332000-05-02 09:56:41 +1000756 if (!prng_commands_loaded) {
757 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
758 fatal("PRNG initialisation failed -- exiting.");
759 prng_commands_loaded = 1;
760 }
761
Damien Millerf3c6cf12000-05-17 22:08:29 +1000762 /* Make sure some other sigchld handler doesn't reap our entropy */
763 /* commands */
764 old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
765
Damien Miller74a333b2000-04-04 15:04:09 +1000766 debug("Seeding random number generator.");
767 debug("OpenSSL random status is now %i\n", RAND_status());
768 debug("%i bytes from system calls", (int)stir_from_system());
769 debug("%i bytes from programs", (int)stir_from_programs());
770 debug("OpenSSL random status is now %i\n", RAND_status());
Damien Miller4018c192000-04-30 09:30:44 +1000771
Damien Millerf3c6cf12000-05-17 22:08:29 +1000772 signal(SIGCHLD, old_sigchld_handler);
773
Damien Miller8d1fd572000-05-17 21:34:07 +1000774 if (!RAND_status())
775 fatal("Couldn't initialise builtin random number generator -- exiting.");
776
Damien Miller4018c192000-04-30 09:30:44 +1000777 if (!prng_seed_loaded)
778 {
779 prng_seed_loaded = 1;
780 prng_seed_saved = 0;
781 prng_read_seedfile();
782 fatal_add_cleanup(prng_seed_cleanup, NULL);
783 atexit(prng_write_seedfile);
784 }
Damien Miller040f3832000-04-03 14:50:43 +1000785}
786#endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */