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
37namespace 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
45struct 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
51static 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
62static int stream_write(BIO* h, const char* buf, int num);
63static int stream_read(BIO* h, char* buf, int size);
64static int stream_puts(BIO* h, const char* str);
65static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
66static int stream_new(BIO* h);
67static int stream_free(BIO* data);
68
69static 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
82static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
83
84static 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
94static 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
102static int stream_free(BIO* b) {
103  if (b == NULL)
104    return 0;
105  return 1;
106}
107
108static 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
126static 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
142static int stream_puts(BIO* b, const char* str) {
143  return stream_write(b, str, strlen(str));
144}
145
146static 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
169OpenSSLStreamAdapter::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
179OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
180  Cleanup();
181}
182
183void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
184  ASSERT(!identity_);
185  identity_.reset(static_cast<OpenSSLIdentity*>(identity));
186}
187
188void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
189  role_ = role;
190}
191
192bool OpenSSLStreamAdapter::GetPeerCertificate(SSLCertificate** cert) const {
193  if (!peer_certificate_)
194    return false;
195
196  *cert = peer_certificate_->GetReference();
197  return true;
198}
199
200bool 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
224bool 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
247bool 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
285bool 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
313int 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
319int OpenSSLStreamAdapter::StartSSLWithPeer() {
320  ASSERT(ssl_server_name_.empty());
321  // It is permitted to specify peer_certificate_ only later.
322  return StartSSL();
323}
324
325void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
326  ASSERT(state_ == SSL_NONE);
327  ssl_mode_ = mode;
328}
329
330//
331// StreamInterface Implementation
332//
333
334StreamResult 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
394StreamResult 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
471void 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
493void OpenSSLStreamAdapter::Close() {
494  Cleanup();
495  ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
496  StreamAdapterInterface::Close();
497}
498
499StreamState 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
512void 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
566int 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
583int 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  // Specify an ECDH group for ECDHE ciphers, otherwise they cannot be
619  // negotiated when acting as the server. Use NIST's P-256 which is commonly
620  // supported.
621  EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
622  if (ecdh == NULL)
623    return -1;
624  SSL_set_options(ssl_, SSL_OP_SINGLE_ECDH_USE);
625  SSL_set_tmp_ecdh(ssl_, ecdh);
626  EC_KEY_free(ecdh);
627
628  // Do the connect
629  return ContinueSSL();
630}
631
632int OpenSSLStreamAdapter::ContinueSSL() {
633  LOG(LS_VERBOSE) << "ContinueSSL";
634  ASSERT(state_ == SSL_CONNECTING);
635
636  // Clear the DTLS timer
637  Thread::Current()->Clear(this, MSG_TIMEOUT);
638
639  int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
640  int ssl_error;
641  switch (ssl_error = SSL_get_error(ssl_, code)) {
642    case SSL_ERROR_NONE:
643      LOG(LS_VERBOSE) << " -- success";
644
645      if (!SSLPostConnectionCheck(ssl_, ssl_server_name_.c_str(), NULL,
646                                  peer_certificate_digest_algorithm_)) {
647        LOG(LS_ERROR) << "TLS post connection check failed";
648        return -1;
649      }
650
651      state_ = SSL_CONNECTED;
652      StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
653      break;
654
655    case SSL_ERROR_WANT_READ: {
656        LOG(LS_VERBOSE) << " -- error want read";
657        struct timeval timeout;
658        if (DTLSv1_get_timeout(ssl_, &timeout)) {
659          int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
660
661          Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
662        }
663      }
664      break;
665
666    case SSL_ERROR_WANT_WRITE:
667      LOG(LS_VERBOSE) << " -- error want write";
668      break;
669
670    case SSL_ERROR_ZERO_RETURN:
671    default:
672      LOG(LS_VERBOSE) << " -- error " << code;
673      return (ssl_error != 0) ? ssl_error : -1;
674  }
675
676  return 0;
677}
678
679void OpenSSLStreamAdapter::Error(const char* context, int err, bool signal) {
680  LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error("
681                  << context << ", " << err << ")";
682  state_ = SSL_ERROR;
683  ssl_error_code_ = err;
684  Cleanup();
685  if (signal)
686    StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
687}
688
689void OpenSSLStreamAdapter::Cleanup() {
690  LOG(LS_INFO) << "Cleanup";
691
692  if (state_ != SSL_ERROR) {
693    state_ = SSL_CLOSED;
694    ssl_error_code_ = 0;
695  }
696
697  if (ssl_) {
698    int ret = SSL_shutdown(ssl_);
699    if (ret < 0) {
700      LOG(LS_WARNING) << "SSL_shutdown failed, error = "
701                      << SSL_get_error(ssl_, ret);
702    }
703
704    SSL_free(ssl_);
705    ssl_ = NULL;
706  }
707  if (ssl_ctx_) {
708    SSL_CTX_free(ssl_ctx_);
709    ssl_ctx_ = NULL;
710  }
711  identity_.reset();
712  peer_certificate_.reset();
713
714  // Clear the DTLS timer
715  Thread::Current()->Clear(this, MSG_TIMEOUT);
716}
717
718
719void OpenSSLStreamAdapter::OnMessage(Message* msg) {
720  // Process our own messages and then pass others to the superclass
721  if (MSG_TIMEOUT == msg->message_id) {
722    LOG(LS_INFO) << "DTLS timeout expired";
723    DTLSv1_handle_timeout(ssl_);
724    ContinueSSL();
725  } else {
726    StreamInterface::OnMessage(msg);
727  }
728}
729
730SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
731  SSL_CTX *ctx = NULL;
732
733  if (role_ == SSL_CLIENT) {
734    ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
735        DTLSv1_client_method() : TLSv1_client_method());
736  } else {
737    ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
738        DTLSv1_server_method() : TLSv1_server_method());
739  }
740  if (ctx == NULL)
741    return NULL;
742
743  if (identity_ && !identity_->ConfigureIdentity(ctx)) {
744    SSL_CTX_free(ctx);
745    return NULL;
746  }
747
748#ifdef _DEBUG
749  SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
750#endif
751
752  int mode = SSL_VERIFY_PEER;
753  if (client_auth_enabled()) {
754    // Require a certificate from the client.
755    // Note: Normally this is always true in production, but it may be disabled
756    // for testing purposes (e.g. SSLAdapter unit tests).
757    mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
758  }
759
760  SSL_CTX_set_verify(ctx, mode, SSLVerifyCallback);
761  SSL_CTX_set_verify_depth(ctx, 4);
762  SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
763
764#ifdef HAVE_DTLS_SRTP
765  if (!srtp_ciphers_.empty()) {
766    if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
767      SSL_CTX_free(ctx);
768      return NULL;
769    }
770  }
771#endif
772
773  return ctx;
774}
775
776int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
777  // Get our SSL structure from the store
778  SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
779                                        store,
780                                        SSL_get_ex_data_X509_STORE_CTX_idx()));
781  OpenSSLStreamAdapter* stream =
782    reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
783
784  if (stream->peer_certificate_digest_algorithm_.empty()) {
785    return 0;
786  }
787  X509* cert = X509_STORE_CTX_get_current_cert(store);
788  int depth = X509_STORE_CTX_get_error_depth(store);
789
790  // For now We ignore the parent certificates and verify the leaf against
791  // the digest.
792  //
793  // TODO(jiayl): Verify the chain is a proper chain and report the chain to
794  // |stream->peer_certificate_|, like what NSS does.
795  if (depth > 0) {
796    LOG(LS_INFO) << "Ignored chained certificate at depth " << depth;
797    return 1;
798  }
799
800  unsigned char digest[EVP_MAX_MD_SIZE];
801  size_t digest_length;
802  if (!OpenSSLCertificate::ComputeDigest(
803           cert,
804           stream->peer_certificate_digest_algorithm_,
805           digest, sizeof(digest),
806           &digest_length)) {
807    LOG(LS_WARNING) << "Failed to compute peer cert digest.";
808    return 0;
809  }
810
811  Buffer computed_digest(digest, digest_length);
812  if (computed_digest != stream->peer_certificate_digest_value_) {
813    LOG(LS_WARNING) << "Rejected peer certificate due to mismatched digest.";
814    return 0;
815  }
816  // Ignore any verification error if the digest matches, since there is no
817  // value in checking the validity of a self-signed cert issued by untrusted
818  // sources.
819  LOG(LS_INFO) << "Accepted peer certificate.";
820
821  // Record the peer's certificate.
822  stream->peer_certificate_.reset(new OpenSSLCertificate(cert));
823  return 1;
824}
825
826// This code is taken from the "Network Security with OpenSSL"
827// sample in chapter 5
828bool OpenSSLStreamAdapter::SSLPostConnectionCheck(SSL* ssl,
829                                                  const char* server_name,
830                                                  const X509* peer_cert,
831                                                  const std::string
832                                                  &peer_digest) {
833  ASSERT(server_name != NULL);
834  bool ok;
835  if (server_name[0] != '\0') {  // traditional mode
836    ok = OpenSSLAdapter::VerifyServerName(ssl, server_name, ignore_bad_cert());
837
838    if (ok) {
839      ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
840            custom_verification_succeeded_);
841    }
842  } else {  // peer-to-peer mode
843    ASSERT((peer_cert != NULL) || (!peer_digest.empty()));
844    // no server name validation
845    ok = true;
846  }
847
848  if (!ok && ignore_bad_cert()) {
849    LOG(LS_ERROR) << "SSL_get_verify_result(ssl) = "
850                  << SSL_get_verify_result(ssl);
851    LOG(LS_INFO) << "Other TLS post connection checks failed.";
852    ok = true;
853  }
854
855  return ok;
856}
857
858bool OpenSSLStreamAdapter::HaveDtls() {
859  return true;
860}
861
862bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
863#ifdef HAVE_DTLS_SRTP
864  return true;
865#else
866  return false;
867#endif
868}
869
870bool OpenSSLStreamAdapter::HaveExporter() {
871#ifdef HAVE_DTLS_SRTP
872  return true;
873#else
874  return false;
875#endif
876}
877
878}  // namespace rtc
879
880#endif  // HAVE_OPENSSL_SSL_H
881