Fix seeding from random device w/o getrandom syscall
[openssl.git] / crypto / rand / rand_unix.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #ifndef _GNU_SOURCE
11 # define _GNU_SOURCE
12 #endif
13 #include "e_os.h"
14 #include <stdio.h>
15 #include "internal/cryptlib.h"
16 #include <openssl/rand.h>
17 #include "rand_lcl.h"
18 #include "internal/rand_int.h"
19 #include <stdio.h>
20 #include "internal/dso.h"
21 #if defined(__linux)
22 # include <asm/unistd.h>
23 #endif
24 #if defined(__FreeBSD__)
25 # include <sys/types.h>
26 # include <sys/sysctl.h>
27 # include <sys/param.h>
28 #endif
29 #if defined(__OpenBSD__) || defined(__NetBSD__)
30 # include <sys/param.h>
31 #endif
32
33 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
34 # include <sys/types.h>
35 # include <sys/stat.h>
36 # include <fcntl.h>
37 # include <unistd.h>
38 # include <sys/time.h>
39
40 static uint64_t get_time_stamp(void);
41 static uint64_t get_timer_bits(void);
42
43 /* Macro to convert two thirty two bit values into a sixty four bit one */
44 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
45
46 /*
47  * Check for the existence and support of POSIX timers.  The standard
48  * says that the _POSIX_TIMERS macro will have a positive value if they
49  * are available.
50  *
51  * However, we want an additional constraint: that the timer support does
52  * not require an extra library dependency.  Early versions of glibc
53  * require -lrt to be specified on the link line to access the timers,
54  * so this needs to be checked for.
55  *
56  * It is worse because some libraries define __GLIBC__ but don't
57  * support the version testing macro (e.g. uClibc).  This means
58  * an extra check is needed.
59  *
60  * The final condition is:
61  *      "have posix timers and either not glibc or glibc without -lrt"
62  *
63  * The nested #if sequences are required to avoid using a parameterised
64  * macro that might be undefined.
65  */
66 # undef OSSL_POSIX_TIMER_OKAY
67 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
68 #  if defined(__GLIBC__)
69 #   if defined(__GLIBC_PREREQ)
70 #    if __GLIBC_PREREQ(2, 17)
71 #     define OSSL_POSIX_TIMER_OKAY
72 #    endif
73 #   endif
74 #  else
75 #   define OSSL_POSIX_TIMER_OKAY
76 #  endif
77 # endif
78 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
79
80 #if defined(OPENSSL_RAND_SEED_NONE)
81 /* none means none. this simplifies the following logic */
82 # undef OPENSSL_RAND_SEED_OS
83 # undef OPENSSL_RAND_SEED_GETRANDOM
84 # undef OPENSSL_RAND_SEED_LIBRANDOM
85 # undef OPENSSL_RAND_SEED_DEVRANDOM
86 # undef OPENSSL_RAND_SEED_RDTSC
87 # undef OPENSSL_RAND_SEED_RDCPU
88 # undef OPENSSL_RAND_SEED_EGD
89 #endif
90
91 #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
92         !defined(OPENSSL_RAND_SEED_NONE)
93 # error "UEFI and VXWorks only support seeding NONE"
94 #endif
95
96 #if defined(OPENSSL_SYS_VXWORKS)
97 /* empty implementation */
98 int rand_pool_init(void)
99 {
100     return 1;
101 }
102
103 void rand_pool_cleanup(void)
104 {
105 }
106
107 void rand_pool_keep_random_devices_open(int keep)
108 {
109 }
110
111 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
112 {
113     return rand_pool_entropy_available(pool);
114 }
115 #endif
116
117 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
118     || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
119     || defined(OPENSSL_SYS_UEFI))
120
121 # if defined(OPENSSL_SYS_VOS)
122
123 #  ifndef OPENSSL_RAND_SEED_OS
124 #   error "Unsupported seeding method configured; must be os"
125 #  endif
126
127 #  if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
128 #   error "Unsupported HP-PA and IA32 at the same time."
129 #  endif
130 #  if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
131 #   error "Must have one of HP-PA or IA32"
132 #  endif
133
134 /*
135  * The following algorithm repeatedly samples the real-time clock (RTC) to
136  * generate a sequence of unpredictable data.  The algorithm relies upon the
137  * uneven execution speed of the code (due to factors such as cache misses,
138  * interrupts, bus activity, and scheduling) and upon the rather large
139  * relative difference between the speed of the clock and the rate at which
140  * it can be read.  If it is ported to an environment where execution speed
141  * is more constant or where the RTC ticks at a much slower rate, or the
142  * clock can be read with fewer instructions, it is likely that the results
143  * would be far more predictable.  This should only be used for legacy
144  * platforms.
145  *
146  * As a precaution, we assume only 2 bits of entropy per byte.
147  */
148 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
149 {
150     short int code;
151     int i, k;
152     size_t bytes_needed;
153     struct timespec ts;
154     unsigned char v;
155 #  ifdef OPENSSL_SYS_VOS_HPPA
156     long duration;
157     extern void s$sleep(long *_duration, short int *_code);
158 #  else
159     long long duration;
160     extern void s$sleep2(long long *_duration, short int *_code);
161 #  endif
162
163     bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
164
165     for (i = 0; i < bytes_needed; i++) {
166         /*
167          * burn some cpu; hope for interrupts, cache collisions, bus
168          * interference, etc.
169          */
170         for (k = 0; k < 99; k++)
171             ts.tv_nsec = random();
172
173 #  ifdef OPENSSL_SYS_VOS_HPPA
174         /* sleep for 1/1024 of a second (976 us).  */
175         duration = 1;
176         s$sleep(&duration, &code);
177 #  else
178         /* sleep for 1/65536 of a second (15 us).  */
179         duration = 1;
180         s$sleep2(&duration, &code);
181 #  endif
182
183         /* Get wall clock time, take 8 bits. */
184         clock_gettime(CLOCK_REALTIME, &ts);
185         v = (unsigned char)(ts.tv_nsec & 0xFF);
186         rand_pool_add(pool, arg, &v, sizeof(v) , 2);
187     }
188     return rand_pool_entropy_available(pool);
189 }
190
191 void rand_pool_cleanup(void)
192 {
193 }
194
195 void rand_pool_keep_random_devices_open(int keep)
196 {
197 }
198
199 # else
200
201 #  if defined(OPENSSL_RAND_SEED_EGD) && \
202         (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
203 #   error "Seeding uses EGD but EGD is turned off or no device given"
204 #  endif
205
206 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
207 #   error "Seeding uses urandom but DEVRANDOM is not configured"
208 #  endif
209
210 #  if defined(OPENSSL_RAND_SEED_OS)
211 #   if !defined(DEVRANDOM)
212 #    error "OS seeding requires DEVRANDOM to be configured"
213 #   endif
214 #   define OPENSSL_RAND_SEED_GETRANDOM
215 #   define OPENSSL_RAND_SEED_DEVRANDOM
216 #  endif
217
218 #  if defined(OPENSSL_RAND_SEED_LIBRANDOM)
219 #   error "librandom not (yet) supported"
220 #  endif
221
222 #  if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
223 /*
224  * sysctl_random(): Use sysctl() to read a random number from the kernel
225  * Returns the number of bytes returned in buf on success, -1 on failure.
226  */
227 static ssize_t sysctl_random(char *buf, size_t buflen)
228 {
229     int mib[2];
230     size_t done = 0;
231     size_t len;
232
233     /*
234      * Note: sign conversion between size_t and ssize_t is safe even
235      * without a range check, see comment in syscall_random()
236      */
237
238     /*
239      * On FreeBSD old implementations returned longs, newer versions support
240      * variable sizes up to 256 byte. The code below would not work properly
241      * when the sysctl returns long and we want to request something not a
242      * multiple of longs, which should never be the case.
243      */
244     if (!ossl_assert(buflen % sizeof(long) == 0)) {
245         errno = EINVAL;
246         return -1;
247     }
248
249     /*
250      * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
251      * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
252      * it returns a variable number of bytes with the current version supporting
253      * up to 256 bytes.
254      * Just return an error on older NetBSD versions.
255      */
256 #if   defined(__NetBSD__) && __NetBSD_Version__ < 400000000
257     errno = ENOSYS;
258     return -1;
259 #endif
260
261     mib[0] = CTL_KERN;
262     mib[1] = KERN_ARND;
263
264     do {
265         len = buflen;
266         if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
267             return done > 0 ? done : -1;
268         done += len;
269         buf += len;
270         buflen -= len;
271     } while (buflen > 0);
272
273     return done;
274 }
275 #  endif
276
277 #  if defined(OPENSSL_RAND_SEED_GETRANDOM)
278 /*
279  * syscall_random(): Try to get random data using a system call
280  * returns the number of bytes returned in buf, or < 0 on error.
281  */
282 static ssize_t syscall_random(void *buf, size_t buflen)
283 {
284     /*
285      * Note: 'buflen' equals the size of the buffer which is used by the
286      * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
287      *
288      *   2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
289      *
290      * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
291      * between size_t and ssize_t is safe even without a range check.
292      */
293
294     /*
295      * Do runtime detection to find getentropy().
296      *
297      * Known OSs that should support this:
298      * - Darwin since 16 (OSX 10.12, IOS 10.0).
299      * - Solaris since 11.3
300      * - OpenBSD since 5.6
301      * - Linux since 3.17 with glibc 2.25
302      * - FreeBSD since 12.0 (1200061)
303      */
304 #  if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
305     extern int getentropy(void *buffer, size_t length) __attribute__((weak));
306
307     if (getentropy != NULL)
308         return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
309 #  else
310     union {
311         void *p;
312         int (*f)(void *buffer, size_t length);
313     } p_getentropy;
314
315     /*
316      * We could cache the result of the lookup, but we normally don't
317      * call this function often.
318      */
319     ERR_set_mark();
320     p_getentropy.p = DSO_global_lookup("getentropy");
321     ERR_pop_to_mark();
322     if (p_getentropy.p != NULL)
323         return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
324 #  endif
325
326     /* Linux supports this since version 3.17 */
327 #  if defined(__linux) && defined(__NR_getrandom)
328     return syscall(__NR_getrandom, buf, buflen, 0);
329 #  elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
330     return sysctl_random(buf, buflen);
331 #  else
332     errno = ENOSYS;
333     return -1;
334 #  endif
335 }
336 #  endif    /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
337
338 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM)
339 static const char *random_device_paths[] = { DEVRANDOM };
340 static struct random_device {
341     int fd;
342     dev_t dev;
343     ino_t ino;
344     mode_t mode;
345     dev_t rdev;
346 } random_devices[OSSL_NELEM(random_device_paths)];
347 static int keep_random_devices_open = 1;
348
349 /*
350  * Verify that the file descriptor associated with the random source is
351  * still valid. The rationale for doing this is the fact that it is not
352  * uncommon for daemons to close all open file handles when daemonizing.
353  * So the handle might have been closed or even reused for opening
354  * another file.
355  */
356 static int check_random_device(struct random_device * rd)
357 {
358     struct stat st;
359
360     return rd->fd != -1
361            && fstat(rd->fd, &st) != -1
362            && rd->dev == st.st_dev
363            && rd->ino == st.st_ino
364            && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
365            && rd->rdev == st.st_rdev;
366 }
367
368 /*
369  * Open a random device if required and return its file descriptor or -1 on error
370  */
371 static int get_random_device(size_t n)
372 {
373     struct stat st;
374     struct random_device * rd = &random_devices[n];
375
376     /* reuse existing file descriptor if it is (still) valid */
377     if (check_random_device(rd))
378         return rd->fd;
379
380     /* open the random device ... */
381     if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
382         return rd->fd;
383
384     /* ... and cache its relevant stat(2) data */
385     if (fstat(rd->fd, &st) != -1) {
386         rd->dev = st.st_dev;
387         rd->ino = st.st_ino;
388         rd->mode = st.st_mode;
389         rd->rdev = st.st_rdev;
390     } else {
391         close(rd->fd);
392         rd->fd = -1;
393     }
394
395     return rd->fd;
396 }
397
398 /*
399  * Close a random device making sure it is a random device
400  */
401 static void close_random_device(size_t n)
402 {
403     struct random_device * rd = &random_devices[n];
404
405     if (check_random_device(rd))
406         close(rd->fd);
407     rd->fd = -1;
408 }
409
410 int rand_pool_init(void)
411 {
412     size_t i;
413
414     for (i = 0; i < OSSL_NELEM(random_devices); i++)
415         random_devices[i].fd = -1;
416
417     return 1;
418 }
419
420 void rand_pool_cleanup(void)
421 {
422     size_t i;
423
424     for (i = 0; i < OSSL_NELEM(random_devices); i++)
425         close_random_device(i);
426 }
427
428 void rand_pool_keep_random_devices_open(int keep)
429 {
430     if (!keep)
431         rand_pool_cleanup();
432
433     keep_random_devices_open = keep;
434 }
435
436 #  else     /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
437
438 int rand_pool_init(void)
439 {
440     return 1;
441 }
442
443 void rand_pool_cleanup(void)
444 {
445 }
446
447 void rand_pool_keep_random_devices_open(int keep)
448 {
449 }
450
451 #  endif    /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
452
453 /*
454  * Try the various seeding methods in turn, exit when successful.
455  *
456  * TODO(DRBG): If more than one entropy source is available, is it
457  * preferable to stop as soon as enough entropy has been collected
458  * (as favored by @rsalz) or should one rather be defensive and add
459  * more entropy than requested and/or from different sources?
460  *
461  * Currently, the user can select multiple entropy sources in the
462  * configure step, yet in practice only the first available source
463  * will be used. A more flexible solution has been requested, but
464  * currently it is not clear how this can be achieved without
465  * overengineering the problem. There are many parameters which
466  * could be taken into account when selecting the order and amount
467  * of input from the different entropy sources (trust, quality,
468  * possibility of blocking).
469  */
470 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
471 {
472 #  if defined(OPENSSL_RAND_SEED_NONE)
473     return rand_pool_entropy_available(pool);
474 #  else
475     size_t bytes_needed;
476     size_t entropy_available = 0;
477     unsigned char *buffer;
478
479 #   if defined(OPENSSL_RAND_SEED_GETRANDOM)
480     {
481         ssize_t bytes;
482         /* Maximum allowed number of consecutive unsuccessful attempts */
483         int attempts = 3;
484
485         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
486         while (bytes_needed != 0 && attempts-- > 0) {
487             buffer = rand_pool_add_begin(pool, bytes_needed);
488             bytes = syscall_random(buffer, bytes_needed);
489             if (bytes > 0) {
490                 rand_pool_add_end(pool, bytes, 8 * bytes);
491                 bytes_needed -= bytes;
492                 attempts = 3; /* reset counter after successful attempt */
493             } else if (bytes < 0 && errno != EINTR) {
494                 break;
495             }
496         }
497     }
498     entropy_available = rand_pool_entropy_available(pool);
499     if (entropy_available > 0)
500         return entropy_available;
501 #   endif
502
503 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
504     {
505         /* Not yet implemented. */
506     }
507 #   endif
508
509 #   if defined(OPENSSL_RAND_SEED_DEVRANDOM)
510     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
511     {
512         size_t i;
513 #ifdef DEVRANDOM_WAIT
514         static int wait_done = 0;
515
516         /*
517          * On some implementations reading from /dev/urandom is possible
518          * before it is initialized. Therefore we wait for /dev/random
519          * to be readable to make sure /dev/urandom is initialized.
520          */
521         if (!wait_done && bytes_needed > 0) {
522              int f = open(DEVRANDOM_WAIT, O_RDONLY);
523
524              if (f >= 0) {
525                  fd_set fds;
526
527                  FD_ZERO(&fds);
528                  FD_SET(f, &fds);
529                  while (select(f+1, &fds, NULL, NULL, NULL) < 0
530                         && errno == EINTR);
531                  close(f);
532              }
533              wait_done = 1;
534         }
535 #endif
536
537         for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths); i++) {
538             ssize_t bytes = 0;
539             /* Maximum allowed number of consecutive unsuccessful attempts */
540             int attempts = 3;
541             const int fd = get_random_device(i);
542
543             if (fd == -1)
544                 continue;
545
546             while (bytes_needed != 0 && attempts-- > 0) {
547                 buffer = rand_pool_add_begin(pool, bytes_needed);
548                 bytes = read(fd, buffer, bytes_needed);
549
550                 if (bytes > 0) {
551                     rand_pool_add_end(pool, bytes, 8 * bytes);
552                     bytes_needed -= bytes;
553                     attempts = 3; /* reset counter after successful attempt */
554                 } else if (bytes < 0 && errno != EINTR) {
555                     break;
556                 }
557             }
558             if (bytes < 0 || !keep_random_devices_open)
559                 close_random_device(i);
560
561             bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
562         }
563         entropy_available = rand_pool_entropy_available(pool);
564         if (entropy_available > 0)
565             return entropy_available;
566     }
567 #   endif
568
569 #   if defined(OPENSSL_RAND_SEED_RDTSC)
570     entropy_available = rand_acquire_entropy_from_tsc(pool);
571     if (entropy_available > 0)
572         return entropy_available;
573 #   endif
574
575 #   if defined(OPENSSL_RAND_SEED_RDCPU)
576     entropy_available = rand_acquire_entropy_from_cpu(pool);
577     if (entropy_available > 0)
578         return entropy_available;
579 #   endif
580
581 #   if defined(OPENSSL_RAND_SEED_EGD)
582     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
583     if (bytes_needed > 0) {
584         static const char *paths[] = { DEVRANDOM_EGD, NULL };
585         int i;
586
587         for (i = 0; paths[i] != NULL; i++) {
588             buffer = rand_pool_add_begin(pool, bytes_needed);
589             if (buffer != NULL) {
590                 size_t bytes = 0;
591                 int num = RAND_query_egd_bytes(paths[i],
592                                                buffer, (int)bytes_needed);
593                 if (num == (int)bytes_needed)
594                     bytes = bytes_needed;
595
596                 rand_pool_add_end(pool, bytes, 8 * bytes);
597                 entropy_available = rand_pool_entropy_available(pool);
598             }
599             if (entropy_available > 0)
600                 return entropy_available;
601         }
602     }
603 #   endif
604
605     return rand_pool_entropy_available(pool);
606 #  endif
607 }
608 # endif
609 #endif
610
611 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
612 int rand_pool_add_nonce_data(RAND_POOL *pool)
613 {
614     struct {
615         pid_t pid;
616         CRYPTO_THREAD_ID tid;
617         uint64_t time;
618     } data = { 0 };
619
620     /*
621      * Add process id, thread id, and a high resolution timestamp to
622      * ensure that the nonce is unique with high probability for
623      * different process instances.
624      */
625     data.pid = getpid();
626     data.tid = CRYPTO_THREAD_get_current_id();
627     data.time = get_time_stamp();
628
629     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
630 }
631
632 int rand_pool_add_additional_data(RAND_POOL *pool)
633 {
634     struct {
635         CRYPTO_THREAD_ID tid;
636         uint64_t time;
637     } data = { 0 };
638
639     /*
640      * Add some noise from the thread id and a high resolution timer.
641      * The thread id adds a little randomness if the drbg is accessed
642      * concurrently (which is the case for the <master> drbg).
643      */
644     data.tid = CRYPTO_THREAD_get_current_id();
645     data.time = get_timer_bits();
646
647     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
648 }
649
650
651 /*
652  * Get the current time with the highest possible resolution
653  *
654  * The time stamp is added to the nonce, so it is optimized for not repeating.
655  * The current time is ideal for this purpose, provided the computer's clock
656  * is synchronized.
657  */
658 static uint64_t get_time_stamp(void)
659 {
660 # if defined(OSSL_POSIX_TIMER_OKAY)
661     {
662         struct timespec ts;
663
664         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
665             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
666     }
667 # endif
668 # if defined(__unix__) \
669      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
670     {
671         struct timeval tv;
672
673         if (gettimeofday(&tv, NULL) == 0)
674             return TWO32TO64(tv.tv_sec, tv.tv_usec);
675     }
676 # endif
677     return time(NULL);
678 }
679
680 /*
681  * Get an arbitrary timer value of the highest possible resolution
682  *
683  * The timer value is added as random noise to the additional data,
684  * which is not considered a trusted entropy sourec, so any result
685  * is acceptable.
686  */
687 static uint64_t get_timer_bits(void)
688 {
689     uint64_t res = OPENSSL_rdtsc();
690
691     if (res != 0)
692         return res;
693
694 # if defined(__sun) || defined(__hpux)
695     return gethrtime();
696 # elif defined(_AIX)
697     {
698         timebasestruct_t t;
699
700         read_wall_time(&t, TIMEBASE_SZ);
701         return TWO32TO64(t.tb_high, t.tb_low);
702     }
703 # elif defined(OSSL_POSIX_TIMER_OKAY)
704     {
705         struct timespec ts;
706
707 #  ifdef CLOCK_BOOTTIME
708 #   define CLOCK_TYPE CLOCK_BOOTTIME
709 #  elif defined(_POSIX_MONOTONIC_CLOCK)
710 #   define CLOCK_TYPE CLOCK_MONOTONIC
711 #  else
712 #   define CLOCK_TYPE CLOCK_REALTIME
713 #  endif
714
715         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
716             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
717     }
718 # endif
719 # if defined(__unix__) \
720      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
721     {
722         struct timeval tv;
723
724         if (gettimeofday(&tv, NULL) == 0)
725             return TWO32TO64(tv.tv_sec, tv.tv_usec);
726     }
727 # endif
728     return time(NULL);
729 }
730 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */