]> andersk Git - openssh.git/blob - entropy.c
- Reduce diff against OpenBSD source
[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  * 3. All advertising materials mentioning features or use of this software
13  *    must display the following acknowledgement:
14  *      This product includes software developed by Markus Friedl.
15  * 4. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "includes.h"
31
32 #include "ssh.h"
33 #include "xmalloc.h"
34
35 #include <openssl/rand.h>
36 #include <openssl/sha.h>
37
38 RCSID("$Id$");
39
40 #ifdef EGD_SOCKET
41 #ifndef offsetof
42 # define offsetof(type, member) ((size_t) &((type *)0)->member)
43 #endif
44 /* Collect entropy from EGD */
45 void get_random_bytes(unsigned char *buf, int len)
46 {
47         static int egd_socket = -1;
48         int c;
49         char egd_message[2] = { 0x02, 0x00 };
50         struct sockaddr_un addr;
51         int addr_len;
52
53         memset(&addr, '\0', sizeof(addr));
54         addr.sun_family = AF_UNIX;
55         
56         /* FIXME: compile time check? */
57         if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
58                 fatal("Random pool path is too long");
59         
60         strcpy(addr.sun_path, EGD_SOCKET);
61         
62         addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
63         
64         if (egd_socket == -1) {
65                 egd_socket = socket(AF_UNIX, SOCK_STREAM, 0);
66                 if (egd_socket == -1)
67                         fatal("Couldn't create AF_UNIX socket: %s", strerror(errno));
68                 if (connect(egd_socket, (struct sockaddr*)&addr, addr_len) == -1)
69                         fatal("Couldn't connect to EGD socket \"%s\": %s", addr.sun_path, strerror(errno));
70         }       
71
72         if (len > 255)
73                 fatal("Too many bytes to read from EGD");
74         
75         /* Send blocking read request to EGD */
76         egd_message[1] = len;
77
78         c = atomicio(write, egd_socket, egd_message, sizeof(egd_message));
79         if (c == -1)
80                 fatal("Couldn't write to EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno));
81
82         c = atomicio(read, egd_socket, buf, len);
83         if (c <= 0)
84                 fatal("Couldn't read from EGD socket \"%s\": %s", EGD_SOCKET, strerror(errno));
85         
86         close(EGD_SOCKET);
87 }
88 #else /* !EGD_SOCKET */
89 #ifdef RANDOM_POOL
90 /* Collect entropy from /dev/urandom or pipe */
91 void get_random_bytes(unsigned char *buf, int len)
92 {
93         static int random_pool = -1;
94         int c;
95
96         if (random_pool == -1) {
97                 random_pool = open(RANDOM_POOL, O_RDONLY);
98                 if (random_pool == -1)
99                         fatal("Couldn't open random pool \"%s\": %s", RANDOM_POOL, strerror(errno));
100         }
101         
102         c = atomicio(read, random_pool, buf, len);
103         if (c <= 0)
104                 fatal("Couldn't read from random pool \"%s\": %s", RANDOM_POOL, strerror(errno));
105 }
106 #endif /* RANDOM_POOL */
107 #endif /* EGD_SOCKET */
108
109 #if !defined(EGD_SOCKET) && !defined(RANDOM_POOL)
110 /* 
111  * FIXME: proper entropy estimations. All current values are guesses
112  * FIXME: Need timeout for slow moving programs
113  * FIXME: More entropy sources
114  */
115
116 double stir_from_system(void);
117 double stir_from_programs(void);
118 double stir_gettimeofday(double entropy_estimate);
119 double stir_clock(double entropy_estimate);
120 double stir_rusage(int who, double entropy_estimate);
121 double hash_output_from_command(const char *path, const char **args, char *hash);
122
123 typedef struct
124 {
125         /* Proportion of data that is entropy */
126         double rate;
127         /* Path to executable */
128         const char *path;
129         /* argv to pass to executable */
130         const char *args[5];
131 } entropy_source_t;
132
133 entropy_source_t entropy_sources[] = {
134 #ifdef PROG_LS
135         { 0.002, PROG_LS,       { "ls", "-alni", "/var/log", NULL } },
136         { 0.002, PROG_LS,       { "ls", "-alni", "/var/adm", NULL } },
137         { 0.002, PROG_LS,       { "ls", "-alni", "/var/mail", NULL } },
138         { 0.002, PROG_LS,       { "ls", "-alni", "/var/spool/mail", NULL } },
139         { 0.002, PROG_LS,       { "ls", "-alni", "/proc", NULL } },
140         { 0.002, PROG_LS,       { "ls", "-alni", "/tmp", NULL } },
141 #endif
142 #ifdef PROG_NETSTAT
143         { 0.005, PROG_NETSTAT,  { "netstat","-an", NULL, NULL } },
144         { 0.010, PROG_NETSTAT,  { "netstat","-in", NULL, NULL } },
145         { 0.002, PROG_NETSTAT,  { "netstat","-rn", NULL, NULL } },
146         { 0.002, PROG_NETSTAT,  { "netstat","-s", NULL, NULL } },
147 #endif
148 #ifdef PROG_ARP
149         { 0.002, PROG_ARP,      { "arp","-a","-n", NULL } },
150 #endif
151 #ifdef PROG_IFCONFIG
152         { 0.002, PROG_IFCONFIG, { "ifconfig", "-a", NULL, NULL } },
153 #endif
154 #ifdef PROG_PS
155         { 0.003, PROG_PS,       { "ps", "laxww", NULL, NULL } },
156         { 0.003, PROG_PS,       { "ps", "-al", NULL, NULL } },
157         { 0.003, PROG_PS,       { "ps", "-efl", NULL, NULL } },
158 #endif
159 #ifdef PROG_W
160         { 0.005, PROG_W,        { "w", NULL, NULL, NULL } },
161 #endif
162 #ifdef PROG_WHO
163         { 0.001, PROG_WHO,      { "who","-i", NULL, NULL } },
164 #endif
165 #ifdef PROG_LAST
166         { 0.001, PROG_LAST,     { "last", NULL, NULL, NULL } },
167 #endif
168 #ifdef PROG_LASTLOG
169         { 0.001, PROG_LASTLOG,  { "lastlog", NULL, NULL, NULL } },
170 #endif
171 #ifdef PROG_DF
172         { 0.010, PROG_DF,       { "df", NULL, NULL, NULL } },
173         { 0.010, PROG_DF,       { "df", "-i", NULL, NULL } },
174 #endif
175 #ifdef PROG_VMSTAT
176         { 0.010, PROG_VMSTAT,   { "vmstat", NULL, NULL, NULL } },
177 #endif
178 #ifdef PROG_UPTIME
179         { 0.001, PROG_UPTIME,   { "uptime", NULL, NULL, NULL } },
180 #endif
181 #ifdef PROG_IPCS
182         { 0.001, PROG_IPCS,     { "-a", NULL, NULL, NULL } },
183 #endif
184 #ifdef PROG_TAIL
185         { 0.001, PROG_TAIL,     { "tail", "-200", "/var/log/messages", NULL, NULL } },
186         { 0.001, PROG_TAIL,     { "tail", "-200", "/var/log/syslog", NULL, NULL } },
187         { 0.001, PROG_TAIL,     { "tail", "-200", "/var/adm/messages", NULL, NULL } },
188         { 0.001, PROG_TAIL,     { "tail", "-200", "/var/adm/syslog", NULL, NULL } },
189         { 0.001, PROG_TAIL,     { "tail", "-200", "/var/log/maillog", NULL, NULL } },
190         { 0.001, PROG_TAIL,     { "tail", "-200", "/var/adm/maillog", NULL, NULL } },
191 #endif
192         { 0.000, NULL,          { NULL, NULL, NULL, NULL, NULL } },
193 };
194
195 double 
196 stir_from_system(void)
197 {
198         double total_entropy_estimate;
199         long int i;
200         
201         total_entropy_estimate = 0;
202         
203         i = getpid();
204         RAND_add(&i, sizeof(i), 0.1);
205         total_entropy_estimate += 0.1;
206         
207         i = getppid();
208         RAND_add(&i, sizeof(i), 0.1);
209         total_entropy_estimate += 0.1;
210
211         i = getuid();
212         RAND_add(&i, sizeof(i), 0.0);
213         i = getgid();
214         RAND_add(&i, sizeof(i), 0.0);
215
216         total_entropy_estimate += stir_gettimeofday(1.0);
217         total_entropy_estimate += stir_clock(0.2);
218         total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
219
220         return(total_entropy_estimate);
221 }
222
223 double 
224 stir_from_programs(void)
225 {
226         int i;
227         int c;
228         double entropy_estimate;
229         double total_entropy_estimate;
230         char hash[SHA_DIGEST_LENGTH];
231
232         /*
233          * Run through list of programs twice to catch differences
234          */
235         total_entropy_estimate = 0;
236         for(i = 0; i < 2; i++) {
237                 c = 0;
238                 while (entropy_sources[c].path != NULL) {
239                         /* Hash output from command */
240                         entropy_estimate = hash_output_from_command(entropy_sources[c].path,
241                                 entropy_sources[c].args, hash);
242
243                         /* Scale back entropy estimate according to command's rate */
244                         entropy_estimate *= entropy_sources[c].rate;
245  
246                         /* Upper bound of entropy estimate is SHA_DIGEST_LENGTH */
247                         if (entropy_estimate > SHA_DIGEST_LENGTH)
248                                 entropy_estimate = SHA_DIGEST_LENGTH;
249
250                         /* * Scale back estimates for subsequent passes through list */
251                         entropy_estimate /= 10.0 * (i + 1.0);
252                         
253                         /* Stir it in */
254                         RAND_add(hash, sizeof(hash), entropy_estimate);
255
256 /* FIXME: turn this off later */
257 #if 1
258                         debug("Got %0.2f bytes of entropy from %s", entropy_estimate, 
259                                 entropy_sources[c].path);
260 #endif
261
262                         total_entropy_estimate += entropy_estimate;
263
264                         /* Execution times should be a little unpredictable */
265                         total_entropy_estimate += stir_gettimeofday(0.05);
266                         total_entropy_estimate += stir_clock(0.05);
267                         total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
268                         total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
269                         
270                         c++;
271                 }
272         }
273         
274         return(total_entropy_estimate);
275 }
276
277 double
278 stir_gettimeofday(double entropy_estimate)
279 {
280         struct timeval tv;
281         
282         if (gettimeofday(&tv, NULL) == -1)
283                 fatal("Couldn't gettimeofday: %s", strerror(errno));
284
285         RAND_add(&tv, sizeof(tv), entropy_estimate);
286         
287         return(entropy_estimate);
288 }
289
290 double
291 stir_clock(double entropy_estimate)
292 {
293 #ifdef HAVE_CLOCK
294         clock_t c;
295         
296         c = clock();
297         RAND_add(&c, sizeof(c), entropy_estimate);
298         
299         return(entropy_estimate);
300 #else /* _HAVE_CLOCK */
301         return(0);
302 #endif /* _HAVE_CLOCK */
303 }
304
305 double
306 stir_rusage(int who, double entropy_estimate)
307 {
308 #ifdef HAVE_GETRUSAGE
309         struct rusage ru;
310         
311    if (getrusage(who, &ru) == -1)
312                 fatal("Couldn't getrusage: %s", strerror(errno));
313
314         RAND_add(&ru, sizeof(ru), 0.1);
315
316         return(entropy_estimate);
317 #else /* _HAVE_GETRUSAGE */
318         return(0);
319 #endif /* _HAVE_GETRUSAGE */
320 }
321
322 double
323 hash_output_from_command(const char *path, const char **args, char *hash)
324 {
325         static int devnull = -1;
326         int p[2];
327         pid_t pid;
328         int status;
329         char buf[2048];
330         int bytes_read;
331         int total_bytes_read;
332         SHA_CTX sha;
333         
334         if (devnull == -1) {
335                 devnull = open("/dev/null", O_RDWR);
336                 if (devnull == -1)
337                         fatal("Couldn't open /dev/null: %s", strerror(errno));
338         }
339         
340         if (pipe(p) == -1)
341                 fatal("Couldn't open pipe: %s", strerror(errno));
342
343         switch (pid = fork()) {
344                 case -1: /* Error */
345                         close(p[0]);
346                         close(p[1]);
347                         fatal("Couldn't fork: %s", strerror(errno));
348                         /* NOTREACHED */
349                 case 0: /* Child */
350                         close(0);
351                         close(1);
352                         close(2);
353                         dup2(devnull, 0);
354                         dup2(p[1], 1);
355                         dup2(p[1], 2);
356                         close(p[0]);
357                         close(p[1]);
358                         close(devnull);
359
360                         execv(path, (char**)args);
361                         debug("(child) Couldn't exec '%s': %s", path, strerror(errno));
362                         _exit(-1);
363                 default: /* Parent */
364                         break;
365         }
366
367         RAND_add(&pid, sizeof(&pid), 0.0);
368
369         close(p[1]);
370
371         /* Hash output from child */
372         SHA1_Init(&sha);
373         total_bytes_read = 0;
374         while ((bytes_read = read(p[0], buf, sizeof(buf)))      > 0) {
375                 SHA1_Update(&sha, buf, bytes_read);
376                 total_bytes_read += bytes_read;
377                 RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
378         }
379         SHA1_Final(hash, &sha);
380
381         close(p[0]);
382         
383         if (waitpid(pid, &status, 0) == -1) {
384                 error("Couldn't wait for child '%s' completion: %s", path, 
385                         strerror(errno));
386                 return(-1);
387         }
388
389         RAND_add(&status, sizeof(&status), 0.0);
390
391         if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0))
392                 return(0.0);
393         else
394                 return(total_bytes_read);
395 }
396 #endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
397
398 #if defined(EGD_SOCKET) || defined(RANDOM_POOL)
399 /*
400  * Seed OpenSSL's random number pool from Kernel random number generator
401  * or EGD
402  */
403 void
404 seed_rng(void)
405 {
406         char buf[32];
407         
408         debug("Seeding random number generator");
409         get_random_bytes(buf, sizeof(buf));
410         RAND_add(buf, sizeof(buf), sizeof(buf));
411         memset(buf, '\0', sizeof(buf));
412 }
413 #else /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
414 /*
415  * Conditionally Seed OpenSSL's random number pool syscalls and program output
416  */
417 void
418 seed_rng(void)
419 {
420         debug("Seeding random number generator.");
421         debug("OpenSSL random status is now %i\n", RAND_status());
422         debug("%i bytes from system calls", (int)stir_from_system());
423         debug("%i bytes from programs", (int)stir_from_programs());
424         debug("OpenSSL random status is now %i\n", RAND_status());
425 }
426 #endif /* defined(EGD_SOCKET) || defined(RANDOM_POOL) */
This page took 0.184039 seconds and 5 git commands to generate.