blob: 0f82d281f81bd54f23e730beefa627fd8e7faf28 [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
11#if HAVE_CONFIG_H
12#include "config.h"
13#endif // HAVE_CONFIG_H
14
15#if HAVE_OPENSSL_SSL_H
16
17#include "webrtc/base/opensslstreamadapter.h"
18
19#include <openssl/bio.h>
20#include <openssl/crypto.h>
21#include <openssl/err.h>
22#include <openssl/rand.h>
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +000023#include <openssl/tls1.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024#include <openssl/x509v3.h>
25
26#include <vector>
27
28#include "webrtc/base/common.h"
29#include "webrtc/base/logging.h"
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000030#include "webrtc/base/safe_conversions.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031#include "webrtc/base/stream.h"
32#include "webrtc/base/openssl.h"
33#include "webrtc/base/openssladapter.h"
34#include "webrtc/base/openssldigest.h"
35#include "webrtc/base/opensslidentity.h"
36#include "webrtc/base/stringutils.h"
37#include "webrtc/base/thread.h"
38
39namespace rtc {
40
41#if (OPENSSL_VERSION_NUMBER >= 0x10001000L)
42#define HAVE_DTLS_SRTP
43#endif
44
45#ifdef HAVE_DTLS_SRTP
46// SRTP cipher suite table
47struct SrtpCipherMapEntry {
48 const char* external_name;
49 const char* internal_name;
50};
51
52// This isn't elegant, but it's better than an external reference
53static SrtpCipherMapEntry SrtpCipherMap[] = {
54 {"AES_CM_128_HMAC_SHA1_80", "SRTP_AES128_CM_SHA1_80"},
55 {"AES_CM_128_HMAC_SHA1_32", "SRTP_AES128_CM_SHA1_32"},
56 {NULL, NULL}
57};
58#endif
59
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +000060// Cipher name table. Maps internal OpenSSL cipher ids to the RFC name.
61struct SslCipherMapEntry {
62 uint32_t openssl_id;
63 const char* rfc_name;
64};
65
66#define DEFINE_CIPHER_ENTRY_SSL3(name) {SSL3_CK_##name, "TLS_"#name}
67#define DEFINE_CIPHER_ENTRY_TLS1(name) {TLS1_CK_##name, "TLS_"#name}
68
69// There currently is no method available to get a RFC-compliant name for a
70// cipher suite from BoringSSL, so we need to define the mapping manually here.
71// This should go away once BoringSSL supports "SSL_CIPHER_standard_name"
72// (as available in OpenSSL if compiled with tracing enabled) or a similar
73// method.
74static const SslCipherMapEntry kSslCipherMap[] = {
75 // TLS v1.0 ciphersuites from RFC2246.
76 DEFINE_CIPHER_ENTRY_SSL3(RSA_RC4_128_SHA),
77 {SSL3_CK_RSA_DES_192_CBC3_SHA,
78 "TLS_RSA_WITH_3DES_EDE_CBC_SHA"},
79
80 // AES ciphersuites from RFC3268.
81 {TLS1_CK_RSA_WITH_AES_128_SHA,
82 "TLS_RSA_WITH_AES_128_CBC_SHA"},
83 {TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
84 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
85 {TLS1_CK_RSA_WITH_AES_256_SHA,
86 "TLS_RSA_WITH_AES_256_CBC_SHA"},
87 {TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
88 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
89
90 // ECC ciphersuites from RFC4492.
91 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_RC4_128_SHA),
92 {TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA,
93 "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"},
94 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
95 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
96
97 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_RC4_128_SHA),
98 {TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA,
99 "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"},
100 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_CBC_SHA),
101 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_CBC_SHA),
102
103 // TLS v1.2 ciphersuites.
104 {TLS1_CK_RSA_WITH_AES_128_SHA256,
105 "TLS_RSA_WITH_AES_128_CBC_SHA256"},
106 {TLS1_CK_RSA_WITH_AES_256_SHA256,
107 "TLS_RSA_WITH_AES_256_CBC_SHA256"},
108 {TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
109 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"},
110 {TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
111 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"},
112
113 // TLS v1.2 GCM ciphersuites from RFC5288.
114 DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_128_GCM_SHA256),
115 DEFINE_CIPHER_ENTRY_TLS1(RSA_WITH_AES_256_GCM_SHA384),
116 DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_128_GCM_SHA256),
117 DEFINE_CIPHER_ENTRY_TLS1(DHE_RSA_WITH_AES_256_GCM_SHA384),
118 DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_128_GCM_SHA256),
119 DEFINE_CIPHER_ENTRY_TLS1(DH_RSA_WITH_AES_256_GCM_SHA384),
120
121 // ECDH HMAC based ciphersuites from RFC5289.
122 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
123 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"},
124 {TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
125 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"},
126 {TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
127 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"},
128 {TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
129 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"},
130
131 // ECDH GCM based ciphersuites from RFC5289.
132 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
133 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
134 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_128_GCM_SHA256),
135 DEFINE_CIPHER_ENTRY_TLS1(ECDHE_RSA_WITH_AES_256_GCM_SHA384),
136
137#ifdef OPENSSL_IS_BORINGSSL
138 {TLS1_CK_ECDHE_RSA_CHACHA20_POLY1305,
139 "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"},
140 {TLS1_CK_ECDHE_ECDSA_CHACHA20_POLY1305,
141 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"},
142 {TLS1_CK_DHE_RSA_CHACHA20_POLY1305,
143 "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"},
144#endif
145
146 {0, NULL}
147};
148
149// Default cipher used between OpenSSL/BoringSSL stream adapters.
150// This needs to be updated when the default of the SSL library changes.
151static const char kDefaultSslCipher[] = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA";
152
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000153//////////////////////////////////////////////////////////////////////
154// StreamBIO
155//////////////////////////////////////////////////////////////////////
156
157static int stream_write(BIO* h, const char* buf, int num);
158static int stream_read(BIO* h, char* buf, int size);
159static int stream_puts(BIO* h, const char* str);
160static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
161static int stream_new(BIO* h);
162static int stream_free(BIO* data);
163
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +0000164// TODO(davidben): This should be const once BoringSSL is assumed.
165static BIO_METHOD methods_stream = {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166 BIO_TYPE_BIO,
167 "stream",
168 stream_write,
169 stream_read,
170 stream_puts,
171 0,
172 stream_ctrl,
173 stream_new,
174 stream_free,
175 NULL,
176};
177
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +0000178static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179
180static BIO* BIO_new_stream(StreamInterface* stream) {
181 BIO* ret = BIO_new(BIO_s_stream());
182 if (ret == NULL)
183 return NULL;
184 ret->ptr = stream;
185 return ret;
186}
187
188// bio methods return 1 (or at least non-zero) on success and 0 on failure.
189
190static int stream_new(BIO* b) {
191 b->shutdown = 0;
192 b->init = 1;
193 b->num = 0; // 1 means end-of-stream
194 b->ptr = 0;
195 return 1;
196}
197
198static int stream_free(BIO* b) {
199 if (b == NULL)
200 return 0;
201 return 1;
202}
203
204static int stream_read(BIO* b, char* out, int outl) {
205 if (!out)
206 return -1;
207 StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
208 BIO_clear_retry_flags(b);
209 size_t read;
210 int error;
211 StreamResult result = stream->Read(out, outl, &read, &error);
212 if (result == SR_SUCCESS) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000213 return checked_cast<int>(read);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214 } else if (result == SR_EOS) {
215 b->num = 1;
216 } else if (result == SR_BLOCK) {
217 BIO_set_retry_read(b);
218 }
219 return -1;
220}
221
222static int stream_write(BIO* b, const char* in, int inl) {
223 if (!in)
224 return -1;
225 StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
226 BIO_clear_retry_flags(b);
227 size_t written;
228 int error;
229 StreamResult result = stream->Write(in, inl, &written, &error);
230 if (result == SR_SUCCESS) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000231 return checked_cast<int>(written);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232 } else if (result == SR_BLOCK) {
233 BIO_set_retry_write(b);
234 }
235 return -1;
236}
237
238static int stream_puts(BIO* b, const char* str) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000239 return stream_write(b, str, checked_cast<int>(strlen(str)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240}
241
242static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
henrike@webrtc.org14abcc72014-05-16 16:54:44 +0000243 RTC_UNUSED(num);
244 RTC_UNUSED(ptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000245
246 switch (cmd) {
247 case BIO_CTRL_RESET:
248 return 0;
249 case BIO_CTRL_EOF:
250 return b->num;
251 case BIO_CTRL_WPENDING:
252 case BIO_CTRL_PENDING:
253 return 0;
254 case BIO_CTRL_FLUSH:
255 return 1;
256 default:
257 return 0;
258 }
259}
260
261/////////////////////////////////////////////////////////////////////////////
262// OpenSSLStreamAdapter
263/////////////////////////////////////////////////////////////////////////////
264
265OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
266 : SSLStreamAdapter(stream),
267 state_(SSL_NONE),
268 role_(SSL_CLIENT),
269 ssl_read_needs_write_(false), ssl_write_needs_read_(false),
270 ssl_(NULL), ssl_ctx_(NULL),
271 custom_verification_succeeded_(false),
272 ssl_mode_(SSL_MODE_TLS) {
273}
274
275OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
276 Cleanup();
277}
278
279void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
280 ASSERT(!identity_);
281 identity_.reset(static_cast<OpenSSLIdentity*>(identity));
282}
283
284void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
285 role_ = role;
286}
287
288bool OpenSSLStreamAdapter::GetPeerCertificate(SSLCertificate** cert) const {
289 if (!peer_certificate_)
290 return false;
291
292 *cert = peer_certificate_->GetReference();
293 return true;
294}
295
296bool OpenSSLStreamAdapter::SetPeerCertificateDigest(const std::string
297 &digest_alg,
298 const unsigned char*
299 digest_val,
300 size_t digest_len) {
301 ASSERT(!peer_certificate_);
302 ASSERT(peer_certificate_digest_algorithm_.size() == 0);
303 ASSERT(ssl_server_name_.empty());
304 size_t expected_len;
305
306 if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
307 LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
308 return false;
309 }
310 if (expected_len != digest_len)
311 return false;
312
313 peer_certificate_digest_value_.SetData(digest_val, digest_len);
314 peer_certificate_digest_algorithm_ = digest_alg;
315
316 return true;
317}
318
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +0000319const char* OpenSSLStreamAdapter::GetRfcSslCipherName(
320 const SSL_CIPHER* cipher) {
321 ASSERT(cipher != NULL);
322 for (const SslCipherMapEntry* entry = kSslCipherMap; entry->rfc_name;
323 ++entry) {
324 if (cipher->id == entry->openssl_id) {
325 return entry->rfc_name;
326 }
327 }
328 return NULL;
329}
330
331bool OpenSSLStreamAdapter::GetSslCipher(std::string* cipher) {
332 if (state_ != SSL_CONNECTED)
333 return false;
334
335 const SSL_CIPHER* current_cipher = SSL_get_current_cipher(ssl_);
336 if (current_cipher == NULL) {
337 return false;
338 }
339
340 const char* cipher_name = GetRfcSslCipherName(current_cipher);
341 if (cipher_name == NULL) {
342 return false;
343 }
344
345 *cipher = cipher_name;
346 return true;
347}
348
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000349// Key Extractor interface
350bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
351 const uint8* context,
352 size_t context_len,
353 bool use_context,
354 uint8* result,
355 size_t result_len) {
356#ifdef HAVE_DTLS_SRTP
357 int i;
358
359 i = SSL_export_keying_material(ssl_, result, result_len,
360 label.c_str(), label.length(),
361 const_cast<uint8 *>(context),
362 context_len, use_context);
363
364 if (i != 1)
365 return false;
366
367 return true;
368#else
369 return false;
370#endif
371}
372
373bool OpenSSLStreamAdapter::SetDtlsSrtpCiphers(
374 const std::vector<std::string>& ciphers) {
375#ifdef HAVE_DTLS_SRTP
376 std::string internal_ciphers;
377
378 if (state_ != SSL_NONE)
379 return false;
380
381 for (std::vector<std::string>::const_iterator cipher = ciphers.begin();
382 cipher != ciphers.end(); ++cipher) {
383 bool found = false;
384 for (SrtpCipherMapEntry *entry = SrtpCipherMap; entry->internal_name;
385 ++entry) {
386 if (*cipher == entry->external_name) {
387 found = true;
388 if (!internal_ciphers.empty())
389 internal_ciphers += ":";
390 internal_ciphers += entry->internal_name;
391 break;
392 }
393 }
394
395 if (!found) {
396 LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
397 return false;
398 }
399 }
400
401 if (internal_ciphers.empty())
402 return false;
403
404 srtp_ciphers_ = internal_ciphers;
405 return true;
406#else
407 return false;
408#endif
409}
410
411bool OpenSSLStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
412#ifdef HAVE_DTLS_SRTP
413 ASSERT(state_ == SSL_CONNECTED);
414 if (state_ != SSL_CONNECTED)
415 return false;
416
henrike@webrtc.orgc10ecea2015-01-07 17:59:28 +0000417 const SRTP_PROTECTION_PROFILE *srtp_profile =
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000418 SSL_get_selected_srtp_profile(ssl_);
419
420 if (!srtp_profile)
421 return false;
422
423 for (SrtpCipherMapEntry *entry = SrtpCipherMap;
424 entry->internal_name; ++entry) {
425 if (!strcmp(entry->internal_name, srtp_profile->name)) {
426 *cipher = entry->external_name;
427 return true;
428 }
429 }
430
431 ASSERT(false); // This should never happen
432
433 return false;
434#else
435 return false;
436#endif
437}
438
439int OpenSSLStreamAdapter::StartSSLWithServer(const char* server_name) {
440 ASSERT(server_name != NULL && server_name[0] != '\0');
441 ssl_server_name_ = server_name;
442 return StartSSL();
443}
444
445int OpenSSLStreamAdapter::StartSSLWithPeer() {
446 ASSERT(ssl_server_name_.empty());
447 // It is permitted to specify peer_certificate_ only later.
448 return StartSSL();
449}
450
451void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
452 ASSERT(state_ == SSL_NONE);
453 ssl_mode_ = mode;
454}
455
456//
457// StreamInterface Implementation
458//
459
460StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
461 size_t* written, int* error) {
462 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
463
464 switch (state_) {
465 case SSL_NONE:
466 // pass-through in clear text
467 return StreamAdapterInterface::Write(data, data_len, written, error);
468
469 case SSL_WAIT:
470 case SSL_CONNECTING:
471 return SR_BLOCK;
472
473 case SSL_CONNECTED:
474 break;
475
476 case SSL_ERROR:
477 case SSL_CLOSED:
478 default:
479 if (error)
480 *error = ssl_error_code_;
481 return SR_ERROR;
482 }
483
484 // OpenSSL will return an error if we try to write zero bytes
485 if (data_len == 0) {
486 if (written)
487 *written = 0;
488 return SR_SUCCESS;
489 }
490
491 ssl_write_needs_read_ = false;
492
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000493 int code = SSL_write(ssl_, data, checked_cast<int>(data_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000494 int ssl_error = SSL_get_error(ssl_, code);
495 switch (ssl_error) {
496 case SSL_ERROR_NONE:
497 LOG(LS_VERBOSE) << " -- success";
498 ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
499 if (written)
500 *written = code;
501 return SR_SUCCESS;
502 case SSL_ERROR_WANT_READ:
503 LOG(LS_VERBOSE) << " -- error want read";
504 ssl_write_needs_read_ = true;
505 return SR_BLOCK;
506 case SSL_ERROR_WANT_WRITE:
507 LOG(LS_VERBOSE) << " -- error want write";
508 return SR_BLOCK;
509
510 case SSL_ERROR_ZERO_RETURN:
511 default:
512 Error("SSL_write", (ssl_error ? ssl_error : -1), false);
513 if (error)
514 *error = ssl_error_code_;
515 return SR_ERROR;
516 }
517 // not reached
518}
519
520StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
521 size_t* read, int* error) {
522 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
523 switch (state_) {
524 case SSL_NONE:
525 // pass-through in clear text
526 return StreamAdapterInterface::Read(data, data_len, read, error);
527
528 case SSL_WAIT:
529 case SSL_CONNECTING:
530 return SR_BLOCK;
531
532 case SSL_CONNECTED:
533 break;
534
535 case SSL_CLOSED:
536 return SR_EOS;
537
538 case SSL_ERROR:
539 default:
540 if (error)
541 *error = ssl_error_code_;
542 return SR_ERROR;
543 }
544
545 // Don't trust OpenSSL with zero byte reads
546 if (data_len == 0) {
547 if (read)
548 *read = 0;
549 return SR_SUCCESS;
550 }
551
552 ssl_read_needs_write_ = false;
553
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000554 int code = SSL_read(ssl_, data, checked_cast<int>(data_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000555 int ssl_error = SSL_get_error(ssl_, code);
556 switch (ssl_error) {
557 case SSL_ERROR_NONE:
558 LOG(LS_VERBOSE) << " -- success";
559 ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
560 if (read)
561 *read = code;
562
563 if (ssl_mode_ == SSL_MODE_DTLS) {
564 // Enforce atomic reads -- this is a short read
565 unsigned int pending = SSL_pending(ssl_);
566
567 if (pending) {
568 LOG(LS_INFO) << " -- short DTLS read. flushing";
569 FlushInput(pending);
570 if (error)
571 *error = SSE_MSG_TRUNC;
572 return SR_ERROR;
573 }
574 }
575 return SR_SUCCESS;
576 case SSL_ERROR_WANT_READ:
577 LOG(LS_VERBOSE) << " -- error want read";
578 return SR_BLOCK;
579 case SSL_ERROR_WANT_WRITE:
580 LOG(LS_VERBOSE) << " -- error want write";
581 ssl_read_needs_write_ = true;
582 return SR_BLOCK;
583 case SSL_ERROR_ZERO_RETURN:
584 LOG(LS_VERBOSE) << " -- remote side closed";
585 return SR_EOS;
586 break;
587 default:
588 LOG(LS_VERBOSE) << " -- error " << code;
589 Error("SSL_read", (ssl_error ? ssl_error : -1), false);
590 if (error)
591 *error = ssl_error_code_;
592 return SR_ERROR;
593 }
594 // not reached
595}
596
597void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
598 unsigned char buf[2048];
599
600 while (left) {
601 // This should always succeed
602 int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
603 int code = SSL_read(ssl_, buf, toread);
604
605 int ssl_error = SSL_get_error(ssl_, code);
606 ASSERT(ssl_error == SSL_ERROR_NONE);
607
608 if (ssl_error != SSL_ERROR_NONE) {
609 LOG(LS_VERBOSE) << " -- error " << code;
610 Error("SSL_read", (ssl_error ? ssl_error : -1), false);
611 return;
612 }
613
614 LOG(LS_VERBOSE) << " -- flushed " << code << " bytes";
615 left -= code;
616 }
617}
618
619void OpenSSLStreamAdapter::Close() {
620 Cleanup();
621 ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
622 StreamAdapterInterface::Close();
623}
624
625StreamState OpenSSLStreamAdapter::GetState() const {
626 switch (state_) {
627 case SSL_WAIT:
628 case SSL_CONNECTING:
629 return SS_OPENING;
630 case SSL_CONNECTED:
631 return SS_OPEN;
632 default:
633 return SS_CLOSED;
634 };
635 // not reached
636}
637
638void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
639 int err) {
640 int events_to_signal = 0;
641 int signal_error = 0;
642 ASSERT(stream == this->stream());
643 if ((events & SE_OPEN)) {
644 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
645 if (state_ != SSL_WAIT) {
646 ASSERT(state_ == SSL_NONE);
647 events_to_signal |= SE_OPEN;
648 } else {
649 state_ = SSL_CONNECTING;
650 if (int err = BeginSSL()) {
651 Error("BeginSSL", err, true);
652 return;
653 }
654 }
655 }
656 if ((events & (SE_READ|SE_WRITE))) {
657 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent"
658 << ((events & SE_READ) ? " SE_READ" : "")
659 << ((events & SE_WRITE) ? " SE_WRITE" : "");
660 if (state_ == SSL_NONE) {
661 events_to_signal |= events & (SE_READ|SE_WRITE);
662 } else if (state_ == SSL_CONNECTING) {
663 if (int err = ContinueSSL()) {
664 Error("ContinueSSL", err, true);
665 return;
666 }
667 } else if (state_ == SSL_CONNECTED) {
668 if (((events & SE_READ) && ssl_write_needs_read_) ||
669 (events & SE_WRITE)) {
670 LOG(LS_VERBOSE) << " -- onStreamWriteable";
671 events_to_signal |= SE_WRITE;
672 }
673 if (((events & SE_WRITE) && ssl_read_needs_write_) ||
674 (events & SE_READ)) {
675 LOG(LS_VERBOSE) << " -- onStreamReadable";
676 events_to_signal |= SE_READ;
677 }
678 }
679 }
680 if ((events & SE_CLOSE)) {
681 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
682 Cleanup();
683 events_to_signal |= SE_CLOSE;
684 // SE_CLOSE is the only event that uses the final parameter to OnEvent().
685 ASSERT(signal_error == 0);
686 signal_error = err;
687 }
688 if (events_to_signal)
689 StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
690}
691
692int OpenSSLStreamAdapter::StartSSL() {
693 ASSERT(state_ == SSL_NONE);
694
695 if (StreamAdapterInterface::GetState() != SS_OPEN) {
696 state_ = SSL_WAIT;
697 return 0;
698 }
699
700 state_ = SSL_CONNECTING;
701 if (int err = BeginSSL()) {
702 Error("BeginSSL", err, false);
703 return err;
704 }
705
706 return 0;
707}
708
709int OpenSSLStreamAdapter::BeginSSL() {
710 ASSERT(state_ == SSL_CONNECTING);
711 // The underlying stream has open. If we are in peer-to-peer mode
712 // then a peer certificate must have been specified by now.
713 ASSERT(!ssl_server_name_.empty() ||
714 !peer_certificate_digest_algorithm_.empty());
715 LOG(LS_INFO) << "BeginSSL: "
716 << (!ssl_server_name_.empty() ? ssl_server_name_ :
717 "with peer");
718
719 BIO* bio = NULL;
720
721 // First set up the context
722 ASSERT(ssl_ctx_ == NULL);
723 ssl_ctx_ = SetupSSLContext();
724 if (!ssl_ctx_)
725 return -1;
726
727 bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
728 if (!bio)
729 return -1;
730
731 ssl_ = SSL_new(ssl_ctx_);
732 if (!ssl_) {
733 BIO_free(bio);
734 return -1;
735 }
736
737 SSL_set_app_data(ssl_, this);
738
739 SSL_set_bio(ssl_, bio, bio); // the SSL object owns the bio now.
740
741 SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
742 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
743
jiayl@webrtc.org11c6bde2014-08-28 16:14:38 +0000744 // Specify an ECDH group for ECDHE ciphers, otherwise they cannot be
745 // negotiated when acting as the server. Use NIST's P-256 which is commonly
746 // supported.
747 EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
748 if (ecdh == NULL)
749 return -1;
750 SSL_set_options(ssl_, SSL_OP_SINGLE_ECDH_USE);
751 SSL_set_tmp_ecdh(ssl_, ecdh);
752 EC_KEY_free(ecdh);
753
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000754 // Do the connect
755 return ContinueSSL();
756}
757
758int OpenSSLStreamAdapter::ContinueSSL() {
759 LOG(LS_VERBOSE) << "ContinueSSL";
760 ASSERT(state_ == SSL_CONNECTING);
761
762 // Clear the DTLS timer
763 Thread::Current()->Clear(this, MSG_TIMEOUT);
764
765 int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
766 int ssl_error;
767 switch (ssl_error = SSL_get_error(ssl_, code)) {
768 case SSL_ERROR_NONE:
769 LOG(LS_VERBOSE) << " -- success";
770
771 if (!SSLPostConnectionCheck(ssl_, ssl_server_name_.c_str(), NULL,
772 peer_certificate_digest_algorithm_)) {
773 LOG(LS_ERROR) << "TLS post connection check failed";
774 return -1;
775 }
776
777 state_ = SSL_CONNECTED;
778 StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
779 break;
780
781 case SSL_ERROR_WANT_READ: {
782 LOG(LS_VERBOSE) << " -- error want read";
783 struct timeval timeout;
784 if (DTLSv1_get_timeout(ssl_, &timeout)) {
785 int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
786
787 Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
788 }
789 }
790 break;
791
792 case SSL_ERROR_WANT_WRITE:
793 LOG(LS_VERBOSE) << " -- error want write";
794 break;
795
796 case SSL_ERROR_ZERO_RETURN:
797 default:
798 LOG(LS_VERBOSE) << " -- error " << code;
799 return (ssl_error != 0) ? ssl_error : -1;
800 }
801
802 return 0;
803}
804
805void OpenSSLStreamAdapter::Error(const char* context, int err, bool signal) {
806 LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error("
807 << context << ", " << err << ")";
808 state_ = SSL_ERROR;
809 ssl_error_code_ = err;
810 Cleanup();
811 if (signal)
812 StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
813}
814
815void OpenSSLStreamAdapter::Cleanup() {
816 LOG(LS_INFO) << "Cleanup";
817
818 if (state_ != SSL_ERROR) {
819 state_ = SSL_CLOSED;
820 ssl_error_code_ = 0;
821 }
822
823 if (ssl_) {
jiayl@webrtc.orgf1d751c2014-09-25 16:38:46 +0000824 int ret = SSL_shutdown(ssl_);
825 if (ret < 0) {
826 LOG(LS_WARNING) << "SSL_shutdown failed, error = "
827 << SSL_get_error(ssl_, ret);
828 }
829
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000830 SSL_free(ssl_);
831 ssl_ = NULL;
832 }
833 if (ssl_ctx_) {
834 SSL_CTX_free(ssl_ctx_);
835 ssl_ctx_ = NULL;
836 }
837 identity_.reset();
838 peer_certificate_.reset();
839
840 // Clear the DTLS timer
841 Thread::Current()->Clear(this, MSG_TIMEOUT);
842}
843
844
845void OpenSSLStreamAdapter::OnMessage(Message* msg) {
846 // Process our own messages and then pass others to the superclass
847 if (MSG_TIMEOUT == msg->message_id) {
848 LOG(LS_INFO) << "DTLS timeout expired";
849 DTLSv1_handle_timeout(ssl_);
850 ContinueSSL();
851 } else {
852 StreamInterface::OnMessage(msg);
853 }
854}
855
856SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
857 SSL_CTX *ctx = NULL;
858
859 if (role_ == SSL_CLIENT) {
860 ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
861 DTLSv1_client_method() : TLSv1_client_method());
862 } else {
863 ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
864 DTLSv1_server_method() : TLSv1_server_method());
865 }
866 if (ctx == NULL)
867 return NULL;
868
869 if (identity_ && !identity_->ConfigureIdentity(ctx)) {
870 SSL_CTX_free(ctx);
871 return NULL;
872 }
873
874#ifdef _DEBUG
875 SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
876#endif
877
tkchin@webrtc.orgc569a492014-09-23 05:56:44 +0000878 int mode = SSL_VERIFY_PEER;
879 if (client_auth_enabled()) {
880 // Require a certificate from the client.
881 // Note: Normally this is always true in production, but it may be disabled
882 // for testing purposes (e.g. SSLAdapter unit tests).
883 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
884 }
885
886 SSL_CTX_set_verify(ctx, mode, SSLVerifyCallback);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000887 SSL_CTX_set_verify_depth(ctx, 4);
888 SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
889
890#ifdef HAVE_DTLS_SRTP
891 if (!srtp_ciphers_.empty()) {
892 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
893 SSL_CTX_free(ctx);
894 return NULL;
895 }
896 }
897#endif
898
899 return ctx;
900}
901
902int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
903 // Get our SSL structure from the store
904 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
905 store,
906 SSL_get_ex_data_X509_STORE_CTX_idx()));
907 OpenSSLStreamAdapter* stream =
908 reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
909
910 if (stream->peer_certificate_digest_algorithm_.empty()) {
911 return 0;
912 }
913 X509* cert = X509_STORE_CTX_get_current_cert(store);
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +0000914 int depth = X509_STORE_CTX_get_error_depth(store);
915
916 // For now We ignore the parent certificates and verify the leaf against
917 // the digest.
918 //
919 // TODO(jiayl): Verify the chain is a proper chain and report the chain to
920 // |stream->peer_certificate_|, like what NSS does.
921 if (depth > 0) {
922 LOG(LS_INFO) << "Ignored chained certificate at depth " << depth;
923 return 1;
924 }
925
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000926 unsigned char digest[EVP_MAX_MD_SIZE];
927 size_t digest_length;
928 if (!OpenSSLCertificate::ComputeDigest(
929 cert,
930 stream->peer_certificate_digest_algorithm_,
931 digest, sizeof(digest),
932 &digest_length)) {
933 LOG(LS_WARNING) << "Failed to compute peer cert digest.";
934 return 0;
935 }
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +0000936
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000937 Buffer computed_digest(digest, digest_length);
938 if (computed_digest != stream->peer_certificate_digest_value_) {
939 LOG(LS_WARNING) << "Rejected peer certificate due to mismatched digest.";
940 return 0;
941 }
942 // Ignore any verification error if the digest matches, since there is no
943 // value in checking the validity of a self-signed cert issued by untrusted
944 // sources.
945 LOG(LS_INFO) << "Accepted peer certificate.";
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +0000946
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000947 // Record the peer's certificate.
948 stream->peer_certificate_.reset(new OpenSSLCertificate(cert));
949 return 1;
950}
951
952// This code is taken from the "Network Security with OpenSSL"
953// sample in chapter 5
954bool OpenSSLStreamAdapter::SSLPostConnectionCheck(SSL* ssl,
955 const char* server_name,
956 const X509* peer_cert,
957 const std::string
958 &peer_digest) {
959 ASSERT(server_name != NULL);
960 bool ok;
961 if (server_name[0] != '\0') { // traditional mode
962 ok = OpenSSLAdapter::VerifyServerName(ssl, server_name, ignore_bad_cert());
963
964 if (ok) {
965 ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
966 custom_verification_succeeded_);
967 }
968 } else { // peer-to-peer mode
969 ASSERT((peer_cert != NULL) || (!peer_digest.empty()));
970 // no server name validation
971 ok = true;
972 }
973
974 if (!ok && ignore_bad_cert()) {
975 LOG(LS_ERROR) << "SSL_get_verify_result(ssl) = "
976 << SSL_get_verify_result(ssl);
977 LOG(LS_INFO) << "Other TLS post connection checks failed.";
978 ok = true;
979 }
980
981 return ok;
982}
983
984bool OpenSSLStreamAdapter::HaveDtls() {
985 return true;
986}
987
988bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
989#ifdef HAVE_DTLS_SRTP
990 return true;
991#else
992 return false;
993#endif
994}
995
996bool OpenSSLStreamAdapter::HaveExporter() {
997#ifdef HAVE_DTLS_SRTP
998 return true;
999#else
1000 return false;
1001#endif
1002}
1003
pthatcher@webrtc.org3ee4fe52015-02-11 22:34:36 +00001004std::string OpenSSLStreamAdapter::GetDefaultSslCipher() {
1005 return kDefaultSslCipher;
1006}
1007
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001008} // namespace rtc
1009
1010#endif // HAVE_OPENSSL_SSL_H