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