blob: 6a42003968cf4ff74400818c826b5ff69d069492 [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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000011#if HAVE_OPENSSL_SSL_H
12
13#include "webrtc/base/opensslstreamadapter.h"
14
15#include <openssl/bio.h>
16#include <openssl/crypto.h>
17#include <openssl/err.h>
18#include <openssl/rand.h>
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +000019#include <openssl/tls1.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#include <openssl/x509v3.h>
torbjorngaad67802016-04-07 08:55:28 -070021#ifndef OPENSSL_IS_BORINGSSL
22#include <openssl/dtls1.h>
23#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024
jbauch555604a2016-04-26 03:13:22 -070025#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026#include <vector>
27
deadbeef89824f62016-09-30 11:55:43 -070028#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029#include "webrtc/base/common.h"
30#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080031#include "webrtc/base/safe_conversions.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032#include "webrtc/base/stream.h"
33#include "webrtc/base/openssl.h"
34#include "webrtc/base/openssladapter.h"
35#include "webrtc/base/openssldigest.h"
36#include "webrtc/base/opensslidentity.h"
37#include "webrtc/base/stringutils.h"
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -070038#include "webrtc/base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039#include "webrtc/base/thread.h"
40
41namespace rtc {
42
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010043#if (OPENSSL_VERSION_NUMBER >= 0x10001000L)
44#define HAVE_DTLS_SRTP
45#endif
46
47#ifdef HAVE_DTLS_SRTP
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -080048// SRTP cipher suite table. |internal_name| is used to construct a
49// colon-separated profile strings which is needed by
50// SSL_CTX_set_tlsext_use_srtp().
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000051struct SrtpCipherMapEntry {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052 const char* internal_name;
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -080053 const int id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000054};
55
56// This isn't elegant, but it's better than an external reference
57static SrtpCipherMapEntry SrtpCipherMap[] = {
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -080058 {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80},
59 {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32},
jbauchcb560652016-08-04 05:20:32 -070060 {"SRTP_AEAD_AES_128_GCM", SRTP_AEAD_AES_128_GCM},
61 {"SRTP_AEAD_AES_256_GCM", SRTP_AEAD_AES_256_GCM},
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -080062 {nullptr, 0}};
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010063#endif
64
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -070065#ifdef OPENSSL_IS_BORINGSSL
66static void TimeCallback(const SSL* ssl, struct timeval* out_clock) {
67 uint64_t time = TimeNanos();
68 out_clock->tv_sec = time / kNumNanosecsPerSec;
69 out_clock->tv_usec = time / kNumNanosecsPerMicrosec;
70}
71#else // #ifdef OPENSSL_IS_BORINGSSL
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010072
73// Cipher name table. Maps internal OpenSSL cipher ids to the RFC name.
74struct SslCipherMapEntry {
75 uint32_t openssl_id;
76 const char* rfc_name;
77};
78
79#define DEFINE_CIPHER_ENTRY_SSL3(name) {SSL3_CK_##name, "TLS_"#name}
80#define DEFINE_CIPHER_ENTRY_TLS1(name) {TLS1_CK_##name, "TLS_"#name}
81
82// There currently is no method available to get a RFC-compliant name for a
83// cipher suite from BoringSSL, so we need to define the mapping manually here.
84// This should go away once BoringSSL supports "SSL_CIPHER_standard_name"
85// (as available in OpenSSL if compiled with tracing enabled) or a similar
86// method.
87static const SslCipherMapEntry kSslCipherMap[] = {
88 // TLS v1.0 ciphersuites from RFC2246.
89 DEFINE_CIPHER_ENTRY_SSL3(RSA_RC4_128_SHA),
90 {SSL3_CK_RSA_DES_192_CBC3_SHA,
91 "TLS_RSA_WITH_3DES_EDE_CBC_SHA"},
92
93 // AES ciphersuites from RFC3268.
94 {TLS1_CK_RSA_WITH_AES_128_SHA,
95 "TLS_RSA_WITH_AES_128_CBC_SHA"},
96 {TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
97 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
98 {TLS1_CK_RSA_WITH_AES_256_SHA,
99 "TLS_RSA_WITH_AES_256_CBC_SHA"},
100 {TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
101 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
102
103 // ECC ciphersuites from RFC4492.
104 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_RC4_128_SHA),
105 {TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA,
106 "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"},
107 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
108 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
109
110 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_RC4_128_SHA),
111 {TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA,
112 "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"},
113 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_CBC_SHA),
114 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_CBC_SHA),
115
116 // TLS v1.2 ciphersuites.
117 {TLS1_CK_RSA_WITH_AES_128_SHA256,
118 "TLS_RSA_WITH_AES_128_CBC_SHA256"},
119 {TLS1_CK_RSA_WITH_AES_256_SHA256,
120 "TLS_RSA_WITH_AES_256_CBC_SHA256"},
121 {TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
122 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"},
123 {TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
124 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"},
125
126 // TLS v1.2 GCM ciphersuites from RFC5288.
127 DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_128_GCM_SHA256),
128 DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_256_GCM_SHA384),
129 DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_128_GCM_SHA256),
130 DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_256_GCM_SHA384),
131 DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_128_GCM_SHA256),
132 DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_256_GCM_SHA384),
133
134 // ECDH HMAC based ciphersuites from RFC5289.
135 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
136 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"},
137 {TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
138 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"},
139 {TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
140 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"},
141 {TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
142 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"},
143
144 // ECDH GCM based ciphersuites from RFC5289.
145 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
146 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
147 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_GCM_SHA256),
148 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_GCM_SHA384),
149
150 {0, NULL}
151};
152#endif // #ifndef OPENSSL_IS_BORINGSSL
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000153
Guo-wei Shieh456696a2015-09-30 21:48:54 -0700154#if defined(_MSC_VER)
155#pragma warning(push)
156#pragma warning(disable : 4309)
157#pragma warning(disable : 4310)
158#endif // defined(_MSC_VER)
159
Guo-wei Shieh456696a2015-09-30 21:48:54 -0700160#if defined(_MSC_VER)
161#pragma warning(pop)
162#endif // defined(_MSC_VER)
163
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164//////////////////////////////////////////////////////////////////////
165// StreamBIO
166//////////////////////////////////////////////////////////////////////
167
168static int stream_write(BIO* h, const char* buf, int num);
169static int stream_read(BIO* h, char* buf, int size);
170static int stream_puts(BIO* h, const char* str);
171static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
172static int stream_new(BIO* h);
173static int stream_free(BIO* data);
174
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +0000175// TODO(davidben): This should be const once BoringSSL is assumed.
176static BIO_METHOD methods_stream = {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177 BIO_TYPE_BIO,
178 "stream",
179 stream_write,
180 stream_read,
181 stream_puts,
182 0,
183 stream_ctrl,
184 stream_new,
185 stream_free,
186 NULL,
187};
188
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +0000189static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190
191static BIO* BIO_new_stream(StreamInterface* stream) {
192 BIO* ret = BIO_new(BIO_s_stream());
193 if (ret == NULL)
194 return NULL;
195 ret->ptr = stream;
196 return ret;
197}
198
199// bio methods return 1 (or at least non-zero) on success and 0 on failure.
200
201static int stream_new(BIO* b) {
202 b->shutdown = 0;
203 b->init = 1;
204 b->num = 0; // 1 means end-of-stream
205 b->ptr = 0;
206 return 1;
207}
208
209static int stream_free(BIO* b) {
210 if (b == NULL)
211 return 0;
212 return 1;
213}
214
215static int stream_read(BIO* b, char* out, int outl) {
216 if (!out)
217 return -1;
218 StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
219 BIO_clear_retry_flags(b);
220 size_t read;
221 int error;
222 StreamResult result = stream->Read(out, outl, &read, &error);
223 if (result == SR_SUCCESS) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000224 return checked_cast<int>(read);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000225 } else if (result == SR_EOS) {
226 b->num = 1;
227 } else if (result == SR_BLOCK) {
228 BIO_set_retry_read(b);
229 }
230 return -1;
231}
232
233static int stream_write(BIO* b, const char* in, int inl) {
234 if (!in)
235 return -1;
236 StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
237 BIO_clear_retry_flags(b);
238 size_t written;
239 int error;
240 StreamResult result = stream->Write(in, inl, &written, &error);
241 if (result == SR_SUCCESS) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000242 return checked_cast<int>(written);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000243 } else if (result == SR_BLOCK) {
244 BIO_set_retry_write(b);
245 }
246 return -1;
247}
248
249static int stream_puts(BIO* b, const char* str) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000250 return stream_write(b, str, checked_cast<int>(strlen(str)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251}
252
253static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
henrike@webrtc.org14abcc72014-05-16 16:54:44 +0000254 RTC_UNUSED(num);
255 RTC_UNUSED(ptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256
257 switch (cmd) {
258 case BIO_CTRL_RESET:
259 return 0;
260 case BIO_CTRL_EOF:
261 return b->num;
262 case BIO_CTRL_WPENDING:
263 case BIO_CTRL_PENDING:
264 return 0;
265 case BIO_CTRL_FLUSH:
266 return 1;
Henrik Lundinf4baca52015-06-10 09:45:58 +0200267 case BIO_CTRL_DGRAM_QUERY_MTU:
268 // openssl defaults to mtu=256 unless we return something here.
269 // The handshake doesn't actually need to send packets above 1k,
270 // so this seems like a sensible value that should work in most cases.
271 // Webrtc uses the same value for video packets.
272 return 1200;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 default:
274 return 0;
275 }
276}
277
278/////////////////////////////////////////////////////////////////////////////
279// OpenSSLStreamAdapter
280/////////////////////////////////////////////////////////////////////////////
281
282OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
283 : SSLStreamAdapter(stream),
284 state_(SSL_NONE),
285 role_(SSL_CLIENT),
Guo-wei Shieha7446d22016-01-11 15:27:03 -0800286 ssl_read_needs_write_(false),
287 ssl_write_needs_read_(false),
288 ssl_(NULL),
289 ssl_ctx_(NULL),
Joachim Bauch831c5582015-05-20 12:48:41 +0200290 ssl_mode_(SSL_MODE_TLS),
Guo-wei Shieha7446d22016-01-11 15:27:03 -0800291 ssl_max_version_(SSL_PROTOCOL_TLS_12) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292
293OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
deadbeef89824f62016-09-30 11:55:43 -0700294 Cleanup(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295}
296
297void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
deadbeef89824f62016-09-30 11:55:43 -0700298 RTC_DCHECK(!identity_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299 identity_.reset(static_cast<OpenSSLIdentity*>(identity));
300}
301
302void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
303 role_ = role;
304}
305
jbauch555604a2016-04-26 03:13:22 -0700306std::unique_ptr<SSLCertificate> OpenSSLStreamAdapter::GetPeerCertificate()
kwibergb4d01c42016-04-06 05:15:06 -0700307 const {
jbauch555604a2016-04-26 03:13:22 -0700308 return peer_certificate_ ? std::unique_ptr<SSLCertificate>(
kwibergb4d01c42016-04-06 05:15:06 -0700309 peer_certificate_->GetReference())
310 : nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311}
312
deadbeef89824f62016-09-30 11:55:43 -0700313bool OpenSSLStreamAdapter::SetPeerCertificateDigest(
314 const std::string& digest_alg,
315 const unsigned char* digest_val,
316 size_t digest_len,
317 SSLPeerCertificateDigestError* error) {
318 RTC_DCHECK(!peer_certificate_verified_);
319 RTC_DCHECK(!has_peer_certificate_digest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320 size_t expected_len;
deadbeef89824f62016-09-30 11:55:43 -0700321 if (error) {
322 *error = SSLPeerCertificateDigestError::NONE;
323 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324
325 if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
326 LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
deadbeef89824f62016-09-30 11:55:43 -0700327 if (error) {
328 *error = SSLPeerCertificateDigestError::UNKNOWN_ALGORITHM;
329 }
deadbeef81f6f4f2016-09-19 17:20:52 -0700330 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331 }
deadbeef89824f62016-09-30 11:55:43 -0700332 if (expected_len != digest_len) {
333 if (error) {
334 *error = SSLPeerCertificateDigestError::INVALID_LENGTH;
335 }
deadbeef81f6f4f2016-09-19 17:20:52 -0700336 return false;
deadbeef89824f62016-09-30 11:55:43 -0700337 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000338
339 peer_certificate_digest_value_.SetData(digest_val, digest_len);
340 peer_certificate_digest_algorithm_ = digest_alg;
341
deadbeef89824f62016-09-30 11:55:43 -0700342 if (!peer_certificate_) {
343 // Normal case, where the digest is set before we obtain the certificate
344 // from the handshake.
345 return true;
346 }
347
348 if (!VerifyPeerCertificate()) {
349 Error("SetPeerCertificateDigest", -1, SSL_AD_BAD_CERTIFICATE, false);
350 if (error) {
351 *error = SSLPeerCertificateDigestError::VERIFICATION_FAILED;
352 }
353 return false;
354 }
355
356 if (state_ == SSL_CONNECTED) {
357 // Post the event asynchronously to unwind the stack. The caller
358 // of ContinueSSL may be the same object listening for these
359 // events and may not be prepared for reentrancy.
360 PostEvent(SE_OPEN | SE_READ | SE_WRITE, 0);
361 }
362
deadbeef81f6f4f2016-09-19 17:20:52 -0700363 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000364}
365
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800366std::string OpenSSLStreamAdapter::SslCipherSuiteToName(int cipher_suite) {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100367#ifdef OPENSSL_IS_BORINGSSL
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800368 const SSL_CIPHER* ssl_cipher = SSL_get_cipher_by_value(cipher_suite);
Guo-wei Shieh456696a2015-09-30 21:48:54 -0700369 if (!ssl_cipher) {
370 return std::string();
371 }
372 char* cipher_name = SSL_CIPHER_get_rfc_name(ssl_cipher);
373 std::string rfc_name = std::string(cipher_name);
374 OPENSSL_free(cipher_name);
375 return rfc_name;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100376#else
377 for (const SslCipherMapEntry* entry = kSslCipherMap; entry->rfc_name;
378 ++entry) {
379 if (cipher_suite == static_cast<int>(entry->openssl_id)) {
380 return entry->rfc_name;
381 }
382 }
383 return std::string();
384#endif
Guo-wei Shieh456696a2015-09-30 21:48:54 -0700385}
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000386
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800387bool OpenSSLStreamAdapter::GetSslCipherSuite(int* cipher_suite) {
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000388 if (state_ != SSL_CONNECTED)
389 return false;
390
391 const SSL_CIPHER* current_cipher = SSL_get_current_cipher(ssl_);
392 if (current_cipher == NULL) {
393 return false;
394 }
395
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800396 *cipher_suite = static_cast<uint16_t>(SSL_CIPHER_get_id(current_cipher));
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000397 return true;
398}
399
torbjorng43166b82016-03-11 00:06:47 -0800400int OpenSSLStreamAdapter::GetSslVersion() const {
401 if (state_ != SSL_CONNECTED)
402 return -1;
403
404 int ssl_version = SSL_version(ssl_);
405 if (ssl_mode_ == SSL_MODE_DTLS) {
406 if (ssl_version == DTLS1_VERSION)
407 return SSL_PROTOCOL_DTLS_10;
408 else if (ssl_version == DTLS1_2_VERSION)
409 return SSL_PROTOCOL_DTLS_12;
410 } else {
411 if (ssl_version == TLS1_VERSION)
412 return SSL_PROTOCOL_TLS_10;
413 else if (ssl_version == TLS1_1_VERSION)
414 return SSL_PROTOCOL_TLS_11;
415 else if (ssl_version == TLS1_2_VERSION)
416 return SSL_PROTOCOL_TLS_12;
417 }
418
419 return -1;
420}
421
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000422// Key Extractor interface
423bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200424 const uint8_t* context,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000425 size_t context_len,
426 bool use_context,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200427 uint8_t* result,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000428 size_t result_len) {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100429#ifdef HAVE_DTLS_SRTP
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000430 int i;
431
Peter Boström0c4e06b2015-10-07 12:23:21 +0200432 i = SSL_export_keying_material(ssl_, result, result_len, label.c_str(),
433 label.length(), const_cast<uint8_t*>(context),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000434 context_len, use_context);
435
436 if (i != 1)
437 return false;
438
439 return true;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100440#else
441 return false;
442#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000443}
444
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800445bool OpenSSLStreamAdapter::SetDtlsSrtpCryptoSuites(
446 const std::vector<int>& ciphers) {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100447#ifdef HAVE_DTLS_SRTP
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000448 std::string internal_ciphers;
449
450 if (state_ != SSL_NONE)
451 return false;
452
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800453 for (std::vector<int>::const_iterator cipher = ciphers.begin();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000454 cipher != ciphers.end(); ++cipher) {
455 bool found = false;
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800456 for (SrtpCipherMapEntry* entry = SrtpCipherMap; entry->internal_name;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000457 ++entry) {
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800458 if (*cipher == entry->id) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000459 found = true;
460 if (!internal_ciphers.empty())
461 internal_ciphers += ":";
462 internal_ciphers += entry->internal_name;
463 break;
464 }
465 }
466
467 if (!found) {
468 LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
469 return false;
470 }
471 }
472
473 if (internal_ciphers.empty())
474 return false;
475
476 srtp_ciphers_ = internal_ciphers;
477 return true;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100478#else
479 return false;
480#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000481}
482
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800483bool OpenSSLStreamAdapter::GetDtlsSrtpCryptoSuite(int* crypto_suite) {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100484#ifdef HAVE_DTLS_SRTP
deadbeef89824f62016-09-30 11:55:43 -0700485 RTC_DCHECK(state_ == SSL_CONNECTED);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000486 if (state_ != SSL_CONNECTED)
487 return false;
488
henrike@webrtc.orgc10ecea2015-01-07 17:59:28 +0000489 const SRTP_PROTECTION_PROFILE *srtp_profile =
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000490 SSL_get_selected_srtp_profile(ssl_);
491
492 if (!srtp_profile)
493 return false;
494
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800495 *crypto_suite = srtp_profile->id;
deadbeef89824f62016-09-30 11:55:43 -0700496 RTC_DCHECK(!SrtpCryptoSuiteToName(*crypto_suite).empty());
Guo-wei Shieh521ed7b2015-11-18 19:41:53 -0800497 return true;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100498#else
499 return false;
500#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000501}
502
deadbeef89824f62016-09-30 11:55:43 -0700503bool OpenSSLStreamAdapter::IsTlsConnected() {
504 return state_ == SSL_CONNECTED;
505}
506
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700507int OpenSSLStreamAdapter::StartSSL() {
deadbeef89824f62016-09-30 11:55:43 -0700508 if (state_ != SSL_NONE) {
509 // Don't allow StartSSL to be called twice.
510 return -1;
511 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700513 if (StreamAdapterInterface::GetState() != SS_OPEN) {
514 state_ = SSL_WAIT;
515 return 0;
516 }
517
518 state_ = SSL_CONNECTING;
519 if (int err = BeginSSL()) {
deadbeef89824f62016-09-30 11:55:43 -0700520 Error("BeginSSL", err, 0, false);
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700521 return err;
522 }
523
524 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000525}
526
527void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
deadbeef89824f62016-09-30 11:55:43 -0700528 RTC_DCHECK(state_ == SSL_NONE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000529 ssl_mode_ = mode;
530}
531
Joachim Bauch831c5582015-05-20 12:48:41 +0200532void OpenSSLStreamAdapter::SetMaxProtocolVersion(SSLProtocolVersion version) {
deadbeef89824f62016-09-30 11:55:43 -0700533 RTC_DCHECK(ssl_ctx_ == NULL);
Joachim Bauch831c5582015-05-20 12:48:41 +0200534 ssl_max_version_ = version;
535}
536
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537//
538// StreamInterface Implementation
539//
540
541StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
542 size_t* written, int* error) {
543 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
544
545 switch (state_) {
546 case SSL_NONE:
547 // pass-through in clear text
548 return StreamAdapterInterface::Write(data, data_len, written, error);
549
550 case SSL_WAIT:
551 case SSL_CONNECTING:
552 return SR_BLOCK;
553
554 case SSL_CONNECTED:
deadbeef89824f62016-09-30 11:55:43 -0700555 if (waiting_to_verify_peer_certificate()) {
556 return SR_BLOCK;
557 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000558 break;
559
560 case SSL_ERROR:
561 case SSL_CLOSED:
562 default:
563 if (error)
564 *error = ssl_error_code_;
565 return SR_ERROR;
566 }
567
568 // OpenSSL will return an error if we try to write zero bytes
569 if (data_len == 0) {
570 if (written)
571 *written = 0;
572 return SR_SUCCESS;
573 }
574
575 ssl_write_needs_read_ = false;
576
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000577 int code = SSL_write(ssl_, data, checked_cast<int>(data_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000578 int ssl_error = SSL_get_error(ssl_, code);
579 switch (ssl_error) {
580 case SSL_ERROR_NONE:
581 LOG(LS_VERBOSE) << " -- success";
deadbeef89824f62016-09-30 11:55:43 -0700582 RTC_DCHECK(0 < code && static_cast<unsigned>(code) <= data_len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000583 if (written)
584 *written = code;
585 return SR_SUCCESS;
586 case SSL_ERROR_WANT_READ:
587 LOG(LS_VERBOSE) << " -- error want read";
588 ssl_write_needs_read_ = true;
589 return SR_BLOCK;
590 case SSL_ERROR_WANT_WRITE:
591 LOG(LS_VERBOSE) << " -- error want write";
592 return SR_BLOCK;
593
594 case SSL_ERROR_ZERO_RETURN:
595 default:
deadbeef89824f62016-09-30 11:55:43 -0700596 Error("SSL_write", (ssl_error ? ssl_error : -1), 0, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000597 if (error)
598 *error = ssl_error_code_;
599 return SR_ERROR;
600 }
601 // not reached
602}
603
604StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
605 size_t* read, int* error) {
606 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
607 switch (state_) {
608 case SSL_NONE:
609 // pass-through in clear text
610 return StreamAdapterInterface::Read(data, data_len, read, error);
611
612 case SSL_WAIT:
613 case SSL_CONNECTING:
614 return SR_BLOCK;
615
616 case SSL_CONNECTED:
deadbeef89824f62016-09-30 11:55:43 -0700617 if (waiting_to_verify_peer_certificate()) {
618 return SR_BLOCK;
619 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000620 break;
621
622 case SSL_CLOSED:
623 return SR_EOS;
624
625 case SSL_ERROR:
626 default:
627 if (error)
628 *error = ssl_error_code_;
629 return SR_ERROR;
630 }
631
632 // Don't trust OpenSSL with zero byte reads
633 if (data_len == 0) {
634 if (read)
635 *read = 0;
636 return SR_SUCCESS;
637 }
638
639 ssl_read_needs_write_ = false;
640
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000641 int code = SSL_read(ssl_, data, checked_cast<int>(data_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000642 int ssl_error = SSL_get_error(ssl_, code);
643 switch (ssl_error) {
644 case SSL_ERROR_NONE:
645 LOG(LS_VERBOSE) << " -- success";
deadbeef89824f62016-09-30 11:55:43 -0700646 RTC_DCHECK(0 < code && static_cast<unsigned>(code) <= data_len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000647 if (read)
648 *read = code;
649
650 if (ssl_mode_ == SSL_MODE_DTLS) {
651 // Enforce atomic reads -- this is a short read
652 unsigned int pending = SSL_pending(ssl_);
653
654 if (pending) {
655 LOG(LS_INFO) << " -- short DTLS read. flushing";
656 FlushInput(pending);
657 if (error)
658 *error = SSE_MSG_TRUNC;
659 return SR_ERROR;
660 }
661 }
662 return SR_SUCCESS;
663 case SSL_ERROR_WANT_READ:
664 LOG(LS_VERBOSE) << " -- error want read";
665 return SR_BLOCK;
666 case SSL_ERROR_WANT_WRITE:
667 LOG(LS_VERBOSE) << " -- error want write";
668 ssl_read_needs_write_ = true;
669 return SR_BLOCK;
670 case SSL_ERROR_ZERO_RETURN:
671 LOG(LS_VERBOSE) << " -- remote side closed";
deadbeef89824f62016-09-30 11:55:43 -0700672 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000673 return SR_EOS;
674 break;
675 default:
676 LOG(LS_VERBOSE) << " -- error " << code;
deadbeef89824f62016-09-30 11:55:43 -0700677 Error("SSL_read", (ssl_error ? ssl_error : -1), 0, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000678 if (error)
679 *error = ssl_error_code_;
680 return SR_ERROR;
681 }
682 // not reached
683}
684
685void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
686 unsigned char buf[2048];
687
688 while (left) {
689 // This should always succeed
690 int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
691 int code = SSL_read(ssl_, buf, toread);
692
693 int ssl_error = SSL_get_error(ssl_, code);
deadbeef89824f62016-09-30 11:55:43 -0700694 RTC_DCHECK(ssl_error == SSL_ERROR_NONE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000695
696 if (ssl_error != SSL_ERROR_NONE) {
697 LOG(LS_VERBOSE) << " -- error " << code;
deadbeef89824f62016-09-30 11:55:43 -0700698 Error("SSL_read", (ssl_error ? ssl_error : -1), 0, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000699 return;
700 }
701
702 LOG(LS_VERBOSE) << " -- flushed " << code << " bytes";
703 left -= code;
704 }
705}
706
707void OpenSSLStreamAdapter::Close() {
deadbeef89824f62016-09-30 11:55:43 -0700708 Cleanup(0);
709 RTC_DCHECK(state_ == SSL_CLOSED || state_ == SSL_ERROR);
710 // When we're closed at SSL layer, also close the stream level which
711 // performs necessary clean up. Otherwise, a new incoming packet after
712 // this could overflow the stream buffer.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000713 StreamAdapterInterface::Close();
714}
715
716StreamState OpenSSLStreamAdapter::GetState() const {
717 switch (state_) {
718 case SSL_WAIT:
719 case SSL_CONNECTING:
720 return SS_OPENING;
721 case SSL_CONNECTED:
deadbeef89824f62016-09-30 11:55:43 -0700722 if (waiting_to_verify_peer_certificate()) {
723 return SS_OPENING;
724 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000725 return SS_OPEN;
726 default:
727 return SS_CLOSED;
728 };
729 // not reached
730}
731
732void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
733 int err) {
734 int events_to_signal = 0;
735 int signal_error = 0;
deadbeef89824f62016-09-30 11:55:43 -0700736 RTC_DCHECK(stream == this->stream());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000737 if ((events & SE_OPEN)) {
738 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
739 if (state_ != SSL_WAIT) {
deadbeef89824f62016-09-30 11:55:43 -0700740 RTC_DCHECK(state_ == SSL_NONE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000741 events_to_signal |= SE_OPEN;
742 } else {
743 state_ = SSL_CONNECTING;
744 if (int err = BeginSSL()) {
deadbeef89824f62016-09-30 11:55:43 -0700745 Error("BeginSSL", err, 0, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000746 return;
747 }
748 }
749 }
750 if ((events & (SE_READ|SE_WRITE))) {
751 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()) {
deadbeef89824f62016-09-30 11:55:43 -0700758 Error("ContinueSSL", err, 0, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000759 return;
760 }
761 } else if (state_ == SSL_CONNECTED) {
762 if (((events & SE_READ) && ssl_write_needs_read_) ||
763 (events & SE_WRITE)) {
764 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 LOG(LS_VERBOSE) << " -- onStreamReadable";
770 events_to_signal |= SE_READ;
771 }
772 }
773 }
774 if ((events & SE_CLOSE)) {
775 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
deadbeef89824f62016-09-30 11:55:43 -0700776 Cleanup(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000777 events_to_signal |= SE_CLOSE;
778 // SE_CLOSE is the only event that uses the final parameter to OnEvent().
deadbeef89824f62016-09-30 11:55:43 -0700779 RTC_DCHECK(signal_error == 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000780 signal_error = err;
781 }
782 if (events_to_signal)
783 StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
784}
785
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000786int OpenSSLStreamAdapter::BeginSSL() {
deadbeef89824f62016-09-30 11:55:43 -0700787 RTC_DCHECK(state_ == SSL_CONNECTING);
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700788 // The underlying stream has opened.
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700789 LOG(LS_INFO) << "BeginSSL with peer.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000790
791 BIO* bio = NULL;
792
Taylor Brandstetterc8762a82016-08-11 12:01:49 -0700793 // First set up the context.
deadbeef89824f62016-09-30 11:55:43 -0700794 RTC_DCHECK(ssl_ctx_ == NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000795 ssl_ctx_ = SetupSSLContext();
796 if (!ssl_ctx_)
797 return -1;
798
799 bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
800 if (!bio)
801 return -1;
802
803 ssl_ = SSL_new(ssl_ctx_);
804 if (!ssl_) {
805 BIO_free(bio);
806 return -1;
807 }
808
809 SSL_set_app_data(ssl_, this);
810
811 SSL_set_bio(ssl_, bio, bio); // the SSL object owns the bio now.
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100812 if (ssl_mode_ == SSL_MODE_DTLS) {
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -0700813#ifdef OPENSSL_IS_BORINGSSL
814 // Change the initial retransmission timer from 1 second to 50ms.
815 // This will likely result in some spurious retransmissions, but
816 // it's useful for ensuring a timely handshake when there's packet
817 // loss.
818 DTLSv1_set_initial_timeout_duration(ssl_, 50);
819#else
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100820 // Enable read-ahead for DTLS so whole packets are read from internal BIO
821 // before parsing. This is done internally by BoringSSL for DTLS.
822 SSL_set_read_ahead(ssl_, 1);
philipel49c08692016-05-24 01:49:43 -0700823#endif
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -0700824 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000825
826 SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
827 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
828
David Benjamin60d5f3f2016-03-24 13:28:25 -0400829#if !defined(OPENSSL_IS_BORINGSSL)
830 // Specify an ECDH group for ECDHE ciphers, otherwise OpenSSL cannot
831 // negotiate them when acting as the server. Use NIST's P-256 which is
832 // commonly supported. BoringSSL doesn't need explicit configuration and has
833 // a reasonable default set.
jiayl@webrtc.org11c6bde2014-08-28 16:14:38 +0000834 EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
835 if (ecdh == NULL)
836 return -1;
837 SSL_set_options(ssl_, SSL_OP_SINGLE_ECDH_USE);
838 SSL_set_tmp_ecdh(ssl_, ecdh);
839 EC_KEY_free(ecdh);
David Benjamin60d5f3f2016-03-24 13:28:25 -0400840#endif
jiayl@webrtc.org11c6bde2014-08-28 16:14:38 +0000841
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000842 // Do the connect
843 return ContinueSSL();
844}
845
846int OpenSSLStreamAdapter::ContinueSSL() {
847 LOG(LS_VERBOSE) << "ContinueSSL";
deadbeef89824f62016-09-30 11:55:43 -0700848 RTC_DCHECK(state_ == SSL_CONNECTING);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000849
850 // Clear the DTLS timer
851 Thread::Current()->Clear(this, MSG_TIMEOUT);
852
853 int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
854 int ssl_error;
855 switch (ssl_error = SSL_get_error(ssl_, code)) {
856 case SSL_ERROR_NONE:
857 LOG(LS_VERBOSE) << " -- success";
deadbeef89824f62016-09-30 11:55:43 -0700858 // By this point, OpenSSL should have given us a certificate, or errored
859 // out if one was missing.
860 RTC_DCHECK(peer_certificate_ || !client_auth_enabled());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000861
862 state_ = SSL_CONNECTED;
deadbeef89824f62016-09-30 11:55:43 -0700863 if (!waiting_to_verify_peer_certificate()) {
864 // We have everything we need to start the connection, so signal
865 // SE_OPEN. If we need a client certificate fingerprint and don't have
866 // it yet, we'll instead signal SE_OPEN in SetPeerCertificateDigest.
867 //
868 // Post the event asynchronously to unwind the stack. The
869 // caller of ContinueSSL may be the same object listening
870 // for these events and may not be prepared for reentrancy.
871 PostEvent(SE_OPEN | SE_READ | SE_WRITE, 0);
872 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000873 break;
874
875 case SSL_ERROR_WANT_READ: {
876 LOG(LS_VERBOSE) << " -- error want read";
877 struct timeval timeout;
878 if (DTLSv1_get_timeout(ssl_, &timeout)) {
879 int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
880
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700881 Thread::Current()->PostDelayed(RTC_FROM_HERE, delay, this,
882 MSG_TIMEOUT, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000883 }
884 }
885 break;
886
887 case SSL_ERROR_WANT_WRITE:
888 LOG(LS_VERBOSE) << " -- error want write";
889 break;
890
891 case SSL_ERROR_ZERO_RETURN:
892 default:
893 LOG(LS_VERBOSE) << " -- error " << code;
zhihuangd82eee02016-08-26 11:25:05 -0700894 SSLHandshakeError ssl_handshake_err = SSLHandshakeError::UNKNOWN;
895 int err_code = ERR_peek_last_error();
896 if (err_code != 0 && ERR_GET_REASON(err_code) == SSL_R_NO_SHARED_CIPHER) {
897 ssl_handshake_err = SSLHandshakeError::INCOMPATIBLE_CIPHERSUITE;
898 }
899 SignalSSLHandshakeError(ssl_handshake_err);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000900 return (ssl_error != 0) ? ssl_error : -1;
901 }
902
903 return 0;
904}
905
deadbeef89824f62016-09-30 11:55:43 -0700906void OpenSSLStreamAdapter::Error(const char* context,
907 int err,
908 uint8_t alert,
909 bool signal) {
910 LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error(" << context << ", " << err
911 << ", " << static_cast<int>(alert) << ")";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000912 state_ = SSL_ERROR;
913 ssl_error_code_ = err;
deadbeef89824f62016-09-30 11:55:43 -0700914 Cleanup(alert);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000915 if (signal)
916 StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
917}
918
deadbeef89824f62016-09-30 11:55:43 -0700919void OpenSSLStreamAdapter::Cleanup(uint8_t alert) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000920 LOG(LS_INFO) << "Cleanup";
921
922 if (state_ != SSL_ERROR) {
923 state_ = SSL_CLOSED;
924 ssl_error_code_ = 0;
925 }
926
927 if (ssl_) {
deadbeef89824f62016-09-30 11:55:43 -0700928 int ret;
929// SSL_send_fatal_alert is only available in BoringSSL.
930#ifdef OPENSSL_IS_BORINGSSL
931 if (alert) {
932 ret = SSL_send_fatal_alert(ssl_, alert);
933 if (ret < 0) {
934 LOG(LS_WARNING) << "SSL_send_fatal_alert failed, error = "
935 << SSL_get_error(ssl_, ret);
936 }
937 } else {
938#endif
939 ret = SSL_shutdown(ssl_);
940 if (ret < 0) {
941 LOG(LS_WARNING) << "SSL_shutdown failed, error = "
942 << SSL_get_error(ssl_, ret);
943 }
944#ifdef OPENSSL_IS_BORINGSSL
jiayl@webrtc.orgf1d751c2014-09-25 16:38:46 +0000945 }
deadbeef89824f62016-09-30 11:55:43 -0700946#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000947 SSL_free(ssl_);
948 ssl_ = NULL;
949 }
950 if (ssl_ctx_) {
951 SSL_CTX_free(ssl_ctx_);
952 ssl_ctx_ = NULL;
953 }
954 identity_.reset();
955 peer_certificate_.reset();
956
957 // Clear the DTLS timer
958 Thread::Current()->Clear(this, MSG_TIMEOUT);
959}
960
961
962void OpenSSLStreamAdapter::OnMessage(Message* msg) {
963 // Process our own messages and then pass others to the superclass
964 if (MSG_TIMEOUT == msg->message_id) {
965 LOG(LS_INFO) << "DTLS timeout expired";
966 DTLSv1_handle_timeout(ssl_);
967 ContinueSSL();
968 } else {
969 StreamInterface::OnMessage(msg);
970 }
971}
972
973SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
974 SSL_CTX *ctx = NULL;
975
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100976#ifdef OPENSSL_IS_BORINGSSL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000977 ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
Joachim Bauch831c5582015-05-20 12:48:41 +0200978 DTLS_method() : TLS_method());
979 // Version limiting for BoringSSL will be done below.
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100980#else
981 const SSL_METHOD* method;
982 switch (ssl_max_version_) {
983 case SSL_PROTOCOL_TLS_10:
984 case SSL_PROTOCOL_TLS_11:
985 // OpenSSL doesn't support setting min/max versions, so we always use
986 // (D)TLS 1.0 if a max. version below the max. available is requested.
987 if (ssl_mode_ == SSL_MODE_DTLS) {
988 if (role_ == SSL_CLIENT) {
989 method = DTLSv1_client_method();
990 } else {
991 method = DTLSv1_server_method();
992 }
993 } else {
994 if (role_ == SSL_CLIENT) {
995 method = TLSv1_client_method();
996 } else {
997 method = TLSv1_server_method();
998 }
999 }
1000 break;
1001 case SSL_PROTOCOL_TLS_12:
1002 default:
1003 if (ssl_mode_ == SSL_MODE_DTLS) {
1004#if (OPENSSL_VERSION_NUMBER >= 0x10002000L)
1005 // DTLS 1.2 only available starting from OpenSSL 1.0.2
1006 if (role_ == SSL_CLIENT) {
1007 method = DTLS_client_method();
1008 } else {
1009 method = DTLS_server_method();
1010 }
1011#else
1012 if (role_ == SSL_CLIENT) {
1013 method = DTLSv1_client_method();
1014 } else {
1015 method = DTLSv1_server_method();
1016 }
1017#endif
1018 } else {
1019#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1020 // New API only available starting from OpenSSL 1.1.0
1021 if (role_ == SSL_CLIENT) {
1022 method = TLS_client_method();
1023 } else {
1024 method = TLS_server_method();
1025 }
1026#else
1027 if (role_ == SSL_CLIENT) {
1028 method = SSLv23_client_method();
1029 } else {
1030 method = SSLv23_server_method();
1031 }
1032#endif
1033 }
1034 break;
1035 }
1036 ctx = SSL_CTX_new(method);
1037#endif // OPENSSL_IS_BORINGSSL
Joachim Bauch831c5582015-05-20 12:48:41 +02001038
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001039 if (ctx == NULL)
1040 return NULL;
1041
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001042#ifdef OPENSSL_IS_BORINGSSL
Joachim Bauch831c5582015-05-20 12:48:41 +02001043 SSL_CTX_set_min_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
1044 DTLS1_VERSION : TLS1_VERSION);
1045 switch (ssl_max_version_) {
1046 case SSL_PROTOCOL_TLS_10:
1047 SSL_CTX_set_max_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
1048 DTLS1_VERSION : TLS1_VERSION);
1049 break;
1050 case SSL_PROTOCOL_TLS_11:
1051 SSL_CTX_set_max_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
1052 DTLS1_VERSION : TLS1_1_VERSION);
1053 break;
1054 case SSL_PROTOCOL_TLS_12:
1055 default:
1056 SSL_CTX_set_max_version(ctx, ssl_mode_ == SSL_MODE_DTLS ?
1057 DTLS1_2_VERSION : TLS1_2_VERSION);
1058 break;
1059 }
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -07001060 // Set a time callback for BoringSSL because:
1061 // 1. Our time function is more accurate (doesn't just use gettimeofday).
1062 // 2. This allows us to inject a fake clock for testing.
deadbeefd685fef2016-06-20 12:00:44 -07001063 SSL_CTX_set_current_time_cb(ctx, &TimeCallback);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001064#endif
Joachim Bauch831c5582015-05-20 12:48:41 +02001065
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001066 if (identity_ && !identity_->ConfigureIdentity(ctx)) {
1067 SSL_CTX_free(ctx);
1068 return NULL;
1069 }
1070
tfarinaa41ab932015-10-30 16:08:48 -07001071#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001072 SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
1073#endif
1074
tkchin@webrtc.orgc569a492014-09-23 05:56:44 +00001075 int mode = SSL_VERIFY_PEER;
1076 if (client_auth_enabled()) {
1077 // Require a certificate from the client.
1078 // Note: Normally this is always true in production, but it may be disabled
1079 // for testing purposes (e.g. SSLAdapter unit tests).
1080 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1081 }
1082
1083 SSL_CTX_set_verify(ctx, mode, SSLVerifyCallback);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001084 SSL_CTX_set_verify_depth(ctx, 4);
Joachim Bauch831c5582015-05-20 12:48:41 +02001085 // Select list of available ciphers. Note that !SHA256 and !SHA384 only
1086 // remove HMAC-SHA256 and HMAC-SHA384 cipher suites, not GCM cipher suites
1087 // with SHA256 or SHA384 as the handshake hash.
1088 // This matches the list of SSLClientSocketOpenSSL in Chromium.
1089 SSL_CTX_set_cipher_list(ctx,
1090 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001091
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001092#ifdef HAVE_DTLS_SRTP
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001093 if (!srtp_ciphers_.empty()) {
1094 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
1095 SSL_CTX_free(ctx);
1096 return NULL;
1097 }
1098 }
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001099#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001100
1101 return ctx;
1102}
1103
deadbeef89824f62016-09-30 11:55:43 -07001104bool OpenSSLStreamAdapter::VerifyPeerCertificate() {
1105 if (!has_peer_certificate_digest() || !peer_certificate_) {
1106 LOG(LS_WARNING) << "Missing digest or peer certificate.";
1107 return false;
1108 }
deadbeef81f6f4f2016-09-19 17:20:52 -07001109
deadbeef89824f62016-09-30 11:55:43 -07001110 unsigned char digest[EVP_MAX_MD_SIZE];
1111 size_t digest_length;
1112 if (!OpenSSLCertificate::ComputeDigest(
1113 peer_certificate_->x509(), peer_certificate_digest_algorithm_, digest,
1114 sizeof(digest), &digest_length)) {
1115 LOG(LS_WARNING) << "Failed to compute peer cert digest.";
1116 return false;
1117 }
1118
1119 Buffer computed_digest(digest, digest_length);
1120 if (computed_digest != peer_certificate_digest_value_) {
1121 LOG(LS_WARNING) << "Rejected peer certificate due to mismatched digest.";
deadbeef81f6f4f2016-09-19 17:20:52 -07001122 return 0;
1123 }
deadbeef89824f62016-09-30 11:55:43 -07001124 // Ignore any verification error if the digest matches, since there is no
1125 // value in checking the validity of a self-signed cert issued by untrusted
1126 // sources.
1127 LOG(LS_INFO) << "Accepted peer certificate.";
1128 peer_certificate_verified_ = true;
1129 return true;
1130}
1131
1132int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
1133 // Get our SSL structure from the store
1134 SSL* ssl = reinterpret_cast<SSL*>(
1135 X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx()));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001136 X509* cert = X509_STORE_CTX_get_current_cert(store);
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +00001137 int depth = X509_STORE_CTX_get_error_depth(store);
1138
deadbeef89824f62016-09-30 11:55:43 -07001139 // For now we ignore the parent certificates and verify the leaf against
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +00001140 // the digest.
1141 //
1142 // TODO(jiayl): Verify the chain is a proper chain and report the chain to
torbjorng07d09362015-09-22 11:58:04 -07001143 // |stream->peer_certificate_|.
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +00001144 if (depth > 0) {
1145 LOG(LS_INFO) << "Ignored chained certificate at depth " << depth;
1146 return 1;
1147 }
1148
deadbeef89824f62016-09-30 11:55:43 -07001149 OpenSSLStreamAdapter* stream =
1150 reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +00001151
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001152 // Record the peer's certificate.
1153 stream->peer_certificate_.reset(new OpenSSLCertificate(cert));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001154
deadbeef89824f62016-09-30 11:55:43 -07001155 // If the peer certificate digest isn't known yet, we'll wait to verify
1156 // until it's known, and for now just return a success status.
1157 if (stream->peer_certificate_digest_algorithm_.empty()) {
1158 LOG(LS_INFO) << "Waiting to verify certificate until digest is known.";
1159 return 1;
1160 }
1161
1162 return stream->VerifyPeerCertificate();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001163}
1164
1165bool OpenSSLStreamAdapter::HaveDtls() {
1166 return true;
1167}
1168
1169bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001170#ifdef HAVE_DTLS_SRTP
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001171 return true;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001172#else
1173 return false;
1174#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001175}
1176
1177bool OpenSSLStreamAdapter::HaveExporter() {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001178#ifdef HAVE_DTLS_SRTP
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001179 return true;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +01001180#else
1181 return false;
1182#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001183}
1184
Taylor Brandstetter4f0dfbd2016-06-15 17:15:23 -07001185bool OpenSSLStreamAdapter::IsBoringSsl() {
1186#ifdef OPENSSL_IS_BORINGSSL
1187 return true;
1188#else
1189 return false;
1190#endif
1191}
1192
torbjorng43166b82016-03-11 00:06:47 -08001193#define CDEF(X) \
1194 { static_cast<uint16_t>(TLS1_CK_##X & 0xffff), "TLS_" #X }
1195
1196struct cipher_list {
1197 uint16_t cipher;
1198 const char* cipher_str;
1199};
1200
1201// TODO(torbjorng): Perhaps add more cipher suites to these lists.
1202static const cipher_list OK_RSA_ciphers[] = {
1203 CDEF(ECDHE_RSA_WITH_AES_128_CBC_SHA),
1204 CDEF(ECDHE_RSA_WITH_AES_256_CBC_SHA),
1205 CDEF(ECDHE_RSA_WITH_AES_128_GCM_SHA256),
1206#ifdef TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA256
1207 CDEF(ECDHE_RSA_WITH_AES_256_GCM_SHA256),
1208#endif
torbjorngaad67802016-04-07 08:55:28 -07001209#ifdef TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
torbjorng43166b82016-03-11 00:06:47 -08001210 CDEF(ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256),
torbjorngaad67802016-04-07 08:55:28 -07001211#endif
torbjorng43166b82016-03-11 00:06:47 -08001212};
1213
1214static const cipher_list OK_ECDSA_ciphers[] = {
1215 CDEF(ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
1216 CDEF(ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
1217 CDEF(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
1218#ifdef TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA256
1219 CDEF(ECDHE_ECDSA_WITH_AES_256_GCM_SHA256),
1220#endif
torbjorngaad67802016-04-07 08:55:28 -07001221#ifdef TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
torbjorng43166b82016-03-11 00:06:47 -08001222 CDEF(ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256),
torbjorngaad67802016-04-07 08:55:28 -07001223#endif
torbjorng43166b82016-03-11 00:06:47 -08001224};
1225#undef CDEF
1226
1227bool OpenSSLStreamAdapter::IsAcceptableCipher(int cipher, KeyType key_type) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +02001228 if (key_type == KT_RSA) {
torbjorng43166b82016-03-11 00:06:47 -08001229 for (const cipher_list& c : OK_RSA_ciphers) {
1230 if (cipher == c.cipher)
1231 return true;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +02001232 }
Joachim Bauch831c5582015-05-20 12:48:41 +02001233 }
torbjorng43166b82016-03-11 00:06:47 -08001234
1235 if (key_type == KT_ECDSA) {
1236 for (const cipher_list& c : OK_ECDSA_ciphers) {
1237 if (cipher == c.cipher)
1238 return true;
1239 }
1240 }
1241
1242 return false;
1243}
1244
1245bool OpenSSLStreamAdapter::IsAcceptableCipher(const std::string& cipher,
1246 KeyType key_type) {
1247 if (key_type == KT_RSA) {
1248 for (const cipher_list& c : OK_RSA_ciphers) {
1249 if (cipher == c.cipher_str)
1250 return true;
1251 }
1252 }
1253
1254 if (key_type == KT_ECDSA) {
1255 for (const cipher_list& c : OK_ECDSA_ciphers) {
1256 if (cipher == c.cipher_str)
1257 return true;
1258 }
1259 }
1260
1261 return false;
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +00001262}
1263
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001264} // namespace rtc
1265
1266#endif // HAVE_OPENSSL_SSL_H