blob: c18295f5771e4d425a1a36f3c8c49642572887ec [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>
23#include <openssl/x509v3.h>
24
25#include <vector>
26
27#include "webrtc/base/common.h"
28#include "webrtc/base/logging.h"
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000029#include "webrtc/base/safe_conversions.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030#include "webrtc/base/stream.h"
31#include "webrtc/base/openssl.h"
32#include "webrtc/base/openssladapter.h"
33#include "webrtc/base/openssldigest.h"
34#include "webrtc/base/opensslidentity.h"
35#include "webrtc/base/stringutils.h"
36#include "webrtc/base/thread.h"
37
38namespace rtc {
39
40#if (OPENSSL_VERSION_NUMBER >= 0x10001000L)
41#define HAVE_DTLS_SRTP
42#endif
43
44#ifdef HAVE_DTLS_SRTP
45// SRTP cipher suite table
46struct SrtpCipherMapEntry {
47 const char* external_name;
48 const char* internal_name;
49};
50
51// This isn't elegant, but it's better than an external reference
52static SrtpCipherMapEntry SrtpCipherMap[] = {
53 {"AES_CM_128_HMAC_SHA1_80", "SRTP_AES128_CM_SHA1_80"},
54 {"AES_CM_128_HMAC_SHA1_32", "SRTP_AES128_CM_SHA1_32"},
55 {NULL, NULL}
56};
57#endif
58
59//////////////////////////////////////////////////////////////////////
60// StreamBIO
61//////////////////////////////////////////////////////////////////////
62
63static int stream_write(BIO* h, const char* buf, int num);
64static int stream_read(BIO* h, char* buf, int size);
65static int stream_puts(BIO* h, const char* str);
66static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
67static int stream_new(BIO* h);
68static int stream_free(BIO* data);
69
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +000070// TODO(davidben): This should be const once BoringSSL is assumed.
71static BIO_METHOD methods_stream = {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072 BIO_TYPE_BIO,
73 "stream",
74 stream_write,
75 stream_read,
76 stream_puts,
77 0,
78 stream_ctrl,
79 stream_new,
80 stream_free,
81 NULL,
82};
83
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +000084static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085
86static BIO* BIO_new_stream(StreamInterface* stream) {
87 BIO* ret = BIO_new(BIO_s_stream());
88 if (ret == NULL)
89 return NULL;
90 ret->ptr = stream;
91 return ret;
92}
93
94// bio methods return 1 (or at least non-zero) on success and 0 on failure.
95
96static int stream_new(BIO* b) {
97 b->shutdown = 0;
98 b->init = 1;
99 b->num = 0; // 1 means end-of-stream
100 b->ptr = 0;
101 return 1;
102}
103
104static int stream_free(BIO* b) {
105 if (b == NULL)
106 return 0;
107 return 1;
108}
109
110static int stream_read(BIO* b, char* out, int outl) {
111 if (!out)
112 return -1;
113 StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
114 BIO_clear_retry_flags(b);
115 size_t read;
116 int error;
117 StreamResult result = stream->Read(out, outl, &read, &error);
118 if (result == SR_SUCCESS) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000119 return checked_cast<int>(read);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000120 } else if (result == SR_EOS) {
121 b->num = 1;
122 } else if (result == SR_BLOCK) {
123 BIO_set_retry_read(b);
124 }
125 return -1;
126}
127
128static int stream_write(BIO* b, const char* in, int inl) {
129 if (!in)
130 return -1;
131 StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
132 BIO_clear_retry_flags(b);
133 size_t written;
134 int error;
135 StreamResult result = stream->Write(in, inl, &written, &error);
136 if (result == SR_SUCCESS) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000137 return checked_cast<int>(written);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138 } else if (result == SR_BLOCK) {
139 BIO_set_retry_write(b);
140 }
141 return -1;
142}
143
144static int stream_puts(BIO* b, const char* str) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000145 return stream_write(b, str, checked_cast<int>(strlen(str)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146}
147
148static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
henrike@webrtc.org14abcc72014-05-16 16:54:44 +0000149 RTC_UNUSED(num);
150 RTC_UNUSED(ptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000151
152 switch (cmd) {
153 case BIO_CTRL_RESET:
154 return 0;
155 case BIO_CTRL_EOF:
156 return b->num;
157 case BIO_CTRL_WPENDING:
158 case BIO_CTRL_PENDING:
159 return 0;
160 case BIO_CTRL_FLUSH:
161 return 1;
162 default:
163 return 0;
164 }
165}
166
167/////////////////////////////////////////////////////////////////////////////
168// OpenSSLStreamAdapter
169/////////////////////////////////////////////////////////////////////////////
170
171OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
172 : SSLStreamAdapter(stream),
173 state_(SSL_NONE),
174 role_(SSL_CLIENT),
175 ssl_read_needs_write_(false), ssl_write_needs_read_(false),
176 ssl_(NULL), ssl_ctx_(NULL),
177 custom_verification_succeeded_(false),
178 ssl_mode_(SSL_MODE_TLS) {
179}
180
181OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
182 Cleanup();
183}
184
185void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
186 ASSERT(!identity_);
187 identity_.reset(static_cast<OpenSSLIdentity*>(identity));
188}
189
190void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
191 role_ = role;
192}
193
194bool OpenSSLStreamAdapter::GetPeerCertificate(SSLCertificate** cert) const {
195 if (!peer_certificate_)
196 return false;
197
198 *cert = peer_certificate_->GetReference();
199 return true;
200}
201
202bool OpenSSLStreamAdapter::SetPeerCertificateDigest(const std::string
203 &digest_alg,
204 const unsigned char*
205 digest_val,
206 size_t digest_len) {
207 ASSERT(!peer_certificate_);
208 ASSERT(peer_certificate_digest_algorithm_.size() == 0);
209 ASSERT(ssl_server_name_.empty());
210 size_t expected_len;
211
212 if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
213 LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
214 return false;
215 }
216 if (expected_len != digest_len)
217 return false;
218
219 peer_certificate_digest_value_.SetData(digest_val, digest_len);
220 peer_certificate_digest_algorithm_ = digest_alg;
221
222 return true;
223}
224
225// Key Extractor interface
226bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
227 const uint8* context,
228 size_t context_len,
229 bool use_context,
230 uint8* result,
231 size_t result_len) {
232#ifdef HAVE_DTLS_SRTP
233 int i;
234
235 i = SSL_export_keying_material(ssl_, result, result_len,
236 label.c_str(), label.length(),
237 const_cast<uint8 *>(context),
238 context_len, use_context);
239
240 if (i != 1)
241 return false;
242
243 return true;
244#else
245 return false;
246#endif
247}
248
249bool OpenSSLStreamAdapter::SetDtlsSrtpCiphers(
250 const std::vector<std::string>& ciphers) {
251#ifdef HAVE_DTLS_SRTP
252 std::string internal_ciphers;
253
254 if (state_ != SSL_NONE)
255 return false;
256
257 for (std::vector<std::string>::const_iterator cipher = ciphers.begin();
258 cipher != ciphers.end(); ++cipher) {
259 bool found = false;
260 for (SrtpCipherMapEntry *entry = SrtpCipherMap; entry->internal_name;
261 ++entry) {
262 if (*cipher == entry->external_name) {
263 found = true;
264 if (!internal_ciphers.empty())
265 internal_ciphers += ":";
266 internal_ciphers += entry->internal_name;
267 break;
268 }
269 }
270
271 if (!found) {
272 LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
273 return false;
274 }
275 }
276
277 if (internal_ciphers.empty())
278 return false;
279
280 srtp_ciphers_ = internal_ciphers;
281 return true;
282#else
283 return false;
284#endif
285}
286
287bool OpenSSLStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
288#ifdef HAVE_DTLS_SRTP
289 ASSERT(state_ == SSL_CONNECTED);
290 if (state_ != SSL_CONNECTED)
291 return false;
292
henrike@webrtc.orgc10ecea2015-01-07 17:59:28 +0000293 const SRTP_PROTECTION_PROFILE *srtp_profile =
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294 SSL_get_selected_srtp_profile(ssl_);
295
296 if (!srtp_profile)
297 return false;
298
299 for (SrtpCipherMapEntry *entry = SrtpCipherMap;
300 entry->internal_name; ++entry) {
301 if (!strcmp(entry->internal_name, srtp_profile->name)) {
302 *cipher = entry->external_name;
303 return true;
304 }
305 }
306
307 ASSERT(false); // This should never happen
308
309 return false;
310#else
311 return false;
312#endif
313}
314
315int OpenSSLStreamAdapter::StartSSLWithServer(const char* server_name) {
316 ASSERT(server_name != NULL && server_name[0] != '\0');
317 ssl_server_name_ = server_name;
318 return StartSSL();
319}
320
321int OpenSSLStreamAdapter::StartSSLWithPeer() {
322 ASSERT(ssl_server_name_.empty());
323 // It is permitted to specify peer_certificate_ only later.
324 return StartSSL();
325}
326
327void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
328 ASSERT(state_ == SSL_NONE);
329 ssl_mode_ = mode;
330}
331
332//
333// StreamInterface Implementation
334//
335
336StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
337 size_t* written, int* error) {
338 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
339
340 switch (state_) {
341 case SSL_NONE:
342 // pass-through in clear text
343 return StreamAdapterInterface::Write(data, data_len, written, error);
344
345 case SSL_WAIT:
346 case SSL_CONNECTING:
347 return SR_BLOCK;
348
349 case SSL_CONNECTED:
350 break;
351
352 case SSL_ERROR:
353 case SSL_CLOSED:
354 default:
355 if (error)
356 *error = ssl_error_code_;
357 return SR_ERROR;
358 }
359
360 // OpenSSL will return an error if we try to write zero bytes
361 if (data_len == 0) {
362 if (written)
363 *written = 0;
364 return SR_SUCCESS;
365 }
366
367 ssl_write_needs_read_ = false;
368
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000369 int code = SSL_write(ssl_, data, checked_cast<int>(data_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370 int ssl_error = SSL_get_error(ssl_, code);
371 switch (ssl_error) {
372 case SSL_ERROR_NONE:
373 LOG(LS_VERBOSE) << " -- success";
374 ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
375 if (written)
376 *written = code;
377 return SR_SUCCESS;
378 case SSL_ERROR_WANT_READ:
379 LOG(LS_VERBOSE) << " -- error want read";
380 ssl_write_needs_read_ = true;
381 return SR_BLOCK;
382 case SSL_ERROR_WANT_WRITE:
383 LOG(LS_VERBOSE) << " -- error want write";
384 return SR_BLOCK;
385
386 case SSL_ERROR_ZERO_RETURN:
387 default:
388 Error("SSL_write", (ssl_error ? ssl_error : -1), false);
389 if (error)
390 *error = ssl_error_code_;
391 return SR_ERROR;
392 }
393 // not reached
394}
395
396StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
397 size_t* read, int* error) {
398 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
399 switch (state_) {
400 case SSL_NONE:
401 // pass-through in clear text
402 return StreamAdapterInterface::Read(data, data_len, read, error);
403
404 case SSL_WAIT:
405 case SSL_CONNECTING:
406 return SR_BLOCK;
407
408 case SSL_CONNECTED:
409 break;
410
411 case SSL_CLOSED:
412 return SR_EOS;
413
414 case SSL_ERROR:
415 default:
416 if (error)
417 *error = ssl_error_code_;
418 return SR_ERROR;
419 }
420
421 // Don't trust OpenSSL with zero byte reads
422 if (data_len == 0) {
423 if (read)
424 *read = 0;
425 return SR_SUCCESS;
426 }
427
428 ssl_read_needs_write_ = false;
429
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000430 int code = SSL_read(ssl_, data, checked_cast<int>(data_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000431 int ssl_error = SSL_get_error(ssl_, code);
432 switch (ssl_error) {
433 case SSL_ERROR_NONE:
434 LOG(LS_VERBOSE) << " -- success";
435 ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
436 if (read)
437 *read = code;
438
439 if (ssl_mode_ == SSL_MODE_DTLS) {
440 // Enforce atomic reads -- this is a short read
441 unsigned int pending = SSL_pending(ssl_);
442
443 if (pending) {
444 LOG(LS_INFO) << " -- short DTLS read. flushing";
445 FlushInput(pending);
446 if (error)
447 *error = SSE_MSG_TRUNC;
448 return SR_ERROR;
449 }
450 }
451 return SR_SUCCESS;
452 case SSL_ERROR_WANT_READ:
453 LOG(LS_VERBOSE) << " -- error want read";
454 return SR_BLOCK;
455 case SSL_ERROR_WANT_WRITE:
456 LOG(LS_VERBOSE) << " -- error want write";
457 ssl_read_needs_write_ = true;
458 return SR_BLOCK;
459 case SSL_ERROR_ZERO_RETURN:
460 LOG(LS_VERBOSE) << " -- remote side closed";
461 return SR_EOS;
462 break;
463 default:
464 LOG(LS_VERBOSE) << " -- error " << code;
465 Error("SSL_read", (ssl_error ? ssl_error : -1), false);
466 if (error)
467 *error = ssl_error_code_;
468 return SR_ERROR;
469 }
470 // not reached
471}
472
473void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
474 unsigned char buf[2048];
475
476 while (left) {
477 // This should always succeed
478 int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
479 int code = SSL_read(ssl_, buf, toread);
480
481 int ssl_error = SSL_get_error(ssl_, code);
482 ASSERT(ssl_error == SSL_ERROR_NONE);
483
484 if (ssl_error != SSL_ERROR_NONE) {
485 LOG(LS_VERBOSE) << " -- error " << code;
486 Error("SSL_read", (ssl_error ? ssl_error : -1), false);
487 return;
488 }
489
490 LOG(LS_VERBOSE) << " -- flushed " << code << " bytes";
491 left -= code;
492 }
493}
494
495void OpenSSLStreamAdapter::Close() {
496 Cleanup();
497 ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
498 StreamAdapterInterface::Close();
499}
500
501StreamState OpenSSLStreamAdapter::GetState() const {
502 switch (state_) {
503 case SSL_WAIT:
504 case SSL_CONNECTING:
505 return SS_OPENING;
506 case SSL_CONNECTED:
507 return SS_OPEN;
508 default:
509 return SS_CLOSED;
510 };
511 // not reached
512}
513
514void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
515 int err) {
516 int events_to_signal = 0;
517 int signal_error = 0;
518 ASSERT(stream == this->stream());
519 if ((events & SE_OPEN)) {
520 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
521 if (state_ != SSL_WAIT) {
522 ASSERT(state_ == SSL_NONE);
523 events_to_signal |= SE_OPEN;
524 } else {
525 state_ = SSL_CONNECTING;
526 if (int err = BeginSSL()) {
527 Error("BeginSSL", err, true);
528 return;
529 }
530 }
531 }
532 if ((events & (SE_READ|SE_WRITE))) {
533 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent"
534 << ((events & SE_READ) ? " SE_READ" : "")
535 << ((events & SE_WRITE) ? " SE_WRITE" : "");
536 if (state_ == SSL_NONE) {
537 events_to_signal |= events & (SE_READ|SE_WRITE);
538 } else if (state_ == SSL_CONNECTING) {
539 if (int err = ContinueSSL()) {
540 Error("ContinueSSL", err, true);
541 return;
542 }
543 } else if (state_ == SSL_CONNECTED) {
544 if (((events & SE_READ) && ssl_write_needs_read_) ||
545 (events & SE_WRITE)) {
546 LOG(LS_VERBOSE) << " -- onStreamWriteable";
547 events_to_signal |= SE_WRITE;
548 }
549 if (((events & SE_WRITE) && ssl_read_needs_write_) ||
550 (events & SE_READ)) {
551 LOG(LS_VERBOSE) << " -- onStreamReadable";
552 events_to_signal |= SE_READ;
553 }
554 }
555 }
556 if ((events & SE_CLOSE)) {
557 LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
558 Cleanup();
559 events_to_signal |= SE_CLOSE;
560 // SE_CLOSE is the only event that uses the final parameter to OnEvent().
561 ASSERT(signal_error == 0);
562 signal_error = err;
563 }
564 if (events_to_signal)
565 StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
566}
567
568int OpenSSLStreamAdapter::StartSSL() {
569 ASSERT(state_ == SSL_NONE);
570
571 if (StreamAdapterInterface::GetState() != SS_OPEN) {
572 state_ = SSL_WAIT;
573 return 0;
574 }
575
576 state_ = SSL_CONNECTING;
577 if (int err = BeginSSL()) {
578 Error("BeginSSL", err, false);
579 return err;
580 }
581
582 return 0;
583}
584
585int OpenSSLStreamAdapter::BeginSSL() {
586 ASSERT(state_ == SSL_CONNECTING);
587 // The underlying stream has open. If we are in peer-to-peer mode
588 // then a peer certificate must have been specified by now.
589 ASSERT(!ssl_server_name_.empty() ||
590 !peer_certificate_digest_algorithm_.empty());
591 LOG(LS_INFO) << "BeginSSL: "
592 << (!ssl_server_name_.empty() ? ssl_server_name_ :
593 "with peer");
594
595 BIO* bio = NULL;
596
597 // First set up the context
598 ASSERT(ssl_ctx_ == NULL);
599 ssl_ctx_ = SetupSSLContext();
600 if (!ssl_ctx_)
601 return -1;
602
603 bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
604 if (!bio)
605 return -1;
606
607 ssl_ = SSL_new(ssl_ctx_);
608 if (!ssl_) {
609 BIO_free(bio);
610 return -1;
611 }
612
613 SSL_set_app_data(ssl_, this);
614
615 SSL_set_bio(ssl_, bio, bio); // the SSL object owns the bio now.
616
617 SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
618 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
619
jiayl@webrtc.org11c6bde2014-08-28 16:14:38 +0000620 // Specify an ECDH group for ECDHE ciphers, otherwise they cannot be
621 // negotiated when acting as the server. Use NIST's P-256 which is commonly
622 // supported.
623 EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
624 if (ecdh == NULL)
625 return -1;
626 SSL_set_options(ssl_, SSL_OP_SINGLE_ECDH_USE);
627 SSL_set_tmp_ecdh(ssl_, ecdh);
628 EC_KEY_free(ecdh);
629
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000630 // Do the connect
631 return ContinueSSL();
632}
633
634int OpenSSLStreamAdapter::ContinueSSL() {
635 LOG(LS_VERBOSE) << "ContinueSSL";
636 ASSERT(state_ == SSL_CONNECTING);
637
638 // Clear the DTLS timer
639 Thread::Current()->Clear(this, MSG_TIMEOUT);
640
641 int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
642 int ssl_error;
643 switch (ssl_error = SSL_get_error(ssl_, code)) {
644 case SSL_ERROR_NONE:
645 LOG(LS_VERBOSE) << " -- success";
646
647 if (!SSLPostConnectionCheck(ssl_, ssl_server_name_.c_str(), NULL,
648 peer_certificate_digest_algorithm_)) {
649 LOG(LS_ERROR) << "TLS post connection check failed";
650 return -1;
651 }
652
653 state_ = SSL_CONNECTED;
654 StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
655 break;
656
657 case SSL_ERROR_WANT_READ: {
658 LOG(LS_VERBOSE) << " -- error want read";
659 struct timeval timeout;
660 if (DTLSv1_get_timeout(ssl_, &timeout)) {
661 int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
662
663 Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
664 }
665 }
666 break;
667
668 case SSL_ERROR_WANT_WRITE:
669 LOG(LS_VERBOSE) << " -- error want write";
670 break;
671
672 case SSL_ERROR_ZERO_RETURN:
673 default:
674 LOG(LS_VERBOSE) << " -- error " << code;
675 return (ssl_error != 0) ? ssl_error : -1;
676 }
677
678 return 0;
679}
680
681void OpenSSLStreamAdapter::Error(const char* context, int err, bool signal) {
682 LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error("
683 << context << ", " << err << ")";
684 state_ = SSL_ERROR;
685 ssl_error_code_ = err;
686 Cleanup();
687 if (signal)
688 StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
689}
690
691void OpenSSLStreamAdapter::Cleanup() {
692 LOG(LS_INFO) << "Cleanup";
693
694 if (state_ != SSL_ERROR) {
695 state_ = SSL_CLOSED;
696 ssl_error_code_ = 0;
697 }
698
699 if (ssl_) {
jiayl@webrtc.orgf1d751c2014-09-25 16:38:46 +0000700 int ret = SSL_shutdown(ssl_);
701 if (ret < 0) {
702 LOG(LS_WARNING) << "SSL_shutdown failed, error = "
703 << SSL_get_error(ssl_, ret);
704 }
705
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000706 SSL_free(ssl_);
707 ssl_ = NULL;
708 }
709 if (ssl_ctx_) {
710 SSL_CTX_free(ssl_ctx_);
711 ssl_ctx_ = NULL;
712 }
713 identity_.reset();
714 peer_certificate_.reset();
715
716 // Clear the DTLS timer
717 Thread::Current()->Clear(this, MSG_TIMEOUT);
718}
719
720
721void OpenSSLStreamAdapter::OnMessage(Message* msg) {
722 // Process our own messages and then pass others to the superclass
723 if (MSG_TIMEOUT == msg->message_id) {
724 LOG(LS_INFO) << "DTLS timeout expired";
725 DTLSv1_handle_timeout(ssl_);
726 ContinueSSL();
727 } else {
728 StreamInterface::OnMessage(msg);
729 }
730}
731
732SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
733 SSL_CTX *ctx = NULL;
734
735 if (role_ == SSL_CLIENT) {
736 ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
737 DTLSv1_client_method() : TLSv1_client_method());
738 } else {
739 ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
740 DTLSv1_server_method() : TLSv1_server_method());
741 }
742 if (ctx == NULL)
743 return NULL;
744
745 if (identity_ && !identity_->ConfigureIdentity(ctx)) {
746 SSL_CTX_free(ctx);
747 return NULL;
748 }
749
750#ifdef _DEBUG
751 SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
752#endif
753
tkchin@webrtc.orgc569a492014-09-23 05:56:44 +0000754 int mode = SSL_VERIFY_PEER;
755 if (client_auth_enabled()) {
756 // Require a certificate from the client.
757 // Note: Normally this is always true in production, but it may be disabled
758 // for testing purposes (e.g. SSLAdapter unit tests).
759 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
760 }
761
762 SSL_CTX_set_verify(ctx, mode, SSLVerifyCallback);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000763 SSL_CTX_set_verify_depth(ctx, 4);
764 SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
765
766#ifdef HAVE_DTLS_SRTP
767 if (!srtp_ciphers_.empty()) {
768 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
769 SSL_CTX_free(ctx);
770 return NULL;
771 }
772 }
773#endif
774
775 return ctx;
776}
777
778int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
779 // Get our SSL structure from the store
780 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
781 store,
782 SSL_get_ex_data_X509_STORE_CTX_idx()));
783 OpenSSLStreamAdapter* stream =
784 reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
785
786 if (stream->peer_certificate_digest_algorithm_.empty()) {
787 return 0;
788 }
789 X509* cert = X509_STORE_CTX_get_current_cert(store);
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +0000790 int depth = X509_STORE_CTX_get_error_depth(store);
791
792 // For now We ignore the parent certificates and verify the leaf against
793 // the digest.
794 //
795 // TODO(jiayl): Verify the chain is a proper chain and report the chain to
796 // |stream->peer_certificate_|, like what NSS does.
797 if (depth > 0) {
798 LOG(LS_INFO) << "Ignored chained certificate at depth " << depth;
799 return 1;
800 }
801
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000802 unsigned char digest[EVP_MAX_MD_SIZE];
803 size_t digest_length;
804 if (!OpenSSLCertificate::ComputeDigest(
805 cert,
806 stream->peer_certificate_digest_algorithm_,
807 digest, sizeof(digest),
808 &digest_length)) {
809 LOG(LS_WARNING) << "Failed to compute peer cert digest.";
810 return 0;
811 }
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +0000812
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000813 Buffer computed_digest(digest, digest_length);
814 if (computed_digest != stream->peer_certificate_digest_value_) {
815 LOG(LS_WARNING) << "Rejected peer certificate due to mismatched digest.";
816 return 0;
817 }
818 // Ignore any verification error if the digest matches, since there is no
819 // value in checking the validity of a self-signed cert issued by untrusted
820 // sources.
821 LOG(LS_INFO) << "Accepted peer certificate.";
henrike@webrtc.org4e5f65a2014-06-05 20:40:11 +0000822
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000823 // Record the peer's certificate.
824 stream->peer_certificate_.reset(new OpenSSLCertificate(cert));
825 return 1;
826}
827
828// This code is taken from the "Network Security with OpenSSL"
829// sample in chapter 5
830bool OpenSSLStreamAdapter::SSLPostConnectionCheck(SSL* ssl,
831 const char* server_name,
832 const X509* peer_cert,
833 const std::string
834 &peer_digest) {
835 ASSERT(server_name != NULL);
836 bool ok;
837 if (server_name[0] != '\0') { // traditional mode
838 ok = OpenSSLAdapter::VerifyServerName(ssl, server_name, ignore_bad_cert());
839
840 if (ok) {
841 ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
842 custom_verification_succeeded_);
843 }
844 } else { // peer-to-peer mode
845 ASSERT((peer_cert != NULL) || (!peer_digest.empty()));
846 // no server name validation
847 ok = true;
848 }
849
850 if (!ok && ignore_bad_cert()) {
851 LOG(LS_ERROR) << "SSL_get_verify_result(ssl) = "
852 << SSL_get_verify_result(ssl);
853 LOG(LS_INFO) << "Other TLS post connection checks failed.";
854 ok = true;
855 }
856
857 return ok;
858}
859
860bool OpenSSLStreamAdapter::HaveDtls() {
861 return true;
862}
863
864bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
865#ifdef HAVE_DTLS_SRTP
866 return true;
867#else
868 return false;
869#endif
870}
871
872bool OpenSSLStreamAdapter::HaveExporter() {
873#ifdef HAVE_DTLS_SRTP
874 return true;
875#else
876 return false;
877#endif
878}
879
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000880} // namespace rtc
881
882#endif // HAVE_OPENSSL_SSL_H