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 22KB

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