blob: 25e83889ef255d241053531beeeba4772ddc0c4c [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.
Damien Miller040f3832000-04-03 14:50:43 +100012 *
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 Miller5f056372000-04-16 12:31:48 +100027#include <openssl/rand.h>
28#include <openssl/sha.h>
Damien Miller040f3832000-04-03 14:50:43 +100029
Damien Millerecbb26d2000-07-15 14:59:14 +100030/* SunOS 4.4.4 needs this */
31#ifdef HAVE_FLOATINGPOINT_H
32# include <floatingpoint.h>
33#endif /* HAVE_FLOATINGPOINT_H */
34
Ben Lindstrom226cfa02001-01-22 05:34:40 +000035#include "ssh.h"
36#include "xmalloc.h"
37#include "atomicio.h"
38#include "log.h"
39
40RCSID("$Id: entropy.c,v 1.24 2001/01/22 05:34:41 mouring Exp $");
Damien Miller040f3832000-04-03 14:50:43 +100041
Damien Miller040f3832000-04-03 14:50:43 +100042#ifndef offsetof
43# define offsetof(type, member) ((size_t) &((type *)0)->member)
44#endif
Damien Miller14c12cb2000-06-07 22:20:23 +100045
Damien Miller14c12cb2000-06-07 22:20:23 +100046/* Number of times to pass through command list gathering entropy */
47#define NUM_ENTROPY_RUNS 1
48
49/* Scale entropy estimates back by this amount on subsequent runs */
50#define SCALE_PER_RUN 10.0
51
52/* Minimum number of commands to be considered valid */
53#define MIN_ENTROPY_SOURCES 16
54
55#define WHITESPACE " \t\n"
56
Damien Miller7b22d652000-06-18 14:07:04 +100057#ifndef RUSAGE_SELF
58# define RUSAGE_SELF 0
59#endif
60#ifndef RUSAGE_CHILDREN
61# define RUSAGE_CHILDREN 0
62#endif
63
Damien Miller14c12cb2000-06-07 22:20:23 +100064#if defined(EGD_SOCKET) || defined(RANDOM_POOL)
65
66#ifdef EGD_SOCKET
Damien Miller040f3832000-04-03 14:50:43 +100067/* Collect entropy from EGD */
Damien Miller64681252000-06-26 13:01:33 +100068int get_random_bytes(unsigned char *buf, int len)
Damien Miller040f3832000-04-03 14:50:43 +100069{
Damien Miller64681252000-06-26 13:01:33 +100070 int fd;
71 char msg[2];
Damien Miller040f3832000-04-03 14:50:43 +100072 struct sockaddr_un addr;
73 int addr_len;
74
Damien Miller64681252000-06-26 13:01:33 +100075 /* Sanity checks */
Damien Miller040f3832000-04-03 14:50:43 +100076 if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
77 fatal("Random pool path is too long");
Damien Miller040f3832000-04-03 14:50:43 +100078 if (len > 255)
79 fatal("Too many bytes to read from EGD");
Damien Miller64681252000-06-26 13:01:33 +100080
81 memset(&addr, '\0', sizeof(addr));
82 addr.sun_family = AF_UNIX;
83 strlcpy(addr.sun_path, EGD_SOCKET, sizeof(addr.sun_path));
84 addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
Damien Miller040f3832000-04-03 14:50:43 +100085
Damien Miller64681252000-06-26 13:01:33 +100086 fd = socket(AF_UNIX, SOCK_STREAM, 0);
87 if (fd == -1) {
88 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
89 return(0);
90 }
91
92 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
93 error("Couldn't connect to EGD socket \"%s\": %s",
94 addr.sun_path, strerror(errno));
95 close(fd);
96 return(0);
97 }
98
Damien Miller040f3832000-04-03 14:50:43 +100099 /* Send blocking read request to EGD */
Damien Miller64681252000-06-26 13:01:33 +1000100 msg[0] = 0x02;
101 msg[1] = len;
Damien Miller040f3832000-04-03 14:50:43 +1000102
Damien Miller64681252000-06-26 13:01:33 +1000103 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
104 error("Couldn't write to EGD socket \"%s\": %s",
105 EGD_SOCKET, strerror(errno));
106 close(fd);
107 return(0);
108 }
Damien Miller040f3832000-04-03 14:50:43 +1000109
Damien Miller64681252000-06-26 13:01:33 +1000110 if (atomicio(read, fd, buf, len) != len) {
111 error("Couldn't read from EGD socket \"%s\": %s",
112 EGD_SOCKET, strerror(errno));
113 close(fd);
114 return(0);
115 }
116
117 close(fd);
118
119 return(1);
Damien Miller040f3832000-04-03 14:50:43 +1000120}
121#else /* !EGD_SOCKET */
122#ifdef RANDOM_POOL
123/* Collect entropy from /dev/urandom or pipe */
Damien Miller64681252000-06-26 13:01:33 +1000124int get_random_bytes(unsigned char *buf, int len)
Damien Miller040f3832000-04-03 14:50:43 +1000125{
Damien Miller64681252000-06-26 13:01:33 +1000126 int random_pool;
Damien Miller040f3832000-04-03 14:50:43 +1000127
Damien Miller64681252000-06-26 13:01:33 +1000128 random_pool = open(RANDOM_POOL, O_RDONLY);
Damien Miller040f3832000-04-03 14:50:43 +1000129 if (random_pool == -1) {
Damien Miller64681252000-06-26 13:01:33 +1000130 error("Couldn't open random pool \"%s\": %s",
131 RANDOM_POOL, strerror(errno));
132 return(0);
Damien Miller040f3832000-04-03 14:50:43 +1000133 }
134
Damien Miller64681252000-06-26 13:01:33 +1000135 if (atomicio(read, random_pool, buf, len) != len) {
136 error("Couldn't read from random pool \"%s\": %s",
137 RANDOM_POOL, strerror(errno));
138 close(random_pool);
139 return(0);
140 }
141
142 close(random_pool);
143
144 return(1);
Damien Miller040f3832000-04-03 14:50:43 +1000145}
146#endif /* RANDOM_POOL */
147#endif /* EGD_SOCKET */
148
Damien Miller14c12cb2000-06-07 22:20:23 +1000149/*
150 * Seed OpenSSL's random number pool from Kernel random number generator
151 * or EGD
152 */
153void
154seed_rng(void)
155{
156 char buf[32];
157
158 debug("Seeding random number generator");
Damien Miller64681252000-06-26 13:01:33 +1000159
Damien Miller08006472000-06-26 13:55:31 +1000160 if (!get_random_bytes(buf, sizeof(buf))) {
161 if (!RAND_status())
162 fatal("Entropy collection failed and entropy exhausted");
163 } else {
164 RAND_add(buf, sizeof(buf), sizeof(buf));
165 }
166
Damien Miller14c12cb2000-06-07 22:20:23 +1000167 memset(buf, '\0', sizeof(buf));
168}
169
Damien Millerf9b625c2000-07-09 22:42:32 +1000170/* No-op */
171void init_rng(void) {}
172
Damien Miller14c12cb2000-06-07 22:20:23 +1000173#else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
174
Damien Miller040f3832000-04-03 14:50:43 +1000175/*
176 * FIXME: proper entropy estimations. All current values are guesses
Damien Miller4018c192000-04-30 09:30:44 +1000177 * FIXME: (ATL) do estimates at compile time?
Damien Miller040f3832000-04-03 14:50:43 +1000178 * FIXME: More entropy sources
179 */
180
Damien Miller4018c192000-04-30 09:30:44 +1000181/* slow command timeouts (all in milliseconds) */
182/* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
183static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
184
Damien Miller0437b332000-05-02 09:56:41 +1000185static int prng_seed_saved = 0;
Damien Millerf9b625c2000-07-09 22:42:32 +1000186static int prng_initialised = 0;
187uid_t original_uid;
Damien Miller040f3832000-04-03 14:50:43 +1000188
189typedef struct
190{
191 /* Proportion of data that is entropy */
192 double rate;
Damien Miller4018c192000-04-30 09:30:44 +1000193 /* Counter goes positive if this command times out */
194 unsigned int badness;
195 /* Increases by factor of two each timeout */
196 unsigned int sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000197 /* Path to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000198 char *path;
Damien Miller040f3832000-04-03 14:50:43 +1000199 /* argv to pass to executable */
Damien Miller0437b332000-05-02 09:56:41 +1000200 char *args[5];
Damien Miller8d1fd572000-05-17 21:34:07 +1000201 /* full command string (debug) */
202 char *cmdstring;
Damien Miller040f3832000-04-03 14:50:43 +1000203} entropy_source_t;
204
Damien Miller4018c192000-04-30 09:30:44 +1000205double stir_from_system(void);
206double stir_from_programs(void);
207double stir_gettimeofday(double entropy_estimate);
208double stir_clock(double entropy_estimate);
209double stir_rusage(int who, double entropy_estimate);
210double hash_output_from_command(entropy_source_t *src, char *hash);
211
Damien Miller0437b332000-05-02 09:56:41 +1000212/* this is initialised from a file, by prng_read_commands() */
213entropy_source_t *entropy_sources = NULL;
Damien Miller040f3832000-04-03 14:50:43 +1000214
Damien Miller040f3832000-04-03 14:50:43 +1000215double
216stir_from_system(void)
217{
218 double total_entropy_estimate;
219 long int i;
220
221 total_entropy_estimate = 0;
222
223 i = getpid();
Damien Miller7b22d652000-06-18 14:07:04 +1000224 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000225 total_entropy_estimate += 0.1;
226
227 i = getppid();
Damien Miller7b22d652000-06-18 14:07:04 +1000228 RAND_add(&i, sizeof(i), 0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000229 total_entropy_estimate += 0.1;
230
231 i = getuid();
232 RAND_add(&i, sizeof(i), 0.0);
233 i = getgid();
234 RAND_add(&i, sizeof(i), 0.0);
235
236 total_entropy_estimate += stir_gettimeofday(1.0);
Damien Miller7b22d652000-06-18 14:07:04 +1000237 total_entropy_estimate += stir_clock(0.5);
Damien Miller040f3832000-04-03 14:50:43 +1000238 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
239
240 return(total_entropy_estimate);
241}
242
243double
244stir_from_programs(void)
245{
246 int i;
247 int c;
248 double entropy_estimate;
249 double total_entropy_estimate;
250 char hash[SHA_DIGEST_LENGTH];
251
Damien Miller040f3832000-04-03 14:50:43 +1000252 total_entropy_estimate = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000253 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
Damien Miller040f3832000-04-03 14:50:43 +1000254 c = 0;
255 while (entropy_sources[c].path != NULL) {
Damien Miller040f3832000-04-03 14:50:43 +1000256
Damien Miller4018c192000-04-30 09:30:44 +1000257 if (!entropy_sources[c].badness) {
258 /* Hash output from command */
259 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
260
261 /* Scale back entropy estimate according to command's rate */
262 entropy_estimate *= entropy_sources[c].rate;
Damien Miller040f3832000-04-03 14:50:43 +1000263
Damien Miller4018c192000-04-30 09:30:44 +1000264 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
265 if (entropy_estimate > SHA_DIGEST_LENGTH)
266 entropy_estimate = SHA_DIGEST_LENGTH;
Damien Miller040f3832000-04-03 14:50:43 +1000267
Damien Miller14c12cb2000-06-07 22:20:23 +1000268 /* Scale back estimates for subsequent passes through list */
269 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
Damien Miller040f3832000-04-03 14:50:43 +1000270
Damien Miller4018c192000-04-30 09:30:44 +1000271 /* Stir it in */
272 RAND_add(hash, sizeof(hash), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000273
Damien Millercb5e44a2000-09-29 12:12:36 +1100274 debug3("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
Damien Miller8d1fd572000-05-17 21:34:07 +1000275 entropy_sources[c].cmdstring);
Damien Miller040f3832000-04-03 14:50:43 +1000276
Damien Miller4018c192000-04-30 09:30:44 +1000277 total_entropy_estimate += entropy_estimate;
Damien Miller040f3832000-04-03 14:50:43 +1000278
279 /* Execution times should be a little unpredictable */
Damien Miller4018c192000-04-30 09:30:44 +1000280 total_entropy_estimate += stir_gettimeofday(0.05);
281 total_entropy_estimate += stir_clock(0.05);
282 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
283 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
284 } else {
Damien Millercb5e44a2000-09-29 12:12:36 +1100285 debug2("Command '%s' disabled (badness %d)",
Damien Miller8d1fd572000-05-17 21:34:07 +1000286 entropy_sources[c].cmdstring, entropy_sources[c].badness);
Damien Miller4018c192000-04-30 09:30:44 +1000287
288 if (entropy_sources[c].badness > 0)
289 entropy_sources[c].badness--;
290 }
291
Damien Miller040f3832000-04-03 14:50:43 +1000292 c++;
293 }
294 }
295
296 return(total_entropy_estimate);
297}
298
299double
300stir_gettimeofday(double entropy_estimate)
301{
302 struct timeval tv;
303
304 if (gettimeofday(&tv, NULL) == -1)
305 fatal("Couldn't gettimeofday: %s", strerror(errno));
306
307 RAND_add(&tv, sizeof(tv), entropy_estimate);
308
309 return(entropy_estimate);
310}
311
312double
313stir_clock(double entropy_estimate)
314{
315#ifdef HAVE_CLOCK
316 clock_t c;
317
318 c = clock();
319 RAND_add(&c, sizeof(c), entropy_estimate);
320
321 return(entropy_estimate);
322#else /* _HAVE_CLOCK */
323 return(0);
324#endif /* _HAVE_CLOCK */
325}
326
327double
328stir_rusage(int who, double entropy_estimate)
329{
330#ifdef HAVE_GETRUSAGE
331 struct rusage ru;
332
Damien Miller4018c192000-04-30 09:30:44 +1000333 if (getrusage(who, &ru) == -1)
Damien Miller7b22d652000-06-18 14:07:04 +1000334 return(0);
Damien Miller040f3832000-04-03 14:50:43 +1000335
Damien Miller7b22d652000-06-18 14:07:04 +1000336 RAND_add(&ru, sizeof(ru), entropy_estimate);
Damien Miller040f3832000-04-03 14:50:43 +1000337
338 return(entropy_estimate);
339#else /* _HAVE_GETRUSAGE */
340 return(0);
341#endif /* _HAVE_GETRUSAGE */
342}
343
Damien Miller8d1fd572000-05-17 21:34:07 +1000344
345static
346int
347_get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
348 int secdiff, usecdiff;
349
350 secdiff = t2->tv_sec - t1->tv_sec;
351 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
352 return (int)(usecdiff / 1000);
353}
354
Damien Miller040f3832000-04-03 14:50:43 +1000355double
Damien Miller4018c192000-04-30 09:30:44 +1000356hash_output_from_command(entropy_source_t *src, char *hash)
Damien Miller040f3832000-04-03 14:50:43 +1000357{
358 static int devnull = -1;
359 int p[2];
Damien Miller4018c192000-04-30 09:30:44 +1000360 fd_set rdset;
361 int cmd_eof = 0, error_abort = 0;
Damien Miller8d1fd572000-05-17 21:34:07 +1000362 struct timeval tv_start, tv_current;
363 int msec_elapsed = 0;
Damien Miller040f3832000-04-03 14:50:43 +1000364 pid_t pid;
365 int status;
Damien Miller8d1fd572000-05-17 21:34:07 +1000366 char buf[16384];
Damien Miller040f3832000-04-03 14:50:43 +1000367 int bytes_read;
368 int total_bytes_read;
369 SHA_CTX sha;
370
Damien Millercb5e44a2000-09-29 12:12:36 +1100371 debug3("Reading output from \'%s\'", src->cmdstring);
372
Damien Miller040f3832000-04-03 14:50:43 +1000373 if (devnull == -1) {
374 devnull = open("/dev/null", O_RDWR);
375 if (devnull == -1)
376 fatal("Couldn't open /dev/null: %s", strerror(errno));
377 }
378
379 if (pipe(p) == -1)
380 fatal("Couldn't open pipe: %s", strerror(errno));
381
Damien Miller8d1fd572000-05-17 21:34:07 +1000382 (void)gettimeofday(&tv_start, NULL); /* record start time */
383
Damien Miller040f3832000-04-03 14:50:43 +1000384 switch (pid = fork()) {
385 case -1: /* Error */
386 close(p[0]);
387 close(p[1]);
388 fatal("Couldn't fork: %s", strerror(errno));
389 /* NOTREACHED */
390 case 0: /* Child */
Damien Miller4018c192000-04-30 09:30:44 +1000391 dup2(devnull, STDIN_FILENO);
392 dup2(p[1], STDOUT_FILENO);
393 dup2(p[1], STDERR_FILENO);
Damien Miller040f3832000-04-03 14:50:43 +1000394 close(p[0]);
395 close(p[1]);
396 close(devnull);
397
Damien Millerf9b625c2000-07-09 22:42:32 +1000398 setuid(original_uid);
Damien Miller4018c192000-04-30 09:30:44 +1000399 execv(src->path, (char**)(src->args));
Damien Miller8d1fd572000-05-17 21:34:07 +1000400 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
401 strerror(errno));
Damien Miller040f3832000-04-03 14:50:43 +1000402 _exit(-1);
403 default: /* Parent */
404 break;
405 }
406
407 RAND_add(&pid, sizeof(&pid), 0.0);
408
409 close(p[1]);
410
411 /* Hash output from child */
412 SHA1_Init(&sha);
413 total_bytes_read = 0;
Damien Miller4018c192000-04-30 09:30:44 +1000414
415 while (!error_abort && !cmd_eof) {
416 int ret;
417 struct timeval tv;
Damien Miller8d1fd572000-05-17 21:34:07 +1000418 int msec_remaining;
419
420 (void) gettimeofday(&tv_current, 0);
Damien Miller14c12cb2000-06-07 22:20:23 +1000421 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
Damien Miller8d1fd572000-05-17 21:34:07 +1000422 if (msec_elapsed >= entropy_timeout_current) {
423 error_abort=1;
424 continue;
425 }
426 msec_remaining = entropy_timeout_current - msec_elapsed;
Damien Miller4018c192000-04-30 09:30:44 +1000427
428 FD_ZERO(&rdset);
429 FD_SET(p[0], &rdset);
Damien Miller8d1fd572000-05-17 21:34:07 +1000430 tv.tv_sec = msec_remaining / 1000;
431 tv.tv_usec = (msec_remaining % 1000) * 1000;
Damien Miller4018c192000-04-30 09:30:44 +1000432
433 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
Damien Miller8d1fd572000-05-17 21:34:07 +1000434
Damien Millerf9b625c2000-07-09 22:42:32 +1000435 RAND_add(&tv, sizeof(tv), 0.0);
436
Damien Miller4018c192000-04-30 09:30:44 +1000437 switch (ret) {
438 case 0:
439 /* timer expired */
440 error_abort = 1;
441 break;
Damien Miller4018c192000-04-30 09:30:44 +1000442 case 1:
443 /* command input */
444 bytes_read = read(p[0], buf, sizeof(buf));
Damien Millerf9b625c2000-07-09 22:42:32 +1000445 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
Damien Miller4018c192000-04-30 09:30:44 +1000446 if (bytes_read == -1) {
447 error_abort = 1;
448 break;
Damien Millerf9b625c2000-07-09 22:42:32 +1000449 } else if (bytes_read) {
Damien Miller8d1fd572000-05-17 21:34:07 +1000450 SHA1_Update(&sha, buf, bytes_read);
451 total_bytes_read += bytes_read;
Damien Millerf9b625c2000-07-09 22:42:32 +1000452 } else {
Damien Miller8d1fd572000-05-17 21:34:07 +1000453 cmd_eof = 1;
Damien Millerf9b625c2000-07-09 22:42:32 +1000454 }
Damien Miller4018c192000-04-30 09:30:44 +1000455 break;
Damien Miller4018c192000-04-30 09:30:44 +1000456 case -1:
457 default:
Damien Millerf9b625c2000-07-09 22:42:32 +1000458 /* error */
Damien Miller8d1fd572000-05-17 21:34:07 +1000459 debug("Command '%s': select() failed: %s", src->cmdstring,
460 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000461 error_abort = 1;
462 break;
Damien Millerf9b625c2000-07-09 22:42:32 +1000463 }
464 }
Damien Miller4018c192000-04-30 09:30:44 +1000465
Damien Miller040f3832000-04-03 14:50:43 +1000466 SHA1_Final(hash, &sha);
467
468 close(p[0]);
Damien Miller8d1fd572000-05-17 21:34:07 +1000469
Damien Millercb5e44a2000-09-29 12:12:36 +1100470 debug3("Time elapsed: %d msec", msec_elapsed);
Damien Miller040f3832000-04-03 14:50:43 +1000471
472 if (waitpid(pid, &status, 0) == -1) {
Damien Millercb5e44a2000-09-29 12:12:36 +1100473 error("Couldn't wait for child '%s' completion: %s", src->cmdstring,
Damien Miller8d1fd572000-05-17 21:34:07 +1000474 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000475 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000476 }
477
478 RAND_add(&status, sizeof(&status), 0.0);
479
Damien Miller4018c192000-04-30 09:30:44 +1000480 if (error_abort) {
481 /* closing p[0] on timeout causes the entropy command to
482 * SIGPIPE. Take whatever output we got, and mark this command
483 * as slow */
Damien Millercb5e44a2000-09-29 12:12:36 +1100484 debug2("Command '%s' timed out", src->cmdstring);
Damien Miller4018c192000-04-30 09:30:44 +1000485 src->sticky_badness *= 2;
486 src->badness = src->sticky_badness;
Damien Miller040f3832000-04-03 14:50:43 +1000487 return(total_bytes_read);
Damien Miller4018c192000-04-30 09:30:44 +1000488 }
489
490 if (WIFEXITED(status)) {
491 if (WEXITSTATUS(status)==0) {
492 return(total_bytes_read);
493 } else {
Damien Millercb5e44a2000-09-29 12:12:36 +1100494 debug2("Command '%s' exit status was %d", src->cmdstring,
Damien Miller14c12cb2000-06-07 22:20:23 +1000495 WEXITSTATUS(status));
Damien Miller4018c192000-04-30 09:30:44 +1000496 src->badness = src->sticky_badness = 128;
497 return (0.0);
498 }
499 } else if (WIFSIGNALED(status)) {
Damien Millercb5e44a2000-09-29 12:12:36 +1100500 debug2("Command '%s' returned on uncaught signal %d !", src->cmdstring,
Damien Miller14c12cb2000-06-07 22:20:23 +1000501 status);
Damien Miller4018c192000-04-30 09:30:44 +1000502 src->badness = src->sticky_badness = 128;
503 return(0.0);
504 } else
505 return(0.0);
Damien Miller040f3832000-04-03 14:50:43 +1000506}
Damien Miller4018c192000-04-30 09:30:44 +1000507
508/*
509 * prng seedfile functions
510 */
511int
512prng_check_seedfile(char *filename) {
513
514 struct stat st;
515
516 /* FIXME raceable: eg replace seed between this stat and subsequent open */
517 /* Not such a problem because we don't trust the seed file anyway */
518 if (lstat(filename, &st) == -1) {
Damien Miller52dc96b2000-10-16 20:13:43 +1100519 /* Give up on hard errors */
Damien Miller4018c192000-04-30 09:30:44 +1000520 if (errno != ENOENT)
Damien Miller52dc96b2000-10-16 20:13:43 +1100521 debug("WARNING: Couldn't stat random seed file \"%s\": %s",
522 filename, strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000523
524 return(0);
525 }
526
527 /* regular file? */
528 if (!S_ISREG(st.st_mode))
529 fatal("PRNG seedfile %.100s is not a regular file", filename);
530
531 /* mode 0600, owned by root or the current user? */
Damien Miller52dc96b2000-10-16 20:13:43 +1100532 if (((st.st_mode & 0177) != 0) || !(st.st_uid == original_uid)) {
533 debug("WARNING: PRNG seedfile %.100s must be mode 0600, owned by uid %d",
Damien Miller4018c192000-04-30 09:30:44 +1000534 filename, getuid());
Damien Miller52dc96b2000-10-16 20:13:43 +1100535 return(0);
536 }
537
Damien Miller4018c192000-04-30 09:30:44 +1000538 return(1);
539}
540
541void
542prng_write_seedfile(void) {
543 int fd;
544 char seed[1024];
545 char filename[1024];
546 struct passwd *pw;
547
548 /* Don't bother if we have already saved a seed */
549 if (prng_seed_saved)
550 return;
551
Damien Millerf9b625c2000-07-09 22:42:32 +1000552 setuid(original_uid);
553
Damien Millerfc0b11b2000-05-02 00:03:55 +1000554 prng_seed_saved = 1;
555
Damien Millerf9b625c2000-07-09 22:42:32 +1000556 pw = getpwuid(original_uid);
Damien Miller4018c192000-04-30 09:30:44 +1000557 if (pw == NULL)
558 fatal("Couldn't get password entry for current user (%i): %s",
Damien Millerf9b625c2000-07-09 22:42:32 +1000559 original_uid, strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000560
561 /* Try to ensure that the parent directory is there */
562 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
563 SSH_USER_DIR);
564 mkdir(filename, 0700);
565
566 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
567 SSH_PRNG_SEED_FILE);
568
569 debug("writing PRNG seed to file %.100s", filename);
570
571 RAND_bytes(seed, sizeof(seed));
572
573 /* Don't care if the seed doesn't exist */
574 prng_check_seedfile(filename);
575
Damien Miller52dc96b2000-10-16 20:13:43 +1100576 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) {
577 debug("WARNING: couldn't access PRNG seedfile %.100s (%.100s)",
578 filename, strerror(errno));
579 } else {
580 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
581 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
582 strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000583
Damien Miller52dc96b2000-10-16 20:13:43 +1100584 close(fd);
585 }
Damien Miller4018c192000-04-30 09:30:44 +1000586}
587
588void
589prng_read_seedfile(void) {
590 int fd;
591 char seed[1024];
592 char filename[1024];
593 struct passwd *pw;
594
Damien Millerf9b625c2000-07-09 22:42:32 +1000595 pw = getpwuid(original_uid);
Damien Miller4018c192000-04-30 09:30:44 +1000596 if (pw == NULL)
597 fatal("Couldn't get password entry for current user (%i): %s",
Damien Millerf9b625c2000-07-09 22:42:32 +1000598 original_uid, strerror(errno));
Damien Miller4018c192000-04-30 09:30:44 +1000599
600 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
601 SSH_PRNG_SEED_FILE);
602
603 debug("loading PRNG seed from file %.100s", filename);
604
605 if (!prng_check_seedfile(filename)) {
Damien Miller21de4502001-01-17 09:37:15 +1100606 verbose("Random seed file not found or not valid, ignoring.");
Damien Miller4018c192000-04-30 09:30:44 +1000607 return;
608 }
609
610 /* open the file and read in the seed */
611 fd = open(filename, O_RDONLY);
612 if (fd == -1)
613 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
614 strerror(errno));
615
616 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
617 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
618 filename);
619 memset(seed, '\0', sizeof(seed));
620 }
621 close(fd);
622
623 /* stir in the seed, with estimated entropy zero */
624 RAND_add(&seed, sizeof(seed), 0.0);
625}
626
Damien Miller0437b332000-05-02 09:56:41 +1000627
628/*
629 * entropy command initialisation functions
630 */
Damien Miller0437b332000-05-02 09:56:41 +1000631int
632prng_read_commands(char *cmdfilename)
633{
634 FILE *f;
Damien Miller0437b332000-05-02 09:56:41 +1000635 char *cp;
Damien Miller14c12cb2000-06-07 22:20:23 +1000636 char line[1024];
637 char cmd[1024];
638 char path[256];
Damien Miller0437b332000-05-02 09:56:41 +1000639 int linenum;
Damien Miller0437b332000-05-02 09:56:41 +1000640 int num_cmds = 64;
641 int cur_cmd = 0;
Damien Miller14c12cb2000-06-07 22:20:23 +1000642 double est;
643 entropy_source_t *entcmd;
Damien Miller0437b332000-05-02 09:56:41 +1000644
645 f = fopen(cmdfilename, "r");
646 if (!f) {
647 fatal("couldn't read entropy commands file %.100s: %.100s",
648 cmdfilename, strerror(errno));
649 }
650
Damien Miller0437b332000-05-02 09:56:41 +1000651 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
652 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
653
Damien Miller14c12cb2000-06-07 22:20:23 +1000654 /* Read in file */
655 linenum = 0;
Damien Miller0437b332000-05-02 09:56:41 +1000656 while (fgets(line, sizeof(line), f)) {
Damien Miller14c12cb2000-06-07 22:20:23 +1000657 int arg;
658 char *argv;
659
Damien Miller0437b332000-05-02 09:56:41 +1000660 linenum++;
661
662 /* skip leading whitespace, test for blank line or comment */
663 cp = line + strspn(line, WHITESPACE);
664 if ((*cp == 0) || (*cp == '#'))
665 continue; /* done with this line */
666
Damien Miller14c12cb2000-06-07 22:20:23 +1000667 /* First non-whitespace char should be double quote delimiting */
668 /* commandline */
669 if (*cp != '"') {
Damien Miller0437b332000-05-02 09:56:41 +1000670 error("bad entropy command, %.100s line %d", cmdfilename,
671 linenum);
672 continue;
Damien Miller14c12cb2000-06-07 22:20:23 +1000673 }
674
675 /* first token, command args (incl. argv[0]) in double quotes */
676 cp = strtok(cp, "\"");
677 if (cp == NULL) {
678 error("missing or bad command string, %.100s line %d -- ignored",
679 cmdfilename, linenum);
680 continue;
681 }
682 strlcpy(cmd, cp, sizeof(cmd));
683
684 /* second token, full command path */
685 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
686 error("missing command path, %.100s line %d -- ignored",
687 cmdfilename, linenum);
688 continue;
689 }
690
691 /* did configure mark this as dead? */
692 if (strncmp("undef", cp, 5) == 0)
693 continue;
694
695 strlcpy(path, cp, sizeof(path));
696
697 /* third token, entropy rate estimate for this command */
698 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
699 error("missing entropy estimate, %.100s line %d -- ignored",
700 cmdfilename, linenum);
701 continue;
702 }
703 est = strtod(cp, &argv);
704
705 /* end of line */
706 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
707 error("garbage at end of line %d in %.100s -- ignored", linenum,
708 cmdfilename);
709 continue;
710 }
711
712 /* save the command for debug messages */
713 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
714
715 /* split the command args */
716 cp = strtok(cmd, WHITESPACE);
717 arg = 0;
718 argv = NULL;
719 do {
720 char *s = (char*)xmalloc(strlen(cp) + 1);
721 strncpy(s, cp, strlen(cp) + 1);
722 entcmd[cur_cmd].args[arg] = s;
723 arg++;
724 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
725
726 if (strtok(NULL, WHITESPACE))
727 error("ignored extra command elements (max 5), %.100s line %d",
728 cmdfilename, linenum);
729
730 /* Copy the command path and rate estimate */
731 entcmd[cur_cmd].path = xstrdup(path);
732 entcmd[cur_cmd].rate = est;
733
734 /* Initialise other values */
735 entcmd[cur_cmd].sticky_badness = 1;
736
737 cur_cmd++;
738
739 /* If we've filled the array, reallocate it twice the size */
740 /* Do this now because even if this we're on the last command,
741 we need another slot to mark the last entry */
742 if (cur_cmd == num_cmds) {
743 num_cmds *= 2;
744 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
Damien Miller0437b332000-05-02 09:56:41 +1000745 }
746 }
747
748 /* zero the last entry */
749 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
Damien Miller14c12cb2000-06-07 22:20:23 +1000750
Damien Miller0437b332000-05-02 09:56:41 +1000751 /* trim to size */
752 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
753
Damien Millerf9b625c2000-07-09 22:42:32 +1000754 debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
Damien Miller0437b332000-05-02 09:56:41 +1000755
756 return (cur_cmd >= MIN_ENTROPY_SOURCES);
757}
758
Damien Miller040f3832000-04-03 14:50:43 +1000759/*
Damien Miller4018c192000-04-30 09:30:44 +1000760 * Write a keyfile at exit
761 */
762void
763prng_seed_cleanup(void *junk)
764{
765 prng_write_seedfile();
766}
767
768/*
769 * Conditionally Seed OpenSSL's random number pool from
770 * syscalls and program output
Damien Miller040f3832000-04-03 14:50:43 +1000771 */
772void
773seed_rng(void)
774{
Damien Millerf3c6cf12000-05-17 22:08:29 +1000775 void *old_sigchld_handler;
Damien Miller0437b332000-05-02 09:56:41 +1000776
Damien Millerf9b625c2000-07-09 22:42:32 +1000777 if (!prng_initialised)
778 fatal("RNG not initialised");
779
Damien Millerf3c6cf12000-05-17 22:08:29 +1000780 /* Make sure some other sigchld handler doesn't reap our entropy */
781 /* commands */
782 old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
783
Damien Millerf9b625c2000-07-09 22:42:32 +1000784 debug("Seeded RNG with %i bytes from programs", (int)stir_from_programs());
785 debug("Seeded RNG with %i bytes from system calls", (int)stir_from_system());
786
787 if (!RAND_status())
788 fatal("Not enough entropy in RNG");
Damien Miller4018c192000-04-30 09:30:44 +1000789
Damien Millerf3c6cf12000-05-17 22:08:29 +1000790 signal(SIGCHLD, old_sigchld_handler);
791
Damien Miller8d1fd572000-05-17 21:34:07 +1000792 if (!RAND_status())
793 fatal("Couldn't initialise builtin random number generator -- exiting.");
Damien Miller040f3832000-04-03 14:50:43 +1000794}
Damien Millerf9b625c2000-07-09 22:42:32 +1000795
796void init_rng(void)
797{
Damien Millerd592b632000-11-25 10:09:32 +1100798 int original_euid;
799
Damien Millerf9b625c2000-07-09 22:42:32 +1000800 original_uid = getuid();
Damien Millerd592b632000-11-25 10:09:32 +1100801 original_euid = geteuid();
Damien Millerf9b625c2000-07-09 22:42:32 +1000802
803 /* Read in collection commands */
804 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
805 fatal("PRNG initialisation failed -- exiting.");
806
807 /* Set ourselves up to save a seed upon exit */
808 prng_seed_saved = 0;
Damien Millerd592b632000-11-25 10:09:32 +1100809
810 /* Give up privs while reading seed file */
811 if ((original_uid != original_euid) && (seteuid(original_uid) == -1))
812 fatal("Couldn't give up privileges");
813
Damien Millerf9b625c2000-07-09 22:42:32 +1000814 prng_read_seedfile();
Damien Millerd592b632000-11-25 10:09:32 +1100815
816 if ((original_uid != original_euid) && (seteuid(original_euid) == -1))
817 fatal("Couldn't restore privileges");
818
Damien Millerf9b625c2000-07-09 22:42:32 +1000819 fatal_add_cleanup(prng_seed_cleanup, NULL);
820 atexit(prng_write_seedfile);
821
822 prng_initialised = 1;
823}
824
Damien Miller040f3832000-04-03 14:50:43 +1000825#endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */