cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
unix.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * Unix Randomness-Gathering Code *
4 * Copyright Peter Gutmann, Paul Kendall, and Chris Wedgwood 1996-2008 *
5 * *
6 ****************************************************************************/
7 
8 /* This module is part of the cryptlib continuously seeded pseudorandom
9  number generator. For usage conditions, see random.c */
10 
11 /* Define the following to print diagnostic information on where randomness
12  is coming from */
13 
14 /* #define DEBUG_RANDOM */
15 
16 /* Comment out the following to disable printed warnings about possible
17  conflicts with signal handlers and other system services */
18 
19 #define DEBUG_CONFLICTS
20 
21 /* General includes */
22 
23 #if defined( __GNUC__ )
24  #define _GNU_SOURCE
25 #endif /* Needed for newer functions like setresuid() */
26 #include <stdio.h>
27 #include <time.h>
28 #include "crypt.h"
29 #include "random/random.h"
30 
31 /* Unix and Unix-like systems share the same makefile, make sure that the
32  user isn't trying to use the Unix randomness code under a non-Unix (but
33  Unix-like) system. This would be pretty unlikely since the makefile
34  automatically adjusts itself based on the environment it's running in,
35  but we use the following safety check just in case. We have to perform
36  this check before we try any includes because Unix and the Unix-like
37  systems don't have the same header files */
38 
39 #ifdef __BEOS__
40  #error For the BeOS build you need to edit $MISCOBJS in the makefile to use 'beos' and not 'unix'
41 #endif /* BeOS has its own randomness-gathering file */
42 #ifdef __ECOS__
43  #error For the eCOS build you need to edit $MISCOBJS in the makefile to use 'ecos' and not 'unix'
44 #endif /* eCOS has its own randomness-gathering file */
45 #ifdef __ITRON__
46  #error For the uITRON build you need to edit $MISCOBJS in the makefile to use 'itron' and not 'unix'
47 #endif /* uITRON has its own randomness-gathering file */
48 #ifdef __PALMSOURCE__
49  #error For the PalmOS build you need to edit $MISCOBJS in the makefile to use 'palmos' and not 'unix'
50 #endif /* PalmOS has its own randomness-gathering file */
51 #ifdef __RTEMS__
52  #error For the RTEMS build you need to edit $MISCOBJS in the makefile to use 'rtems' and not 'unix'
53 #endif /* RTEMS has its own randomness-gathering file */
54 #if defined( __TANDEM_NSK__ ) || defined( __TANDEM_OSS__ )
55  #error For the Tandem build you need to edit $MISCOBJS in the makefile to use 'tandem' and not 'unix'
56 #endif /* Tandem OSS has its own randomness-gathering file */
57 #if defined( __VXWORKS__ )
58  #error For the VxWorks build you need to edit $MISCOBJS in the makefile to use 'vxworks' and not 'unix'
59 #endif /* VxWorks has its own randomness-gathering file */
60 #if defined( __XMK__ )
61  #error For the Xilinx XMK build you need to edit $MISCOBJS in the makefile to use 'xmk' and not 'unix'
62 #endif /* XMK has its own randomness-gathering file */
63 
64 /* OS-specific includes */
65 
66 #if defined( __hpux ) && ( OSVERSION >= 10 )
67  #define _XOPEN_SOURCE_EXTENDED
68 #endif /* Workaround for inconsistent PHUX networking headers */
69 #include <unistd.h>
70 #include <errno.h>
71 #include <fcntl.h>
72 #include <pwd.h>
73 #if !( defined( __QNX__ ) || defined( __MVS__ ) )
74  #include <sys/errno.h>
75  #include <sys/ipc.h>
76 #endif /* !( QNX || MVS ) */
77 #include <sys/time.h> /* SCO and SunOS need this before resource.h */
78 #ifndef __QNX__
79  #if defined( _MPRAS ) && !( defined( _XOPEN_SOURCE ) && \
80  defined( __XOPEN_SOURCE_EXTENDED ) )
81  /* On MP-RAS 3.02, the X/Open test macros must be set to include
82  getrusage(). */
83  #define _XOPEN_SOURCE 1
84  #define _XOPEN_SOURCE_EXTENDED 1
85  #define MPRAS_XOPEN_DEFINES
86  #endif /* MP-RAS */
87  #include <sys/resource.h>
88  #if defined( MPRAS_XOPEN_DEFINES )
89  #undef _XOPEN_SOURCE
90  #undef _XOPEN_SOURCE_EXTENDED
91  #undef MPRAS_XOPEN_DEFINES
92  #endif /* MP-RAS */
93 #endif /* QNX */
94 #if defined( _AIX ) || defined( __QNX__ )
95  #include <sys/select.h>
96 #endif /* Aches || QNX */
97 #ifdef _AIX
98  #include <sys/systemcfg.h>
99 #endif /* Aches */
100 #ifdef __CYGWIN__
101  #include <signal.h>
102  #include <sys/ipc.h>
103  #include <sys/sem.h>
104  #include <sys/shm.h>
105 #endif /* CYGWIN */
106 #if !( defined( __QNX__ ) || defined( __CYGWIN__ ) )
107  #include <sys/shm.h>
108 #endif /* QNX || Cygwin */
109 #if defined( __linux__ ) && ( defined(__i386__) || defined(__x86_64__) )
110  #include <sys/timex.h> /* For rdtsc() */
111 #endif /* Linux on x86 */
112 #include <signal.h>
113 #include <sys/socket.h>
114 #include <sys/stat.h>
115 #include <sys/types.h> /* Verschiedene komische Typen */
116 #include <sys/un.h>
117 #if defined( __hpux ) && ( OSVERSION == 9 )
118  #include <vfork.h>
119 #endif /* __hpux 9.x, after that it's in unistd.h */
120 #include <sys/wait.h>
121 /* #include <kitchensink.h> */
122 
123 #if defined( sun ) || defined( __ultrix__ ) || defined( __hpux )
124  #define HAS_VFORK
125 #endif /* Unixen that have vfork() */
126 
127 /* Crays and QNX 4.x don't have a rlimit/rusage so we have to fake the
128  functions and structs */
129 
130 #if defined( _CRAY ) || \
131  ( defined( __QNX__ ) && OSVERSION <= 4 )
132  #define setrlimit( x, y )
133  struct rlimit { int dummy1, dummy2; };
134  struct rusage { int dummy; };
135 #endif /* Systems without rlimit/rusage */
136 
137 /* If we're using threads, we have to protect the entropy gatherer with
138  a mutex to prevent multiple threads from trying to initate polls at the
139  same time. Unlike the kernel mutexes, we don't have to worry about
140  being called recursively, so there's no need for special-case handling
141  for Posix' nasty non-reentrant mutexes */
142 
143 #ifdef USE_THREADS
144  #include <pthread.h>
145 
146  #define lockPollingMutex() pthread_mutex_lock( &gathererMutex )
147  #define unlockPollingMutex() pthread_mutex_unlock( &gathererMutex )
148 #else
149  #define lockPollingMutex()
150  #define unlockPollingMutex()
151 #endif /* USE_THREADS */
152 
153 /* The size of the intermediate buffer used to accumulate polled data */
154 
155 #define RANDOM_BUFSIZE 4096
156 #if RANDOM_BUFSIZE > MAX_INTLENGTH_SHORT
157  #error RANDOM_BUFSIZE exceeds randomness accumulator size
158 #endif /* RANDOM_BUFSIZE > MAX_INTLENGTH_SHORT */
159 
160 /* A special form of the ENSURES() predicate used in the forked child
161  process, which calls exit() rather than returning */
162 
163 #define ENSURES_EXIT( x ) \
164  if( !( x ) ) { assert( INTERNAL_ERROR ); exit( -1 ); }
165 
166 /* The structure containing information on random-data sources. Each record
167  contains the source and a relative estimate of its usefulness (weighting)
168  which is used to scale the number of kB of output from the source (total
169  = data_bytes / usefulness). Usually the weighting is in the range 1-3
170  (or 0 for especially useless sources), resulting in a usefulness rating
171  of 1...3 for each kB of source output (or 0 for the useless sources).
172 
173  If the source is constantly changing (certain types of network statistics
174  have this characteristic) but the amount of output is small, the weighting
175  is given as a negative value to indicate that the output should be treated
176  as if a minimum of 1K of output had been obtained. If the source produces
177  a lot of output then the scale factor is fractional, resulting in a
178  usefulness rating of < 1 for each kB of source output.
179 
180  In order to provide enough randomness to satisfy the requirements for a
181  slow poll, we need to accumulate at least 20 points of usefulness (a
182  typical system should get about 30 points). This is useful not only for
183  use on source-starved systems but also in special circumstances like
184  running in a *BSD jail, in which only other processes running in the jail
185  are visible, severely restricting the amount of entropy that can be
186  collected.
187 
188  Some potential options are missed out because of special considerations.
189  pstat -i and pstat -f can produce amazing amounts of output (the record is
190  600K on an Oracle server) that floods the buffer and doesn't yield
191  anything useful (apart from perhaps increasing the entropy of the vmstat
192  output a bit), so we don't bother with this. pstat in general produces
193  quite a bit of output, but it doesn't change much over time, so it gets
194  very low weightings. netstat -s produces constantly-changing output but
195  also produces quite a bit of it, so it only gets a weighting of 2 rather
196  than 3. The same holds for netstat -in, which gets 1 rather than 2. In
197  addition some of the lower-ranked sources are either rather heavyweight
198  or of low value, and frequently duplicate information obtained by other
199  means like kstat or /procfs. To avoid waiting for a long time for them
200  to produce output, we only use them if earlier, quicker sources aren't
201  available.
202 
203  Some binaries are stored in different locations on different systems so
204  alternative paths are given for them. The code sorts out which one to run
205  by itself, once it finds an exectable somewhere it moves on to the next
206  source. The sources are arranged roughly in their order of usefulness,
207  occasionally sources that provide a tiny amount of relatively useless
208  data are placed ahead of ones that provide a large amount of possibly
209  useful data because another 100 bytes can't hurt, and it means the buffer
210  won't be swamped by one or two high-output sources. All the high-output
211  sources are clustered towards the end of the list for this reason. Some
212  binaries are checked for in a certain order, for example under Slowaris
213  /usr/ucb/ps understands aux as an arg, but the others don't. Some systems
214  have conditional defines enabling alternatives to commands that don't
215  understand the usual options but will provide enough output (in the form
216  of error messages) to look like they're the real thing, causing
217  alternative options to be skipped (we can't check the return either
218  because some commands return peculiar, non-zero status even when they're
219  working correctly).
220 
221  In order to maximise use of the buffer, the code performs a form of run-
222  length compression on its input where a repeated sequence of bytes is
223  replaced by the occurrence count mod 256. Some commands output an awful
224  lot of whitespace, this measure greatly increases the amount of data that
225  we can fit in the buffer.
226 
227  When we scale the weighting using the SC() macro, some preprocessors may
228  give a division by zero warning for the most obvious expression 'weight ?
229  1024 / weight : 0' (and gcc 2.7.2.2 dies with a division by zero trap), so
230  we define a value SC_0 that evaluates to zero when fed to '1024 / SC_0' */
231 
232 #define SC( weight ) ( 1024 / weight ) /* Scale factor */
233 #define SC_0 16384 /* SC( SC_0 ) evalutes to 0 */
234 
235 typedef struct {
236  const char *path; /* Path to check for existence of source */
237  const char *arg; /* Args for source */
238  const int usefulness; /* Usefulness of source */
239  FILE *pipe; /* Pipe to source as FILE * */
240  int pipeFD; /* Pipe to source as FD */
241  pid_t pid; /* pid of child for waitpid() */
242  int length; /* Quantity of output produced */
243  const BOOLEAN hasAlternative; /* Whether source has alt.location */
245 
246 static DATA_SOURCE_INFO dataSources[] = {
247  /* Sources that are always polled */
248  { "/bin/vmstat", "-s", SC( -3 ), NULL, 0, 0, 0, TRUE },
249  { "/usr/bin/vmstat", "-s", SC( -3 ), NULL, 0, 0, 0, FALSE },
250  { "/bin/vmstat", "-c", SC( -3 ), NULL, 0, 0, 0, TRUE },
251  { "/usr/bin/vmstat", "-c", SC( -3 ), NULL, 0, 0, 0, FALSE },
252 #if defined( __APPLE__ )
253  { "/usr/bin/vm_stat", NULL, SC( -3 ), NULL, 0, 0, 0, FALSE },
254 #endif /* Mach version of vmstat */
255  { "/usr/bin/pfstat", NULL, SC( -2 ), NULL, 0, 0, 0, FALSE },
256  { "/bin/vmstat", "-i", SC( -2 ), NULL, 0, 0, 0, TRUE },
257  { "/usr/bin/vmstat", "-i", SC( -2 ), NULL, 0, 0, 0, FALSE },
258 #if defined( _AIX ) || defined( __SCO_VERSION__ )
259  { "/usr/bin/vmstat", "-f", SC( -1 ), NULL, 0, 0, 0, FALSE },
260 #endif /* OS-specific extensions to vmstat */
261  { "/usr/ucb/netstat", "-s", SC( 2 ), NULL, 0, 0, 0, TRUE },
262  { "/usr/bin/netstat", "-s", SC( 2 ), NULL, 0, 0, 0, TRUE },
263  { "/usr/sbin/netstat", "-s", SC( 2 ), NULL, 0, 0, 0, TRUE },
264  { "/bin/netstat", "-s", SC( 2 ), NULL, 0, 0, 0, TRUE },
265  { "/usr/etc/netstat", "-s", SC( 2 ), NULL, 0, 0, 0, FALSE },
266  { "/usr/bin/nfsstat", NULL, SC( 2 ), NULL, 0, 0, 0, FALSE },
267  { "/usr/ucb/netstat", "-m", SC( -1 ), NULL, 0, 0, 0, TRUE },
268  { "/usr/bin/netstat", "-m", SC( -1 ), NULL, 0, 0, 0, TRUE },
269  { "/usr/sbin/netstat", "-m", SC( -1 ), NULL, 0, 0, 0, TRUE },
270  { "/bin/netstat", "-m", SC( -1 ), NULL, 0, 0, 0, TRUE },
271  { "/usr/etc/netstat", "-m", SC( -1 ), NULL, 0, 0, 0, FALSE },
272  { "/usr/ucb/netstat", "-in", SC( -1 ), NULL, 0, 0, 0, TRUE },
273  { "/usr/bin/netstat", "-in", SC( -1 ), NULL, 0, 0, 0, TRUE },
274  { "/usr/sbin/netstat", "-in", SC( -1 ), NULL, 0, 0, 0, TRUE },
275  { "/bin/netstat", "-in", SC( -1 ), NULL, 0, 0, 0, TRUE },
276  { "/usr/etc/netstat", "-in", SC( -1 ), NULL, 0, 0, 0, FALSE },
277 #ifndef __SCO_VERSION__
278  { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.7.1.0", SC( -1 ), NULL, 0, 0, 0, FALSE }, /* UDP in */
279  { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.7.4.0", SC( -1 ), NULL, 0, 0, 0, FALSE }, /* UDP out */
280  { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.4.3.0", SC( -1 ), NULL, 0, 0, 0, FALSE }, /* IP ? */
281  { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.6.10.0", SC( -1 ), NULL, 0, 0, 0, FALSE }, /* TCP ? */
282  { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.6.11.0", SC( -1 ), NULL, 0, 0, 0, FALSE }, /* TCP ? */
283  { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.6.13.0", SC( -1 ), NULL, 0, 0, 0, FALSE }, /* TCP ? */
284 #else
285  { "/usr/sbin/snmpstat", "-an localhost public", SC( SC_0 ), NULL, 0, 0, 0, FALSE },
286  { "/usr/sbin/snmpstat", "-in localhost public", SC( SC_0 ), NULL, 0, 0, 0, FALSE }, /* Subset of netstat info */
287  { "/usr/sbin/snmpstat", "-Sn localhost public", SC( SC_0 ), NULL, 0, 0, 0, FALSE },
288 #endif /* SCO/UnixWare vs.everything else */
289  { "/usr/bin/smartctl", "-A /dev/hda" , SC( 1 ), NULL, 0, 0, 0, FALSE },
290  { "/usr/bin/smartctl", "-A /dev/hdb" , SC( 1 ), NULL, 0, 0, 0, FALSE },
291  { "/usr/bin/mpstat", NULL, SC( 1 ), NULL, 0, 0, 0, FALSE },
292  { "/usr/bin/w", NULL, SC( 1 ), NULL, 0, 0, 0, TRUE },
293  { "/usr/bsd/w", NULL, SC( 1 ), NULL, 0, 0, 0, FALSE },
294  { "/usr/bin/df", NULL, SC( 1 ), NULL, 0, 0, 0, TRUE },
295  { "/bin/df", NULL, SC( 1 ), NULL, 0, 0, 0, FALSE },
296  { "/usr/sbin/portstat", NULL, SC( 1 ), NULL, 0, 0, 0, FALSE },
297  { "/usr/bin/iostat", NULL, SC( SC_0 ), NULL, 0, 0, 0, FALSE },
298  { "/usr/bin/uptime", NULL, SC( SC_0 ), NULL, 0, 0, 0, TRUE },
299  { "/usr/bsd/uptime", NULL, SC( SC_0 ), NULL, 0, 0, 0, FALSE },
300  { "/usr/bin/vmstat", "-f", SC( SC_0 ), NULL, 0, 0, 0, TRUE },
301  { "/bin/vmstat", "-f", SC( SC_0 ), NULL, 0, 0, 0, TRUE },
302  { "/usr/ucb/netstat", "-n", SC( 0.5 ), NULL, 0, 0, 0, TRUE },
303  { "/usr/bin/netstat", "-n", SC( 0.5 ), NULL, 0, 0, 0, TRUE },
304  { "/usr/sbin/netstat", "-n", SC( 0.5 ), NULL, 0, 0, 0, TRUE },
305  { "/bin/netstat", "-n", SC( 0.5 ), NULL, 0, 0, 0, TRUE },
306  { "/usr/etc/netstat", "-n", SC( 0.5 ), NULL, 0, 0, 0, FALSE },
307 
308  /* End-of-lightweight-sources section marker */
309  { "", NULL, SC( SC_0 ), NULL, 0, 0, 0, FALSE },
310 
311  /* Potentially heavyweight or low-value sources that are only polled if
312  alternative sources aren't available. ntptrace is somewhat
313  problematic in that some versions don't support -r and -t, made worse
314  by the fact that various servers in the commonly-used pool.ntp.org
315  cluster refuse to answer ntptrace. As a result, using this can hang
316  for quite awhile before it times out, so we treat it as a heavyweight
317  source even though in theory it's a nice high-entropy lightweight
318  one */
319  { "/usr/sbin/ntptrace", "-r2 -t1 -nv", SC( -1 ), NULL, 0, 0, 0, FALSE },
320 #if defined( __sgi ) || defined( __hpux )
321  { "/bin/ps", "-el", SC( 0.3 ), NULL, 0, 0, 0, TRUE },
322 #endif /* SGI || PHUX */
323  { "/usr/ucb/ps", "aux", SC( 0.3 ), NULL, 0, 0, 0, TRUE },
324  { "/usr/bin/ps", "aux", SC( 0.3 ), NULL, 0, 0, 0, TRUE },
325  { "/bin/ps", "aux", SC( 0.3 ), NULL, 0, 0, 0, FALSE },
326  { "/usr/bin/ipcs", "-a", SC( 0.5 ), NULL, 0, 0, 0, TRUE },
327  { "/bin/ipcs", "-a", SC( 0.5 ), NULL, 0, 0, 0, FALSE },
328  /* Unreliable source, depends on system usage */
329  { "/etc/pstat", "-p", SC( 0.5 ), NULL, 0, 0, 0, TRUE },
330  { "/bin/pstat", "-p", SC( 0.5 ), NULL, 0, 0, 0, FALSE },
331  { "/etc/pstat", "-S", SC( 0.2 ), NULL, 0, 0, 0, TRUE },
332  { "/bin/pstat", "-S", SC( 0.2 ), NULL, 0, 0, 0, FALSE },
333  { "/etc/pstat", "-v", SC( 0.2 ), NULL, 0, 0, 0, TRUE },
334  { "/bin/pstat", "-v", SC( 0.2 ), NULL, 0, 0, 0, FALSE },
335  { "/etc/pstat", "-x", SC( 0.2 ), NULL, 0, 0, 0, TRUE },
336  { "/bin/pstat", "-x", SC( 0.2 ), NULL, 0, 0, 0, FALSE },
337  { "/etc/pstat", "-t", SC( 0.1 ), NULL, 0, 0, 0, TRUE },
338  { "/bin/pstat", "-t", SC( 0.1 ), NULL, 0, 0, 0, FALSE },
339  /* pstat is your friend */
340 #ifndef __SCO_VERSION__
341  { "/usr/sbin/sar", "-AR", SC( 0.05 ), NULL, 0, 0, 0, FALSE }, /* Only updated hourly */
342 #endif /* SCO/UnixWare */
343  { "/usr/bin/last", "-n 50", SC( 0.3 ), NULL, 0, 0, 0, TRUE },
344 #ifdef __sgi
345  { "/usr/bsd/last", "-50", SC( 0.3 ), NULL, 0, 0, 0, FALSE },
346 #endif /* SGI */
347 #ifdef __hpux
348  { "/etc/last", "-50", SC( 0.3 ), NULL, 0, 0, 0, FALSE },
349 #endif /* PHUX */
350  { "/usr/bsd/last", "-n 50", SC( 0.3 ), NULL, 0, 0, 0, FALSE },
351 #ifdef sun
352  { "/usr/bin/showrev", "-a", SC( 0.1 ), NULL, 0, 0, 0, FALSE },
353  { "/usr/sbin/swap", "-l", SC( SC_0 ), NULL, 0, 0, 0, FALSE },
354  { "/usr/sbin/prtconf", "-v", SC( SC_0 ), NULL, 0, 0, 0, FALSE },
355 #endif /* SunOS/Slowaris */
356  { "/usr/sbin/psrinfo", NULL, SC( SC_0 ), NULL, 0, 0, 0, FALSE },
357  { "/usr/bin/lsof", "-blnwP", SC( 0.3 ), NULL, 0, 0, 0, TRUE },
358  { "/usr/local/bin/lsof", "-blnwP", SC( 0.3 ), NULL, 0, 0, 0, FALSE },
359  /* Output is very system and version-dependent
360  and can also be extremely voluminous */
361  { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.5.1.0", SC( 0.1 ), NULL, 0, 0, 0, FALSE }, /* ICMP ? */
362  { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.5.3.0", SC( 0.1 ), NULL, 0, 0, 0, FALSE }, /* ICMP ? */
363  { "/etc/arp", "-a", SC( 0.1 ), NULL, 0, 0, 0, TRUE },
364  { "/usr/etc/arp", "-a", SC( 0.1 ), NULL, 0, 0, 0, TRUE },
365  { "/usr/bin/arp", "-a", SC( 0.1 ), NULL, 0, 0, 0, TRUE },
366  { "/usr/sbin/arp", "-a", SC( 0.1 ), NULL, 0, 0, 0, FALSE },
367  { "/usr/sbin/ripquery", "-nw 1 127.0.0.1", SC( 0.1 ), NULL, 0, 0, 0, FALSE },
368  { "/bin/lpstat", "-t", SC( 0.1 ), NULL, 0, 0, 0, TRUE },
369  { "/usr/bin/lpstat", "-t", SC( 0.1 ), NULL, 0, 0, 0, TRUE },
370  { "/usr/ucb/lpstat", "-t", SC( 0.1 ), NULL, 0, 0, 0, FALSE },
371  { "/usr/bin/tcpdump", "-c 5 -efvvx", SC( 1 ), NULL, 0, 0, 0, FALSE },
372  /* This is very environment-dependant. If
373  network traffic is low, it'll probably time
374  out before delivering 5 packets, which is OK
375  because it'll probably be fixed stuff like ARP
376  anyway */
377  { "/usr/sbin/advfsstat", "-b usr_domain", SC( SC_0 ), NULL, 0, 0, 0, FALSE },
378  { "/usr/sbin/advfsstat", "-l 2 usr_domain", SC( 0.5 ), NULL, 0, 0, 0, FALSE },
379  { "/usr/sbin/advfsstat", "-p usr_domain", SC( SC_0 ), NULL, 0, 0, 0, FALSE },
380  /* This is a complex and screwball program. Some
381  systems have things like rX_dmn, x = integer,
382  for RAID systems, but the statistics are
383  pretty dodgy */
384 #if 0
385  /* The following aren't enabled since they're somewhat slow and not very
386  unpredictable, however they give an indication of the sort of sources
387  you can use (for example the finger might be more useful on a
388  firewalled internal network) */
389  { "/usr/bin/finger", "@ml.media.mit.edu", SC( 0.9 ), NULL, 0, 0, 0, FALSE },
390  { "/usr/local/bin/wget", "-O - http://lavarand.sgi.com/block.html", SC( 0.9 ), NULL, 0, 0, 0, FALSE },
391  { "/bin/cat", "/usr/spool/mqueue/syslog", SC( 0.9 ), NULL, 0, 0, 0, FALSE },
392 #endif /* 0 */
393 
394  /* End-of-sources marker */
395  { NULL, NULL, 0, NULL, 0, 0, 0, FALSE },
396  { NULL, NULL, 0, NULL, 0, 0, 0, FALSE }
397  };
398 
399 /* Variables to manage the child process that fills the buffer */
400 
401 static pid_t gathererProcess = 0;/* The child process that fills the buffer */
402 static BYTE *gathererBuffer; /* Shared buffer for gathering random noise */
403 static int gathererMemID; /* ID for shared memory */
404 static int gathererBufSize; /* Size of the shared memory buffer */
405 static struct sigaction gathererOldHandler; /* Previous signal handler */
406 #ifdef USE_THREADS
407  static pthread_mutex_t gathererMutex; /* Mutex to protect the polling */
408 #endif /* USE_THREADS */
409 
410 /* The struct at the start of the shared memory buffer used to communicate
411  information from the child to the parent */
412 
413 typedef struct {
414  int usefulness; /* Usefulness of data in buffer */
415  int noBytes; /* No.of bytes in buffer */
416  } GATHERER_INFO;
417 
418 /****************************************************************************
419 * *
420 * Utility Functions *
421 * *
422 ****************************************************************************/
423 
424 #if defined( __hpux ) && ( OSVERSION == 9 )
425 
426 /* PHUX 9.x doesn't support getrusage in libc (wonderful...) */
427 
428 #include <syscall.h>
429 
431 static int getrusage( int who, OUT struct rusage *rusage )
432  {
433  return( syscall( SYS_getrusage, who, rusage ) );
434  }
435 #endif /* __hpux */
436 
437 #if defined( __MVS__ ) || defined( __hpux )
438 
439 /* MVS USS and PHUX don't have wait4() so we emulate it with waitpid() and
440  getrusage() */
441 
442 CHECK_RETVAL STDC_NONNULL_ARG( ( 2, 4 ) ) \
443 pid_t wait4( pid_t pid, OUT int *status, int options,
444  OUT struct rusage *rusage )
445  {
446  const pid_t waitPid = waitpid( pid, status, options );
447 
448  getrusage( RUSAGE_CHILDREN, rusage );
449  return( waitPid );
450  }
451 #endif /* MVS || PHUX */
452 
453 /* Cray Unicos and QNX 4.x have neither wait4() nor getrusage, so we fake
454  it */
455 
456 #if defined( _CRAY ) || ( defined( __QNX__ ) && OSVERSION <= 4 )
457 
458 CHECK_RETVAL STDC_NONNULL_ARG( ( 2, 4 ) ) \
459 pid_t wait4( pid_t pid, OUT int *status, int options,
460  OUT struct rusage *rusage )
461  {
462  return( waitpid( pid, status, options ) );
463  }
464 #endif /* Cray Unicos || QNX 4.x */
465 
466 /* Under SunOS 4.x popen() doesn't record the pid of the child process. When
467  pclose() is called, instead of calling waitpid() for the correct child, it
468  calls wait() repeatedly until the right child is reaped. The problem whit
469  this behaviour is that this reaps any other children that happen to have
470  died at that moment, and when their pclose() comes along, the process hangs
471  forever.
472 
473  This behaviour may be related to older SVR3-compatible SIGCLD handling in
474  which, under the SIG_IGN disposition, the status of the child was discarded
475  (i.e. no zombies were generated) so that when the parent called wait() it
476  would block until all children terminated, whereupon wait() would return -1
477  with errno set to ECHILD.
478 
479  The fix for this problem is to use a wrapper for popen()/pclose() that
480  saves the pid in the dataSources structure (code adapted from GNU-libc's
481  popen() call). Doing our own popen() has other advantages as well, for
482  example we use the more secure execl() to run the child instead of the
483  dangerous system().
484 
485  Aut viam inveniam aut faciam */
486 
488 static FILE *my_popen( INOUT DATA_SOURCE_INFO *entry )
489  {
490  int pipedes[ 2 + 8 ];
491  FILE *stream;
492 
493  /* Sanity check for stdin and stdout */
494  REQUIRES_N( STDIN_FILENO <= 1 && STDOUT_FILENO <= 1 );
495 
496  /* Create the pipe. Note that under QNX the pipe resource manager
497  'pipe' must be running in order to use pipes */
498  if( pipe( pipedes ) < 0 )
499  return( NULL );
500 
501  /* Fork off the child ("vfork() is like an OS orgasm. All OSes want to
502  do it, but most just end up faking it" - Chris Wedgwood). If your OS
503  supports it, you should try and use vfork() here because it's rather
504  more efficient and has guaranteed copy-on-write semantics that prevent
505  cryptlib object data from being copied to the child. Many modern
506  Unixen use COW for forks anyway (e.g. Linux, for which vfork() is just
507  an alias for fork()), so we get most of the benefits of vfork() with a
508  plain fork(), however there's another problem with fork that isn't
509  fixed by COW. Any large program, when forked, requires (at least
510  temporarily) a lot of address space. That is, when the process is
511  forked the system needs to allocate many virtual pages (backing store)
512  even if those pages are never used. If the system doesn't have enough
513  swap space available to support this, the fork() will fail when the
514  system tries to reserver backing store for pages that are never
515  touched. Even in non-large processes this can cause problems when (as
516  with the randomness-gatherer) many children are forked at once.
517 
518  In the absence of threads the use of pcreate() (which only requires
519  backing store for the new processes' stack, not the entire process)
520  would do the trick, however pcreate() isn't compatible with threads,
521  which makes it of little use for the default thread-enabled cryptlib
522  build
523 
524  Although OSF/1 has vfork(), it has nasty interactions with threading
525  and can cause other problems with handling of children, so we don't
526  use it */
527 #ifdef HAS_VFORK
528  entry->pid = vfork();
529 #else
530  entry->pid = fork();
531 #endif /* Unixen that have vfork() */
532  if( entry->pid == ( pid_t ) -1 )
533  {
534  /* The fork failed */
535  close( pipedes[ 0 ] );
536  close( pipedes[ 1 ] );
537  return( NULL );
538  }
539 
540  if( entry->pid == ( pid_t ) 0 )
541  {
542  int fd;
543 
544  /* We are the child, connect the read side of the pipe to stdout and
545  unplug stdin and stderr */
546  if( dup2( pipedes[ STDOUT_FILENO ], STDOUT_FILENO ) < 0 )
547  exit( 127 );
548  if( ( fd = open( "/dev/null", O_RDWR ) ) > 0 )
549  {
550  dup2( fd, STDIN_FILENO );
551  dup2( fd, STDERR_FILENO );
552  close( fd );
553  }
554 
555  /* If we're root, give up our permissions to make sure that we don't
556  inadvertently read anything sensitive. If the getpwnam() fails
557  (this can happen if we're chrooted with no "nobody" entry in the
558  local passwd file) we default to -1, which is usually nobody.
559  The newer setreXid() and setresXid() calls use a parameter value
560  of -1 to indicate "don't change this value" so this isn't
561  possible any longer, but then there's not really much else that
562  we can do at this point.
563 
564  We don't check whether the change succeeds since it's not a major
565  security problem but just a precaution */
566  if( geteuid() == 0 )
567  {
568  static uid_t gathererUID = ( uid_t ) -1, gathererGID = ( uid_t ) -1;
569 
570  if( gathererUID == ( uid_t ) -1 )
571  {
572  struct passwd *passwd;
573 
574  passwd = getpwnam( "nobody" );
575  if( passwd != NULL )
576  {
577  gathererUID = passwd->pw_uid;
578  gathererGID = passwd->pw_gid;
579  }
580  else
581  {
582  assert( DEBUG_WARN );
583  }
584  }
585  if( gathererUID != ( uid_t ) -1 )
586  {
587 #if 0 /* Not available on some OSes */
588  ( void ) setuid( gathererUID );
589  ( void ) seteuid( gathererUID );
590  ( void ) setgid( gathererGID );
591  ( void ) setegid( gathererGID );
592 #else
593  #if( defined( __linux__ ) || ( defined( __FreeBSD__ ) && OSVERSION >= 5 ) || \
594  ( defined( __hpux ) && OSVERSION >= 11 ) )
595  ( void ) setresuid( gathererUID, gathererUID, gathererUID );
596  ( void ) setresgid( gathererGID, gathererGID, gathererGID );
597  #else
598  ( void ) setreuid( gathererUID, gathererUID );
599  ( void ) setregid( gathererGID, gathererGID );
600  #endif /* OSses with setresXid() */
601 #endif /* 0 */
602  }
603  }
604 
605  /* Close the pipe descriptors */
606  close( pipedes[ STDIN_FILENO ] );
607  close( pipedes[ STDOUT_FILENO ] );
608 
609  /* Try and exec the program */
610  execl( entry->path, entry->path, entry->arg, NULL );
611 
612  /* Die if the exec failed. Since vfork() doesn't duplicate the stdio
613  buffers (or anything else for that matter), we have to use _exit()
614  rather than exit() to ensure that the shutdown actions don't upset
615  the parent's state */
616 #ifdef HAS_VFORK
617  _exit( 127 );
618 #else
619  exit( 127 );
620 #endif /* Unixen that have vfork() */
621  }
622 
623  /* We are the parent. Close the irrelevant side of the pipe and open the
624  relevant side as a new stream. Mark our side of the pipe to close on
625  exec, so new children won't see it */
626  close( pipedes[ STDOUT_FILENO ] );
627  fcntl( pipedes[ STDIN_FILENO ], F_SETFD, FD_CLOEXEC );
628  stream = fdopen( pipedes[ STDIN_FILENO ], "r" );
629  if( stream == NULL )
630  {
631  int savedErrno = errno;
632 
633  /* The stream couldn't be opened or the child structure couldn't be
634  allocated. Kill the child and close the other side of the pipe */
635  kill( entry->pid, SIGKILL );
636  close( pipedes[ STDOUT_FILENO ] );
637  waitpid( entry->pid, NULL, 0 );
638  entry->pid = 0;
639  errno = savedErrno;
640  return( NULL );
641  }
642 
643  return( stream );
644  }
645 
647 static int my_pclose( INOUT DATA_SOURCE_INFO *entry,
648  INOUT struct rusage *rusage )
649  {
650  pid_t pid;
651  int iterationCount = 0, status = 0;
652 
653  /* Close the pipe */
654  fclose( entry->pipe );
655  entry->pipe = NULL;
656 
657  /* Wait for the child to terminate, ignoring the return value from the
658  process because some programs return funny values that would result
659  in the input being discarded even if they executed successfully.
660  This isn't a problem because the result data size threshold will
661  filter out any programs that exit with a usage message without
662  producing useful output */
663  do
664  {
665  /* We use wait4() instead of waitpid() to get the last bit of
666  entropy data, the resource usage of the child */
667  pid = wait4( entry->pid, NULL, 0, rusage );
668  }
669  while( pid == -1 && errno == EINTR && \
670  iterationCount++ < FAILSAFE_ITERATIONS_MED );
671  if( pid != entry->pid )
672  status = -1;
673  entry->pid = 0;
674  return( status );
675  }
676 
677 /****************************************************************************
678 * *
679 * Fast Poll *
680 * *
681 ****************************************************************************/
682 
683 /* Fast poll - not terribly useful. SCO has a gettimeofday() prototype but
684  no actual system call that implements it, and no getrusage() at all, so
685  we use times() instead */
686 
687 #if defined( _CRAY ) || defined( _M_XENIX )
688  #include <sys/times.h>
689 #endif /* Systems without getrusage() */
690 
691 void fastPoll( void )
692  {
693  RANDOM_STATE randomState;
694  BYTE buffer[ RANDOM_BUFSIZE + 8 ];
695 #if !( defined( _CRAY ) || defined( _M_XENIX ) )
696  struct timeval tv;
697  #if !( defined( __QNX__ ) && OSVERSION <= 4 )
698  struct rusage rusage;
699  #endif /* !QNX 4.x */
700 #else
701  struct tms tms;
702 #endif /* Systems without getrusage() */
703 #ifdef _AIX
704  timebasestruct_t cpuClockInfo;
705 #endif /* Aches */
706 #if ( defined( sun ) && ( OSVERSION >= 5 ) )
707  hrtime_t hrTime;
708 #endif /* Slowaris */
709 #if ( defined( __QNX__ ) && OSVERSION >= 5 )
710  uint64_t clockCycles;
711 #endif /* QNX */
712 #if defined( _POSIX_TIMERS ) && ( _POSIX_TIMERS > 0 ) && 0 /* See below */
713  struct timespec timeSpec;
714 #endif /* _POSIX_TIMERS > 0 */
715  int status;
716 
717  status = initRandomData( randomState, buffer, RANDOM_BUFSIZE );
718  ENSURES_V( cryptStatusOK( status ) );
719 
720  /* Mix in the process ID. This doesn't change per process but will
721  change if the process forks, ensuring that the parent and child data
722  differs from the parent */
723  addRandomValue( randomState, getpid() );
724 
725 #if !( defined( _CRAY ) || defined( _M_XENIX ) )
726  gettimeofday( &tv, NULL );
727  addRandomValue( randomState, tv.tv_sec );
728  addRandomValue( randomState, tv.tv_usec );
729 
730  /* SunOS 5.4 has the function call but no prototypes for it, if you're
731  compiling this under 5.4 you'll have to copy the header files from 5.5
732  or something similar */
733  #if !( defined( __QNX__ ) && OSVERSION <= 4 )
734  getrusage( RUSAGE_SELF, &rusage );
735  addRandomData( randomState, &rusage, sizeof( struct rusage ) );
736  #endif /* !QNX 4.x */
737 #else
738  /* Merely a subset of getrusage(), but it's the best that we can do. On
739  Crays it provides access to the hardware clock, so the data is quite
740  good */
741  times( &tms );
742  addRandomData( randomState, &tms, sizeof( struct tms ) );
743 #endif /* Systems without getrusage() */
744 #ifdef _AIX
745  /* Add the value of the nanosecond-level CPU clock or time base register */
746  read_real_time( &cpuClockInfo, sizeof( timebasestruct_t ) );
747  addRandomData( randomState, &cpuClockInfo, sizeof( timebasestruct_t ) );
748 #endif /* _AIX */
749 #if ( defined( sun ) && ( OSVERSION >= 5 ) )
750  /* Read the Sparc %tick register (equivalent to the P5 TSC). This is
751  only readable by the kernel by default, although Solaris 8 and newer
752  make it readable in user-space. To do this portably, we use
753  gethrtime(), which does the same thing */
754  hrTime = gethrtime();
755  addRandomData( randomState, &hrTime, sizeof( hrtime_t ) );
756 #endif /* Slowaris */
757 #ifdef rdtscl
758  if( getSysCaps() & SYSCAP_FLAG_RDTSC )
759  {
760  unsigned long tscValue;
761 
762  rdtscl( tscValue );
763  addRandomValue( randomState, tscValue );
764  }
765 #endif /* rdtsc available */
766 #if ( defined( __QNX__ ) && OSVERSION >= 5 )
767  /* Return the output of RDTSC or its equivalent on other systems. We
768  don't worry about locking the thread to a CPU since we're not using
769  it for timing (in fact being run on another CPU helps the entropy) */
770  clockCycles = ClockCycles();
771  addRandomData( randomState, &clockCycles, sizeof( uint64_t ) );
772 #endif /* QNX */
773  /* Get real-time (or as close to it as possible) clock information if
774  it's available. These values are platform-specific, but typically use
775  a high-resolution source like the Pentium TSC.
776 
777  (Unfortunately we can't safely use this function because it's often
778  not present in libc but needs to be pulled in via the real-time
779  extensions library librt instead, which causes all sorts of
780  portability problems) */
781 #if defined( _POSIX_TIMERS ) && ( _POSIX_TIMERS > 0 ) && 0
782  if( clock_gettime( CLOCK_REALTIME, &timeSpec ) == 0 )
783  addRandomData( randomState, &timeSpec, sizeof( struct timespec ) );
784  if( clock_gettime( CLOCK_PROCESS_CPUTIME_ID, &timeSpec ) == 0 )
785  addRandomData( randomState, &timeSpec, sizeof( struct timespec ) );
786  if( clock_gettime( CLOCK_THREAD_CPUTIME_ID, &timeSpec ) == 0 )
787  addRandomData( randomState, &timeSpec, sizeof( struct timespec ) );
788 #endif /* _POSIX_TIMERS > 0 */
789 
790  /* Flush any remaining data through */
791  endRandomData( randomState, 0 );
792  }
793 
794 /****************************************************************************
795 * *
796 * Slow Poll *
797 * *
798 ****************************************************************************/
799 
800 /* Slowaris-specific slow poll using kstat, which provides kernel statistics.
801  Since there can be a hundred or more of these, we use a larger-than-usual
802  intermediate buffer to cut down on kernel traffic.
803 
804  Unfortunately Slowaris is the only OS that provides this interface, some
805  of the *BSDs have kenv, but this just returns fixed information like PCI
806  bus device addresses and so on, and isn't useful for providing entropy */
807 
808 #if ( defined( sun ) && ( OSVERSION >= 5 ) )
809 
810 #define USE_KSTAT
811 #include <kstat.h>
812 
813 #define BIG_RANDOM_BUFSIZE ( RANDOM_BUFSIZE * 2 )
814 
815 CHECK_RETVAL \
816 static int getKstatData( void )
817  {
818  kstat_ctl_t *kc;
819  kstat_t *ksp;
820  RANDOM_STATE randomState;
822  int noEntries = 0, quality;
823 
824  /* Try and open a kernel stats handle */
825  if( ( kc = kstat_open() ) == NULL )
826  return( FALSE );
827 
828  initRandomData( randomState, buffer, BIG_RANDOM_BUFSIZE );
829 
830  /* Walk down the chain of stats reading each one. Since some of the
831  stats can be rather lengthy, we optionally send them directly to
832  the randomness pool rather than using the accumulator */
833  for( ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next )
834  {
835  if( kstat_read( kc, ksp, NULL ) == -1 || \
836  ksp->ks_data_size <= 0 )
837  continue;
838  addRandomData( randomState, ksp, sizeof( kstat_t ) );
839  if( ksp->ks_data_size > BIG_RANDOM_BUFSIZE )
840  {
842 
843  setMessageData( &msgData, ksp->ks_data, ksp->ks_data_size );
845  &msgData, CRYPT_IATTRIBUTE_ENTROPY );
846  }
847  else
848  addRandomData( randomState, ksp->ks_data, ksp->ks_data_size );
849  noEntries++;
850  }
851  kstat_close( kc );
852 
853  /* Flush any remaining data through and produce an estimate of its
854  value. We require that we get at least 50 entries and give them a
855  maximum value of 35 to ensure that some data is still coming from
856  other sources */
857  quality = ( noEntries > 50 ) ? 35 : 0;
858  endRandomData( randomState, quality );
859 
860  return( quality );
861  }
862 #endif /* Slowaris */
863 
864 /* SYSV /proc interface, which provides assorted information that usually
865  has to be obtained the hard way via a slow poll.
866 
867  Note that getProcData() gets data from the legacy /proc pseudo-filesystem
868  using ioctls() whereas getProcFSdata()gets data from the current /procfs
869  filesystem using file reads */
870 
871 #if ( defined( sun ) && ( OSVERSION >= 5 ) ) || defined( __osf__ ) || \
872  defined( __alpha__ ) || defined( __linux__ )
873 
874 #define USE_PROC
875 #include <sys/procfs.h>
876 
877 CHECK_RETVAL \
878 static int getProcData( void )
879  {
880 #ifdef PIOCSTATUS
881  prstatus_t prStatus;
882 #endif /* PIOCSTATUS */
883 #ifdef PIOCPSINFO
884  prpsinfo_t prMisc;
885 #endif /* PIOCPSINFO */
886 #ifdef PIOCUSAGE
887  prusage_t prUsage;
888 #endif /* PIOCUSAGE */
889 #ifdef PIOCACINFO
890  struct pracinfo pracInfo;
891 #endif /* PIOCACINFO */
892 
893  RANDOM_STATE randomState;
894  BYTE buffer[ RANDOM_BUFSIZE + 8 ];
895  char fileName[ 128 + 8 ];
896  int fd, noEntries = 0, quality, status;
897 
898  /* Try and open the process info for this process. We don't use
899  O_NOFOLLOW because on some Unixen special files can be symlinks and
900  in any case a system that allows attackers to mess with privileged
901  filesystems like this is presumably a goner anyway */
902  sprintf_s( fileName, 128, "/proc/%d", getpid() );
903  if( ( fd = open( fileName, O_RDONLY ) ) == -1 )
904  return( 0 );
905  if( fd <= 2 )
906  {
907  /* We've been given a standard I/O handle, something's wrong */
908  close( fd );
909  return( 0 );
910  }
911 
912  status = initRandomData( randomState, buffer, RANDOM_BUFSIZE );
913  ENSURES_EXT( cryptStatusOK( status ), 0 );
914 
915  /* Get the process status information, misc information, and resource
916  usage */
917 #ifdef PIOCSTATUS
918  if( ioctl( fd, PIOCSTATUS, &prStatus ) != -1 )
919  {
920 #ifdef DEBUG_RANDOM
921  printf( __FILE__ ": PIOCSTATUS contributed %d bytes.\n",
922  sizeof( prstatus_t ) );
923 #endif /* DEBUG_RANDOM */
924  addRandomData( randomState, &prStatus, sizeof( prstatus_t ) );
925  noEntries++;
926  }
927 #endif /* PIOCSTATUS */
928 #ifdef PIOCPSINFO
929  if( ioctl( fd, PIOCPSINFO, &prMisc ) != -1 )
930  {
931 #ifdef DEBUG_RANDOM
932  printf( __FILE__ ": PIOCPSINFO contributed %d bytes.\n",
933  sizeof( prpsinfo_t ) );
934 #endif /* DEBUG_RANDOM */
935  addRandomData( randomState, &prMisc, sizeof( prpsinfo_t ) );
936  noEntries++;
937  }
938 #endif /* PIOCPSINFO */
939 #ifdef PIOCUSAGE
940  if( ioctl( fd, PIOCUSAGE, &prUsage ) != -1 )
941  {
942 #ifdef DEBUG_RANDOM
943  printf( __FILE__ ": PIOCUSAGE contributed %d bytes.\n",
944  sizeof( prusage_t ) );
945 #endif /* DEBUG_RANDOM */
946  addRandomData( randomState, &prUsage, sizeof( prusage_t ) );
947  noEntries++;
948  }
949 #endif /* PIOCUSAGE */
950 
951 #ifdef PIOCACINFO
952  if( ioctl( fd, PIOCACINFO, &pracInfo ) != -1 )
953  {
954 #ifdef DEBUG_RANDOM
955  printf( __FILE__ ": PIOCACINFO contributed %d bytes.\n",
956  sizeof( struct pracinfo ) );
957 #endif /* DEBUG_RANDOM */
958  addRandomData( randomState, &pracInfo, sizeof( struct pracinfo ) );
959  noEntries++;
960  }
961 #endif /* PIOCACINFO */
962  close( fd );
963 
964  /* Flush any remaining data through and produce an estimate of its
965  value. We require that at least two of the sources exist and accesses
966  to them succeed, and give them a relatively low value since they're
967  returning information that has some overlap with that returned by the
968  general slow poll (although there's also a lot of low-level stuff
969  present that the slow poll doesn't get) */
970  quality = ( noEntries > 2 ) ? 10 : 0;
971  endRandomData( randomState, quality );
972 
973  return( quality );
974  }
975 #endif /* Slowaris || OSF/1 || Linux */
976 
977 /* Named process information /procfs interface. Each source is given a
978  weighting of 1-3, with 1 being a static (although unpredictable) source,
979  2 being a slowly-changing source, and 3 being a rapidly-changing
980  source */
981 
982 CHECK_RETVAL \
983 static int getProcFSdata( void )
984  {
985  typedef struct {
986  const char *source;
987  const int value;
988  } PROCSOURCE_INFO;
989  static const PROCSOURCE_INFO procSources[] = {
990  { "/proc/diskstats", 2 }, { "/proc/interrupts", 3 },
991  { "/proc/loadavg", 2 }, { "/proc/locks", 1 },
992  { "/proc/meminfo", 3 }, { "/proc/net/dev", 2 },
993  { "/proc/net/ipx", 2 }, { "/proc/modules", 1 },
994  { "/proc/mounts", 1 }, { "/proc/net/netstat", 2 },
995  { "/proc/net/rt_cache", 1 }, { "/proc/net/rt_cache_stat", 3 },
996  { "/proc/net/snmp", 2 }, { "/proc/net/softnet_stat", 2 },
997  { "/proc/net/stat/arp_cache", 3 }, { "/proc/net/stat/ndisc_cache", 2 },
998  { "/proc/net/stat/rt_cache", 3 }, { "/proc/net/tcp", 3 },
999  { "/proc/net/udp", 2 }, { "/proc/net/wireless", 2 },
1000  { "/proc/slabinfo", 3 }, { "/proc/stat", 3 },
1001  { "/proc/sys/fs/inode-state", 1 }, { "/proc/sys/fs/file-nr", 1 },
1002  { "/proc/sys/fs/dentry-state", 1 }, { "/proc/sysvipc/msg", 1 },
1003  { "/proc/sysvipc/sem", 1 }, { "/proc/sysvipc/shm", 1 },
1004  { "/proc/zoneinfo", 3 },
1005  { "/sys/devices/system/node/node0/numastat", 2 },
1006  { NULL, 0 }, { NULL, 0 }
1007  };
1009  BYTE buffer[ 1024 + 8 ];
1010  int procIndex, procFD, procValue = 0, quality;
1011 
1012  /* Read the first 1K of data from some of the more useful sources (most
1013  of these produce far less than 1K output) */
1014  for( procIndex = 0;
1015  procSources[ procIndex ].source != NULL && \
1016  procIndex < FAILSAFE_ARRAYSIZE( procSources, PROCSOURCE_INFO );
1017  procIndex++ )
1018  {
1019  int count, status;
1020 
1021  /* Try and open the data source. We don't use O_NOFOLLOW because on
1022  some Unixen special files can be symlinks and in any case a
1023  system that allows attackers to mess with privileged filesystems
1024  like this is presumably a goner anyway */
1025  procFD = open( procSources[ procIndex ].source, O_RDONLY );
1026  if( procFD < 0 )
1027  continue;
1028  if( procFD <= 2 )
1029  {
1030  /* We've been given a standard I/O handle, something's wrong */
1031  close( procFD );
1032  return( 0 );
1033  }
1034 
1035  /* Read data from the source */
1036  count = read( procFD, buffer, 1024 );
1037  if( count > 16 )
1038  {
1039 #ifdef DEBUG_RANDOM
1040  printf( __FILE__ ": %s contributed %d bytes.\n",
1041  procSources[ procIndex ].source, count );
1042 #endif /* DEBUG_RANDOM */
1043  setMessageData( &msgData, buffer, count );
1045  IMESSAGE_SETATTRIBUTE_S, &msgData,
1046  CRYPT_IATTRIBUTE_ENTROPY );
1047  if( cryptStatusOK( status ) )
1048  procValue += procSources[ procIndex ].value;
1049  }
1050  close( procFD );
1051  }
1052  ENSURES( procIndex < FAILSAFE_ARRAYSIZE( procSources, PROCSOURCE_INFO ) );
1053  zeroise( buffer, 1024 );
1054  if( procValue < 5 )
1055  return( 0 );
1056 
1057  /* Produce an estimate of the data's value. We require that we get a
1058  quality value of at least 5 and limit it to a maximum value of 50 to
1059  ensure that some data is still coming from other sources */
1060  quality = min( procValue, 50 );
1062  ( MESSAGE_CAST ) &quality,
1063  CRYPT_IATTRIBUTE_ENTROPY_QUALITY );
1064  return( quality );
1065  }
1066 
1067 /* /dev/random interface */
1068 
1069 #define DEVRANDOM_BYTES 128
1070 
1071 CHECK_RETVAL \
1072 static int getDevRandomData( void )
1073  {
1075  BYTE buffer[ DEVRANDOM_BYTES + 8 ];
1076 #if defined( __APPLE__ ) || ( defined( __FreeBSD__ ) && OSVERSION >= 5 )
1077  static const int quality = 50; /* See comment below */
1078 #else
1079  static const int quality = 75;
1080 #endif /* Mac OS X || FreeBSD 5.x */
1081  int randFD, noBytes;
1082 
1083  /* Check whether there's a /dev/random present. We don't use O_NOFOLLOW
1084  because on some Unixen special files can be symlinks and in any case
1085  a system that allows attackers to mess with privileged filesystems
1086  like this is presumably a goner anyway */
1087  if( ( randFD = open( "/dev/urandom", O_RDONLY ) ) < 0 )
1088  return( 0 );
1089  if( randFD <= 2 )
1090  {
1091  /* We've been given a standard I/O handle, something's wrong */
1092  close( randFD );
1093  return( 0 );
1094  }
1095 
1096  /* Read data from /dev/urandom, which won't block (although the quality
1097  of the noise is arguably slighly less). We only assign this a 75%
1098  quality factor to ensure that we still get randomness from other
1099  sources as well. Under FreeBSD 5.x and OS X, the /dev/random
1100  implementation is broken, using a pretend dev-random implemented with
1101  Yarrow and a 160-bit pool (animi sub vulpe latent) so we only assign
1102  a 50% quality factor. These generators also lie about entropy, with
1103  both /random and /urandom being the same PRNG-based implementation.
1104  The AIX /dev/random isn't an original /dev/random either but merely
1105  provides a compatible interface, taking its input from interrupt
1106  timings of a very small number of sources such as ethernet and SCSI
1107  adapters and postprocessing them with Yarrow. This implementation is
1108  also a lot more conservative about its entropy estimation, such that
1109  the blocking interface blocks a lot more often than the original
1110  /dev/random implementation would. In addition it stops gathering
1111  entropy (from interrupts) when it thinks it has enough, and only
1112  resumes when the value falls below a certain value */
1113  noBytes = read( randFD, buffer, DEVRANDOM_BYTES );
1114  close( randFD );
1115  if( noBytes < 1 )
1116  {
1117 #ifdef DEBUG_RANDOM
1118  printf( __FILE__ ": /dev/random read failed.\n" );
1119 #endif /* DEBUG_RANDOM */
1120  return( 0 );
1121  }
1122 #ifdef DEBUG_RANDOM
1123  printf( __FILE__ ": /dev/random contributed %d bytes.\n", noBytes );
1124 #endif /* DEBUG_RANDOM */
1125  setMessageData( &msgData, buffer, noBytes );
1127  CRYPT_IATTRIBUTE_ENTROPY );
1128  zeroise( buffer, DEVRANDOM_BYTES );
1129  if( noBytes < DEVRANDOM_BYTES )
1130  return( 0 );
1132  ( MESSAGE_CAST ) &quality,
1133  CRYPT_IATTRIBUTE_ENTROPY_QUALITY );
1134  return( quality );
1135  }
1136 
1137 /* egd/prngd interface */
1138 
1139 CHECK_RETVAL \
1140 static int getEGDdata( void )
1141  {
1142  static const char *egdSources[] = {
1143  "/var/run/egd-pool", "/dev/egd-pool", "/etc/egd-pool", NULL, NULL };
1145  BYTE buffer[ DEVRANDOM_BYTES + 8 ];
1146  static const int quality = 75;
1147  int egdIndex, sockFD, noBytes = CRYPT_ERROR, status;
1148 
1149  /* Look for the egd/prngd output. We re-search each time because,
1150  unlike /dev/random, it's both a user-level process and a movable
1151  feast, so it can disappear and reappear at a different location
1152  between runs */
1153  sockFD = socket( AF_UNIX, SOCK_STREAM, 0 );
1154  if( sockFD < 0 )
1155  return( 0 );
1156  for( egdIndex = 0; egdSources[ egdIndex ] != NULL && \
1157  egdIndex < FAILSAFE_ARRAYSIZE( egdSources, char * );
1158  egdIndex++ )
1159  {
1160  struct sockaddr_un sockAddr;
1161 
1162  memset( &sockAddr, 0, sizeof( struct sockaddr_un ) );
1163  sockAddr.sun_family = AF_UNIX;
1164  strlcpy_s( sockAddr.sun_path, sizeof( sockAddr.sun_path ),
1165  egdSources[ egdIndex ] );
1166  if( connect( sockFD, ( struct sockaddr * ) &sockAddr,
1167  sizeof( struct sockaddr_un ) ) >= 0 )
1168  break;
1169  }
1170  ENSURES( egdIndex < FAILSAFE_ARRAYSIZE( egdSources, char * ) );
1171  if( egdSources[ egdIndex ] == NULL )
1172  {
1173  close( sockFD );
1174  return( 0 );
1175  }
1176 
1177  /* Read up to 128 bytes of data from the source:
1178  write: BYTE 1 = read data nonblocking
1179  BYTE DEVRANDOM_BYTES = count
1180  read: BYTE returned bytes
1181  BYTE[] data
1182  As with /dev/random we only assign this a 75% quality factor to
1183  ensure that we still get randomness from other sources as well */
1184  buffer[ 0 ] = 1;
1185  buffer[ 1 ] = DEVRANDOM_BYTES;
1186  status = write( sockFD, buffer, 2 );
1187  if( status == 2 )
1188  {
1189  status = read( sockFD, buffer, 1 );
1190  noBytes = buffer[ 0 ];
1191  if( status != 1 || noBytes < 0 || noBytes > DEVRANDOM_BYTES )
1192  status = -1;
1193  else
1194  status = read( sockFD, buffer, noBytes );
1195  }
1196  close( sockFD );
1197  if( ( status < 0 ) || ( status != noBytes ) )
1198  {
1199 #ifdef DEBUG_RANDOM
1200  printf( __FILE__ ": EGD (%s) read failed.\n", egdSources[ egdIndex ] );
1201 #endif /* DEBUG_RANDOM */
1202  return( 0 );
1203  }
1204 
1205  /* Send the data to the pool */
1206 #ifdef DEBUG_RANDOM
1207  printf( __FILE__ ": EGD (%s) contributed %d bytes.\n",
1208  egdSources[ egdIndex ], noBytes );
1209 #endif /* DEBUG_RANDOM */
1210  setMessageData( &msgData, buffer, noBytes );
1212  CRYPT_IATTRIBUTE_ENTROPY );
1213  zeroise( buffer, DEVRANDOM_BYTES );
1214  if( noBytes < DEVRANDOM_BYTES )
1215  return( 0 );
1217  ( MESSAGE_CAST ) &quality,
1218  CRYPT_IATTRIBUTE_ENTROPY_QUALITY );
1219  return( quality );
1220  }
1221 
1222 /* Get data from an entropy source */
1223 
1225 static int getEntropySourceData( INOUT DATA_SOURCE_INFO *dataSource,
1226  OUT_BUFFER( bufSize, *bufPos ) BYTE *bufPtr,
1227  IN_LENGTH const int bufSize,
1228  OUT_LENGTH int *bufPos )
1229  {
1230  int bufReadPos = 0, bufWritePos = 0;
1231  size_t noBytes;
1232 
1233  /* Try and get more data from the source. If we get zero bytes, the
1234  source has sent us all it has */
1235  if( ( noBytes = fread( bufPtr, 1, bufSize, dataSource->pipe ) ) <= 0 )
1236  {
1237  struct rusage rusage;
1238  int total = 0;
1239 
1240  /* If there's a problem, exit */
1241  if( my_pclose( dataSource, &rusage ) != 0 )
1242  return( 0 );
1243 
1244  /* Try and estimate how much entropy we're getting from a data
1245  source */
1246  if( dataSource->usefulness != 0 )
1247  {
1248  if( dataSource->usefulness < 0 )
1249  {
1250  /* Absolute rating, 1024 / -n */
1251  total = 1025 / -dataSource->usefulness;
1252  }
1253  else
1254  {
1255  /* Relative rating, 1024 * n */
1256  total = dataSource->length / dataSource->usefulness;
1257  }
1258  }
1259 #ifdef DEBUG_RANDOM
1260  printf( __FILE__ ": %s %s contributed %d bytes (compressed), "
1261  "usefulness = %d.\n", dataSource->path,
1262  ( dataSource->arg != NULL ) ? dataSource->arg : "",
1263  dataSource->length, total );
1264 #endif /* DEBUG_RANDOM */
1265 
1266  /* Copy in the last bit of entropy data, the resource usage of the
1267  popen()ed child */
1268  if( sizeof( struct rusage ) < bufSize )
1269  {
1270  memcpy( bufPtr, &rusage, sizeof( struct rusage ) );
1271  *bufPos += sizeof( struct rusage );
1272  }
1273 
1274  return( total );
1275  }
1276 
1277  /* Run-length compress the input byte sequence */
1278  while( bufReadPos < noBytes )
1279  {
1280  const int ch = byteToInt( bufPtr[ bufReadPos ] );
1281 
1282  /* If it's a single byte or we're at the end of the buffer, just
1283  copy it over */
1284  if( bufReadPos >= bufSize - 1 || ch != bufPtr[ bufReadPos + 1 ] )
1285  {
1286  bufPtr[ bufWritePos++ ] = ch;
1287  bufReadPos++;
1288  }
1289  else
1290  {
1291  int count = 0;
1292 
1293  /* It's a run of repeated bytes, replace them with the byte
1294  count mod 256 */
1295  while( bufReadPos < noBytes && ( ch == bufPtr[ bufReadPos ] ) )
1296  {
1297  count++;
1298  bufReadPos++;
1299  }
1300  bufPtr[ bufWritePos++ ] = count;
1301  }
1302  }
1303 
1304  /* Remember the number of (compressed) bytes of input that we obtained */
1305  *bufPos += bufWritePos;
1306  dataSource->length += noBytes;
1307 
1308  return( 0 );
1309  }
1310 
1311 /* The child process that performs the polling, forked from slowPoll() */
1312 
1313 #define SLOWPOLL_TIMEOUT 30 /* Time out after 30 seconds */
1314 
1315 static void childPollingProcess( const int existingEntropy )
1316  {
1317  GATHERER_INFO *gathererInfo;
1318  MONOTIMER_INFO timerInfo;
1319  BOOLEAN moreSources;
1320  struct timeval tv;
1321  struct rlimit rl = { 0, 0 };
1322  fd_set fds;
1323 #if defined( __hpux )
1324  size_t maxFD = 0;
1325 #else
1326  int maxFD = 0;
1327 #endif /* OS-specific brokenness */
1328  int usefulness = 0, fdIndex, bufPos, i, iterationCount, status;
1329 
1330  /* General housekeeping: Make sure that we can never dump core, and close
1331  all inherited file descriptors. We need to do this because if we
1332  don't and the calling app has FILE *'s open, these will be flushed
1333  when we call exit() in the child and again when the parent writes to
1334  them or closes them, resulting in everything that was present in the
1335  FILE * buffer at the time of the fork() being written twice. An
1336  alternative solution would be to call _exit() instead if exit() below,
1337  but this is somewhat system-dependant and therefore a bit risky to
1338  use. Note that we don't close any of the standard handles because
1339  this could lead to the next file being opened being given the stdin/
1340  stdout/stderr handle, which in general is just a nuisance but then
1341  some older kernels didn't check handles when running a setuid program
1342  so that it was actually an exploitable flaw. In addition some later
1343  kernels (e.g. NetBSD) overreact to the problem a bit and complain
1344  when they see a setuid program with stdin/stdout/stderr closed, so
1345  it's a good idea to leave these open. We could in theory close them
1346  anyway and reopen them to /dev/null, but it's not clear whether this
1347  really buys us anything.
1348 
1349  In addition to this we should in theory call cryptEnd() since we
1350  don't need any cryptlib objects beyond this point and it'd be a good
1351  idea to clean them up to get rid of sensitive data held in memory.
1352  However in some cases when using a crypto device or network interface
1353  or similar item the shutdown in the child will also shut down the
1354  parent item because while cryptlib objects are reference-counted the
1355  external items aren't (they're beyond the control of cryptlib). Even
1356  destroying just contexts with keys loaded isn't possible because they
1357  may be tied to a device that will propagate the shutdown from the
1358  child to the parent via the device.
1359 
1360  In general the child will be short-lived, and the use in its further
1361  children of vfork() or the fact that many modern fork()s have copy-on-
1362  write semantics even if no vfork() is available will mean that
1363  cryptlib memory is never copied to the child and further children. It
1364  would, however, be better if there were some way to perform a neutron-
1365  bomb type shutdown that only zeroises senstive information while
1366  leaving structures intact */
1367  setrlimit( RLIMIT_CORE, &rl );
1368  for( fdIndex = getdtablesize() - 1; fdIndex > STDOUT_FILENO; fdIndex-- )
1369  close( fdIndex );
1370  fclose( stderr ); /* Arrghh!! It's Stuart code!! */
1371 
1372  /* Fire up each randomness source */
1373  FD_ZERO( &fds );
1374  for( i = 0; dataSources[ i ].path != NULL && \
1375  i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO ); i++ )
1376  {
1377  /* Check for the end-of-lightweight-sources marker */
1378  if( dataSources[ i ].path[ 0 ] == '\0' )
1379  {
1380  /* If we're only polling lightweight sources because we've
1381  already obtained entropy from additional sources,we're
1382  done */
1383  if( existingEntropy >= 50 )
1384  {
1385 #ifdef DEBUG_RANDOM
1386  puts( __FILE__ ": All lightweight sources polled, exiting "
1387  "without polling\nheavyweight ones." );
1388 #endif /* DEBUG_RANDOM */
1389  break;
1390  }
1391 
1392  /* We're polling all sources, continue with the heavyweight
1393  ones */
1394  continue;
1395  }
1396 
1397  /* Since popen() is a fairly heavyweight function, we check to see
1398  whether the executable exists before we try to run it */
1399  if( access( dataSources[ i ].path, X_OK ) )
1400  {
1401 #ifdef DEBUG_RANDOM
1402  printf( __FILE__ ": %s not present%s.\n", dataSources[ i ].path,
1403  dataSources[ i ].hasAlternative ? \
1404  ", has alternatives" : "" );
1405 #endif /* DEBUG_RANDOM */
1406  dataSources[ i ].pipe = NULL;
1407  }
1408  else
1409  dataSources[ i ].pipe = my_popen( &dataSources[ i ] );
1410  if( dataSources[ i ].pipe == NULL )
1411  continue;
1412  if( fileno( dataSources[ i ].pipe ) >= FD_SETSIZE )
1413  {
1414  /* The fd is larger than what can be fitted into an fd_set, don't
1415  try and use it. This can happen if the calling app opens a
1416  large number of files, since most FD_SET() macros don't
1417  perform any safety checks this can cause segfaults and other
1418  problems if we don't perform the check ourselves */
1419  fclose( dataSources[ i ].pipe );
1420  dataSources[ i ].pipe = NULL;
1421  continue;
1422  }
1423 
1424  /* Set up the data source information */
1425  dataSources[ i ].pipeFD = fileno( dataSources[ i ].pipe );
1426  if( dataSources[ i ].pipeFD > maxFD )
1427  maxFD = dataSources[ i ].pipeFD;
1428  fcntl( dataSources[ i ].pipeFD, F_SETFL, O_NONBLOCK );
1429  FD_SET( dataSources[ i ].pipeFD, &fds );
1430  dataSources[ i ].length = 0;
1431 
1432  /* If there are alternatives for this command, don't try and execute
1433  them */
1434  iterationCount = 0;
1435  while( dataSources[ i ].path != NULL && \
1436  dataSources[ i ].hasAlternative && \
1437  i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO ) && \
1438  iterationCount++ < FAILSAFE_ITERATIONS_MED )
1439  {
1440 #ifdef DEBUG_RANDOM
1441  printf( __FILE__ ": Skipping %s.\n", dataSources[ i + 1 ].path );
1442 #endif /* DEBUG_RANDOM */
1443  i++;
1444  }
1445  ENSURES_EXIT( iterationCount < FAILSAFE_ITERATIONS_MED );
1446  /* i is checked as part of the loop control */
1447  }
1448  ENSURES_EXIT( i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO ) );
1449  gathererInfo = ( GATHERER_INFO * ) gathererBuffer;
1450  bufPos = sizeof( GATHERER_INFO ); /* Start of buf.has status info */
1451 
1452  /* Suck up all of the data that we can get from each of the sources */
1453  status = setMonoTimer( &timerInfo, SLOWPOLL_TIMEOUT );
1454  ENSURES_EXIT( cryptStatusOK( status ) );
1455  for( moreSources = TRUE, iterationCount = 0;
1456  moreSources && bufPos < gathererBufSize && \
1457  iterationCount < FAILSAFE_ITERATIONS_MAX;
1458  iterationCount++ )
1459  {
1460  /* Wait for data to become available from any of the sources, with a
1461  timeout of 10 seconds. This adds even more randomness since data
1462  becomes available in a nondeterministic fashion. Kudos to HP's QA
1463  department for managing to ship a select() that breaks its own
1464  prototype */
1465  tv.tv_sec = 10;
1466  tv.tv_usec = 0;
1467 #if defined( __hpux ) && ( OSVERSION == 9 || OSVERSION == 0 )
1468  if( select( maxFD + 1, ( int * ) &fds, NULL, NULL, &tv ) == -1 )
1469 #else
1470  if( select( maxFD + 1, &fds, NULL, NULL, &tv ) == -1 )
1471 #endif /* __hpux */
1472  break;
1473 
1474  /* One of the sources has data available, read it into the buffer */
1475  for( i = 0; dataSources[ i ].path != NULL && \
1476  i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO );
1477  i++ )
1478  {
1479  if( dataSources[ i ].pipe != NULL && \
1480  FD_ISSET( dataSources[ i ].pipeFD, &fds ) )
1481  usefulness += getEntropySourceData( &dataSources[ i ],
1482  gathererBuffer + bufPos,
1483  gathererBufSize - bufPos,
1484  &bufPos );
1485  }
1486  ENSURES_EXIT( i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO ) );
1487 
1488  /* Check if there's more input available on any of the sources */
1489  moreSources = FALSE;
1490  FD_ZERO( &fds );
1491  for( i = 0; dataSources[ i ].path != NULL && \
1492  i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO );
1493  i++ )
1494  {
1495  if( dataSources[ i ].pipe != NULL )
1496  {
1497  FD_SET( dataSources[ i ].pipeFD, &fds );
1498  moreSources = TRUE;
1499  }
1500  }
1501  ENSURES_EXIT( i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO ) );
1502 
1503  /* If we've gone over our time limit, kill anything still hanging
1504  around and exit. This prevents problems with input from blocked
1505  sources */
1506  if( checkMonoTimerExpired( &timerInfo ) )
1507  {
1508  for( i = 0; dataSources[ i ].path != NULL && \
1509  i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO );
1510  i++ )
1511  {
1512  if( dataSources[ i ].pipe != NULL )
1513  {
1514 #ifdef DEBUG_RANDOM
1515  printf( __FILE__ ": Aborting read of %s due to "
1516  "timeout.\n", dataSources[ i ].path );
1517 #endif /* DEBUG_RANDOM */
1518  fclose( dataSources[ i ].pipe );
1519  kill( dataSources[ i ].pid, SIGKILL );
1520  dataSources[ i ].pipe = NULL;
1521  dataSources[ i ].pid = 0;
1522  }
1523  }
1524  ENSURES_EXIT( i < FAILSAFE_ARRAYSIZE( dataSources, DATA_SOURCE_INFO ) );
1525  moreSources = FALSE;
1526 #ifdef DEBUG_RANDOM
1527  puts( __FILE__ ": Poll timed out, probably due to blocked data "
1528  "source." );
1529 #endif /* DEBUG_RANDOM */
1530  }
1531  }
1532  ENSURES_EXIT( iterationCount < FAILSAFE_ITERATIONS_MAX );
1533  gathererInfo->usefulness = usefulness;
1534  gathererInfo->noBytes = bufPos;
1535 #ifdef DEBUG_RANDOM
1536  printf( __FILE__ ": Got %d bytes, usefulness = %d.\n", bufPos,
1537  usefulness );
1538 #endif /* DEBUG_RANDOM */
1539 
1540  /* "Thou child of the daemon, ... wilt thou not cease...?"
1541  -- Acts 13:10 */
1542  exit( 0 );
1543  }
1544 
1545 /* Unix slow poll. If a few of the randomness sources create a large amount
1546  of output then the slowPoll() stops once the buffer has been filled (but
1547  before all of the randomness sources have been sucked dry) so that the
1548  'usefulness' factor remains below the threshold. For this reason the
1549  gatherer buffer has to be fairly sizeable on moderately loaded systems.
1550 
1551  An alternative strategy, suggested by Massimo Squillace, is to use a
1552  chunk of shared memory protected by a semaphore, with the first
1553  sizeof( int ) bytes at the start serving as a high-water mark. The
1554  process forks and waitpid()'s for the child's pid. The child forks all
1555  the entropy-gatherers and exits, allowing the parent to resume execution.
1556  The child's children are inherited by init (double-fork paradigm), when
1557  each one is finished it takes the semaphore, writes data to the shared
1558  memory segment at the given offset, updates the offset, releases the
1559  semaphore again, and exits, to be reaped by init.
1560 
1561  The parent monitors the shared memory offset and when enough data is
1562  available takes the semaphore, grabs the data, and releases the shared
1563  memory area and semaphore. If any children are still running they'll get
1564  errors when they try to access the semaphore or shared memory and
1565  silently exit.
1566 
1567  This approach has the advantage that all of the forked processes are
1568  managed by init rather than having the parent have to wait for them, but
1569  the disadvantage that the end-of-job handling is rather less rigorous.
1570  An additional disadvantage is that the existing code has had a lot of
1571  real-world testing and adaptation to system-specific quirks, which would
1572  have to be repeated for any new version */
1573 
1574 #define SHARED_BUFSIZE 49152 /* Usually about 25K are filled */
1575 
1576 void slowPoll( void )
1577  {
1578  const int pageSize = getSysVar( SYSVAR_PAGESIZE );
1579  int extraEntropy = 0;
1580 
1581  /* Make sure that we don't start more than one slow poll at a time. The
1582  gathererProcess value may be positive (a PID) or -1 (error), so we
1583  compare it to the specific value 0 (= not-used) in the check */
1584  lockPollingMutex();
1585  if( gathererProcess != 0 )
1586  {
1588  return;
1589  }
1590 
1591  /* The popen()-level slow poll is the screen-scraping interface of last
1592  resort that we use only if we can't get the entropy in any other
1593  way. If the system provides entropy from alternate sources, we don't
1594  have have to try the screen-scraping slow poll (a number of these
1595  additional sources, things like procfs and kstats, duplicate the
1596  sources polled in the slow poll anyway, so we're not adding much by
1597  polling these extra sources if we've already got the data directly) */
1598  extraEntropy += getDevRandomData();
1599  if( !access( "/proc/interrupts", R_OK ) )
1600  extraEntropy += getProcFSdata();
1601  extraEntropy += getEGDdata();
1602 #ifdef USE_KSTAT
1603  extraEntropy += getKstatData();
1604 #endif /* USE_KSTAT */
1605 #ifdef USE_PROC
1606  extraEntropy += getProcData();
1607 #endif /* USE_PROC */
1608 #ifdef DEBUG_RANDOM
1609  printf( __FILE__ ": Got %d additional entropy from direct sources.\n",
1610  extraEntropy );
1611  if( extraEntropy >= 100 )
1612  {
1613  puts( " (Skipping full slowpoll since sufficient entropy is "
1614  "available)." );
1615  }
1616 #endif /* DEBUG_RANDOM */
1617  if( extraEntropy >= 100 )
1618  {
1619  /* We got enough entropy from the additional sources, we don't
1620  have to go through with the full (heavyweight) poll */
1622  return;
1623  }
1624 
1625  /* QNX 4.x doesn't have SYSV shared memory, so we can't go beyond this
1626  point, all that we can do is warn the user that they'll have to use
1627  the entropy mechanisms for embedded systems (without proper entropy
1628  sources) */
1629 #if defined( __QNX__ ) && OSVERSION <= 4
1630  fprintf( stderr, "cryptlib: QNX 4.x doesn't contain the OS mechanisms "
1631  "required to provide\n system entropy sources that "
1632  "can be used for key generation. In\n order to use "
1633  "cryptlib in this environment, you need to apply the\n"
1634  " randomness mechanisms for embedded systems "
1635  "described in the\n cryptlib manual.\n" );
1636  abort();
1637 #else
1638 
1639  /* Check whether a non-default SIGCHLD handler is present. This is
1640  necessary because if the program that cryptlib is a part of installs
1641  its own handler it will end up reaping the cryptlib children before
1642  cryptlib can. As a result my_pclose() will call waitpid() on a
1643  process that has already been reaped by the installed handler and
1644  return an error, so the read data won't be added to the randomness
1645  pool */
1646  if( sigaction( SIGCHLD, NULL, &gathererOldHandler ) < 0 )
1647  {
1648  /* This assumes that stderr is open, i.e. that we're not a daemon
1649  (this should be the case at least during the development/debugging
1650  stage) */
1651  fprintf( stderr, "cryptlib: sigaction() failed, errno = %d, "
1652  "file " __FILE__ ", line %d.\n", errno, __LINE__ );
1653  abort();
1654  }
1655 
1656  /* Check for handler override */
1657  if( gathererOldHandler.sa_handler != SIG_DFL && \
1658  gathererOldHandler.sa_handler != SIG_IGN )
1659  {
1660 #ifdef DEBUG_CONFLICTS
1661  /* We overwrote the caller's handler, warn them about this */
1662  fprintf( stderr, "cryptlib: Conflicting SIGCHLD handling detected "
1663  "in randomness polling code,\nfile " __FILE__ ", line %d. "
1664  "See the source code for more\ninformation.\n", __LINE__ );
1665 #endif /* DEBUG_CONFLICTS */
1666  }
1667 
1668  /* If a non-default handler is present, replace it with the default
1669  handler */
1670  if( gathererOldHandler.sa_handler != SIG_DFL )
1671  {
1672  struct sigaction newHandler;
1673 
1674  memset( &newHandler, 0, sizeof( newHandler ) );
1675  newHandler.sa_handler = SIG_DFL;
1676  sigemptyset( &newHandler.sa_mask );
1677  sigaction( SIGCHLD, &newHandler, NULL );
1678  }
1679 
1680  /* Set up the shared memory */
1681  gathererBufSize = ( SHARED_BUFSIZE / pageSize ) * ( pageSize + 1 );
1682  if( ( gathererMemID = shmget( IPC_PRIVATE, gathererBufSize,
1683  IPC_CREAT | 0600 ) ) == -1 || \
1684  ( gathererBuffer = ( BYTE * ) shmat( gathererMemID,
1685  NULL, 0 ) ) == ( BYTE * ) -1 )
1686  {
1687  /* There was a problem obtaining the shared memory, warn the user
1688  and exit */
1689 #ifdef _CRAY
1690  if( errno == ENOSYS )
1691  {
1692  /* Unicos supports shmget/shmat, but older Crays don't implement
1693  it and return ENOSYS */
1694  fprintf( stderr, "cryptlib: SYSV shared memory required for "
1695  "random number gathering isn't\n supported on this "
1696  "type of Cray hardware (ENOSYS),\n file " __FILE__
1697  ", line %d.\n", __LINE__ );
1698  }
1699 #endif /* Cray */
1700 #ifdef DEBUG_CONFLICTS
1701  fprintf( stderr, "cryptlib: shmget()/shmat() failed, errno = %d, "
1702  "file " __FILE__ ", line %d.\n", errno, __LINE__ );
1703 #endif /* DEBUG_CONFLICTS */
1704  if( gathererMemID != -1 )
1705  shmctl( gathererMemID, IPC_RMID, NULL );
1706  if( gathererOldHandler.sa_handler != SIG_DFL )
1707  sigaction( SIGCHLD, &gathererOldHandler, NULL );
1709  return; /* Something broke */
1710  }
1711 
1712  /* At this point we have a possible race condition since we need to set
1713  the gatherer PID value inside the mutex but messing with mutexes
1714  across a fork() is somewhat messy. To resolve this, we set the PID
1715  to a nonzero value (which marks it as busy) and exit the mutex, then
1716  overwrite it with the real PID (also nonzero) from the fork */
1717  gathererProcess = -1;
1719 
1720  /* Fork off the gatherer, the parent process returns to the caller.
1721 
1722  Programs using the OS X Core Foundation framework will complain if a
1723  program calls fork() and doesn't follow it up with an exec() (which
1724  really screws up daemonization ), printing an error message:
1725 
1726  The process has forked and you cannot use this CoreFoundation \
1727  functionality safely. You MUST exec().
1728 
1729  There are workarounds possible but they're daemon-specific and
1730  involve running under launchd, which isn't really an option here.
1731  For now this is left as an OS X framework problem, there doesn't
1732  seem to be anything that we can do to fix it here */
1733  if( ( gathererProcess = fork() ) != 0 )
1734  {
1735  /* If we're the parent, we're done */
1736  if( gathererProcess != -1 )
1737  return;
1738 
1739  /* The fork() failed, clean up and reset the gatherer PID to make
1740  sure that we're not locked out of retrying the poll later */
1741 #ifdef DEBUG_CONFLICTS
1742  fprintf( stderr, "cryptlib: fork() failed, errno = %d, file "
1743  __FILE__ ", line %d.\n", errno, __LINE__ );
1744 #endif /* DEBUG_CONFLICTS */
1745  lockPollingMutex();
1746  shmctl( gathererMemID, IPC_RMID, NULL );
1747  if( gathererOldHandler.sa_handler != SIG_DFL )
1748  sigaction( SIGCHLD, &gathererOldHandler, NULL );
1749  gathererProcess = 0;
1751  return;
1752  }
1753 
1754  /* Make the child an explicitly distinct function */
1755  childPollingProcess( extraEntropy );
1756 #endif /* !QNX 4.x */
1757  }
1758 
1759 /* Wait for the randomness gathering to finish */
1760 
1761 #if !defined( _POSIX_PRIORITY_SCHEDULING ) || ( _POSIX_PRIORITY_SCHEDULING < 0 )
1762  /* No sched_yield() or sched_yield() not supported */
1763  #define sched_yield()
1764 #elif ( _POSIX_PRIORITY_SCHEDULING == 0 )
1765 
1766 static void my_sched_yield( void )
1767  {
1768  /* sched_yield() is only supported if sysconf() tells us that it is */
1769  if( sysconf( _SC_PRIORITY_SCHEDULING ) > 0 )
1770  sched_yield();
1771  }
1772 #define sched_yield my_sched_yield
1773 
1774 #endif /* Systems without sched_yield() */
1775 
1776 CHECK_RETVAL \
1778  {
1780  GATHERER_INFO *gathererInfo = ( GATHERER_INFO * ) gathererBuffer;
1781  int quality, status;
1782 
1783  lockPollingMutex();
1784  if( gathererProcess <= 0 )
1785  {
1786  /* There's no gatherer running, exit */
1788 
1789  return( CRYPT_OK );
1790  }
1791 
1792  /* If this is a forced shutdown, be fairly assertive with the gathering
1793  process */
1794  if( force )
1795  {
1796  /* Politely ask the the gatherer to shut down and (try and) yield
1797  our timeslice a few times so that the shutdown can take effect.
1798  This is unfortunately somewhat implementation-dependant in that
1799  in some cases it'll only yield the current thread's timeslice
1800  rather than the overall process' timeslice, or if it's a high-
1801  priority thread it'll be scheduled again before any lower-
1802  priority threads get to run */
1803  kill( gathererProcess, SIGTERM );
1804  sched_yield();
1805  sched_yield();
1806  sched_yield(); /* Well, sync is done three times too... */
1807 
1808  /* If the gatherer is still running, ask again, less politely this
1809  time */
1810  if( kill( gathererProcess, 0 ) != -1 || errno != ESRCH )
1811  kill( gathererProcess, SIGKILL );
1812  }
1813 
1814  /* Wait for the gathering process to finish and, if it was sucessful,
1815  add the randomness that it's gathered */
1816  if( waitpid( gathererProcess, &status, 0 ) >= 0 && WIFEXITED( status ) )
1817  {
1818  /* The child terminated normally, forward its output to the system
1819  device. We don't check for errors at this point (apart from
1820  warning in the debug version) since this is an invisible internal
1821  routine for which we can't easily recover from problems. Any
1822  problems are caught at a higher level by the randomness-quality
1823  checking */
1824  if( gathererInfo->noBytes > 0 && !force )
1825  {
1826  quality = min( gathererInfo->usefulness * 5, 100 ); /* 0-20 -> 0-100 */
1827  setMessageData( &msgData, gathererBuffer, gathererInfo->noBytes );
1830  &msgData, CRYPT_IATTRIBUTE_ENTROPY );
1831  assert( cryptStatusOK( status ) );
1832  if( quality > 0 )
1833  {
1834  /* On some very cut-down embedded systems the entropy
1835  quality can be zero so we only send a quality estimate if
1836  there's actually something there */
1838  IMESSAGE_SETATTRIBUTE, &quality,
1839  CRYPT_IATTRIBUTE_ENTROPY_QUALITY );
1840  assert( cryptStatusOK( status ) );
1841  }
1842  }
1843  }
1844  zeroise( gathererBuffer, gathererBufSize );
1845 
1846  /* Detach and delete the shared memory (the latter is necessary because
1847  otherwise the unused ID hangs around until the process terminates)
1848  and restore the original signal handler if we replaced someone else's
1849  one */
1850 #if !( defined( __QNX__ ) && OSVERSION <= 4 )
1851  shmdt( gathererBuffer );
1852  shmctl( gathererMemID, IPC_RMID, NULL );
1853  if( gathererOldHandler.sa_handler != SIG_DFL )
1854  {
1855  struct sigaction oact;
1856 
1857  /* We replaced someone else's handler for the slow poll, reinstate
1858  the original one. Since someone else could have in turn replaced
1859  our handler, we check for this and warn the user if necessary */
1860  sigaction( SIGCHLD, NULL, &oact );
1861  if( oact.sa_handler != SIG_DFL )
1862  {
1863 #ifdef DEBUG_CONFLICTS
1864  /* The current handler isn't the one that we installed, warn the
1865  user */
1866  fprintf( stderr, "cryptlib: SIGCHLD handler was replaced "
1867  "while slow poll was in progress,\nfile " __FILE__
1868  ", line %d. See the source code for more\n"
1869  "information.\n", __LINE__ );
1870 #endif /* DEBUG_CONFLICTS */
1871  }
1872  else
1873  {
1874  /* Our handler is still in place, replace it with the original
1875  one */
1876  sigaction( SIGCHLD, &gathererOldHandler, NULL );
1877  }
1878  }
1879 #endif /* !QNX 4.x */
1880  gathererProcess = 0;
1882 
1883  return( CRYPT_OK );
1884  }
1885 
1886 /* Check whether we've forked and we're the child. The mechanism used varies
1887  depending on whether we're running in a single-threaded or multithreaded
1888  environment, for single-threaded we check whether the pid has changed
1889  since the last check, for multithreaded environments this isn't reliable
1890  since some systems have per-thread pid's so we need to use
1891  pthread_atfork() as a trigger to set the pid-changed flag.
1892 
1893  Under Aches, calling pthread_atfork() with any combination of arguments or
1894  circumstances produces a segfault, so we undefine USE_THREADS to force the
1895  use of the getpid()-based fork detection. In addition some other
1896  environments don't support the call, so we exclude those as well. FreeBSD
1897  is a particular pain because of its highly confusing use of -RELEASE,
1898  -STABLE, and -CURRENT while maintaining the same version, it's present in
1899  5.x-CURRENT but not 5.x-RELEASE or -STABLE, so we have to exclude it for
1900  all 5.x to be safe */
1901 
1902 #if defined( USE_THREADS ) && \
1903  ( defined( _AIX ) || defined( _CRAY ) || defined( __MVS__ ) || \
1904  defined( _MPRAS ) || defined( __APPLE__ ) || \
1905  ( defined( __FreeBSD__ ) && OSVERSION <= 5 ) )
1906  #undef USE_THREADS
1907 #endif /* USE_THREADS && OSes without pthread_atfork() */
1908 
1909 #ifdef USE_THREADS
1910 
1911 static BOOLEAN forked = FALSE;
1912 static pthread_mutex_t forkedMutex;
1913 
1914 BOOLEAN checkForked( void )
1915  {
1916  BOOLEAN hasForked;
1917 
1918  /* Read the forked-t flag in a thread-safe manner */
1919  pthread_mutex_lock( &forkedMutex );
1920  hasForked = forked;
1921  forked = FALSE;
1922  pthread_mutex_unlock( &forkedMutex );
1923 
1924  return( hasForked );
1925  }
1926 
1927 void setForked( void )
1928  {
1929  /* Set the forked-t flag in a thread-safe manner */
1930  pthread_mutex_lock( &forkedMutex );
1931  forked = TRUE;
1932  pthread_mutex_unlock( &forkedMutex );
1933  }
1934 
1935 #else
1936 
1938  {
1939  static pid_t originalPID = -1;
1940 
1941  /* Set the initial PID if necessary */
1942  if( originalPID == -1 )
1943  originalPID = getpid();
1944 
1945  /* If the pid has changed we've forked and we're the child, remember the
1946  new pid */
1947  if( getpid() != originalPID )
1948  {
1949  originalPID = getpid();
1950  return( TRUE );
1951  }
1952 
1953  return( FALSE );
1954  }
1955 #endif /* USE_THREADS */
1956 
1957 /* Initialise and clean up any auxiliary randomness-related objects */
1958 
1959 void initRandomPolling( void )
1960  {
1961  /* If it's multithreaded code, we need to ensure that we're signalled if
1962  another thread calls fork(). Hardcoding in the Posix function name at
1963  this point is safe because it also works for Solaris threads. We set
1964  the forked flag in both the child and the parent to ensure that both
1965  sides remix the pool thoroughly */
1966 #ifdef USE_THREADS
1967  pthread_atfork( NULL, setForked, setForked );
1968 
1969  pthread_mutex_init( &gathererMutex, NULL );
1970  pthread_mutex_init( &forkedMutex, NULL );
1971 #endif /* USE_THREADS */
1972  }
1973 
1974 void endRandomPolling( void )
1975  {
1976 #ifdef USE_THREADS
1977  pthread_mutex_destroy( &forkedMutex );
1978  pthread_mutex_destroy( &gathererMutex );
1979 #endif /* USE_THREADS */
1980  }