bde4ac16cb89f5e10f5ef8411d1d70cf3b056289
[openssl.git] / crypto / rand / rand_unix.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #define _GNU_SOURCE
11 #include "e_os.h"
12 #include <stdio.h>
13 #include "internal/cryptlib.h"
14 #include <openssl/rand.h>
15 #include "rand_lcl.h"
16 #include "internal/rand_int.h"
17 #include <stdio.h>
18 #if defined(__linux)
19 # include <sys/syscall.h>
20 #endif
21 #if defined(__FreeBSD__)
22 # include <sys/types.h>
23 # include <sys/sysctl.h>
24 # include <sys/param.h>
25 #endif
26 #if defined(__OpenBSD__) || defined(__NetBSD__)
27 # include <sys/param.h>
28 #endif
29 #ifdef OPENSSL_SYS_UNIX
30 # include <sys/types.h>
31 # include <unistd.h>
32 # include <sys/time.h>
33
34 static uint64_t get_time_stamp(void);
35 static uint64_t get_timer_bits(void);
36
37 /* Macro to convert two thirty two bit values into a sixty four bit one */
38 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
39
40 /*
41  * Check for the existence and support of POSIX timers.  The standard
42  * says that the _POSIX_TIMERS macro will have a positive value if they
43  * are available.
44  *
45  * However, we want an additional constraint: that the timer support does
46  * not require an extra library dependency.  Early versions of glibc
47  * require -lrt to be specified on the link line to access the timers,
48  * so this needs to be checked for.
49  *
50  * It is worse because some libraries define __GLIBC__ but don't
51  * support the version testing macro (e.g. uClibc).  This means
52  * an extra check is needed.
53  *
54  * The final condition is:
55  *      "have posix timers and either not glibc or glibc without -lrt"
56  *
57  * The nested #if sequences are required to avoid using a parameterised
58  * macro that might be undefined.
59  */
60 # undef OSSL_POSIX_TIMER_OKAY
61 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
62 #  if defined(__GLIBC__)
63 #   if defined(__GLIBC_PREREQ)
64 #    if __GLIBC_PREREQ(2, 17)
65 #     define OSSL_POSIX_TIMER_OKAY
66 #    endif
67 #   endif
68 #  else
69 #   define OSSL_POSIX_TIMER_OKAY
70 #  endif
71 # endif
72 #endif
73
74 int syscall_random(void *buf, size_t buflen);
75
76 #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
77         !defined(OPENSSL_RAND_SEED_NONE)
78 # error "UEFI and VXWorks only support seeding NONE"
79 #endif
80
81 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
82     || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
83     || defined(OPENSSL_SYS_UEFI))
84
85 # if defined(OPENSSL_SYS_VOS)
86
87 #  ifndef OPENSSL_RAND_SEED_OS
88 #   error "Unsupported seeding method configured; must be os"
89 #  endif
90
91 #  if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
92 #   error "Unsupported HP-PA and IA32 at the same time."
93 #  endif
94 #  if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
95 #   error "Must have one of HP-PA or IA32"
96 #  endif
97
98 /*
99  * The following algorithm repeatedly samples the real-time clock (RTC) to
100  * generate a sequence of unpredictable data.  The algorithm relies upon the
101  * uneven execution speed of the code (due to factors such as cache misses,
102  * interrupts, bus activity, and scheduling) and upon the rather large
103  * relative difference between the speed of the clock and the rate at which
104  * it can be read.  If it is ported to an environment where execution speed
105  * is more constant or where the RTC ticks at a much slower rate, or the
106  * clock can be read with fewer instructions, it is likely that the results
107  * would be far more predictable.  This should only be used for legacy
108  * platforms.
109  *
110  * As a precaution, we assume only 2 bits of entropy per byte.
111  */
112 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
113 {
114     short int code;
115     int i, k;
116     size_t bytes_needed;
117     struct timespec ts;
118     unsigned char v;
119 #  ifdef OPENSSL_SYS_VOS_HPPA
120     long duration;
121     extern void s$sleep(long *_duration, short int *_code);
122 #  else
123     long long duration;
124     extern void s$sleep2(long long *_duration, short int *_code);
125 #  endif
126
127     bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
128
129     for (i = 0; i < bytes_needed; i++) {
130         /*
131          * burn some cpu; hope for interrupts, cache collisions, bus
132          * interference, etc.
133          */
134         for (k = 0; k < 99; k++)
135             ts.tv_nsec = random();
136
137 #  ifdef OPENSSL_SYS_VOS_HPPA
138         /* sleep for 1/1024 of a second (976 us).  */
139         duration = 1;
140         s$sleep(&duration, &code);
141 #  else
142         /* sleep for 1/65536 of a second (15 us).  */
143         duration = 1;
144         s$sleep2(&duration, &code);
145 #  endif
146
147         /* Get wall clock time, take 8 bits. */
148         clock_gettime(CLOCK_REALTIME, &ts);
149         v = (unsigned char)(ts.tv_nsec & 0xFF);
150         rand_pool_add(pool, arg, &v, sizeof(v) , 2);
151     }
152     return rand_pool_entropy_available(pool);
153 }
154
155 # else
156
157 #  if defined(OPENSSL_RAND_SEED_EGD) && \
158         (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
159 #   error "Seeding uses EGD but EGD is turned off or no device given"
160 #  endif
161
162 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
163 #   error "Seeding uses urandom but DEVRANDOM is not configured"
164 #  endif
165
166 #  if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
167 #   if __GLIBC_PREREQ(2, 25)
168 #    define OPENSSL_HAVE_GETRANDOM
169 #   endif
170 #  endif
171
172 #  if (defined(__FreeBSD__) && __FreeBSD_version >= 1200061)
173 #   define OPENSSL_HAVE_GETRANDOM
174 #  endif
175
176 #  if defined(OPENSSL_HAVE_GETRANDOM)
177 #   include <sys/random.h>
178 #  endif
179
180 #  if defined(OPENSSL_RAND_SEED_OS)
181 #   if !defined(DEVRANDOM)
182 #    error "OS seeding requires DEVRANDOM to be configured"
183 #   endif
184 #   define OPENSSL_RAND_SEED_GETRANDOM
185 #   define OPENSSL_RAND_SEED_DEVRANDOM
186 #  endif
187
188 #  if defined(OPENSSL_RAND_SEED_LIBRANDOM)
189 #   error "librandom not (yet) supported"
190 #  endif
191
192 #  if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
193 /*
194  * sysctl_random(): Use sysctl() to read a random number from the kernel
195  * Returns the size on success, 0 on failure.
196  */
197 static size_t sysctl_random(char *buf, size_t buflen)
198 {
199     int mib[2];
200     size_t done = 0;
201     size_t len;
202
203     /*
204      * On FreeBSD old implementations returned longs, newer versions support
205      * variable sizes up to 256 byte. The code below would not work properly
206      * when the sysctl returns long and we want to request something not a
207      * multiple of longs, which should never be the case.
208      */
209     if (!ossl_assert(buflen % sizeof(long) == 0))
210         return 0;
211
212     /*
213      * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
214      * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
215      * it returns a variable number of bytes with the current version supporting
216      * up to 256 bytes.
217      * Just return an error on older NetBSD versions.
218      */
219 #if   defined(__NetBSD__) && __NetBSD_Version__ < 400000000
220     return 0;
221 #endif
222
223     mib[0] = CTL_KERN;
224     mib[1] = KERN_ARND;
225
226     do {
227         len = buflen;
228         if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
229             return done;
230         done += len;
231         buf += len;
232         buflen -= len;
233     } while (buflen > 0);
234
235     return done;
236 }
237 #  endif
238
239 /*
240  * syscall_random(): Try to get random data using a system call
241  * returns the number of bytes returned in buf, or <= 0 on error.
242  */
243 int syscall_random(void *buf, size_t buflen)
244 {
245 #  if defined(OPENSSL_HAVE_GETRANDOM)
246     return (int)getrandom(buf, buflen, 0);
247 #  endif
248
249 #  if defined(__linux) && defined(SYS_getrandom)
250     return (int)syscall(SYS_getrandom, buf, buflen, 0);
251 #  endif
252
253 #  if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
254     return (int)sysctl_random(buf, buflen);
255 #  endif
256
257    /* Supported since OpenBSD 5.6 */
258 #  if defined(__OpenBSD__) && OpenBSD >= 201411
259     return getentropy(buf, buflen);
260 #  endif
261
262     return -1;
263 }
264
265 /*
266  * Try the various seeding methods in turn, exit when successful.
267  *
268  * TODO(DRBG): If more than one entropy source is available, is it
269  * preferable to stop as soon as enough entropy has been collected
270  * (as favored by @rsalz) or should one rather be defensive and add
271  * more entropy than requested and/or from different sources?
272  *
273  * Currently, the user can select multiple entropy sources in the
274  * configure step, yet in practice only the first available source
275  * will be used. A more flexible solution has been requested, but
276  * currently it is not clear how this can be achieved without
277  * overengineering the problem. There are many parameters which
278  * could be taken into account when selecting the order and amount
279  * of input from the different entropy sources (trust, quality,
280  * possibility of blocking).
281  */
282 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
283 {
284 #  ifdef OPENSSL_RAND_SEED_NONE
285     return rand_pool_entropy_available(pool);
286 #  else
287     size_t bytes_needed;
288     size_t entropy_available = 0;
289     unsigned char *buffer;
290
291 #   ifdef OPENSSL_RAND_SEED_GETRANDOM
292     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
293     buffer = rand_pool_add_begin(pool, bytes_needed);
294     if (buffer != NULL) {
295         size_t bytes = 0;
296
297         if (syscall_random(buffer, bytes_needed) == (int)bytes_needed)
298             bytes = bytes_needed;
299
300         rand_pool_add_end(pool, bytes, 8 * bytes);
301         entropy_available = rand_pool_entropy_available(pool);
302     }
303     if (entropy_available > 0)
304         return entropy_available;
305 #   endif
306
307 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
308     {
309         /* Not yet implemented. */
310     }
311 #   endif
312
313 #   ifdef OPENSSL_RAND_SEED_DEVRANDOM
314     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
315     if (bytes_needed > 0) {
316         static const char *paths[] = { DEVRANDOM, NULL };
317         FILE *fp;
318         int i;
319
320         for (i = 0; paths[i] != NULL; i++) {
321             if ((fp = fopen(paths[i], "rb")) == NULL)
322                 continue;
323             setbuf(fp, NULL);
324             buffer = rand_pool_add_begin(pool, bytes_needed);
325             if (buffer != NULL) {
326                 size_t bytes = 0;
327                 if (fread(buffer, 1, bytes_needed, fp) == bytes_needed)
328                     bytes = bytes_needed;
329
330                 rand_pool_add_end(pool, bytes, 8 * bytes);
331                 entropy_available = rand_pool_entropy_available(pool);
332             }
333             fclose(fp);
334             if (entropy_available > 0)
335                 return entropy_available;
336
337             bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
338         }
339     }
340 #   endif
341
342 #   ifdef OPENSSL_RAND_SEED_RDTSC
343     entropy_available = rand_acquire_entropy_from_tsc(pool);
344     if (entropy_available > 0)
345         return entropy_available;
346 #   endif
347
348 #   ifdef OPENSSL_RAND_SEED_RDCPU
349     entropy_available = rand_acquire_entropy_from_cpu(pool);
350     if (entropy_available > 0)
351         return entropy_available;
352 #   endif
353
354 #   ifdef OPENSSL_RAND_SEED_EGD
355     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
356     if (bytes_needed > 0) {
357         static const char *paths[] = { DEVRANDOM_EGD, NULL };
358         int i;
359
360         for (i = 0; paths[i] != NULL; i++) {
361             buffer = rand_pool_add_begin(pool, bytes_needed);
362             if (buffer != NULL) {
363                 size_t bytes = 0;
364                 int num = RAND_query_egd_bytes(paths[i],
365                                                buffer, (int)bytes_needed);
366                 if (num == (int)bytes_needed)
367                     bytes = bytes_needed;
368
369                 rand_pool_add_end(pool, bytes, 8 * bytes);
370                 entropy_available = rand_pool_entropy_available(pool);
371             }
372             if (entropy_available > 0)
373                 return entropy_available;
374         }
375     }
376 #   endif
377
378     return rand_pool_entropy_available(pool);
379 #  endif
380 }
381 # endif
382 #endif
383
384 #ifdef OPENSSL_SYS_UNIX
385 int rand_pool_add_nonce_data(RAND_POOL *pool)
386 {
387     struct {
388         pid_t pid;
389         CRYPTO_THREAD_ID tid;
390         uint64_t time;
391     } data = { 0 };
392
393     /*
394      * Add process id, thread id, and a high resolution timestamp to
395      * ensure that the nonce is unique whith high probability for
396      * different process instances.
397      */
398     data.pid = getpid();
399     data.tid = CRYPTO_THREAD_get_current_id();
400     data.time = get_time_stamp();
401
402     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
403 }
404
405 int rand_pool_add_additional_data(RAND_POOL *pool)
406 {
407     struct {
408         CRYPTO_THREAD_ID tid;
409         uint64_t time;
410     } data = { 0 };
411
412     /*
413      * Add some noise from the thread id and a high resolution timer.
414      * The thread id adds a little randomness if the drbg is accessed
415      * concurrently (which is the case for the <master> drbg).
416      */
417     data.tid = CRYPTO_THREAD_get_current_id();
418     data.time = get_timer_bits();
419
420     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
421 }
422
423
424
425 /*
426  * Get the current time with the highest possible resolution
427  *
428  * The time stamp is added to the nonce, so it is optimized for not repeating.
429  * The current time is ideal for this purpose, provided the computer's clock
430  * is synchronized.
431  */
432 static uint64_t get_time_stamp(void)
433 {
434 # if defined(OSSL_POSIX_TIMER_OKAY)
435     {
436         struct timespec ts;
437
438         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
439             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
440     }
441 # endif
442 # if defined(__unix__) \
443      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
444     {
445         struct timeval tv;
446
447         if (gettimeofday(&tv, NULL) == 0)
448             return TWO32TO64(tv.tv_sec, tv.tv_usec);
449     }
450 # endif
451     return time(NULL);
452 }
453
454 /*
455  * Get an arbitrary timer value of the highest possible resolution
456  *
457  * The timer value is added as random noise to the additional data,
458  * which is not considered a trusted entropy sourec, so any result
459  * is acceptable.
460  */
461 static uint64_t get_timer_bits(void)
462 {
463     uint64_t res = OPENSSL_rdtsc();
464
465     if (res != 0)
466         return res;
467
468 # if defined(__sun) || defined(__hpux)
469     return gethrtime();
470 # elif defined(_AIX)
471     {
472         timebasestruct_t t;
473
474         read_wall_time(&t, TIMEBASE_SZ);
475         return TWO32TO64(t.tb_high, t.tb_low);
476     }
477 # elif defined(OSSL_POSIX_TIMER_OKAY)
478     {
479         struct timespec ts;
480
481 #  ifdef CLOCK_BOOTTIME
482 #   define CLOCK_TYPE CLOCK_BOOTTIME
483 #  elif defined(_POSIX_MONOTONIC_CLOCK)
484 #   define CLOCK_TYPE CLOCK_MONOTONIC
485 #  else
486 #   define CLOCK_TYPE CLOCK_REALTIME
487 #  endif
488
489         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
490             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
491     }
492 # endif
493 # if defined(__unix__) \
494      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
495     {
496         struct timeval tv;
497
498         if (gettimeofday(&tv, NULL) == 0)
499             return TWO32TO64(tv.tv_sec, tv.tv_usec);
500     }
501 # endif
502     return time(NULL);
503 }
504 #endif