dbrandom.c 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. /* this is used to generate unique output from the same hashpool */
  30. static uint32_t counter = 0;
  31. /* the max value for the counter, so it won't integer overflow */
  32. #define MAX_COUNTER (1<<30)
  33. static unsigned char hashpool[SHA1_HASH_SIZE] = {0};
  34. static int donerandinit = 0;
  35. #define INIT_SEED_SIZE 32 /* 256 bits */
  36. /* The basic setup is we read some data from /dev/(u)random or prngd and hash it
  37. * into hashpool. To read data, we hash together current hashpool contents,
  38. * and a counter. We feed more data in by hashing the current pool and new
  39. * data into the pool.
  40. *
  41. * It is important to ensure that counter doesn't wrap around before we
  42. * feed in new entropy.
  43. *
  44. */
  45. /* Pass len=0 to hash an entire file */
  46. static int
  47. process_file(hash_state *hs, const char *filename,
  48. unsigned int len, int prngd)
  49. {
  50. static int already_blocked = 0;
  51. int readfd;
  52. unsigned int readcount;
  53. int ret = DROPBEAR_FAILURE;
  54. #ifdef DROPBEAR_PRNGD_SOCKET
  55. if (prngd)
  56. {
  57. readfd = connect_unix(filename);
  58. }
  59. else
  60. #endif
  61. {
  62. readfd = open(filename, O_RDONLY);
  63. }
  64. if (readfd < 0) {
  65. goto out;
  66. }
  67. readcount = 0;
  68. while (len == 0 || readcount < len)
  69. {
  70. int readlen, wantread;
  71. unsigned char readbuf[4096];
  72. if (!already_blocked && !prngd)
  73. {
  74. int res;
  75. struct timeval timeout;
  76. fd_set read_fds;
  77. timeout.tv_sec = 2;
  78. timeout.tv_usec = 0;
  79. FD_ZERO(&read_fds);
  80. FD_SET(readfd, &read_fds);
  81. res = select(readfd + 1, &read_fds, NULL, NULL, &timeout);
  82. if (res == 0)
  83. {
  84. dropbear_log(LOG_WARNING, "Warning: Reading the randomness source '%s' seems to have blocked.\nYou may need to find a better entropy source.", filename);
  85. already_blocked = 1;
  86. }
  87. }
  88. if (len == 0)
  89. {
  90. wantread = sizeof(readbuf);
  91. }
  92. else
  93. {
  94. wantread = MIN(sizeof(readbuf), len-readcount);
  95. }
  96. #ifdef DROPBEAR_PRNGD_SOCKET
  97. if (prngd)
  98. {
  99. char egdcmd[2];
  100. egdcmd[0] = 0x02; /* blocking read */
  101. egdcmd[1] = (unsigned char)wantread;
  102. if (write(readfd, egdcmd, 2) < 0)
  103. {
  104. dropbear_exit("Can't send command to egd");
  105. }
  106. }
  107. #endif
  108. readlen = read(readfd, readbuf, wantread);
  109. if (readlen <= 0) {
  110. if (readlen < 0 && errno == EINTR) {
  111. continue;
  112. }
  113. if (readlen == 0 && len == 0)
  114. {
  115. /* whole file was read as requested */
  116. break;
  117. }
  118. goto out;
  119. }
  120. sha1_process(hs, readbuf, readlen);
  121. readcount += readlen;
  122. }
  123. ret = DROPBEAR_SUCCESS;
  124. out:
  125. close(readfd);
  126. return ret;
  127. }
  128. void addrandom(unsigned char * buf, unsigned int len)
  129. {
  130. hash_state hs;
  131. /* hash in the new seed data */
  132. sha1_init(&hs);
  133. /* existing state (zeroes on startup) */
  134. sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
  135. /* new */
  136. sha1_process(&hs, buf, len);
  137. sha1_done(&hs, hashpool);
  138. }
  139. static void write_urandom()
  140. {
  141. #ifndef DROPBEAR_PRNGD_SOCKET
  142. /* This is opportunistic, don't worry about failure */
  143. unsigned char buf[INIT_SEED_SIZE];
  144. FILE *f = fopen(DROPBEAR_URANDOM_DEV, "w");
  145. if (!f) {
  146. return;
  147. }
  148. genrandom(buf, sizeof(buf));
  149. fwrite(buf, sizeof(buf), 1, f);
  150. fclose(f);
  151. #endif
  152. }
  153. /* Initialise the prng from /dev/urandom or prngd. This function can
  154. * be called multiple times */
  155. void seedrandom() {
  156. hash_state hs;
  157. pid_t pid;
  158. struct timeval tv;
  159. clock_t clockval;
  160. /* hash in the new seed data */
  161. sha1_init(&hs);
  162. /* existing state */
  163. sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
  164. #ifdef DROPBEAR_PRNGD_SOCKET
  165. if (process_file(&hs, DROPBEAR_PRNGD_SOCKET, INIT_SEED_SIZE, 1)
  166. != DROPBEAR_SUCCESS) {
  167. dropbear_exit("Failure reading random device %s",
  168. DROPBEAR_PRNGD_SOCKET);
  169. }
  170. #else
  171. /* non-blocking random source (probably /dev/urandom) */
  172. if (process_file(&hs, DROPBEAR_URANDOM_DEV, INIT_SEED_SIZE, 0)
  173. != DROPBEAR_SUCCESS) {
  174. dropbear_exit("Failure reading random device %s",
  175. DROPBEAR_URANDOM_DEV);
  176. }
  177. #endif
  178. /* A few other sources to fall back on.
  179. * Add more here for other platforms */
  180. #ifdef __linux__
  181. /* Seems to be a reasonable source of entropy from timers. Possibly hard
  182. * for even local attackers to reproduce */
  183. process_file(&hs, "/proc/timer_list", 0, 0);
  184. /* Might help on systems with wireless */
  185. process_file(&hs, "/proc/interrupts", 0, 0);
  186. process_file(&hs, "/proc/loadavg", 0, 0);
  187. process_file(&hs, "/proc/sys/kernel/random/entropy_avail", 0, 0);
  188. /* Mostly network visible but useful in some situations.
  189. * Limit size to avoid slowdowns on systems with lots of routes */
  190. process_file(&hs, "/proc/net/netstat", 4096, 0);
  191. process_file(&hs, "/proc/net/dev", 4096, 0);
  192. process_file(&hs, "/proc/net/tcp", 4096, 0);
  193. /* Also includes interface lo */
  194. process_file(&hs, "/proc/net/rt_cache", 4096, 0);
  195. process_file(&hs, "/proc/vmstat", 0, 0);
  196. #endif
  197. pid = getpid();
  198. sha1_process(&hs, (void*)&pid, sizeof(pid));
  199. /* gettimeofday() doesn't completely fill out struct timeval on
  200. OS X (10.8.3), avoid valgrind warnings by clearing it first */
  201. memset(&tv, 0x0, sizeof(tv));
  202. gettimeofday(&tv, NULL);
  203. sha1_process(&hs, (void*)&tv, sizeof(tv));
  204. clockval = clock();
  205. sha1_process(&hs, (void*)&clockval, sizeof(clockval));
  206. /* When a private key is read by the client or server it will
  207. * be added to the hashpool - see runopts.c */
  208. sha1_done(&hs, hashpool);
  209. counter = 0;
  210. donerandinit = 1;
  211. /* Feed it all back into /dev/urandom - this might help if Dropbear
  212. * is running from inetd and gets new state each time */
  213. write_urandom();
  214. }
  215. /* return len bytes of pseudo-random data */
  216. void genrandom(unsigned char* buf, unsigned int len) {
  217. hash_state hs;
  218. unsigned char hash[SHA1_HASH_SIZE];
  219. unsigned int copylen;
  220. if (!donerandinit) {
  221. dropbear_exit("seedrandom not done");
  222. }
  223. while (len > 0) {
  224. sha1_init(&hs);
  225. sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
  226. sha1_process(&hs, (void*)&counter, sizeof(counter));
  227. sha1_done(&hs, hash);
  228. counter++;
  229. if (counter > MAX_COUNTER) {
  230. seedrandom();
  231. }
  232. copylen = MIN(len, SHA1_HASH_SIZE);
  233. memcpy(buf, hash, copylen);
  234. len -= copylen;
  235. buf += copylen;
  236. }
  237. m_burn(hash, sizeof(hash));
  238. }
  239. /* Generates a random mp_int.
  240. * max is a *mp_int specifying an upper bound.
  241. * rand must be an initialised *mp_int for the result.
  242. * the result rand satisfies: 0 < rand < max
  243. * */
  244. void gen_random_mpint(mp_int *max, mp_int *rand) {
  245. unsigned char *randbuf = NULL;
  246. unsigned int len = 0;
  247. const unsigned char masks[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
  248. const int size_bits = mp_count_bits(max);
  249. len = size_bits / 8;
  250. if ((size_bits % 8) != 0) {
  251. len += 1;
  252. }
  253. randbuf = (unsigned char*)m_malloc(len);
  254. do {
  255. genrandom(randbuf, len);
  256. /* Mask out the unrequired bits - mp_read_unsigned_bin expects
  257. * MSB first.*/
  258. randbuf[0] &= masks[size_bits % 8];
  259. bytes_to_mp(rand, randbuf, len);
  260. /* keep regenerating until we get one satisfying
  261. * 0 < rand < max */
  262. } while (!(mp_cmp(rand, max) == MP_LT && mp_cmp_d(rand, 0) == MP_GT));
  263. m_burn(randbuf, len);
  264. m_free(randbuf);
  265. }