challenge.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <sys/time.h>
  4. #include "challenge.h"
  5. #include "options.h"
  6. #include "md5.h"
  7. /* generate_challenge: Generates a random challenge, incorporating the current
  8. * local timestamp to avoid replay attacks.
  9. */
  10. challenge_t* generate_challenge(void) {
  11. struct timeval tt;
  12. challenge_t *c;
  13. int i;
  14. c = (challenge_t *) calloc(1, sizeof(challenge_t));
  15. gettimeofday(&tt, 0);
  16. c->sec = tt.tv_sec;
  17. c->usec_rnd = tt.tv_usec + rand();
  18. for (i=0;i<6;i++)
  19. c->random[i] = rand();
  20. return c;
  21. }
  22. /* generate_response: Generates a response to the given challenge. The response
  23. * is generated by combining the concatenating the challenge data with the
  24. * md5 digest of the password, and then calculating the MD5 digest of the
  25. * entire buffer. The result is stored in the passed-in challenge, overwriting
  26. * the challenge data.
  27. */
  28. void generate_response(challenge_t *challenge) {
  29. md5_byte_t buf[sizeof(challenge_t)+kMD5_digest_size];
  30. md5_state_t state;
  31. memcpy(buf, challenge, sizeof(challenge_t));
  32. memcpy(&buf[sizeof(challenge_t)], opts.password_digest, kMD5_digest_size);
  33. memset(challenge, 0, sizeof(challenge_t));
  34. md5_init(&state);
  35. md5_append(&state, buf, sizeof(challenge_t)+kMD5_digest_size);
  36. md5_finish(&state, (md5_byte_t*)challenge);
  37. }
  38. /* validate_challenge: Checks whether a given response matches the expected
  39. * response, returning 1 if validation succeeded, and 0 otherwise. Note that
  40. * overwriting the local challenge with the challenge result is not a problem,
  41. * as the data will not be used again anyway (authentication either succeeds,
  42. * or the connection is closed down).
  43. */
  44. int validate_challenge(challenge_t *local, challenge_t *remote) {
  45. generate_response(local);
  46. if (memcmp(local, remote, sizeof(challenge_t)) == 0)
  47. return 1;
  48. return 0;
  49. }