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