Random.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/random/Random.h"
  16. #include "crypto/random/seed/RandomSeed.h"
  17. #include "crypto/random/seed/SystemRandomSeed.h"
  18. #include "memory/Allocator.h"
  19. #include "util/Bits.h"
  20. #include "util/Assert.h"
  21. #include "util/Base32.h"
  22. #include "util/Identity.h"
  23. #include <crypto_hash_sha256.h>
  24. #include <crypto_stream_salsa20.h>
  25. /**
  26. * cjdns random generator:
  27. * It is with great apprehension that I have decided to go forward with this random generator.
  28. * Sadly there doesn't exist any plain-and-simple random generation library for C without
  29. * bundling libevent, openssl or some other megalyth.
  30. *
  31. * Additionally most random generators use a feedback loop which is difficult to validate as
  32. * it has a period which is not immedietly obvious by looking at it. Additionally, this
  33. * feedback loop design leads to issues like:
  34. * http://www.openssl.org/news/secadv_prng.txt
  35. *
  36. * How this random generator works:
  37. * 1. All available random sources such as dev/urandom and sysctl(RANDOM_UUID) are combined
  38. * with a rolling SHA-512 hash, the result is placed in the Random_SeedGen union.
  39. *
  40. * 2. Random_SeedGen is SHA-256 hashed into Random.tempSeed
  41. *
  42. * 3. Random numbers are generated by running salsa20 with Random.tempSeed as the key, and
  43. * Random.nonce 64 bit counter which is incremented each run, never reset, and assumed
  44. * never to wrap.
  45. *
  46. * Adding entropy to the generator is as follows:
  47. * Random_addRandom() adds a sample of randomness by rotating and XORing it into
  48. * Random_SeedGen.collectedEntropy.
  49. * Every 256 calls to Random_addRandom(), Random_SeedGen is again hashed into Random.tempSeed.
  50. * Note that Random.nonce is *not* reset ever during the operation of the generator because
  51. * otherwise, 512 successive calls to Random_addRandom() with the same input would cause the
  52. * random generator to repeat.
  53. *
  54. *
  55. * State-compromize extension:
  56. * It is acknoliged that a compromize of the generator's internal state will result in the
  57. * attacker knowing every output which has been and will be generated or with the current
  58. * tempSeed. After a further 256 calls to Random_addRandom(), the generator should recover.
  59. *
  60. * While using a feedback loop with a one-way hash function to frustrate backtracking seems
  61. * enticing, it stands to reason that the only way a hash function can be one-way is by
  62. * destroying entropy, destruction of entropy in a feedback system could lead to an oscillation
  63. * effect when it becomes entropy starved. Though this issue does not seem to have been
  64. * exploited in other prngs, proving that it cannot be exploited is beyond my abilities and the
  65. * devil you know is better than the devil you don't.
  66. *
  67. *
  68. * Iterative Guessing:
  69. * This generator only introduces the entropy given by Random_addRandom() once every 256 calls.
  70. * Assuming each call introduces at least 1 bit of good entropy, iterative guessing requires
  71. * guessing a 256 bit value for each iteration.
  72. *
  73. *
  74. * Input based Attacks:
  75. * The generator is as conservitive as possible about the entropy provided in calls to
  76. * Random_addRandom(), valuing each at 1 bit of entropy. Since the number is rotated and XORd
  77. * into collectedEntropy, some calls with 0 bits of entropy can be smoothed over by other calls
  78. * with > 1 bit of entropy. If Random_addRandom() is called arbitrarily many times with 0 bits
  79. * of entropy, since the inputs are XORd into collectedEntropy the entropy level of
  80. * collectedEntropy will remain unchanged.
  81. *
  82. * Even if the attacker is able to gather information from the generator's output and craft
  83. * inputs to Random_addRandom() which *decrease* the entropy in collectedEntropy, this will not
  84. * decrease the performance of the generator itself because the 256 bit Random_SeedGen.seed
  85. * is seeded with the primary seed meterial (eg dev/urandom) and never altered for duration of
  86. * the generator's operation.
  87. */
  88. /** How many bytes to buffer so requests for a small amount of random do not invoke salsa20. */
  89. #define BUFFSIZE 128
  90. /** The key material which is used to generate the temporary seed. */
  91. union Random_SeedGen
  92. {
  93. struct {
  94. /**
  95. * Read directly from the seed supplier (dev/urandom etc.),
  96. * same for the whole run of the generator.
  97. */
  98. uint64_t seed[4];
  99. /**
  100. * Initialized by the seed supplier
  101. * then XORd with the input given to Random_addRandom().
  102. */
  103. uint32_t collectedEntropy[8];
  104. } elements;
  105. /** Used to generate tempSeed. */
  106. uint64_t buff[8];
  107. };
  108. struct Random
  109. {
  110. /** The random seed which is used to generate random numbers. */
  111. uint64_t tempSeed[4];
  112. /** Incremented every call to salsa20, never reset. */
  113. uint64_t nonce;
  114. /** buffer of random generated in the last rand cycle. */
  115. uint8_t buff[BUFFSIZE];
  116. /** the next number to read out of buff. */
  117. int nextByte;
  118. /** A counter which Random_addRandom() uses to rotate the random input. */
  119. int addRandomCounter;
  120. /** The seed generator for generating new temporary random seeds. */
  121. union Random_SeedGen* seedGen;
  122. /** The collector for getting the original permanent random seed from the operating system. */
  123. struct RandomSeed* seed;
  124. Identity
  125. };
  126. /**
  127. * Add a random number to the entropy pool.
  128. * 1 bit of entropy is extracted from each call to addRandom(), every 256 calls
  129. * this function will generate a new temporary seed using the permanent seed and
  130. * the collected entropy.
  131. *
  132. * Worst case scenario, Random_addRandom() is completely broken, the original
  133. * seed is still used and the nonce is never reset so the only loss is forward secrecy.
  134. */
  135. void Random_addRandom(struct Random* rand, uint32_t randomNumber)
  136. {
  137. Identity_check(rand);
  138. #define rotl(a,b) (((a) << (b)) | ((a) >> (31 - (b))))
  139. rand->seedGen->elements.collectedEntropy[rand->addRandomCounter % 8] ^=
  140. rotl(randomNumber, rand->addRandomCounter / 8);
  141. if (++rand->addRandomCounter >= 256) {
  142. crypto_hash_sha256((uint8_t*)rand->tempSeed,
  143. (uint8_t*)rand->seedGen->buff,
  144. sizeof(union Random_SeedGen));
  145. rand->addRandomCounter = 0;
  146. }
  147. }
  148. static void stir(struct Random* rand)
  149. {
  150. crypto_stream_salsa20_xor((uint8_t*)rand->buff,
  151. (uint8_t*)rand->buff,
  152. BUFFSIZE,
  153. (uint8_t*)&rand->nonce,
  154. (uint8_t*)rand->tempSeed);
  155. rand->nonce++;
  156. rand->nextByte = 0;
  157. }
  158. static uintptr_t randomCopy(struct Random* rand, uint8_t* location, uint64_t count)
  159. {
  160. uintptr_t num = (uintptr_t) count;
  161. if (num > (uintptr_t)(BUFFSIZE - rand->nextByte)) {
  162. num = (BUFFSIZE - rand->nextByte);
  163. }
  164. Bits_memcpy(location, &rand->buff[rand->nextByte], num);
  165. rand->nextByte += num;
  166. return num;
  167. }
  168. void Random_bytes(struct Random* rand, uint8_t* location, uint64_t count)
  169. {
  170. Identity_check(rand);
  171. if (count > BUFFSIZE) {
  172. // big request, don't buffer it.
  173. crypto_stream_salsa20_xor((uint8_t*)location,
  174. (uint8_t*)location,
  175. count,
  176. (uint8_t*)&rand->nonce,
  177. (uint8_t*)rand->tempSeed);
  178. rand->nonce++;
  179. return;
  180. }
  181. for (;;) {
  182. uintptr_t sz = randomCopy(rand, location, count);
  183. location += sz;
  184. count -= sz;
  185. if (count == 0) {
  186. return;
  187. }
  188. stir(rand);
  189. }
  190. }
  191. void Random_base32(struct Random* rand, uint8_t* output, uint32_t length)
  192. {
  193. Identity_check(rand);
  194. uint64_t index = 0;
  195. for (;;) {
  196. uint8_t bin[16];
  197. Random_bytes(rand, bin, 16);
  198. int ret = Base32_encode(&output[index], length - index, (uint8_t*)bin, 16);
  199. if (ret == Base32_TOO_BIG || index + ret == length) {
  200. break;
  201. }
  202. index += ret;
  203. }
  204. output[length - 1] = '\0';
  205. }
  206. struct Random* Random_newWithSeed(struct Allocator* alloc,
  207. struct Log* logger,
  208. struct RandomSeed* seed,
  209. struct Except* eh)
  210. {
  211. union Random_SeedGen* seedGen = Allocator_calloc(alloc, sizeof(union Random_SeedGen), 1);
  212. if (RandomSeed_get(seed, seedGen->buff)) {
  213. Except_throw(eh, "Unable to initialize secure random number generator");
  214. }
  215. struct Random* rand = Allocator_calloc(alloc, sizeof(struct Random), 1);
  216. rand->seedGen = seedGen;
  217. rand->seed = seed;
  218. rand->nextByte = BUFFSIZE;
  219. Identity_set(rand);
  220. rand->addRandomCounter = 255;
  221. Random_addRandom(rand, 0);
  222. stir(rand);
  223. return rand;
  224. }
  225. struct Random* Random_new(struct Allocator* alloc, struct Log* logger, struct Except* eh)
  226. {
  227. struct RandomSeed* rs = SystemRandomSeed_new(NULL, 0, logger, alloc);
  228. return Random_newWithSeed(alloc, logger, rs, eh);
  229. }