Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

479 lignes
12 KiB

  1. /*
  2. * Non-physical true random number generator based on timing jitter.
  3. *
  4. * Copyright Stephan Mueller <smueller@chronox.de>, 2013 - 2022
  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. #ifndef _JITTERENTROPY_BASE_USER_H
  42. #define _JITTERENTROPY_BASE_USER_H
  43. /*
  44. * Set the following defines as needed for your environment
  45. * Compilation for AWS-LC #define AWSLC
  46. * Compilation for libgcrypt #define LIBGCRYPT
  47. * Compilation for OpenSSL #define OPENSSL
  48. */
  49. #include <limits.h>
  50. #include <time.h>
  51. #include <stdint.h>
  52. #include <stdio.h>
  53. #include <stdlib.h>
  54. #include <string.h>
  55. #include <sys/types.h>
  56. #include <sys/stat.h>
  57. #include <fcntl.h>
  58. #include <unistd.h>
  59. #include <errno.h>
  60. #include <sched.h>
  61. /* Timer-less entropy source */
  62. #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
  63. #include <pthread.h>
  64. #endif /* JENT_CONF_ENABLE_INTERNAL_TIMER */
  65. #ifdef LIBGCRYPT
  66. #include <config.h>
  67. #include "g10lib.h"
  68. #endif
  69. #ifdef OPENSSL
  70. #include <openssl/crypto.h>
  71. #ifdef OPENSSL_FIPS
  72. #include <openssl/fips.h>
  73. #endif
  74. #endif
  75. #if defined(AWSLC)
  76. #include <openssl/crypto.h>
  77. #endif
  78. #ifdef __MACH__
  79. #include <assert.h>
  80. #include <CoreServices/CoreServices.h>
  81. #include <mach/mach.h>
  82. #include <mach/mach_time.h>
  83. #include <unistd.h>
  84. #endif
  85. #if (__x86_64__) || (__i386__)
  86. /* Support rdtsc read on 64-bit and 32-bit x86 architectures */
  87. #ifdef __x86_64__
  88. /* specify 64 bit type since long is 32 bits in LLP64 x86_64 systems */
  89. # define DECLARE_ARGS(val, low, high) uint64_t low, high
  90. # define EAX_EDX_VAL(val, low, high) ((low) | (high) << 32)
  91. # define EAX_EDX_RET(val, low, high) "=a" (low), "=d" (high)
  92. #elif __i386__
  93. # define DECLARE_ARGS(val, low, high) unsigned long val
  94. # define EAX_EDX_VAL(val, low, high) val
  95. # define EAX_EDX_RET(val, low, high) "=A" (val)
  96. #endif
  97. static inline void jent_get_nstime(uint64_t *out)
  98. {
  99. DECLARE_ARGS(val, low, high);
  100. asm volatile("rdtsc" : EAX_EDX_RET(val, low, high));
  101. *out = EAX_EDX_VAL(val, low, high);
  102. }
  103. #elif defined(__aarch64__)
  104. static inline void jent_get_nstime(uint64_t *out)
  105. {
  106. uint64_t ctr_val;
  107. /*
  108. * Use the system counter for aarch64 (64 bit ARM).
  109. */
  110. asm volatile("mrs %0, cntvct_el0" : "=r" (ctr_val));
  111. *out = ctr_val;
  112. }
  113. #elif defined(__s390x__)
  114. static inline void jent_get_nstime(uint64_t *out)
  115. {
  116. /*
  117. * This is MVS+STCK code! Enable it with -S in the compiler.
  118. *
  119. * uint64_t clk;
  120. * __asm__ volatile("stck %0" : "=m" (clk) : : "cc");
  121. * *out = (uint64_t)(clk);
  122. */
  123. /*
  124. * This is GCC+STCKE code. STCKE command and data format:
  125. * z/Architecture - Principles of Operation
  126. * http://publibz.boulder.ibm.com/epubs/pdf/dz9zr007.pdf
  127. *
  128. * The current value of bits 0-103 of the TOD clock is stored in bytes
  129. * 1-13 of the sixteen-byte output:
  130. *
  131. * bits 0-7: zeros (reserved for future extention)
  132. * bits 8-111: TOD Clock value
  133. * bits 112-127: Programmable Field
  134. *
  135. * Output bit 59 (TOD-Clock bit 51) effectively increments every
  136. * microsecond. Bits 60 to 111 of STCKE output are fractions of
  137. * a miscrosecond: bit 59 is 1.0us, bit 60 is .5us, bit 61 is .25us,
  138. * bit 62 is .125us, bit 63 is 62.5ns, etc.
  139. *
  140. * Some of these bits can be implemented, some not. 64 bits of
  141. * the TOD clock are implemented usually nowadays, these are
  142. * bits 8-71 of the output.
  143. *
  144. * The stepping value of TOD-clock bit position 63, if implemented,
  145. * is 2^-12 microseconds, or approximately 244 picoseconds. This value
  146. * is called a clock unit.
  147. */
  148. uint8_t clk[16];
  149. asm volatile("stcke %0" : "=Q" (clk) : : "cc");
  150. /* s390x is big-endian, so just perfom a byte-by-byte copy */
  151. *out = *(uint64_t *)(clk + 1);
  152. }
  153. #elif defined(__powerpc)
  154. /* taken from http://www.ecrypt.eu.org/ebats/cpucycles.html */
  155. static inline void jent_get_nstime(uint64_t *out)
  156. {
  157. unsigned long high;
  158. unsigned long low;
  159. unsigned long newhigh;
  160. uint64_t result;
  161. asm volatile(
  162. "Lcpucycles:mftbu %0;mftb %1;mftbu %2;cmpw %0,%2;bne Lcpucycles"
  163. : "=r" (high), "=r" (low), "=r" (newhigh)
  164. );
  165. result = high;
  166. result <<= 32;
  167. result |= low;
  168. *out = result;
  169. }
  170. #else /* (__x86_64__) || (__i386__) || (__aarch64__) || (__s390x__) || (__powerpc) */
  171. static inline void jent_get_nstime(uint64_t *out)
  172. {
  173. /* OSX does not have clock_gettime -- taken from
  174. * http://developer.apple.com/library/mac/qa/qa1398/_index.html */
  175. # ifdef __MACH__
  176. *out = mach_absolute_time();
  177. # elif _AIX
  178. /* clock_gettime() on AIX returns a timer value that increments in
  179. * steps of 1000
  180. */
  181. uint64_t tmp = 0;
  182. timebasestruct_t aixtime;
  183. read_real_time(&aixtime, TIMEBASE_SZ);
  184. tmp = aixtime.tb_high;
  185. tmp = tmp << 32;
  186. tmp = tmp | aixtime.tb_low;
  187. *out = tmp;
  188. # else /* __MACH__ */
  189. /* we could use CLOCK_MONOTONIC(_RAW), but with CLOCK_REALTIME
  190. * we get some nice extra entropy once in a while from the NTP actions
  191. * that we want to use as well... though, we do not rely on that
  192. * extra little entropy */
  193. uint64_t tmp = 0;
  194. struct timespec time;
  195. if (clock_gettime(CLOCK_REALTIME, &time) == 0)
  196. {
  197. tmp = ((uint64_t)time.tv_sec & 0xFFFFFFFF) * 1000000000UL;
  198. tmp = tmp + (uint64_t)time.tv_nsec;
  199. }
  200. *out = tmp;
  201. # endif /* __MACH__ */
  202. }
  203. #endif /* (__x86_64__) || (__i386__) || (__aarch64__) */
  204. static inline void *jent_zalloc(size_t len)
  205. {
  206. void *tmp = NULL;
  207. #ifdef LIBGCRYPT
  208. /* When using the libgcrypt secure memory mechanism, all precautions
  209. * are taken to protect our state. If the user disables secmem during
  210. * runtime, it is his decision and we thus try not to overrule his
  211. * decision for less memory protection. */
  212. #define CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY
  213. tmp = gcry_xmalloc_secure(len);
  214. #elif defined(OPENSSL) || defined(AWSLC)
  215. /* Does this allocation implies secure memory use? */
  216. tmp = OPENSSL_malloc(len);
  217. #else
  218. /* we have no secure memory allocation! Hence
  219. * we do not set CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY */
  220. tmp = malloc(len);
  221. #endif /* LIBGCRYPT */
  222. if(NULL != tmp)
  223. memset(tmp, 0, len);
  224. return tmp;
  225. }
  226. static inline void jent_zfree(void *ptr, unsigned int len)
  227. {
  228. #ifdef LIBGCRYPT
  229. memset(ptr, 0, len);
  230. gcry_free(ptr);
  231. #elif defined(AWSLC)
  232. /* AWS-LC stores the length of allocated memory internally and automatically wipes it in OPENSSL_free */
  233. (void) len;
  234. OPENSSL_free(ptr);
  235. #elif defined(OPENSSL)
  236. OPENSSL_cleanse(ptr, len);
  237. OPENSSL_free(ptr);
  238. #else
  239. memset(ptr, 0, len);
  240. free(ptr);
  241. #endif /* LIBGCRYPT */
  242. }
  243. static inline int jent_fips_enabled(void)
  244. {
  245. #ifdef LIBGCRYPT
  246. return fips_mode();
  247. #elif defined(AWSLC)
  248. return FIPS_mode();
  249. #elif defined(OPENSSL)
  250. #ifdef OPENSSL_FIPS
  251. return FIPS_mode();
  252. #else
  253. return 0;
  254. #endif
  255. #else
  256. #define FIPS_MODE_SWITCH_FILE "/proc/sys/crypto/fips_enabled"
  257. char buf[2] = "0";
  258. int fd = 0;
  259. if ((fd = open(FIPS_MODE_SWITCH_FILE, O_RDONLY)) >= 0) {
  260. while (read(fd, buf, sizeof(buf)) < 0 && errno == EINTR);
  261. close(fd);
  262. }
  263. if (buf[0] == '1')
  264. return 1;
  265. else
  266. return 0;
  267. #endif
  268. }
  269. static inline void jent_memset_secure(void *s, size_t n)
  270. {
  271. #if defined(AWSLC)
  272. OPENSSL_cleanse(s, n);
  273. #else
  274. memset(s, 0, n);
  275. __asm__ __volatile__("" : : "r" (s) : "memory");
  276. #endif
  277. }
  278. static inline long jent_ncpu(void)
  279. {
  280. #ifdef _POSIX_SOURCE
  281. long ncpu = sysconf(_SC_NPROCESSORS_ONLN);
  282. if (ncpu == -1)
  283. return -errno;
  284. if (ncpu == 0)
  285. return -EFAULT;
  286. return ncpu;
  287. #else
  288. return 1;
  289. #endif
  290. }
  291. #ifdef __linux__
  292. # if defined(_SC_LEVEL1_DCACHE_SIZE) && \
  293. defined(_SC_LEVEL2_CACHE_SIZE) && \
  294. defined(_SC_LEVEL3_CACHE_SIZE)
  295. static inline void jent_get_cachesize(long *l1, long *l2, long *l3)
  296. {
  297. *l1 = sysconf(_SC_LEVEL1_DCACHE_SIZE);
  298. *l2 = sysconf(_SC_LEVEL2_CACHE_SIZE);
  299. *l3 = sysconf(_SC_LEVEL3_CACHE_SIZE);
  300. }
  301. # else
  302. static inline void jent_get_cachesize(long *l1, long *l2, long *l3)
  303. {
  304. #define JENT_SYSFS_CACHE_DIR "/sys/devices/system/cpu/cpu0/cache"
  305. long val;
  306. unsigned int i;
  307. char buf[10], file[50];
  308. int fd = 0;
  309. /* Iterate over all caches */
  310. for (i = 0; i < 4; i++) {
  311. unsigned int shift = 0;
  312. char *ext;
  313. /*
  314. * Check the cache type - we are only interested in Unified
  315. * and Data caches.
  316. */
  317. memset(buf, 0, sizeof(buf));
  318. snprintf(file, sizeof(file), "%s/index%u/type",
  319. JENT_SYSFS_CACHE_DIR, i);
  320. fd = open(file, O_RDONLY);
  321. if (fd < 0)
  322. continue;
  323. while (read(fd, buf, sizeof(buf)) < 0 && errno == EINTR);
  324. close(fd);
  325. buf[sizeof(buf) - 1] = '\0';
  326. if (strncmp(buf, "Data", 4) && strncmp(buf, "Unified", 7))
  327. continue;
  328. /* Get size of cache */
  329. memset(buf, 0, sizeof(buf));
  330. snprintf(file, sizeof(file), "%s/index%u/size",
  331. JENT_SYSFS_CACHE_DIR, i);
  332. fd = open(file, O_RDONLY);
  333. if (fd < 0)
  334. continue;
  335. while (read(fd, buf, sizeof(buf)) < 0 && errno == EINTR);
  336. close(fd);
  337. buf[sizeof(buf) - 1] = '\0';
  338. ext = strstr(buf, "K");
  339. if (ext) {
  340. shift = 10;
  341. *ext = '\0';
  342. } else {
  343. ext = strstr(buf, "M");
  344. if (ext) {
  345. shift = 20;
  346. *ext = '\0';
  347. }
  348. }
  349. val = strtol(buf, NULL, 10);
  350. if (val == LONG_MAX)
  351. continue;
  352. val <<= shift;
  353. if (!*l1)
  354. *l1 = val;
  355. else if (!*l2)
  356. *l2 = val;
  357. else {
  358. *l3 = val;
  359. break;
  360. }
  361. }
  362. #undef JENT_SYSFS_CACHE_DIR
  363. }
  364. # endif
  365. static inline uint32_t jent_cache_size_roundup(void)
  366. {
  367. static int checked = 0;
  368. static uint32_t cache_size = 0;
  369. if (!checked) {
  370. long l1 = 0, l2 = 0, l3 = 0;
  371. jent_get_cachesize(&l1, &l2, &l3);
  372. checked = 1;
  373. /* Cache size reported by system */
  374. if (l1 > 0)
  375. cache_size += (uint32_t)l1;
  376. if (l2 > 0)
  377. cache_size += (uint32_t)l2;
  378. if (l3 > 0)
  379. cache_size += (uint32_t)l3;
  380. /*
  381. * Force the output_size to be of the form
  382. * (bounding_power_of_2 - 1).
  383. */
  384. cache_size |= (cache_size >> 1);
  385. cache_size |= (cache_size >> 2);
  386. cache_size |= (cache_size >> 4);
  387. cache_size |= (cache_size >> 8);
  388. cache_size |= (cache_size >> 16);
  389. if (cache_size == 0)
  390. return 0;
  391. /*
  392. * Make the output_size the smallest power of 2 strictly
  393. * greater than cache_size.
  394. */
  395. cache_size++;
  396. }
  397. return cache_size;
  398. }
  399. #else /* __linux__ */
  400. static inline uint32_t jent_cache_size_roundup(void)
  401. {
  402. return 0;
  403. }
  404. #endif /* __linux__ */
  405. static inline void jent_yield(void)
  406. {
  407. sched_yield();
  408. }
  409. /* --- helpers needed in user space -- */
  410. static inline uint64_t rol64(uint64_t x, int n)
  411. {
  412. return ( (x << (n&(64-1))) | (x >> ((64-n)&(64-1))) );
  413. }
  414. #endif /* _JITTERENTROPY_BASE_USER_H */