• 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 #include "rtc_base/openssl_stream_adapter.h"
12 
13 #include <openssl/bio.h>
14 #include <openssl/crypto.h>
15 #include <openssl/err.h>
16 #include <openssl/rand.h>
17 #include <openssl/tls1.h>
18 #include <openssl/x509v3.h>
19 #ifndef OPENSSL_IS_BORINGSSL
20 #include <openssl/dtls1.h>
21 #include <openssl/ssl.h>
22 #endif
23 
24 #include <memory>
25 #include <utility>
26 #include <vector>
27 
28 #include "rtc_base/checks.h"
29 #include "rtc_base/logging.h"
30 #include "rtc_base/numerics/safe_conversions.h"
31 #include "rtc_base/openssl.h"
32 #include "rtc_base/openssl_adapter.h"
33 #include "rtc_base/openssl_digest.h"
34 #include "rtc_base/openssl_identity.h"
35 #include "rtc_base/ssl_certificate.h"
36 #include "rtc_base/stream.h"
37 #include "rtc_base/thread.h"
38 #include "rtc_base/time_utils.h"
39 #include "system_wrappers/include/field_trial.h"
40 
41 #if (OPENSSL_VERSION_NUMBER < 0x10100000L)
42 #error "webrtc requires at least OpenSSL version 1.1.0, to support DTLS-SRTP"
43 #endif
44 
45 // Defines for the TLS Cipher Suite Map.
46 #define DEFINE_CIPHER_ENTRY_SSL3(name) \
47   { SSL3_CK_##name, "TLS_" #name }
48 #define DEFINE_CIPHER_ENTRY_TLS1(name) \
49   { TLS1_CK_##name, "TLS_" #name }
50 
51 namespace rtc {
52 namespace {
53 
54 // SRTP cipher suite table. |internal_name| is used to construct a
55 // colon-separated profile strings which is needed by
56 // SSL_CTX_set_tlsext_use_srtp().
57 struct SrtpCipherMapEntry {
58   const char* internal_name;
59   const int id;
60 };
61 
62 // Cipher name table. Maps internal OpenSSL cipher ids to the RFC name.
63 struct SslCipherMapEntry {
64   uint32_t openssl_id;
65   const char* rfc_name;
66 };
67 
68 // This isn't elegant, but it's better than an external reference
69 constexpr SrtpCipherMapEntry kSrtpCipherMap[] = {
70     {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80},
71     {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32},
72     {"SRTP_AEAD_AES_128_GCM", SRTP_AEAD_AES_128_GCM},
73     {"SRTP_AEAD_AES_256_GCM", SRTP_AEAD_AES_256_GCM}};
74 
75 #ifndef OPENSSL_IS_BORINGSSL
76 // The "SSL_CIPHER_standard_name" function is only available in OpenSSL when
77 // compiled with tracing, so we need to define the mapping manually here.
78 constexpr SslCipherMapEntry kSslCipherMap[] = {
79     // TLS v1.0 ciphersuites from RFC2246.
80     DEFINE_CIPHER_ENTRY_SSL3(RSA_RC4_128_SHA),
81     {SSL3_CK_RSA_DES_192_CBC3_SHA, "TLS_RSA_WITH_3DES_EDE_CBC_SHA"},
82 
83     // AES ciphersuites from RFC3268.
84     {TLS1_CK_RSA_WITH_AES_128_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA"},
85     {TLS1_CK_DHE_RSA_WITH_AES_128_SHA, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
86     {TLS1_CK_RSA_WITH_AES_256_SHA, "TLS_RSA_WITH_AES_256_CBC_SHA"},
87     {TLS1_CK_DHE_RSA_WITH_AES_256_SHA, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
88 
89     // ECC ciphersuites from RFC4492.
90     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_RC4_128_SHA),
91     {TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA,
92      "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"},
93     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
94     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
95 
96     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_RC4_128_SHA),
97     {TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA,
98      "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"},
99     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_CBC_SHA),
100     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_CBC_SHA),
101 
102     // TLS v1.2 ciphersuites.
103     {TLS1_CK_RSA_WITH_AES_128_SHA256, "TLS_RSA_WITH_AES_128_CBC_SHA256"},
104     {TLS1_CK_RSA_WITH_AES_256_SHA256, "TLS_RSA_WITH_AES_256_CBC_SHA256"},
105     {TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
106      "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"},
107     {TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
108      "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"},
109 
110     // TLS v1.2 GCM ciphersuites from RFC5288.
111     DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_128_GCM_SHA256),
112     DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_256_GCM_SHA384),
113     DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_128_GCM_SHA256),
114     DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_256_GCM_SHA384),
115     DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_128_GCM_SHA256),
116     DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_256_GCM_SHA384),
117 
118     // ECDH HMAC based ciphersuites from RFC5289.
119     {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
120      "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"},
121     {TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
122      "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"},
123     {TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
124      "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"},
125     {TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
126      "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"},
127 
128     // ECDH GCM based ciphersuites from RFC5289.
129     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
130     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
131     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_GCM_SHA256),
132     DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_GCM_SHA384),
133 
134     {0, nullptr}};
135 #endif  // #ifndef OPENSSL_IS_BORINGSSL
136 
137 #ifdef OPENSSL_IS_BORINGSSL
138 // Enabled by EnableTimeCallbackForTesting. Should never be set in production
139 // code.
140 bool g_use_time_callback_for_testing = false;
141 // Not used in production code. Actual time should be relative to Jan 1, 1970.
TimeCallbackForTesting(const SSL * ssl,struct timeval * out_clock)142 void TimeCallbackForTesting(const SSL* ssl, struct timeval* out_clock) {
143   int64_t time = TimeNanos();
144   out_clock->tv_sec = time / kNumNanosecsPerSec;
145   out_clock->tv_usec = (time % kNumNanosecsPerSec) / kNumNanosecsPerMicrosec;
146 }
147 #endif
148 
149 }  // namespace
150 
151 //////////////////////////////////////////////////////////////////////
152 // StreamBIO
153 //////////////////////////////////////////////////////////////////////
154 
155 static int stream_write(BIO* h, const char* buf, int num);
156 static int stream_read(BIO* h, char* buf, int size);
157 static int stream_puts(BIO* h, const char* str);
158 static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
159 static int stream_new(BIO* h);
160 static int stream_free(BIO* data);
161 
BIO_stream_method()162 static BIO_METHOD* BIO_stream_method() {
163   static BIO_METHOD* method = [] {
164     BIO_METHOD* method = BIO_meth_new(BIO_TYPE_BIO, "stream");
165     BIO_meth_set_write(method, stream_write);
166     BIO_meth_set_read(method, stream_read);
167     BIO_meth_set_puts(method, stream_puts);
168     BIO_meth_set_ctrl(method, stream_ctrl);
169     BIO_meth_set_create(method, stream_new);
170     BIO_meth_set_destroy(method, stream_free);
171     return method;
172   }();
173   return method;
174 }
175 
BIO_new_stream(StreamInterface * stream)176 static BIO* BIO_new_stream(StreamInterface* stream) {
177   BIO* ret = BIO_new(BIO_stream_method());
178   if (ret == nullptr) {
179     return nullptr;
180   }
181   BIO_set_data(ret, stream);
182   return ret;
183 }
184 
185 // bio methods return 1 (or at least non-zero) on success and 0 on failure.
186 
stream_new(BIO * b)187 static int stream_new(BIO* b) {
188   BIO_set_shutdown(b, 0);
189   BIO_set_init(b, 1);
190   BIO_set_data(b, 0);
191   return 1;
192 }
193 
stream_free(BIO * b)194 static int stream_free(BIO* b) {
195   if (b == nullptr) {
196     return 0;
197   }
198   return 1;
199 }
200 
stream_read(BIO * b,char * out,int outl)201 static int stream_read(BIO* b, char* out, int outl) {
202   if (!out) {
203     return -1;
204   }
205   StreamInterface* stream = static_cast<StreamInterface*>(BIO_get_data(b));
206   BIO_clear_retry_flags(b);
207   size_t read;
208   int error;
209   StreamResult result = stream->Read(out, outl, &read, &error);
210   if (result == SR_SUCCESS) {
211     return checked_cast<int>(read);
212   } else if (result == SR_BLOCK) {
213     BIO_set_retry_read(b);
214   }
215   return -1;
216 }
217 
stream_write(BIO * b,const char * in,int inl)218 static int stream_write(BIO* b, const char* in, int inl) {
219   if (!in) {
220     return -1;
221   }
222   StreamInterface* stream = static_cast<StreamInterface*>(BIO_get_data(b));
223   BIO_clear_retry_flags(b);
224   size_t written;
225   int error;
226   StreamResult result = stream->Write(in, inl, &written, &error);
227   if (result == SR_SUCCESS) {
228     return checked_cast<int>(written);
229   } else if (result == SR_BLOCK) {
230     BIO_set_retry_write(b);
231   }
232   return -1;
233 }
234 
stream_puts(BIO * b,const char * str)235 static int stream_puts(BIO* b, const char* str) {
236   return stream_write(b, str, checked_cast<int>(strlen(str)));
237 }
238 
stream_ctrl(BIO * b,int cmd,long num,void * ptr)239 static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
240   switch (cmd) {
241     case BIO_CTRL_RESET:
242       return 0;
243     case BIO_CTRL_EOF: {
244       StreamInterface* stream = static_cast<StreamInterface*>(ptr);
245       // 1 means end-of-stream.
246       return (stream->GetState() == SS_CLOSED) ? 1 : 0;
247     }
248     case BIO_CTRL_WPENDING:
249     case BIO_CTRL_PENDING:
250       return 0;
251     case BIO_CTRL_FLUSH:
252       return 1;
253     case BIO_CTRL_DGRAM_QUERY_MTU:
254       // openssl defaults to mtu=256 unless we return something here.
255       // The handshake doesn't actually need to send packets above 1k,
256       // so this seems like a sensible value that should work in most cases.
257       // Webrtc uses the same value for video packets.
258       return 1200;
259     default:
260       return 0;
261   }
262 }
263 
264 /////////////////////////////////////////////////////////////////////////////
265 // OpenSSLStreamAdapter
266 /////////////////////////////////////////////////////////////////////////////
267 
OpenSSLStreamAdapter(std::unique_ptr<StreamInterface> stream)268 OpenSSLStreamAdapter::OpenSSLStreamAdapter(
269     std::unique_ptr<StreamInterface> stream)
270     : SSLStreamAdapter(std::move(stream)),
271       state_(SSL_NONE),
272       role_(SSL_CLIENT),
273       ssl_read_needs_write_(false),
274       ssl_write_needs_read_(false),
275       ssl_(nullptr),
276       ssl_ctx_(nullptr),
277       ssl_mode_(SSL_MODE_TLS),
278       ssl_max_version_(SSL_PROTOCOL_TLS_12),
279       // Default is to support legacy TLS protocols.
280       // This will be changed to default non-support in M82 or M83.
281       support_legacy_tls_protocols_flag_(
282           !webrtc::field_trial::IsDisabled("WebRTC-LegacyTlsProtocols")) {}
283 
~OpenSSLStreamAdapter()284 OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
285   Cleanup(0);
286 }
287 
SetIdentity(std::unique_ptr<SSLIdentity> identity)288 void OpenSSLStreamAdapter::SetIdentity(std::unique_ptr<SSLIdentity> identity) {
289   RTC_DCHECK(!identity_);
290   identity_.reset(static_cast<OpenSSLIdentity*>(identity.release()));
291 }
292 
GetIdentityForTesting() const293 OpenSSLIdentity* OpenSSLStreamAdapter::GetIdentityForTesting() const {
294   return identity_.get();
295 }
296 
SetServerRole(SSLRole role)297 void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
298   role_ = role;
299 }
300 
SetPeerCertificateDigest(const std::string & digest_alg,const unsigned char * digest_val,size_t digest_len,SSLPeerCertificateDigestError * error)301 bool OpenSSLStreamAdapter::SetPeerCertificateDigest(
302     const std::string& digest_alg,
303     const unsigned char* digest_val,
304     size_t digest_len,
305     SSLPeerCertificateDigestError* error) {
306   RTC_DCHECK(!peer_certificate_verified_);
307   RTC_DCHECK(!HasPeerCertificateDigest());
308   size_t expected_len;
309   if (error) {
310     *error = SSLPeerCertificateDigestError::NONE;
311   }
312 
313   if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
314     RTC_LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
315     if (error) {
316       *error = SSLPeerCertificateDigestError::UNKNOWN_ALGORITHM;
317     }
318     return false;
319   }
320   if (expected_len != digest_len) {
321     if (error) {
322       *error = SSLPeerCertificateDigestError::INVALID_LENGTH;
323     }
324     return false;
325   }
326 
327   peer_certificate_digest_value_.SetData(digest_val, digest_len);
328   peer_certificate_digest_algorithm_ = digest_alg;
329 
330   if (!peer_cert_chain_) {
331     // Normal case, where the digest is set before we obtain the certificate
332     // from the handshake.
333     return true;
334   }
335 
336   if (!VerifyPeerCertificate()) {
337     Error("SetPeerCertificateDigest", -1, SSL_AD_BAD_CERTIFICATE, false);
338     if (error) {
339       *error = SSLPeerCertificateDigestError::VERIFICATION_FAILED;
340     }
341     return false;
342   }
343 
344   if (state_ == SSL_CONNECTED) {
345     // Post the event asynchronously to unwind the stack. The caller
346     // of ContinueSSL may be the same object listening for these
347     // events and may not be prepared for reentrancy.
348     PostEvent(SE_OPEN | SE_READ | SE_WRITE, 0);
349   }
350 
351   return true;
352 }
353 
SslCipherSuiteToName(int cipher_suite)354 std::string OpenSSLStreamAdapter::SslCipherSuiteToName(int cipher_suite) {
355 #ifdef OPENSSL_IS_BORINGSSL
356   const SSL_CIPHER* ssl_cipher = SSL_get_cipher_by_value(cipher_suite);
357   if (!ssl_cipher) {
358     return std::string();
359   }
360   return SSL_CIPHER_standard_name(ssl_cipher);
361 #else
362   for (const SslCipherMapEntry* entry = kSslCipherMap; entry->rfc_name;
363        ++entry) {
364     if (cipher_suite == static_cast<int>(entry->openssl_id)) {
365       return entry->rfc_name;
366     }
367   }
368   return std::string();
369 #endif
370 }
371 
GetSslCipherSuite(int * cipher_suite)372 bool OpenSSLStreamAdapter::GetSslCipherSuite(int* cipher_suite) {
373   if (state_ != SSL_CONNECTED) {
374     return false;
375   }
376 
377   const SSL_CIPHER* current_cipher = SSL_get_current_cipher(ssl_);
378   if (current_cipher == nullptr) {
379     return false;
380   }
381 
382   *cipher_suite = static_cast<uint16_t>(SSL_CIPHER_get_id(current_cipher));
383   return true;
384 }
385 
GetSslVersion() const386 SSLProtocolVersion OpenSSLStreamAdapter::GetSslVersion() const {
387   if (state_ != SSL_CONNECTED) {
388     return SSL_PROTOCOL_NOT_GIVEN;
389   }
390 
391   int ssl_version = SSL_version(ssl_);
392   if (ssl_mode_ == SSL_MODE_DTLS) {
393     if (ssl_version == DTLS1_VERSION) {
394       return SSL_PROTOCOL_DTLS_10;
395     } else if (ssl_version == DTLS1_2_VERSION) {
396       return SSL_PROTOCOL_DTLS_12;
397     }
398   } else {
399     if (ssl_version == TLS1_VERSION) {
400       return SSL_PROTOCOL_TLS_10;
401     } else if (ssl_version == TLS1_1_VERSION) {
402       return SSL_PROTOCOL_TLS_11;
403     } else if (ssl_version == TLS1_2_VERSION) {
404       return SSL_PROTOCOL_TLS_12;
405     }
406   }
407 
408   return SSL_PROTOCOL_NOT_GIVEN;
409 }
410 
GetSslVersionBytes(int * version) const411 bool OpenSSLStreamAdapter::GetSslVersionBytes(int* version) const {
412   if (state_ != SSL_CONNECTED) {
413     return false;
414   }
415   *version = SSL_version(ssl_);
416   return true;
417 }
418 
419 // 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)420 bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
421                                                 const uint8_t* context,
422                                                 size_t context_len,
423                                                 bool use_context,
424                                                 uint8_t* result,
425                                                 size_t result_len) {
426   if (SSL_export_keying_material(ssl_, result, result_len, label.c_str(),
427                                  label.length(), const_cast<uint8_t*>(context),
428                                  context_len, use_context) != 1) {
429     return false;
430   }
431   return true;
432 }
433 
SetDtlsSrtpCryptoSuites(const std::vector<int> & ciphers)434 bool OpenSSLStreamAdapter::SetDtlsSrtpCryptoSuites(
435     const std::vector<int>& ciphers) {
436   if (state_ != SSL_NONE) {
437     return false;
438   }
439 
440   std::string internal_ciphers;
441   for (const int cipher : ciphers) {
442     bool found = false;
443     for (const auto& entry : kSrtpCipherMap) {
444       if (cipher == entry.id) {
445         found = true;
446         if (!internal_ciphers.empty()) {
447           internal_ciphers += ":";
448         }
449         internal_ciphers += entry.internal_name;
450         break;
451       }
452     }
453 
454     if (!found) {
455       RTC_LOG(LS_ERROR) << "Could not find cipher: " << cipher;
456       return false;
457     }
458   }
459 
460   if (internal_ciphers.empty()) {
461     return false;
462   }
463 
464   srtp_ciphers_ = internal_ciphers;
465   return true;
466 }
467 
GetDtlsSrtpCryptoSuite(int * crypto_suite)468 bool OpenSSLStreamAdapter::GetDtlsSrtpCryptoSuite(int* crypto_suite) {
469   RTC_DCHECK(state_ == SSL_CONNECTED);
470   if (state_ != SSL_CONNECTED) {
471     return false;
472   }
473 
474   const SRTP_PROTECTION_PROFILE* srtp_profile =
475       SSL_get_selected_srtp_profile(ssl_);
476 
477   if (!srtp_profile) {
478     return false;
479   }
480 
481   *crypto_suite = srtp_profile->id;
482   RTC_DCHECK(!SrtpCryptoSuiteToName(*crypto_suite).empty());
483   return true;
484 }
485 
IsTlsConnected()486 bool OpenSSLStreamAdapter::IsTlsConnected() {
487   return state_ == SSL_CONNECTED;
488 }
489 
StartSSL()490 int OpenSSLStreamAdapter::StartSSL() {
491   // Don't allow StartSSL to be called twice.
492   if (state_ != SSL_NONE) {
493     return -1;
494   }
495 
496   if (StreamAdapterInterface::GetState() != SS_OPEN) {
497     state_ = SSL_WAIT;
498     return 0;
499   }
500 
501   state_ = SSL_CONNECTING;
502   if (int err = BeginSSL()) {
503     Error("BeginSSL", err, 0, false);
504     return err;
505   }
506 
507   return 0;
508 }
509 
SetMode(SSLMode mode)510 void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
511   RTC_DCHECK(state_ == SSL_NONE);
512   ssl_mode_ = mode;
513 }
514 
SetMaxProtocolVersion(SSLProtocolVersion version)515 void OpenSSLStreamAdapter::SetMaxProtocolVersion(SSLProtocolVersion version) {
516   RTC_DCHECK(ssl_ctx_ == nullptr);
517   ssl_max_version_ = version;
518 }
519 
SetInitialRetransmissionTimeout(int timeout_ms)520 void OpenSSLStreamAdapter::SetInitialRetransmissionTimeout(int timeout_ms) {
521   RTC_DCHECK(ssl_ctx_ == nullptr);
522   dtls_handshake_timeout_ms_ = timeout_ms;
523 }
524 
525 //
526 // StreamInterface Implementation
527 //
528 
Write(const void * data,size_t data_len,size_t * written,int * error)529 StreamResult OpenSSLStreamAdapter::Write(const void* data,
530                                          size_t data_len,
531                                          size_t* written,
532                                          int* error) {
533   RTC_LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
534 
535   switch (state_) {
536     case SSL_NONE:
537       // pass-through in clear text
538       return StreamAdapterInterface::Write(data, data_len, written, error);
539 
540     case SSL_WAIT:
541     case SSL_CONNECTING:
542       return SR_BLOCK;
543 
544     case SSL_CONNECTED:
545       if (WaitingToVerifyPeerCertificate()) {
546         return SR_BLOCK;
547       }
548       break;
549 
550     case SSL_ERROR:
551     case SSL_CLOSED:
552     default:
553       if (error) {
554         *error = ssl_error_code_;
555       }
556       return SR_ERROR;
557   }
558 
559   // OpenSSL will return an error if we try to write zero bytes
560   if (data_len == 0) {
561     if (written) {
562       *written = 0;
563     }
564     return SR_SUCCESS;
565   }
566 
567   ssl_write_needs_read_ = false;
568 
569   int code = SSL_write(ssl_, data, checked_cast<int>(data_len));
570   int ssl_error = SSL_get_error(ssl_, code);
571   switch (ssl_error) {
572     case SSL_ERROR_NONE:
573       RTC_LOG(LS_VERBOSE) << " -- success";
574       RTC_DCHECK_GT(code, 0);
575       RTC_DCHECK_LE(code, data_len);
576       if (written)
577         *written = code;
578       return SR_SUCCESS;
579     case SSL_ERROR_WANT_READ:
580       RTC_LOG(LS_VERBOSE) << " -- error want read";
581       ssl_write_needs_read_ = true;
582       return SR_BLOCK;
583     case SSL_ERROR_WANT_WRITE:
584       RTC_LOG(LS_VERBOSE) << " -- error want write";
585       return SR_BLOCK;
586 
587     case SSL_ERROR_ZERO_RETURN:
588     default:
589       Error("SSL_write", (ssl_error ? ssl_error : -1), 0, false);
590       if (error) {
591         *error = ssl_error_code_;
592       }
593       return SR_ERROR;
594   }
595   // not reached
596 }
597 
Read(void * data,size_t data_len,size_t * read,int * error)598 StreamResult OpenSSLStreamAdapter::Read(void* data,
599                                         size_t data_len,
600                                         size_t* read,
601                                         int* error) {
602   RTC_LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
603   switch (state_) {
604     case SSL_NONE:
605       // pass-through in clear text
606       return StreamAdapterInterface::Read(data, data_len, read, error);
607     case SSL_WAIT:
608     case SSL_CONNECTING:
609       return SR_BLOCK;
610     case SSL_CONNECTED:
611       if (WaitingToVerifyPeerCertificate()) {
612         return SR_BLOCK;
613       }
614       break;
615     case SSL_CLOSED:
616       return SR_EOS;
617     case SSL_ERROR:
618     default:
619       if (error) {
620         *error = ssl_error_code_;
621       }
622       return SR_ERROR;
623   }
624 
625   // Don't trust OpenSSL with zero byte reads
626   if (data_len == 0) {
627     if (read) {
628       *read = 0;
629     }
630     return SR_SUCCESS;
631   }
632 
633   ssl_read_needs_write_ = false;
634 
635   const int code = SSL_read(ssl_, data, checked_cast<int>(data_len));
636   const int ssl_error = SSL_get_error(ssl_, code);
637 
638   switch (ssl_error) {
639     case SSL_ERROR_NONE:
640       RTC_LOG(LS_VERBOSE) << " -- success";
641       RTC_DCHECK_GT(code, 0);
642       RTC_DCHECK_LE(code, data_len);
643       if (read) {
644         *read = code;
645       }
646 
647       if (ssl_mode_ == SSL_MODE_DTLS) {
648         // Enforce atomic reads -- this is a short read
649         unsigned int pending = SSL_pending(ssl_);
650 
651         if (pending) {
652           RTC_LOG(LS_INFO) << " -- short DTLS read. flushing";
653           FlushInput(pending);
654           if (error) {
655             *error = SSE_MSG_TRUNC;
656           }
657           return SR_ERROR;
658         }
659       }
660       return SR_SUCCESS;
661     case SSL_ERROR_WANT_READ:
662       RTC_LOG(LS_VERBOSE) << " -- error want read";
663       return SR_BLOCK;
664     case SSL_ERROR_WANT_WRITE:
665       RTC_LOG(LS_VERBOSE) << " -- error want write";
666       ssl_read_needs_write_ = true;
667       return SR_BLOCK;
668     case SSL_ERROR_ZERO_RETURN:
669       RTC_LOG(LS_VERBOSE) << " -- remote side closed";
670       Close();
671       return SR_EOS;
672     default:
673       Error("SSL_read", (ssl_error ? ssl_error : -1), 0, false);
674       if (error) {
675         *error = ssl_error_code_;
676       }
677       return SR_ERROR;
678   }
679   // not reached
680 }
681 
FlushInput(unsigned int left)682 void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
683   unsigned char buf[2048];
684 
685   while (left) {
686     // This should always succeed
687     const int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
688     const int code = SSL_read(ssl_, buf, toread);
689 
690     const int ssl_error = SSL_get_error(ssl_, code);
691     RTC_DCHECK(ssl_error == SSL_ERROR_NONE);
692 
693     if (ssl_error != SSL_ERROR_NONE) {
694       RTC_DLOG(LS_VERBOSE) << " -- error " << code;
695       Error("SSL_read", (ssl_error ? ssl_error : -1), 0, false);
696       return;
697     }
698 
699     RTC_LOG(LS_VERBOSE) << " -- flushed " << code << " bytes";
700     left -= code;
701   }
702 }
703 
Close()704 void OpenSSLStreamAdapter::Close() {
705   Cleanup(0);
706   RTC_DCHECK(state_ == SSL_CLOSED || state_ == SSL_ERROR);
707   // When we're closed at SSL layer, also close the stream level which
708   // performs necessary clean up. Otherwise, a new incoming packet after
709   // this could overflow the stream buffer.
710   StreamAdapterInterface::Close();
711 }
712 
GetState() const713 StreamState OpenSSLStreamAdapter::GetState() const {
714   switch (state_) {
715     case SSL_WAIT:
716     case SSL_CONNECTING:
717       return SS_OPENING;
718     case SSL_CONNECTED:
719       if (WaitingToVerifyPeerCertificate()) {
720         return SS_OPENING;
721       }
722       return SS_OPEN;
723     default:
724       return SS_CLOSED;
725   }
726   // not reached
727 }
728 
OnEvent(StreamInterface * stream,int events,int err)729 void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream,
730                                    int events,
731                                    int err) {
732   int events_to_signal = 0;
733   int signal_error = 0;
734   RTC_DCHECK(stream == this->stream());
735 
736   if ((events & SE_OPEN)) {
737     RTC_LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
738     if (state_ != SSL_WAIT) {
739       RTC_DCHECK(state_ == SSL_NONE);
740       events_to_signal |= SE_OPEN;
741     } else {
742       state_ = SSL_CONNECTING;
743       if (int err = BeginSSL()) {
744         Error("BeginSSL", err, 0, true);
745         return;
746       }
747     }
748   }
749 
750   if ((events & (SE_READ | SE_WRITE))) {
751     RTC_LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent"
752                         << ((events & SE_READ) ? " SE_READ" : "")
753                         << ((events & SE_WRITE) ? " SE_WRITE" : "");
754     if (state_ == SSL_NONE) {
755       events_to_signal |= events & (SE_READ | SE_WRITE);
756     } else if (state_ == SSL_CONNECTING) {
757       if (int err = ContinueSSL()) {
758         Error("ContinueSSL", err, 0, true);
759         return;
760       }
761     } else if (state_ == SSL_CONNECTED) {
762       if (((events & SE_READ) && ssl_write_needs_read_) ||
763           (events & SE_WRITE)) {
764         RTC_LOG(LS_VERBOSE) << " -- onStreamWriteable";
765         events_to_signal |= SE_WRITE;
766       }
767       if (((events & SE_WRITE) && ssl_read_needs_write_) ||
768           (events & SE_READ)) {
769         RTC_LOG(LS_VERBOSE) << " -- onStreamReadable";
770         events_to_signal |= SE_READ;
771       }
772     }
773   }
774 
775   if ((events & SE_CLOSE)) {
776     RTC_LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err
777                         << ")";
778     Cleanup(0);
779     events_to_signal |= SE_CLOSE;
780     // SE_CLOSE is the only event that uses the final parameter to OnEvent().
781     RTC_DCHECK(signal_error == 0);
782     signal_error = err;
783   }
784 
785   if (events_to_signal) {
786     StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
787   }
788 }
789 
BeginSSL()790 int OpenSSLStreamAdapter::BeginSSL() {
791   RTC_DCHECK(state_ == SSL_CONNECTING);
792   // The underlying stream has opened.
793   RTC_LOG(LS_INFO) << "BeginSSL with peer.";
794 
795   BIO* bio = nullptr;
796 
797   // First set up the context.
798   RTC_DCHECK(ssl_ctx_ == nullptr);
799   ssl_ctx_ = SetupSSLContext();
800   if (!ssl_ctx_) {
801     return -1;
802   }
803 
804   bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
805   if (!bio) {
806     return -1;
807   }
808 
809   ssl_ = SSL_new(ssl_ctx_);
810   if (!ssl_) {
811     BIO_free(bio);
812     return -1;
813   }
814 
815   SSL_set_app_data(ssl_, this);
816 
817   SSL_set_bio(ssl_, bio, bio);  // the SSL object owns the bio now.
818   if (ssl_mode_ == SSL_MODE_DTLS) {
819 #ifdef OPENSSL_IS_BORINGSSL
820     DTLSv1_set_initial_timeout_duration(ssl_, dtls_handshake_timeout_ms_);
821 #else
822     // Enable read-ahead for DTLS so whole packets are read from internal BIO
823     // before parsing. This is done internally by BoringSSL for DTLS.
824     SSL_set_read_ahead(ssl_, 1);
825 #endif
826   }
827 
828   SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
829                          SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
830 
831   // Do the connect
832   return ContinueSSL();
833 }
834 
ContinueSSL()835 int OpenSSLStreamAdapter::ContinueSSL() {
836   RTC_LOG(LS_VERBOSE) << "ContinueSSL";
837   RTC_DCHECK(state_ == SSL_CONNECTING);
838 
839   // Clear the DTLS timer
840   Thread::Current()->Clear(this, MSG_TIMEOUT);
841 
842   const int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
843   const int ssl_error = SSL_get_error(ssl_, code);
844 
845   switch (ssl_error) {
846     case SSL_ERROR_NONE:
847       RTC_LOG(LS_VERBOSE) << " -- success";
848       // By this point, OpenSSL should have given us a certificate, or errored
849       // out if one was missing.
850       RTC_DCHECK(peer_cert_chain_ || !GetClientAuthEnabled());
851 
852       state_ = SSL_CONNECTED;
853       if (!WaitingToVerifyPeerCertificate()) {
854         // We have everything we need to start the connection, so signal
855         // SE_OPEN. If we need a client certificate fingerprint and don't have
856         // it yet, we'll instead signal SE_OPEN in SetPeerCertificateDigest.
857         //
858         // TODO(deadbeef): Post this event asynchronously to unwind the stack.
859         // The caller of ContinueSSL may be the same object listening for these
860         // events and may not be prepared for reentrancy.
861         // PostEvent(SE_OPEN | SE_READ | SE_WRITE, 0);
862         StreamAdapterInterface::OnEvent(stream(), SE_OPEN | SE_READ | SE_WRITE,
863                                         0);
864       }
865       break;
866 
867     case SSL_ERROR_WANT_READ: {
868       RTC_LOG(LS_VERBOSE) << " -- error want read";
869       struct timeval timeout;
870       if (DTLSv1_get_timeout(ssl_, &timeout)) {
871         int delay = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
872 
873         Thread::Current()->PostDelayed(RTC_FROM_HERE, delay, this, MSG_TIMEOUT,
874                                        0);
875       }
876     } break;
877 
878     case SSL_ERROR_WANT_WRITE:
879       RTC_LOG(LS_VERBOSE) << " -- error want write";
880       break;
881 
882     case SSL_ERROR_ZERO_RETURN:
883     default:
884       RTC_LOG(LS_VERBOSE) << " -- error " << code;
885       SSLHandshakeError ssl_handshake_err = SSLHandshakeError::UNKNOWN;
886       int err_code = ERR_peek_last_error();
887       if (err_code != 0 && ERR_GET_REASON(err_code) == SSL_R_NO_SHARED_CIPHER) {
888         ssl_handshake_err = SSLHandshakeError::INCOMPATIBLE_CIPHERSUITE;
889       }
890       SignalSSLHandshakeError(ssl_handshake_err);
891       return (ssl_error != 0) ? ssl_error : -1;
892   }
893 
894   return 0;
895 }
896 
Error(const char * context,int err,uint8_t alert,bool signal)897 void OpenSSLStreamAdapter::Error(const char* context,
898                                  int err,
899                                  uint8_t alert,
900                                  bool signal) {
901   RTC_LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error(" << context << ", "
902                       << err << ", " << static_cast<int>(alert) << ")";
903   state_ = SSL_ERROR;
904   ssl_error_code_ = err;
905   Cleanup(alert);
906   if (signal) {
907     StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
908   }
909 }
910 
Cleanup(uint8_t alert)911 void OpenSSLStreamAdapter::Cleanup(uint8_t alert) {
912   RTC_LOG(LS_INFO) << "Cleanup";
913 
914   if (state_ != SSL_ERROR) {
915     state_ = SSL_CLOSED;
916     ssl_error_code_ = 0;
917   }
918 
919   if (ssl_) {
920     int ret;
921 // SSL_send_fatal_alert is only available in BoringSSL.
922 #ifdef OPENSSL_IS_BORINGSSL
923     if (alert) {
924       ret = SSL_send_fatal_alert(ssl_, alert);
925       if (ret < 0) {
926         RTC_LOG(LS_WARNING) << "SSL_send_fatal_alert failed, error = "
927                             << SSL_get_error(ssl_, ret);
928       }
929     } else {
930 #endif
931       ret = SSL_shutdown(ssl_);
932       if (ret < 0) {
933         RTC_LOG(LS_WARNING)
934             << "SSL_shutdown failed, error = " << SSL_get_error(ssl_, ret);
935       }
936 #ifdef OPENSSL_IS_BORINGSSL
937     }
938 #endif
939     SSL_free(ssl_);
940     ssl_ = nullptr;
941   }
942   if (ssl_ctx_) {
943     SSL_CTX_free(ssl_ctx_);
944     ssl_ctx_ = nullptr;
945   }
946   identity_.reset();
947   peer_cert_chain_.reset();
948 
949   // Clear the DTLS timer
950   Thread::Current()->Clear(this, MSG_TIMEOUT);
951 }
952 
OnMessage(Message * msg)953 void OpenSSLStreamAdapter::OnMessage(Message* msg) {
954   // Process our own messages and then pass others to the superclass
955   if (MSG_TIMEOUT == msg->message_id) {
956     RTC_LOG(LS_INFO) << "DTLS timeout expired";
957     DTLSv1_handle_timeout(ssl_);
958     ContinueSSL();
959   } else {
960     StreamInterface::OnMessage(msg);
961   }
962 }
963 
SetupSSLContext()964 SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
965   SSL_CTX* ctx =
966       SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ? DTLS_method() : TLS_method());
967   if (ctx == nullptr) {
968     return nullptr;
969   }
970 
971   if (support_legacy_tls_protocols_flag_) {
972     // TODO(https://bugs.webrtc.org/10261): Completely remove this branch in
973     // M84.
974     SSL_CTX_set_min_proto_version(
975         ctx, ssl_mode_ == SSL_MODE_DTLS ? DTLS1_VERSION : TLS1_VERSION);
976     switch (ssl_max_version_) {
977       case SSL_PROTOCOL_TLS_10:
978         SSL_CTX_set_max_proto_version(
979             ctx, ssl_mode_ == SSL_MODE_DTLS ? DTLS1_VERSION : TLS1_VERSION);
980         break;
981       case SSL_PROTOCOL_TLS_11:
982         SSL_CTX_set_max_proto_version(
983             ctx, ssl_mode_ == SSL_MODE_DTLS ? DTLS1_VERSION : TLS1_1_VERSION);
984         break;
985       case SSL_PROTOCOL_TLS_12:
986       default:
987         SSL_CTX_set_max_proto_version(
988             ctx, ssl_mode_ == SSL_MODE_DTLS ? DTLS1_2_VERSION : TLS1_2_VERSION);
989         break;
990     }
991   } else {
992     // TODO(https://bugs.webrtc.org/10261): Make this the default in M84.
993     SSL_CTX_set_min_proto_version(
994         ctx, ssl_mode_ == SSL_MODE_DTLS ? DTLS1_2_VERSION : TLS1_2_VERSION);
995     SSL_CTX_set_max_proto_version(
996         ctx, ssl_mode_ == SSL_MODE_DTLS ? DTLS1_2_VERSION : TLS1_2_VERSION);
997   }
998 
999 #ifdef OPENSSL_IS_BORINGSSL
1000   // SSL_CTX_set_current_time_cb is only supported in BoringSSL.
1001   if (g_use_time_callback_for_testing) {
1002     SSL_CTX_set_current_time_cb(ctx, &TimeCallbackForTesting);
1003   }
1004 #endif
1005 
1006   if (identity_ && !identity_->ConfigureIdentity(ctx)) {
1007     SSL_CTX_free(ctx);
1008     return nullptr;
1009   }
1010 
1011 #if !defined(NDEBUG)
1012   SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
1013 #endif
1014 
1015   int mode = SSL_VERIFY_PEER;
1016   if (GetClientAuthEnabled()) {
1017     // Require a certificate from the client.
1018     // Note: Normally this is always true in production, but it may be disabled
1019     // for testing purposes (e.g. SSLAdapter unit tests).
1020     mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1021   }
1022 
1023   // Configure a custom certificate verification callback to check the peer
1024   // certificate digest. Note the second argument to SSL_CTX_set_verify is to
1025   // override individual errors in the default verification logic, which is not
1026   // what we want here.
1027   SSL_CTX_set_verify(ctx, mode, nullptr);
1028   SSL_CTX_set_cert_verify_callback(ctx, SSLVerifyCallback, nullptr);
1029 
1030   // Select list of available ciphers. Note that !SHA256 and !SHA384 only
1031   // remove HMAC-SHA256 and HMAC-SHA384 cipher suites, not GCM cipher suites
1032   // with SHA256 or SHA384 as the handshake hash.
1033   // This matches the list of SSLClientSocketOpenSSL in Chromium.
1034   SSL_CTX_set_cipher_list(
1035       ctx, "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
1036 
1037   if (!srtp_ciphers_.empty()) {
1038     if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
1039       SSL_CTX_free(ctx);
1040       return nullptr;
1041     }
1042   }
1043 
1044   return ctx;
1045 }
1046 
VerifyPeerCertificate()1047 bool OpenSSLStreamAdapter::VerifyPeerCertificate() {
1048   if (!HasPeerCertificateDigest() || !peer_cert_chain_ ||
1049       !peer_cert_chain_->GetSize()) {
1050     RTC_LOG(LS_WARNING) << "Missing digest or peer certificate.";
1051     return false;
1052   }
1053   const OpenSSLCertificate* leaf_cert =
1054       static_cast<const OpenSSLCertificate*>(&peer_cert_chain_->Get(0));
1055 
1056   unsigned char digest[EVP_MAX_MD_SIZE];
1057   size_t digest_length;
1058   if (!OpenSSLCertificate::ComputeDigest(
1059           leaf_cert->x509(), peer_certificate_digest_algorithm_, digest,
1060           sizeof(digest), &digest_length)) {
1061     RTC_LOG(LS_WARNING) << "Failed to compute peer cert digest.";
1062     return false;
1063   }
1064 
1065   Buffer computed_digest(digest, digest_length);
1066   if (computed_digest != peer_certificate_digest_value_) {
1067     RTC_LOG(LS_WARNING)
1068         << "Rejected peer certificate due to mismatched digest.";
1069     return false;
1070   }
1071   // Ignore any verification error if the digest matches, since there is no
1072   // value in checking the validity of a self-signed cert issued by untrusted
1073   // sources.
1074   RTC_LOG(LS_INFO) << "Accepted peer certificate.";
1075   peer_certificate_verified_ = true;
1076   return true;
1077 }
1078 
GetPeerSSLCertChain() const1079 std::unique_ptr<SSLCertChain> OpenSSLStreamAdapter::GetPeerSSLCertChain()
1080     const {
1081   return peer_cert_chain_ ? peer_cert_chain_->Clone() : nullptr;
1082 }
1083 
SSLVerifyCallback(X509_STORE_CTX * store,void * arg)1084 int OpenSSLStreamAdapter::SSLVerifyCallback(X509_STORE_CTX* store, void* arg) {
1085   // Get our SSL structure and OpenSSLStreamAdapter from the store.
1086   SSL* ssl = reinterpret_cast<SSL*>(
1087       X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx()));
1088   OpenSSLStreamAdapter* stream =
1089       reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
1090 
1091 #if defined(OPENSSL_IS_BORINGSSL)
1092   STACK_OF(X509)* chain = SSL_get_peer_full_cert_chain(ssl);
1093   // Creates certificate chain.
1094   std::vector<std::unique_ptr<SSLCertificate>> cert_chain;
1095   for (X509* cert : chain) {
1096     cert_chain.emplace_back(new OpenSSLCertificate(cert));
1097   }
1098   stream->peer_cert_chain_.reset(new SSLCertChain(std::move(cert_chain)));
1099 #else
1100   // Record the peer's certificate.
1101   X509* cert = X509_STORE_CTX_get0_cert(store);
1102   stream->peer_cert_chain_.reset(
1103       new SSLCertChain(std::make_unique<OpenSSLCertificate>(cert)));
1104 #endif
1105 
1106   // If the peer certificate digest isn't known yet, we'll wait to verify
1107   // until it's known, and for now just return a success status.
1108   if (stream->peer_certificate_digest_algorithm_.empty()) {
1109     RTC_LOG(LS_INFO) << "Waiting to verify certificate until digest is known.";
1110     return 1;
1111   }
1112 
1113   if (!stream->VerifyPeerCertificate()) {
1114     X509_STORE_CTX_set_error(store, X509_V_ERR_CERT_REJECTED);
1115     return 0;
1116   }
1117 
1118   return 1;
1119 }
1120 
IsBoringSsl()1121 bool OpenSSLStreamAdapter::IsBoringSsl() {
1122 #ifdef OPENSSL_IS_BORINGSSL
1123   return true;
1124 #else
1125   return false;
1126 #endif
1127 }
1128 
1129 #define CDEF(X) \
1130   { static_cast<uint16_t>(TLS1_CK_##X & 0xffff), "TLS_" #X }
1131 
1132 struct cipher_list {
1133   uint16_t cipher;
1134   const char* cipher_str;
1135 };
1136 
1137 // TODO(torbjorng): Perhaps add more cipher suites to these lists.
1138 static const cipher_list OK_RSA_ciphers[] = {
1139     CDEF(ECDHE_RSA_WITH_AES_128_CBC_SHA),
1140     CDEF(ECDHE_RSA_WITH_AES_256_CBC_SHA),
1141     CDEF(ECDHE_RSA_WITH_AES_128_GCM_SHA256),
1142 #ifdef TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA256
1143     CDEF(ECDHE_RSA_WITH_AES_256_GCM_SHA256),
1144 #endif
1145 #ifdef TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
1146     CDEF(ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256),
1147 #endif
1148 };
1149 
1150 static const cipher_list OK_ECDSA_ciphers[] = {
1151     CDEF(ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
1152     CDEF(ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
1153     CDEF(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
1154 #ifdef TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA256
1155     CDEF(ECDHE_ECDSA_WITH_AES_256_GCM_SHA256),
1156 #endif
1157 #ifdef TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
1158     CDEF(ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256),
1159 #endif
1160 };
1161 #undef CDEF
1162 
IsAcceptableCipher(int cipher,KeyType key_type)1163 bool OpenSSLStreamAdapter::IsAcceptableCipher(int cipher, KeyType key_type) {
1164   if (key_type == KT_RSA) {
1165     for (const cipher_list& c : OK_RSA_ciphers) {
1166       if (cipher == c.cipher) {
1167         return true;
1168       }
1169     }
1170   }
1171 
1172   if (key_type == KT_ECDSA) {
1173     for (const cipher_list& c : OK_ECDSA_ciphers) {
1174       if (cipher == c.cipher) {
1175         return true;
1176       }
1177     }
1178   }
1179 
1180   return false;
1181 }
1182 
IsAcceptableCipher(const std::string & cipher,KeyType key_type)1183 bool OpenSSLStreamAdapter::IsAcceptableCipher(const std::string& cipher,
1184                                               KeyType key_type) {
1185   if (key_type == KT_RSA) {
1186     for (const cipher_list& c : OK_RSA_ciphers) {
1187       if (cipher == c.cipher_str) {
1188         return true;
1189       }
1190     }
1191   }
1192 
1193   if (key_type == KT_ECDSA) {
1194     for (const cipher_list& c : OK_ECDSA_ciphers) {
1195       if (cipher == c.cipher_str) {
1196         return true;
1197       }
1198     }
1199   }
1200 
1201   return false;
1202 }
1203 
EnableTimeCallbackForTesting()1204 void OpenSSLStreamAdapter::EnableTimeCallbackForTesting() {
1205 #ifdef OPENSSL_IS_BORINGSSL
1206   g_use_time_callback_for_testing = true;
1207 #endif
1208 }
1209 
1210 }  // namespace rtc
1211