Home | History | Annotate | Download | only in base
      1 /*
      2  * libjingle
      3  * Copyright 2004--2008, Google Inc.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions are met:
      7  *
      8  *  1. Redistributions of source code must retain the above copyright notice,
      9  *     this list of conditions and the following disclaimer.
     10  *  2. Redistributions in binary form must reproduce the above copyright notice,
     11  *     this list of conditions and the following disclaimer in the documentation
     12  *     and/or other materials provided with the distribution.
     13  *  3. The name of the author may not be used to endorse or promote products
     14  *     derived from this software without specific prior written permission.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
     17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
     19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #if HAVE_CONFIG_H
     29 #include "config.h"
     30 #endif  // HAVE_CONFIG_H
     31 
     32 #if HAVE_OPENSSL_SSL_H
     33 
     34 #include "talk/base/opensslstreamadapter.h"
     35 
     36 #include <openssl/bio.h>
     37 #include <openssl/crypto.h>
     38 #include <openssl/err.h>
     39 #include <openssl/rand.h>
     40 #include <openssl/ssl.h>
     41 #include <openssl/x509v3.h>
     42 
     43 #include <vector>
     44 
     45 #include "talk/base/common.h"
     46 #include "talk/base/logging.h"
     47 #include "talk/base/stream.h"
     48 #include "talk/base/openssladapter.h"
     49 #include "talk/base/openssldigest.h"
     50 #include "talk/base/opensslidentity.h"
     51 #include "talk/base/stringutils.h"
     52 #include "talk/base/thread.h"
     53 
     54 namespace talk_base {
     55 
     56 #if (OPENSSL_VERSION_NUMBER >= 0x10001000L)
     57 #define HAVE_DTLS_SRTP
     58 #endif
     59 
     60 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
     61 #define HAVE_DTLS
     62 #endif
     63 
     64 #ifdef HAVE_DTLS_SRTP
     65 // SRTP cipher suite table
     66 struct SrtpCipherMapEntry {
     67   const char* external_name;
     68   const char* internal_name;
     69 };
     70 
     71 // This isn't elegant, but it's better than an external reference
     72 static SrtpCipherMapEntry SrtpCipherMap[] = {
     73   {"AES_CM_128_HMAC_SHA1_80", "SRTP_AES128_CM_SHA1_80"},
     74   {"AES_CM_128_HMAC_SHA1_32", "SRTP_AES128_CM_SHA1_32"},
     75   {NULL, NULL}
     76 };
     77 #endif
     78 
     79 //////////////////////////////////////////////////////////////////////
     80 // StreamBIO
     81 //////////////////////////////////////////////////////////////////////
     82 
     83 static int stream_write(BIO* h, const char* buf, int num);
     84 static int stream_read(BIO* h, char* buf, int size);
     85 static int stream_puts(BIO* h, const char* str);
     86 static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
     87 static int stream_new(BIO* h);
     88 static int stream_free(BIO* data);
     89 
     90 static BIO_METHOD methods_stream = {
     91   BIO_TYPE_BIO,
     92   "stream",
     93   stream_write,
     94   stream_read,
     95   stream_puts,
     96   0,
     97   stream_ctrl,
     98   stream_new,
     99   stream_free,
    100   NULL,
    101 };
    102 
    103 static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
    104 
    105 static BIO* BIO_new_stream(StreamInterface* stream) {
    106   BIO* ret = BIO_new(BIO_s_stream());
    107   if (ret == NULL)
    108     return NULL;
    109   ret->ptr = stream;
    110   return ret;
    111 }
    112 
    113 // bio methods return 1 (or at least non-zero) on success and 0 on failure.
    114 
    115 static int stream_new(BIO* b) {
    116   b->shutdown = 0;
    117   b->init = 1;
    118   b->num = 0;  // 1 means end-of-stream
    119   b->ptr = 0;
    120   return 1;
    121 }
    122 
    123 static int stream_free(BIO* b) {
    124   if (b == NULL)
    125     return 0;
    126   return 1;
    127 }
    128 
    129 static int stream_read(BIO* b, char* out, int outl) {
    130   if (!out)
    131     return -1;
    132   StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
    133   BIO_clear_retry_flags(b);
    134   size_t read;
    135   int error;
    136   StreamResult result = stream->Read(out, outl, &read, &error);
    137   if (result == SR_SUCCESS) {
    138     return read;
    139   } else if (result == SR_EOS) {
    140     b->num = 1;
    141   } else if (result == SR_BLOCK) {
    142     BIO_set_retry_read(b);
    143   }
    144   return -1;
    145 }
    146 
    147 static int stream_write(BIO* b, const char* in, int inl) {
    148   if (!in)
    149     return -1;
    150   StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
    151   BIO_clear_retry_flags(b);
    152   size_t written;
    153   int error;
    154   StreamResult result = stream->Write(in, inl, &written, &error);
    155   if (result == SR_SUCCESS) {
    156     return written;
    157   } else if (result == SR_BLOCK) {
    158     BIO_set_retry_write(b);
    159   }
    160   return -1;
    161 }
    162 
    163 static int stream_puts(BIO* b, const char* str) {
    164   return stream_write(b, str, strlen(str));
    165 }
    166 
    167 static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
    168   UNUSED(num);
    169   UNUSED(ptr);
    170 
    171   switch (cmd) {
    172     case BIO_CTRL_RESET:
    173       return 0;
    174     case BIO_CTRL_EOF:
    175       return b->num;
    176     case BIO_CTRL_WPENDING:
    177     case BIO_CTRL_PENDING:
    178       return 0;
    179     case BIO_CTRL_FLUSH:
    180       return 1;
    181     default:
    182       return 0;
    183   }
    184 }
    185 
    186 /////////////////////////////////////////////////////////////////////////////
    187 // OpenSSLStreamAdapter
    188 /////////////////////////////////////////////////////////////////////////////
    189 
    190 OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
    191     : SSLStreamAdapter(stream),
    192       state_(SSL_NONE),
    193       role_(SSL_CLIENT),
    194       ssl_read_needs_write_(false), ssl_write_needs_read_(false),
    195       ssl_(NULL), ssl_ctx_(NULL),
    196       custom_verification_succeeded_(false),
    197       ssl_mode_(SSL_MODE_TLS) {
    198 }
    199 
    200 OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
    201   Cleanup();
    202 }
    203 
    204 void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
    205   ASSERT(!identity_);
    206   identity_.reset(static_cast<OpenSSLIdentity*>(identity));
    207 }
    208 
    209 void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
    210   role_ = role;
    211 }
    212 
    213 void OpenSSLStreamAdapter::SetPeerCertificate(SSLCertificate* cert) {
    214   ASSERT(!peer_certificate_);
    215   ASSERT(peer_certificate_digest_algorithm_.empty());
    216   ASSERT(ssl_server_name_.empty());
    217   peer_certificate_.reset(static_cast<OpenSSLCertificate*>(cert));
    218 }
    219 
    220 bool OpenSSLStreamAdapter::SetPeerCertificateDigest(const std::string
    221                                                     &digest_alg,
    222                                                     const unsigned char*
    223                                                     digest_val,
    224                                                     size_t digest_len) {
    225   ASSERT(!peer_certificate_);
    226   ASSERT(peer_certificate_digest_algorithm_.size() == 0);
    227   ASSERT(ssl_server_name_.empty());
    228   size_t expected_len;
    229 
    230   if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
    231     LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
    232     return false;
    233   }
    234   if (expected_len != digest_len)
    235     return false;
    236 
    237   peer_certificate_digest_value_.SetData(digest_val, digest_len);
    238   peer_certificate_digest_algorithm_ = digest_alg;
    239 
    240   return true;
    241 }
    242 
    243 // Key Extractor interface
    244 bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
    245                                                 const uint8* context,
    246                                                 size_t context_len,
    247                                                 bool use_context,
    248                                                 uint8* result,
    249                                                 size_t result_len) {
    250 #ifdef HAVE_DTLS_SRTP
    251   int i;
    252 
    253   i = SSL_export_keying_material(ssl_, result, result_len,
    254                                  label.c_str(), label.length(),
    255                                  const_cast<uint8 *>(context),
    256                                  context_len, use_context);
    257 
    258   if (i != 1)
    259     return false;
    260 
    261   return true;
    262 #else
    263   return false;
    264 #endif
    265 }
    266 
    267 bool OpenSSLStreamAdapter::SetDtlsSrtpCiphers(
    268     const std::vector<std::string>& ciphers) {
    269   std::string internal_ciphers;
    270 
    271   if (state_ != SSL_NONE)
    272     return false;
    273 
    274 #ifdef HAVE_DTLS_SRTP
    275   for (std::vector<std::string>::const_iterator cipher = ciphers.begin();
    276        cipher != ciphers.end(); ++cipher) {
    277     bool found = false;
    278     for (SrtpCipherMapEntry *entry = SrtpCipherMap; entry->internal_name;
    279          ++entry) {
    280       if (*cipher == entry->external_name) {
    281         found = true;
    282         if (!internal_ciphers.empty())
    283           internal_ciphers += ":";
    284         internal_ciphers += entry->internal_name;
    285         break;
    286       }
    287     }
    288 
    289     if (!found) {
    290       LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
    291       return false;
    292     }
    293   }
    294 
    295   if (internal_ciphers.empty())
    296     return false;
    297 
    298   srtp_ciphers_ = internal_ciphers;
    299   return true;
    300 #else
    301   return false;
    302 #endif
    303 }
    304 
    305 bool OpenSSLStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
    306 #ifdef HAVE_DTLS_SRTP
    307   ASSERT(state_ == SSL_CONNECTED);
    308   if (state_ != SSL_CONNECTED)
    309     return false;
    310 
    311   SRTP_PROTECTION_PROFILE *srtp_profile =
    312       SSL_get_selected_srtp_profile(ssl_);
    313 
    314   if (!srtp_profile)
    315     return false;
    316 
    317   for (SrtpCipherMapEntry *entry = SrtpCipherMap;
    318        entry->internal_name; ++entry) {
    319     if (!strcmp(entry->internal_name, srtp_profile->name)) {
    320       *cipher = entry->external_name;
    321       return true;
    322     }
    323   }
    324 
    325   ASSERT(false);  // This should never happen
    326 
    327   return false;
    328 #else
    329   return false;
    330 #endif
    331 }
    332 
    333 int OpenSSLStreamAdapter::StartSSLWithServer(const char* server_name) {
    334   ASSERT(server_name != NULL && server_name[0] != '\0');
    335   ssl_server_name_ = server_name;
    336   return StartSSL();
    337 }
    338 
    339 int OpenSSLStreamAdapter::StartSSLWithPeer() {
    340   ASSERT(ssl_server_name_.empty());
    341   // It is permitted to specify peer_certificate_ only later.
    342   return StartSSL();
    343 }
    344 
    345 void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
    346   ASSERT(state_ == SSL_NONE);
    347   ssl_mode_ = mode;
    348 }
    349 
    350 //
    351 // StreamInterface Implementation
    352 //
    353 
    354 StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
    355                                          size_t* written, int* error) {
    356   LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
    357 
    358   switch (state_) {
    359   case SSL_NONE:
    360     // pass-through in clear text
    361     return StreamAdapterInterface::Write(data, data_len, written, error);
    362 
    363   case SSL_WAIT:
    364   case SSL_CONNECTING:
    365     return SR_BLOCK;
    366 
    367   case SSL_CONNECTED:
    368     break;
    369 
    370   case SSL_ERROR:
    371   case SSL_CLOSED:
    372   default:
    373     if (error)
    374       *error = ssl_error_code_;
    375     return SR_ERROR;
    376   }
    377 
    378   // OpenSSL will return an error if we try to write zero bytes
    379   if (data_len == 0) {
    380     if (written)
    381       *written = 0;
    382     return SR_SUCCESS;
    383   }
    384 
    385   ssl_write_needs_read_ = false;
    386 
    387   int code = SSL_write(ssl_, data, data_len);
    388   int ssl_error = SSL_get_error(ssl_, code);
    389   switch (ssl_error) {
    390   case SSL_ERROR_NONE:
    391     LOG(LS_VERBOSE) << " -- success";
    392     ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
    393     if (written)
    394       *written = code;
    395     return SR_SUCCESS;
    396   case SSL_ERROR_WANT_READ:
    397     LOG(LS_VERBOSE) << " -- error want read";
    398     ssl_write_needs_read_ = true;
    399     return SR_BLOCK;
    400   case SSL_ERROR_WANT_WRITE:
    401     LOG(LS_VERBOSE) << " -- error want write";
    402     return SR_BLOCK;
    403 
    404   case SSL_ERROR_ZERO_RETURN:
    405   default:
    406     Error("SSL_write", (ssl_error ? ssl_error : -1), false);
    407     if (error)
    408       *error = ssl_error_code_;
    409     return SR_ERROR;
    410   }
    411   // not reached
    412 }
    413 
    414 StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
    415                                         size_t* read, int* error) {
    416   LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
    417   switch (state_) {
    418     case SSL_NONE:
    419       // pass-through in clear text
    420       return StreamAdapterInterface::Read(data, data_len, read, error);
    421 
    422     case SSL_WAIT:
    423     case SSL_CONNECTING:
    424       return SR_BLOCK;
    425 
    426     case SSL_CONNECTED:
    427       break;
    428 
    429     case SSL_CLOSED:
    430       return SR_EOS;
    431 
    432     case SSL_ERROR:
    433     default:
    434       if (error)
    435         *error = ssl_error_code_;
    436       return SR_ERROR;
    437   }
    438 
    439   // Don't trust OpenSSL with zero byte reads
    440   if (data_len == 0) {
    441     if (read)
    442       *read = 0;
    443     return SR_SUCCESS;
    444   }
    445 
    446   ssl_read_needs_write_ = false;
    447 
    448   int code = SSL_read(ssl_, data, data_len);
    449   int ssl_error = SSL_get_error(ssl_, code);
    450   switch (ssl_error) {
    451     case SSL_ERROR_NONE:
    452       LOG(LS_VERBOSE) << " -- success";
    453       ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
    454       if (read)
    455         *read = code;
    456 
    457       if (ssl_mode_ == SSL_MODE_DTLS) {
    458         // Enforce atomic reads -- this is a short read
    459         unsigned int pending = SSL_pending(ssl_);
    460 
    461         if (pending) {
    462           LOG(LS_INFO) << " -- short DTLS read. flushing";
    463           FlushInput(pending);
    464           if (error)
    465             *error = SSE_MSG_TRUNC;
    466           return SR_ERROR;
    467         }
    468       }
    469       return SR_SUCCESS;
    470     case SSL_ERROR_WANT_READ:
    471       LOG(LS_VERBOSE) << " -- error want read";
    472       return SR_BLOCK;
    473     case SSL_ERROR_WANT_WRITE:
    474       LOG(LS_VERBOSE) << " -- error want write";
    475       ssl_read_needs_write_ = true;
    476       return SR_BLOCK;
    477     case SSL_ERROR_ZERO_RETURN:
    478       LOG(LS_VERBOSE) << " -- remote side closed";
    479       return SR_EOS;
    480       break;
    481     default:
    482       LOG(LS_VERBOSE) << " -- error " << code;
    483       Error("SSL_read", (ssl_error ? ssl_error : -1), false);
    484       if (error)
    485         *error = ssl_error_code_;
    486       return SR_ERROR;
    487   }
    488   // not reached
    489 }
    490 
    491 void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
    492   unsigned char buf[2048];
    493 
    494   while (left) {
    495     // This should always succeed
    496     int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
    497     int code = SSL_read(ssl_, buf, toread);
    498 
    499     int ssl_error = SSL_get_error(ssl_, code);
    500     ASSERT(ssl_error == SSL_ERROR_NONE);
    501 
    502     if (ssl_error != SSL_ERROR_NONE) {
    503       LOG(LS_VERBOSE) << " -- error " << code;
    504       Error("SSL_read", (ssl_error ? ssl_error : -1), false);
    505       return;
    506     }
    507 
    508     LOG(LS_VERBOSE) << " -- flushed " << code << " bytes";
    509     left -= code;
    510   }
    511 }
    512 
    513 void OpenSSLStreamAdapter::Close() {
    514   Cleanup();
    515   ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
    516   StreamAdapterInterface::Close();
    517 }
    518 
    519 StreamState OpenSSLStreamAdapter::GetState() const {
    520   switch (state_) {
    521     case SSL_WAIT:
    522     case SSL_CONNECTING:
    523       return SS_OPENING;
    524     case SSL_CONNECTED:
    525       return SS_OPEN;
    526     default:
    527       return SS_CLOSED;
    528   };
    529   // not reached
    530 }
    531 
    532 void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
    533                                    int err) {
    534   int events_to_signal = 0;
    535   int signal_error = 0;
    536   ASSERT(stream == this->stream());
    537   if ((events & SE_OPEN)) {
    538     LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
    539     if (state_ != SSL_WAIT) {
    540       ASSERT(state_ == SSL_NONE);
    541       events_to_signal |= SE_OPEN;
    542     } else {
    543       state_ = SSL_CONNECTING;
    544       if (int err = BeginSSL()) {
    545         Error("BeginSSL", err, true);
    546         return;
    547       }
    548     }
    549   }
    550   if ((events & (SE_READ|SE_WRITE))) {
    551     LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent"
    552                  << ((events & SE_READ) ? " SE_READ" : "")
    553                  << ((events & SE_WRITE) ? " SE_WRITE" : "");
    554     if (state_ == SSL_NONE) {
    555       events_to_signal |= events & (SE_READ|SE_WRITE);
    556     } else if (state_ == SSL_CONNECTING) {
    557       if (int err = ContinueSSL()) {
    558         Error("ContinueSSL", err, true);
    559         return;
    560       }
    561     } else if (state_ == SSL_CONNECTED) {
    562       if (((events & SE_READ) && ssl_write_needs_read_) ||
    563           (events & SE_WRITE)) {
    564         LOG(LS_VERBOSE) << " -- onStreamWriteable";
    565         events_to_signal |= SE_WRITE;
    566       }
    567       if (((events & SE_WRITE) && ssl_read_needs_write_) ||
    568           (events & SE_READ)) {
    569         LOG(LS_VERBOSE) << " -- onStreamReadable";
    570         events_to_signal |= SE_READ;
    571       }
    572     }
    573   }
    574   if ((events & SE_CLOSE)) {
    575     LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
    576     Cleanup();
    577     events_to_signal |= SE_CLOSE;
    578     // SE_CLOSE is the only event that uses the final parameter to OnEvent().
    579     ASSERT(signal_error == 0);
    580     signal_error = err;
    581   }
    582   if (events_to_signal)
    583     StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
    584 }
    585 
    586 int OpenSSLStreamAdapter::StartSSL() {
    587   ASSERT(state_ == SSL_NONE);
    588 
    589   if (StreamAdapterInterface::GetState() != SS_OPEN) {
    590     state_ = SSL_WAIT;
    591     return 0;
    592   }
    593 
    594   state_ = SSL_CONNECTING;
    595   if (int err = BeginSSL()) {
    596     Error("BeginSSL", err, false);
    597     return err;
    598   }
    599 
    600   return 0;
    601 }
    602 
    603 int OpenSSLStreamAdapter::BeginSSL() {
    604   ASSERT(state_ == SSL_CONNECTING);
    605   // The underlying stream has open. If we are in peer-to-peer mode
    606   // then a peer certificate must have been specified by now.
    607   ASSERT(!ssl_server_name_.empty() ||
    608          peer_certificate_ ||
    609          !peer_certificate_digest_algorithm_.empty());
    610   LOG(LS_INFO) << "BeginSSL: "
    611                << (!ssl_server_name_.empty() ? ssl_server_name_ :
    612                                                "with peer");
    613 
    614   BIO* bio = NULL;
    615 
    616   // First set up the context
    617   ASSERT(ssl_ctx_ == NULL);
    618   ssl_ctx_ = SetupSSLContext();
    619   if (!ssl_ctx_)
    620     return -1;
    621 
    622   bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
    623   if (!bio)
    624     return -1;
    625 
    626   ssl_ = SSL_new(ssl_ctx_);
    627   if (!ssl_) {
    628     BIO_free(bio);
    629     return -1;
    630   }
    631 
    632   SSL_set_app_data(ssl_, this);
    633 
    634   SSL_set_bio(ssl_, bio, bio);  // the SSL object owns the bio now.
    635 
    636   SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
    637                SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
    638 
    639   // Do the connect
    640   return ContinueSSL();
    641 }
    642 
    643 int OpenSSLStreamAdapter::ContinueSSL() {
    644   LOG(LS_VERBOSE) << "ContinueSSL";
    645   ASSERT(state_ == SSL_CONNECTING);
    646 
    647   // Clear the DTLS timer
    648   Thread::Current()->Clear(this, MSG_TIMEOUT);
    649 
    650   int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
    651   int ssl_error;
    652   switch (ssl_error = SSL_get_error(ssl_, code)) {
    653     case SSL_ERROR_NONE:
    654       LOG(LS_VERBOSE) << " -- success";
    655 
    656       if (!SSLPostConnectionCheck(ssl_, ssl_server_name_.c_str(),
    657                                   peer_certificate_ ?
    658                                       peer_certificate_->x509() : NULL,
    659                                   peer_certificate_digest_algorithm_)) {
    660         LOG(LS_ERROR) << "TLS post connection check failed";
    661         return -1;
    662       }
    663 
    664       state_ = SSL_CONNECTED;
    665       StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
    666       break;
    667 
    668     case SSL_ERROR_WANT_READ: {
    669         LOG(LS_VERBOSE) << " -- error want read";
    670 #ifdef HAVE_DTLS
    671         struct timeval timeout;
    672         if (DTLSv1_get_timeout(ssl_, &timeout)) {
    673           int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
    674 
    675           Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
    676         }
    677 #endif
    678       }
    679       break;
    680 
    681     case SSL_ERROR_WANT_WRITE:
    682       LOG(LS_VERBOSE) << " -- error want write";
    683       break;
    684 
    685     case SSL_ERROR_ZERO_RETURN:
    686     default:
    687       LOG(LS_VERBOSE) << " -- error " << code;
    688       return (ssl_error != 0) ? ssl_error : -1;
    689   }
    690 
    691   return 0;
    692 }
    693 
    694 void OpenSSLStreamAdapter::Error(const char* context, int err, bool signal) {
    695   LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error("
    696                   << context << ", " << err << ")";
    697   state_ = SSL_ERROR;
    698   ssl_error_code_ = err;
    699   Cleanup();
    700   if (signal)
    701     StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
    702 }
    703 
    704 void OpenSSLStreamAdapter::Cleanup() {
    705   LOG(LS_INFO) << "Cleanup";
    706 
    707   if (state_ != SSL_ERROR) {
    708     state_ = SSL_CLOSED;
    709     ssl_error_code_ = 0;
    710   }
    711 
    712   if (ssl_) {
    713     SSL_free(ssl_);
    714     ssl_ = NULL;
    715   }
    716   if (ssl_ctx_) {
    717     SSL_CTX_free(ssl_ctx_);
    718     ssl_ctx_ = NULL;
    719   }
    720   identity_.reset();
    721   peer_certificate_.reset();
    722 
    723   // Clear the DTLS timer
    724   Thread::Current()->Clear(this, MSG_TIMEOUT);
    725 }
    726 
    727 
    728 void OpenSSLStreamAdapter::OnMessage(Message* msg) {
    729   // Process our own messages and then pass others to the superclass
    730   if (MSG_TIMEOUT == msg->message_id) {
    731     LOG(LS_INFO) << "DTLS timeout expired";
    732 #ifdef HAVE_DTLS
    733     DTLSv1_handle_timeout(ssl_);
    734 #endif
    735     ContinueSSL();
    736   } else {
    737     StreamInterface::OnMessage(msg);
    738   }
    739 }
    740 
    741 SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
    742   SSL_CTX *ctx = NULL;
    743 
    744   if (role_ == SSL_CLIENT) {
    745 #ifdef HAVE_DTLS
    746     ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
    747         DTLSv1_client_method() : TLSv1_client_method());
    748 #else
    749     ctx = SSL_CTX_new(TLSv1_client_method());
    750 #endif
    751   } else {
    752 #ifdef HAVE_DTLS
    753     ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
    754         DTLSv1_server_method() : TLSv1_server_method());
    755 #else
    756     ctx = SSL_CTX_new(TLSv1_server_method());
    757 #endif
    758   }
    759   if (ctx == NULL)
    760     return NULL;
    761 
    762   if (identity_ && !identity_->ConfigureIdentity(ctx)) {
    763     SSL_CTX_free(ctx);
    764     return NULL;
    765   }
    766 
    767   if (!peer_certificate_) {  // traditional mode
    768     // Add the root cert to the SSL context
    769     if (!OpenSSLAdapter::ConfigureTrustedRootCertificates(ctx)) {
    770       SSL_CTX_free(ctx);
    771       return NULL;
    772     }
    773   }
    774 
    775   if (peer_certificate_ && role_ == SSL_SERVER)
    776     // we must specify which client cert to ask for
    777     SSL_CTX_add_client_CA(ctx, peer_certificate_->x509());
    778 
    779 #ifdef _DEBUG
    780   SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
    781 #endif
    782 
    783   SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
    784                      SSLVerifyCallback);
    785   SSL_CTX_set_verify_depth(ctx, 4);
    786   SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
    787 
    788 #ifdef HAVE_DTLS_SRTP
    789   if (!srtp_ciphers_.empty()) {
    790     if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
    791       SSL_CTX_free(ctx);
    792       return NULL;
    793     }
    794   }
    795 #endif
    796 
    797   return ctx;
    798 }
    799 
    800 int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
    801 #if _DEBUG
    802   if (!ok) {
    803     char data[256];
    804     X509* cert = X509_STORE_CTX_get_current_cert(store);
    805     int depth = X509_STORE_CTX_get_error_depth(store);
    806     int err = X509_STORE_CTX_get_error(store);
    807 
    808     LOG(LS_INFO) << "Error with certificate at depth: " << depth;
    809     X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
    810     LOG(LS_INFO) << "  issuer  = " << data;
    811     X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
    812     LOG(LS_INFO) << "  subject = " << data;
    813     LOG(LS_INFO) << "  err     = " << err
    814       << ":" << X509_verify_cert_error_string(err);
    815   }
    816 #endif
    817 
    818   // Get our SSL structure from the store
    819   SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
    820                                         store,
    821                                         SSL_get_ex_data_X509_STORE_CTX_idx()));
    822 
    823   OpenSSLStreamAdapter* stream =
    824     reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
    825 
    826   // In peer-to-peer mode, no root cert / certificate authority was
    827   // specified, so the libraries knows of no certificate to accept,
    828   // and therefore it will necessarily call here on the first cert it
    829   // tries to verify.
    830   if (!ok && stream->peer_certificate_) {
    831     X509* cert = X509_STORE_CTX_get_current_cert(store);
    832     int err = X509_STORE_CTX_get_error(store);
    833     // peer-to-peer mode: allow the certificate to be self-signed,
    834     // assuming it matches the cert that was specified.
    835     if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT &&
    836         X509_cmp(cert, stream->peer_certificate_->x509()) == 0) {
    837       LOG(LS_INFO) << "Accepted self-signed peer certificate authority";
    838       ok = 1;
    839     }
    840   } else if (!ok && !stream->peer_certificate_digest_algorithm_.empty()) {
    841     X509* cert = X509_STORE_CTX_get_current_cert(store);
    842     int err = X509_STORE_CTX_get_error(store);
    843 
    844     // peer-to-peer mode: allow the certificate to be self-signed,
    845     // assuming it matches the digest that was specified.
    846     if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) {
    847       unsigned char digest[EVP_MAX_MD_SIZE];
    848       std::size_t digest_length;
    849 
    850       if (OpenSSLCertificate::
    851          ComputeDigest(cert,
    852                        stream->peer_certificate_digest_algorithm_,
    853                        digest, sizeof(digest),
    854                        &digest_length)) {
    855         Buffer computed_digest(digest, digest_length);
    856         if (computed_digest == stream->peer_certificate_digest_value_) {
    857           LOG(LS_INFO) <<
    858               "Accepted self-signed peer certificate authority";
    859           ok = 1;
    860         }
    861       }
    862     }
    863   } else if (!ok && OpenSSLAdapter::custom_verify_callback_) {
    864     // this applies only in traditional mode
    865     void* cert =
    866         reinterpret_cast<void*>(X509_STORE_CTX_get_current_cert(store));
    867     if (OpenSSLAdapter::custom_verify_callback_(cert)) {
    868       stream->custom_verification_succeeded_ = true;
    869       LOG(LS_INFO) << "validated certificate using custom callback";
    870       ok = 1;
    871     }
    872   }
    873 
    874   if (!ok && stream->ignore_bad_cert()) {
    875     LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
    876     ok = 1;
    877   }
    878 
    879   return ok;
    880 }
    881 
    882 // This code is taken from the "Network Security with OpenSSL"
    883 // sample in chapter 5
    884 bool OpenSSLStreamAdapter::SSLPostConnectionCheck(SSL* ssl,
    885                                                   const char* server_name,
    886                                                   const X509* peer_cert,
    887                                                   const std::string
    888                                                   &peer_digest) {
    889   ASSERT(server_name != NULL);
    890   bool ok;
    891   if (server_name[0] != '\0') {  // traditional mode
    892     ok = OpenSSLAdapter::VerifyServerName(ssl, server_name, ignore_bad_cert());
    893 
    894     if (ok) {
    895       ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
    896             custom_verification_succeeded_);
    897     }
    898   } else {  // peer-to-peer mode
    899     ASSERT((peer_cert != NULL) || (!peer_digest.empty()));
    900     // no server name validation
    901     ok = true;
    902   }
    903 
    904   if (!ok && ignore_bad_cert()) {
    905     LOG(LS_ERROR) << "SSL_get_verify_result(ssl) = "
    906                   << SSL_get_verify_result(ssl);
    907     LOG(LS_INFO) << "Other TLS post connection checks failed.";
    908     ok = true;
    909   }
    910 
    911   return ok;
    912 }
    913 
    914 bool OpenSSLStreamAdapter::HaveDtls() {
    915 #ifdef HAVE_DTLS
    916   return true;
    917 #else
    918   return false;
    919 #endif
    920 }
    921 
    922 bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
    923 #ifdef HAVE_DTLS_SRTP
    924   return true;
    925 #else
    926   return false;
    927 #endif
    928 }
    929 
    930 bool OpenSSLStreamAdapter::HaveExporter() {
    931 #ifdef HAVE_DTLS_SRTP
    932   return true;
    933 #else
    934   return false;
    935 #endif
    936 }
    937 
    938 }  // namespace talk_base
    939 
    940 #endif  // HAVE_OPENSSL_SSL_H
    941