drbg_lib.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. /*
  2. * Copyright 2011-2020 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_local.h"
  14. #include "internal/thread_once.h"
  15. #include "crypto/rand.h"
  16. #include "crypto/cryptlib.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. if (drbg->get_entropy != NULL)
  280. entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
  281. min_entropylen, max_entropylen, 0);
  282. if (entropylen < min_entropylen
  283. || entropylen > max_entropylen) {
  284. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
  285. goto end;
  286. }
  287. if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
  288. noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
  289. drbg->min_noncelen, drbg->max_noncelen);
  290. if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
  291. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
  292. goto end;
  293. }
  294. }
  295. if (!drbg->meth->instantiate(drbg, entropy, entropylen,
  296. nonce, noncelen, pers, perslen)) {
  297. RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
  298. goto end;
  299. }
  300. drbg->state = DRBG_READY;
  301. drbg->generate_counter = 1;
  302. drbg->reseed_time = time(NULL);
  303. if (drbg->enable_reseed_propagation) {
  304. if (drbg->parent == NULL)
  305. tsan_counter(&drbg->reseed_counter);
  306. else
  307. tsan_store(&drbg->reseed_counter,
  308. tsan_load(&drbg->parent->reseed_counter));
  309. }
  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. if (drbg->get_entropy != NULL)
  370. entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
  371. drbg->min_entropylen,
  372. drbg->max_entropylen,
  373. prediction_resistance);
  374. if (entropylen < drbg->min_entropylen
  375. || entropylen > drbg->max_entropylen) {
  376. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
  377. goto end;
  378. }
  379. if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
  380. goto end;
  381. drbg->state = DRBG_READY;
  382. drbg->generate_counter = 1;
  383. drbg->reseed_time = time(NULL);
  384. if (drbg->enable_reseed_propagation) {
  385. if (drbg->parent == NULL)
  386. tsan_counter(&drbg->reseed_counter);
  387. else
  388. tsan_store(&drbg->reseed_counter,
  389. tsan_load(&drbg->parent->reseed_counter));
  390. }
  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. if (!RAND_DRBG_reseed(drbg, NULL, 0, 0)) {
  483. RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_RESEED_ERROR);
  484. }
  485. }
  486. }
  487. rand_pool_free(drbg->seed_pool);
  488. drbg->seed_pool = NULL;
  489. return drbg->state == DRBG_READY;
  490. }
  491. /*
  492. * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
  493. * to or if |prediction_resistance| is set. Additional input can be
  494. * sent in |adin| and |adinlen|.
  495. *
  496. * Requires that drbg->lock is already locked for write, if non-null.
  497. *
  498. * Returns 1 on success, 0 on failure.
  499. *
  500. */
  501. int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
  502. int prediction_resistance,
  503. const unsigned char *adin, size_t adinlen)
  504. {
  505. int fork_id;
  506. int reseed_required = 0;
  507. if (drbg->state != DRBG_READY) {
  508. /* try to recover from previous errors */
  509. rand_drbg_restart(drbg, NULL, 0, 0);
  510. if (drbg->state == DRBG_ERROR) {
  511. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
  512. return 0;
  513. }
  514. if (drbg->state == DRBG_UNINITIALISED) {
  515. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
  516. return 0;
  517. }
  518. }
  519. if (outlen > drbg->max_request) {
  520. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
  521. return 0;
  522. }
  523. if (adinlen > drbg->max_adinlen) {
  524. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
  525. return 0;
  526. }
  527. fork_id = openssl_get_fork_id();
  528. if (drbg->fork_id != fork_id) {
  529. drbg->fork_id = fork_id;
  530. reseed_required = 1;
  531. }
  532. if (drbg->reseed_interval > 0) {
  533. if (drbg->generate_counter >= drbg->reseed_interval)
  534. reseed_required = 1;
  535. }
  536. if (drbg->reseed_time_interval > 0) {
  537. time_t now = time(NULL);
  538. if (now < drbg->reseed_time
  539. || now - drbg->reseed_time >= drbg->reseed_time_interval)
  540. reseed_required = 1;
  541. }
  542. if (drbg->enable_reseed_propagation && drbg->parent != NULL) {
  543. if (drbg->reseed_counter != tsan_load(&drbg->parent->reseed_counter))
  544. reseed_required = 1;
  545. }
  546. if (reseed_required || prediction_resistance) {
  547. if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
  548. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
  549. return 0;
  550. }
  551. adin = NULL;
  552. adinlen = 0;
  553. }
  554. if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
  555. drbg->state = DRBG_ERROR;
  556. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
  557. return 0;
  558. }
  559. drbg->generate_counter++;
  560. return 1;
  561. }
  562. /*
  563. * Generates |outlen| random bytes and stores them in |out|. It will
  564. * using the given |drbg| to generate the bytes.
  565. *
  566. * Requires that drbg->lock is already locked for write, if non-null.
  567. *
  568. * Returns 1 on success 0 on failure.
  569. */
  570. int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
  571. {
  572. unsigned char *additional = NULL;
  573. size_t additional_len;
  574. size_t chunk;
  575. size_t ret = 0;
  576. if (drbg->adin_pool == NULL) {
  577. if (drbg->type == 0)
  578. goto err;
  579. drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
  580. if (drbg->adin_pool == NULL)
  581. goto err;
  582. }
  583. additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
  584. &additional);
  585. for ( ; outlen > 0; outlen -= chunk, out += chunk) {
  586. chunk = outlen;
  587. if (chunk > drbg->max_request)
  588. chunk = drbg->max_request;
  589. ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
  590. if (!ret)
  591. goto err;
  592. }
  593. ret = 1;
  594. err:
  595. if (additional != NULL)
  596. rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
  597. return ret;
  598. }
  599. /*
  600. * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
  601. *
  602. * Setting the callbacks is allowed only if the drbg has not been
  603. * initialized yet. Otherwise, the operation will fail.
  604. *
  605. * Returns 1 on success, 0 on failure.
  606. */
  607. int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
  608. RAND_DRBG_get_entropy_fn get_entropy,
  609. RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
  610. RAND_DRBG_get_nonce_fn get_nonce,
  611. RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
  612. {
  613. if (drbg->state != DRBG_UNINITIALISED)
  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 reseed propagation */
  766. drbg->enable_reseed_propagation = 1;
  767. drbg->reseed_counter = 1;
  768. /*
  769. * Ignore instantiation error to support just-in-time instantiation.
  770. *
  771. * The state of the drbg will be checked in RAND_DRBG_generate() and
  772. * an automatic recovery is attempted.
  773. */
  774. (void)RAND_DRBG_instantiate(drbg,
  775. (const unsigned char *) ossl_pers_string,
  776. sizeof(ossl_pers_string) - 1);
  777. return drbg;
  778. err:
  779. RAND_DRBG_free(drbg);
  780. return NULL;
  781. }
  782. /*
  783. * Initialize the global DRBGs on first use.
  784. * Returns 1 on success, 0 on failure.
  785. */
  786. DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
  787. {
  788. /*
  789. * ensure that libcrypto is initialized, otherwise the
  790. * DRBG locks are not cleaned up properly
  791. */
  792. if (!OPENSSL_init_crypto(0, NULL))
  793. return 0;
  794. if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
  795. return 0;
  796. if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
  797. goto err1;
  798. master_drbg = drbg_setup(NULL);
  799. if (master_drbg == NULL)
  800. goto err2;
  801. return 1;
  802. err2:
  803. CRYPTO_THREAD_cleanup_local(&public_drbg);
  804. err1:
  805. CRYPTO_THREAD_cleanup_local(&private_drbg);
  806. return 0;
  807. }
  808. /* Clean up the global DRBGs before exit */
  809. void rand_drbg_cleanup_int(void)
  810. {
  811. if (master_drbg != NULL) {
  812. RAND_DRBG_free(master_drbg);
  813. master_drbg = NULL;
  814. CRYPTO_THREAD_cleanup_local(&private_drbg);
  815. CRYPTO_THREAD_cleanup_local(&public_drbg);
  816. }
  817. }
  818. void drbg_delete_thread_state(void)
  819. {
  820. RAND_DRBG *drbg;
  821. drbg = CRYPTO_THREAD_get_local(&public_drbg);
  822. CRYPTO_THREAD_set_local(&public_drbg, NULL);
  823. RAND_DRBG_free(drbg);
  824. drbg = CRYPTO_THREAD_get_local(&private_drbg);
  825. CRYPTO_THREAD_set_local(&private_drbg, NULL);
  826. RAND_DRBG_free(drbg);
  827. }
  828. /* Implements the default OpenSSL RAND_bytes() method */
  829. static int drbg_bytes(unsigned char *out, int count)
  830. {
  831. int ret;
  832. RAND_DRBG *drbg = RAND_DRBG_get0_public();
  833. if (drbg == NULL)
  834. return 0;
  835. ret = RAND_DRBG_bytes(drbg, out, count);
  836. return ret;
  837. }
  838. /*
  839. * Calculates the minimum length of a full entropy buffer
  840. * which is necessary to seed (i.e. instantiate) the DRBG
  841. * successfully.
  842. */
  843. size_t rand_drbg_seedlen(RAND_DRBG *drbg)
  844. {
  845. /*
  846. * If no os entropy source is available then RAND_seed(buffer, bufsize)
  847. * is expected to succeed if and only if the buffer length satisfies
  848. * the following requirements, which follow from the calculations
  849. * in RAND_DRBG_instantiate().
  850. */
  851. size_t min_entropy = drbg->strength;
  852. size_t min_entropylen = drbg->min_entropylen;
  853. /*
  854. * Extra entropy for the random nonce in the absence of a
  855. * get_nonce callback, see comment in RAND_DRBG_instantiate().
  856. */
  857. if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
  858. min_entropy += drbg->strength / 2;
  859. min_entropylen += drbg->min_noncelen;
  860. }
  861. /*
  862. * Convert entropy requirement from bits to bytes
  863. * (dividing by 8 without rounding upwards, because
  864. * all entropy requirements are divisible by 8).
  865. */
  866. min_entropy >>= 3;
  867. /* Return a value that satisfies both requirements */
  868. return min_entropy > min_entropylen ? min_entropy : min_entropylen;
  869. }
  870. /* Implements the default OpenSSL RAND_add() method */
  871. static int drbg_add(const void *buf, int num, double randomness)
  872. {
  873. int ret = 0;
  874. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  875. size_t buflen;
  876. size_t seedlen;
  877. if (drbg == NULL)
  878. return 0;
  879. if (num < 0 || randomness < 0.0)
  880. return 0;
  881. rand_drbg_lock(drbg);
  882. seedlen = rand_drbg_seedlen(drbg);
  883. buflen = (size_t)num;
  884. if (buflen < seedlen || randomness < (double) seedlen) {
  885. #if defined(OPENSSL_RAND_SEED_NONE)
  886. /*
  887. * If no os entropy source is available, a reseeding will fail
  888. * inevitably. So we use a trick to mix the buffer contents into
  889. * the DRBG state without forcing a reseeding: we generate a
  890. * dummy random byte, using the buffer content as additional data.
  891. * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
  892. */
  893. unsigned char dummy[1];
  894. ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
  895. rand_drbg_unlock(drbg);
  896. return ret;
  897. #else
  898. /*
  899. * If an os entropy source is available then we declare the buffer content
  900. * as additional data by setting randomness to zero and trigger a regular
  901. * reseeding.
  902. */
  903. randomness = 0.0;
  904. #endif
  905. }
  906. if (randomness > (double)seedlen) {
  907. /*
  908. * The purpose of this check is to bound |randomness| by a
  909. * relatively small value in order to prevent an integer
  910. * overflow when multiplying by 8 in the rand_drbg_restart()
  911. * call below. Note that randomness is measured in bytes,
  912. * not bits, so this value corresponds to eight times the
  913. * security strength.
  914. */
  915. randomness = (double)seedlen;
  916. }
  917. ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
  918. rand_drbg_unlock(drbg);
  919. return ret;
  920. }
  921. /* Implements the default OpenSSL RAND_seed() method */
  922. static int drbg_seed(const void *buf, int num)
  923. {
  924. return drbg_add(buf, num, num);
  925. }
  926. /* Implements the default OpenSSL RAND_status() method */
  927. static int drbg_status(void)
  928. {
  929. int ret;
  930. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  931. if (drbg == NULL)
  932. return 0;
  933. rand_drbg_lock(drbg);
  934. ret = drbg->state == DRBG_READY ? 1 : 0;
  935. rand_drbg_unlock(drbg);
  936. return ret;
  937. }
  938. /*
  939. * Get the master DRBG.
  940. * Returns pointer to the DRBG on success, NULL on failure.
  941. *
  942. */
  943. RAND_DRBG *RAND_DRBG_get0_master(void)
  944. {
  945. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  946. return NULL;
  947. return master_drbg;
  948. }
  949. /*
  950. * Get the public DRBG.
  951. * Returns pointer to the DRBG on success, NULL on failure.
  952. */
  953. RAND_DRBG *RAND_DRBG_get0_public(void)
  954. {
  955. RAND_DRBG *drbg;
  956. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  957. return NULL;
  958. drbg = CRYPTO_THREAD_get_local(&public_drbg);
  959. if (drbg == NULL) {
  960. if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
  961. return NULL;
  962. drbg = drbg_setup(master_drbg);
  963. CRYPTO_THREAD_set_local(&public_drbg, drbg);
  964. }
  965. return drbg;
  966. }
  967. /*
  968. * Get the private DRBG.
  969. * Returns pointer to the DRBG on success, NULL on failure.
  970. */
  971. RAND_DRBG *RAND_DRBG_get0_private(void)
  972. {
  973. RAND_DRBG *drbg;
  974. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  975. return NULL;
  976. drbg = CRYPTO_THREAD_get_local(&private_drbg);
  977. if (drbg == NULL) {
  978. if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
  979. return NULL;
  980. drbg = drbg_setup(master_drbg);
  981. CRYPTO_THREAD_set_local(&private_drbg, drbg);
  982. }
  983. return drbg;
  984. }
  985. RAND_METHOD rand_meth = {
  986. drbg_seed,
  987. drbg_bytes,
  988. NULL,
  989. drbg_add,
  990. drbg_bytes,
  991. drbg_status
  992. };
  993. RAND_METHOD *RAND_OpenSSL(void)
  994. {
  995. return &rand_meth;
  996. }