drbg_lib.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. /*
  2. * Copyright 2011-2022 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 && drbg->parent == NULL)
  304. tsan_counter(&drbg->reseed_counter);
  305. end:
  306. if (entropy != NULL && drbg->cleanup_entropy != NULL)
  307. drbg->cleanup_entropy(drbg, entropy, entropylen);
  308. if (nonce != NULL && drbg->cleanup_nonce != NULL)
  309. drbg->cleanup_nonce(drbg, nonce, noncelen);
  310. if (drbg->state == DRBG_READY)
  311. return 1;
  312. return 0;
  313. }
  314. /*
  315. * Uninstantiate |drbg|. Must be instantiated before it can be used.
  316. *
  317. * Requires that drbg->lock is already locked for write, if non-null.
  318. *
  319. * Returns 1 on success, 0 on failure.
  320. */
  321. int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
  322. {
  323. if (drbg->meth == NULL) {
  324. drbg->state = DRBG_ERROR;
  325. RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
  326. RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
  327. return 0;
  328. }
  329. /* Clear the entire drbg->ctr struct, then reset some important
  330. * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
  331. * initial values.
  332. */
  333. drbg->meth->uninstantiate(drbg);
  334. return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
  335. }
  336. /*
  337. * Reseed |drbg|, mixing in the specified data
  338. *
  339. * Requires that drbg->lock is already locked for write, if non-null.
  340. *
  341. * Returns 1 on success, 0 on failure.
  342. */
  343. int RAND_DRBG_reseed(RAND_DRBG *drbg,
  344. const unsigned char *adin, size_t adinlen,
  345. int prediction_resistance)
  346. {
  347. unsigned char *entropy = NULL;
  348. size_t entropylen = 0;
  349. if (drbg->state == DRBG_ERROR) {
  350. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
  351. return 0;
  352. }
  353. if (drbg->state == DRBG_UNINITIALISED) {
  354. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
  355. return 0;
  356. }
  357. if (adin == NULL) {
  358. adinlen = 0;
  359. } else if (adinlen > drbg->max_adinlen) {
  360. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
  361. return 0;
  362. }
  363. drbg->state = DRBG_ERROR;
  364. if (drbg->get_entropy != NULL)
  365. entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
  366. drbg->min_entropylen,
  367. drbg->max_entropylen,
  368. prediction_resistance);
  369. if (entropylen < drbg->min_entropylen
  370. || entropylen > drbg->max_entropylen) {
  371. RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
  372. goto end;
  373. }
  374. if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
  375. goto end;
  376. drbg->state = DRBG_READY;
  377. drbg->generate_counter = 1;
  378. drbg->reseed_time = time(NULL);
  379. if (drbg->enable_reseed_propagation && drbg->parent == NULL)
  380. tsan_counter(&drbg->reseed_counter);
  381. end:
  382. if (entropy != NULL && drbg->cleanup_entropy != NULL)
  383. drbg->cleanup_entropy(drbg, entropy, entropylen);
  384. if (drbg->state == DRBG_READY)
  385. return 1;
  386. return 0;
  387. }
  388. /*
  389. * Restart |drbg|, using the specified entropy or additional input
  390. *
  391. * Tries its best to get the drbg instantiated by all means,
  392. * regardless of its current state.
  393. *
  394. * Optionally, a |buffer| of |len| random bytes can be passed,
  395. * which is assumed to contain at least |entropy| bits of entropy.
  396. *
  397. * If |entropy| > 0, the buffer content is used as entropy input.
  398. *
  399. * If |entropy| == 0, the buffer content is used as additional input
  400. *
  401. * Returns 1 on success, 0 on failure.
  402. *
  403. * This function is used internally only.
  404. */
  405. int rand_drbg_restart(RAND_DRBG *drbg,
  406. const unsigned char *buffer, size_t len, size_t entropy)
  407. {
  408. int reseeded = 0;
  409. const unsigned char *adin = NULL;
  410. size_t adinlen = 0;
  411. if (drbg->seed_pool != NULL) {
  412. RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
  413. drbg->state = DRBG_ERROR;
  414. rand_pool_free(drbg->seed_pool);
  415. drbg->seed_pool = NULL;
  416. return 0;
  417. }
  418. if (buffer != NULL) {
  419. if (entropy > 0) {
  420. if (drbg->max_entropylen < len) {
  421. RANDerr(RAND_F_RAND_DRBG_RESTART,
  422. RAND_R_ENTROPY_INPUT_TOO_LONG);
  423. drbg->state = DRBG_ERROR;
  424. return 0;
  425. }
  426. if (entropy > 8 * len) {
  427. RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
  428. drbg->state = DRBG_ERROR;
  429. return 0;
  430. }
  431. /* will be picked up by the rand_drbg_get_entropy() callback */
  432. drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
  433. if (drbg->seed_pool == NULL)
  434. return 0;
  435. } else {
  436. if (drbg->max_adinlen < len) {
  437. RANDerr(RAND_F_RAND_DRBG_RESTART,
  438. RAND_R_ADDITIONAL_INPUT_TOO_LONG);
  439. drbg->state = DRBG_ERROR;
  440. return 0;
  441. }
  442. adin = buffer;
  443. adinlen = len;
  444. }
  445. }
  446. /* repair error state */
  447. if (drbg->state == DRBG_ERROR)
  448. RAND_DRBG_uninstantiate(drbg);
  449. /* repair uninitialized state */
  450. if (drbg->state == DRBG_UNINITIALISED) {
  451. /* reinstantiate drbg */
  452. RAND_DRBG_instantiate(drbg,
  453. (const unsigned char *) ossl_pers_string,
  454. sizeof(ossl_pers_string) - 1);
  455. /* already reseeded. prevent second reseeding below */
  456. reseeded = (drbg->state == DRBG_READY);
  457. }
  458. /* refresh current state if entropy or additional input has been provided */
  459. if (drbg->state == DRBG_READY) {
  460. if (adin != NULL) {
  461. /*
  462. * mix in additional input without reseeding
  463. *
  464. * Similar to RAND_DRBG_reseed(), but the provided additional
  465. * data |adin| is mixed into the current state without pulling
  466. * entropy from the trusted entropy source using get_entropy().
  467. * This is not a reseeding in the strict sense of NIST SP 800-90A.
  468. */
  469. drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
  470. } else if (reseeded == 0) {
  471. /* do a full reseeding if it has not been done yet above */
  472. if (!RAND_DRBG_reseed(drbg, NULL, 0, 0)) {
  473. RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_RESEED_ERROR);
  474. }
  475. }
  476. }
  477. rand_pool_free(drbg->seed_pool);
  478. drbg->seed_pool = NULL;
  479. return drbg->state == DRBG_READY;
  480. }
  481. /*
  482. * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
  483. * to or if |prediction_resistance| is set. Additional input can be
  484. * sent in |adin| and |adinlen|.
  485. *
  486. * Requires that drbg->lock is already locked for write, if non-null.
  487. *
  488. * Returns 1 on success, 0 on failure.
  489. *
  490. */
  491. int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
  492. int prediction_resistance,
  493. const unsigned char *adin, size_t adinlen)
  494. {
  495. int fork_id;
  496. int reseed_required = 0;
  497. if (drbg->state != DRBG_READY) {
  498. /* try to recover from previous errors */
  499. rand_drbg_restart(drbg, NULL, 0, 0);
  500. if (drbg->state == DRBG_ERROR) {
  501. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
  502. return 0;
  503. }
  504. if (drbg->state == DRBG_UNINITIALISED) {
  505. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
  506. return 0;
  507. }
  508. }
  509. if (outlen > drbg->max_request) {
  510. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
  511. return 0;
  512. }
  513. if (adinlen > drbg->max_adinlen) {
  514. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
  515. return 0;
  516. }
  517. fork_id = openssl_get_fork_id();
  518. if (drbg->fork_id != fork_id) {
  519. drbg->fork_id = fork_id;
  520. reseed_required = 1;
  521. }
  522. if (drbg->reseed_interval > 0) {
  523. if (drbg->generate_counter >= drbg->reseed_interval)
  524. reseed_required = 1;
  525. }
  526. if (drbg->reseed_time_interval > 0) {
  527. time_t now = time(NULL);
  528. if (now < drbg->reseed_time
  529. || now - drbg->reseed_time >= drbg->reseed_time_interval)
  530. reseed_required = 1;
  531. }
  532. if (drbg->enable_reseed_propagation && drbg->parent != NULL) {
  533. if (drbg->reseed_counter != tsan_load(&drbg->parent->reseed_counter))
  534. reseed_required = 1;
  535. }
  536. if (reseed_required || prediction_resistance) {
  537. if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
  538. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
  539. return 0;
  540. }
  541. adin = NULL;
  542. adinlen = 0;
  543. }
  544. if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
  545. drbg->state = DRBG_ERROR;
  546. RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
  547. return 0;
  548. }
  549. drbg->generate_counter++;
  550. return 1;
  551. }
  552. /*
  553. * Generates |outlen| random bytes and stores them in |out|. It will
  554. * using the given |drbg| to generate the bytes.
  555. *
  556. * Requires that drbg->lock is already locked for write, if non-null.
  557. *
  558. * Returns 1 on success 0 on failure.
  559. */
  560. int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
  561. {
  562. unsigned char *additional = NULL;
  563. size_t additional_len;
  564. size_t chunk;
  565. size_t ret = 0;
  566. if (drbg->adin_pool == NULL) {
  567. if (drbg->type == 0)
  568. goto err;
  569. drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
  570. if (drbg->adin_pool == NULL)
  571. goto err;
  572. }
  573. additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
  574. &additional);
  575. for ( ; outlen > 0; outlen -= chunk, out += chunk) {
  576. chunk = outlen;
  577. if (chunk > drbg->max_request)
  578. chunk = drbg->max_request;
  579. ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
  580. if (!ret)
  581. goto err;
  582. }
  583. ret = 1;
  584. err:
  585. if (additional != NULL)
  586. rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
  587. return ret;
  588. }
  589. /*
  590. * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
  591. *
  592. * Setting the callbacks is allowed only if the drbg has not been
  593. * initialized yet. Otherwise, the operation will fail.
  594. *
  595. * Returns 1 on success, 0 on failure.
  596. */
  597. int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
  598. RAND_DRBG_get_entropy_fn get_entropy,
  599. RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
  600. RAND_DRBG_get_nonce_fn get_nonce,
  601. RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
  602. {
  603. if (drbg->state != DRBG_UNINITIALISED)
  604. return 0;
  605. drbg->get_entropy = get_entropy;
  606. drbg->cleanup_entropy = cleanup_entropy;
  607. drbg->get_nonce = get_nonce;
  608. drbg->cleanup_nonce = cleanup_nonce;
  609. return 1;
  610. }
  611. /*
  612. * Set the reseed interval.
  613. *
  614. * The drbg will reseed automatically whenever the number of generate
  615. * requests exceeds the given reseed interval. If the reseed interval
  616. * is 0, then this feature is disabled.
  617. *
  618. * Returns 1 on success, 0 on failure.
  619. */
  620. int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
  621. {
  622. if (interval > MAX_RESEED_INTERVAL)
  623. return 0;
  624. drbg->reseed_interval = interval;
  625. return 1;
  626. }
  627. /*
  628. * Set the reseed time interval.
  629. *
  630. * The drbg will reseed automatically whenever the time elapsed since
  631. * the last reseeding exceeds the given reseed time interval. For safety,
  632. * a reseeding will also occur if the clock has been reset to a smaller
  633. * value.
  634. *
  635. * Returns 1 on success, 0 on failure.
  636. */
  637. int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
  638. {
  639. if (interval > MAX_RESEED_TIME_INTERVAL)
  640. return 0;
  641. drbg->reseed_time_interval = interval;
  642. return 1;
  643. }
  644. /*
  645. * Set the default values for reseed (time) intervals of new DRBG instances
  646. *
  647. * The default values can be set independently for master DRBG instances
  648. * (without a parent) and slave DRBG instances (with parent).
  649. *
  650. * Returns 1 on success, 0 on failure.
  651. */
  652. int RAND_DRBG_set_reseed_defaults(
  653. unsigned int _master_reseed_interval,
  654. unsigned int _slave_reseed_interval,
  655. time_t _master_reseed_time_interval,
  656. time_t _slave_reseed_time_interval
  657. )
  658. {
  659. if (_master_reseed_interval > MAX_RESEED_INTERVAL
  660. || _slave_reseed_interval > MAX_RESEED_INTERVAL)
  661. return 0;
  662. if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
  663. || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
  664. return 0;
  665. master_reseed_interval = _master_reseed_interval;
  666. slave_reseed_interval = _slave_reseed_interval;
  667. master_reseed_time_interval = _master_reseed_time_interval;
  668. slave_reseed_time_interval = _slave_reseed_time_interval;
  669. return 1;
  670. }
  671. /*
  672. * Locks the given drbg. Locking a drbg which does not have locking
  673. * enabled is considered a successful no-op.
  674. *
  675. * Returns 1 on success, 0 on failure.
  676. */
  677. int rand_drbg_lock(RAND_DRBG *drbg)
  678. {
  679. if (drbg->lock != NULL)
  680. return CRYPTO_THREAD_write_lock(drbg->lock);
  681. return 1;
  682. }
  683. /*
  684. * Unlocks the given drbg. Unlocking 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_unlock(RAND_DRBG *drbg)
  690. {
  691. if (drbg->lock != NULL)
  692. return CRYPTO_THREAD_unlock(drbg->lock);
  693. return 1;
  694. }
  695. /*
  696. * Enables locking for the given drbg
  697. *
  698. * Locking can only be enabled if the random generator
  699. * is in the uninitialized state.
  700. *
  701. * Returns 1 on success, 0 on failure.
  702. */
  703. int rand_drbg_enable_locking(RAND_DRBG *drbg)
  704. {
  705. if (drbg->state != DRBG_UNINITIALISED) {
  706. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  707. RAND_R_DRBG_ALREADY_INITIALIZED);
  708. return 0;
  709. }
  710. if (drbg->lock == NULL) {
  711. if (drbg->parent != NULL && drbg->parent->lock == NULL) {
  712. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  713. RAND_R_PARENT_LOCKING_NOT_ENABLED);
  714. return 0;
  715. }
  716. drbg->lock = CRYPTO_THREAD_lock_new();
  717. if (drbg->lock == NULL) {
  718. RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
  719. RAND_R_FAILED_TO_CREATE_LOCK);
  720. return 0;
  721. }
  722. }
  723. return 1;
  724. }
  725. /*
  726. * Get and set the EXDATA
  727. */
  728. int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
  729. {
  730. return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
  731. }
  732. void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
  733. {
  734. return CRYPTO_get_ex_data(&drbg->ex_data, idx);
  735. }
  736. /*
  737. * The following functions provide a RAND_METHOD that works on the
  738. * global DRBG. They lock.
  739. */
  740. /*
  741. * Allocates a new global DRBG on the secure heap (if enabled) and
  742. * initializes it with default settings.
  743. *
  744. * Returns a pointer to the new DRBG instance on success, NULL on failure.
  745. */
  746. static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
  747. {
  748. RAND_DRBG *drbg;
  749. drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
  750. if (drbg == NULL)
  751. return NULL;
  752. /* Only the master DRBG needs to have a lock */
  753. if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
  754. goto err;
  755. /* enable reseed propagation */
  756. drbg->enable_reseed_propagation = 1;
  757. drbg->reseed_counter = 1;
  758. /*
  759. * Ignore instantiation error to support just-in-time instantiation.
  760. *
  761. * The state of the drbg will be checked in RAND_DRBG_generate() and
  762. * an automatic recovery is attempted.
  763. */
  764. (void)RAND_DRBG_instantiate(drbg,
  765. (const unsigned char *) ossl_pers_string,
  766. sizeof(ossl_pers_string) - 1);
  767. return drbg;
  768. err:
  769. RAND_DRBG_free(drbg);
  770. return NULL;
  771. }
  772. /*
  773. * Initialize the global DRBGs on first use.
  774. * Returns 1 on success, 0 on failure.
  775. */
  776. DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
  777. {
  778. /*
  779. * ensure that libcrypto is initialized, otherwise the
  780. * DRBG locks are not cleaned up properly
  781. */
  782. if (!OPENSSL_init_crypto(0, NULL))
  783. return 0;
  784. if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
  785. return 0;
  786. if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
  787. goto err1;
  788. master_drbg = drbg_setup(NULL);
  789. if (master_drbg == NULL)
  790. goto err2;
  791. return 1;
  792. err2:
  793. CRYPTO_THREAD_cleanup_local(&public_drbg);
  794. err1:
  795. CRYPTO_THREAD_cleanup_local(&private_drbg);
  796. return 0;
  797. }
  798. /* Clean up the global DRBGs before exit */
  799. void rand_drbg_cleanup_int(void)
  800. {
  801. if (master_drbg != NULL) {
  802. RAND_DRBG_free(master_drbg);
  803. master_drbg = NULL;
  804. CRYPTO_THREAD_cleanup_local(&private_drbg);
  805. CRYPTO_THREAD_cleanup_local(&public_drbg);
  806. }
  807. }
  808. void drbg_delete_thread_state(void)
  809. {
  810. RAND_DRBG *drbg;
  811. drbg = CRYPTO_THREAD_get_local(&public_drbg);
  812. CRYPTO_THREAD_set_local(&public_drbg, NULL);
  813. RAND_DRBG_free(drbg);
  814. drbg = CRYPTO_THREAD_get_local(&private_drbg);
  815. CRYPTO_THREAD_set_local(&private_drbg, NULL);
  816. RAND_DRBG_free(drbg);
  817. }
  818. /* Implements the default OpenSSL RAND_bytes() method */
  819. static int drbg_bytes(unsigned char *out, int count)
  820. {
  821. int ret;
  822. RAND_DRBG *drbg = RAND_DRBG_get0_public();
  823. if (drbg == NULL)
  824. return 0;
  825. ret = RAND_DRBG_bytes(drbg, out, count);
  826. return ret;
  827. }
  828. /*
  829. * Calculates the minimum length of a full entropy buffer
  830. * which is necessary to seed (i.e. instantiate) the DRBG
  831. * successfully.
  832. */
  833. size_t rand_drbg_seedlen(RAND_DRBG *drbg)
  834. {
  835. /*
  836. * If no os entropy source is available then RAND_seed(buffer, bufsize)
  837. * is expected to succeed if and only if the buffer length satisfies
  838. * the following requirements, which follow from the calculations
  839. * in RAND_DRBG_instantiate().
  840. */
  841. size_t min_entropy = drbg->strength;
  842. size_t min_entropylen = drbg->min_entropylen;
  843. /*
  844. * Extra entropy for the random nonce in the absence of a
  845. * get_nonce callback, see comment in RAND_DRBG_instantiate().
  846. */
  847. if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
  848. min_entropy += drbg->strength / 2;
  849. min_entropylen += drbg->min_noncelen;
  850. }
  851. /*
  852. * Convert entropy requirement from bits to bytes
  853. * (dividing by 8 without rounding upwards, because
  854. * all entropy requirements are divisible by 8).
  855. */
  856. min_entropy >>= 3;
  857. /* Return a value that satisfies both requirements */
  858. return min_entropy > min_entropylen ? min_entropy : min_entropylen;
  859. }
  860. /* Implements the default OpenSSL RAND_add() method */
  861. static int drbg_add(const void *buf, int num, double randomness)
  862. {
  863. int ret = 0;
  864. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  865. size_t buflen;
  866. size_t seedlen;
  867. if (drbg == NULL)
  868. return 0;
  869. if (num < 0 || randomness < 0.0)
  870. return 0;
  871. rand_drbg_lock(drbg);
  872. seedlen = rand_drbg_seedlen(drbg);
  873. buflen = (size_t)num;
  874. if (buflen < seedlen || randomness < (double) seedlen) {
  875. #if defined(OPENSSL_RAND_SEED_NONE)
  876. /*
  877. * If no os entropy source is available, a reseeding will fail
  878. * inevitably. So we use a trick to mix the buffer contents into
  879. * the DRBG state without forcing a reseeding: we generate a
  880. * dummy random byte, using the buffer content as additional data.
  881. * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
  882. */
  883. unsigned char dummy[1];
  884. ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
  885. rand_drbg_unlock(drbg);
  886. return ret;
  887. #else
  888. /*
  889. * If an os entropy source is available then we declare the buffer content
  890. * as additional data by setting randomness to zero and trigger a regular
  891. * reseeding.
  892. */
  893. randomness = 0.0;
  894. #endif
  895. }
  896. if (randomness > (double)seedlen) {
  897. /*
  898. * The purpose of this check is to bound |randomness| by a
  899. * relatively small value in order to prevent an integer
  900. * overflow when multiplying by 8 in the rand_drbg_restart()
  901. * call below. Note that randomness is measured in bytes,
  902. * not bits, so this value corresponds to eight times the
  903. * security strength.
  904. */
  905. randomness = (double)seedlen;
  906. }
  907. ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
  908. rand_drbg_unlock(drbg);
  909. return ret;
  910. }
  911. /* Implements the default OpenSSL RAND_seed() method */
  912. static int drbg_seed(const void *buf, int num)
  913. {
  914. return drbg_add(buf, num, num);
  915. }
  916. /* Implements the default OpenSSL RAND_status() method */
  917. static int drbg_status(void)
  918. {
  919. int ret;
  920. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  921. if (drbg == NULL)
  922. return 0;
  923. rand_drbg_lock(drbg);
  924. ret = drbg->state == DRBG_READY ? 1 : 0;
  925. rand_drbg_unlock(drbg);
  926. return ret;
  927. }
  928. /*
  929. * Get the master DRBG.
  930. * Returns pointer to the DRBG on success, NULL on failure.
  931. *
  932. */
  933. RAND_DRBG *RAND_DRBG_get0_master(void)
  934. {
  935. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  936. return NULL;
  937. return master_drbg;
  938. }
  939. /*
  940. * Get the public DRBG.
  941. * Returns pointer to the DRBG on success, NULL on failure.
  942. */
  943. RAND_DRBG *RAND_DRBG_get0_public(void)
  944. {
  945. RAND_DRBG *drbg;
  946. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  947. return NULL;
  948. drbg = CRYPTO_THREAD_get_local(&public_drbg);
  949. if (drbg == NULL) {
  950. if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
  951. return NULL;
  952. drbg = drbg_setup(master_drbg);
  953. CRYPTO_THREAD_set_local(&public_drbg, drbg);
  954. }
  955. return drbg;
  956. }
  957. /*
  958. * Get the private DRBG.
  959. * Returns pointer to the DRBG on success, NULL on failure.
  960. */
  961. RAND_DRBG *RAND_DRBG_get0_private(void)
  962. {
  963. RAND_DRBG *drbg;
  964. if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
  965. return NULL;
  966. drbg = CRYPTO_THREAD_get_local(&private_drbg);
  967. if (drbg == NULL) {
  968. if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
  969. return NULL;
  970. drbg = drbg_setup(master_drbg);
  971. CRYPTO_THREAD_set_local(&private_drbg, drbg);
  972. }
  973. return drbg;
  974. }
  975. RAND_METHOD rand_meth = {
  976. drbg_seed,
  977. drbg_bytes,
  978. NULL,
  979. drbg_add,
  980. drbg_bytes,
  981. drbg_status
  982. };
  983. RAND_METHOD *RAND_OpenSSL(void)
  984. {
  985. return &rand_meth;
  986. }