1
0

Random.c 9.5 KB

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