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