You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ottery_entropy_egd.c 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* Libottery by Nick Mathewson.
  2. This software has been dedicated to the public domain under the CC0
  3. public domain dedication.
  4. To the extent possible under law, the person who associated CC0 with
  5. libottery has waived all copyright and related or neighboring rights
  6. to libottery.
  7. You should have received a copy of the CC0 legalcode along with this
  8. work in doc/cc0.txt. If not, see
  9. <http://creativecommons.org/publicdomain/zero/1.0/>.
  10. */
  11. #ifndef _WIN32
  12. /* TODO: Support win32. */
  13. #include <sys/socket.h>
  14. /** Implement an entropy-source that uses the EGD protocol. The
  15. * Entropy-Gathering Daemon is program (actually, one of several programs)
  16. * that watches system events, periodically runs commands whose outputs have
  17. * high variance, and so on. It communicates over a simple socket-based
  18. * protocol, of which we use only a tiny piece. */
  19. static int
  20. ottery_get_entropy_egd(const struct ottery_entropy_config *cfg,
  21. struct ottery_entropy_state *state,
  22. uint8_t *out, size_t outlen)
  23. {
  24. int sock, n, result;
  25. unsigned char msg[2];
  26. (void) state;
  27. if (! cfg || ! cfg->egd_sockaddr || ! cfg->egd_socklen)
  28. return OTTERY_ERR_INIT_STRONG_RNG;
  29. if (outlen > 255)
  30. return OTTERY_ERR_ACCESS_STRONG_RNG;
  31. sock = socket(cfg->egd_sockaddr->sa_family, SOCK_STREAM, 0);
  32. if (sock < 0)
  33. return OTTERY_ERR_INIT_STRONG_RNG;
  34. if (connect(sock, cfg->egd_sockaddr, cfg->egd_socklen) < 0) {
  35. result = OTTERY_ERR_INIT_STRONG_RNG;
  36. goto out;
  37. }
  38. msg[0] = 1; /* nonblocking request */
  39. msg[1] = (unsigned char) outlen; /* for outlen bytes */
  40. if (write(sock, msg, 2) != 2 ||
  41. read(sock, msg, 1) != 1) {
  42. result = OTTERY_ERR_ACCESS_STRONG_RNG;
  43. goto out;
  44. }
  45. if (msg[0] != outlen) {
  46. /* TODO Use any bytes we get, even if they aren't as many as we wanted. */
  47. result = OTTERY_ERR_ACCESS_STRONG_RNG;
  48. goto out;
  49. }
  50. n = ottery_read_n_bytes_from_file_(sock, out, outlen);
  51. if (n < 0 || (size_t)n != outlen) {
  52. result = OTTERY_ERR_ACCESS_STRONG_RNG;
  53. goto out;
  54. }
  55. result = 0;
  56. out:
  57. close(sock);
  58. return result;
  59. }
  60. #define ENTROPY_SOURCE_EGD \
  61. { ottery_get_entropy_egd, SRC(EGD)|DOM(EGD)|FL(STRONG) }
  62. #endif