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