Random.c 10 KB

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