drbg_lib.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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_id = openssl_get_fork_id();
  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 accommodate 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 fork_id;
  504. int reseed_required = 0;
  505. if (drbg->state != DRBG_READY) {
  506. /* try to recover from previous errors */
  507. rand_drbg_restart(drbg, NULL, 0, 0);
  508. if (drbg->state == DRBG_ERROR) {
  509. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
  510. return 0;
  511. }
  512. if (drbg->state == DRBG_UNINITIALISED) {
  513. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
  514. return 0;
  515. }
  516. }
  517. if (outlen > drbg->max_request) {
  518. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
  519. return 0;
  520. }
  521. if (adinlen > drbg->max_adinlen) {
  522. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
  523. return 0;
  524. }
  525. fork_id = openssl_get_fork_id();
  526. if (drbg->fork_id != fork_id) {
  527. drbg->fork_id = fork_id;
  528. reseed_required = 1;
  529. }
  530. if (drbg->reseed_interval > 0) {
  531. if (drbg->reseed_gen_counter >= drbg->reseed_interval)
  532. reseed_required = 1;
  533. }
  534. if (drbg->reseed_time_interval > 0) {
  535. time_t now = time(NULL);
  536. if (now < drbg->reseed_time
  537. || now - drbg->reseed_time >= drbg->reseed_time_interval)
  538. reseed_required = 1;
  539. }
  540. if (drbg->parent != NULL) {
  541. unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
  542. if (reseed_counter > 0
  543. && tsan_load(&drbg->parent->reseed_prop_counter)
  544. != reseed_counter)
  545. reseed_required = 1;
  546. }
  547. if (reseed_required || prediction_resistance) {
  548. if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
  549. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
  550. return 0;
  551. }
  552. adin = NULL;
  553. adinlen = 0;
  554. }
  555. if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
  556. drbg->state = DRBG_ERROR;
  557. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
  558. return 0;
  559. }
  560. drbg->reseed_gen_counter++;
  561. return 1;
  562. }
  563. /*
  564. * Generates |outlen| random bytes and stores them in |out|. It will
  565. * using the given |drbg| to generate the bytes.
  566. *
  567. * Requires that drbg->lock is already locked for write, if non-null.
  568. *
  569. * Returns 1 on success 0 on failure.
  570. */
  571. int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
  572. {
  573. unsigned char *additional = NULL;
  574. size_t additional_len;
  575. size_t chunk;
  576. size_t ret = 0;
  577. if (drbg->adin_pool == NULL) {
  578. if (drbg->type == 0)
  579. goto err;
  580. drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
  581. if (drbg->adin_pool == NULL)
  582. goto err;
  583. }
  584. additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
  585. &additional);
  586. for ( ; outlen > 0; outlen -= chunk, out += chunk) {
  587. chunk = outlen;
  588. if (chunk > drbg->max_request)
  589. chunk = drbg->max_request;
  590. ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
  591. if (!ret)
  592. goto err;
  593. }
  594. ret = 1;
  595. err:
  596. if (additional != NULL)
  597. rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
  598. return ret;
  599. }
  600. /*
  601. * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
  602. *
  603. * Setting the callbacks is allowed only if the drbg has not been
  604. * initialized yet. Otherwise, the operation will fail.
  605. *
  606. * Returns 1 on success, 0 on failure.
  607. */
  608. int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
  609. RAND_DRBG_get_entropy_fn get_entropy,
  610. RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
  611. RAND_DRBG_get_nonce_fn get_nonce,
  612. RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
  613. {
  614. if (drbg->state != DRBG_UNINITIALISED
  615. || drbg->parent != NULL)
  616. return 0;
  617. drbg->get_entropy = get_entropy;
  618. drbg->cleanup_entropy = cleanup_entropy;
  619. drbg->get_nonce = get_nonce;
  620. drbg->cleanup_nonce = cleanup_nonce;
  621. return 1;
  622. }
  623. /*
  624. * Set the reseed interval.
  625. *
  626. * The drbg will reseed automatically whenever the number of generate
  627. * requests exceeds the given reseed interval. If the reseed interval
  628. * is 0, then this feature is disabled.
  629. *
  630. * Returns 1 on success, 0 on failure.
  631. */
  632. int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
  633. {
  634. if (interval > MAX_RESEED_INTERVAL)
  635. return 0;
  636. drbg->reseed_interval = interval;
  637. return 1;
  638. }
  639. /*
  640. * Set the reseed time interval.
  641. *
  642. * The drbg will reseed automatically whenever the time elapsed since
  643. * the last reseeding exceeds the given reseed time interval. For safety,
  644. * a reseeding will also occur if the clock has been reset to a smaller
  645. * value.
  646. *
  647. * Returns 1 on success, 0 on failure.
  648. */
  649. int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
  650. {
  651. if (interval > MAX_RESEED_TIME_INTERVAL)
  652. return 0;
  653. drbg->reseed_time_interval = interval;
  654. return 1;
  655. }
  656. /*
  657. * Set the default values for reseed (time) intervals of new DRBG instances
  658. *
  659. * The default values can be set independently for master DRBG instances
  660. * (without a parent) and slave DRBG instances (with parent).
  661. *
  662. * Returns 1 on success, 0 on failure.
  663. */
  664. int RAND_DRBG_set_reseed_defaults(
  665. unsigned int _master_reseed_interval,
  666. unsigned int _slave_reseed_interval,
  667. time_t _master_reseed_time_interval,
  668. time_t _slave_reseed_time_interval
  669. )
  670. {
  671. if (_master_reseed_interval > MAX_RESEED_INTERVAL
  672. || _slave_reseed_interval > MAX_RESEED_INTERVAL)
  673. return 0;
  674. if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
  675. || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
  676. return 0;
  677. master_reseed_interval = _master_reseed_interval;
  678. slave_reseed_interval = _slave_reseed_interval;
  679. master_reseed_time_interval = _master_reseed_time_interval;
  680. slave_reseed_time_interval = _slave_reseed_time_interval;
  681. return 1;
  682. }
  683. /*
  684. * Locks the given drbg. Locking a drbg which does not have locking
  685. * enabled is considered a successful no-op.
  686. *
  687. * Returns 1 on success, 0 on failure.
  688. */
  689. int rand_drbg_lock(RAND_DRBG *drbg)
  690. {
  691. if (drbg->lock != NULL)
  692. return CRYPTO_THREAD_write_lock(drbg->lock);
  693. return 1;
  694. }
  695. /*
  696. * Unlocks the given drbg. Unlocking a drbg which does not have locking
  697. * enabled is considered a successful no-op.
  698. *
  699. * Returns 1 on success, 0 on failure.
  700. */
  701. int rand_drbg_unlock(RAND_DRBG *drbg)
  702. {
  703. if (drbg->lock != NULL)
  704. return CRYPTO_THREAD_unlock(drbg->lock);
  705. return 1;
  706. }
  707. /*
  708. * Enables locking for the given drbg
  709. *
  710. * Locking can only be enabled if the random generator
  711. * is in the uninitialized state.
  712. *
  713. * Returns 1 on success, 0 on failure.
  714. */
  715. int rand_drbg_enable_locking(RAND_DRBG *drbg)
  716. {
  717. if (drbg->state != DRBG_UNINITIALISED) {
  718. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  719. RAND_R_DRBG_ALREADY_INITIALIZED);
  720. return 0;
  721. }
  722. if (drbg->lock == NULL) {
  723. if (drbg->parent != NULL && drbg->parent->lock == NULL) {
  724. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  725. RAND_R_PARENT_LOCKING_NOT_ENABLED);
  726. return 0;
  727. }
  728. drbg->lock = CRYPTO_THREAD_lock_new();
  729. if (drbg->lock == NULL) {
  730. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  731. RAND_R_FAILED_TO_CREATE_LOCK);
  732. return 0;
  733. }
  734. }
  735. return 1;
  736. }
  737. /*
  738. * Get and set the EXDATA
  739. */
  740. int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
  741. {
  742. return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
  743. }
  744. void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
  745. {
  746. return CRYPTO_get_ex_data(&drbg->ex_data, idx);
  747. }
  748. /*
  749. * The following functions provide a RAND_METHOD that works on the
  750. * global DRBG. They lock.
  751. */
  752. /*
  753. * Allocates a new global DRBG on the secure heap (if enabled) and
  754. * initializes it with default settings.
  755. *
  756. * Returns a pointer to the new DRBG instance on success, NULL on failure.
  757. */
  758. static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
  759. {
  760. RAND_DRBG *drbg;
  761. drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
  762. if (drbg == NULL)
  763. return NULL;
  764. /* Only the master DRBG needs to have a lock */
  765. if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
  766. goto err;
  767. /* enable seed propagation */
  768. tsan_store(&drbg->reseed_prop_counter, 1);
  769. /*
  770. * Ignore instantiation error to support just-in-time instantiation.
  771. *
  772. * The state of the drbg will be checked in RAND_DRBG_generate() and
  773. * an automatic recovery is attempted.
  774. */
  775. (void)RAND_DRBG_instantiate(drbg,
  776. (const unsigned char *) ossl_pers_string,
  777. sizeof(ossl_pers_string) - 1);
  778. return drbg;
  779. err:
  780. RAND_DRBG_free(drbg);
  781. return NULL;
  782. }
  783. /*
  784. * Initialize the global DRBGs on first use.
  785. * Returns 1 on success, 0 on failure.
  786. */
  787. DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
  788. {
  789. /*
  790. * ensure that libcrypto is initialized, otherwise the
  791. * DRBG locks are not cleaned up properly
  792. */
  793. if (!OPENSSL_init_crypto(0, NULL))
  794. return 0;
  795. if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
  796. return 0;
  797. if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
  798. goto err1;
  799. master_drbg = drbg_setup(NULL);
  800. if (master_drbg == NULL)
  801. goto err2;
  802. return 1;
  803. err2:
  804. CRYPTO_THREAD_cleanup_local(&public_drbg);
  805. err1:
  806. CRYPTO_THREAD_cleanup_local(&private_drbg);
  807. return 0;
  808. }
  809. /* Clean up the global DRBGs before exit */
  810. void rand_drbg_cleanup_int(void)
  811. {
  812. if (master_drbg != NULL) {
  813. RAND_DRBG_free(master_drbg);
  814. master_drbg = NULL;
  815. CRYPTO_THREAD_cleanup_local(&private_drbg);
  816. CRYPTO_THREAD_cleanup_local(&public_drbg);
  817. }
  818. }
  819. void drbg_delete_thread_state(void)
  820. {
  821. RAND_DRBG *drbg;
  822. drbg = CRYPTO_THREAD_get_local(&public_drbg);
  823. CRYPTO_THREAD_set_local(&public_drbg, NULL);
  824. RAND_DRBG_free(drbg);
  825. drbg = CRYPTO_THREAD_get_local(&private_drbg);
  826. CRYPTO_THREAD_set_local(&private_drbg, NULL);
  827. RAND_DRBG_free(drbg);
  828. }
  829. /* Implements the default OpenSSL RAND_bytes() method */
  830. static int drbg_bytes(unsigned char *out, int count)
  831. {
  832. int ret;
  833. RAND_DRBG *drbg = RAND_DRBG_get0_public();
  834. if (drbg == NULL)
  835. return 0;
  836. ret = RAND_DRBG_bytes(drbg, out, count);
  837. return ret;
  838. }
  839. /*
  840. * Calculates the minimum length of a full entropy buffer
  841. * which is necessary to seed (i.e. instantiate) the DRBG
  842. * successfully.
  843. */
  844. size_t rand_drbg_seedlen(RAND_DRBG *drbg)
  845. {
  846. /*
  847. * If no os entropy source is available then RAND_seed(buffer, bufsize)
  848. * is expected to succeed if and only if the buffer length satisfies
  849. * the following requirements, which follow from the calculations
  850. * in RAND_DRBG_instantiate().
  851. */
  852. size_t min_entropy = drbg->strength;
  853. size_t min_entropylen = drbg->min_entropylen;
  854. /*
  855. * Extra entropy for the random nonce in the absence of a
  856. * get_nonce callback, see comment in RAND_DRBG_instantiate().
  857. */
  858. if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
  859. min_entropy += drbg->strength / 2;
  860. min_entropylen += drbg->min_noncelen;
  861. }
  862. /*
  863. * Convert entropy requirement from bits to bytes
  864. * (dividing by 8 without rounding upwards, because
  865. * all entropy requirements are divisible by 8).
  866. */
  867. min_entropy >>= 3;
  868. /* Return a value that satisfies both requirements */
  869. return min_entropy > min_entropylen ? min_entropy : min_entropylen;
  870. }
  871. /* Implements the default OpenSSL RAND_add() method */
  872. static int drbg_add(const void *buf, int num, double randomness)
  873. {
  874. int ret = 0;
  875. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  876. size_t buflen;
  877. size_t seedlen;
  878. if (drbg == NULL)
  879. return 0;
  880. if (num < 0 || randomness < 0.0)
  881. return 0;
  882. rand_drbg_lock(drbg);
  883. seedlen = rand_drbg_seedlen(drbg);
  884. buflen = (size_t)num;
  885. if (buflen < seedlen || randomness < (double) seedlen) {
  886. #if defined(OPENSSL_RAND_SEED_NONE)
  887. /*
  888. * If no os entropy source is available, a reseeding will fail
  889. * inevitably. So we use a trick to mix the buffer contents into
  890. * the DRBG state without forcing a reseeding: we generate a
  891. * dummy random byte, using the buffer content as additional data.
  892. * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
  893. */
  894. unsigned char dummy[1];
  895. ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
  896. rand_drbg_unlock(drbg);
  897. return ret;
  898. #else
  899. /*
  900. * If an os entropy source is avaible then we declare the buffer content
  901. * as additional data by setting randomness to zero and trigger a regular
  902. * reseeding.
  903. */
  904. randomness = 0.0;
  905. #endif
  906. }
  907. if (randomness > (double)seedlen) {
  908. /*
  909. * The purpose of this check is to bound |randomness| by a
  910. * relatively small value in order to prevent an integer
  911. * overflow when multiplying by 8 in the rand_drbg_restart()
  912. * call below. Note that randomness is measured in bytes,
  913. * not bits, so this value corresponds to eight times the
  914. * security strength.
  915. */
  916. randomness = (double)seedlen;
  917. }
  918. ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
  919. rand_drbg_unlock(drbg);
  920. return ret;
  921. }
  922. /* Implements the default OpenSSL RAND_seed() method */
  923. static int drbg_seed(const void *buf, int num)
  924. {
  925. return drbg_add(buf, num, num);
  926. }
  927. /* Implements the default OpenSSL RAND_status() method */
  928. static int drbg_status(void)
  929. {
  930. int ret;
  931. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  932. if (drbg == NULL)
  933. return 0;
  934. rand_drbg_lock(drbg);
  935. ret = drbg->state == DRBG_READY ? 1 : 0;
  936. rand_drbg_unlock(drbg);
  937. return ret;
  938. }
  939. /*
  940. * Get the master DRBG.
  941. * Returns pointer to the DRBG on success, NULL on failure.
  942. *
  943. */
  944. RAND_DRBG *RAND_DRBG_get0_master(void)
  945. {
  946. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  947. return NULL;
  948. return master_drbg;
  949. }
  950. /*
  951. * Get the public DRBG.
  952. * Returns pointer to the DRBG on success, NULL on failure.
  953. */
  954. RAND_DRBG *RAND_DRBG_get0_public(void)
  955. {
  956. RAND_DRBG *drbg;
  957. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  958. return NULL;
  959. drbg = CRYPTO_THREAD_get_local(&public_drbg);
  960. if (drbg == NULL) {
  961. if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
  962. return NULL;
  963. drbg = drbg_setup(master_drbg);
  964. CRYPTO_THREAD_set_local(&public_drbg, drbg);
  965. }
  966. return drbg;
  967. }
  968. /*
  969. * Get the private DRBG.
  970. * Returns pointer to the DRBG on success, NULL on failure.
  971. */
  972. RAND_DRBG *RAND_DRBG_get0_private(void)
  973. {
  974. RAND_DRBG *drbg;
  975. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  976. return NULL;
  977. drbg = CRYPTO_THREAD_get_local(&private_drbg);
  978. if (drbg == NULL) {
  979. if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
  980. return NULL;
  981. drbg = drbg_setup(master_drbg);
  982. CRYPTO_THREAD_set_local(&private_drbg, drbg);
  983. }
  984. return drbg;
  985. }
  986. RAND_METHOD rand_meth = {
  987. drbg_seed,
  988. drbg_bytes,
  989. NULL,
  990. drbg_add,
  991. drbg_bytes,
  992. drbg_status
  993. };
  994. RAND_METHOD *RAND_OpenSSL(void)
  995. {
  996. return &rand_meth;
  997. }