auth.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * auth.h
  3. * Key exchange with an onion router.
  4. *
  5. * Matej Pfajfar <mp292@cam.ac.uk>
  6. */
  7. /*
  8. * Changes :
  9. * $Log$
  10. * Revision 1.1 2002/06/26 22:45:50 arma
  11. * Initial revision
  12. *
  13. * Revision 1.1 2002/03/28 11:00:57 badbytes
  14. * Key exchange with an onion router.
  15. *
  16. */
  17. #include <openssl/rand.h>
  18. #include <string.h>
  19. #include <unistd.h>
  20. #include <sys/socket.h>
  21. #include <netinet/in.h>
  22. #include "../common/log.h"
  23. #include "auth.h"
  24. /* send session keys and bandwidth info to the router */
  25. int send_auth(int or_sock, uint32_t bandwidth, RSA *pkey, unsigned char *f_session_key, unsigned char *b_session_key)
  26. {
  27. int retval;
  28. int x;
  29. unsigned char message[20]; /* bandwidth(32bits), forward key(64bits), backward key(64bits) */
  30. unsigned char cipher[128];
  31. if ((or_sock <= 0) || (bandwidth <= 0) || !pkey || !f_session_key || !b_session_key) /* invalid parameters */
  32. return -1;
  33. bandwidth = htonl(bandwidth); /* convert to network order */
  34. /* generate the session keys */
  35. retval = RAND_bytes(f_session_key, 8);
  36. if (!retval)
  37. {
  38. log(LOG_ERR,"Not enough randomness to generate a session key.");
  39. return -1;
  40. }
  41. retval = RAND_bytes(b_session_key, 8);
  42. if (!retval)
  43. {
  44. log(LOG_ERR,"Not enough randomness to generate a session key.");
  45. return -1;
  46. }
  47. /* compose the message */
  48. memcpy((void *)message, (void *)&bandwidth, 4);
  49. memcpy((void *)(message + 4), (void *)f_session_key, 8);
  50. memcpy((void *)(message + 12), (void *)b_session_key, 8);
  51. printf("f_session_key: ");
  52. for(x=0;x<8;x++) {
  53. printf("%d ",f_session_key[x]);
  54. }
  55. printf("\nb_session_key: ");
  56. for(x=0;x<8;x++) {
  57. printf("%d ",b_session_key[x]);
  58. }
  59. printf("\n");
  60. /* encrypt with RSA */
  61. retval = RSA_public_encrypt(20, message, cipher, pkey, RSA_PKCS1_PADDING);
  62. if (retval == -1)
  63. {
  64. log(LOG_ERR,"Public key encryption failed.");
  65. return -1;
  66. }
  67. /* send the ciphertext */
  68. retval = send(or_sock, cipher, 128, 0);
  69. if (retval < 128)
  70. {
  71. log(LOG_ERR,"Connection to router lost while exchanging session keys.");
  72. return -1;
  73. }
  74. return 0;
  75. }