]> andersk Git - openssh.git/blame - entropy.c
- markus@cvs.openbsd.org 2001/08/30 22:22:32
[openssh.git] / entropy.c
CommitLineData
bfc9a610 1/*
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.
bfc9a610 12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 */
24
25#include "includes.h"
26
35484284 27#include <openssl/rand.h>
28#include <openssl/sha.h>
c7c72446 29#include <openssl/crypto.h>
bfc9a610 30
819b676f 31/* SunOS 4.4.4 needs this */
32#ifdef HAVE_FLOATINGPOINT_H
33# include <floatingpoint.h>
34#endif /* HAVE_FLOATINGPOINT_H */
35
42f11eb2 36#include "ssh.h"
e1a023df 37#include "misc.h"
42f11eb2 38#include "xmalloc.h"
39#include "atomicio.h"
effa6591 40#include "pathnames.h"
42f11eb2 41#include "log.h"
42
bfc9a610 43RCSID("$Id$");
44
bfc9a610 45#ifndef offsetof
46# define offsetof(type, member) ((size_t) &((type *)0)->member)
47#endif
48c99b2c 48
48c99b2c 49/* Number of times to pass through command list gathering entropy */
50#define NUM_ENTROPY_RUNS 1
51
52/* Scale entropy estimates back by this amount on subsequent runs */
53#define SCALE_PER_RUN 10.0
54
55/* Minimum number of commands to be considered valid */
56#define MIN_ENTROPY_SOURCES 16
57
58#define WHITESPACE " \t\n"
59
cbd7492e 60#ifndef RUSAGE_SELF
61# define RUSAGE_SELF 0
62#endif
63#ifndef RUSAGE_CHILDREN
64# define RUSAGE_CHILDREN 0
65#endif
66
86b416a7 67#if defined(_POSIX_SAVED_IDS) && !defined(BROKEN_SAVED_UIDS)
68# define SAVED_IDS_WORK_WITH_SETEUID
69#endif
70
d60382e0 71static void
e339aa53 72check_openssl_version(void)
c7c72446 73{
74 if (SSLeay() != OPENSSL_VERSION_NUMBER)
32e0cb42 75 fatal("OpenSSL version mismatch. Built against %lx, you "
76 "have %lx", OPENSSL_VERSION_NUMBER, SSLeay());
c7c72446 77}
78
9bdd5929 79#if defined(PRNGD_SOCKET) || defined(PRNGD_PORT)
80# define USE_PRNGD
81#endif
c7c72446 82
9bdd5929 83#if defined(USE_PRNGD) || defined(RANDOM_POOL)
48c99b2c 84
9bdd5929 85#ifdef USE_PRNGD
86/* Collect entropy from PRNGD/EGD */
e339aa53 87int
88get_random_bytes(unsigned char *buf, int len)
bfc9a610 89{
be0b9bb7 90 int fd;
91 char msg[2];
9bdd5929 92#ifdef PRNGD_PORT
93 struct sockaddr_in addr;
94#else
bfc9a610 95 struct sockaddr_un addr;
9bdd5929 96#endif
6a951840 97 int addr_len, rval, errors;
e1a023df 98 mysig_t old_sigpipe;
bfc9a610 99
9bdd5929 100 memset(&addr, '\0', sizeof(addr));
101
102#ifdef PRNGD_PORT
103 addr.sin_family = AF_INET;
104 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
105 addr.sin_port = htons(PRNGD_PORT);
106 addr_len = sizeof(struct sockaddr_in);
107#else /* use IP socket PRNGD_SOCKET instead */
be0b9bb7 108 /* Sanity checks */
9bdd5929 109 if (sizeof(PRNGD_SOCKET) > sizeof(addr.sun_path))
bfc9a610 110 fatal("Random pool path is too long");
be0b9bb7 111 if (len > 255)
9bdd5929 112 fatal("Too many bytes to read from PRNGD");
be0b9bb7 113
be0b9bb7 114 addr.sun_family = AF_UNIX;
9bdd5929 115 strlcpy(addr.sun_path, PRNGD_SOCKET, sizeof(addr.sun_path));
116 addr_len = offsetof(struct sockaddr_un, sun_path) +
117 sizeof(PRNGD_SOCKET);
118#endif
2b87da3b 119
e1a023df 120 old_sigpipe = mysignal(SIGPIPE, SIG_IGN);
6a951840 121
122 errors = rval = 0;
123reopen:
9bdd5929 124#ifdef PRNGD_PORT
125 fd = socket(addr.sin_family, SOCK_STREAM, 0);
126 if (fd == -1) {
127 error("Couldn't create AF_INET socket: %s", strerror(errno));
128 goto done;
129 }
130#else
131 fd = socket(addr.sun_family, SOCK_STREAM, 0);
be0b9bb7 132 if (fd == -1) {
133 error("Couldn't create AF_UNIX socket: %s", strerror(errno));
6a951840 134 goto done;
be0b9bb7 135 }
9bdd5929 136#endif
bfc9a610 137
be0b9bb7 138 if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
9bdd5929 139#ifdef PRNGD_PORT
140 error("Couldn't connect to PRNGD port %d: %s",
141 PRNGD_PORT, strerror(errno));
142#else
143 error("Couldn't connect to PRNGD socket \"%s\": %s",
144 addr.sun_path, strerror(errno));
145#endif
6a951840 146 goto done;
be0b9bb7 147 }
bfc9a610 148
9bdd5929 149 /* Send blocking read request to PRNGD */
be0b9bb7 150 msg[0] = 0x02;
151 msg[1] = len;
152
153 if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
6a951840 154 if (errno == EPIPE && errors < 10) {
155 close(fd);
156 errors++;
157 goto reopen;
158 }
9bdd5929 159 error("Couldn't write to PRNGD socket: %s",
160 strerror(errno));
6a951840 161 goto done;
be0b9bb7 162 }
bfc9a610 163
be0b9bb7 164 if (atomicio(read, fd, buf, len) != len) {
6a951840 165 if (errno == EPIPE && errors < 10) {
166 close(fd);
167 errors++;
168 goto reopen;
169 }
9bdd5929 170 error("Couldn't read from PRNGD socket: %s",
171 strerror(errno));
6a951840 172 goto done;
be0b9bb7 173 }
2b87da3b 174
6a951840 175 rval = 1;
176done:
2adddc78 177 mysignal(SIGPIPE, old_sigpipe);
6a951840 178 if (fd != -1)
179 close(fd);
180 return(rval);
bfc9a610 181}
9bdd5929 182#else /* !USE_PRNGD */
bfc9a610 183#ifdef RANDOM_POOL
184/* Collect entropy from /dev/urandom or pipe */
d60382e0 185static int
e339aa53 186get_random_bytes(unsigned char *buf, int len)
bfc9a610 187{
be0b9bb7 188 int random_pool;
bfc9a610 189
be0b9bb7 190 random_pool = open(RANDOM_POOL, O_RDONLY);
bfc9a610 191 if (random_pool == -1) {
2b87da3b 192 error("Couldn't open random pool \"%s\": %s",
be0b9bb7 193 RANDOM_POOL, strerror(errno));
194 return(0);
bfc9a610 195 }
2b87da3b 196
be0b9bb7 197 if (atomicio(read, random_pool, buf, len) != len) {
2b87da3b 198 error("Couldn't read from random pool \"%s\": %s",
be0b9bb7 199 RANDOM_POOL, strerror(errno));
200 close(random_pool);
201 return(0);
202 }
2b87da3b 203
be0b9bb7 204 close(random_pool);
2b87da3b 205
be0b9bb7 206 return(1);
bfc9a610 207}
208#endif /* RANDOM_POOL */
9bdd5929 209#endif /* USE_PRNGD */
bfc9a610 210
48c99b2c 211/*
212 * Seed OpenSSL's random number pool from Kernel random number generator
9bdd5929 213 * or PRNGD/EGD
48c99b2c 214 */
215void
216seed_rng(void)
217{
9bdd5929 218 unsigned char buf[32];
2b87da3b 219
48c99b2c 220 debug("Seeding random number generator");
be0b9bb7 221
b5b3f75d 222 if (!get_random_bytes(buf, sizeof(buf))) {
223 if (!RAND_status())
224 fatal("Entropy collection failed and entropy exhausted");
225 } else {
226 RAND_add(buf, sizeof(buf), sizeof(buf));
227 }
2b87da3b 228
48c99b2c 229 memset(buf, '\0', sizeof(buf));
230}
231
e339aa53 232void
233init_rng(void)
c7c72446 234{
235 check_openssl_version();
236}
264dce47 237
9bdd5929 238#else /* defined(USE_PRNGD) || defined(RANDOM_POOL) */
48c99b2c 239
2b87da3b 240/*
bfc9a610 241 * FIXME: proper entropy estimations. All current values are guesses
b7a87eea 242 * FIXME: (ATL) do estimates at compile time?
bfc9a610 243 * FIXME: More entropy sources
244 */
245
b7a87eea 246/* slow command timeouts (all in milliseconds) */
247/* static int entropy_timeout_default = ENTROPY_TIMEOUT_MSEC; */
248static int entropy_timeout_current = ENTROPY_TIMEOUT_MSEC;
249
d3083fbd 250static int prng_seed_saved = 0;
264dce47 251static int prng_initialised = 0;
252uid_t original_uid;
bfc9a610 253
254typedef struct
255{
256 /* Proportion of data that is entropy */
257 double rate;
b7a87eea 258 /* Counter goes positive if this command times out */
259 unsigned int badness;
260 /* Increases by factor of two each timeout */
261 unsigned int sticky_badness;
bfc9a610 262 /* Path to executable */
d3083fbd 263 char *path;
bfc9a610 264 /* argv to pass to executable */
d3083fbd 265 char *args[5];
ad85db64 266 /* full command string (debug) */
267 char *cmdstring;
bfc9a610 268} entropy_source_t;
269
b7a87eea 270double stir_from_system(void);
271double stir_from_programs(void);
272double stir_gettimeofday(double entropy_estimate);
273double stir_clock(double entropy_estimate);
274double stir_rusage(int who, double entropy_estimate);
275double hash_output_from_command(entropy_source_t *src, char *hash);
276
d3083fbd 277/* this is initialised from a file, by prng_read_commands() */
278entropy_source_t *entropy_sources = NULL;
bfc9a610 279
2b87da3b 280double
bfc9a610 281stir_from_system(void)
282{
283 double total_entropy_estimate;
284 long int i;
2b87da3b 285
bfc9a610 286 total_entropy_estimate = 0;
2b87da3b 287
bfc9a610 288 i = getpid();
cbd7492e 289 RAND_add(&i, sizeof(i), 0.5);
bfc9a610 290 total_entropy_estimate += 0.1;
2b87da3b 291
bfc9a610 292 i = getppid();
cbd7492e 293 RAND_add(&i, sizeof(i), 0.5);
bfc9a610 294 total_entropy_estimate += 0.1;
295
296 i = getuid();
297 RAND_add(&i, sizeof(i), 0.0);
298 i = getgid();
299 RAND_add(&i, sizeof(i), 0.0);
300
301 total_entropy_estimate += stir_gettimeofday(1.0);
cbd7492e 302 total_entropy_estimate += stir_clock(0.5);
bfc9a610 303 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
304
305 return(total_entropy_estimate);
306}
307
2b87da3b 308double
bfc9a610 309stir_from_programs(void)
310{
311 int i;
312 int c;
313 double entropy_estimate;
314 double total_entropy_estimate;
315 char hash[SHA_DIGEST_LENGTH];
316
bfc9a610 317 total_entropy_estimate = 0;
48c99b2c 318 for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
bfc9a610 319 c = 0;
320 while (entropy_sources[c].path != NULL) {
bfc9a610 321
b7a87eea 322 if (!entropy_sources[c].badness) {
323 /* Hash output from command */
324 entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
325
326 /* Scale back entropy estimate according to command's rate */
327 entropy_estimate *= entropy_sources[c].rate;
2b87da3b 328
b7a87eea 329 /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
330 if (entropy_estimate > SHA_DIGEST_LENGTH)
331 entropy_estimate = SHA_DIGEST_LENGTH;
bfc9a610 332
2b87da3b 333 /* Scale back estimates for subsequent passes through list */
48c99b2c 334 entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
2b87da3b 335
b7a87eea 336 /* Stir it in */
337 RAND_add(hash, sizeof(hash), entropy_estimate);
bfc9a610 338
2b87da3b 339 debug3("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
ad85db64 340 entropy_sources[c].cmdstring);
bfc9a610 341
b7a87eea 342 total_entropy_estimate += entropy_estimate;
bfc9a610 343
344 /* Execution times should be a little unpredictable */
b7a87eea 345 total_entropy_estimate += stir_gettimeofday(0.05);
346 total_entropy_estimate += stir_clock(0.05);
347 total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
348 total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
349 } else {
22d89d24 350 debug2("Command '%s' disabled (badness %d)",
ad85db64 351 entropy_sources[c].cmdstring, entropy_sources[c].badness);
b7a87eea 352
353 if (entropy_sources[c].badness > 0)
354 entropy_sources[c].badness--;
355 }
356
bfc9a610 357 c++;
358 }
359 }
2b87da3b 360
bfc9a610 361 return(total_entropy_estimate);
362}
363
364double
365stir_gettimeofday(double entropy_estimate)
366{
367 struct timeval tv;
2b87da3b 368
bfc9a610 369 if (gettimeofday(&tv, NULL) == -1)
370 fatal("Couldn't gettimeofday: %s", strerror(errno));
371
372 RAND_add(&tv, sizeof(tv), entropy_estimate);
2b87da3b 373
bfc9a610 374 return(entropy_estimate);
375}
376
377double
378stir_clock(double entropy_estimate)
379{
380#ifdef HAVE_CLOCK
381 clock_t c;
2b87da3b 382
bfc9a610 383 c = clock();
384 RAND_add(&c, sizeof(c), entropy_estimate);
2b87da3b 385
bfc9a610 386 return(entropy_estimate);
387#else /* _HAVE_CLOCK */
388 return(0);
389#endif /* _HAVE_CLOCK */
390}
391
392double
393stir_rusage(int who, double entropy_estimate)
394{
395#ifdef HAVE_GETRUSAGE
396 struct rusage ru;
2b87da3b 397
b7a87eea 398 if (getrusage(who, &ru) == -1)
cbd7492e 399 return(0);
bfc9a610 400
cbd7492e 401 RAND_add(&ru, sizeof(ru), entropy_estimate);
bfc9a610 402
403 return(entropy_estimate);
404#else /* _HAVE_GETRUSAGE */
405 return(0);
406#endif /* _HAVE_GETRUSAGE */
407}
408
ad85db64 409
e339aa53 410static int
ad85db64 411_get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
412 int secdiff, usecdiff;
413
414 secdiff = t2->tv_sec - t1->tv_sec;
415 usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
416 return (int)(usecdiff / 1000);
417}
418
bfc9a610 419double
b7a87eea 420hash_output_from_command(entropy_source_t *src, char *hash)
bfc9a610 421{
422 static int devnull = -1;
423 int p[2];
b7a87eea 424 fd_set rdset;
425 int cmd_eof = 0, error_abort = 0;
ad85db64 426 struct timeval tv_start, tv_current;
427 int msec_elapsed = 0;
bfc9a610 428 pid_t pid;
429 int status;
ad85db64 430 char buf[16384];
bfc9a610 431 int bytes_read;
432 int total_bytes_read;
433 SHA_CTX sha;
2b87da3b 434
22d89d24 435 debug3("Reading output from \'%s\'", src->cmdstring);
436
bfc9a610 437 if (devnull == -1) {
438 devnull = open("/dev/null", O_RDWR);
439 if (devnull == -1)
440 fatal("Couldn't open /dev/null: %s", strerror(errno));
441 }
2b87da3b 442
bfc9a610 443 if (pipe(p) == -1)
444 fatal("Couldn't open pipe: %s", strerror(errno));
445
ad85db64 446 (void)gettimeofday(&tv_start, NULL); /* record start time */
447
bfc9a610 448 switch (pid = fork()) {
449 case -1: /* Error */
450 close(p[0]);
451 close(p[1]);
452 fatal("Couldn't fork: %s", strerror(errno));
453 /* NOTREACHED */
454 case 0: /* Child */
b7a87eea 455 dup2(devnull, STDIN_FILENO);
456 dup2(p[1], STDOUT_FILENO);
457 dup2(p[1], STDERR_FILENO);
bfc9a610 458 close(p[0]);
459 close(p[1]);
460 close(devnull);
461
264dce47 462 setuid(original_uid);
b7a87eea 463 execv(src->path, (char**)(src->args));
ad85db64 464 debug("(child) Couldn't exec '%s': %s", src->cmdstring,
465 strerror(errno));
bfc9a610 466 _exit(-1);
467 default: /* Parent */
468 break;
469 }
470
471 RAND_add(&pid, sizeof(&pid), 0.0);
472
473 close(p[1]);
474
475 /* Hash output from child */
476 SHA1_Init(&sha);
477 total_bytes_read = 0;
b7a87eea 478
479 while (!error_abort && !cmd_eof) {
480 int ret;
481 struct timeval tv;
ad85db64 482 int msec_remaining;
483
484 (void) gettimeofday(&tv_current, 0);
48c99b2c 485 msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
ad85db64 486 if (msec_elapsed >= entropy_timeout_current) {
487 error_abort=1;
488 continue;
489 }
490 msec_remaining = entropy_timeout_current - msec_elapsed;
b7a87eea 491
492 FD_ZERO(&rdset);
493 FD_SET(p[0], &rdset);
ad85db64 494 tv.tv_sec = msec_remaining / 1000;
495 tv.tv_usec = (msec_remaining % 1000) * 1000;
b7a87eea 496
497 ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
ad85db64 498
264dce47 499 RAND_add(&tv, sizeof(tv), 0.0);
500
b7a87eea 501 switch (ret) {
502 case 0:
503 /* timer expired */
504 error_abort = 1;
505 break;
b7a87eea 506 case 1:
507 /* command input */
29a47408 508 do {
509 bytes_read = read(p[0], buf, sizeof(buf));
510 } while (bytes_read == -1 && errno == EINTR);
264dce47 511 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
b7a87eea 512 if (bytes_read == -1) {
513 error_abort = 1;
514 break;
264dce47 515 } else if (bytes_read) {
ad85db64 516 SHA1_Update(&sha, buf, bytes_read);
517 total_bytes_read += bytes_read;
264dce47 518 } else {
ad85db64 519 cmd_eof = 1;
264dce47 520 }
b7a87eea 521 break;
b7a87eea 522 case -1:
523 default:
264dce47 524 /* error */
ad85db64 525 debug("Command '%s': select() failed: %s", src->cmdstring,
526 strerror(errno));
b7a87eea 527 error_abort = 1;
528 break;
264dce47 529 }
530 }
b7a87eea 531
bfc9a610 532 SHA1_Final(hash, &sha);
533
534 close(p[0]);
ad85db64 535
22d89d24 536 debug3("Time elapsed: %d msec", msec_elapsed);
2b87da3b 537
bfc9a610 538 if (waitpid(pid, &status, 0) == -1) {
22d89d24 539 error("Couldn't wait for child '%s' completion: %s", src->cmdstring,
ad85db64 540 strerror(errno));
b7a87eea 541 return(0.0);
bfc9a610 542 }
543
544 RAND_add(&status, sizeof(&status), 0.0);
545
b7a87eea 546 if (error_abort) {
547 /* closing p[0] on timeout causes the entropy command to
548 * SIGPIPE. Take whatever output we got, and mark this command
549 * as slow */
22d89d24 550 debug2("Command '%s' timed out", src->cmdstring);
b7a87eea 551 src->sticky_badness *= 2;
552 src->badness = src->sticky_badness;
bfc9a610 553 return(total_bytes_read);
b7a87eea 554 }
555
556 if (WIFEXITED(status)) {
557 if (WEXITSTATUS(status)==0) {
558 return(total_bytes_read);
559 } else {
2b87da3b 560 debug2("Command '%s' exit status was %d", src->cmdstring,
48c99b2c 561 WEXITSTATUS(status));
b7a87eea 562 src->badness = src->sticky_badness = 128;
563 return (0.0);
564 }
565 } else if (WIFSIGNALED(status)) {
2b87da3b 566 debug2("Command '%s' returned on uncaught signal %d !", src->cmdstring,
48c99b2c 567 status);
b7a87eea 568 src->badness = src->sticky_badness = 128;
569 return(0.0);
570 } else
571 return(0.0);
572}
573
574/*
575 * prng seedfile functions
576 */
577int
578prng_check_seedfile(char *filename) {
579
580 struct stat st;
581
582 /* FIXME raceable: eg replace seed between this stat and subsequent open */
583 /* Not such a problem because we don't trust the seed file anyway */
584 if (lstat(filename, &st) == -1) {
5b2d4b75 585 /* Give up on hard errors */
b7a87eea 586 if (errno != ENOENT)
2b87da3b 587 debug("WARNING: Couldn't stat random seed file \"%s\": %s",
5b2d4b75 588 filename, strerror(errno));
b7a87eea 589
590 return(0);
591 }
592
593 /* regular file? */
594 if (!S_ISREG(st.st_mode))
595 fatal("PRNG seedfile %.100s is not a regular file", filename);
596
597 /* mode 0600, owned by root or the current user? */
5b2d4b75 598 if (((st.st_mode & 0177) != 0) || !(st.st_uid == original_uid)) {
599 debug("WARNING: PRNG seedfile %.100s must be mode 0600, owned by uid %d",
b7a87eea 600 filename, getuid());
5b2d4b75 601 return(0);
602 }
2b87da3b 603
b7a87eea 604 return(1);
605}
606
607void
608prng_write_seedfile(void) {
609 int fd;
610 char seed[1024];
611 char filename[1024];
612 struct passwd *pw;
613
614 /* Don't bother if we have already saved a seed */
615 if (prng_seed_saved)
616 return;
2b87da3b 617
264dce47 618 setuid(original_uid);
2b87da3b 619
52bcc044 620 prng_seed_saved = 1;
2b87da3b 621
264dce47 622 pw = getpwuid(original_uid);
b7a87eea 623 if (pw == NULL)
2b87da3b 624 fatal("Couldn't get password entry for current user (%i): %s",
264dce47 625 original_uid, strerror(errno));
2b87da3b 626
b7a87eea 627 /* Try to ensure that the parent directory is there */
2b87da3b 628 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
effa6591 629 _PATH_SSH_USER_DIR);
b7a87eea 630 mkdir(filename, 0700);
631
2b87da3b 632 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
b7a87eea 633 SSH_PRNG_SEED_FILE);
634
635 debug("writing PRNG seed to file %.100s", filename);
636
637 RAND_bytes(seed, sizeof(seed));
638
639 /* Don't care if the seed doesn't exist */
640 prng_check_seedfile(filename);
2b87da3b 641
5b2d4b75 642 if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) {
2b87da3b 643 debug("WARNING: couldn't access PRNG seedfile %.100s (%.100s)",
5b2d4b75 644 filename, strerror(errno));
2b87da3b 645 } else {
5b2d4b75 646 if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
2b87da3b 647 fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
5b2d4b75 648 strerror(errno));
b7a87eea 649
5b2d4b75 650 close(fd);
651 }
b7a87eea 652}
653
654void
655prng_read_seedfile(void) {
656 int fd;
657 char seed[1024];
658 char filename[1024];
659 struct passwd *pw;
2b87da3b 660
264dce47 661 pw = getpwuid(original_uid);
b7a87eea 662 if (pw == NULL)
2b87da3b 663 fatal("Couldn't get password entry for current user (%i): %s",
264dce47 664 original_uid, strerror(errno));
2b87da3b 665
666 snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
b7a87eea 667 SSH_PRNG_SEED_FILE);
668
669 debug("loading PRNG seed from file %.100s", filename);
670
671 if (!prng_check_seedfile(filename)) {
52ce34a2 672 verbose("Random seed file not found or not valid, ignoring.");
b7a87eea 673 return;
674 }
675
676 /* open the file and read in the seed */
677 fd = open(filename, O_RDONLY);
678 if (fd == -1)
2b87da3b 679 fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
b7a87eea 680 strerror(errno));
681
682 if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
683 verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
684 filename);
685 memset(seed, '\0', sizeof(seed));
686 }
687 close(fd);
688
689 /* stir in the seed, with estimated entropy zero */
690 RAND_add(&seed, sizeof(seed), 0.0);
bfc9a610 691}
b7a87eea 692
d3083fbd 693
694/*
695 * entropy command initialisation functions
696 */
d3083fbd 697int
698prng_read_commands(char *cmdfilename)
699{
700 FILE *f;
d3083fbd 701 char *cp;
48c99b2c 702 char line[1024];
703 char cmd[1024];
704 char path[256];
d3083fbd 705 int linenum;
d3083fbd 706 int num_cmds = 64;
707 int cur_cmd = 0;
48c99b2c 708 double est;
709 entropy_source_t *entcmd;
d3083fbd 710
711 f = fopen(cmdfilename, "r");
712 if (!f) {
713 fatal("couldn't read entropy commands file %.100s: %.100s",
714 cmdfilename, strerror(errno));
715 }
716
d3083fbd 717 entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
718 memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
719
48c99b2c 720 /* Read in file */
721 linenum = 0;
d3083fbd 722 while (fgets(line, sizeof(line), f)) {
48c99b2c 723 int arg;
724 char *argv;
725
d3083fbd 726 linenum++;
727
728 /* skip leading whitespace, test for blank line or comment */
729 cp = line + strspn(line, WHITESPACE);
730 if ((*cp == 0) || (*cp == '#'))
731 continue; /* done with this line */
732
48c99b2c 733 /* First non-whitespace char should be double quote delimiting */
734 /* commandline */
735 if (*cp != '"') {
736 error("bad entropy command, %.100s line %d", cmdfilename,
737 linenum);
738 continue;
2b87da3b 739 }
d3083fbd 740
48c99b2c 741 /* first token, command args (incl. argv[0]) in double quotes */
742 cp = strtok(cp, "\"");
743 if (cp == NULL) {
744 error("missing or bad command string, %.100s line %d -- ignored",
745 cmdfilename, linenum);
746 continue;
747 }
748 strlcpy(cmd, cp, sizeof(cmd));
2b87da3b 749
48c99b2c 750 /* second token, full command path */
751 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
752 error("missing command path, %.100s line %d -- ignored",
753 cmdfilename, linenum);
754 continue;
755 }
d3083fbd 756
48c99b2c 757 /* did configure mark this as dead? */
758 if (strncmp("undef", cp, 5) == 0)
759 continue;
d3083fbd 760
2b87da3b 761 strlcpy(path, cp, sizeof(path));
48c99b2c 762
763 /* third token, entropy rate estimate for this command */
764 if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
765 error("missing entropy estimate, %.100s line %d -- ignored",
766 cmdfilename, linenum);
767 continue;
768 }
769 est = strtod(cp, &argv);
770
771 /* end of line */
772 if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
2b87da3b 773 error("garbage at end of line %d in %.100s -- ignored", linenum,
48c99b2c 774 cmdfilename);
d3083fbd 775 continue;
776 }
48c99b2c 777
778 /* save the command for debug messages */
779 entcmd[cur_cmd].cmdstring = xstrdup(cmd);
2b87da3b 780
48c99b2c 781 /* split the command args */
782 cp = strtok(cmd, WHITESPACE);
783 arg = 0;
784 argv = NULL;
785 do {
786 char *s = (char*)xmalloc(strlen(cp) + 1);
787 strncpy(s, cp, strlen(cp) + 1);
788 entcmd[cur_cmd].args[arg] = s;
789 arg++;
790 } while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
2b87da3b 791
48c99b2c 792 if (strtok(NULL, WHITESPACE))
793 error("ignored extra command elements (max 5), %.100s line %d",
794 cmdfilename, linenum);
795
796 /* Copy the command path and rate estimate */
797 entcmd[cur_cmd].path = xstrdup(path);
798 entcmd[cur_cmd].rate = est;
799
800 /* Initialise other values */
801 entcmd[cur_cmd].sticky_badness = 1;
802
803 cur_cmd++;
804
805 /* If we've filled the array, reallocate it twice the size */
806 /* Do this now because even if this we're on the last command,
807 we need another slot to mark the last entry */
808 if (cur_cmd == num_cmds) {
809 num_cmds *= 2;
810 entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
811 }
d3083fbd 812 }
813
814 /* zero the last entry */
815 memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
48c99b2c 816
d3083fbd 817 /* trim to size */
818 entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
819
264dce47 820 debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
d3083fbd 821
822 return (cur_cmd >= MIN_ENTROPY_SOURCES);
823}
824
b7a87eea 825/*
826 * Write a keyfile at exit
2b87da3b 827 */
b7a87eea 828void
829prng_seed_cleanup(void *junk)
830{
831 prng_write_seedfile();
832}
833
bfc9a610 834/*
b7a87eea 835 * Conditionally Seed OpenSSL's random number pool from
836 * syscalls and program output
bfc9a610 837 */
838void
839seed_rng(void)
840{
e1a023df 841 mysig_t old_sigchld_handler;
d3083fbd 842
264dce47 843 if (!prng_initialised)
844 fatal("RNG not initialised");
2b87da3b 845
a64009ad 846 /* Make sure some other sigchld handler doesn't reap our entropy */
847 /* commands */
e1a023df 848 old_sigchld_handler = mysignal(SIGCHLD, SIG_DFL);
a64009ad 849
e339aa53 850 debug("Seeded RNG with %i bytes from programs",
851 (int)stir_from_programs());
852 debug("Seeded RNG with %i bytes from system calls",
853 (int)stir_from_system());
264dce47 854
855 if (!RAND_status())
856 fatal("Not enough entropy in RNG");
b7a87eea 857
e1a023df 858 mysignal(SIGCHLD, old_sigchld_handler);
a64009ad 859
ad85db64 860 if (!RAND_status())
861 fatal("Couldn't initialise builtin random number generator -- exiting.");
264dce47 862}
ad85db64 863
e339aa53 864void
865init_rng(void)
264dce47 866{
e879a080 867 int original_euid;
2b87da3b 868
c7c72446 869 check_openssl_version();
870
264dce47 871 original_uid = getuid();
e879a080 872 original_euid = geteuid();
264dce47 873
874 /* Read in collection commands */
875 if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
876 fatal("PRNG initialisation failed -- exiting.");
877
878 /* Set ourselves up to save a seed upon exit */
2b87da3b 879 prng_seed_saved = 0;
e879a080 880
881 /* Give up privs while reading seed file */
e9a13ac1 882#ifdef SAVED_IDS_WORK_WITH_SETEUID
e879a080 883 if ((original_uid != original_euid) && (seteuid(original_uid) == -1))
884 fatal("Couldn't give up privileges");
e9a13ac1 885#else /* SAVED_IDS_WORK_WITH_SETEUID */
886 /*
887 * Propagate the privileged uid to all of our uids.
888 * Set the effective uid to the given (unprivileged) uid.
889 */
d5c4c52e 890 if (original_uid != original_euid && (setuid(original_euid) == -1 ||
891 seteuid(original_uid) == -1))
e9a13ac1 892 fatal("Couldn't give up privileges");
893#endif /* SAVED_IDS_WORK_WITH_SETEUID */
2b87da3b 894
264dce47 895 prng_read_seedfile();
e879a080 896
e9a13ac1 897#ifdef SAVED_IDS_WORK_WITH_SETEUID
e879a080 898 if ((original_uid != original_euid) && (seteuid(original_euid) == -1))
899 fatal("Couldn't restore privileges");
e9a13ac1 900#else /* SAVED_IDS_WORK_WITH_SETEUID */
901 /*
902 * We are unable to restore the real uid to its unprivileged value.
903 * Propagate the real uid (usually more privileged) to effective uid
904 * as well.
905 */
d5c4c52e 906 if (original_uid != original_euid && (seteuid(original_euid) == -1 ||
907 setuid(original_uid) == -1))
e9a13ac1 908 fatal("Couldn't restore privileges");
909#endif /* SAVED_IDS_WORK_WITH_SETEUID */
e879a080 910
264dce47 911 fatal_add_cleanup(prng_seed_cleanup, NULL);
912 atexit(prng_write_seedfile);
913
914 prng_initialised = 1;
bfc9a610 915}
264dce47 916
9bdd5929 917#endif /* defined(USE_PRNGD) || defined(RANDOM_POOL) */
This page took 0.252828 seconds and 5 git commands to generate.