• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/tls1.h>
24 #include <openssl/x509v3.h>
25 
26 #include <vector>
27 
28 #include "webrtc/base/common.h"
29 #include "webrtc/base/logging.h"
30 #include "webrtc/base/safe_conversions.h"
31 #include "webrtc/base/stream.h"
32 #include "webrtc/base/openssl.h"
33 #include "webrtc/base/openssladapter.h"
34 #include "webrtc/base/openssldigest.h"
35 #include "webrtc/base/opensslidentity.h"
36 #include "webrtc/base/stringutils.h"
37 #include "webrtc/base/thread.h"
38 
39 namespace rtc {
40 
41 #if (OPENSSL_VERSION_NUMBER >= 0x10001000L)
42 #define HAVE_DTLS_SRTP
43 #endif
44 
45 #ifdef HAVE_DTLS_SRTP
46 // SRTP cipher suite table. |internal_name| is used to construct a
47 // colon-separated profile strings which is needed by
48 // SSL_CTX_set_tlsext_use_srtp().
49 struct SrtpCipherMapEntry {
50   const char* internal_name;
51   const int id;
52 };
53 
54 // This isn't elegant, but it's better than an external reference
55 static SrtpCipherMapEntry SrtpCipherMap[] = {
56     {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80},
57     {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32},
58     {nullptr, 0}};
59 #endif
60 
61 #ifndef OPENSSL_IS_BORINGSSL
62 
63 // Cipher name table. Maps internal OpenSSL cipher ids to the RFC name.
64 struct SslCipherMapEntry {
65   uint32_t openssl_id;
66   const char* rfc_name;
67 };
68 
69 #define DEFINE_CIPHER_ENTRY_SSL3(name)  {SSL3_CK_##name, "TLS_"#name}
70 #define DEFINE_CIPHER_ENTRY_TLS1(name)  {TLS1_CK_##name, "TLS_"#name}
71 
72 // There currently is no method available to get a RFC-compliant name for a
73 // cipher suite from BoringSSL, so we need to define the mapping manually here.
74 // This should go away once BoringSSL supports "SSL_CIPHER_standard_name"
75 // (as available in OpenSSL if compiled with tracing enabled) or a similar
76 // method.
77 static const SslCipherMapEntry kSslCipherMap[] = {
78   // TLS v1.0 ciphersuites from RFC2246.
79   DEFINE_CIPHER_ENTRY_SSL3(RSA_RC4_128_SHA),
80   {SSL3_CK_RSA_DES_192_CBC3_SHA,
81       "TLS_RSA_WITH_3DES_EDE_CBC_SHA"},
82 
83   // AES ciphersuites from RFC3268.
84   {TLS1_CK_RSA_WITH_AES_128_SHA,
85       "TLS_RSA_WITH_AES_128_CBC_SHA"},
86   {TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
87       "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
88   {TLS1_CK_RSA_WITH_AES_256_SHA,
89       "TLS_RSA_WITH_AES_256_CBC_SHA"},
90   {TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
91       "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
92 
93   // ECC ciphersuites from RFC4492.
94   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_RC4_128_SHA),
95   {TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA,
96       "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"},
97   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
98   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
99 
100   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_RC4_128_SHA),
101   {TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA,
102       "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"},
103   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_CBC_SHA),
104   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_CBC_SHA),
105 
106   // TLS v1.2 ciphersuites.
107   {TLS1_CK_RSA_WITH_AES_128_SHA256,
108       "TLS_RSA_WITH_AES_128_CBC_SHA256"},
109   {TLS1_CK_RSA_WITH_AES_256_SHA256,
110       "TLS_RSA_WITH_AES_256_CBC_SHA256"},
111   {TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
112       "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"},
113   {TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
114       "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"},
115 
116   // TLS v1.2 GCM ciphersuites from RFC5288.
117   DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_128_GCM_SHA256),
118   DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_256_GCM_SHA384),
119   DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_128_GCM_SHA256),
120   DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_256_GCM_SHA384),
121   DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_128_GCM_SHA256),
122   DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_256_GCM_SHA384),
123 
124   // ECDH HMAC based ciphersuites from RFC5289.
125   {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
126       "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"},
127   {TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
128       "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"},
129   {TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
130       "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"},
131   {TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
132       "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"},
133 
134   // ECDH GCM based ciphersuites from RFC5289.
135   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
136   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
137   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_GCM_SHA256),
138   DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_GCM_SHA384),
139 
140   {0, NULL}
141 };
142 #endif  // #ifndef OPENSSL_IS_BORINGSSL
143 
144 #if defined(_MSC_VER)
145 #pragma warning(push)
146 #pragma warning(disable : 4309)
147 #pragma warning(disable : 4310)
148 #endif  // defined(_MSC_VER)
149 
150 // Default cipher used between OpenSSL/BoringSSL stream adapters.
151 // This needs to be updated when the default of the SSL library changes.
152 // static_cast<uint16_t> causes build warnings on windows platform.
153 static int kDefaultSslCipher10 =
154     static_cast<uint16_t>(TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA);
155 static int kDefaultSslEcCipher10 =
156     static_cast<uint16_t>(TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
157 #ifdef OPENSSL_IS_BORINGSSL
158 static int kDefaultSslCipher12 =
159     static_cast<uint16_t>(TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
160 static int kDefaultSslEcCipher12 =
161     static_cast<uint16_t>(TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
162 // Fallback cipher for DTLS 1.2 if hardware-accelerated AES-GCM is unavailable.
163 // TODO(davidben): Switch to the standardized CHACHA20_POLY1305 variant when
164 // available.
165 static int kDefaultSslCipher12NoAesGcm =
166     static_cast<uint16_t>(TLS1_CK_ECDHE_RSA_CHACHA20_POLY1305_OLD);
167 static int kDefaultSslEcCipher12NoAesGcm =
168     static_cast<uint16_t>(TLS1_CK_ECDHE_ECDSA_CHACHA20_POLY1305_OLD);
169 #else  // !OPENSSL_IS_BORINGSSL
170 // OpenSSL sorts differently than BoringSSL, so the default cipher doesn't
171 // change between TLS 1.0 and TLS 1.2 with the current setup.
172 static int kDefaultSslCipher12 =
173     static_cast<uint16_t>(TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA);
174 static int kDefaultSslEcCipher12 =
175     static_cast<uint16_t>(TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
176 #endif
177 
178 #if defined(_MSC_VER)
179 #pragma warning(pop)
180 #endif  // defined(_MSC_VER)
181 
182 //////////////////////////////////////////////////////////////////////
183 // StreamBIO
184 //////////////////////////////////////////////////////////////////////
185 
186 static int stream_write(BIO* h, const char* buf, int num);
187 static int stream_read(BIO* h, char* buf, int size);
188 static int stream_puts(BIO* h, const char* str);
189 static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
190 static int stream_new(BIO* h);
191 static int stream_free(BIO* data);
192 
193 // TODO(davidben): This should be const once BoringSSL is assumed.
194 static BIO_METHOD methods_stream = {
195   BIO_TYPE_BIO,
196   "stream",
197   stream_write,
198   stream_read,
199   stream_puts,
200   0,
201   stream_ctrl,
202   stream_new,
203   stream_free,
204   NULL,
205 };
206 
BIO_s_stream()207 static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
208 
BIO_new_stream(StreamInterface * stream)209 static BIO* BIO_new_stream(StreamInterface* stream) {
210   BIO* ret = BIO_new(BIO_s_stream());
211   if (ret == NULL)
212     return NULL;
213   ret->ptr = stream;
214   return ret;
215 }
216 
217 // bio methods return 1 (or at least non-zero) on success and 0 on failure.
218 
stream_new(BIO * b)219 static int stream_new(BIO* b) {
220   b->shutdown = 0;
221   b->init = 1;
222   b->num = 0;  // 1 means end-of-stream
223   b->ptr = 0;
224   return 1;
225 }
226 
stream_free(BIO * b)227 static int stream_free(BIO* b) {
228   if (b == NULL)
229     return 0;
230   return 1;
231 }
232 
stream_read(BIO * b,char * out,int outl)233 static int stream_read(BIO* b, char* out, int outl) {
234   if (!out)
235     return -1;
236   StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
237   BIO_clear_retry_flags(b);
238   size_t read;
239   int error;
240   StreamResult result = stream->Read(out, outl, &read, &error);
241   if (result == SR_SUCCESS) {
242     return checked_cast<int>(read);
243   } else if (result == SR_EOS) {
244     b->num = 1;
245   } else if (result == SR_BLOCK) {
246     BIO_set_retry_read(b);
247   }
248   return -1;
249 }
250 
stream_write(BIO * b,const char * in,int inl)251 static int stream_write(BIO* b, const char* in, int inl) {
252   if (!in)
253     return -1;
254   StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
255   BIO_clear_retry_flags(b);
256   size_t written;
257   int error;
258   StreamResult result = stream->Write(in, inl, &written, &error);
259   if (result == SR_SUCCESS) {
260     return checked_cast<int>(written);
261   } else if (result == SR_BLOCK) {
262     BIO_set_retry_write(b);
263   }
264   return -1;
265 }
266 
stream_puts(BIO * b,const char * str)267 static int stream_puts(BIO* b, const char* str) {
268   return stream_write(b, str, checked_cast<int>(strlen(str)));
269 }
270 
stream_ctrl(BIO * b,int cmd,long num,void * ptr)271 static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
272   RTC_UNUSED(num);
273   RTC_UNUSED(ptr);
274 
275   switch (cmd) {
276     case BIO_CTRL_RESET:
277       return 0;
278     case BIO_CTRL_EOF:
279       return b->num;
280     case BIO_CTRL_WPENDING:
281     case BIO_CTRL_PENDING:
282       return 0;
283     case BIO_CTRL_FLUSH:
284       return 1;
285     case BIO_CTRL_DGRAM_QUERY_MTU:
286       // openssl defaults to mtu=256 unless we return something here.
287       // The handshake doesn't actually need to send packets above 1k,
288       // so this seems like a sensible value that should work in most cases.
289       // Webrtc uses the same value for video packets.
290       return 1200;
291     default:
292       return 0;
293   }
294 }
295 
296 /////////////////////////////////////////////////////////////////////////////
297 // OpenSSLStreamAdapter
298 /////////////////////////////////////////////////////////////////////////////
299 
OpenSSLStreamAdapter(StreamInterface * stream)300 OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
301     : SSLStreamAdapter(stream),
302       state_(SSL_NONE),
303       role_(SSL_CLIENT),
304       ssl_read_needs_write_(false),
305       ssl_write_needs_read_(false),
306       ssl_(NULL),
307       ssl_ctx_(NULL),
308       custom_verification_succeeded_(false),
309       ssl_mode_(SSL_MODE_TLS),
310       ssl_max_version_(SSL_PROTOCOL_TLS_12) {}
311 
~OpenSSLStreamAdapter()312 OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
313   Cleanup();
314 }
315 
SetIdentity(SSLIdentity * identity)316 void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
317   ASSERT(!identity_);
318   identity_.reset(static_cast<OpenSSLIdentity*>(identity));
319 }
320 
SetServerRole(SSLRole role)321 void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
322   role_ = role;
323 }
324 
GetPeerCertificate(SSLCertificate ** cert) const325 bool OpenSSLStreamAdapter::GetPeerCertificate(SSLCertificate** cert) const {
326   if (!peer_certificate_)
327     return false;
328 
329   *cert = peer_certificate_->GetReference();
330   return true;
331 }
332 
SetPeerCertificateDigest(const std::string & digest_alg,const unsigned char * digest_val,size_t digest_len)333 bool OpenSSLStreamAdapter::SetPeerCertificateDigest(const std::string
334                                                     &digest_alg,
335                                                     const unsigned char*
336                                                     digest_val,
337                                                     size_t digest_len) {
338   ASSERT(!peer_certificate_);
339   ASSERT(peer_certificate_digest_algorithm_.size() == 0);
340   ASSERT(ssl_server_name_.empty());
341   size_t expected_len;
342 
343   if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
344     LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
345     return false;
346   }
347   if (expected_len != digest_len)
348     return false;
349 
350   peer_certificate_digest_value_.SetData(digest_val, digest_len);
351   peer_certificate_digest_algorithm_ = digest_alg;
352 
353   return true;
354 }
355 
SslCipherSuiteToName(int cipher_suite)356 std::string OpenSSLStreamAdapter::SslCipherSuiteToName(int cipher_suite) {
357 #ifdef OPENSSL_IS_BORINGSSL
358   const SSL_CIPHER* ssl_cipher = SSL_get_cipher_by_value(cipher_suite);
359   if (!ssl_cipher) {
360     return std::string();
361   }
362   char* cipher_name = SSL_CIPHER_get_rfc_name(ssl_cipher);
363   std::string rfc_name = std::string(cipher_name);
364   OPENSSL_free(cipher_name);
365   return rfc_name;
366 #else
367   for (const SslCipherMapEntry* entry = kSslCipherMap; entry->rfc_name;
368        ++entry) {
369     if (cipher_suite == static_cast<int>(entry->openssl_id)) {
370       return entry->rfc_name;
371     }
372   }
373   return std::string();
374 #endif
375 }
376 
GetSslCipherSuite(int * cipher_suite)377 bool OpenSSLStreamAdapter::GetSslCipherSuite(int* cipher_suite) {
378   if (state_ != SSL_CONNECTED)
379     return false;
380 
381   const SSL_CIPHER* current_cipher = SSL_get_current_cipher(ssl_);
382   if (current_cipher == NULL) {
383     return false;
384   }
385 
386   *cipher_suite = static_cast<uint16_t>(SSL_CIPHER_get_id(current_cipher));
387   return true;
388 }
389 
390 // Key Extractor interface
ExportKeyingMaterial(const std::string & label,const uint8_t * context,size_t context_len,bool use_context,uint8_t * result,size_t result_len)391 bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
392                                                 const uint8_t* context,
393                                                 size_t context_len,
394                                                 bool use_context,
395                                                 uint8_t* result,
396                                                 size_t result_len) {
397 #ifdef HAVE_DTLS_SRTP
398   int i;
399 
400   i = SSL_export_keying_material(ssl_, result, result_len, label.c_str(),
401                                  label.length(), const_cast<uint8_t*>(context),
402                                  context_len, use_context);
403 
404   if (i != 1)
405     return false;
406 
407   return true;
408 #else
409   return false;
410 #endif
411 }
412 
SetDtlsSrtpCryptoSuites(const std::vector<int> & ciphers)413 bool OpenSSLStreamAdapter::SetDtlsSrtpCryptoSuites(
414     const std::vector<int>& ciphers) {
415 #ifdef HAVE_DTLS_SRTP
416   std::string internal_ciphers;
417 
418   if (state_ != SSL_NONE)
419     return false;
420 
421   for (std::vector<int>::const_iterator cipher = ciphers.begin();
422        cipher != ciphers.end(); ++cipher) {
423     bool found = false;
424     for (SrtpCipherMapEntry* entry = SrtpCipherMap; entry->internal_name;
425          ++entry) {
426       if (*cipher == entry->id) {
427         found = true;
428         if (!internal_ciphers.empty())
429           internal_ciphers += ":";
430         internal_ciphers += entry->internal_name;
431         break;
432       }
433     }
434 
435     if (!found) {
436       LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
437       return false;
438     }
439   }
440 
441   if (internal_ciphers.empty())
442     return false;
443 
444   srtp_ciphers_ = internal_ciphers;
445   return true;
446 #else
447   return false;
448 #endif
449 }
450 
GetDtlsSrtpCryptoSuite(int * crypto_suite)451 bool OpenSSLStreamAdapter::GetDtlsSrtpCryptoSuite(int* crypto_suite) {
452 #ifdef HAVE_DTLS_SRTP
453   ASSERT(state_ == SSL_CONNECTED);
454   if (state_ != SSL_CONNECTED)
455     return false;
456 
457   const SRTP_PROTECTION_PROFILE *srtp_profile =
458       SSL_get_selected_srtp_profile(ssl_);
459 
460   if (!srtp_profile)
461     return false;
462 
463   *crypto_suite = srtp_profile->id;
464   ASSERT(!SrtpCryptoSuiteToName(*crypto_suite).empty());
465   return true;
466 #else
467   return false;
468 #endif
469 }
470 
StartSSLWithServer(const char * server_name)471 int OpenSSLStreamAdapter::StartSSLWithServer(const char* server_name) {
472   ASSERT(server_name != NULL && server_name[0] != '\0');
473   ssl_server_name_ = server_name;
474   return StartSSL();
475 }
476 
StartSSLWithPeer()477 int OpenSSLStreamAdapter::StartSSLWithPeer() {
478   ASSERT(ssl_server_name_.empty());
479   // It is permitted to specify peer_certificate_ only later.
480   return StartSSL();
481 }
482 
SetMode(SSLMode mode)483 void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
484   ASSERT(state_ == SSL_NONE);
485   ssl_mode_ = mode;
486 }
487 
SetMaxProtocolVersion(SSLProtocolVersion version)488 void OpenSSLStreamAdapter::SetMaxProtocolVersion(SSLProtocolVersion version) {
489   ASSERT(ssl_ctx_ == NULL);
490   ssl_max_version_ = version;
491 }
492 
493 //
494 // StreamInterface Implementation
495 //
496 
Write(const void * data,size_t data_len,size_t * written,int * error)497 StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
498                                          size_t* written, int* error) {
499   LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
500 
501   switch (state_) {
502   case SSL_NONE:
503     // pass-through in clear text
504     return StreamAdapterInterface::Write(data, data_len, written, error);
505 
506   case SSL_WAIT:
507   case SSL_CONNECTING:
508     return SR_BLOCK;
509 
510   case SSL_CONNECTED:
511     break;
512 
513   case SSL_ERROR:
514   case SSL_CLOSED:
515   default:
516     if (error)
517       *error = ssl_error_code_;
518     return SR_ERROR;
519   }
520 
521   // OpenSSL will return an error if we try to write zero bytes
522   if (data_len == 0) {
523     if (written)
524       *written = 0;
525     return SR_SUCCESS;
526   }
527 
528   ssl_write_needs_read_ = false;
529 
530   int code = SSL_write(ssl_, data, checked_cast<int>(data_len));
531   int ssl_error = SSL_get_error(ssl_, code);
532   switch (ssl_error) {
533   case SSL_ERROR_NONE:
534     LOG(LS_VERBOSE) << " -- success";
535     ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
536     if (written)
537       *written = code;
538     return SR_SUCCESS;
539   case SSL_ERROR_WANT_READ:
540     LOG(LS_VERBOSE) << " -- error want read";
541     ssl_write_needs_read_ = true;
542     return SR_BLOCK;
543   case SSL_ERROR_WANT_WRITE:
544     LOG(LS_VERBOSE) << " -- error want write";
545     return SR_BLOCK;
546 
547   case SSL_ERROR_ZERO_RETURN:
548   default:
549     Error("SSL_write", (ssl_error ? ssl_error : -1), false);
550     if (error)
551       *error = ssl_error_code_;
552     return SR_ERROR;
553   }
554   // not reached
555 }
556 
Read(void * data,size_t data_len,size_t * read,int * error)557 StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
558                                         size_t* read, int* error) {
559   LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
560   switch (state_) {
561     case SSL_NONE:
562       // pass-through in clear text
563       return StreamAdapterInterface::Read(data, data_len, read, error);
564 
565     case SSL_WAIT:
566     case SSL_CONNECTING:
567       return SR_BLOCK;
568 
569     case SSL_CONNECTED:
570       break;
571 
572     case SSL_CLOSED:
573       return SR_EOS;
574 
575     case SSL_ERROR:
576     default:
577       if (error)
578         *error = ssl_error_code_;
579       return SR_ERROR;
580   }
581 
582   // Don't trust OpenSSL with zero byte reads
583   if (data_len == 0) {
584     if (read)
585       *read = 0;
586     return SR_SUCCESS;
587   }
588 
589   ssl_read_needs_write_ = false;
590 
591   int code = SSL_read(ssl_, data, checked_cast<int>(data_len));
592   int ssl_error = SSL_get_error(ssl_, code);
593   switch (ssl_error) {
594     case SSL_ERROR_NONE:
595       LOG(LS_VERBOSE) << " -- success";
596       ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
597       if (read)
598         *read = code;
599 
600       if (ssl_mode_ == SSL_MODE_DTLS) {
601         // Enforce atomic reads -- this is a short read
602         unsigned int pending = SSL_pending(ssl_);
603 
604         if (pending) {
605           LOG(LS_INFO) << " -- short DTLS read. flushing";
606           FlushInput(pending);
607           if (error)
608             *error = SSE_MSG_TRUNC;
609           return SR_ERROR;
610         }
611       }
612       return SR_SUCCESS;
613     case SSL_ERROR_WANT_READ:
614       LOG(LS_VERBOSE) << " -- error want read";
615       return SR_BLOCK;
616     case SSL_ERROR_WANT_WRITE:
617       LOG(LS_VERBOSE) << " -- error want write";
618       ssl_read_needs_write_ = true;
619       return SR_BLOCK;
620     case SSL_ERROR_ZERO_RETURN:
621       LOG(LS_VERBOSE) << " -- remote side closed";
622       return SR_EOS;
623       break;
624     default:
625       LOG(LS_VERBOSE) << " -- error " << code;
626       Error("SSL_read", (ssl_error ? ssl_error : -1), false);
627       if (error)
628         *error = ssl_error_code_;
629       return SR_ERROR;
630   }
631   // not reached
632 }
633 
FlushInput(unsigned int left)634 void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
635   unsigned char buf[2048];
636 
637   while (left) {
638     // This should always succeed
639     int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
640     int code = SSL_read(ssl_, buf, toread);
641 
642     int ssl_error = SSL_get_error(ssl_, code);
643     ASSERT(ssl_error == SSL_ERROR_NONE);
644 
645     if (ssl_error != SSL_ERROR_NONE) {
646       LOG(LS_VERBOSE) << " -- error " << code;
647       Error("SSL_read", (ssl_error ? ssl_error : -1), false);
648       return;
649     }
650 
651     LOG(LS_VERBOSE) << " -- flushed " << code << " bytes";
652     left -= code;
653   }
654 }
655 
Close()656 void OpenSSLStreamAdapter::Close() {
657   Cleanup();
658   ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
659   StreamAdapterInterface::Close();
660 }
661 
GetState() const662 StreamState OpenSSLStreamAdapter::GetState() const {
663   switch (state_) {
664     case SSL_WAIT:
665     case SSL_CONNECTING:
666       return SS_OPENING;
667     case SSL_CONNECTED:
668       return SS_OPEN;
669     default:
670       return SS_CLOSED;
671   };
672   // not reached
673 }
674 
OnEvent(StreamInterface * stream,int events,int err)675 void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
676                                    int err) {
677   int events_to_signal = 0;
678   int signal_error = 0;
679   ASSERT(stream == this->stream());
680   if ((events & SE_OPEN)) {
681     LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
682     if (state_ != SSL_WAIT) {
683       ASSERT(state_ == SSL_NONE);
684       events_to_signal |= SE_OPEN;
685     } else {
686       state_ = SSL_CONNECTING;
687       if (int err = BeginSSL()) {
688         Error("BeginSSL", err, true);
689         return;
690       }
691     }
692   }
693   if ((events & (SE_READ|SE_WRITE))) {
694     LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent"
695                  << ((events & SE_READ) ? " SE_READ" : "")
696                  << ((events & SE_WRITE) ? " SE_WRITE" : "");
697     if (state_ == SSL_NONE) {
698       events_to_signal |= events & (SE_READ|SE_WRITE);
699     } else if (state_ == SSL_CONNECTING) {
700       if (int err = ContinueSSL()) {
701         Error("ContinueSSL", err, true);
702         return;
703       }
704     } else if (state_ == SSL_CONNECTED) {
705       if (((events & SE_READ) && ssl_write_needs_read_) ||
706           (events & SE_WRITE)) {
707         LOG(LS_VERBOSE) << " -- onStreamWriteable";
708         events_to_signal |= SE_WRITE;
709       }
710       if (((events & SE_WRITE) && ssl_read_needs_write_) ||
711           (events & SE_READ)) {
712         LOG(LS_VERBOSE) << " -- onStreamReadable";
713         events_to_signal |= SE_READ;
714       }
715     }
716   }
717   if ((events & SE_CLOSE)) {
718     LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
719     Cleanup();
720     events_to_signal |= SE_CLOSE;
721     // SE_CLOSE is the only event that uses the final parameter to OnEvent().
722     ASSERT(signal_error == 0);
723     signal_error = err;
724   }
725   if (events_to_signal)
726     StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
727 }
728 
StartSSL()729 int OpenSSLStreamAdapter::StartSSL() {
730   ASSERT(state_ == SSL_NONE);
731 
732   if (StreamAdapterInterface::GetState() != SS_OPEN) {
733     state_ = SSL_WAIT;
734     return 0;
735   }
736 
737   state_ = SSL_CONNECTING;
738   if (int err = BeginSSL()) {
739     Error("BeginSSL", err, false);
740     return err;
741   }
742 
743   return 0;
744 }
745 
BeginSSL()746 int OpenSSLStreamAdapter::BeginSSL() {
747   ASSERT(state_ == SSL_CONNECTING);
748   // The underlying stream has open. If we are in peer-to-peer mode
749   // then a peer certificate must have been specified by now.
750   ASSERT(!ssl_server_name_.empty() ||
751          !peer_certificate_digest_algorithm_.empty());
752   LOG(LS_INFO) << "BeginSSL: "
753                << (!ssl_server_name_.empty() ? ssl_server_name_ :
754                                                "with peer");
755 
756   BIO* bio = NULL;
757 
758   // First set up the context
759   ASSERT(ssl_ctx_ == NULL);
760   ssl_ctx_ = SetupSSLContext();
761   if (!ssl_ctx_)
762     return -1;
763 
764   bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
765   if (!bio)
766     return -1;
767 
768   ssl_ = SSL_new(ssl_ctx_);
769   if (!ssl_) {
770     BIO_free(bio);
771     return -1;
772   }
773 
774   SSL_set_app_data(ssl_, this);
775 
776   SSL_set_bio(ssl_, bio, bio);  // the SSL object owns the bio now.
777 #ifndef OPENSSL_IS_BORINGSSL
778   if (ssl_mode_ == SSL_MODE_DTLS) {
779     // Enable read-ahead for DTLS so whole packets are read from internal BIO
780     // before parsing. This is done internally by BoringSSL for DTLS.
781     SSL_set_read_ahead(ssl_, 1);
782   }
783 #endif
784 
785   SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
786                SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
787 
788   // Specify an ECDH group for ECDHE ciphers, otherwise they cannot be
789   // negotiated when acting as the server. Use NIST's P-256 which is commonly
790   // supported.
791   EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
792   if (ecdh == NULL)
793     return -1;
794   SSL_set_options(ssl_, SSL_OP_SINGLE_ECDH_USE);
795   SSL_set_tmp_ecdh(ssl_, ecdh);
796   EC_KEY_free(ecdh);
797 
798   // Do the connect
799   return ContinueSSL();
800 }
801 
ContinueSSL()802 int OpenSSLStreamAdapter::ContinueSSL() {
803   LOG(LS_VERBOSE) << "ContinueSSL";
804   ASSERT(state_ == SSL_CONNECTING);
805 
806   // Clear the DTLS timer
807   Thread::Current()->Clear(this, MSG_TIMEOUT);
808 
809   int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
810   int ssl_error;
811   switch (ssl_error = SSL_get_error(ssl_, code)) {
812     case SSL_ERROR_NONE:
813       LOG(LS_VERBOSE) << " -- success";
814 
815       if (!SSLPostConnectionCheck(ssl_, ssl_server_name_.c_str(), NULL,
816                                   peer_certificate_digest_algorithm_)) {
817         LOG(LS_ERROR) << "TLS post connection check failed";
818         return -1;
819       }
820 
821       state_ = SSL_CONNECTED;
822       StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
823       break;
824 
825     case SSL_ERROR_WANT_READ: {
826         LOG(LS_VERBOSE) << " -- error want read";
827         struct timeval timeout;
828         if (DTLSv1_get_timeout(ssl_, &timeout)) {
829           int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
830 
831           Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
832         }
833       }
834       break;
835 
836     case SSL_ERROR_WANT_WRITE:
837       LOG(LS_VERBOSE) << " -- error want write";
838       break;
839 
840     case SSL_ERROR_ZERO_RETURN:
841     default:
842       LOG(LS_VERBOSE) << " -- error " << code;
843       return (ssl_error != 0) ? ssl_error : -1;
844   }
845 
846   return 0;
847 }
848 
Error(const char * context,int err,bool signal)849 void OpenSSLStreamAdapter::Error(const char* context, int err, bool signal) {
850   LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error("
851                   << context << ", " << err << ")";
852   state_ = SSL_ERROR;
853   ssl_error_code_ = err;
854   Cleanup();
855   if (signal)
856     StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
857 }
858 
Cleanup()859 void OpenSSLStreamAdapter::Cleanup() {
860   LOG(LS_INFO) << "Cleanup";
861 
862   if (state_ != SSL_ERROR) {
863     state_ = SSL_CLOSED;
864     ssl_error_code_ = 0;
865   }
866 
867   if (ssl_) {
868     int ret = SSL_shutdown(ssl_);
869     if (ret < 0) {
870       LOG(LS_WARNING) << "SSL_shutdown failed, error = "
871                       << SSL_get_error(ssl_, ret);
872     }
873 
874     SSL_free(ssl_);
875     ssl_ = NULL;
876   }
877   if (ssl_ctx_) {
878     SSL_CTX_free(ssl_ctx_);
879     ssl_ctx_ = NULL;
880   }
881   identity_.reset();
882   peer_certificate_.reset();
883 
884   // Clear the DTLS timer
885   Thread::Current()->Clear(this, MSG_TIMEOUT);
886 }
887 
888 
OnMessage(Message * msg)889 void OpenSSLStreamAdapter::OnMessage(Message* msg) {
890   // Process our own messages and then pass others to the superclass
891   if (MSG_TIMEOUT == msg->message_id) {
892     LOG(LS_INFO) << "DTLS timeout expired";
893     DTLSv1_handle_timeout(ssl_);
894     ContinueSSL();
895   } else {
896     StreamInterface::OnMessage(msg);
897   }
898 }
899 
SetupSSLContext()900 SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
901   SSL_CTX *ctx = NULL;
902 
903 #ifdef OPENSSL_IS_BORINGSSL
904     ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
905         DTLS_method() : TLS_method());
906     // Version limiting for BoringSSL will be done below.
907 #else
908   const SSL_METHOD* method;
909   switch (ssl_max_version_) {
910     case SSL_PROTOCOL_TLS_10:
911     case SSL_PROTOCOL_TLS_11:
912       // OpenSSL doesn't support setting min/max versions, so we always use
913       // (D)TLS 1.0 if a max. version below the max. available is requested.
914       if (ssl_mode_ == SSL_MODE_DTLS) {
915         if (role_ == SSL_CLIENT) {
916           method = DTLSv1_client_method();
917         } else {
918           method = DTLSv1_server_method();
919         }
920       } else {
921         if (role_ == SSL_CLIENT) {
922           method = TLSv1_client_method();
923         } else {
924           method = TLSv1_server_method();
925         }
926       }
927       break;
928     case SSL_PROTOCOL_TLS_12:
929     default:
930       if (ssl_mode_ == SSL_MODE_DTLS) {
931 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L)
932         // DTLS 1.2 only available starting from OpenSSL 1.0.2
933         if (role_ == SSL_CLIENT) {
934           method = DTLS_client_method();
935         } else {
936           method = DTLS_server_method();
937         }
938 #else
939         if (role_ == SSL_CLIENT) {
940           method = DTLSv1_client_method();
941         } else {
942           method = DTLSv1_server_method();
943         }
944 #endif
945       } else {
946 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
947         // New API only available starting from OpenSSL 1.1.0
948         if (role_ == SSL_CLIENT) {
949           method = TLS_client_method();
950         } else {
951           method = TLS_server_method();
952         }
953 #else
954         if (role_ == SSL_CLIENT) {
955           method = SSLv23_client_method();
956         } else {
957           method = SSLv23_server_method();
958         }
959 #endif
960       }
961       break;
962   }
963   ctx = SSL_CTX_new(method);
964 #endif  // OPENSSL_IS_BORINGSSL
965 
966   if (ctx == NULL)
967     return NULL;
968 
969 #ifdef OPENSSL_IS_BORINGSSL
970   SSL_CTX_set_min_proto_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
971       DTLS1_VERSION : TLS1_VERSION);
972   switch (ssl_max_version_) {
973     case SSL_PROTOCOL_TLS_10:
974       SSL_CTX_set_max_proto_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
975           DTLS1_VERSION : TLS1_VERSION);
976       break;
977     case SSL_PROTOCOL_TLS_11:
978       SSL_CTX_set_max_proto_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
979           DTLS1_VERSION : TLS1_1_VERSION);
980       break;
981     case SSL_PROTOCOL_TLS_12:
982     default:
983       SSL_CTX_set_max_proto_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
984           DTLS1_2_VERSION : TLS1_2_VERSION);
985       break;
986   }
987 #endif
988 
989   if (identity_ && !identity_->ConfigureIdentity(ctx)) {
990     SSL_CTX_free(ctx);
991     return NULL;
992   }
993 
994 #if !defined(NDEBUG)
995   SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
996 #endif
997 
998   int mode = SSL_VERIFY_PEER;
999   if (client_auth_enabled()) {
1000     // Require a certificate from the client.
1001     // Note: Normally this is always true in production, but it may be disabled
1002     // for testing purposes (e.g. SSLAdapter unit tests).
1003     mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1004   }
1005 
1006   SSL_CTX_set_verify(ctx, mode, SSLVerifyCallback);
1007   SSL_CTX_set_verify_depth(ctx, 4);
1008   // Select list of available ciphers. Note that !SHA256 and !SHA384 only
1009   // remove HMAC-SHA256 and HMAC-SHA384 cipher suites, not GCM cipher suites
1010   // with SHA256 or SHA384 as the handshake hash.
1011   // This matches the list of SSLClientSocketOpenSSL in Chromium.
1012   SSL_CTX_set_cipher_list(ctx,
1013       "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
1014 
1015 #ifdef HAVE_DTLS_SRTP
1016   if (!srtp_ciphers_.empty()) {
1017     if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
1018       SSL_CTX_free(ctx);
1019       return NULL;
1020     }
1021   }
1022 #endif
1023 
1024   return ctx;
1025 }
1026 
SSLVerifyCallback(int ok,X509_STORE_CTX * store)1027 int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
1028   // Get our SSL structure from the store
1029   SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
1030                                         store,
1031                                         SSL_get_ex_data_X509_STORE_CTX_idx()));
1032   OpenSSLStreamAdapter* stream =
1033     reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
1034 
1035   if (stream->peer_certificate_digest_algorithm_.empty()) {
1036     return 0;
1037   }
1038   X509* cert = X509_STORE_CTX_get_current_cert(store);
1039   int depth = X509_STORE_CTX_get_error_depth(store);
1040 
1041   // For now We ignore the parent certificates and verify the leaf against
1042   // the digest.
1043   //
1044   // TODO(jiayl): Verify the chain is a proper chain and report the chain to
1045   // |stream->peer_certificate_|.
1046   if (depth > 0) {
1047     LOG(LS_INFO) << "Ignored chained certificate at depth " << depth;
1048     return 1;
1049   }
1050 
1051   unsigned char digest[EVP_MAX_MD_SIZE];
1052   size_t digest_length;
1053   if (!OpenSSLCertificate::ComputeDigest(
1054            cert,
1055            stream->peer_certificate_digest_algorithm_,
1056            digest, sizeof(digest),
1057            &digest_length)) {
1058     LOG(LS_WARNING) << "Failed to compute peer cert digest.";
1059     return 0;
1060   }
1061 
1062   Buffer computed_digest(digest, digest_length);
1063   if (computed_digest != stream->peer_certificate_digest_value_) {
1064     LOG(LS_WARNING) << "Rejected peer certificate due to mismatched digest.";
1065     return 0;
1066   }
1067   // Ignore any verification error if the digest matches, since there is no
1068   // value in checking the validity of a self-signed cert issued by untrusted
1069   // sources.
1070   LOG(LS_INFO) << "Accepted peer certificate.";
1071 
1072   // Record the peer's certificate.
1073   stream->peer_certificate_.reset(new OpenSSLCertificate(cert));
1074   return 1;
1075 }
1076 
1077 // This code is taken from the "Network Security with OpenSSL"
1078 // sample in chapter 5
SSLPostConnectionCheck(SSL * ssl,const char * server_name,const X509 * peer_cert,const std::string & peer_digest)1079 bool OpenSSLStreamAdapter::SSLPostConnectionCheck(SSL* ssl,
1080                                                   const char* server_name,
1081                                                   const X509* peer_cert,
1082                                                   const std::string
1083                                                   &peer_digest) {
1084   ASSERT(server_name != NULL);
1085   bool ok;
1086   if (server_name[0] != '\0') {  // traditional mode
1087     ok = OpenSSLAdapter::VerifyServerName(ssl, server_name, ignore_bad_cert());
1088 
1089     if (ok) {
1090       ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
1091             custom_verification_succeeded_);
1092     }
1093   } else {  // peer-to-peer mode
1094     ASSERT((peer_cert != NULL) || (!peer_digest.empty()));
1095     // no server name validation
1096     ok = true;
1097   }
1098 
1099   if (!ok && ignore_bad_cert()) {
1100     LOG(LS_ERROR) << "SSL_get_verify_result(ssl) = "
1101                   << SSL_get_verify_result(ssl);
1102     LOG(LS_INFO) << "Other TLS post connection checks failed.";
1103     ok = true;
1104   }
1105 
1106   return ok;
1107 }
1108 
HaveDtls()1109 bool OpenSSLStreamAdapter::HaveDtls() {
1110   return true;
1111 }
1112 
HaveDtlsSrtp()1113 bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
1114 #ifdef HAVE_DTLS_SRTP
1115   return true;
1116 #else
1117   return false;
1118 #endif
1119 }
1120 
HaveExporter()1121 bool OpenSSLStreamAdapter::HaveExporter() {
1122 #ifdef HAVE_DTLS_SRTP
1123   return true;
1124 #else
1125   return false;
1126 #endif
1127 }
1128 
GetDefaultSslCipherForTest(SSLProtocolVersion version,KeyType key_type)1129 int OpenSSLStreamAdapter::GetDefaultSslCipherForTest(SSLProtocolVersion version,
1130                                                      KeyType key_type) {
1131   if (key_type == KT_RSA) {
1132     switch (version) {
1133       case SSL_PROTOCOL_TLS_10:
1134       case SSL_PROTOCOL_TLS_11:
1135         return kDefaultSslCipher10;
1136       case SSL_PROTOCOL_TLS_12:
1137       default:
1138 #ifdef OPENSSL_IS_BORINGSSL
1139         if (EVP_has_aes_hardware()) {
1140           return kDefaultSslCipher12;
1141         } else {
1142           return kDefaultSslCipher12NoAesGcm;
1143         }
1144 #else  // !OPENSSL_IS_BORINGSSL
1145         return kDefaultSslCipher12;
1146 #endif
1147     }
1148   } else if (key_type == KT_ECDSA) {
1149     switch (version) {
1150       case SSL_PROTOCOL_TLS_10:
1151       case SSL_PROTOCOL_TLS_11:
1152         return kDefaultSslEcCipher10;
1153       case SSL_PROTOCOL_TLS_12:
1154       default:
1155 #ifdef OPENSSL_IS_BORINGSSL
1156         if (EVP_has_aes_hardware()) {
1157           return kDefaultSslEcCipher12;
1158         } else {
1159           return kDefaultSslEcCipher12NoAesGcm;
1160         }
1161 #else  // !OPENSSL_IS_BORINGSSL
1162         return kDefaultSslEcCipher12;
1163 #endif
1164     }
1165   } else {
1166     RTC_NOTREACHED();
1167     return kDefaultSslEcCipher12;
1168   }
1169 }
1170 
1171 }  // namespace rtc
1172 
1173 #endif  // HAVE_OPENSSL_SSL_H
1174