Debian Codegraph @

jitterentropy-base-user.h

raw symbols SCIP
1 /*
2 * Non-physical true random number generator based on timing jitter.
3 *
4 * Copyright Stephan Mueller <[email protected]>, 2013 - 2026
5 *
6 * License
7 * =======
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, and the entire permission notice in its entirety,
14 * including the disclaimer of warranties.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. The name of the author may not be used to endorse or promote
19 * products derived from this software without specific prior
20 * written permission.
21 *
22 * ALTERNATIVELY, this product may be distributed under the terms of
23 * the GNU General Public License, in which case the provisions of the GPL are
24 * required INSTEAD OF the above restrictions. (This clause is
25 * necessary due to a potential bad interaction between the GPL and
26 * the restrictions contained in a BSD-style copyright.)
27 *
28 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
29 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
31 * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
32 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
34 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
38 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
39 * DAMAGE.
40 */
41
42 #ifndef _JITTERENTROPY_BASE_USER_H
43 #define _JITTERENTROPY_BASE_USER_H
44
45 /*
46 * Set the following defines as needed for your environment
47 * Compilation for AWS-LC #define AWSLC
48 * Compilation for libgcrypt #define LIBGCRYPT
49 * Compilation for OpenSSL #define OPENSSL
50 */
51
52 #include <sys/types.h>
53 #include <sys/stat.h>
54
55 #include <limits.h>
56 #include <time.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61
62 #include <fcntl.h>
63 #include <unistd.h>
64 #include <errno.h>
65 #include <sched.h>
66
67 #ifdef LIBGCRYPT
68 #include <gcrypt.h>
69 #endif
70
71 #ifdef OPENSSL
72 #include <openssl/crypto.h>
73 #include <openssl/evp.h>
74 #endif
75
76 #if defined(AWSLC)
77 #include <openssl/crypto.h>
78 #endif
79
80 #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
81 #include <sys/mman.h>
82 #endif
83
84 #ifdef __MACH__
85 #include <assert.h>
86 #include <CoreServices/CoreServices.h>
87 #include <mach/mach.h>
88 #include <mach/mach_time.h>
89 #include <unistd.h>
90 #endif
91
92 #ifdef __APPLE__
93 #include <sys/sysctl.h>
94 #endif
95
96 /* Override this, if you want to allocate more than 2 MB of secure memory */
97 #ifndef JENT_SECURE_MEMORY_SIZE_MAX
98 #define JENT_SECURE_MEMORY_SIZE_MAX 2097152
99 #endif
100
101 #if (__x86_64__) || (__i386__)
102 /* Support rdtsc read on 64-bit and 32-bit x86 architectures */
103
104 #ifdef __x86_64__
105 /* specify 64 bit type since long is 32 bits in LLP64 x86_64 systems */
106 # define DECLARE_ARGS(val, low, high) uint64_t low, high
107 # define EAX_EDX_VAL(val, low, high) ((low) | (high) << 32)
108 # define EAX_EDX_RET(val, low, high) "=a" (low), "=d" (high)
109 #elif __i386__
110 # define DECLARE_ARGS(val, low, high) unsigned long long val
111 # define EAX_EDX_VAL(val, low, high) val
112 # define EAX_EDX_RET(val, low, high) "=A" (val)
113 #endif
114
115 static inline void jent_get_nstime(uint64_t *out)
116 {
117 DECLARE_ARGS(val, low, high);
118 #ifdef __sun__
119 __asm("rdtsc" : EAX_EDX_RET(val, low, high));
120 #else
121 __asm__ __volatile__("rdtsc" : EAX_EDX_RET(val, low, high));
122 #endif
123 *out = EAX_EDX_VAL(val, low, high);
124 }
125
126 #elif defined(__aarch64__)
127
128 #ifndef AARCH64_NSTIME_REGISTER
129 #define AARCH64_NSTIME_REGISTER "cntvct_el0"
130 #endif
131
132 static inline void jent_get_nstime(uint64_t *out)
133 {
134 uint64_t ctr_val;
135 #if !defined(__MACH__)
136 /*
137 * Use the system counter for aarch64 (64 bit ARM)...
138 */
139 __asm__ __volatile__("mrs %0, " AARCH64_NSTIME_REGISTER : "=r" (ctr_val));
140 #else
141 /*
142 * Except on modern Apple platforms. Especially on M1 generation Arm64
143 * CPUs, the system counter is too coarse. Instead, use
144 * clock_gettime_nsec_np(CLOCK_UPTIME_RAW), that is equivalent to
145 * march_absolute_time(), but scaled to nanoseconds. See e.g.
146 * https://www.manpagez.com/man/3/clock_gettime_nsec_np/.
147 */
148 ctr_val = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
149 #endif
150 *out = ctr_val;
151 }
152
153 #elif defined(__s390x__)
154
155 static inline void jent_get_nstime(uint64_t *out)
156 {
157 /*
158 * This is MVS+STCK code! Enable it with -S in the compiler.
159 *
160 * uint64_t clk;
161 * __asm__ __volatile__("stck %0" : "=m" (clk) : : "cc");
162 * *out = (uint64_t)(clk);
163 */
164
165 /*
166 * This is GCC+STCKE code. STCKE command and data format:
167 * z/Architecture - Principles of Operation
168 * http://publibz.boulder.ibm.com/epubs/pdf/dz9zr007.pdf
169 *
170 * The current value of bits 0-103 of the TOD clock is stored in bytes
171 * 1-13 of the sixteen-byte output:
172 *
173 * bits 0-7: zeros (reserved for future extention)
174 * bits 8-111: TOD Clock value
175 * bits 112-127: Programmable Field
176 *
177 * Output bit 59 (TOD-Clock bit 51) effectively increments every
178 * microsecond. Bits 60 to 111 of STCKE output are fractions of
179 * a miscrosecond: bit 59 is 1.0us, bit 60 is .5us, bit 61 is .25us,
180 * bit 62 is .125us, bit 63 is 62.5ns, etc.
181 *
182 * Some of these bits can be implemented, some not. 64 bits of
183 * the TOD clock are implemented usually nowadays, these are
184 * bits 8-71 of the output.
185 *
186 * The stepping value of TOD-clock bit position 63, if implemented,
187 * is 2^-12 microseconds, or approximately 244 picoseconds. This value
188 * is called a clock unit.
189 */
190
191 uint8_t clk[16];
192
193 __asm__ __volatile__("stcke %0" : "=Q" (clk) : : "cc");
194
195 /* s390x is big-endian, so just perfom a byte-by-byte copy */
196 *out = *(uint64_t *)(clk + 1);
197 }
198
199 #elif defined(__powerpc)
200 /*
201 * Uncomment this for newer PPC CPUs
202 * Newer PPC CPUs do not support mftbu/mftb
203 * these instructions were obsoleted and replaced by
204 * mfspr. special processor registers 268 and 269 are the
205 * ones we want.
206 */
207 /* #define POWER_PC_USE_NEW_INSTRUCTIONS */
208
209 /* taken from http://www.ecrypt.eu.org/ebats/cpucycles.html */
210
211 static inline void jent_get_nstime(uint64_t *out)
212 {
213 unsigned long high;
214 unsigned long low;
215 unsigned long newhigh;
216 uint64_t result;
217 #ifdef POWER_PC_USE_NEW_INSTRUCTIONS /* Newer PPC CPUs do not support mftbu/mftb */
218 __asm__ __volatile__(
219 "Lcpucycles:mfspr %0, 269;mfspr %1, 268;mfspr %2, 269;cmpw %0,%2;bne Lcpucycles"
220 : "=r" (high), "=r" (low), "=r" (newhigh)
221 );
222 #else
223 __asm__ __volatile__(
224 "Lcpucycles:mftbu %0;mftb %1;mftbu %2;cmpw %0,%2;bne Lcpucycles"
225 : "=r" (high), "=r" (low), "=r" (newhigh)
226 );
227 #endif
228 result = high;
229 result <<= 32;
230 result |= low;
231 *out = result;
232 }
233
234 #else /* (__x86_64__) || (__i386__) || (__aarch64__) || (__s390x__) || (__powerpc) */
235
236 static inline void jent_get_nstime(uint64_t *out)
237 {
238 /*
239 * OSX does not have clock_gettime -- taken from
240 * http://developer.apple.com/library/mac/qa/qa1398/_index.html
241 */
242 # ifdef __MACH__
243 *out = mach_absolute_time();
244 # elif _AIX
245 /*
246 * clock_gettime() on AIX returns a timer value that increments in
247 * steps of 1000
248 */
249 uint64_t tmp = 0;
250 timebasestruct_t aixtime;
251 read_real_time(&aixtime, TIMEBASE_SZ);
252 time_base_to_time(&aixtime, TIMEBASE_SZ);
253 tmp = (uint64_t)aixtime.tb_high * 1000000000UL;
254 tmp += (uint64_t)aixtime.tb_low;
255 *out = tmp;
256 # else /* __MACH__ */
257 /* we could use CLOCK_MONOTONIC(_RAW), but with CLOCK_REALTIME
258 * we get some nice extra entropy once in a while from the NTP actions
259 * that we want to use as well... though, we do not rely on that
260 * extra little entropy */
261 uint64_t tmp = 0;
262 struct timespec time;
263 if (clock_gettime(CLOCK_REALTIME, &time) == 0) {
264 tmp = ((uint64_t)time.tv_sec & 0xFFFFFFFF) * 1000000000UL;
265 tmp = tmp + (uint64_t)time.tv_nsec;
266 }
267 *out = tmp;
268 # endif /* __MACH__ */
269 }
270
271 #endif /* (__x86_64__) || (__i386__) || (__aarch64__) */
272
273 static inline void jent_memset_secure(void *s, size_t n)
274 {
275 #if (defined(AWSLC) || defined(OPENSSL))
276 OPENSSL_cleanse(s, n);
277 #else
278 memset(s, 0, n);
279 __asm__ __volatile__("" : : "r" (s) : "memory");
280 #endif
281 }
282
283 static inline void *jent_zalloc(size_t len)
284 {
285 #define JENT_BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
286 #define JENT_IS_POWER_OF_2(n) (JENT_BUILD_BUG_ON((n & (n - 1)) != 0))
287
288 void *tmp = NULL;
289
290 #ifdef LIBGCRYPT
291 /* Set the maximum usable locked memory to 2 MiB at fist call.
292 *
293 * You may have to adapt or delete this, if you
294 * also use libgcrypt at other places in your software!
295 */
296 if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P)) {
297 gcry_control(GCRYCTL_INIT_SECMEM, JENT_SECURE_MEMORY_SIZE_MAX, 0);
298 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
299 }
300 /* When using the libgcrypt secure memory mechanism, all precautions
301 * are taken to protect our state. If the user disables secmem during
302 * runtime, it is his decision and we thus try not to overrule his
303 * decision for less memory protection. */
304 #define CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY
305 tmp = gcry_xmalloc_secure(len);
306 #elif defined(AWSLC)
307 tmp = OPENSSL_malloc(len);
308 #elif defined(OPENSSL)
309 /* We only call secure malloc initialization here,
310 * if not already done. The 2 MiB max. reserved here
311 * are sufficient for jitterentropy but probably
312 * too small for a whole application doing crypto
313 * operations with OpenSSL.
314 *
315 * Both min and max value must be power of 2.
316 * min must be smaller than max.
317 *
318 * May preallocate more before making the first
319 * call into jitterentropy!*/
320 JENT_IS_POWER_OF_2(JENT_SECURE_MEMORY_SIZE_MAX);
321 if (CRYPTO_secure_malloc_initialized() ||
322 CRYPTO_secure_malloc_init(JENT_SECURE_MEMORY_SIZE_MAX, 32)) {
323 tmp = OPENSSL_secure_malloc(len);
324 }
325 #define CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY
326 /* If secure memory was not available, OpenSSL
327 * falls back to "normal" memory. So double check. */
328 if (tmp && !CRYPTO_secure_allocated(tmp)) {
329 OPENSSL_secure_free(tmp);
330 tmp = NULL;
331 }
332
333 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
334 tmp = malloc(len);
335 if (!tmp)
336 return NULL;
337 /*
338 * prevent paging out of the memory state to swap space
339 * if this fails, check the current memory lock limits
340 * and capabilities (e.g. RLIMIT_MEMLOCK and CAP_IPC_LOCK)
341 */
342 #ifndef JENT_CONF_RELAX_MLOCK
343 #define CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY
344 if (mlock(tmp, len)) {
345 #else
346 /*
347 * use this only for CI or restricted containers if not possible
348 * otherwise
349 */
350 if (mlock(tmp, len) && errno != EPERM && errno != EAGAIN) {
351 #endif
352 free(tmp);
353 return NULL;
354 }
355
356 #else /* LIBGCRYPT */
357
358 /* we have no secure memory allocation! Hence
359 * we do not set CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY */
360 tmp = malloc(len);
361
362 #endif /* LIBGCRYPT */
363
364 if(NULL != tmp)
365 jent_memset_secure(tmp, len);
366 return tmp;
367
368 #undef JENT_IS_POWER_OF_2
369 #undef JENT_BUILD_BUG_ON
370 }
371
372 static inline void jent_zfree(void *ptr, size_t len)
373 {
374 #ifdef LIBGCRYPT
375 /* gcry_free automatically wipes memory allocated with
376 * gcry_(x)malloc_secure */
377 (void) len;
378 gcry_free(ptr);
379
380 #elif defined(AWSLC)
381 /* AWS-LC stores the length of allocated memory internally and automatically wipes it in OPENSSL_free */
382 (void) len;
383 OPENSSL_free(ptr);
384
385 #elif defined(OPENSSL)
386 OPENSSL_cleanse(ptr, len);
387 OPENSSL_secure_free(ptr);
388
389 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
390 /* while memory returned to the OS is automatically unlocked,
391 * it is not known how long libc keeps this memory cached
392 * internally therefore its more robust to nevertheless
393 * unlock here. */
394 munlock(ptr, len);
395 jent_memset_secure(ptr, len);
396 free(ptr);
397
398 #else
399 jent_memset_secure(ptr, len);
400 free(ptr);
401 #endif /* LIBGCRYPT */
402 }
403
404 static inline int jent_fips_enabled(void)
405 {
406 #ifdef LIBGCRYPT
407 return gcry_fips_mode_active();
408 #elif defined(AWSLC)
409 return FIPS_mode();
410 #elif defined(OPENSSL)
411 return EVP_default_properties_is_fips_enabled(NULL);
412 #else
413 #define FIPS_MODE_SWITCH_FILE "/proc/sys/crypto/fips_enabled"
414 char buf[2] = "0";
415 int fd = 0;
416 ssize_t rlen;
417
418 if ((fd = open(FIPS_MODE_SWITCH_FILE, O_RDONLY)) >= 0) {
419 do {
420 rlen = read(fd, buf, sizeof(buf));
421 } while (rlen < 0 && errno == EINTR);
422 close(fd);
423 if (rlen <= 0)
424 return 0;
425 }
426 if (buf[0] == '1')
427 return 1;
428 else
429 return 0;
430 #endif
431 }
432
433 static inline long jent_ncpu(void)
434 {
435 #if defined(_POSIX_SOURCE) || defined(__APPLE__)
436 long ncpu = sysconf(_SC_NPROCESSORS_ONLN);
437
438 if (ncpu == -1)
439 return -errno;
440
441 if (ncpu == 0)
442 return -EFAULT;
443
444 return ncpu;
445 #else
446 return 1;
447 #endif
448 }
449
450 #ifdef __linux__
451
452 # if defined(_SC_LEVEL1_DCACHE_SIZE) && \
453 defined(_SC_LEVEL2_CACHE_SIZE) && \
454 defined(_SC_LEVEL3_CACHE_SIZE)
455
456 static inline void jent_get_cachesize_sysconf(long *l1, long *l2, long *l3)
457 {
458 *l1 = sysconf(_SC_LEVEL1_DCACHE_SIZE);
459 *l2 = sysconf(_SC_LEVEL2_CACHE_SIZE);
460 *l3 = sysconf(_SC_LEVEL3_CACHE_SIZE);
461 }
462
463 # else
464
465 static inline void jent_get_cachesize_sysconf(long *l1, long *l2, long *l3)
466 {
467 *l1 = 0;
468 *l2 = 0;
469 *l3 = 0;
470 }
471 # endif
472
473 static inline void jent_get_cachesize_sysfs(long *l1, long *l2, long *l3)
474 {
475 #define JENT_SYSFS_CACHE_DIR "/sys/devices/system/cpu/cpu0/cache"
476 long val;
477 unsigned int i;
478 char buf[10], file[50];
479 int fd = 0;
480 ssize_t rlen;
481
482 /* Iterate over all caches */
483 for (i = 0; i < 4; i++) {
484 unsigned int shift = 0;
485 char *ext, *endptr;
486
487 /*
488 * Check the cache type - we are only interested in Unified
489 * and Data caches.
490 */
491 memset(buf, 0, sizeof(buf));
492 snprintf(file, sizeof(file), "%s/index%u/type",
493 JENT_SYSFS_CACHE_DIR, i);
494 fd = open(file, O_RDONLY);
495 if (fd < 0)
496 continue;
497 do {
498 rlen = read(fd, buf, sizeof(buf));
499 } while (rlen < 0 && errno == EINTR);
500 close(fd);
501 if (rlen <= 0)
502 continue;
503 buf[sizeof(buf) - 1] = '\0';
504
505 if (strncmp(buf, "Data", 4) && strncmp(buf, "Unified", 7))
506 continue;
507
508 /* Get size of cache */
509 memset(buf, 0, sizeof(buf));
510 snprintf(file, sizeof(file), "%s/index%u/size",
511 JENT_SYSFS_CACHE_DIR, i);
512
513 fd = open(file, O_RDONLY);
514 if (fd < 0)
515 continue;
516 do {
517 rlen = read(fd, buf, sizeof(buf));
518 } while (rlen < 0 && errno == EINTR);
519 close(fd);
520 if (rlen <= 0)
521 continue;
522 buf[sizeof(buf) - 1] = '\0';
523
524 ext = strstr(buf, "K");
525 if (ext) {
526 shift = 10;
527 *ext = '\0';
528 } else {
529 ext = strstr(buf, "M");
530 if (ext) {
531 shift = 20;
532 *ext = '\0';
533 }
534 }
535
536 errno = 0;
537 val = strtol(buf, &endptr, 10);
538 if (errno != 0 || endptr == buf || val <= 0 || val == LONG_MAX)
539 continue;
540 val <<= shift;
541
542 if (!*l1)
543 *l1 = val;
544 else if (!*l2)
545 *l2 = val;
546 else {
547 *l3 = val;
548 break;
549 }
550 }
551 #undef JENT_SYSFS_CACHE_DIR
552 }
553
554 #endif
555
556 #ifdef __APPLE__
557
558 static inline void jent_get_cachesize_sysconf(long *l1, long *l2, long *l3)
559 {
560 size_t size;
561
562 size = sizeof(*l1);
563 if (sysctlbyname("hw.l1dcachesize", l1, &size, NULL, 0) != 0) {
564 *l1 = 0;
565 }
566
567 size = sizeof(*l2);
568 if (sysctlbyname("hw.l2cachesize", l2, &size, NULL, 0) != 0) {
569 *l2 = 0;
570 }
571
572 size = sizeof(*l3);
573 if (sysctlbyname("hw.l3cachesize", l3, &size, NULL, 0) != 0) {
574 *l3 = 0;
575 }
576 }
577
578 #endif
579
580 #if defined(__linux__) || defined(__APPLE__)
581
582 static inline uint32_t jent_cache_size_to_memory(long l1, long l2, long l3,
583 int all_caches)
584 {
585 uint32_t cache_size = 0;
586
587 /* Cache size reported by system */
588 if (l1 > 0)
589 cache_size += (uint32_t)l1;
590 if (all_caches) {
591 if (l2 > 0)
592 cache_size += (uint32_t)l2;
593 if (l3 > 0)
594 cache_size += (uint32_t)l3;
595 }
596
597 /* Force the output_size to be of the form (bounding_power_of_2 - 1). */
598 cache_size |= (cache_size >> 1);
599 cache_size |= (cache_size >> 2);
600 cache_size |= (cache_size >> 4);
601 cache_size |= (cache_size >> 8);
602 cache_size |= (cache_size >> 16);
603
604 return cache_size;
605 }
606
607 static inline uint32_t jent_cache_size_roundup(int all_caches)
608 {
609 uint32_t cache_size = 0;
610
611 long l1 = 0, l2 = 0, l3 = 0;
612
613 jent_get_cachesize_sysconf(&l1, &l2, &l3);
614
615 cache_size = jent_cache_size_to_memory(l1, l2, l3, all_caches);
616 #ifdef __linux__
617 if (cache_size == 0) {
618 jent_get_cachesize_sysfs(&l1, &l2, &l3);
619 cache_size = jent_cache_size_to_memory(l1, l2, l3,
620 all_caches);
621
622 if (cache_size == 0)
623 return 0;
624 }
625 #endif
626
627 /*
628 * Make the output_size the smallest power of 2 strictly
629 * greater than cache_size.
630 */
631 cache_size++;
632
633 return cache_size;
634 }
635
636 #else /* __linux__ || __APPLE__ */
637
638 static inline uint32_t jent_cache_size_roundup(int all_caches)
639 {
640 (void)all_caches;
641 return 0;
642 }
643
644 #endif /* __linux__ || __APPLE__ */
645
646 static inline void jent_yield(void)
647 {
648 sched_yield();
649 }
650
651 /* --- helpers needed in user space -- */
652
653 static inline uint64_t rol64(uint64_t x, int n)
654 {
655 return ( (x << (n&(64-1))) | (x >> ((64-n)&(64-1))) );
656 }
657
658 #endif /* _JITTERENTROPY_BASE_USER_H */