Add support for getrandom() or equivalent system calls and use them by default
[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__)
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, 2 /*entropy_per_byte*/);
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(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      * Old implementations returned longs, newer versions support variable
205      * sizes up to 256 byte. The code below would not work properly when
206      * the sysctl returns long and we want to request something not a multiple
207      * of longs, which should never be the case.
208      */
209     ossl_assert(buflen % sizeof(long) == 0);
210
211     mib[0] = CTL_KERN;
212     mib[1] = KERN_ARND;
213
214     do {
215         len = buflen;
216         if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
217             return done;
218         done += len;
219         buf += len;
220         buflen -= len;
221     } while (buflen > 0);
222
223     return done;
224 }
225 #  endif
226
227 /*
228  * syscall_random(): Try to get random data using a system call
229  * returns the number of bytes returned in buf, or <= 0 on error.
230  */
231 int syscall_random(void *buf, size_t buflen)
232 {
233 #  if defined(OPENSSL_HAVE_GETRANDOM)
234     return (int)getrandom(buf, buflen, 0);
235 #  endif
236
237 #  if defined(__linux) && defined(SYS_getrandom)
238     return (int)syscall(SYS_getrandom, buf, buflen, 0);
239 #  endif
240
241 #  if defined(__FreeBSD__) && defined(KERN_ARND)
242     return (int)sysctl_random(buf, buflen);
243 #  endif
244
245    /* Supported since OpenBSD 5.6 */
246 #  if defined(__OpenBSD__) && OpenBSD >= 201411
247     return getentropy(buf, buflen);
248 #  endif
249
250     return -1;
251 }
252
253 /*
254  * Try the various seeding methods in turn, exit when successful.
255  *
256  * TODO(DRBG): If more than one entropy source is available, is it
257  * preferable to stop as soon as enough entropy has been collected
258  * (as favored by @rsalz) or should one rather be defensive and add
259  * more entropy than requested and/or from different sources?
260  *
261  * Currently, the user can select multiple entropy sources in the
262  * configure step, yet in practice only the first available source
263  * will be used. A more flexible solution has been requested, but
264  * currently it is not clear how this can be achieved without
265  * overengineering the problem. There are many parameters which
266  * could be taken into account when selecting the order and amount
267  * of input from the different entropy sources (trust, quality,
268  * possibility of blocking).
269  */
270 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
271 {
272 #  ifdef OPENSSL_RAND_SEED_NONE
273     return rand_pool_entropy_available(pool);
274 #  else
275     size_t bytes_needed;
276     size_t entropy_available = 0;
277     unsigned char *buffer;
278
279 #   ifdef OPENSSL_RAND_SEED_GETRANDOM
280     bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
281     buffer = rand_pool_add_begin(pool, bytes_needed);
282     if (buffer != NULL) {
283         size_t bytes = 0;
284
285         if (syscall_random(buffer, bytes_needed) == (int)bytes_needed)
286             bytes = bytes_needed;
287
288         rand_pool_add_end(pool, bytes, 8 * bytes);
289         entropy_available = rand_pool_entropy_available(pool);
290     }
291     if (entropy_available > 0)
292         return entropy_available;
293 #   endif
294
295 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
296     {
297         /* Not yet implemented. */
298     }
299 #   endif
300
301 #   ifdef OPENSSL_RAND_SEED_DEVRANDOM
302     bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
303     if (bytes_needed > 0) {
304         static const char *paths[] = { DEVRANDOM, NULL };
305         FILE *fp;
306         int i;
307
308         for (i = 0; paths[i] != NULL; i++) {
309             if ((fp = fopen(paths[i], "rb")) == NULL)
310                 continue;
311             setbuf(fp, NULL);
312             buffer = rand_pool_add_begin(pool, bytes_needed);
313             if (buffer != NULL) {
314                 size_t bytes = 0;
315                 if (fread(buffer, 1, bytes_needed, fp) == bytes_needed)
316                     bytes = bytes_needed;
317
318                 rand_pool_add_end(pool, bytes, 8 * bytes);
319                 entropy_available = rand_pool_entropy_available(pool);
320             }
321             fclose(fp);
322             if (entropy_available > 0)
323                 return entropy_available;
324
325             bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
326         }
327     }
328 #   endif
329
330 #   ifdef OPENSSL_RAND_SEED_RDTSC
331     entropy_available = rand_acquire_entropy_from_tsc(pool);
332     if (entropy_available > 0)
333         return entropy_available;
334 #   endif
335
336 #   ifdef OPENSSL_RAND_SEED_RDCPU
337     entropy_available = rand_acquire_entropy_from_cpu(pool);
338     if (entropy_available > 0)
339         return entropy_available;
340 #   endif
341
342 #   ifdef OPENSSL_RAND_SEED_EGD
343     bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
344     if (bytes_needed > 0) {
345         static const char *paths[] = { DEVRANDOM_EGD, NULL };
346         int i;
347
348         for (i = 0; paths[i] != NULL; i++) {
349             buffer = rand_pool_add_begin(pool, bytes_needed);
350             if (buffer != NULL) {
351                 size_t bytes = 0;
352                 int num = RAND_query_egd_bytes(paths[i],
353                                                buffer, (int)bytes_needed);
354                 if (num == (int)bytes_needed)
355                     bytes = bytes_needed;
356
357                 rand_pool_add_end(pool, bytes, 8 * bytes);
358                 entropy_available = rand_pool_entropy_available(pool);
359             }
360             if (entropy_available > 0)
361                 return entropy_available;
362         }
363     }
364 #   endif
365
366     return rand_pool_entropy_available(pool);
367 #  endif
368 }
369 # endif
370 #endif
371
372 #ifdef OPENSSL_SYS_UNIX
373 int rand_pool_add_nonce_data(RAND_POOL *pool)
374 {
375     struct {
376         pid_t pid;
377         CRYPTO_THREAD_ID tid;
378         uint64_t time;
379     } data = { 0 };
380
381     /*
382      * Add process id, thread id, and a high resolution timestamp to
383      * ensure that the nonce is unique whith high probability for
384      * different process instances.
385      */
386     data.pid = getpid();
387     data.tid = CRYPTO_THREAD_get_current_id();
388     data.time = get_time_stamp();
389
390     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
391 }
392
393 int rand_pool_add_additional_data(RAND_POOL *pool)
394 {
395     struct {
396         CRYPTO_THREAD_ID tid;
397         uint64_t time;
398     } data = { 0 };
399
400     /*
401      * Add some noise from the thread id and a high resolution timer.
402      * The thread id adds a little randomness if the drbg is accessed
403      * concurrently (which is the case for the <master> drbg).
404      */
405     data.tid = CRYPTO_THREAD_get_current_id();
406     data.time = get_timer_bits();
407
408     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
409 }
410
411
412
413 /*
414  * Get the current time with the highest possible resolution
415  *
416  * The time stamp is added to the nonce, so it is optimized for not repeating.
417  * The current time is ideal for this purpose, provided the computer's clock
418  * is synchronized.
419  */
420 static uint64_t get_time_stamp(void)
421 {
422 # if defined(OSSL_POSIX_TIMER_OKAY)
423     {
424         struct timespec ts;
425
426         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
427             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
428     }
429 # endif
430 # if defined(__unix__) \
431      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
432     {
433         struct timeval tv;
434
435         if (gettimeofday(&tv, NULL) == 0)
436             return TWO32TO64(tv.tv_sec, tv.tv_usec);
437     }
438 # endif
439     return time(NULL);
440 }
441
442 /*
443  * Get an arbitrary timer value of the highest possible resolution
444  *
445  * The timer value is added as random noise to the additional data,
446  * which is not considered a trusted entropy sourec, so any result
447  * is acceptable.
448  */
449 static uint64_t get_timer_bits(void)
450 {
451     uint64_t res = OPENSSL_rdtsc();
452
453     if (res != 0)
454         return res;
455
456 # if defined(__sun) || defined(__hpux)
457     return gethrtime();
458 # elif defined(_AIX)
459     {
460         timebasestruct_t t;
461
462         read_wall_time(&t, TIMEBASE_SZ);
463         return TWO32TO64(t.tb_high, t.tb_low);
464     }
465 # elif defined(OSSL_POSIX_TIMER_OKAY)
466     {
467         struct timespec ts;
468
469 #  ifdef CLOCK_BOOTTIME
470 #   define CLOCK_TYPE CLOCK_BOOTTIME
471 #  elif defined(_POSIX_MONOTONIC_CLOCK)
472 #   define CLOCK_TYPE CLOCK_MONOTONIC
473 #  else
474 #   define CLOCK_TYPE CLOCK_REALTIME
475 #  endif
476
477         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
478             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
479     }
480 # endif
481 # if defined(__unix__) \
482      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
483     {
484         struct timeval tv;
485
486         if (gettimeofday(&tv, NULL) == 0)
487             return TWO32TO64(tv.tv_sec, tv.tv_usec);
488     }
489 # endif
490     return time(NULL);
491 }
492 #endif