fortuna.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. * fortuna.c
  3. * Fortuna-like PRNG.
  4. *
  5. * Copyright (c) 2005 Marko Kreen
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  18. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  21. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  23. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  24. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  25. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  26. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  27. * SUCH DAMAGE.
  28. *
  29. * contrib/pgcrypto/fortuna.c
  30. */
  31. #include <u.h>
  32. #include <rijndael.h>
  33. #include <sha2.h>
  34. #include "../port/lib.h"
  35. #include "mem.h"
  36. #include "dat.h"
  37. #include "fns.h"
  38. /*
  39. * Why Fortuna-like: There does not seem to be any definitive reference
  40. * on Fortuna in the net. Instead this implementation is based on
  41. * following references:
  42. *
  43. * http://en.wikipedia.org/wiki/Fortuna_(PRNG)
  44. * - Wikipedia article
  45. * http://jlcooke.ca/random/
  46. * - Jean-Luc Cooke Fortuna-based /dev/random driver for Linux.
  47. */
  48. /*
  49. * There is some confusion about whether and how to carry forward
  50. * the state of the pools. Seems like original Fortuna does not
  51. * do it, resetting hash after each request. I guess expecting
  52. * feeding to happen more often that requesting. This is absolutely
  53. * unsuitable for pgcrypto, as nothing asynchronous happens here.
  54. *
  55. * J.L. Cooke fixed this by feeding previous hash to new re-initialized
  56. * hash context.
  57. *
  58. * Fortuna predecessor Yarrow requires ability to query intermediate
  59. * 'final result' from hash, without affecting it.
  60. *
  61. * This implementation uses the Yarrow method - asking intermediate
  62. * results, but continuing with old state.
  63. */
  64. /*
  65. * Algorithm parameters
  66. */
  67. /*
  68. * How many pools.
  69. *
  70. * Original Fortuna uses 32 pools, that means 32'th pool is
  71. * used not earlier than in 13th year. This is a waste in
  72. * pgcrypto, as we have very low-frequancy seeding. Here
  73. * is preferable to have all entropy usable in reasonable time.
  74. *
  75. * With 23 pools, 23th pool is used after 9 days which seems
  76. * more sane.
  77. *
  78. * In our case the minimal cycle time would be bit longer
  79. * than the system-randomness feeding frequency.
  80. */
  81. enum{
  82. numPools = 23,
  83. /* in microseconds */
  84. reseedInterval = 100000, /* 0.1 sec */
  85. /* for one big request, reseed after this many bytes */
  86. reseedBytes = (1024*1024),
  87. /*
  88. * Skip reseed if pool 0 has less than this many
  89. * bytes added since last reseed.
  90. */
  91. pool0Fill = (256/8),
  92. /*
  93. * Algorithm constants
  94. */
  95. /* Both cipher key size and hash result size */
  96. block = 32,
  97. /* cipher block size */
  98. ciphBlock = 16
  99. };
  100. /* for internal wrappers */
  101. typedef SHA256Ctx mdCtx;
  102. typedef rijndaelCtx ciphCtx;
  103. struct FState
  104. {
  105. uint8_t counter[ciphBlock];
  106. uint8_t result[ciphBlock];
  107. uint8_t key[block];
  108. mdCtx pool[numPools];
  109. ciphCtx ciph;
  110. unsigned reseedCount;
  111. int32_t lastReseedTime;
  112. unsigned pool0Bytes;
  113. unsigned rndPos;
  114. int tricksDone;
  115. };
  116. typedef struct FState FState;
  117. /*
  118. * Use our own wrappers here.
  119. * - Need to get intermediate result from digest, without affecting it.
  120. * - Need re-set key on a cipher context.
  121. * - Algorithms are guaranteed to exist.
  122. * - No memory allocations.
  123. */
  124. static void
  125. ciph_init(ciphCtx * ctx, const uint8_t *key, int klen)
  126. {
  127. rijndael_set_key(ctx, (const uint32_t *) key, klen, 1);
  128. }
  129. static void
  130. ciph_encrypt(ciphCtx * ctx, const uint8_t *in, uint8_t *out)
  131. {
  132. rijndael_encrypt(ctx, (const uint32_t *) in, (uint32_t *) out);
  133. }
  134. static void
  135. md_init(mdCtx * ctx)
  136. {
  137. SHA256_Init(ctx);
  138. }
  139. static void
  140. md_update(mdCtx * ctx, const uint8_t *data, int len)
  141. {
  142. SHA256_Update(ctx, data, len);
  143. }
  144. static void
  145. md_result(mdCtx * ctx, uint8_t *dst)
  146. {
  147. SHA256Ctx tmp;
  148. memmove(&tmp, ctx, sizeof(*ctx));
  149. SHA256_Final(dst, &tmp);
  150. memset(&tmp, 0, sizeof(tmp));
  151. }
  152. /*
  153. * initialize state
  154. */
  155. static void
  156. init_state(FState *st)
  157. {
  158. int i;
  159. memset(st, 0, sizeof(*st));
  160. for (i = 0; i < numPools; i++)
  161. md_init(&st->pool[i]);
  162. }
  163. /*
  164. * Endianess does not matter.
  165. * It just needs to change without repeating.
  166. */
  167. static void
  168. inc_counter(FState *st)
  169. {
  170. uint32_t *val = (uint32_t *) st->counter;
  171. if (++val[0])
  172. return;
  173. if (++val[1])
  174. return;
  175. if (++val[2])
  176. return;
  177. ++val[3];
  178. }
  179. /*
  180. * This is called 'cipher in counter mode'.
  181. */
  182. static void
  183. encrypt_counter(FState *st, uint8_t *dst)
  184. {
  185. ciph_encrypt(&st->ciph, st->counter, dst);
  186. inc_counter(st);
  187. }
  188. /*
  189. * The time between reseed must be at least reseedInterval
  190. * microseconds.
  191. */
  192. static int
  193. enough_time_passed(FState *st)
  194. {
  195. int ok;
  196. int32_t now;
  197. int32_t last = st->lastReseedTime;
  198. now = seconds();
  199. /* check how much time has passed */
  200. ok = 0;
  201. if (now - last >= reseedInterval)
  202. ok = 1;
  203. /* reseed will happen, update lastReseedTime */
  204. if (ok)
  205. st->lastReseedTime=now;
  206. return ok;
  207. }
  208. /*
  209. * generate new key from all the pools
  210. */
  211. static void
  212. reseed(FState *st)
  213. {
  214. unsigned k;
  215. unsigned n;
  216. mdCtx key_md;
  217. uint8_t buf[block];
  218. /* set pool as empty */
  219. st->pool0Bytes = 0;
  220. /*
  221. * Both #0 and #1 reseed would use only pool 0. Just skip #0 then.
  222. */
  223. n = ++st->reseedCount;
  224. /*
  225. * The goal: use k-th pool only 1/(2^k) of the time.
  226. */
  227. md_init(&key_md);
  228. for (k = 0; k < numPools; k++)
  229. {
  230. md_result(&st->pool[k], buf);
  231. md_update(&key_md, buf, block);
  232. if (n & 1 || !n)
  233. break;
  234. n >>= 1;
  235. }
  236. /* add old key into mix too */
  237. md_update(&key_md, st->key, block);
  238. /* now we have new key */
  239. md_result(&key_md, st->key);
  240. /* use new key */
  241. ciph_init(&st->ciph, st->key, block);
  242. memset(&key_md, 0, sizeof(key_md));
  243. memset(buf, 0, block);
  244. }
  245. /*
  246. * Pick a random pool. This uses key bytes as random source.
  247. */
  248. static unsigned
  249. get_rand_pool(FState *st)
  250. {
  251. unsigned rnd;
  252. /*
  253. * This slightly prefers lower pools - thats OK.
  254. */
  255. rnd = st->key[st->rndPos] % numPools;
  256. st->rndPos++;
  257. if (st->rndPos >= block)
  258. st->rndPos = 0;
  259. return rnd;
  260. }
  261. /*
  262. * update pools
  263. */
  264. static void
  265. add_entropy(FState *st, const uint8_t *data, unsigned len)
  266. {
  267. unsigned pos;
  268. uint8_t hash[block];
  269. mdCtx md;
  270. /* hash given data */
  271. md_init(&md);
  272. md_update(&md, data, len);
  273. md_result(&md, hash);
  274. /*
  275. * Make sure the pool 0 is initialized, then update randomly.
  276. */
  277. if (st->reseedCount == 0)
  278. pos = 0;
  279. else
  280. pos = get_rand_pool(st);
  281. md_update(&st->pool[pos], hash, block);
  282. if (pos == 0)
  283. st->pool0Bytes += len;
  284. memset(hash, 0, block);
  285. memset(&md, 0, sizeof(md));
  286. }
  287. /*
  288. * Just take 2 next blocks as new key
  289. */
  290. static void
  291. rekey(FState *st)
  292. {
  293. encrypt_counter(st, st->key);
  294. encrypt_counter(st, st->key + ciphBlock);
  295. ciph_init(&st->ciph, st->key, block);
  296. }
  297. /*
  298. * Hide public constants. (counter, pools > 0)
  299. *
  300. * This can also be viewed as spreading the startup
  301. * entropy over all of the components.
  302. */
  303. static void
  304. startup_tricks(FState *st)
  305. {
  306. int i;
  307. uint8_t buf[block];
  308. /* Use next block as counter. */
  309. encrypt_counter(st, st->counter);
  310. /* Now shuffle pools, excluding #0 */
  311. for (i = 1; i < numPools; i++)
  312. {
  313. encrypt_counter(st, buf);
  314. encrypt_counter(st, buf + ciphBlock);
  315. md_update(&st->pool[i], buf, block);
  316. }
  317. memset(buf, 0, block);
  318. /* Hide the key. */
  319. rekey(st);
  320. /* This can be done only once. */
  321. st->tricksDone = 1;
  322. }
  323. static void
  324. extract_data(FState *st, unsigned count, uint8_t *dst)
  325. {
  326. unsigned n;
  327. unsigned block_nr = 0;
  328. /* Should we reseed? */
  329. if (st->pool0Bytes >= pool0Fill || st->reseedCount == 0)
  330. if (enough_time_passed(st))
  331. reseed(st);
  332. /* Do some randomization on first call */
  333. if (!st->tricksDone)
  334. startup_tricks(st);
  335. while (count > 0)
  336. {
  337. /* produce bytes */
  338. encrypt_counter(st, st->result);
  339. /* copy result */
  340. if (count > ciphBlock)
  341. n = ciphBlock;
  342. else
  343. n = count;
  344. memmove(dst, st->result, n);
  345. dst += n;
  346. count -= n;
  347. /* must not give out too many bytes with one key */
  348. block_nr++;
  349. if (block_nr > (reseedBytes / ciphBlock))
  350. {
  351. rekey(st);
  352. block_nr = 0;
  353. }
  354. }
  355. /* Set new key for next request. */
  356. rekey(st);
  357. }
  358. static FState mainState;
  359. static int initDone = 0;
  360. static void init(){
  361. init_state(&mainState);
  362. initDone = 1;
  363. }
  364. /*
  365. * public interface
  366. */
  367. void
  368. fortuna_add_entropy(const uint8_t *data, unsigned len)
  369. {
  370. if (!initDone)
  371. {
  372. init();
  373. }
  374. if (!data || !len)
  375. return;
  376. add_entropy(&mainState, data, len);
  377. }
  378. void
  379. fortuna_get_bytes(unsigned len, uint8_t *dst)
  380. {
  381. if (!initDone)
  382. {
  383. init();
  384. }
  385. if (!dst || !len)
  386. return;
  387. extract_data(&mainState, len, dst);
  388. }