drbg_lib.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. /*
  2. * Copyright 2011-2019 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. #include <string.h>
  10. #include <openssl/crypto.h>
  11. #include <openssl/err.h>
  12. #include <openssl/rand.h>
  13. #include "rand_lcl.h"
  14. #include "internal/thread_once.h"
  15. #include "internal/rand_int.h"
  16. #include "internal/cryptlib_int.h"
  17. /*
  18. * Support framework for NIST SP 800-90A DRBG
  19. *
  20. * See manual page RAND_DRBG(7) for a general overview.
  21. *
  22. * The OpenSSL model is to have new and free functions, and that new
  23. * does all initialization. That is not the NIST model, which has
  24. * instantiation and un-instantiate, and re-use within a new/free
  25. * lifecycle. (No doubt this comes from the desire to support hardware
  26. * DRBG, where allocation of resources on something like an HSM is
  27. * a much bigger deal than just re-setting an allocated resource.)
  28. */
  29. /*
  30. * The three shared DRBG instances
  31. *
  32. * There are three shared DRBG instances: <master>, <public>, and <private>.
  33. */
  34. /*
  35. * The <master> DRBG
  36. *
  37. * Not used directly by the application, only for reseeding the two other
  38. * DRBGs. It reseeds itself by pulling either randomness from os entropy
  39. * sources or by consuming randomness which was added by RAND_add().
  40. *
  41. * The <master> DRBG is a global instance which is accessed concurrently by
  42. * all threads. The necessary locking is managed automatically by its child
  43. * DRBG instances during reseeding.
  44. */
  45. static RAND_DRBG *master_drbg;
  46. /*
  47. * The <public> DRBG
  48. *
  49. * Used by default for generating random bytes using RAND_bytes().
  50. *
  51. * The <public> DRBG is thread-local, i.e., there is one instance per thread.
  52. */
  53. static CRYPTO_THREAD_LOCAL public_drbg;
  54. /*
  55. * The <private> DRBG
  56. *
  57. * Used by default for generating private keys using RAND_priv_bytes()
  58. *
  59. * The <private> DRBG is thread-local, i.e., there is one instance per thread.
  60. */
  61. static CRYPTO_THREAD_LOCAL private_drbg;
  62. /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
  63. static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
  64. static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
  65. static int rand_drbg_type = RAND_DRBG_TYPE;
  66. static unsigned int rand_drbg_flags = RAND_DRBG_FLAGS;
  67. static unsigned int master_reseed_interval = MASTER_RESEED_INTERVAL;
  68. static unsigned int slave_reseed_interval = SLAVE_RESEED_INTERVAL;
  69. static time_t master_reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
  70. static time_t slave_reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
  71. /* A logical OR of all used DRBG flag bits (currently there is only one) */
  72. static const unsigned int rand_drbg_used_flags =
  73. RAND_DRBG_FLAG_CTR_NO_DF;
  74. static RAND_DRBG *drbg_setup(RAND_DRBG *parent);
  75. static RAND_DRBG *rand_drbg_new(int secure,
  76. int type,
  77. unsigned int flags,
  78. RAND_DRBG *parent);
  79. /*
  80. * Set/initialize |drbg| to be of type |type|, with optional |flags|.
  81. *
  82. * If |type| and |flags| are zero, use the defaults
  83. *
  84. * Returns 1 on success, 0 on failure.
  85. */
  86. int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
  87. {
  88. int ret = 1;
  89. if (type == 0 && flags == 0) {
  90. type = rand_drbg_type;
  91. flags = rand_drbg_flags;
  92. }
  93. /* If set is called multiple times - clear the old one */
  94. if (drbg->type != 0 && (type != drbg->type || flags != drbg->flags)) {
  95. drbg->meth->uninstantiate(drbg);
  96. rand_pool_free(drbg->adin_pool);
  97. drbg->adin_pool = NULL;
  98. }
  99. drbg->state = DRBG_UNINITIALISED;
  100. drbg->flags = flags;
  101. drbg->type = type;
  102. switch (type) {
  103. default:
  104. drbg->type = 0;
  105. drbg->flags = 0;
  106. drbg->meth = NULL;
  107. RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
  108. return 0;
  109. case 0:
  110. /* Uninitialized; that's okay. */
  111. drbg->meth = NULL;
  112. return 1;
  113. case NID_aes_128_ctr:
  114. case NID_aes_192_ctr:
  115. case NID_aes_256_ctr:
  116. ret = drbg_ctr_init(drbg);
  117. break;
  118. }
  119. if (ret == 0) {
  120. drbg->state = DRBG_ERROR;
  121. RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
  122. }
  123. return ret;
  124. }
  125. /*
  126. * Set/initialize default |type| and |flag| for new drbg instances.
  127. *
  128. * Returns 1 on success, 0 on failure.
  129. */
  130. int RAND_DRBG_set_defaults(int type, unsigned int flags)
  131. {
  132. int ret = 1;
  133. switch (type) {
  134. default:
  135. RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
  136. return 0;
  137. case NID_aes_128_ctr:
  138. case NID_aes_192_ctr:
  139. case NID_aes_256_ctr:
  140. break;
  141. }
  142. if ((flags & ~rand_drbg_used_flags) != 0) {
  143. RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
  144. return 0;
  145. }
  146. rand_drbg_type = type;
  147. rand_drbg_flags = flags;
  148. return ret;
  149. }
  150. /*
  151. * Allocate memory and initialize a new DRBG. The DRBG is allocated on
  152. * the secure heap if |secure| is nonzero and the secure heap is enabled.
  153. * The |parent|, if not NULL, will be used as random source for reseeding.
  154. *
  155. * Returns a pointer to the new DRBG instance on success, NULL on failure.
  156. */
  157. static RAND_DRBG *rand_drbg_new(int secure,
  158. int type,
  159. unsigned int flags,
  160. RAND_DRBG *parent)
  161. {
  162. RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
  163. : OPENSSL_zalloc(sizeof(*drbg));
  164. if (drbg == NULL) {
  165. RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
  166. return NULL;
  167. }
  168. drbg->secure = secure && CRYPTO_secure_allocated(drbg);
  169. drbg->fork_count = rand_fork_count;
  170. drbg->parent = parent;
  171. if (parent == NULL) {
  172. drbg->get_entropy = rand_drbg_get_entropy;
  173. drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
  174. #ifndef RAND_DRBG_GET_RANDOM_NONCE
  175. drbg->get_nonce = rand_drbg_get_nonce;
  176. drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
  177. #endif
  178. drbg->reseed_interval = master_reseed_interval;
  179. drbg->reseed_time_interval = master_reseed_time_interval;
  180. } else {
  181. drbg->get_entropy = rand_drbg_get_entropy;
  182. drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
  183. /*
  184. * Do not provide nonce callbacks, the child DRBGs will
  185. * obtain their nonce using random bits from the parent.
  186. */
  187. drbg->reseed_interval = slave_reseed_interval;
  188. drbg->reseed_time_interval = slave_reseed_time_interval;
  189. }
  190. if (RAND_DRBG_set(drbg, type, flags) == 0)
  191. goto err;
  192. if (parent != NULL) {
  193. rand_drbg_lock(parent);
  194. if (drbg->strength > parent->strength) {
  195. /*
  196. * We currently don't support the algorithm from NIST SP 800-90C
  197. * 10.1.2 to use a weaker DRBG as source
  198. */
  199. rand_drbg_unlock(parent);
  200. RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
  201. goto err;
  202. }
  203. rand_drbg_unlock(parent);
  204. }
  205. return drbg;
  206. err:
  207. RAND_DRBG_free(drbg);
  208. return NULL;
  209. }
  210. RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
  211. {
  212. return rand_drbg_new(0, type, flags, parent);
  213. }
  214. RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
  215. {
  216. return rand_drbg_new(1, type, flags, parent);
  217. }
  218. /*
  219. * Uninstantiate |drbg| and free all memory.
  220. */
  221. void RAND_DRBG_free(RAND_DRBG *drbg)
  222. {
  223. if (drbg == NULL)
  224. return;
  225. if (drbg->meth != NULL)
  226. drbg->meth->uninstantiate(drbg);
  227. rand_pool_free(drbg->adin_pool);
  228. CRYPTO_THREAD_lock_free(drbg->lock);
  229. CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
  230. if (drbg->secure)
  231. OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
  232. else
  233. OPENSSL_clear_free(drbg, sizeof(*drbg));
  234. }
  235. /*
  236. * Instantiate |drbg|, after it has been initialized. Use |pers| and
  237. * |perslen| as prediction-resistance input.
  238. *
  239. * Requires that drbg->lock is already locked for write, if non-null.
  240. *
  241. * Returns 1 on success, 0 on failure.
  242. */
  243. int RAND_DRBG_instantiate(RAND_DRBG *drbg,
  244. const unsigned char *pers, size_t perslen)
  245. {
  246. unsigned char *nonce = NULL, *entropy = NULL;
  247. size_t noncelen = 0, entropylen = 0;
  248. size_t min_entropy = drbg->strength;
  249. size_t min_entropylen = drbg->min_entropylen;
  250. size_t max_entropylen = drbg->max_entropylen;
  251. if (perslen > drbg->max_perslen) {
  252. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
  253. RAND_R_PERSONALISATION_STRING_TOO_LONG);
  254. goto end;
  255. }
  256. if (drbg->meth == NULL) {
  257. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
  258. RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
  259. goto end;
  260. }
  261. if (drbg->state != DRBG_UNINITIALISED) {
  262. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
  263. drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
  264. : RAND_R_ALREADY_INSTANTIATED);
  265. goto end;
  266. }
  267. drbg->state = DRBG_ERROR;
  268. /*
  269. * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
  270. * and nonce in 1 call by increasing the entropy with 50% and increasing
  271. * the minimum length to accomadate the length of the nonce.
  272. * We do this in case a nonce is require and get_nonce is NULL.
  273. */
  274. if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
  275. min_entropy += drbg->strength / 2;
  276. min_entropylen += drbg->min_noncelen;
  277. max_entropylen += drbg->max_noncelen;
  278. }
  279. drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
  280. if (drbg->reseed_next_counter) {
  281. drbg->reseed_next_counter++;
  282. if(!drbg->reseed_next_counter)
  283. drbg->reseed_next_counter = 1;
  284. }
  285. if (drbg->get_entropy != NULL)
  286. entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
  287. min_entropylen, max_entropylen, 0);
  288. if (entropylen < min_entropylen
  289. || entropylen > max_entropylen) {
  290. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
  291. goto end;
  292. }
  293. if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
  294. noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
  295. drbg->min_noncelen, drbg->max_noncelen);
  296. if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
  297. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
  298. goto end;
  299. }
  300. }
  301. if (!drbg->meth->instantiate(drbg, entropy, entropylen,
  302. nonce, noncelen, pers, perslen)) {
  303. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
  304. goto end;
  305. }
  306. drbg->state = DRBG_READY;
  307. drbg->reseed_gen_counter = 1;
  308. drbg->reseed_time = time(NULL);
  309. tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
  310. end:
  311. if (entropy != NULL && drbg->cleanup_entropy != NULL)
  312. drbg->cleanup_entropy(drbg, entropy, entropylen);
  313. if (nonce != NULL && drbg->cleanup_nonce != NULL)
  314. drbg->cleanup_nonce(drbg, nonce, noncelen);
  315. if (drbg->state == DRBG_READY)
  316. return 1;
  317. return 0;
  318. }
  319. /*
  320. * Uninstantiate |drbg|. Must be instantiated before it can be used.
  321. *
  322. * Requires that drbg->lock is already locked for write, if non-null.
  323. *
  324. * Returns 1 on success, 0 on failure.
  325. */
  326. int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
  327. {
  328. if (drbg->meth == NULL) {
  329. drbg->state = DRBG_ERROR;
  330. RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
  331. RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
  332. return 0;
  333. }
  334. /* Clear the entire drbg->ctr struct, then reset some important
  335. * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
  336. * initial values.
  337. */
  338. drbg->meth->uninstantiate(drbg);
  339. return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
  340. }
  341. /*
  342. * Reseed |drbg|, mixing in the specified data
  343. *
  344. * Requires that drbg->lock is already locked for write, if non-null.
  345. *
  346. * Returns 1 on success, 0 on failure.
  347. */
  348. int RAND_DRBG_reseed(RAND_DRBG *drbg,
  349. const unsigned char *adin, size_t adinlen,
  350. int prediction_resistance)
  351. {
  352. unsigned char *entropy = NULL;
  353. size_t entropylen = 0;
  354. if (drbg->state == DRBG_ERROR) {
  355. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
  356. return 0;
  357. }
  358. if (drbg->state == DRBG_UNINITIALISED) {
  359. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
  360. return 0;
  361. }
  362. if (adin == NULL) {
  363. adinlen = 0;
  364. } else if (adinlen > drbg->max_adinlen) {
  365. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
  366. return 0;
  367. }
  368. drbg->state = DRBG_ERROR;
  369. drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
  370. if (drbg->reseed_next_counter) {
  371. drbg->reseed_next_counter++;
  372. if(!drbg->reseed_next_counter)
  373. drbg->reseed_next_counter = 1;
  374. }
  375. if (drbg->get_entropy != NULL)
  376. entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
  377. drbg->min_entropylen,
  378. drbg->max_entropylen,
  379. prediction_resistance);
  380. if (entropylen < drbg->min_entropylen
  381. || entropylen > drbg->max_entropylen) {
  382. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
  383. goto end;
  384. }
  385. if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
  386. goto end;
  387. drbg->state = DRBG_READY;
  388. drbg->reseed_gen_counter = 1;
  389. drbg->reseed_time = time(NULL);
  390. tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
  391. end:
  392. if (entropy != NULL && drbg->cleanup_entropy != NULL)
  393. drbg->cleanup_entropy(drbg, entropy, entropylen);
  394. if (drbg->state == DRBG_READY)
  395. return 1;
  396. return 0;
  397. }
  398. /*
  399. * Restart |drbg|, using the specified entropy or additional input
  400. *
  401. * Tries its best to get the drbg instantiated by all means,
  402. * regardless of its current state.
  403. *
  404. * Optionally, a |buffer| of |len| random bytes can be passed,
  405. * which is assumed to contain at least |entropy| bits of entropy.
  406. *
  407. * If |entropy| > 0, the buffer content is used as entropy input.
  408. *
  409. * If |entropy| == 0, the buffer content is used as additional input
  410. *
  411. * Returns 1 on success, 0 on failure.
  412. *
  413. * This function is used internally only.
  414. */
  415. int rand_drbg_restart(RAND_DRBG *drbg,
  416. const unsigned char *buffer, size_t len, size_t entropy)
  417. {
  418. int reseeded = 0;
  419. const unsigned char *adin = NULL;
  420. size_t adinlen = 0;
  421. if (drbg->seed_pool != NULL) {
  422. RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
  423. drbg->state = DRBG_ERROR;
  424. rand_pool_free(drbg->seed_pool);
  425. drbg->seed_pool = NULL;
  426. return 0;
  427. }
  428. if (buffer != NULL) {
  429. if (entropy > 0) {
  430. if (drbg->max_entropylen < len) {
  431. RANDerr(RAND_F_RAND_DRBG_RESTART,
  432. RAND_R_ENTROPY_INPUT_TOO_LONG);
  433. drbg->state = DRBG_ERROR;
  434. return 0;
  435. }
  436. if (entropy > 8 * len) {
  437. RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
  438. drbg->state = DRBG_ERROR;
  439. return 0;
  440. }
  441. /* will be picked up by the rand_drbg_get_entropy() callback */
  442. drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
  443. if (drbg->seed_pool == NULL)
  444. return 0;
  445. } else {
  446. if (drbg->max_adinlen < len) {
  447. RANDerr(RAND_F_RAND_DRBG_RESTART,
  448. RAND_R_ADDITIONAL_INPUT_TOO_LONG);
  449. drbg->state = DRBG_ERROR;
  450. return 0;
  451. }
  452. adin = buffer;
  453. adinlen = len;
  454. }
  455. }
  456. /* repair error state */
  457. if (drbg->state == DRBG_ERROR)
  458. RAND_DRBG_uninstantiate(drbg);
  459. /* repair uninitialized state */
  460. if (drbg->state == DRBG_UNINITIALISED) {
  461. /* reinstantiate drbg */
  462. RAND_DRBG_instantiate(drbg,
  463. (const unsigned char *) ossl_pers_string,
  464. sizeof(ossl_pers_string) - 1);
  465. /* already reseeded. prevent second reseeding below */
  466. reseeded = (drbg->state == DRBG_READY);
  467. }
  468. /* refresh current state if entropy or additional input has been provided */
  469. if (drbg->state == DRBG_READY) {
  470. if (adin != NULL) {
  471. /*
  472. * mix in additional input without reseeding
  473. *
  474. * Similar to RAND_DRBG_reseed(), but the provided additional
  475. * data |adin| is mixed into the current state without pulling
  476. * entropy from the trusted entropy source using get_entropy().
  477. * This is not a reseeding in the strict sense of NIST SP 800-90A.
  478. */
  479. drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
  480. } else if (reseeded == 0) {
  481. /* do a full reseeding if it has not been done yet above */
  482. RAND_DRBG_reseed(drbg, NULL, 0, 0);
  483. }
  484. }
  485. rand_pool_free(drbg->seed_pool);
  486. drbg->seed_pool = NULL;
  487. return drbg->state == DRBG_READY;
  488. }
  489. /*
  490. * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
  491. * to or if |prediction_resistance| is set. Additional input can be
  492. * sent in |adin| and |adinlen|.
  493. *
  494. * Requires that drbg->lock is already locked for write, if non-null.
  495. *
  496. * Returns 1 on success, 0 on failure.
  497. *
  498. */
  499. int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
  500. int prediction_resistance,
  501. const unsigned char *adin, size_t adinlen)
  502. {
  503. int reseed_required = 0;
  504. if (drbg->state != DRBG_READY) {
  505. /* try to recover from previous errors */
  506. rand_drbg_restart(drbg, NULL, 0, 0);
  507. if (drbg->state == DRBG_ERROR) {
  508. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
  509. return 0;
  510. }
  511. if (drbg->state == DRBG_UNINITIALISED) {
  512. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
  513. return 0;
  514. }
  515. }
  516. if (outlen > drbg->max_request) {
  517. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
  518. return 0;
  519. }
  520. if (adinlen > drbg->max_adinlen) {
  521. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
  522. return 0;
  523. }
  524. if (drbg->fork_count != rand_fork_count) {
  525. drbg->fork_count = rand_fork_count;
  526. reseed_required = 1;
  527. }
  528. if (drbg->reseed_interval > 0) {
  529. if (drbg->reseed_gen_counter >= drbg->reseed_interval)
  530. reseed_required = 1;
  531. }
  532. if (drbg->reseed_time_interval > 0) {
  533. time_t now = time(NULL);
  534. if (now < drbg->reseed_time
  535. || now - drbg->reseed_time >= drbg->reseed_time_interval)
  536. reseed_required = 1;
  537. }
  538. if (drbg->parent != NULL) {
  539. unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
  540. if (reseed_counter > 0
  541. && tsan_load(&drbg->parent->reseed_prop_counter)
  542. != reseed_counter)
  543. reseed_required = 1;
  544. }
  545. if (reseed_required || prediction_resistance) {
  546. if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
  547. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
  548. return 0;
  549. }
  550. adin = NULL;
  551. adinlen = 0;
  552. }
  553. if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
  554. drbg->state = DRBG_ERROR;
  555. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
  556. return 0;
  557. }
  558. drbg->reseed_gen_counter++;
  559. return 1;
  560. }
  561. /*
  562. * Generates |outlen| random bytes and stores them in |out|. It will
  563. * using the given |drbg| to generate the bytes.
  564. *
  565. * Requires that drbg->lock is already locked for write, if non-null.
  566. *
  567. * Returns 1 on success 0 on failure.
  568. */
  569. int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
  570. {
  571. unsigned char *additional = NULL;
  572. size_t additional_len;
  573. size_t chunk;
  574. size_t ret = 0;
  575. if (drbg->adin_pool == NULL) {
  576. if (drbg->type == 0)
  577. goto err;
  578. drbg->adin_pool = rand_pool_new(0, 0, drbg->max_adinlen);
  579. if (drbg->adin_pool == NULL)
  580. goto err;
  581. }
  582. additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
  583. &additional);
  584. for ( ; outlen > 0; outlen -= chunk, out += chunk) {
  585. chunk = outlen;
  586. if (chunk > drbg->max_request)
  587. chunk = drbg->max_request;
  588. ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
  589. if (!ret)
  590. goto err;
  591. }
  592. ret = 1;
  593. err:
  594. if (additional != NULL)
  595. rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
  596. return ret;
  597. }
  598. /*
  599. * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
  600. *
  601. * Setting the callbacks is allowed only if the drbg has not been
  602. * initialized yet. Otherwise, the operation will fail.
  603. *
  604. * Returns 1 on success, 0 on failure.
  605. */
  606. int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
  607. RAND_DRBG_get_entropy_fn get_entropy,
  608. RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
  609. RAND_DRBG_get_nonce_fn get_nonce,
  610. RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
  611. {
  612. if (drbg->state != DRBG_UNINITIALISED
  613. || drbg->parent != NULL)
  614. return 0;
  615. drbg->get_entropy = get_entropy;
  616. drbg->cleanup_entropy = cleanup_entropy;
  617. drbg->get_nonce = get_nonce;
  618. drbg->cleanup_nonce = cleanup_nonce;
  619. return 1;
  620. }
  621. /*
  622. * Set the reseed interval.
  623. *
  624. * The drbg will reseed automatically whenever the number of generate
  625. * requests exceeds the given reseed interval. If the reseed interval
  626. * is 0, then this feature is disabled.
  627. *
  628. * Returns 1 on success, 0 on failure.
  629. */
  630. int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
  631. {
  632. if (interval > MAX_RESEED_INTERVAL)
  633. return 0;
  634. drbg->reseed_interval = interval;
  635. return 1;
  636. }
  637. /*
  638. * Set the reseed time interval.
  639. *
  640. * The drbg will reseed automatically whenever the time elapsed since
  641. * the last reseeding exceeds the given reseed time interval. For safety,
  642. * a reseeding will also occur if the clock has been reset to a smaller
  643. * value.
  644. *
  645. * Returns 1 on success, 0 on failure.
  646. */
  647. int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
  648. {
  649. if (interval > MAX_RESEED_TIME_INTERVAL)
  650. return 0;
  651. drbg->reseed_time_interval = interval;
  652. return 1;
  653. }
  654. /*
  655. * Set the default values for reseed (time) intervals of new DRBG instances
  656. *
  657. * The default values can be set independently for master DRBG instances
  658. * (without a parent) and slave DRBG instances (with parent).
  659. *
  660. * Returns 1 on success, 0 on failure.
  661. */
  662. int RAND_DRBG_set_reseed_defaults(
  663. unsigned int _master_reseed_interval,
  664. unsigned int _slave_reseed_interval,
  665. time_t _master_reseed_time_interval,
  666. time_t _slave_reseed_time_interval
  667. )
  668. {
  669. if (_master_reseed_interval > MAX_RESEED_INTERVAL
  670. || _slave_reseed_interval > MAX_RESEED_INTERVAL)
  671. return 0;
  672. if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
  673. || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
  674. return 0;
  675. master_reseed_interval = _master_reseed_interval;
  676. slave_reseed_interval = _slave_reseed_interval;
  677. master_reseed_time_interval = _master_reseed_time_interval;
  678. slave_reseed_time_interval = _slave_reseed_time_interval;
  679. return 1;
  680. }
  681. /*
  682. * Locks the given drbg. Locking a drbg which does not have locking
  683. * enabled is considered a successful no-op.
  684. *
  685. * Returns 1 on success, 0 on failure.
  686. */
  687. int rand_drbg_lock(RAND_DRBG *drbg)
  688. {
  689. if (drbg->lock != NULL)
  690. return CRYPTO_THREAD_write_lock(drbg->lock);
  691. return 1;
  692. }
  693. /*
  694. * Unlocks the given drbg. Unlocking a drbg which does not have locking
  695. * enabled is considered a successful no-op.
  696. *
  697. * Returns 1 on success, 0 on failure.
  698. */
  699. int rand_drbg_unlock(RAND_DRBG *drbg)
  700. {
  701. if (drbg->lock != NULL)
  702. return CRYPTO_THREAD_unlock(drbg->lock);
  703. return 1;
  704. }
  705. /*
  706. * Enables locking for the given drbg
  707. *
  708. * Locking can only be enabled if the random generator
  709. * is in the uninitialized state.
  710. *
  711. * Returns 1 on success, 0 on failure.
  712. */
  713. int rand_drbg_enable_locking(RAND_DRBG *drbg)
  714. {
  715. if (drbg->state != DRBG_UNINITIALISED) {
  716. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  717. RAND_R_DRBG_ALREADY_INITIALIZED);
  718. return 0;
  719. }
  720. if (drbg->lock == NULL) {
  721. if (drbg->parent != NULL && drbg->parent->lock == NULL) {
  722. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  723. RAND_R_PARENT_LOCKING_NOT_ENABLED);
  724. return 0;
  725. }
  726. drbg->lock = CRYPTO_THREAD_lock_new();
  727. if (drbg->lock == NULL) {
  728. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  729. RAND_R_FAILED_TO_CREATE_LOCK);
  730. return 0;
  731. }
  732. }
  733. return 1;
  734. }
  735. /*
  736. * Get and set the EXDATA
  737. */
  738. int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
  739. {
  740. return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
  741. }
  742. void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
  743. {
  744. return CRYPTO_get_ex_data(&drbg->ex_data, idx);
  745. }
  746. /*
  747. * The following functions provide a RAND_METHOD that works on the
  748. * global DRBG. They lock.
  749. */
  750. /*
  751. * Allocates a new global DRBG on the secure heap (if enabled) and
  752. * initializes it with default settings.
  753. *
  754. * Returns a pointer to the new DRBG instance on success, NULL on failure.
  755. */
  756. static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
  757. {
  758. RAND_DRBG *drbg;
  759. drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
  760. if (drbg == NULL)
  761. return NULL;
  762. /* Only the master DRBG needs to have a lock */
  763. if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
  764. goto err;
  765. /* enable seed propagation */
  766. tsan_store(&drbg->reseed_prop_counter, 1);
  767. /*
  768. * Ignore instantiation error to support just-in-time instantiation.
  769. *
  770. * The state of the drbg will be checked in RAND_DRBG_generate() and
  771. * an automatic recovery is attempted.
  772. */
  773. (void)RAND_DRBG_instantiate(drbg,
  774. (const unsigned char *) ossl_pers_string,
  775. sizeof(ossl_pers_string) - 1);
  776. return drbg;
  777. err:
  778. RAND_DRBG_free(drbg);
  779. return NULL;
  780. }
  781. /*
  782. * Initialize the global DRBGs on first use.
  783. * Returns 1 on success, 0 on failure.
  784. */
  785. DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
  786. {
  787. /*
  788. * ensure that libcrypto is initialized, otherwise the
  789. * DRBG locks are not cleaned up properly
  790. */
  791. if (!OPENSSL_init_crypto(0, NULL))
  792. return 0;
  793. if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
  794. return 0;
  795. if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
  796. goto err1;
  797. master_drbg = drbg_setup(NULL);
  798. if (master_drbg == NULL)
  799. goto err2;
  800. return 1;
  801. err2:
  802. CRYPTO_THREAD_cleanup_local(&public_drbg);
  803. err1:
  804. CRYPTO_THREAD_cleanup_local(&private_drbg);
  805. return 0;
  806. }
  807. /* Clean up the global DRBGs before exit */
  808. void rand_drbg_cleanup_int(void)
  809. {
  810. if (master_drbg != NULL) {
  811. RAND_DRBG_free(master_drbg);
  812. master_drbg = NULL;
  813. CRYPTO_THREAD_cleanup_local(&private_drbg);
  814. CRYPTO_THREAD_cleanup_local(&public_drbg);
  815. }
  816. }
  817. void drbg_delete_thread_state(void)
  818. {
  819. RAND_DRBG *drbg;
  820. drbg = CRYPTO_THREAD_get_local(&public_drbg);
  821. CRYPTO_THREAD_set_local(&public_drbg, NULL);
  822. RAND_DRBG_free(drbg);
  823. drbg = CRYPTO_THREAD_get_local(&private_drbg);
  824. CRYPTO_THREAD_set_local(&private_drbg, NULL);
  825. RAND_DRBG_free(drbg);
  826. }
  827. /* Implements the default OpenSSL RAND_bytes() method */
  828. static int drbg_bytes(unsigned char *out, int count)
  829. {
  830. int ret;
  831. RAND_DRBG *drbg = RAND_DRBG_get0_public();
  832. if (drbg == NULL)
  833. return 0;
  834. ret = RAND_DRBG_bytes(drbg, out, count);
  835. return ret;
  836. }
  837. /*
  838. * Calculates the minimum length of a full entropy buffer
  839. * which is necessary to seed (i.e. instantiate) the DRBG
  840. * successfully.
  841. */
  842. size_t rand_drbg_seedlen(RAND_DRBG *drbg)
  843. {
  844. /*
  845. * If no os entropy source is available then RAND_seed(buffer, bufsize)
  846. * is expected to succeed if and only if the buffer length satisfies
  847. * the following requirements, which follow from the calculations
  848. * in RAND_DRBG_instantiate().
  849. */
  850. size_t min_entropy = drbg->strength;
  851. size_t min_entropylen = drbg->min_entropylen;
  852. /*
  853. * Extra entropy for the random nonce in the absence of a
  854. * get_nonce callback, see comment in RAND_DRBG_instantiate().
  855. */
  856. if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
  857. min_entropy += drbg->strength / 2;
  858. min_entropylen += drbg->min_noncelen;
  859. }
  860. /*
  861. * Convert entropy requirement from bits to bytes
  862. * (dividing by 8 without rounding upwards, because
  863. * all entropy requirements are divisible by 8).
  864. */
  865. min_entropy >>= 3;
  866. /* Return a value that satisfies both requirements */
  867. return min_entropy > min_entropylen ? min_entropy : min_entropylen;
  868. }
  869. /* Implements the default OpenSSL RAND_add() method */
  870. static int drbg_add(const void *buf, int num, double randomness)
  871. {
  872. int ret = 0;
  873. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  874. size_t buflen;
  875. size_t seedlen;
  876. if (drbg == NULL)
  877. return 0;
  878. if (num < 0 || randomness < 0.0)
  879. return 0;
  880. rand_drbg_lock(drbg);
  881. seedlen = rand_drbg_seedlen(drbg);
  882. buflen = (size_t)num;
  883. if (buflen < seedlen || randomness < (double) seedlen) {
  884. #if defined(OPENSSL_RAND_SEED_NONE)
  885. /*
  886. * If no os entropy source is available, a reseeding will fail
  887. * inevitably. So we use a trick to mix the buffer contents into
  888. * the DRBG state without forcing a reseeding: we generate a
  889. * dummy random byte, using the buffer content as additional data.
  890. * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
  891. */
  892. unsigned char dummy[1];
  893. ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
  894. rand_drbg_unlock(drbg);
  895. return ret;
  896. #else
  897. /*
  898. * If an os entropy source is avaible then we declare the buffer content
  899. * as additional data by setting randomness to zero and trigger a regular
  900. * reseeding.
  901. */
  902. randomness = 0.0;
  903. #endif
  904. }
  905. if (randomness > (double)seedlen) {
  906. /*
  907. * The purpose of this check is to bound |randomness| by a
  908. * relatively small value in order to prevent an integer
  909. * overflow when multiplying by 8 in the rand_drbg_restart()
  910. * call below. Note that randomness is measured in bytes,
  911. * not bits, so this value corresponds to eight times the
  912. * security strength.
  913. */
  914. randomness = (double)seedlen;
  915. }
  916. ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
  917. rand_drbg_unlock(drbg);
  918. return ret;
  919. }
  920. /* Implements the default OpenSSL RAND_seed() method */
  921. static int drbg_seed(const void *buf, int num)
  922. {
  923. return drbg_add(buf, num, num);
  924. }
  925. /* Implements the default OpenSSL RAND_status() method */
  926. static int drbg_status(void)
  927. {
  928. int ret;
  929. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  930. if (drbg == NULL)
  931. return 0;
  932. rand_drbg_lock(drbg);
  933. ret = drbg->state == DRBG_READY ? 1 : 0;
  934. rand_drbg_unlock(drbg);
  935. return ret;
  936. }
  937. /*
  938. * Get the master DRBG.
  939. * Returns pointer to the DRBG on success, NULL on failure.
  940. *
  941. */
  942. RAND_DRBG *RAND_DRBG_get0_master(void)
  943. {
  944. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  945. return NULL;
  946. return master_drbg;
  947. }
  948. /*
  949. * Get the public DRBG.
  950. * Returns pointer to the DRBG on success, NULL on failure.
  951. */
  952. RAND_DRBG *RAND_DRBG_get0_public(void)
  953. {
  954. RAND_DRBG *drbg;
  955. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  956. return NULL;
  957. drbg = CRYPTO_THREAD_get_local(&public_drbg);
  958. if (drbg == NULL) {
  959. if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
  960. return NULL;
  961. drbg = drbg_setup(master_drbg);
  962. CRYPTO_THREAD_set_local(&public_drbg, drbg);
  963. }
  964. return drbg;
  965. }
  966. /*
  967. * Get the private DRBG.
  968. * Returns pointer to the DRBG on success, NULL on failure.
  969. */
  970. RAND_DRBG *RAND_DRBG_get0_private(void)
  971. {
  972. RAND_DRBG *drbg;
  973. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  974. return NULL;
  975. drbg = CRYPTO_THREAD_get_local(&private_drbg);
  976. if (drbg == NULL) {
  977. if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
  978. return NULL;
  979. drbg = drbg_setup(master_drbg);
  980. CRYPTO_THREAD_set_local(&private_drbg, drbg);
  981. }
  982. return drbg;
  983. }
  984. RAND_METHOD rand_meth = {
  985. drbg_seed,
  986. drbg_bytes,
  987. NULL,
  988. drbg_add,
  989. drbg_bytes,
  990. drbg_status
  991. };
  992. RAND_METHOD *RAND_OpenSSL(void)
  993. {
  994. return &rand_meth;
  995. }