Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

472 строки
18 KiB

  1. /*
  2. * Non-physical true random number generator based on timing jitter.
  3. *
  4. * Copyright Stephan Mueller <smueller@chronox.de>, 2014 - 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_H
  42. #define _JITTERENTROPY_H
  43. #ifdef __cplusplus
  44. extern "C" {
  45. #endif
  46. /***************************************************************************
  47. * Jitter RNG Configuration Section
  48. *
  49. * You may alter the following options
  50. ***************************************************************************/
  51. /*
  52. * Enable timer-less timer support with JENT_CONF_ENABLE_INTERNAL_TIMER
  53. *
  54. * In case the hardware is identified to not provide a high-resolution time
  55. * stamp, this option enables a built-in high-resolution time stamp mechanism.
  56. *
  57. * The timer-less noise source is based on threads. This noise source requires
  58. * the linking with the POSIX threads library. I.e. the executing environment
  59. * must offer POSIX threads. If this option is disabled, no linking
  60. * with the POSIX threads library is needed.
  61. */
  62. /*
  63. * Disable the loop shuffle operation
  64. *
  65. * The shuffle operation enlarges the timing of the conditioning function
  66. * by a variable length defined by the LSB of a time stamp. Some mathematicians
  67. * are concerned that this pseudo-random selection of the loop iteration count
  68. * may create some form of dependency between the different loop counts
  69. * and the associated time duration of the conditioning function. It
  70. * also complicates entropy assessment because it effectively combines a bunch
  71. * of shifted/scaled copies the same distribution and masks failures from the
  72. * health testing.
  73. *
  74. * By enabling this flag, the loop shuffle operation is disabled and
  75. * the entropy collection operates in a way that honor the concerns.
  76. *
  77. * By enabling this flag, the time of collecting entropy may be enlarged.
  78. */
  79. #define JENT_CONF_DISABLE_LOOP_SHUFFLE
  80. /*
  81. * Shall the LAG predictor health test be enabled?
  82. */
  83. #define JENT_HEALTH_LAG_PREDICTOR
  84. /*
  85. * Shall the jent_memaccess use a (statistically) random selection for the
  86. * memory to update?
  87. */
  88. #define JENT_RANDOM_MEMACCESS
  89. /***************************************************************************
  90. * Jitter RNG State Definition Section
  91. ***************************************************************************/
  92. #if defined(_MSC_VER)
  93. #include "arch/jitterentropy-base-windows.h"
  94. #else
  95. #include "jitterentropy-base-user.h"
  96. #endif
  97. #define SHA3_256_SIZE_DIGEST_BITS 256
  98. #define SHA3_256_SIZE_DIGEST (SHA3_256_SIZE_DIGEST_BITS >> 3)
  99. /*
  100. * The output 256 bits can receive more than 256 bits of min entropy,
  101. * of course, but the 256-bit output of SHA3-256(M) can only asymptotically
  102. * approach 256 bits of min entropy, not attain that bound. Random maps will
  103. * tend to have output collisions, which reduces the creditable output entropy
  104. * (that is what SP 800-90B Section 3.1.5.1.2 attempts to bound).
  105. *
  106. * The value "64" is justified in Appendix A.4 of the current 90C draft,
  107. * and aligns with NIST's in "epsilon" definition in this document, which is
  108. * that a string can be considered "full entropy" if you can bound the min
  109. * entropy in each bit of output to at least 1-epsilon, where epsilon is
  110. * required to be <= 2^(-32).
  111. */
  112. #define ENTROPY_SAFETY_FACTOR 64
  113. /**
  114. * Function pointer data structure to register an external thread handler
  115. * used for the timer-less mode of the Jitter RNG.
  116. *
  117. * The external caller provides these function pointers to handle the
  118. * management of the timer thread that is spawned by the Jitter RNG.
  119. *
  120. * @var jent_notime_init This function is intended to initialze the threading
  121. * support. All data that is required by the threading code must be
  122. * held in the data structure @param ctx. The Jitter RNG maintains the
  123. * data structure and uses it for every invocation of the following calls.
  124. *
  125. * @var jent_notime_fini This function shall terminate the threading support.
  126. * The function must dispose of all memory and resources used for the
  127. * threading operation. It must also dispose of the @param ctx memory.
  128. *
  129. * @var jent_notime_start This function is called when the Jitter RNG wants
  130. * to start a thread. Besides providing a pointer to the @param ctx
  131. * allocated during initialization time, the Jitter RNG provides a
  132. * pointer to the function the thread shall execute and the argument
  133. * the function shall be invoked with. These two parameters have the
  134. * same purpose as the trailing two parameters of pthread_create(3).
  135. *
  136. * @var jent_notime_stop This function is invoked by the Jitter RNG when the
  137. * thread should be stopped. Note, the Jitter RNG intends to start/stop
  138. * the thread frequently.
  139. *
  140. * An example implementation is found in the Jitter RNG itself with its
  141. * default thread handler of jent_notime_thread_builtin.
  142. *
  143. * If the caller wants to register its own thread handler, it must be done
  144. * with the API call jent_entropy_switch_notime_impl as the first
  145. * call to interact with the Jitter RNG, even before jent_entropy_init.
  146. * After jent_entropy_init is called, changing of the threading implementation
  147. * is not allowed.
  148. */
  149. struct jent_notime_thread {
  150. int (*jent_notime_init)(void **ctx);
  151. void (*jent_notime_fini)(void *ctx);
  152. int (*jent_notime_start)(void *ctx,
  153. void *(*start_routine) (void *), void *arg);
  154. void (*jent_notime_stop)(void *ctx);
  155. };
  156. /* The entropy pool */
  157. struct rand_data
  158. {
  159. /* all data values that are vital to maintain the security
  160. * of the RNG are marked as SENSITIVE. A user must not
  161. * access that information while the RNG executes its loops to
  162. * calculate the next random value. */
  163. void *hash_state; /* SENSITIVE hash state entropy pool */
  164. uint64_t prev_time; /* SENSITIVE Previous time stamp */
  165. #define DATA_SIZE_BITS (SHA3_256_SIZE_DIGEST_BITS)
  166. #ifndef JENT_HEALTH_LAG_PREDICTOR
  167. uint64_t last_delta; /* SENSITIVE stuck test */
  168. uint64_t last_delta2; /* SENSITIVE stuck test */
  169. #endif /* JENT_HEALTH_LAG_PREDICTOR */
  170. unsigned int flags; /* Flags used to initialize */
  171. unsigned int osr; /* Oversampling rate */
  172. #ifdef JENT_RANDOM_MEMACCESS
  173. /* The step size should be larger than the cacheline size. */
  174. # ifndef JENT_MEMORY_BITS
  175. # define JENT_MEMORY_BITS 17
  176. # endif
  177. # ifndef JENT_MEMORY_SIZE
  178. # define JENT_MEMORY_SIZE (UINT32_C(1)<<JENT_MEMORY_BITS)
  179. # endif
  180. #else /* JENT_RANDOM_MEMACCESS */
  181. # ifndef JENT_MEMORY_BLOCKS
  182. # define JENT_MEMORY_BLOCKS 512
  183. # endif
  184. # ifndef JENT_MEMORY_BLOCKSIZE
  185. # define JENT_MEMORY_BLOCKSIZE 128
  186. # endif
  187. # ifndef JENT_MEMORY_SIZE
  188. # define JENT_MEMORY_SIZE (JENT_MEMORY_BLOCKS*JENT_MEMORY_BLOCKSIZE)
  189. # endif
  190. #endif /* JENT_RANDOM_MEMACCESS */
  191. #define JENT_MEMORY_ACCESSLOOPS 128
  192. unsigned char *mem; /* Memory access location with size of
  193. * JENT_MEMORY_SIZE or memsize */
  194. #ifdef JENT_RANDOM_MEMACCESS
  195. uint32_t memmask; /* Memory mask (size of memory - 1) */
  196. #else
  197. unsigned int memlocation; /* Pointer to byte in *mem */
  198. unsigned int memblocks; /* Number of memory blocks in *mem */
  199. unsigned int memblocksize; /* Size of one memory block in bytes */
  200. #endif
  201. unsigned int memaccessloops; /* Number of memory accesses per random
  202. * bit generation */
  203. /* Repetition Count Test */
  204. int rct_count; /* Number of stuck values */
  205. /* Adaptive Proportion Test for a significance level of 2^-30 */
  206. unsigned int apt_cutoff; /* Calculated using a corrected version
  207. * of the SP800-90B sec 4.4.2 formula */
  208. #define JENT_APT_WINDOW_SIZE 512 /* Data window size */
  209. unsigned int apt_observations; /* Number of collected observations in
  210. * current window. */
  211. unsigned int apt_count; /* The number of times the reference
  212. * symbol been encountered in the
  213. * window. */
  214. uint64_t apt_base; /* APT base reference */
  215. unsigned int health_failure; /* Permanent health failure */
  216. unsigned int apt_base_set:1; /* APT base reference set? */
  217. unsigned int fips_enabled:1;
  218. unsigned int enable_notime:1; /* Use internal high-res timer */
  219. unsigned int max_mem_set:1; /* Maximum memory configured by user */
  220. #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
  221. volatile uint8_t notime_interrupt; /* indicator to interrupt ctr */
  222. volatile uint64_t notime_timer; /* high-res timer mock-up */
  223. uint64_t notime_prev_timer; /* previous timer value */
  224. void *notime_thread_ctx; /* register thread data */
  225. #endif /* JENT_CONF_ENABLE_INTERNAL_TIMER */
  226. uint64_t jent_common_timer_gcd; /* Common divisor for all time deltas */
  227. #ifdef JENT_HEALTH_LAG_PREDICTOR
  228. /* Lag predictor test to look for re-occurring patterns. */
  229. /* The lag global cutoff selected based on the selection of osr. */
  230. unsigned int lag_global_cutoff;
  231. /* The lag local cutoff selected based on the selection of osr. */
  232. unsigned int lag_local_cutoff;
  233. /*
  234. * The number of times the lag predictor was correct. Compared to the
  235. * global cutoff.
  236. */
  237. unsigned int lag_prediction_success_count;
  238. /*
  239. * The size of the current run of successes. Compared to the local
  240. * cutoff.
  241. */
  242. unsigned int lag_prediction_success_run;
  243. /*
  244. * The total number of collected observations since the health test was
  245. * last reset.
  246. */
  247. unsigned int lag_best_predictor;
  248. /*
  249. * The total number of collected observations since the health test was
  250. * last reset.
  251. */
  252. unsigned int lag_observations;
  253. /*
  254. * This is the size of the window used by the predictor. The predictor
  255. * is reset between windows.
  256. */
  257. #define JENT_LAG_WINDOW_SIZE (1U<<17)
  258. /*
  259. * The amount of history to base predictions on. This must be a power
  260. * of 2. Must be 4 or greater.
  261. */
  262. #define JENT_LAG_HISTORY_SIZE 8
  263. #define JENT_LAG_MASK (JENT_LAG_HISTORY_SIZE - 1)
  264. /* The delta history for the lag predictor. */
  265. uint64_t lag_delta_history[JENT_LAG_HISTORY_SIZE];
  266. /* The scoreboard that tracks how successful each predictor lag is. */
  267. unsigned int lag_scoreboard[JENT_LAG_HISTORY_SIZE];
  268. #endif /* JENT_HEALTH_LAG_PREDICTOR */
  269. };
  270. /* Flags that can be used to initialize the RNG */
  271. #define JENT_DISABLE_STIR (1<<0) /* UNUSED */
  272. #define JENT_DISABLE_UNBIAS (1<<1) /* UNUSED */
  273. #define JENT_DISABLE_MEMORY_ACCESS (1<<2) /* Disable memory access for more
  274. entropy, saves MEMORY_SIZE RAM for
  275. entropy collector */
  276. #define JENT_FORCE_INTERNAL_TIMER (1<<3) /* Force the use of the internal
  277. timer */
  278. #define JENT_DISABLE_INTERNAL_TIMER (1<<4) /* Disable the potential use of
  279. the internal timer. */
  280. #define JENT_FORCE_FIPS (1<<5) /* Force FIPS compliant mode
  281. including full SP800-90B
  282. compliance. */
  283. /* Flags field limiting the amount of memory to be used for memory access */
  284. #define JENT_FLAGS_TO_MEMSIZE_SHIFT 28
  285. #define JENT_FLAGS_TO_MAX_MEMSIZE(val) (val >> JENT_FLAGS_TO_MEMSIZE_SHIFT)
  286. #define JENT_MAX_MEMSIZE_TO_FLAGS(val) (val << JENT_FLAGS_TO_MEMSIZE_SHIFT)
  287. #define JENT_MAX_MEMSIZE_32kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 1))
  288. #define JENT_MAX_MEMSIZE_64kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 2))
  289. #define JENT_MAX_MEMSIZE_128kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 3))
  290. #define JENT_MAX_MEMSIZE_256kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 4))
  291. #define JENT_MAX_MEMSIZE_512kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 5))
  292. #define JENT_MAX_MEMSIZE_1MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 6))
  293. #define JENT_MAX_MEMSIZE_2MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 7))
  294. #define JENT_MAX_MEMSIZE_4MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 8))
  295. #define JENT_MAX_MEMSIZE_8MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 9))
  296. #define JENT_MAX_MEMSIZE_16MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(10))
  297. #define JENT_MAX_MEMSIZE_32MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(11))
  298. #define JENT_MAX_MEMSIZE_64MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(12))
  299. #define JENT_MAX_MEMSIZE_128MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(13))
  300. #define JENT_MAX_MEMSIZE_256MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(14))
  301. #define JENT_MAX_MEMSIZE_512MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(15))
  302. #define JENT_MAX_MEMSIZE_MAX JENT_MAX_MEMSIZE_512MB
  303. #define JENT_MAX_MEMSIZE_MASK JENT_MAX_MEMSIZE_MAX
  304. /* We start at 32kB -> offset is log2(32768) */
  305. #define JENT_MAX_MEMSIZE_OFFSET 14
  306. #ifdef JENT_CONF_DISABLE_LOOP_SHUFFLE
  307. # define JENT_MIN_OSR 3
  308. #else
  309. # define JENT_MIN_OSR 1
  310. #endif
  311. #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
  312. /* -- BEGIN Main interface functions -- */
  313. #ifndef JENT_STUCK_INIT_THRES
  314. /*
  315. * Per default, not more than 90% of all measurements during initialization
  316. * are allowed to be stuck.
  317. *
  318. * It is allowed to change this value as required for the intended environment.
  319. */
  320. #define JENT_STUCK_INIT_THRES(x) ((x*9) / 10)
  321. #endif
  322. #ifdef JENT_PRIVATE_COMPILE
  323. # define JENT_PRIVATE_STATIC static
  324. #else /* JENT_PRIVATE_COMPILE */
  325. #if defined(_MSC_VER)
  326. #define JENT_PRIVATE_STATIC __declspec(dllexport)
  327. #else
  328. #define JENT_PRIVATE_STATIC __attribute__((visibility("default")))
  329. #endif
  330. #endif
  331. /* Number of low bits of the time value that we want to consider */
  332. /* get raw entropy */
  333. JENT_PRIVATE_STATIC
  334. ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len);
  335. JENT_PRIVATE_STATIC
  336. ssize_t jent_read_entropy_safe(struct rand_data **ec, char *data, size_t len);
  337. /* initialize an instance of the entropy collector */
  338. JENT_PRIVATE_STATIC
  339. struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
  340. unsigned int flags);
  341. /* clearing of entropy collector */
  342. JENT_PRIVATE_STATIC
  343. void jent_entropy_collector_free(struct rand_data *entropy_collector);
  344. /* initialization of entropy collector */
  345. JENT_PRIVATE_STATIC
  346. int jent_entropy_init(void);
  347. JENT_PRIVATE_STATIC
  348. int jent_entropy_init_ex(unsigned int osr, unsigned int flags);
  349. /*
  350. * Set a callback to run on health failure in FIPS mode.
  351. * This function will take an action determined by the caller.
  352. */
  353. typedef void (*jent_fips_failure_cb)(struct rand_data *ec,
  354. unsigned int health_failure);
  355. JENT_PRIVATE_STATIC
  356. int jent_set_fips_failure_callback(jent_fips_failure_cb cb);
  357. /* return version number of core library */
  358. JENT_PRIVATE_STATIC
  359. unsigned int jent_version(void);
  360. /* Set a different thread handling logic for the notimer support */
  361. JENT_PRIVATE_STATIC
  362. int jent_entropy_switch_notime_impl(struct jent_notime_thread *new_thread);
  363. /* -- END of Main interface functions -- */
  364. /* -- BEGIN timer-less threading support functions to prevent code dupes -- */
  365. #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
  366. struct jent_notime_ctx {
  367. pthread_attr_t notime_pthread_attr; /* pthreads library */
  368. pthread_t notime_thread_id; /* pthreads thread ID */
  369. };
  370. JENT_PRIVATE_STATIC
  371. int jent_notime_init(void **ctx);
  372. JENT_PRIVATE_STATIC
  373. void jent_notime_fini(void *ctx);
  374. #else
  375. static inline int jent_notime_init(void **ctx) { (void)ctx; return 0; }
  376. static inline void jent_notime_fini(void *ctx) { (void)ctx; }
  377. #endif /* JENT_CONF_ENABLE_INTERNAL_TIMER */
  378. /* -- END timer-less threading support functions to prevent code dupes -- */
  379. /* -- BEGIN error codes for init function -- */
  380. #define ENOTIME 1 /* Timer service not available */
  381. #define ECOARSETIME 2 /* Timer too coarse for RNG */
  382. #define ENOMONOTONIC 3 /* Timer is not monotonic increasing */
  383. #define EMINVARIATION 4 /* Timer variations too small for RNG */
  384. #define EVARVAR 5 /* Timer does not produce variations of variations
  385. (2nd derivation of time is zero) */
  386. #define EMINVARVAR 6 /* Timer variations of variations is too small */
  387. #define EPROGERR 7 /* Programming error */
  388. #define ESTUCK 8 /* Too many stuck results during init. */
  389. #define EHEALTH 9 /* Health test failed during initialization */
  390. #define ERCT 10 /* RCT failed during initialization */
  391. #define EHASH 11 /* Hash self test failed */
  392. #define EMEM 12 /* Can't allocate memory for initialization */
  393. #define EGCD 13 /* GCD self-test failed */
  394. /* -- END error codes for init function -- */
  395. /* -- BEGIN error masks for health tests -- */
  396. #define JENT_RCT_FAILURE 1 /* Failure in RCT health test. */
  397. #define JENT_APT_FAILURE 2 /* Failure in APT health test. */
  398. #define JENT_LAG_FAILURE 4 /* Failure in Lag predictor health test. */
  399. /* -- END error masks for health tests -- */
  400. /* -- BEGIN statistical test functions only complied with CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT -- */
  401. #ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT
  402. JENT_PRIVATE_STATIC
  403. uint64_t jent_lfsr_var_stat(struct rand_data *ec, unsigned int min);
  404. #endif /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */
  405. /* -- END of statistical test function -- */
  406. #ifdef __cplusplus
  407. }
  408. #endif
  409. #endif /* _JITTERENTROPY_H */