dbrandom.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * Dropbear - a SSH2 server
  3. *
  4. * Copyright (c) 2002,2003 Matt Johnston
  5. * All rights reserved.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE. */
  24. #include "includes.h"
  25. #include "buffer.h"
  26. #include "dbutil.h"
  27. #include "bignum.h"
  28. #include "dbrandom.h"
  29. #include "runopts.h"
  30. /* this is used to generate unique output from the same hashpool */
  31. static uint32_t counter = 0;
  32. /* the max value for the counter, so it won't integer overflow */
  33. #define MAX_COUNTER (1<<30)
  34. static unsigned char hashpool[SHA256_HASH_SIZE] = {0};
  35. static int donerandinit = 0;
  36. #define INIT_SEED_SIZE 32 /* 256 bits */
  37. /* The basic setup is we read some data from /dev/(u)random or prngd and hash it
  38. * into hashpool. To read data, we hash together current hashpool contents,
  39. * and a counter. We feed more data in by hashing the current pool and new
  40. * data into the pool.
  41. *
  42. * It is important to ensure that counter doesn't wrap around before we
  43. * feed in new entropy.
  44. *
  45. */
  46. /* Pass wantlen=0 to hash an entire file */
  47. static int
  48. process_file(hash_state *hs, const char *filename,
  49. unsigned int wantlen, int prngd) {
  50. int readfd = -1;
  51. unsigned int readcount;
  52. int ret = DROPBEAR_FAILURE;
  53. if (prngd) {
  54. #if DROPBEAR_USE_PRNGD
  55. readfd = connect_unix(filename);
  56. #endif
  57. } else {
  58. readfd = open(filename, O_RDONLY);
  59. }
  60. if (readfd < 0) {
  61. goto out;
  62. }
  63. readcount = 0;
  64. while (wantlen == 0 || readcount < wantlen) {
  65. int readlen, wantread;
  66. unsigned char readbuf[4096];
  67. if (wantlen == 0) {
  68. wantread = sizeof(readbuf);
  69. } else {
  70. wantread = MIN(sizeof(readbuf), wantlen-readcount);
  71. }
  72. #if DROPBEAR_USE_PRNGD
  73. if (prngd) {
  74. char egdcmd[2];
  75. egdcmd[0] = 0x02; /* blocking read */
  76. egdcmd[1] = (unsigned char)wantread;
  77. if (write(readfd, egdcmd, 2) < 0) {
  78. dropbear_exit("Can't send command to egd");
  79. }
  80. }
  81. #endif
  82. readlen = read(readfd, readbuf, wantread);
  83. if (readlen <= 0) {
  84. if (readlen < 0 && errno == EINTR) {
  85. continue;
  86. }
  87. if (readlen == 0 && wantlen == 0) {
  88. /* whole file was read as requested */
  89. break;
  90. }
  91. goto out;
  92. }
  93. sha256_process(hs, readbuf, readlen);
  94. readcount += readlen;
  95. }
  96. ret = DROPBEAR_SUCCESS;
  97. out:
  98. close(readfd);
  99. return ret;
  100. }
  101. void addrandom(const unsigned char * buf, unsigned int len)
  102. {
  103. hash_state hs;
  104. #if DROPBEAR_FUZZ
  105. if (fuzz.fuzzing) {
  106. return;
  107. }
  108. #endif
  109. /* hash in the new seed data */
  110. sha256_init(&hs);
  111. /* existing state (zeroes on startup) */
  112. sha256_process(&hs, (void*)hashpool, sizeof(hashpool));
  113. /* new */
  114. sha256_process(&hs, buf, len);
  115. sha256_done(&hs, hashpool);
  116. }
  117. static void write_urandom()
  118. {
  119. #if DROPBEAR_FUZZ
  120. if (fuzz.fuzzing) {
  121. return;
  122. }
  123. #endif
  124. #if !DROPBEAR_USE_PRNGD
  125. /* This is opportunistic, don't worry about failure */
  126. unsigned char buf[INIT_SEED_SIZE];
  127. FILE *f = fopen(DROPBEAR_URANDOM_DEV, "w");
  128. if (!f) {
  129. return;
  130. }
  131. genrandom(buf, sizeof(buf));
  132. fwrite(buf, sizeof(buf), 1, f);
  133. fclose(f);
  134. #endif
  135. }
  136. #if DROPBEAR_FUZZ
  137. void fuzz_seed(const unsigned char* dat, unsigned int len) {
  138. hash_state hs;
  139. sha256_init(&hs);
  140. sha256_process(&hs, "fuzzfuzzfuzz", strlen("fuzzfuzzfuzz"));
  141. sha256_process(&hs, dat, len);
  142. sha256_done(&hs, hashpool);
  143. counter = 0;
  144. donerandinit = 1;
  145. }
  146. #endif
  147. #ifdef HAVE_GETRANDOM
  148. /* Reads entropy seed with getrandom().
  149. * May block if the kernel isn't ready.
  150. * Return DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
  151. static int process_getrandom(hash_state *hs) {
  152. char buf[INIT_SEED_SIZE];
  153. ssize_t ret;
  154. /* First try non-blocking so that we can warn about waiting */
  155. ret = getrandom(buf, sizeof(buf), GRND_NONBLOCK);
  156. if (ret == -1) {
  157. if (errno == ENOSYS) {
  158. /* Old kernel */
  159. return DROPBEAR_FAILURE;
  160. }
  161. /* Other errors fall through to blocking getrandom() */
  162. TRACE(("first getrandom() failed: %d %s", errno, strerror(errno)))
  163. if (errno == EAGAIN) {
  164. dropbear_log(LOG_WARNING, "Waiting for kernel randomness to be initialised...");
  165. }
  166. }
  167. /* Wait blocking if needed. Loop in case we get EINTR */
  168. while (ret != sizeof(buf)) {
  169. ret = getrandom(buf, sizeof(buf), 0);
  170. if (ret == sizeof(buf)) {
  171. /* Success */
  172. break;
  173. }
  174. if (ret == -1 && errno == EINTR) {
  175. /* Try again. */
  176. continue;
  177. }
  178. if (ret >= 0) {
  179. TRACE(("Short read %zd from getrandom() shouldn't happen", ret))
  180. /* Try again? */
  181. continue;
  182. }
  183. /* Unexpected problem, fall back to /dev/urandom */
  184. TRACE(("2nd getrandom() failed: %d %s", errno, strerror(errno)))
  185. break;
  186. }
  187. if (ret == sizeof(buf)) {
  188. /* Success, stir in the entropy */
  189. sha256_process(hs, (void*)buf, sizeof(buf));
  190. return DROPBEAR_SUCCESS;
  191. }
  192. return DROPBEAR_FAILURE;
  193. }
  194. #endif /* HAVE_GETRANDOM */
  195. /* Initialise the prng from /dev/urandom or prngd. This function can
  196. * be called multiple times */
  197. void seedrandom() {
  198. hash_state hs;
  199. pid_t pid;
  200. struct timeval tv;
  201. clock_t clockval;
  202. int urandom_seeded = 0;
  203. #if DROPBEAR_FUZZ
  204. if (fuzz.fuzzing) {
  205. return;
  206. }
  207. #endif
  208. /* hash in the new seed data */
  209. sha256_init(&hs);
  210. /* existing state */
  211. sha256_process(&hs, (void*)hashpool, sizeof(hashpool));
  212. #ifdef HAVE_GETRANDOM
  213. if (process_getrandom(&hs) == DROPBEAR_SUCCESS) {
  214. urandom_seeded = 1;
  215. }
  216. #endif
  217. if (!urandom_seeded) {
  218. #if DROPBEAR_USE_PRNGD
  219. if (process_file(&hs, DROPBEAR_PRNGD_SOCKET, INIT_SEED_SIZE, 1)
  220. != DROPBEAR_SUCCESS) {
  221. dropbear_exit("Failure reading random device %s",
  222. DROPBEAR_PRNGD_SOCKET);
  223. urandom_seeded = 1;
  224. }
  225. #else
  226. /* non-blocking random source (probably /dev/urandom) */
  227. if (process_file(&hs, DROPBEAR_URANDOM_DEV, INIT_SEED_SIZE, 0)
  228. != DROPBEAR_SUCCESS) {
  229. dropbear_exit("Failure reading random device %s",
  230. DROPBEAR_URANDOM_DEV);
  231. urandom_seeded = 1;
  232. }
  233. #endif
  234. } /* urandom_seeded */
  235. /* A few other sources to fall back on.
  236. * Add more here for other platforms */
  237. #ifdef __linux__
  238. /* Seems to be a reasonable source of entropy from timers. Possibly hard
  239. * for even local attackers to reproduce */
  240. process_file(&hs, "/proc/timer_list", 0, 0);
  241. /* Might help on systems with wireless */
  242. process_file(&hs, "/proc/interrupts", 0, 0);
  243. process_file(&hs, "/proc/loadavg", 0, 0);
  244. process_file(&hs, "/proc/sys/kernel/random/entropy_avail", 0, 0);
  245. /* Mostly network visible but useful in some situations.
  246. * Limit size to avoid slowdowns on systems with lots of routes */
  247. process_file(&hs, "/proc/net/netstat", 4096, 0);
  248. process_file(&hs, "/proc/net/dev", 4096, 0);
  249. process_file(&hs, "/proc/net/tcp", 4096, 0);
  250. /* Also includes interface lo */
  251. process_file(&hs, "/proc/net/rt_cache", 4096, 0);
  252. process_file(&hs, "/proc/vmstat", 0, 0);
  253. #endif
  254. pid = getpid();
  255. sha256_process(&hs, (void*)&pid, sizeof(pid));
  256. /* gettimeofday() doesn't completely fill out struct timeval on
  257. OS X (10.8.3), avoid valgrind warnings by clearing it first */
  258. memset(&tv, 0x0, sizeof(tv));
  259. gettimeofday(&tv, NULL);
  260. sha256_process(&hs, (void*)&tv, sizeof(tv));
  261. clockval = clock();
  262. sha256_process(&hs, (void*)&clockval, sizeof(clockval));
  263. /* When a private key is read by the client or server it will
  264. * be added to the hashpool - see runopts.c */
  265. sha256_done(&hs, hashpool);
  266. counter = 0;
  267. donerandinit = 1;
  268. /* Feed it all back into /dev/urandom - this might help if Dropbear
  269. * is running from inetd and gets new state each time */
  270. write_urandom();
  271. }
  272. /* return len bytes of pseudo-random data */
  273. void genrandom(unsigned char* buf, unsigned int len) {
  274. hash_state hs;
  275. unsigned char hash[SHA256_HASH_SIZE];
  276. unsigned int copylen;
  277. if (!donerandinit) {
  278. dropbear_exit("seedrandom not done");
  279. }
  280. while (len > 0) {
  281. sha256_init(&hs);
  282. sha256_process(&hs, (void*)hashpool, sizeof(hashpool));
  283. sha256_process(&hs, (void*)&counter, sizeof(counter));
  284. sha256_done(&hs, hash);
  285. counter++;
  286. if (counter > MAX_COUNTER) {
  287. seedrandom();
  288. }
  289. copylen = MIN(len, SHA256_HASH_SIZE);
  290. memcpy(buf, hash, copylen);
  291. len -= copylen;
  292. buf += copylen;
  293. }
  294. m_burn(hash, sizeof(hash));
  295. }
  296. /* Generates a random mp_int.
  297. * max is a *mp_int specifying an upper bound.
  298. * rand must be an initialised *mp_int for the result.
  299. * the result rand satisfies: 0 < rand < max
  300. * */
  301. void gen_random_mpint(mp_int *max, mp_int *rand) {
  302. unsigned char *randbuf = NULL;
  303. unsigned int len = 0;
  304. const unsigned char masks[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
  305. const int size_bits = mp_count_bits(max);
  306. len = size_bits / 8;
  307. if ((size_bits % 8) != 0) {
  308. len += 1;
  309. }
  310. randbuf = (unsigned char*)m_malloc(len);
  311. do {
  312. genrandom(randbuf, len);
  313. /* Mask out the unrequired bits - mp_read_unsigned_bin expects
  314. * MSB first.*/
  315. randbuf[0] &= masks[size_bits % 8];
  316. bytes_to_mp(rand, randbuf, len);
  317. /* keep regenerating until we get one satisfying
  318. * 0 < rand < max */
  319. } while (!(mp_cmp(rand, max) == MP_LT && mp_cmp_d(rand, 0) == MP_GT));
  320. m_burn(randbuf, len);
  321. m_free(randbuf);
  322. }