blob: 60ce6ae0dc2665970479c7e9d7adf2350eaa24b8 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/opensslstreamadapter.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
13#include <openssl/bio.h>
14#include <openssl/crypto.h>
15#include <openssl/err.h>
16#include <openssl/rand.h>
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +000017#include <openssl/tls1.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000018#include <openssl/x509v3.h>
torbjorngaad67802016-04-07 08:55:28 -070019#ifndef OPENSSL_IS_BORINGSSL
20#include <openssl/dtls1.h>
ssarohabbfed522016-12-11 18:42:07 -080021#include <openssl/ssl.h>
torbjorngaad67802016-04-07 08:55:28 -070022#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023
jbauch555604a2016-04-26 03:13:22 -070024#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025#include <vector>
26
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/checks.h"
28#include "rtc_base/logging.h"
29#include "rtc_base/openssl.h"
30#include "rtc_base/openssladapter.h"
31#include "rtc_base/openssldigest.h"
32#include "rtc_base/opensslidentity.h"
33#include "rtc_base/safe_conversions.h"
34#include "rtc_base/stream.h"
35#include "rtc_base/stringutils.h"
36#include "rtc_base/thread.h"
37#include "rtc_base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000038
deadbeef6cf94a02016-11-28 17:38:34 -080039namespace {
40 bool g_use_time_callback_for_testing = false;
41}
42
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043namespace rtc {
44
deadbeef1b54a5f2017-01-23 19:39:57 -080045#if (OPENSSL_VERSION_NUMBER < 0x10001000L)
46#error "webrtc requires at least OpenSSL version 1.0.1, to support DTLS-SRTP"
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010047#endif
48
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -080049// SRTP cipher suite table. |internal_name| is used to construct a
50// colon-separated profile strings which is needed by
51// SSL_CTX_set_tlsext_use_srtp().
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052struct SrtpCipherMapEntry {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053 const char* internal_name;
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -080054 const int id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055};
56
57// This isn't elegant, but it's better than an external reference
58static SrtpCipherMapEntry SrtpCipherMap[] = {
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -080059 {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80},
60 {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32},
jbauchcb560652016-08-04 05:20:32 -070061 {"SRTP_AEAD_AES_128_GCM", SRTP_AEAD_AES_128_GCM},
62 {"SRTP_AEAD_AES_256_GCM", SRTP_AEAD_AES_256_GCM},
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -080063 {nullptr, 0}};
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010064
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -070065#ifdef OPENSSL_IS_BORINGSSL
deadbeef6cf94a02016-11-28 17:38:34 -080066// Not used in production code. Actual time should be relative to Jan 1, 1970.
67static void TimeCallbackForTesting(const SSL* ssl, struct timeval* out_clock) {
nissedeb95f32016-11-28 01:54:54 -080068 int64_t time = TimeNanos();
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -070069 out_clock->tv_sec = time / kNumNanosecsPerSec;
deadbeef7a07f132016-11-21 14:33:57 -080070 out_clock->tv_usec = (time % kNumNanosecsPerSec) / kNumNanosecsPerMicrosec;
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -070071}
72#else // #ifdef OPENSSL_IS_BORINGSSL
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010073
74// Cipher name table. Maps internal OpenSSL cipher ids to the RFC name.
75struct SslCipherMapEntry {
76 uint32_t openssl_id;
77 const char* rfc_name;
78};
79
80#define DEFINE_CIPHER_ENTRY_SSL3(name) {SSL3_CK_##name, "TLS_"#name}
81#define DEFINE_CIPHER_ENTRY_TLS1(name) {TLS1_CK_##name, "TLS_"#name}
82
83// There currently is no method available to get a RFC-compliant name for a
84// cipher suite from BoringSSL, so we need to define the mapping manually here.
85// This should go away once BoringSSL supports "SSL_CIPHER_standard_name"
86// (as available in OpenSSL if compiled with tracing enabled) or a similar
87// method.
88static const SslCipherMapEntry kSslCipherMap[] = {
deadbeef37f5ecf2017-02-27 14:06:41 -080089 // TLS v1.0 ciphersuites from RFC2246.
90 DEFINE_CIPHER_ENTRY_SSL3(RSA_RC4_128_SHA),
91 {SSL3_CK_RSA_DES_192_CBC3_SHA, "TLS_RSA_WITH_3DES_EDE_CBC_SHA"},
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010092
deadbeef37f5ecf2017-02-27 14:06:41 -080093 // AES ciphersuites from RFC3268.
94 {TLS1_CK_RSA_WITH_AES_128_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA"},
95 {TLS1_CK_DHE_RSA_WITH_AES_128_SHA, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
96 {TLS1_CK_RSA_WITH_AES_256_SHA, "TLS_RSA_WITH_AES_256_CBC_SHA"},
97 {TLS1_CK_DHE_RSA_WITH_AES_256_SHA, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010098
deadbeef37f5ecf2017-02-27 14:06:41 -080099 // ECC ciphersuites from RFC4492.
100 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_RC4_128_SHA),
101 {TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA,
102 "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"},
103 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
104 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100105
deadbeef37f5ecf2017-02-27 14:06:41 -0800106 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_RC4_128_SHA),
107 {TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA,
108 "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"},
109 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_CBC_SHA),
110 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_CBC_SHA),
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100111
deadbeef37f5ecf2017-02-27 14:06:41 -0800112 // TLS v1.2 ciphersuites.
113 {TLS1_CK_RSA_WITH_AES_128_SHA256, "TLS_RSA_WITH_AES_128_CBC_SHA256"},
114 {TLS1_CK_RSA_WITH_AES_256_SHA256, "TLS_RSA_WITH_AES_256_CBC_SHA256"},
115 {TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
116 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"},
117 {TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
118 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"},
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100119
deadbeef37f5ecf2017-02-27 14:06:41 -0800120 // TLS v1.2 GCM ciphersuites from RFC5288.
121 DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_128_GCM_SHA256),
122 DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_256_GCM_SHA384),
123 DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_128_GCM_SHA256),
124 DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_256_GCM_SHA384),
125 DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_128_GCM_SHA256),
126 DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_256_GCM_SHA384),
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100127
deadbeef37f5ecf2017-02-27 14:06:41 -0800128 // ECDH HMAC based ciphersuites from RFC5289.
129 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
130 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"},
131 {TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
132 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"},
133 {TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
134 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"},
135 {TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
136 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"},
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100137
deadbeef37f5ecf2017-02-27 14:06:41 -0800138 // ECDH GCM based ciphersuites from RFC5289.
139 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
140 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
141 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_GCM_SHA256),
142 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_GCM_SHA384),
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100143
deadbeef37f5ecf2017-02-27 14:06:41 -0800144 {0, nullptr}};
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100145#endif // #ifndef OPENSSL_IS_BORINGSSL
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000146
Guo-wei Shieh456696a2015-09-30 21:48:54 -0700147#if defined(_MSC_VER)
148#pragma warning(push)
149#pragma warning(disable : 4309)
150#pragma warning(disable : 4310)
151#endif // defined(_MSC_VER)
152
Guo-wei Shieh456696a2015-09-30 21:48:54 -0700153#if defined(_MSC_VER)
154#pragma warning(pop)
155#endif // defined(_MSC_VER)
156
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157//////////////////////////////////////////////////////////////////////
158// StreamBIO
159//////////////////////////////////////////////////////////////////////
160
161static int stream_write(BIO* h, const char* buf, int num);
162static int stream_read(BIO* h, char* buf, int size);
163static int stream_puts(BIO* h, const char* str);
164static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
165static int stream_new(BIO* h);
166static int stream_free(BIO* data);
167
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +0000168// TODO(davidben): This should be const once BoringSSL is assumed.
169static BIO_METHOD methods_stream = {
deadbeef37f5ecf2017-02-27 14:06:41 -0800170 BIO_TYPE_BIO, "stream", stream_write, stream_read, stream_puts, 0,
171 stream_ctrl, stream_new, stream_free, nullptr,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172};
173
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +0000174static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175
176static BIO* BIO_new_stream(StreamInterface* stream) {
177 BIO* ret = BIO_new(BIO_s_stream());
deadbeef37f5ecf2017-02-27 14:06:41 -0800178 if (ret == nullptr)
179 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180 ret->ptr = stream;
181 return ret;
182}
183
184// bio methods return 1 (or at least non-zero) on success and 0 on failure.
185
186static int stream_new(BIO* b) {
187 b->shutdown = 0;
188 b->init = 1;
189 b->num = 0; // 1 means end-of-stream
190 b->ptr = 0;
191 return 1;
192}
193
194static int stream_free(BIO* b) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800195 if (b == nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196 return 0;
197 return 1;
198}
199
200static int stream_read(BIO* b, char* out, int outl) {
201 if (!out)
202 return -1;
203 StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
204 BIO_clear_retry_flags(b);
205 size_t read;
206 int error;
207 StreamResult result = stream->Read(out, outl, &read, &error);
208 if (result == SR_SUCCESS) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000209 return checked_cast<int>(read);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210 } else if (result == SR_EOS) {
211 b->num = 1;
212 } else if (result == SR_BLOCK) {
213 BIO_set_retry_read(b);
214 }
215 return -1;
216}
217
218static int stream_write(BIO* b, const char* in, int inl) {
219 if (!in)
220 return -1;
221 StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
222 BIO_clear_retry_flags(b);
223 size_t written;
224 int error;
225 StreamResult result = stream->Write(in, inl, &written, &error);
226 if (result == SR_SUCCESS) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000227 return checked_cast<int>(written);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000228 } else if (result == SR_BLOCK) {
229 BIO_set_retry_write(b);
230 }
231 return -1;
232}
233
234static int stream_puts(BIO* b, const char* str) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000235 return stream_write(b, str, checked_cast<int>(strlen(str)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000236}
237
238static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239 switch (cmd) {
240 case BIO_CTRL_RESET:
241 return 0;
242 case BIO_CTRL_EOF:
243 return b->num;
244 case BIO_CTRL_WPENDING:
245 case BIO_CTRL_PENDING:
246 return 0;
247 case BIO_CTRL_FLUSH:
248 return 1;
Henrik Lundinf4baca52015-06-10 09:45:58 +0200249 case BIO_CTRL_DGRAM_QUERY_MTU:
250 // openssl defaults to mtu=256 unless we return something here.
251 // The handshake doesn't actually need to send packets above 1k,
252 // so this seems like a sensible value that should work in most cases.
253 // Webrtc uses the same value for video packets.
254 return 1200;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255 default:
256 return 0;
257 }
258}
259
260/////////////////////////////////////////////////////////////////////////////
261// OpenSSLStreamAdapter
262/////////////////////////////////////////////////////////////////////////////
263
264OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
265 : SSLStreamAdapter(stream),
266 state_(SSL_NONE),
267 role_(SSL_CLIENT),
Guo-wei Shieha7446d22016-01-11 15:27:03 -0800268 ssl_read_needs_write_(false),
269 ssl_write_needs_read_(false),
deadbeef37f5ecf2017-02-27 14:06:41 -0800270 ssl_(nullptr),
271 ssl_ctx_(nullptr),
Joachim Bauch831c5582015-05-20 12:48:41 +0200272 ssl_mode_(SSL_MODE_TLS),
Guo-wei Shieha7446d22016-01-11 15:27:03 -0800273 ssl_max_version_(SSL_PROTOCOL_TLS_12) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000274
275OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
deadbeef89824f62016-09-30 11:55:43 -0700276 Cleanup(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277}
278
279void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
deadbeef89824f62016-09-30 11:55:43 -0700280 RTC_DCHECK(!identity_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281 identity_.reset(static_cast<OpenSSLIdentity*>(identity));
282}
283
284void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
285 role_ = role;
286}
287
jbauch555604a2016-04-26 03:13:22 -0700288std::unique_ptr<SSLCertificate> OpenSSLStreamAdapter::GetPeerCertificate()
kwibergb4d01c42016-04-06 05:15:06 -0700289 const {
jbauch555604a2016-04-26 03:13:22 -0700290 return peer_certificate_ ? std::unique_ptr<SSLCertificate>(
kwibergb4d01c42016-04-06 05:15:06 -0700291 peer_certificate_->GetReference())
292 : nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293}
294
deadbeef89824f62016-09-30 11:55:43 -0700295bool OpenSSLStreamAdapter::SetPeerCertificateDigest(
296 const std::string& digest_alg,
297 const unsigned char* digest_val,
298 size_t digest_len,
299 SSLPeerCertificateDigestError* error) {
300 RTC_DCHECK(!peer_certificate_verified_);
301 RTC_DCHECK(!has_peer_certificate_digest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302 size_t expected_len;
deadbeef89824f62016-09-30 11:55:43 -0700303 if (error) {
304 *error = SSLPeerCertificateDigestError::NONE;
305 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306
307 if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
308 LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
deadbeef89824f62016-09-30 11:55:43 -0700309 if (error) {
310 *error = SSLPeerCertificateDigestError::UNKNOWN_ALGORITHM;
311 }
deadbeef81f6f4f2016-09-19 17:20:52 -0700312 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313 }
deadbeef89824f62016-09-30 11:55:43 -0700314 if (expected_len != digest_len) {
315 if (error) {
316 *error = SSLPeerCertificateDigestError::INVALID_LENGTH;
317 }
deadbeef81f6f4f2016-09-19 17:20:52 -0700318 return false;
deadbeef89824f62016-09-30 11:55:43 -0700319 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320
321 peer_certificate_digest_value_.SetData(digest_val, digest_len);
322 peer_certificate_digest_algorithm_ = digest_alg;
323
deadbeef89824f62016-09-30 11:55:43 -0700324 if (!peer_certificate_) {
325 // Normal case, where the digest is set before we obtain the certificate
326 // from the handshake.
327 return true;
328 }
329
330 if (!VerifyPeerCertificate()) {
331 Error("SetPeerCertificateDigest", -1, SSL_AD_BAD_CERTIFICATE, false);
332 if (error) {
333 *error = SSLPeerCertificateDigestError::VERIFICATION_FAILED;
334 }
335 return false;
336 }
337
338 if (state_ == SSL_CONNECTED) {
339 // Post the event asynchronously to unwind the stack. The caller
340 // of ContinueSSL may be the same object listening for these
341 // events and may not be prepared for reentrancy.
342 PostEvent(SE_OPEN | SE_READ | SE_WRITE, 0);
343 }
344
deadbeef81f6f4f2016-09-19 17:20:52 -0700345 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346}
347
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800348std::string OpenSSLStreamAdapter::SslCipherSuiteToName(int cipher_suite) {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100349#ifdef OPENSSL_IS_BORINGSSL
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800350 const SSL_CIPHER* ssl_cipher = SSL_get_cipher_by_value(cipher_suite);
Guo-wei Shieh456696a2015-09-30 21:48:54 -0700351 if (!ssl_cipher) {
352 return std::string();
353 }
David Benjamina8f73762017-09-28 15:49:42 -0400354 return SSL_CIPHER_standard_name(ssl_cipher);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100355#else
356 for (const SslCipherMapEntry* entry = kSslCipherMap; entry->rfc_name;
357 ++entry) {
358 if (cipher_suite == static_cast<int>(entry->openssl_id)) {
359 return entry->rfc_name;
360 }
361 }
362 return std::string();
363#endif
Guo-wei Shieh456696a2015-09-30 21:48:54 -0700364}
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000365
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800366bool OpenSSLStreamAdapter::GetSslCipherSuite(int* cipher_suite) {
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000367 if (state_ != SSL_CONNECTED)
368 return false;
369
370 const SSL_CIPHER* current_cipher = SSL_get_current_cipher(ssl_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800371 if (current_cipher == nullptr) {
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000372 return false;
373 }
374
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800375 *cipher_suite = static_cast<uint16_t>(SSL_CIPHER_get_id(current_cipher));
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000376 return true;
377}
378
torbjorng43166b82016-03-11 00:06:47 -0800379int OpenSSLStreamAdapter::GetSslVersion() const {
380 if (state_ != SSL_CONNECTED)
381 return -1;
382
383 int ssl_version = SSL_version(ssl_);
384 if (ssl_mode_ == SSL_MODE_DTLS) {
385 if (ssl_version == DTLS1_VERSION)
386 return SSL_PROTOCOL_DTLS_10;
387 else if (ssl_version == DTLS1_2_VERSION)
388 return SSL_PROTOCOL_DTLS_12;
389 } else {
390 if (ssl_version == TLS1_VERSION)
391 return SSL_PROTOCOL_TLS_10;
392 else if (ssl_version == TLS1_1_VERSION)
393 return SSL_PROTOCOL_TLS_11;
394 else if (ssl_version == TLS1_2_VERSION)
395 return SSL_PROTOCOL_TLS_12;
396 }
397
398 return -1;
399}
400
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000401// Key Extractor interface
402bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200403 const uint8_t* context,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000404 size_t context_len,
405 bool use_context,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200406 uint8_t* result,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000407 size_t result_len) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000408 int i;
409
Peter Boström0c4e06b2015-10-07 12:23:21 +0200410 i = SSL_export_keying_material(ssl_, result, result_len, label.c_str(),
411 label.length(), const_cast<uint8_t*>(context),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 context_len, use_context);
413
414 if (i != 1)
415 return false;
416
417 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000418}
419
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800420bool OpenSSLStreamAdapter::SetDtlsSrtpCryptoSuites(
421 const std::vector<int>& ciphers) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000422 std::string internal_ciphers;
423
424 if (state_ != SSL_NONE)
425 return false;
426
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800427 for (std::vector<int>::const_iterator cipher = ciphers.begin();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000428 cipher != ciphers.end(); ++cipher) {
429 bool found = false;
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800430 for (SrtpCipherMapEntry* entry = SrtpCipherMap; entry->internal_name;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000431 ++entry) {
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800432 if (*cipher == entry->id) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433 found = true;
434 if (!internal_ciphers.empty())
435 internal_ciphers += ":";
436 internal_ciphers += entry->internal_name;
437 break;
438 }
439 }
440
441 if (!found) {
442 LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
443 return false;
444 }
445 }
446
447 if (internal_ciphers.empty())
448 return false;
449
450 srtp_ciphers_ = internal_ciphers;
451 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000452}
453
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800454bool OpenSSLStreamAdapter::GetDtlsSrtpCryptoSuite(int* crypto_suite) {
deadbeef89824f62016-09-30 11:55:43 -0700455 RTC_DCHECK(state_ == SSL_CONNECTED);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000456 if (state_ != SSL_CONNECTED)
457 return false;
458
henrike@webrtc.orgc10ecea2015-01-07 17:59:28 +0000459 const SRTP_PROTECTION_PROFILE *srtp_profile =
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000460 SSL_get_selected_srtp_profile(ssl_);
461
462 if (!srtp_profile)
463 return false;
464
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800465 *crypto_suite = srtp_profile->id;
deadbeef89824f62016-09-30 11:55:43 -0700466 RTC_DCHECK(!SrtpCryptoSuiteToName(*crypto_suite).empty());
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800467 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000468}
469
deadbeef89824f62016-09-30 11:55:43 -0700470bool OpenSSLStreamAdapter::IsTlsConnected() {
471 return state_ == SSL_CONNECTED;
472}
473
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700474int OpenSSLStreamAdapter::StartSSL() {
deadbeef89824f62016-09-30 11:55:43 -0700475 if (state_ != SSL_NONE) {
476 // Don't allow StartSSL to be called twice.
477 return -1;
478 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000479
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700480 if (StreamAdapterInterface::GetState() != SS_OPEN) {
481 state_ = SSL_WAIT;
482 return 0;
483 }
484
485 state_ = SSL_CONNECTING;
486 if (int err = BeginSSL()) {
deadbeef89824f62016-09-30 11:55:43 -0700487 Error("BeginSSL", err, 0, false);
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700488 return err;
489 }
490
491 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000492}
493
494void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
deadbeef89824f62016-09-30 11:55:43 -0700495 RTC_DCHECK(state_ == SSL_NONE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000496 ssl_mode_ = mode;
497}
498
Joachim Bauch831c5582015-05-20 12:48:41 +0200499void OpenSSLStreamAdapter::SetMaxProtocolVersion(SSLProtocolVersion version) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800500 RTC_DCHECK(ssl_ctx_ == nullptr);
Joachim Bauch831c5582015-05-20 12:48:41 +0200501 ssl_max_version_ = version;
502}
503
skvladd0309122017-02-02 17:18:37 -0800504void OpenSSLStreamAdapter::SetInitialRetransmissionTimeout(
505 int timeout_ms) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800506 RTC_DCHECK(ssl_ctx_ == nullptr);
skvladd0309122017-02-02 17:18:37 -0800507 dtls_handshake_timeout_ms_ = timeout_ms;
508}
509
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510//
511// StreamInterface Implementation
512//
513
514StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
515 size_t* written, int* error) {
516 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
517
518 switch (state_) {
519 case SSL_NONE:
520 // pass-through in clear text
521 return StreamAdapterInterface::Write(data, data_len, written, error);
522
523 case SSL_WAIT:
524 case SSL_CONNECTING:
525 return SR_BLOCK;
526
527 case SSL_CONNECTED:
deadbeef89824f62016-09-30 11:55:43 -0700528 if (waiting_to_verify_peer_certificate()) {
529 return SR_BLOCK;
530 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000531 break;
532
533 case SSL_ERROR:
534 case SSL_CLOSED:
535 default:
536 if (error)
537 *error = ssl_error_code_;
538 return SR_ERROR;
539 }
540
541 // OpenSSL will return an error if we try to write zero bytes
542 if (data_len == 0) {
543 if (written)
544 *written = 0;
545 return SR_SUCCESS;
546 }
547
548 ssl_write_needs_read_ = false;
549
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000550 int code = SSL_write(ssl_, data, checked_cast<int>(data_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000551 int ssl_error = SSL_get_error(ssl_, code);
552 switch (ssl_error) {
553 case SSL_ERROR_NONE:
554 LOG(LS_VERBOSE) << " -- success";
kwibergee89e782017-08-09 17:22:01 -0700555 RTC_DCHECK_GT(code, 0);
556 RTC_DCHECK_LE(code, data_len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000557 if (written)
558 *written = code;
559 return SR_SUCCESS;
560 case SSL_ERROR_WANT_READ:
561 LOG(LS_VERBOSE) << " -- error want read";
562 ssl_write_needs_read_ = true;
563 return SR_BLOCK;
564 case SSL_ERROR_WANT_WRITE:
565 LOG(LS_VERBOSE) << " -- error want write";
566 return SR_BLOCK;
567
568 case SSL_ERROR_ZERO_RETURN:
569 default:
deadbeef89824f62016-09-30 11:55:43 -0700570 Error("SSL_write", (ssl_error ? ssl_error : -1), 0, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000571 if (error)
572 *error = ssl_error_code_;
573 return SR_ERROR;
574 }
575 // not reached
576}
577
578StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
579 size_t* read, int* error) {
580 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
581 switch (state_) {
582 case SSL_NONE:
583 // pass-through in clear text
584 return StreamAdapterInterface::Read(data, data_len, read, error);
585
586 case SSL_WAIT:
587 case SSL_CONNECTING:
588 return SR_BLOCK;
589
590 case SSL_CONNECTED:
deadbeef89824f62016-09-30 11:55:43 -0700591 if (waiting_to_verify_peer_certificate()) {
592 return SR_BLOCK;
593 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000594 break;
595
596 case SSL_CLOSED:
597 return SR_EOS;
598
599 case SSL_ERROR:
600 default:
601 if (error)
602 *error = ssl_error_code_;
603 return SR_ERROR;
604 }
605
606 // Don't trust OpenSSL with zero byte reads
607 if (data_len == 0) {
608 if (read)
609 *read = 0;
610 return SR_SUCCESS;
611 }
612
613 ssl_read_needs_write_ = false;
614
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000615 int code = SSL_read(ssl_, data, checked_cast<int>(data_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000616 int ssl_error = SSL_get_error(ssl_, code);
617 switch (ssl_error) {
618 case SSL_ERROR_NONE:
619 LOG(LS_VERBOSE) << " -- success";
kwibergee89e782017-08-09 17:22:01 -0700620 RTC_DCHECK_GT(code, 0);
621 RTC_DCHECK_LE(code, data_len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000622 if (read)
623 *read = code;
624
625 if (ssl_mode_ == SSL_MODE_DTLS) {
626 // Enforce atomic reads -- this is a short read
627 unsigned int pending = SSL_pending(ssl_);
628
629 if (pending) {
630 LOG(LS_INFO) << " -- short DTLS read. flushing";
631 FlushInput(pending);
632 if (error)
633 *error = SSE_MSG_TRUNC;
634 return SR_ERROR;
635 }
636 }
637 return SR_SUCCESS;
638 case SSL_ERROR_WANT_READ:
639 LOG(LS_VERBOSE) << " -- error want read";
640 return SR_BLOCK;
641 case SSL_ERROR_WANT_WRITE:
642 LOG(LS_VERBOSE) << " -- error want write";
643 ssl_read_needs_write_ = true;
644 return SR_BLOCK;
645 case SSL_ERROR_ZERO_RETURN:
646 LOG(LS_VERBOSE) << " -- remote side closed";
deadbeef89824f62016-09-30 11:55:43 -0700647 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000648 return SR_EOS;
649 break;
650 default:
651 LOG(LS_VERBOSE) << " -- error " << code;
deadbeef89824f62016-09-30 11:55:43 -0700652 Error("SSL_read", (ssl_error ? ssl_error : -1), 0, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000653 if (error)
654 *error = ssl_error_code_;
655 return SR_ERROR;
656 }
657 // not reached
658}
659
660void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
661 unsigned char buf[2048];
662
663 while (left) {
664 // This should always succeed
665 int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
666 int code = SSL_read(ssl_, buf, toread);
667
668 int ssl_error = SSL_get_error(ssl_, code);
deadbeef89824f62016-09-30 11:55:43 -0700669 RTC_DCHECK(ssl_error == SSL_ERROR_NONE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000670
671 if (ssl_error != SSL_ERROR_NONE) {
672 LOG(LS_VERBOSE) << " -- error " << code;
deadbeef89824f62016-09-30 11:55:43 -0700673 Error("SSL_read", (ssl_error ? ssl_error : -1), 0, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000674 return;
675 }
676
677 LOG(LS_VERBOSE) << " -- flushed " << code << " bytes";
678 left -= code;
679 }
680}
681
682void OpenSSLStreamAdapter::Close() {
deadbeef89824f62016-09-30 11:55:43 -0700683 Cleanup(0);
684 RTC_DCHECK(state_ == SSL_CLOSED || state_ == SSL_ERROR);
685 // When we're closed at SSL layer, also close the stream level which
686 // performs necessary clean up. Otherwise, a new incoming packet after
687 // this could overflow the stream buffer.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000688 StreamAdapterInterface::Close();
689}
690
691StreamState OpenSSLStreamAdapter::GetState() const {
692 switch (state_) {
693 case SSL_WAIT:
694 case SSL_CONNECTING:
695 return SS_OPENING;
696 case SSL_CONNECTED:
deadbeef89824f62016-09-30 11:55:43 -0700697 if (waiting_to_verify_peer_certificate()) {
698 return SS_OPENING;
699 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000700 return SS_OPEN;
701 default:
702 return SS_CLOSED;
703 };
704 // not reached
705}
706
707void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
708 int err) {
709 int events_to_signal = 0;
710 int signal_error = 0;
deadbeef89824f62016-09-30 11:55:43 -0700711 RTC_DCHECK(stream == this->stream());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000712 if ((events & SE_OPEN)) {
713 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
714 if (state_ != SSL_WAIT) {
deadbeef89824f62016-09-30 11:55:43 -0700715 RTC_DCHECK(state_ == SSL_NONE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000716 events_to_signal |= SE_OPEN;
717 } else {
718 state_ = SSL_CONNECTING;
719 if (int err = BeginSSL()) {
deadbeef89824f62016-09-30 11:55:43 -0700720 Error("BeginSSL", err, 0, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000721 return;
722 }
723 }
724 }
725 if ((events & (SE_READ|SE_WRITE))) {
726 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent"
727 << ((events & SE_READ) ? " SE_READ" : "")
728 << ((events & SE_WRITE) ? " SE_WRITE" : "");
729 if (state_ == SSL_NONE) {
730 events_to_signal |= events & (SE_READ|SE_WRITE);
731 } else if (state_ == SSL_CONNECTING) {
732 if (int err = ContinueSSL()) {
deadbeef89824f62016-09-30 11:55:43 -0700733 Error("ContinueSSL", err, 0, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000734 return;
735 }
736 } else if (state_ == SSL_CONNECTED) {
737 if (((events & SE_READ) && ssl_write_needs_read_) ||
738 (events & SE_WRITE)) {
739 LOG(LS_VERBOSE) << " -- onStreamWriteable";
740 events_to_signal |= SE_WRITE;
741 }
742 if (((events & SE_WRITE) && ssl_read_needs_write_) ||
743 (events & SE_READ)) {
744 LOG(LS_VERBOSE) << " -- onStreamReadable";
745 events_to_signal |= SE_READ;
746 }
747 }
748 }
749 if ((events & SE_CLOSE)) {
750 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
deadbeef89824f62016-09-30 11:55:43 -0700751 Cleanup(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000752 events_to_signal |= SE_CLOSE;
753 // SE_CLOSE is the only event that uses the final parameter to OnEvent().
deadbeef89824f62016-09-30 11:55:43 -0700754 RTC_DCHECK(signal_error == 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000755 signal_error = err;
756 }
757 if (events_to_signal)
758 StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
759}
760
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000761int OpenSSLStreamAdapter::BeginSSL() {
deadbeef89824f62016-09-30 11:55:43 -0700762 RTC_DCHECK(state_ == SSL_CONNECTING);
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700763 // The underlying stream has opened.
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700764 LOG(LS_INFO) << "BeginSSL with peer.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000765
deadbeef37f5ecf2017-02-27 14:06:41 -0800766 BIO* bio = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000767
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700768 // First set up the context.
deadbeef37f5ecf2017-02-27 14:06:41 -0800769 RTC_DCHECK(ssl_ctx_ == nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000770 ssl_ctx_ = SetupSSLContext();
771 if (!ssl_ctx_)
772 return -1;
773
774 bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
775 if (!bio)
776 return -1;
777
778 ssl_ = SSL_new(ssl_ctx_);
779 if (!ssl_) {
780 BIO_free(bio);
781 return -1;
782 }
783
784 SSL_set_app_data(ssl_, this);
785
786 SSL_set_bio(ssl_, bio, bio); // the SSL object owns the bio now.
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100787 if (ssl_mode_ == SSL_MODE_DTLS) {
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -0700788#ifdef OPENSSL_IS_BORINGSSL
skvladd0309122017-02-02 17:18:37 -0800789 DTLSv1_set_initial_timeout_duration(ssl_, dtls_handshake_timeout_ms_);
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -0700790#else
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100791 // Enable read-ahead for DTLS so whole packets are read from internal BIO
792 // before parsing. This is done internally by BoringSSL for DTLS.
793 SSL_set_read_ahead(ssl_, 1);
philipel49c08692016-05-24 01:49:43 -0700794#endif
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -0700795 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000796
797 SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
798 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
799
David Benjamin60d5f3f2016-03-24 13:28:25 -0400800#if !defined(OPENSSL_IS_BORINGSSL)
801 // Specify an ECDH group for ECDHE ciphers, otherwise OpenSSL cannot
802 // negotiate them when acting as the server. Use NIST's P-256 which is
803 // commonly supported. BoringSSL doesn't need explicit configuration and has
804 // a reasonable default set.
jiayl@webrtc.org11c6bde2014-08-28 16:14:38 +0000805 EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
deadbeef37f5ecf2017-02-27 14:06:41 -0800806 if (ecdh == nullptr)
jiayl@webrtc.org11c6bde2014-08-28 16:14:38 +0000807 return -1;
808 SSL_set_options(ssl_, SSL_OP_SINGLE_ECDH_USE);
809 SSL_set_tmp_ecdh(ssl_, ecdh);
810 EC_KEY_free(ecdh);
David Benjamin60d5f3f2016-03-24 13:28:25 -0400811#endif
jiayl@webrtc.org11c6bde2014-08-28 16:14:38 +0000812
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000813 // Do the connect
814 return ContinueSSL();
815}
816
817int OpenSSLStreamAdapter::ContinueSSL() {
818 LOG(LS_VERBOSE) << "ContinueSSL";
deadbeef89824f62016-09-30 11:55:43 -0700819 RTC_DCHECK(state_ == SSL_CONNECTING);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000820
821 // Clear the DTLS timer
822 Thread::Current()->Clear(this, MSG_TIMEOUT);
823
824 int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
825 int ssl_error;
826 switch (ssl_error = SSL_get_error(ssl_, code)) {
827 case SSL_ERROR_NONE:
828 LOG(LS_VERBOSE) << " -- success";
deadbeef89824f62016-09-30 11:55:43 -0700829 // By this point, OpenSSL should have given us a certificate, or errored
830 // out if one was missing.
831 RTC_DCHECK(peer_certificate_ || !client_auth_enabled());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000832
833 state_ = SSL_CONNECTED;
deadbeef89824f62016-09-30 11:55:43 -0700834 if (!waiting_to_verify_peer_certificate()) {
835 // We have everything we need to start the connection, so signal
836 // SE_OPEN. If we need a client certificate fingerprint and don't have
837 // it yet, we'll instead signal SE_OPEN in SetPeerCertificateDigest.
838 //
Taylor Brandstetterfe69a742016-09-30 17:34:32 -0700839 // TODO(deadbeef): Post this event asynchronously to unwind the stack.
840 // The caller of ContinueSSL may be the same object listening for these
841 // events and may not be prepared for reentrancy.
842 // PostEvent(SE_OPEN | SE_READ | SE_WRITE, 0);
843 StreamAdapterInterface::OnEvent(stream(), SE_OPEN | SE_READ | SE_WRITE,
844 0);
deadbeef89824f62016-09-30 11:55:43 -0700845 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000846 break;
847
848 case SSL_ERROR_WANT_READ: {
849 LOG(LS_VERBOSE) << " -- error want read";
850 struct timeval timeout;
851 if (DTLSv1_get_timeout(ssl_, &timeout)) {
852 int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
853
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700854 Thread::Current()->PostDelayed(RTC_FROM_HERE, delay, this,
855 MSG_TIMEOUT, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000856 }
857 }
858 break;
859
860 case SSL_ERROR_WANT_WRITE:
861 LOG(LS_VERBOSE) << " -- error want write";
862 break;
863
864 case SSL_ERROR_ZERO_RETURN:
865 default:
866 LOG(LS_VERBOSE) << " -- error " << code;
zhihuangd82eee02016-08-26 11:25:05 -0700867 SSLHandshakeError ssl_handshake_err = SSLHandshakeError::UNKNOWN;
868 int err_code = ERR_peek_last_error();
869 if (err_code != 0 && ERR_GET_REASON(err_code) == SSL_R_NO_SHARED_CIPHER) {
870 ssl_handshake_err = SSLHandshakeError::INCOMPATIBLE_CIPHERSUITE;
871 }
872 SignalSSLHandshakeError(ssl_handshake_err);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000873 return (ssl_error != 0) ? ssl_error : -1;
874 }
875
876 return 0;
877}
878
deadbeef89824f62016-09-30 11:55:43 -0700879void OpenSSLStreamAdapter::Error(const char* context,
880 int err,
881 uint8_t alert,
882 bool signal) {
883 LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error(" << context << ", " << err
884 << ", " << static_cast<int>(alert) << ")";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000885 state_ = SSL_ERROR;
886 ssl_error_code_ = err;
deadbeef89824f62016-09-30 11:55:43 -0700887 Cleanup(alert);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000888 if (signal)
889 StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
890}
891
deadbeef89824f62016-09-30 11:55:43 -0700892void OpenSSLStreamAdapter::Cleanup(uint8_t alert) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000893 LOG(LS_INFO) << "Cleanup";
894
895 if (state_ != SSL_ERROR) {
896 state_ = SSL_CLOSED;
897 ssl_error_code_ = 0;
898 }
899
900 if (ssl_) {
deadbeef89824f62016-09-30 11:55:43 -0700901 int ret;
902// SSL_send_fatal_alert is only available in BoringSSL.
903#ifdef OPENSSL_IS_BORINGSSL
904 if (alert) {
905 ret = SSL_send_fatal_alert(ssl_, alert);
906 if (ret < 0) {
907 LOG(LS_WARNING) << "SSL_send_fatal_alert failed, error = "
908 << SSL_get_error(ssl_, ret);
909 }
910 } else {
911#endif
912 ret = SSL_shutdown(ssl_);
913 if (ret < 0) {
914 LOG(LS_WARNING) << "SSL_shutdown failed, error = "
915 << SSL_get_error(ssl_, ret);
916 }
917#ifdef OPENSSL_IS_BORINGSSL
jiayl@webrtc.orgf1d751c2014-09-25 16:38:46 +0000918 }
deadbeef89824f62016-09-30 11:55:43 -0700919#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000920 SSL_free(ssl_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800921 ssl_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000922 }
923 if (ssl_ctx_) {
924 SSL_CTX_free(ssl_ctx_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800925 ssl_ctx_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000926 }
927 identity_.reset();
928 peer_certificate_.reset();
929
930 // Clear the DTLS timer
931 Thread::Current()->Clear(this, MSG_TIMEOUT);
932}
933
934
935void OpenSSLStreamAdapter::OnMessage(Message* msg) {
936 // Process our own messages and then pass others to the superclass
937 if (MSG_TIMEOUT == msg->message_id) {
938 LOG(LS_INFO) << "DTLS timeout expired";
939 DTLSv1_handle_timeout(ssl_);
940 ContinueSSL();
941 } else {
942 StreamInterface::OnMessage(msg);
943 }
944}
945
946SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800947 SSL_CTX* ctx = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000948
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100949#ifdef OPENSSL_IS_BORINGSSL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000950 ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
Joachim Bauch831c5582015-05-20 12:48:41 +0200951 DTLS_method() : TLS_method());
952 // Version limiting for BoringSSL will be done below.
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100953#else
954 const SSL_METHOD* method;
955 switch (ssl_max_version_) {
956 case SSL_PROTOCOL_TLS_10:
957 case SSL_PROTOCOL_TLS_11:
958 // OpenSSL doesn't support setting min/max versions, so we always use
959 // (D)TLS 1.0 if a max. version below the max. available is requested.
960 if (ssl_mode_ == SSL_MODE_DTLS) {
961 if (role_ == SSL_CLIENT) {
962 method = DTLSv1_client_method();
963 } else {
964 method = DTLSv1_server_method();
965 }
966 } else {
967 if (role_ == SSL_CLIENT) {
968 method = TLSv1_client_method();
969 } else {
970 method = TLSv1_server_method();
971 }
972 }
973 break;
974 case SSL_PROTOCOL_TLS_12:
975 default:
976 if (ssl_mode_ == SSL_MODE_DTLS) {
977#if (OPENSSL_VERSION_NUMBER >= 0x10002000L)
978 // DTLS 1.2 only available starting from OpenSSL 1.0.2
979 if (role_ == SSL_CLIENT) {
980 method = DTLS_client_method();
981 } else {
982 method = DTLS_server_method();
983 }
984#else
985 if (role_ == SSL_CLIENT) {
986 method = DTLSv1_client_method();
987 } else {
988 method = DTLSv1_server_method();
989 }
990#endif
991 } else {
992#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
993 // New API only available starting from OpenSSL 1.1.0
994 if (role_ == SSL_CLIENT) {
995 method = TLS_client_method();
996 } else {
997 method = TLS_server_method();
998 }
999#else
1000 if (role_ == SSL_CLIENT) {
1001 method = SSLv23_client_method();
1002 } else {
1003 method = SSLv23_server_method();
1004 }
1005#endif
1006 }
1007 break;
1008 }
1009 ctx = SSL_CTX_new(method);
1010#endif // OPENSSL_IS_BORINGSSL
Joachim Bauch831c5582015-05-20 12:48:41 +02001011
deadbeef37f5ecf2017-02-27 14:06:41 -08001012 if (ctx == nullptr)
1013 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001014
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001015#ifdef OPENSSL_IS_BORINGSSL
davidbene36c46e2016-12-06 17:12:02 -08001016 SSL_CTX_set_min_proto_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
Joachim Bauch831c5582015-05-20 12:48:41 +02001017 DTLS1_VERSION : TLS1_VERSION);
1018 switch (ssl_max_version_) {
1019 case SSL_PROTOCOL_TLS_10:
davidbene36c46e2016-12-06 17:12:02 -08001020 SSL_CTX_set_max_proto_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
Joachim Bauch831c5582015-05-20 12:48:41 +02001021 DTLS1_VERSION : TLS1_VERSION);
1022 break;
1023 case SSL_PROTOCOL_TLS_11:
davidbene36c46e2016-12-06 17:12:02 -08001024 SSL_CTX_set_max_proto_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
Joachim Bauch831c5582015-05-20 12:48:41 +02001025 DTLS1_VERSION : TLS1_1_VERSION);
1026 break;
1027 case SSL_PROTOCOL_TLS_12:
1028 default:
davidbene36c46e2016-12-06 17:12:02 -08001029 SSL_CTX_set_max_proto_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
Joachim Bauch831c5582015-05-20 12:48:41 +02001030 DTLS1_2_VERSION : TLS1_2_VERSION);
1031 break;
1032 }
deadbeef6cf94a02016-11-28 17:38:34 -08001033 if (g_use_time_callback_for_testing) {
1034 SSL_CTX_set_current_time_cb(ctx, &TimeCallbackForTesting);
1035 }
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001036#endif
Joachim Bauch831c5582015-05-20 12:48:41 +02001037
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001038 if (identity_ && !identity_->ConfigureIdentity(ctx)) {
1039 SSL_CTX_free(ctx);
deadbeef37f5ecf2017-02-27 14:06:41 -08001040 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001041 }
1042
tfarinaa41ab932015-10-30 16:08:48 -07001043#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001044 SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
1045#endif
1046
tkchin@webrtc.orgc569a492014-09-23 05:56:44 +00001047 int mode = SSL_VERIFY_PEER;
1048 if (client_auth_enabled()) {
1049 // Require a certificate from the client.
1050 // Note: Normally this is always true in production, but it may be disabled
1051 // for testing purposes (e.g. SSLAdapter unit tests).
1052 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1053 }
1054
1055 SSL_CTX_set_verify(ctx, mode, SSLVerifyCallback);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001056 SSL_CTX_set_verify_depth(ctx, 4);
Joachim Bauch831c5582015-05-20 12:48:41 +02001057 // Select list of available ciphers. Note that !SHA256 and !SHA384 only
1058 // remove HMAC-SHA256 and HMAC-SHA384 cipher suites, not GCM cipher suites
1059 // with SHA256 or SHA384 as the handshake hash.
1060 // This matches the list of SSLClientSocketOpenSSL in Chromium.
deadbeef37f5ecf2017-02-27 14:06:41 -08001061 SSL_CTX_set_cipher_list(
1062 ctx, "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001063
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001064 if (!srtp_ciphers_.empty()) {
1065 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
1066 SSL_CTX_free(ctx);
deadbeef37f5ecf2017-02-27 14:06:41 -08001067 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001068 }
1069 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001070
1071 return ctx;
1072}
1073
deadbeef89824f62016-09-30 11:55:43 -07001074bool OpenSSLStreamAdapter::VerifyPeerCertificate() {
1075 if (!has_peer_certificate_digest() || !peer_certificate_) {
1076 LOG(LS_WARNING) << "Missing digest or peer certificate.";
1077 return false;
1078 }
deadbeef81f6f4f2016-09-19 17:20:52 -07001079
deadbeef89824f62016-09-30 11:55:43 -07001080 unsigned char digest[EVP_MAX_MD_SIZE];
1081 size_t digest_length;
1082 if (!OpenSSLCertificate::ComputeDigest(
1083 peer_certificate_->x509(), peer_certificate_digest_algorithm_, digest,
1084 sizeof(digest), &digest_length)) {
1085 LOG(LS_WARNING) << "Failed to compute peer cert digest.";
1086 return false;
1087 }
1088
1089 Buffer computed_digest(digest, digest_length);
1090 if (computed_digest != peer_certificate_digest_value_) {
1091 LOG(LS_WARNING) << "Rejected peer certificate due to mismatched digest.";
jbauchf8f457b2017-03-09 16:24:57 -08001092 return false;
deadbeef81f6f4f2016-09-19 17:20:52 -07001093 }
deadbeef89824f62016-09-30 11:55:43 -07001094 // Ignore any verification error if the digest matches, since there is no
1095 // value in checking the validity of a self-signed cert issued by untrusted
1096 // sources.
1097 LOG(LS_INFO) << "Accepted peer certificate.";
1098 peer_certificate_verified_ = true;
1099 return true;
1100}
1101
1102int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
1103 // Get our SSL structure from the store
1104 SSL* ssl = reinterpret_cast<SSL*>(
1105 X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx()));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001106 X509* cert = X509_STORE_CTX_get_current_cert(store);
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +00001107 int depth = X509_STORE_CTX_get_error_depth(store);
1108
deadbeef89824f62016-09-30 11:55:43 -07001109 // For now we ignore the parent certificates and verify the leaf against
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +00001110 // the digest.
1111 //
1112 // TODO(jiayl): Verify the chain is a proper chain and report the chain to
torbjorng07d09362015-09-22 11:58:04 -07001113 // |stream->peer_certificate_|.
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +00001114 if (depth > 0) {
1115 LOG(LS_INFO) << "Ignored chained certificate at depth " << depth;
1116 return 1;
1117 }
1118
deadbeef89824f62016-09-30 11:55:43 -07001119 OpenSSLStreamAdapter* stream =
1120 reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +00001121
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001122 // Record the peer's certificate.
1123 stream->peer_certificate_.reset(new OpenSSLCertificate(cert));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124
deadbeef89824f62016-09-30 11:55:43 -07001125 // If the peer certificate digest isn't known yet, we'll wait to verify
1126 // until it's known, and for now just return a success status.
1127 if (stream->peer_certificate_digest_algorithm_.empty()) {
1128 LOG(LS_INFO) << "Waiting to verify certificate until digest is known.";
1129 return 1;
1130 }
1131
1132 return stream->VerifyPeerCertificate();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001133}
1134
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -07001135bool OpenSSLStreamAdapter::IsBoringSsl() {
1136#ifdef OPENSSL_IS_BORINGSSL
1137 return true;
1138#else
1139 return false;
1140#endif
1141}
1142
torbjorng43166b82016-03-11 00:06:47 -08001143#define CDEF(X) \
1144 { static_cast<uint16_t>(TLS1_CK_##X & 0xffff), "TLS_" #X }
1145
1146struct cipher_list {
1147 uint16_t cipher;
1148 const char* cipher_str;
1149};
1150
1151// TODO(torbjorng): Perhaps add more cipher suites to these lists.
1152static const cipher_list OK_RSA_ciphers[] = {
1153 CDEF(ECDHE_RSA_WITH_AES_128_CBC_SHA),
1154 CDEF(ECDHE_RSA_WITH_AES_256_CBC_SHA),
1155 CDEF(ECDHE_RSA_WITH_AES_128_GCM_SHA256),
1156#ifdef TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA256
1157 CDEF(ECDHE_RSA_WITH_AES_256_GCM_SHA256),
1158#endif
torbjorngaad67802016-04-07 08:55:28 -07001159#ifdef TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
torbjorng43166b82016-03-11 00:06:47 -08001160 CDEF(ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256),
torbjorngaad67802016-04-07 08:55:28 -07001161#endif
torbjorng43166b82016-03-11 00:06:47 -08001162};
1163
1164static const cipher_list OK_ECDSA_ciphers[] = {
1165 CDEF(ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
1166 CDEF(ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
1167 CDEF(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
1168#ifdef TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA256
1169 CDEF(ECDHE_ECDSA_WITH_AES_256_GCM_SHA256),
1170#endif
torbjorngaad67802016-04-07 08:55:28 -07001171#ifdef TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
torbjorng43166b82016-03-11 00:06:47 -08001172 CDEF(ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256),
torbjorngaad67802016-04-07 08:55:28 -07001173#endif
torbjorng43166b82016-03-11 00:06:47 -08001174};
1175#undef CDEF
1176
1177bool OpenSSLStreamAdapter::IsAcceptableCipher(int cipher, KeyType key_type) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +02001178 if (key_type == KT_RSA) {
torbjorng43166b82016-03-11 00:06:47 -08001179 for (const cipher_list& c : OK_RSA_ciphers) {
1180 if (cipher == c.cipher)
1181 return true;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +02001182 }
Joachim Bauch831c5582015-05-20 12:48:41 +02001183 }
torbjorng43166b82016-03-11 00:06:47 -08001184
1185 if (key_type == KT_ECDSA) {
1186 for (const cipher_list& c : OK_ECDSA_ciphers) {
1187 if (cipher == c.cipher)
1188 return true;
1189 }
1190 }
1191
1192 return false;
1193}
1194
1195bool OpenSSLStreamAdapter::IsAcceptableCipher(const std::string& cipher,
1196 KeyType key_type) {
1197 if (key_type == KT_RSA) {
1198 for (const cipher_list& c : OK_RSA_ciphers) {
1199 if (cipher == c.cipher_str)
1200 return true;
1201 }
1202 }
1203
1204 if (key_type == KT_ECDSA) {
1205 for (const cipher_list& c : OK_ECDSA_ciphers) {
1206 if (cipher == c.cipher_str)
1207 return true;
1208 }
1209 }
1210
1211 return false;
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +00001212}
1213
deadbeef6cf94a02016-11-28 17:38:34 -08001214void OpenSSLStreamAdapter::enable_time_callback_for_testing() {
1215 g_use_time_callback_for_testing = true;
1216}
1217
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001218} // namespace rtc