You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ottery.c 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. /* Libottery by Nick Mathewson.
  2. This software has been dedicated to the public domain under the CC0
  3. public domain dedication.
  4. To the extent possible under law, the person who associated CC0 with
  5. libottery has waived all copyright and related or neighboring rights
  6. to libottery.
  7. You should have received a copy of the CC0 legalcode along with this
  8. work in doc/cc0.txt. If not, see
  9. <http://creativecommons.org/publicdomain/zero/1.0/>.
  10. */
  11. #define OTTERY_INTERNAL
  12. #include "ottery-internal.h"
  13. #include "ottery.h"
  14. #include "ottery_st.h"
  15. #include "ottery_nolock.h"
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <sys/types.h>
  19. #include <unistd.h>
  20. #include <limits.h>
  21. #include <stdio.h>
  22. /* I've added a few assertions to sanity-check for debugging, but they should
  23. * never ever ever trigger. It's fine to build this code with NDEBUG. */
  24. #include <assert.h>
  25. #ifdef _WIN32
  26. /* On Windows, there is no fork(), so we don't need to worry about forking. */
  27. #define OTTERY_NO_PID_CHECK
  28. #endif
  29. #ifdef BUILD_RSPAMD
  30. #include "cryptobox.h"
  31. #endif
  32. /** Magic number for deciding whether an ottery_state is initialized. */
  33. #define MAGIC_BASIS 0x11b07734
  34. /** Macro: yield the correct magic number for an ottery_state, based on
  35. * its position in RAM. */
  36. #define MAGIC(ptr) (((uint32_t)(uintptr_t)(ptr)) ^ MAGIC_BASIS)
  37. static inline int ottery_st_rand_lock_and_check(struct ottery_state *st)
  38. __attribute__((always_inline));
  39. static int ottery_st_reseed(struct ottery_state *state);
  40. static int ottery_st_add_seed_impl(struct ottery_state *st, const uint8_t *seed, size_t n, int locking, int check_magic);
  41. #ifndef OTTERY_NO_WIPE_STACK
  42. static void ottery_wipe_stack_(void) __attribute__((noinline));
  43. #endif
  44. #define LOCK(st) ACQUIRE_LOCK(&(st)->mutex)
  45. #define UNLOCK(st) RELEASE_LOCK(&(st)->mutex)
  46. size_t
  47. ottery_get_sizeof_config(void)
  48. {
  49. return sizeof(struct ottery_config);
  50. }
  51. size_t
  52. ottery_get_sizeof_state(void)
  53. {
  54. return sizeof(struct ottery_state);
  55. }
  56. size_t
  57. ottery_get_sizeof_state_nolock(void)
  58. {
  59. return sizeof(struct ottery_state_nolock);
  60. }
  61. const char *
  62. ottery_get_version_string(void)
  63. {
  64. return OTTERY_VERSION_STRING;
  65. }
  66. uint32_t
  67. ottery_get_version(void)
  68. {
  69. return OTTERY_VERSION;
  70. }
  71. uint32_t
  72. ottery_get_build_flags(void)
  73. {
  74. uint32_t result = 0;
  75. #ifdef OTTERY_NO_PID_CHECK
  76. result |= OTTERY_BLDFLG_NO_PID_CHECK;
  77. #endif
  78. #ifdef OTTERY_NO_INIT_CHECK
  79. result |= OTTERY_BLDFLG_NO_INIT_CHECK;
  80. #endif
  81. #ifdef OTTERY_NO_LOCKS
  82. result |= OTTERY_BLDFLG_NO_LOCKING;
  83. #endif
  84. #ifdef OTTERY_NO_CLEAR_AFTER_YIELD
  85. result |= OTTERY_BLDFLG_NO_CLEAR_AFTER_YIELD;
  86. #endif
  87. #ifdef OTTERY_NO_WIPE_STACK
  88. result |= OTTERY_BLDFLG_NO_WIPE_STACK;
  89. #endif
  90. #ifdef OTTERY_NO_SIMD
  91. result |= OTTERY_BLDFLG_NO_SIMD;
  92. #endif
  93. return result;
  94. }
  95. #ifndef OTTERY_NO_CLEAR_AFTER_YIELD
  96. /** Used to zero out the contents of our buffer after we've just given a few
  97. * to the user. */
  98. #define CLEARBUF(ptr,n) do { memset((ptr), 0, (n)); } while (0)
  99. #else
  100. #define CLEARBUF(ptr,n) ((void)0)
  101. #endif
  102. /**
  103. * Volatile pointer to memset: we use this to keep the compiler from
  104. * eliminating our call to memset. (Don't make this static.)
  105. */
  106. void * (*volatile ottery_memset_volatile_)(void *, int, size_t) = memset;
  107. void
  108. ottery_memclear_(void *mem, size_t len)
  109. {
  110. /* NOTE: whenever we change this, change test/test_memclear.c accordingly */
  111. ottery_memset_volatile_(mem, 0, len);
  112. }
  113. #ifndef OTTERY_NO_WIPE_STACK
  114. /* Chosen more or less arbitrarily */
  115. #define WIPE_STACK_LEN 512
  116. /**
  117. * Try to clear memory on the stack to clean up after our PRF. This can't
  118. * easily be done in standard C, so we're doing an ugly hack in hopes that it
  119. * actually helps.
  120. *
  121. * This should never be necessary in a correct program, but if your program is
  122. * doing something stupid like leaking uninitialized stack, it might keep an
  123. * attacker from exploiting that.
  124. **/
  125. static void
  126. ottery_wipe_stack_(void)
  127. {
  128. char buf[WIPE_STACK_LEN];
  129. ottery_memset_volatile_(buf, 0, sizeof(buf));
  130. }
  131. #else
  132. #define ottery_wipe_stack_() ((void)0)
  133. #endif
  134. int
  135. ottery_config_init(struct ottery_config *cfg)
  136. {
  137. cfg->impl = NULL;
  138. cfg->entropy_config.urandom_fname = NULL;
  139. cfg->entropy_config.urandom_fd = -1;
  140. cfg->entropy_config.urandom_fd_is_set = 0;
  141. cfg->entropy_config.disabled_sources = 0;
  142. cfg->entropy_config.weak_sources = 0;
  143. cfg->entropy_config.egd_sockaddr = NULL;
  144. cfg->entropy_config.egd_socklen = 0;
  145. cfg->entropy_config.allow_nondev_urandom = 0;
  146. return 0;
  147. }
  148. static const struct ottery_prf *
  149. ottery_get_impl(const char *impl)
  150. {
  151. int i;
  152. const struct ottery_prf *ALL_PRFS[] = {
  153. #ifdef HAVE_SIMD_CHACHA_2
  154. &ottery_prf_chacha20_krovetz_2_,
  155. &ottery_prf_chacha12_krovetz_2_,
  156. &ottery_prf_chacha8_krovetz_2_,
  157. #endif
  158. #ifdef HAVE_SIMD_CHACHA
  159. &ottery_prf_chacha20_krovetz_1_,
  160. &ottery_prf_chacha12_krovetz_1_,
  161. &ottery_prf_chacha8_krovetz_1_,
  162. #endif
  163. #ifdef BUILD_RSPAMD
  164. #if defined(__x86_64__) && defined(RSPAMD_HAS_TARGET_ATTR)
  165. &ottery_prf_aes_cryptobox_,
  166. #endif
  167. &ottery_prf_chacha20_cryptobox_,
  168. #endif
  169. &ottery_prf_chacha20_merged_,
  170. &ottery_prf_chacha12_merged_,
  171. &ottery_prf_chacha8_merged_,
  172. NULL,
  173. };
  174. const uint32_t cap = ottery_get_cpu_capabilities_();
  175. for (i = 0; ALL_PRFS[i]; ++i) {
  176. const struct ottery_prf *prf = ALL_PRFS[i];
  177. if ((prf->required_cpucap & cap) != prf->required_cpucap)
  178. continue;
  179. if (impl == NULL)
  180. return prf;
  181. if (!strcmp(impl, prf->name))
  182. return prf;
  183. if (!strcmp(impl, prf->impl))
  184. return prf;
  185. if (!strcmp(impl, prf->flav))
  186. return prf;
  187. }
  188. return NULL;
  189. }
  190. int
  191. ottery_config_force_implementation(struct ottery_config *cfg,
  192. const char *impl)
  193. {
  194. const struct ottery_prf *prf = ottery_get_impl(impl);
  195. if (prf) {
  196. cfg->impl = prf;
  197. return 0;
  198. }
  199. return OTTERY_ERR_INVALID_ARGUMENT;
  200. }
  201. void
  202. ottery_config_set_manual_prf_(struct ottery_config *cfg,
  203. const struct ottery_prf *prf)
  204. {
  205. cfg->impl = prf;
  206. }
  207. void
  208. ottery_config_set_urandom_device(struct ottery_config *cfg,
  209. const char *fname)
  210. {
  211. cfg->entropy_config.urandom_fname = fname;
  212. }
  213. void
  214. ottery_config_set_urandom_fd(struct ottery_config *cfg,
  215. int fd)
  216. {
  217. cfg->entropy_config.urandom_fd = fd;
  218. cfg->entropy_config.urandom_fd_is_set = (fd >= 0);
  219. }
  220. void
  221. ottery_config_set_egd_socket(struct ottery_config *cfg,
  222. const struct sockaddr *addr,
  223. int len)
  224. {
  225. cfg->entropy_config.egd_sockaddr = addr;
  226. cfg->entropy_config.egd_socklen = len;
  227. }
  228. void
  229. ottery_config_disable_entropy_sources(struct ottery_config *cfg,
  230. uint32_t disabled_sources)
  231. {
  232. cfg->entropy_config.disabled_sources =
  233. (disabled_sources & OTTERY_ENTROPY_ALL_SOURCES);
  234. }
  235. void
  236. ottery_config_mark_entropy_sources_weak(struct ottery_config *cfg,
  237. uint32_t disabled_sources)
  238. {
  239. cfg->entropy_config.weak_sources =
  240. (disabled_sources & OTTERY_ENTROPY_ALL_SOURCES);
  241. }
  242. /**
  243. * As ottery_st_nextblock_nolock(), but fill the entire block with
  244. * entropy, and don't try to rekey the state.
  245. */
  246. static void
  247. ottery_st_nextblock_nolock_norekey(struct ottery_state *st)
  248. {
  249. st->prf.generate(st->state, st->buffer, st->block_counter);
  250. ottery_wipe_stack_();
  251. ++st->block_counter;
  252. }
  253. /**
  254. * Generate (st->output_len) bytes of pseudorandom data from the PRF into
  255. * (st->buffer). Use the first st->prf.state_bytes of those bytes to replace
  256. * the PRF state and advance (st->pos) to point after them.
  257. *
  258. * This function does not acquire the lock on the state; use it within
  259. * another function that does.
  260. *
  261. * @param st The state to use when generating the block.
  262. */
  263. static void
  264. ottery_st_nextblock_nolock(struct ottery_state_nolock *st)
  265. {
  266. ottery_st_nextblock_nolock_norekey(st);
  267. st->prf.setup(st->state, st->buffer);
  268. CLEARBUF(st->buffer, st->prf.state_bytes);
  269. st->block_counter = 0;
  270. st->pos = st->prf.state_bytes;
  271. }
  272. /**
  273. * Initialize or reinitialize a PRNG state.
  274. *
  275. * @param st The state to initialize or reinitialize.
  276. * @param prf The configuration to use. (Ignored for reinit)
  277. * @return An OTTERY_ERR_* value (zero on success, nonzero on failure).
  278. */
  279. static int
  280. ottery_st_initialize(struct ottery_state *st,
  281. const struct ottery_config *config,
  282. int locked)
  283. {
  284. const struct ottery_prf *prf = NULL;
  285. struct ottery_config cfg_tmp;
  286. int err;
  287. /* We really need our state to be aligned. If it isn't, let's give an
  288. * error now, and not a crash when the SIMD instructions start to fail.
  289. */
  290. if (((uintptr_t)st) & 0xf)
  291. return OTTERY_ERR_STATE_ALIGNMENT;
  292. if (!config) {
  293. ottery_config_init(&cfg_tmp);
  294. config = &cfg_tmp;
  295. }
  296. prf = config->impl;
  297. if (!prf)
  298. prf = ottery_get_impl(NULL);
  299. memset(st, 0, sizeof(*st));
  300. if (locked) {
  301. /* Now set up the spinlock or mutex or hybrid thing. */
  302. if (INIT_LOCK(&st->mutex))
  303. return OTTERY_ERR_LOCK_INIT;
  304. }
  305. /* Check invariants for PRF, in case we wrote some bad code. */
  306. if ((prf->state_len > MAX_STATE_LEN) ||
  307. (prf->state_bytes > MAX_STATE_BYTES) ||
  308. (prf->state_bytes > prf->output_len) ||
  309. (prf->output_len > MAX_OUTPUT_LEN))
  310. return OTTERY_ERR_INTERNAL;
  311. /* Check whether some of our structure size assumptions are right. */
  312. if ((sizeof(struct ottery_state) > OTTERY_STATE_DUMMY_SIZE_) ||
  313. (sizeof(struct ottery_config) > OTTERY_CONFIG_DUMMY_SIZE_))
  314. return OTTERY_ERR_INTERNAL;
  315. memcpy(&st->entropy_config, &config->entropy_config,
  316. sizeof(struct ottery_entropy_config));
  317. /* Copy the PRF into place. */
  318. memcpy(&st->prf, prf, sizeof(*prf));
  319. if ((err = ottery_st_reseed(st)))
  320. return err;
  321. /* Set the magic number last, or else we might look like we succeeded
  322. * when we didn't */
  323. st->magic = MAGIC(st);
  324. st->pid = getpid();
  325. return 0;
  326. }
  327. static int
  328. ottery_st_reseed(struct ottery_state *st)
  329. {
  330. /* Now seed the PRF: Generate some random bytes from the OS, and use them
  331. * as whatever keys/nonces/whatever the PRF wants to have. */
  332. /* XXXX Add seed rather than starting from scratch? */
  333. int err;
  334. uint32_t flags=0;
  335. size_t buflen = ottery_get_entropy_bufsize_(st->prf.state_bytes);
  336. uint8_t *buf = alloca(buflen);
  337. if (!buf)
  338. return OTTERY_ERR_INIT_STRONG_RNG;
  339. if ((err = ottery_get_entropy_(&st->entropy_config, &st->entropy_state, 0,
  340. buf, st->prf.state_bytes,
  341. &buflen,
  342. &flags)))
  343. return err;
  344. if (buflen < st->prf.state_bytes)
  345. return OTTERY_ERR_ACCESS_STRONG_RNG;
  346. /* The first state_bytes bytes become the initial key. */
  347. st->prf.setup(st->state, buf);
  348. /* If there are more bytes, we mix them into the key with add_seed */
  349. if (buflen > st->prf.state_bytes)
  350. ottery_st_add_seed_impl(st,
  351. buf + st->prf.state_bytes,
  352. buflen - st->prf.state_bytes,
  353. 0,
  354. 0);
  355. ottery_memclear_(buf, buflen);
  356. st->last_entropy_flags = flags;
  357. st->entropy_src_flags = flags;
  358. /* Generate the first block of output. */
  359. st->block_counter = 0;
  360. ottery_st_nextblock_nolock(st);
  361. return 0;
  362. }
  363. int
  364. ottery_st_init(struct ottery_state *st, const struct ottery_config *cfg)
  365. {
  366. return ottery_st_initialize(st, cfg, 1);
  367. }
  368. int
  369. ottery_st_init_nolock(struct ottery_state_nolock *st,
  370. const struct ottery_config *cfg)
  371. {
  372. return ottery_st_initialize(st, cfg, 0);
  373. }
  374. static int
  375. ottery_st_add_seed_impl(struct ottery_state *st, const uint8_t *seed, size_t n, int locking, int check_magic)
  376. {
  377. #ifndef OTTERY_NO_INIT_CHECK
  378. if (check_magic && UNLIKELY(st->magic != MAGIC(st))) {
  379. ottery_fatal_error_(OTTERY_ERR_STATE_INIT);
  380. return OTTERY_ERR_STATE_INIT;
  381. }
  382. #endif
  383. /* If the user passed NULL, then we should reseed from the operating
  384. * system. */
  385. uint8_t *tmp_seed = NULL;
  386. size_t tmp_seed_len = 0;
  387. uint32_t flags = 0;
  388. if (!seed || !n) {
  389. int err;
  390. tmp_seed_len = ottery_get_entropy_bufsize_(st->prf.state_bytes);
  391. tmp_seed = alloca(tmp_seed_len);
  392. if (!tmp_seed)
  393. return OTTERY_ERR_INIT_STRONG_RNG;
  394. n = tmp_seed_len;
  395. if ((err = ottery_get_entropy_(&st->entropy_config, &st->entropy_state, 0,
  396. tmp_seed, st->prf.state_bytes,
  397. &n,
  398. &flags)))
  399. return err;
  400. if (n < st->prf.state_bytes)
  401. return OTTERY_ERR_ACCESS_STRONG_RNG;
  402. seed = tmp_seed;
  403. }
  404. if (locking)
  405. LOCK(st);
  406. /* The algorithm here is really easy. We grab a block of output from the
  407. * PRNG, that the first (state_bytes) bytes of that, XOR it with up to
  408. * (state_bytes) bytes of our new seed data, and use that to set our new
  409. * state. We do this over and over until we have no more seed data to add.
  410. */
  411. while (n) {
  412. unsigned i;
  413. size_t m = n > st->prf.state_bytes/2 ? st->prf.state_bytes/2 : n;
  414. ottery_st_nextblock_nolock_norekey(st);
  415. for (i = 0; i < m; ++i) {
  416. st->buffer[i] ^= seed[i];
  417. }
  418. st->prf.setup(st->state, st->buffer);
  419. st->block_counter = 0;
  420. n -= m;
  421. seed += m;
  422. }
  423. /* Now make sure that st->buffer is set up with the new state. */
  424. ottery_st_nextblock_nolock(st);
  425. st->entropy_src_flags |= flags;
  426. st->last_entropy_flags = flags;
  427. if (locking)
  428. UNLOCK(st);
  429. /* If we used stack-allocated seed material, wipe it. */
  430. if (tmp_seed)
  431. ottery_memclear_(tmp_seed, tmp_seed_len);
  432. return 0;
  433. }
  434. int
  435. ottery_st_add_seed(struct ottery_state *st, const uint8_t *seed, size_t n)
  436. {
  437. return ottery_st_add_seed_impl(st, seed, n, 1, 1);
  438. }
  439. int
  440. ottery_st_add_seed_nolock(struct ottery_state_nolock *st, const uint8_t *seed, size_t n)
  441. {
  442. return ottery_st_add_seed_impl(st, seed, n, 0, 1);
  443. }
  444. void
  445. ottery_st_wipe(struct ottery_state *st)
  446. {
  447. DESTROY_LOCK(&st->mutex);
  448. ottery_st_wipe_nolock(st);
  449. }
  450. void
  451. ottery_st_wipe_nolock(struct ottery_state_nolock *st)
  452. {
  453. ottery_memclear_(st, sizeof(struct ottery_state));
  454. }
  455. void
  456. ottery_st_prevent_backtracking_nolock(struct ottery_state_nolock *st)
  457. {
  458. #ifdef OTTERY_NO_CLEAR_AFTER_YIELD
  459. memset(st->buffer, 0, st->pos);
  460. #else
  461. (void)st;
  462. #endif
  463. }
  464. void
  465. ottery_st_prevent_backtracking(struct ottery_state *st)
  466. {
  467. LOCK(st);
  468. ottery_st_prevent_backtracking_nolock(st);
  469. UNLOCK(st);
  470. }
  471. /** Function that's invoked on a fatal error. See
  472. * ottery_set_fatal_handler() for more information. */
  473. static void (*ottery_fatal_handler)(int) = NULL;
  474. void
  475. ottery_fatal_error_(int error)
  476. {
  477. if (ottery_fatal_handler)
  478. ottery_fatal_handler(error);
  479. else
  480. abort();
  481. }
  482. void
  483. ottery_set_fatal_handler(void (*fn)(int))
  484. {
  485. ottery_fatal_handler = fn;
  486. }
  487. /**
  488. * Shared prologue for functions generating random bytes from an ottery_state.
  489. * Make sure that the state is initialized.
  490. */
  491. static inline int
  492. ottery_st_rand_check_init(struct ottery_state *st)
  493. {
  494. #ifndef OTTERY_NO_INIT_CHECK
  495. if (UNLIKELY(st->magic != MAGIC(st))) {
  496. ottery_fatal_error_(OTTERY_ERR_STATE_INIT);
  497. return -1;
  498. }
  499. #else
  500. (void)st;
  501. #endif
  502. return 0;
  503. }
  504. /* XXXX */
  505. static inline int
  506. ottery_st_rand_check_pid(struct ottery_state *st)
  507. {
  508. #ifndef OTTERY_NO_PID_CHECK
  509. if (UNLIKELY(st->pid != getpid())) {
  510. int err;
  511. if ((err = ottery_st_reseed(st))) {
  512. ottery_fatal_error_(OTTERY_ERR_FLAG_POSTFORK_RESEED|err);
  513. return -1;
  514. }
  515. st->pid = getpid();
  516. }
  517. #else
  518. (void) st;
  519. #endif
  520. return 0;
  521. }
  522. static inline int
  523. ottery_st_rand_lock_and_check(struct ottery_state *st)
  524. {
  525. if (ottery_st_rand_check_init(st))
  526. return -1;
  527. LOCK(st);
  528. if (ottery_st_rand_check_pid(st)) {
  529. UNLOCK(st);
  530. return -1;
  531. }
  532. return 0;
  533. }
  534. static inline int
  535. ottery_st_rand_check_nolock(struct ottery_state_nolock *st)
  536. {
  537. if (ottery_st_rand_check_init(st))
  538. return -1;
  539. if (ottery_st_rand_check_pid(st))
  540. return -1;
  541. return 0;
  542. }
  543. /**
  544. * Generate a small-ish number of bytes from an ottery_state, using
  545. * buffered data. If there is insufficient data in the buffer right now,
  546. * use what we have, and generate more.
  547. *
  548. * @param st The state to use.
  549. * @param out A location to write to.
  550. * @param n The number of bytes to write. Must not be greater than
  551. * st->prf.output_len*2 - st->prf.state_bytes - st->pos - 1.
  552. */
  553. static inline void
  554. ottery_st_rand_bytes_from_buf(struct ottery_state *st, uint8_t *out,
  555. size_t n)
  556. {
  557. if (n + st->pos < st->prf.output_len) {
  558. memcpy(out, st->buffer+st->pos, n);
  559. CLEARBUF(st->buffer+st->pos, n);
  560. st->pos += n;
  561. } else {
  562. unsigned cpy = st->prf.output_len - st->pos;
  563. memcpy(out, st->buffer+st->pos, cpy);
  564. n -= cpy;
  565. out += cpy;
  566. ottery_st_nextblock_nolock(st);
  567. memcpy(out, st->buffer+st->pos, n);
  568. CLEARBUF(st->buffer, n);
  569. st->pos += n;
  570. assert(st->pos < st->prf.output_len);
  571. }
  572. }
  573. static void
  574. ottery_st_rand_bytes_impl(struct ottery_state *st, void *out_,
  575. size_t n)
  576. {
  577. uint8_t *out = out_;
  578. size_t cpy;
  579. if (n + st->pos < st->prf.output_len * 2 - st->prf.state_bytes - 1) {
  580. /* Fulfill it all from the buffer simply if possible. */
  581. ottery_st_rand_bytes_from_buf(st, out, n);
  582. return;
  583. }
  584. /* Okay. That's not going to happen. Well, take what we can... */
  585. cpy = st->prf.output_len - st->pos;
  586. memcpy(out, st->buffer + st->pos, cpy);
  587. out += cpy;
  588. n -= cpy;
  589. /* Then take whole blocks so long as we need them, without stirring... */
  590. while (n >= st->prf.output_len) {
  591. /* (We could save a memcpy here if we generated the block directly at out
  592. * rather than doing the memcpy here. First we'd need to make sure that we
  593. * had gotten the block aligned to a 16-byte boundary, though, and we'd
  594. * have some other tricky bookkeeping to do. Let's call this good enough
  595. * for now.) */
  596. ottery_st_nextblock_nolock_norekey(st);
  597. memcpy(out, st->buffer, st->prf.output_len);
  598. out += st->prf.output_len;
  599. n -= st->prf.output_len;
  600. }
  601. /* Then stir for the last part. */
  602. ottery_st_nextblock_nolock(st);
  603. ottery_st_rand_bytes_from_buf(st, out, n);
  604. }
  605. void
  606. ottery_st_rand_bytes(struct ottery_state *st, void *out_, size_t n)
  607. {
  608. if (ottery_st_rand_lock_and_check(st))
  609. return;
  610. ottery_st_rand_bytes_impl(st, out_, n);
  611. UNLOCK(st);
  612. }
  613. void
  614. ottery_st_rand_bytes_nolock(struct ottery_state_nolock *st, void *out_, size_t n)
  615. {
  616. if (ottery_st_rand_check_nolock(st))
  617. return;
  618. ottery_st_rand_bytes_impl(st, out_, n);
  619. }
  620. /**
  621. * Assign an integer type from bytes at a possibly unaligned pointer.
  622. *
  623. * @param type the type of integer to assign.
  624. * @param r the integer lvalue to write to.
  625. * @param p a pointer to the bytes to read from.
  626. **/
  627. #define INT_ASSIGN_PTR(type, r, p) do { \
  628. memcpy(&r, p, sizeof(type)); \
  629. } while (0)
  630. /**
  631. * Shared code for implementing rand_unsigned() and rand_uint64().
  632. *
  633. * @param st The state to use.
  634. * @param inttype The type of integer to generate.
  635. **/
  636. #define OTTERY_RETURN_RAND_INTTYPE_IMPL(st, inttype, unlock) do { \
  637. inttype result; \
  638. if (sizeof(inttype) + (st)->pos <= (st)->prf.output_len) { \
  639. INT_ASSIGN_PTR(inttype, result, (st)->buffer + (st)->pos); \
  640. CLEARBUF((st)->buffer + (st)->pos, sizeof(inttype)); \
  641. (st)->pos += sizeof(inttype); \
  642. if (st->pos == (st)->prf.output_len) { \
  643. ottery_st_nextblock_nolock(st); \
  644. } \
  645. } else { \
  646. /* Our handling of this case here is significantly simpler */ \
  647. /* than that of ottery_st_rand_bytes_from_buf, at the expense */ \
  648. /* of wasting up to sizeof(inttype)-1 bytes. Since inttype */ \
  649. /* is at most 8 bytes long, that's not such a big deal. */ \
  650. ottery_st_nextblock_nolock(st); \
  651. INT_ASSIGN_PTR(inttype, result, (st)->buffer + (st)->pos); \
  652. CLEARBUF((st)->buffer, sizeof(inttype)); \
  653. (st)->pos += sizeof(inttype); \
  654. } \
  655. unlock; \
  656. return result; \
  657. } while (0)
  658. #define OTTERY_RETURN_RAND_INTTYPE(st, inttype) do { \
  659. if (ottery_st_rand_lock_and_check(st)) \
  660. return (inttype)0; \
  661. OTTERY_RETURN_RAND_INTTYPE_IMPL(st, inttype, UNLOCK(st)); \
  662. } while (0)
  663. #define OTTERY_RETURN_RAND_INTTYPE_NOLOCK(st, inttype) do { \
  664. if (ottery_st_rand_check_nolock(st)) \
  665. return (inttype)0; \
  666. OTTERY_RETURN_RAND_INTTYPE_IMPL(st, inttype, ); \
  667. } while (0)
  668. unsigned
  669. ottery_st_rand_unsigned(struct ottery_state *st)
  670. {
  671. OTTERY_RETURN_RAND_INTTYPE(st, unsigned);
  672. }
  673. unsigned
  674. ottery_st_rand_unsigned_nolock(struct ottery_state_nolock *st)
  675. {
  676. OTTERY_RETURN_RAND_INTTYPE_NOLOCK(st, unsigned);
  677. }
  678. uint32_t
  679. ottery_st_rand_uint32(struct ottery_state *st)
  680. {
  681. OTTERY_RETURN_RAND_INTTYPE(st, uint32_t);
  682. }
  683. uint32_t
  684. ottery_st_rand_uint32_nolock(struct ottery_state_nolock *st)
  685. {
  686. OTTERY_RETURN_RAND_INTTYPE_NOLOCK(st, uint32_t);
  687. }
  688. uint64_t
  689. ottery_st_rand_uint64(struct ottery_state *st)
  690. {
  691. OTTERY_RETURN_RAND_INTTYPE(st, uint64_t);
  692. }
  693. uint64_t
  694. ottery_st_rand_uint64_nolock(struct ottery_state_nolock *st)
  695. {
  696. OTTERY_RETURN_RAND_INTTYPE_NOLOCK(st, uint64_t);
  697. }
  698. unsigned
  699. ottery_st_rand_range_nolock(struct ottery_state_nolock *st, unsigned upper)
  700. {
  701. unsigned lim = upper+1;
  702. unsigned divisor = lim ? (UINT_MAX / lim) : 1;
  703. unsigned n;
  704. do {
  705. n = (ottery_st_rand_unsigned_nolock(st) / divisor);
  706. } while (n > upper);
  707. return n;
  708. }
  709. uint64_t
  710. ottery_st_rand_range64_nolock(struct ottery_state_nolock *st, uint64_t upper)
  711. {
  712. uint64_t lim = upper+1;
  713. uint64_t divisor = lim ? (UINT64_MAX / lim) : 1;
  714. uint64_t n;
  715. do {
  716. n = (ottery_st_rand_uint64_nolock(st) / divisor);
  717. } while (n > upper);
  718. return n;
  719. }
  720. unsigned
  721. ottery_st_rand_range(struct ottery_state *state, unsigned upper)
  722. {
  723. unsigned n;
  724. if (ottery_st_rand_check_init(state))
  725. return 0;
  726. LOCK(state);
  727. n = ottery_st_rand_range_nolock(state, upper);
  728. UNLOCK(state);
  729. return n;
  730. }
  731. uint64_t
  732. ottery_st_rand_range64(struct ottery_state *state, uint64_t upper)
  733. {
  734. uint64_t n;
  735. if (ottery_st_rand_check_init(state))
  736. return 0;
  737. LOCK(state);
  738. n = ottery_st_rand_range64_nolock(state, upper);
  739. UNLOCK(state);
  740. return n;
  741. }