DRBG: implement a get_nonce() callback
[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 #include "e_os.h"
11 #include <stdio.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/rand.h>
14 #include "rand_lcl.h"
15 #include "internal/rand_int.h"
16 #include <stdio.h>
17 #ifdef OPENSSL_SYS_UNIX
18 # include <sys/types.h>
19 # include <unistd.h>
20 # include <sys/time.h>
21
22 static uint64_t get_time_stamp(void);
23 static uint64_t get_timer_bits(void);
24
25 /* Macro to convert two thirty two bit values into a sixty four bit one */
26 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
27
28 /*
29  * Check for the existence and support of POSIX timers.  The standard
30  * says that the _POSIX_TIMERS macro will have a positive value if they
31  * are available.
32  *
33  * However, we want an additional constraint: that the timer support does
34  * not require an extra library dependency.  Early versions of glibc
35  * require -lrt to be specified on the link line to access the timers,
36  * so this needs to be checked for.
37  *
38  * It is worse because some libraries define __GLIBC__ but don't
39  * support the version testing macro (e.g. uClibc).  This means
40  * an extra check is needed.
41  *
42  * The final condition is:
43  *      "have posix timers and either not glibc or glibc without -lrt"
44  *
45  * The nested #if sequences are required to avoid using a parameterised
46  * macro that might be undefined.
47  */
48 # undef OSSL_POSIX_TIMER_OKAY
49 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
50 #  if defined(__GLIBC__)
51 #   if defined(__GLIBC_PREREQ)
52 #    if __GLIBC_PREREQ(2, 17)
53 #     define OSSL_POSIX_TIMER_OKAY
54 #    endif
55 #   endif
56 #  else
57 #   define OSSL_POSIX_TIMER_OKAY
58 #  endif
59 # endif
60 #endif
61
62 #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
63         !defined(OPENSSL_RAND_SEED_NONE)
64 # error "UEFI and VXWorks only support seeding NONE"
65 #endif
66
67 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
68     || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
69     || defined(OPENSSL_SYS_UEFI))
70
71 # if defined(OPENSSL_SYS_VOS)
72
73 #  ifndef OPENSSL_RAND_SEED_OS
74 #   error "Unsupported seeding method configured; must be os"
75 #  endif
76
77 #  if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
78 #   error "Unsupported HP-PA and IA32 at the same time."
79 #  endif
80 #  if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
81 #   error "Must have one of HP-PA or IA32"
82 #  endif
83
84 /*
85  * The following algorithm repeatedly samples the real-time clock (RTC) to
86  * generate a sequence of unpredictable data.  The algorithm relies upon the
87  * uneven execution speed of the code (due to factors such as cache misses,
88  * interrupts, bus activity, and scheduling) and upon the rather large
89  * relative difference between the speed of the clock and the rate at which
90  * it can be read.  If it is ported to an environment where execution speed
91  * is more constant or where the RTC ticks at a much slower rate, or the
92  * clock can be read with fewer instructions, it is likely that the results
93  * would be far more predictable.  This should only be used for legacy
94  * platforms.
95  *
96  * As a precaution, we assume only 2 bits of entropy per byte.
97  */
98 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
99 {
100     short int code;
101     int i, k;
102     size_t bytes_needed;
103     struct timespec ts;
104     unsigned char v;
105 #  ifdef OPENSSL_SYS_VOS_HPPA
106     long duration;
107     extern void s$sleep(long *_duration, short int *_code);
108 #  else
109     long long duration;
110     extern void s$sleep2(long long *_duration, short int *_code);
111 #  endif
112
113     bytes_needed = rand_pool_bytes_needed(pool, 2 /*entropy_per_byte*/);
114
115     for (i = 0; i < bytes_needed; i++) {
116         /*
117          * burn some cpu; hope for interrupts, cache collisions, bus
118          * interference, etc.
119          */
120         for (k = 0; k < 99; k++)
121             ts.tv_nsec = random();
122
123 #  ifdef OPENSSL_SYS_VOS_HPPA
124         /* sleep for 1/1024 of a second (976 us).  */
125         duration = 1;
126         s$sleep(&duration, &code);
127 #  else
128         /* sleep for 1/65536 of a second (15 us).  */
129         duration = 1;
130         s$sleep2(&duration, &code);
131 #  endif
132
133         /* Get wall clock time, take 8 bits. */
134         clock_gettime(CLOCK_REALTIME, &ts);
135         v = (unsigned char)(ts.tv_nsec & 0xFF);
136         rand_pool_add(pool, arg, &v, sizeof(v) , 2);
137     }
138     return rand_pool_entropy_available(pool);
139 }
140
141 # else
142
143 #  if defined(OPENSSL_RAND_SEED_EGD) && \
144         (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
145 #   error "Seeding uses EGD but EGD is turned off or no device given"
146 #  endif
147
148 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
149 #   error "Seeding uses urandom but DEVRANDOM is not configured"
150 #  endif
151
152 #  if defined(OPENSSL_RAND_SEED_OS)
153 #   if !defined(DEVRANDOM)
154 #    error "OS seeding requires DEVRANDOM to be configured"
155 #   endif
156 #   define OPENSSL_RAND_SEED_DEVRANDOM
157 #   if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
158 #    if __GLIBC_PREREQ(2, 25)
159 #     define OPENSSL_RAND_SEED_GETRANDOM
160 #    endif
161 #   endif
162 #  endif
163
164 #  ifdef OPENSSL_RAND_SEED_GETRANDOM
165 #   include <sys/random.h>
166 #  endif
167
168 #  if defined(OPENSSL_RAND_SEED_LIBRANDOM)
169 #   error "librandom not (yet) supported"
170 #  endif
171
172 /*
173  * Try the various seeding methods in turn, exit when successful.
174  *
175  * TODO(DRBG): If more than one entropy source is available, is it
176  * preferable to stop as soon as enough entropy has been collected
177  * (as favored by @rsalz) or should one rather be defensive and add
178  * more entropy than requested and/or from different sources?
179  *
180  * Currently, the user can select multiple entropy sources in the
181  * configure step, yet in practice only the first available source
182  * will be used. A more flexible solution has been requested, but
183  * currently it is not clear how this can be achieved without
184  * overengineering the problem. There are many parameters which
185  * could be taken into account when selecting the order and amount
186  * of input from the different entropy sources (trust, quality,
187  * possibility of blocking).
188  */
189 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
190 {
191 #  ifdef OPENSSL_RAND_SEED_NONE
192     return rand_pool_entropy_available(pool);
193 #  else
194     size_t bytes_needed;
195     size_t entropy_available = 0;
196     unsigned char *buffer;
197
198 #   ifdef OPENSSL_RAND_SEED_GETRANDOM
199     bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
200     buffer = rand_pool_add_begin(pool, bytes_needed);
201     if (buffer != NULL) {
202         size_t bytes = 0;
203
204         if (getrandom(buffer, bytes_needed, 0) == (int)bytes_needed)
205             bytes = bytes_needed;
206
207         rand_pool_add_end(pool, bytes, 8 * bytes);
208         entropy_available = rand_pool_entropy_available(pool);
209     }
210     if (entropy_available > 0)
211         return entropy_available;
212 #   endif
213
214 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
215     {
216         /* Not yet implemented. */
217     }
218 #   endif
219
220 #   ifdef OPENSSL_RAND_SEED_DEVRANDOM
221     bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
222     if (bytes_needed > 0) {
223         static const char *paths[] = { DEVRANDOM, NULL };
224         FILE *fp;
225         int i;
226
227         for (i = 0; paths[i] != NULL; i++) {
228             if ((fp = fopen(paths[i], "rb")) == NULL)
229                 continue;
230             setbuf(fp, NULL);
231             buffer = rand_pool_add_begin(pool, bytes_needed);
232             if (buffer != NULL) {
233                 size_t bytes = 0;
234                 if (fread(buffer, 1, bytes_needed, fp) == bytes_needed)
235                     bytes = bytes_needed;
236
237                 rand_pool_add_end(pool, bytes, 8 * bytes);
238                 entropy_available = rand_pool_entropy_available(pool);
239             }
240             fclose(fp);
241             if (entropy_available > 0)
242                 return entropy_available;
243
244             bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
245         }
246     }
247 #   endif
248
249 #   ifdef OPENSSL_RAND_SEED_RDTSC
250     entropy_available = rand_acquire_entropy_from_tsc(pool);
251     if (entropy_available > 0)
252         return entropy_available;
253 #   endif
254
255 #   ifdef OPENSSL_RAND_SEED_RDCPU
256     entropy_available = rand_acquire_entropy_from_cpu(pool);
257     if (entropy_available > 0)
258         return entropy_available;
259 #   endif
260
261 #   ifdef OPENSSL_RAND_SEED_EGD
262     bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
263     if (bytes_needed > 0) {
264         static const char *paths[] = { DEVRANDOM_EGD, NULL };
265         int i;
266
267         for (i = 0; paths[i] != NULL; i++) {
268             buffer = rand_pool_add_begin(pool, bytes_needed);
269             if (buffer != NULL) {
270                 size_t bytes = 0;
271                 int num = RAND_query_egd_bytes(paths[i],
272                                                buffer, (int)bytes_needed);
273                 if (num == (int)bytes_needed)
274                     bytes = bytes_needed;
275
276                 rand_pool_add_end(pool, bytes, 8 * bytes);
277                 entropy_available = rand_pool_entropy_available(pool);
278             }
279             if (entropy_available > 0)
280                 return entropy_available;
281         }
282     }
283 #   endif
284
285     return rand_pool_entropy_available(pool);
286 #  endif
287 }
288 # endif
289 #endif
290
291 #ifdef OPENSSL_SYS_UNIX
292 int rand_pool_add_nonce_data(RAND_POOL *pool)
293 {
294     struct {
295         pid_t pid;
296         CRYPTO_THREAD_ID tid;
297         uint64_t time;
298     } data = { 0 };
299
300     /*
301      * Add process id, thread id, and a high resolution timestamp to
302      * ensure that the nonce is unique whith high probability for
303      * different process instances.
304      */
305     data.pid = getpid();
306     data.tid = CRYPTO_THREAD_get_current_id();
307     data.time = get_time_stamp();
308
309     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
310 }
311
312 int rand_pool_add_additional_data(RAND_POOL *pool)
313 {
314     struct {
315         CRYPTO_THREAD_ID tid;
316         uint64_t time;
317     } data = { 0 };
318
319     /*
320      * Add some noise from the thread id and a high resolution timer.
321      * The thread id adds a little randomness if the drbg is accessed
322      * concurrently (which is the case for the <master> drbg).
323      */
324     data.tid = CRYPTO_THREAD_get_current_id();
325     data.time = get_timer_bits();
326
327     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
328 }
329
330
331
332 /*
333  * Get the current time with the highest possible resolution
334  *
335  * The time stamp is added to the nonce, so it is optimized for not repeating.
336  * The current time is ideal for this purpose, provided the computer's clock
337  * is synchronized.
338  */
339 static uint64_t get_time_stamp(void)
340 {
341 # if defined(OSSL_POSIX_TIMER_OKAY)
342     {
343         struct timespec ts;
344
345         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
346             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
347     }
348 # endif
349 # if defined(__unix__) \
350      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
351     {
352         struct timeval tv;
353
354         if (gettimeofday(&tv, NULL) == 0)
355             return TWO32TO64(tv.tv_sec, tv.tv_usec);
356     }
357 # endif
358     return time(NULL);
359 }
360
361 /*
362  * Get an arbitrary timer value of the highest possible resolution
363  *
364  * The timer value is added as random noise to the additional data,
365  * which is not considered a trusted entropy sourec, so any result
366  * is acceptable.
367  */
368 static uint64_t get_timer_bits(void)
369 {
370     uint64_t res = OPENSSL_rdtsc();
371
372     if (res != 0)
373         return res;
374
375 # if defined(__sun) || defined(__hpux)
376     return gethrtime();
377 # elif defined(_AIX)
378     {
379         timebasestruct_t t;
380
381         read_wall_time(&t, TIMEBASE_SZ);
382         return TWO32TO64(t.tb_high, t.tb_low);
383     }
384 # elif defined(OSSL_POSIX_TIMER_OKAY)
385     {
386         struct timespec ts;
387
388 #  ifdef CLOCK_BOOTTIME
389 #   define CLOCK_TYPE CLOCK_BOOTTIME
390 #  elif defined(_POSIX_MONOTONIC_CLOCK)
391 #   define CLOCK_TYPE CLOCK_MONOTONIC
392 #  else
393 #   define CLOCK_TYPE CLOCK_REALTIME
394 #  endif
395
396         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
397             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
398     }
399 # endif
400 # if defined(__unix__) \
401      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
402     {
403         struct timeval tv;
404
405         if (gettimeofday(&tv, NULL) == 0)
406             return TWO32TO64(tv.tv_sec, tv.tv_usec);
407     }
408 # endif
409     return time(NULL);
410 }
411 #endif