SSLBridge.cpp 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. /*
  2. * Copyright (c) 2002-2009 Moxie Marlinspike
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 3 of the
  7. * License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  17. * USA
  18. */
  19. #include "SSLBridge.hpp"
  20. #include <string.h>
  21. using namespace boost::asio;
  22. X509* SSLBridge::getServerCertificate() {
  23. return SSL_get_peer_certificate(serverSession);
  24. }
  25. void SSLBridge::buildClientContext(SSL_CTX *context, Certificate *leaf, std::list<Certificate*> *chain) {
  26. SSL_CTX_sess_set_new_cb(context, &SessionCache::setNewSessionIdTramp);
  27. SSL_CTX_sess_set_get_cb(context, &SessionCache::getSessionIdTramp);
  28. SSL_CTX_use_certificate(context, leaf->getCert());
  29. SSL_CTX_use_PrivateKey(context, leaf->getKey());
  30. if (SSL_CTX_check_private_key(context) == 0) {
  31. std::cerr << "*** Assertion Failed - Generated PrivateKey Doesn't Work." << std::endl;
  32. throw SSLConnectionError();
  33. }
  34. std::list<Certificate*>::iterator i = chain->begin();
  35. std::list<Certificate*>::iterator end = chain->end();
  36. for (;i != end; i++) {
  37. SSL_CTX_add_extra_chain_cert(context, (*i)->getCert());
  38. }
  39. // if (chain != NULL)
  40. // SSL_CTX_add_extra_chain_cert(context, chain->getCert());
  41. SSL_CTX_set_mode(context, SSL_MODE_AUTO_RETRY);
  42. }
  43. ip::tcp::endpoint SSLBridge::getRemoteEndpoint() {
  44. return serverSocket->remote_endpoint();
  45. }
  46. void SSLBridge::setServerName() {
  47. X509 *serverCertificate = getServerCertificate();
  48. X509_NAME *serverNameField = X509_get_subject_name(serverCertificate);
  49. char *serverNameStr = X509_NAME_oneline(serverNameField, NULL, 0);
  50. this->serverName = std::string((const char*)serverNameStr);
  51. int commonNameIndex;
  52. if ((commonNameIndex = this->serverName.find("CN=")) != std::string::npos)
  53. this->serverName = this->serverName.substr(commonNameIndex+3);
  54. free(serverNameStr);
  55. }
  56. void SSLBridge::handshakeWithClient(CertificateManager &manager, bool wildcardOK) {
  57. Certificate *leaf;
  58. std::list<Certificate*> *chain;
  59. ip::tcp::endpoint endpoint = getRemoteEndpoint();
  60. manager.getCertificateForTarget(endpoint, wildcardOK, getServerCertificate(), &leaf, &chain);
  61. setServerName();
  62. SSL_CTX *clientContext = SSL_CTX_new(SSLv23_server_method());
  63. buildClientContext(clientContext, leaf, chain);
  64. SSL *clientSession = SSL_new(clientContext);
  65. SSL_set_fd(clientSession, clientSocket->native());
  66. if (SSL_accept(clientSession) == 0) {
  67. Logger::logError("SSL Accept Failed!");
  68. throw SSLConnectionError();
  69. }
  70. this->clientSession = clientSession;
  71. }
  72. void SSLBridge::handshakeWithServer() {
  73. int bogus;
  74. ip::address_v4 serverAddress = serverSocket->remote_endpoint().address().to_v4();
  75. SSL_CTX *serverCtx = SSL_CTX_new(SSLv23_client_method());;
  76. SSL *serverSession = SSL_new(serverCtx);;
  77. SSL_SESSION *sessionId = cache->getSessionId(serverSession,
  78. serverAddress.to_bytes().data(),
  79. serverAddress.to_bytes().size(),
  80. &bogus);
  81. if (sessionId != NULL) {
  82. SSL_set_session(serverSession, sessionId);
  83. SSL_SESSION_free(sessionId);
  84. }
  85. SSL_set_connect_state(serverSession);
  86. SSL_set_fd(serverSession, serverSocket->native());
  87. SSL_set_options(serverSession, SSL_OP_ALL);
  88. if (SSL_connect(serverSession) < 0) {
  89. Logger::logError("Error on SSL Connect.");
  90. throw SSLConnectionError();
  91. }
  92. cache->setNewSessionId(serverSession, SSL_get1_session(serverSession),
  93. serverAddress.to_bytes().data(),
  94. serverAddress.to_bytes().size());
  95. this->serverSession = serverSession;
  96. }
  97. void SSLBridge::shuttleData() {
  98. struct pollfd fds[2] = {{clientSocket->native(), POLLIN | POLLPRI | POLLHUP | POLLERR, 0},
  99. {serverSocket->native(), POLLIN | POLLPRI | POLLHUP | POLLERR, 0}};
  100. for (;;) {
  101. if (poll(fds, 2, -1) < 0) return;
  102. if (isAvailable(fds[0].revents)) if (!readFromClient()) return;
  103. if (isAvailable(fds[1].revents)) if (!readFromServer()) return;
  104. if (isClosed(fds[0].revents)) return;
  105. if (isClosed(fds[1].revents)) return;
  106. }
  107. }
  108. int SSLBridge::isAvailable(int revents) {
  109. return revents & POLLIN || revents & POLLPRI;
  110. }
  111. int SSLBridge::isClosed(int revents) {
  112. return revents & POLLERR || revents & POLLHUP;
  113. }
  114. bool SSLBridge::readFromClient() {
  115. char buf[4096];
  116. int bytesRead;
  117. int bytesWritten;
  118. do {
  119. if ((bytesRead = SSL_read(clientSession, buf, sizeof(buf))) <= 0)
  120. return SSL_get_error(clientSession, bytesRead) == SSL_ERROR_WANT_READ ? true : false;
  121. if ((bytesWritten = SSL_write(serverSession, buf, bytesRead)) <= 0)
  122. return false; // FIXME
  123. Logger::logFromClient(serverName, buf, bytesRead);
  124. } while (SSL_pending(clientSession));
  125. return true;
  126. }
  127. bool SSLBridge::readFromServer() {
  128. char buf[4096];
  129. int bytesRead;
  130. int bytesWritten;
  131. do {
  132. if ((bytesRead = SSL_read(serverSession, buf, sizeof(buf))) <= 0)
  133. return SSL_get_error(serverSession, bytesRead) == SSL_ERROR_WANT_READ ? true : false;
  134. if ((bytesWritten = SSL_write(clientSession, buf, bytesRead)) < bytesRead)
  135. return false; // FIXME
  136. Logger::logFromServer(serverName, buf, bytesRead);
  137. } while (SSL_pending(serverSession));
  138. return true;
  139. }
  140. void SSLBridge::close() {
  141. if (closed) return;
  142. else closed = true;
  143. if (serverSession) SSL_free(serverSession);
  144. if (clientSession) SSL_free(clientSession);
  145. clientSocket->close();
  146. serverSocket->close();
  147. }