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