1 /*
2 * Copyright 2008 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "rtc_base/openssl_adapter.h"
12
13 #include <errno.h>
14 #include <openssl/bio.h>
15 #include <openssl/err.h>
16 #include <openssl/rand.h>
17 #include <openssl/x509.h>
18 #include <string.h>
19 #include <time.h>
20
21 #include <memory>
22
23 #include "absl/memory/memory.h"
24 #include "rtc_base/checks.h"
25 #include "rtc_base/location.h"
26 #include "rtc_base/logging.h"
27 #include "rtc_base/numerics/safe_conversions.h"
28 #include "rtc_base/openssl.h"
29 #include "rtc_base/openssl_certificate.h"
30 #include "rtc_base/openssl_utility.h"
31 #include "rtc_base/string_encode.h"
32 #include "rtc_base/thread.h"
33
34 //////////////////////////////////////////////////////////////////////
35 // SocketBIO
36 //////////////////////////////////////////////////////////////////////
37
38 static int socket_write(BIO* h, const char* buf, int num);
39 static int socket_read(BIO* h, char* buf, int size);
40 static int socket_puts(BIO* h, const char* str);
41 static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2); // NOLINT
42 static int socket_new(BIO* h);
43 static int socket_free(BIO* data);
44
BIO_socket_method()45 static BIO_METHOD* BIO_socket_method() {
46 static BIO_METHOD* methods = [] {
47 BIO_METHOD* methods = BIO_meth_new(BIO_TYPE_BIO, "socket");
48 BIO_meth_set_write(methods, socket_write);
49 BIO_meth_set_read(methods, socket_read);
50 BIO_meth_set_puts(methods, socket_puts);
51 BIO_meth_set_ctrl(methods, socket_ctrl);
52 BIO_meth_set_create(methods, socket_new);
53 BIO_meth_set_destroy(methods, socket_free);
54 return methods;
55 }();
56 return methods;
57 }
58
BIO_new_socket(rtc::AsyncSocket * socket)59 static BIO* BIO_new_socket(rtc::AsyncSocket* socket) {
60 BIO* ret = BIO_new(BIO_socket_method());
61 if (ret == nullptr) {
62 return nullptr;
63 }
64 BIO_set_data(ret, socket);
65 return ret;
66 }
67
socket_new(BIO * b)68 static int socket_new(BIO* b) {
69 BIO_set_shutdown(b, 0);
70 BIO_set_init(b, 1);
71 BIO_set_data(b, 0);
72 return 1;
73 }
74
socket_free(BIO * b)75 static int socket_free(BIO* b) {
76 if (b == nullptr)
77 return 0;
78 return 1;
79 }
80
socket_read(BIO * b,char * out,int outl)81 static int socket_read(BIO* b, char* out, int outl) {
82 if (!out)
83 return -1;
84 rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(BIO_get_data(b));
85 BIO_clear_retry_flags(b);
86 int result = socket->Recv(out, outl, nullptr);
87 if (result > 0) {
88 return result;
89 } else if (socket->IsBlocking()) {
90 BIO_set_retry_read(b);
91 }
92 return -1;
93 }
94
socket_write(BIO * b,const char * in,int inl)95 static int socket_write(BIO* b, const char* in, int inl) {
96 if (!in)
97 return -1;
98 rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(BIO_get_data(b));
99 BIO_clear_retry_flags(b);
100 int result = socket->Send(in, inl);
101 if (result > 0) {
102 return result;
103 } else if (socket->IsBlocking()) {
104 BIO_set_retry_write(b);
105 }
106 return -1;
107 }
108
socket_puts(BIO * b,const char * str)109 static int socket_puts(BIO* b, const char* str) {
110 return socket_write(b, str, rtc::checked_cast<int>(strlen(str)));
111 }
112
socket_ctrl(BIO * b,int cmd,long num,void * ptr)113 static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) { // NOLINT
114 switch (cmd) {
115 case BIO_CTRL_RESET:
116 return 0;
117 case BIO_CTRL_EOF: {
118 rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(ptr);
119 // 1 means socket closed.
120 return (socket->GetState() == rtc::AsyncSocket::CS_CLOSED) ? 1 : 0;
121 }
122 case BIO_CTRL_WPENDING:
123 case BIO_CTRL_PENDING:
124 return 0;
125 case BIO_CTRL_FLUSH:
126 return 1;
127 default:
128 return 0;
129 }
130 }
131
LogSslError()132 static void LogSslError() {
133 // Walk down the error stack to find the SSL error.
134 uint32_t error_code;
135 const char* file;
136 int line;
137 do {
138 error_code = ERR_get_error_line(&file, &line);
139 if (ERR_GET_LIB(error_code) == ERR_LIB_SSL) {
140 RTC_LOG(LS_ERROR) << "ERR_LIB_SSL: " << error_code << ", " << file << ":"
141 << line;
142 break;
143 }
144 } while (error_code != 0);
145 }
146
147 /////////////////////////////////////////////////////////////////////////////
148 // OpenSSLAdapter
149 /////////////////////////////////////////////////////////////////////////////
150
151 namespace rtc {
152
InitializeSSL()153 bool OpenSSLAdapter::InitializeSSL() {
154 if (!SSL_library_init())
155 return false;
156 #if !defined(ADDRESS_SANITIZER) || !defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
157 // Loading the error strings crashes mac_asan. Omit this debugging aid there.
158 SSL_load_error_strings();
159 #endif
160 ERR_load_BIO_strings();
161 OpenSSL_add_all_algorithms();
162 RAND_poll();
163 return true;
164 }
165
CleanupSSL()166 bool OpenSSLAdapter::CleanupSSL() {
167 return true;
168 }
169
OpenSSLAdapter(AsyncSocket * socket,OpenSSLSessionCache * ssl_session_cache,SSLCertificateVerifier * ssl_cert_verifier)170 OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket,
171 OpenSSLSessionCache* ssl_session_cache,
172 SSLCertificateVerifier* ssl_cert_verifier)
173 : SSLAdapter(socket),
174 ssl_session_cache_(ssl_session_cache),
175 ssl_cert_verifier_(ssl_cert_verifier),
176 state_(SSL_NONE),
177 role_(SSL_CLIENT),
178 ssl_read_needs_write_(false),
179 ssl_write_needs_read_(false),
180 ssl_(nullptr),
181 ssl_ctx_(nullptr),
182 ssl_mode_(SSL_MODE_TLS),
183 ignore_bad_cert_(false),
184 custom_cert_verifier_status_(false) {
185 // If a factory is used, take a reference on the factory's SSL_CTX.
186 // Otherwise, we'll create our own later.
187 // Either way, we'll release our reference via SSL_CTX_free() in Cleanup().
188 if (ssl_session_cache_ != nullptr) {
189 ssl_ctx_ = ssl_session_cache_->GetSSLContext();
190 RTC_DCHECK(ssl_ctx_);
191 // Note: if using OpenSSL, requires version 1.1.0 or later.
192 SSL_CTX_up_ref(ssl_ctx_);
193 }
194 }
195
~OpenSSLAdapter()196 OpenSSLAdapter::~OpenSSLAdapter() {
197 Cleanup();
198 }
199
SetIgnoreBadCert(bool ignore)200 void OpenSSLAdapter::SetIgnoreBadCert(bool ignore) {
201 ignore_bad_cert_ = ignore;
202 }
203
SetAlpnProtocols(const std::vector<std::string> & protos)204 void OpenSSLAdapter::SetAlpnProtocols(const std::vector<std::string>& protos) {
205 alpn_protocols_ = protos;
206 }
207
SetEllipticCurves(const std::vector<std::string> & curves)208 void OpenSSLAdapter::SetEllipticCurves(const std::vector<std::string>& curves) {
209 elliptic_curves_ = curves;
210 }
211
SetMode(SSLMode mode)212 void OpenSSLAdapter::SetMode(SSLMode mode) {
213 RTC_DCHECK(!ssl_ctx_);
214 RTC_DCHECK(state_ == SSL_NONE);
215 ssl_mode_ = mode;
216 }
217
SetCertVerifier(SSLCertificateVerifier * ssl_cert_verifier)218 void OpenSSLAdapter::SetCertVerifier(
219 SSLCertificateVerifier* ssl_cert_verifier) {
220 RTC_DCHECK(!ssl_ctx_);
221 ssl_cert_verifier_ = ssl_cert_verifier;
222 }
223
SetIdentity(std::unique_ptr<SSLIdentity> identity)224 void OpenSSLAdapter::SetIdentity(std::unique_ptr<SSLIdentity> identity) {
225 RTC_DCHECK(!identity_);
226 identity_ =
227 absl::WrapUnique(static_cast<OpenSSLIdentity*>(identity.release()));
228 }
229
SetRole(SSLRole role)230 void OpenSSLAdapter::SetRole(SSLRole role) {
231 role_ = role;
232 }
233
Accept(SocketAddress * paddr)234 AsyncSocket* OpenSSLAdapter::Accept(SocketAddress* paddr) {
235 RTC_DCHECK(role_ == SSL_SERVER);
236 AsyncSocket* socket = SSLAdapter::Accept(paddr);
237 if (!socket) {
238 return nullptr;
239 }
240
241 SSLAdapter* adapter = SSLAdapter::Create(socket);
242 adapter->SetIdentity(identity_->Clone());
243 adapter->SetRole(rtc::SSL_SERVER);
244 adapter->SetIgnoreBadCert(ignore_bad_cert_);
245 adapter->StartSSL("");
246 return adapter;
247 }
248
StartSSL(const char * hostname)249 int OpenSSLAdapter::StartSSL(const char* hostname) {
250 if (state_ != SSL_NONE)
251 return -1;
252
253 ssl_host_name_ = hostname;
254
255 if (socket_->GetState() != Socket::CS_CONNECTED) {
256 state_ = SSL_WAIT;
257 return 0;
258 }
259
260 state_ = SSL_CONNECTING;
261 if (int err = BeginSSL()) {
262 Error("BeginSSL", err, false);
263 return err;
264 }
265
266 return 0;
267 }
268
BeginSSL()269 int OpenSSLAdapter::BeginSSL() {
270 RTC_LOG(LS_INFO) << "OpenSSLAdapter::BeginSSL: " << ssl_host_name_;
271 RTC_DCHECK(state_ == SSL_CONNECTING);
272
273 int err = 0;
274 BIO* bio = nullptr;
275
276 // First set up the context. We should either have a factory, with its own
277 // pre-existing context, or be running standalone, in which case we will
278 // need to create one, and specify |false| to disable session caching.
279 if (ssl_session_cache_ == nullptr) {
280 RTC_DCHECK(!ssl_ctx_);
281 ssl_ctx_ = CreateContext(ssl_mode_, false);
282 }
283
284 if (!ssl_ctx_) {
285 err = -1;
286 goto ssl_error;
287 }
288
289 if (identity_ && !identity_->ConfigureIdentity(ssl_ctx_)) {
290 SSL_CTX_free(ssl_ctx_);
291 err = -1;
292 goto ssl_error;
293 }
294
295 bio = BIO_new_socket(socket_);
296 if (!bio) {
297 err = -1;
298 goto ssl_error;
299 }
300
301 ssl_ = SSL_new(ssl_ctx_);
302 if (!ssl_) {
303 err = -1;
304 goto ssl_error;
305 }
306
307 SSL_set_app_data(ssl_, this);
308
309 // SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER allows different buffers to be passed
310 // into SSL_write when a record could only be partially transmitted (and thus
311 // requires another call to SSL_write to finish transmission). This allows us
312 // to copy the data into our own buffer when this occurs, since the original
313 // buffer can't safely be accessed after control exits Send.
314 // TODO(deadbeef): Do we want SSL_MODE_ENABLE_PARTIAL_WRITE? It doesn't
315 // appear Send handles partial writes properly, though maybe we never notice
316 // since we never send more than 16KB at once..
317 SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
318 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
319
320 // Enable SNI, if a hostname is supplied.
321 if (!ssl_host_name_.empty()) {
322 SSL_set_tlsext_host_name(ssl_, ssl_host_name_.c_str());
323
324 // Enable session caching, if configured and a hostname is supplied.
325 if (ssl_session_cache_ != nullptr) {
326 SSL_SESSION* cached = ssl_session_cache_->LookupSession(ssl_host_name_);
327 if (cached) {
328 if (SSL_set_session(ssl_, cached) == 0) {
329 RTC_LOG(LS_WARNING) << "Failed to apply SSL session from cache";
330 err = -1;
331 goto ssl_error;
332 }
333
334 RTC_LOG(LS_INFO) << "Attempting to resume SSL session to "
335 << ssl_host_name_;
336 }
337 }
338 }
339
340 #ifdef OPENSSL_IS_BORINGSSL
341 // Set a couple common TLS extensions; even though we don't use them yet.
342 SSL_enable_ocsp_stapling(ssl_);
343 SSL_enable_signed_cert_timestamps(ssl_);
344 #endif
345
346 if (!alpn_protocols_.empty()) {
347 std::string tls_alpn_string = TransformAlpnProtocols(alpn_protocols_);
348 if (!tls_alpn_string.empty()) {
349 SSL_set_alpn_protos(
350 ssl_, reinterpret_cast<const unsigned char*>(tls_alpn_string.data()),
351 rtc::dchecked_cast<unsigned>(tls_alpn_string.size()));
352 }
353 }
354
355 if (!elliptic_curves_.empty()) {
356 SSL_set1_curves_list(ssl_, rtc::join(elliptic_curves_, ':').c_str());
357 }
358
359 // Now that the initial config is done, transfer ownership of |bio| to the
360 // SSL object. If ContinueSSL() fails, the bio will be freed in Cleanup().
361 SSL_set_bio(ssl_, bio, bio);
362 bio = nullptr;
363
364 // Do the connect.
365 err = ContinueSSL();
366 if (err != 0) {
367 goto ssl_error;
368 }
369
370 return err;
371
372 ssl_error:
373 Cleanup();
374 if (bio) {
375 BIO_free(bio);
376 }
377
378 return err;
379 }
380
ContinueSSL()381 int OpenSSLAdapter::ContinueSSL() {
382 RTC_DCHECK(state_ == SSL_CONNECTING);
383
384 // Clear the DTLS timer
385 Thread::Current()->Clear(this, MSG_TIMEOUT);
386
387 int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
388 switch (SSL_get_error(ssl_, code)) {
389 case SSL_ERROR_NONE:
390 if (!SSLPostConnectionCheck(ssl_, ssl_host_name_)) {
391 RTC_LOG(LS_ERROR) << "TLS post connection check failed";
392 // make sure we close the socket
393 Cleanup();
394 // The connect failed so return -1 to shut down the socket
395 return -1;
396 }
397
398 state_ = SSL_CONNECTED;
399 AsyncSocketAdapter::OnConnectEvent(this);
400 // TODO(benwright): Refactor this code path.
401 // Don't let ourselves go away during the callbacks
402 // PRefPtr<OpenSSLAdapter> lock(this);
403 // RTC_LOG(LS_INFO) << " -- onStreamReadable";
404 // AsyncSocketAdapter::OnReadEvent(this);
405 // RTC_LOG(LS_INFO) << " -- onStreamWriteable";
406 // AsyncSocketAdapter::OnWriteEvent(this);
407 break;
408
409 case SSL_ERROR_WANT_READ:
410 RTC_LOG(LS_VERBOSE) << " -- error want read";
411 struct timeval timeout;
412 if (DTLSv1_get_timeout(ssl_, &timeout)) {
413 int delay = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
414
415 Thread::Current()->PostDelayed(RTC_FROM_HERE, delay, this, MSG_TIMEOUT,
416 0);
417 }
418 break;
419
420 case SSL_ERROR_WANT_WRITE:
421 break;
422
423 case SSL_ERROR_ZERO_RETURN:
424 default:
425 RTC_LOG(LS_WARNING) << "ContinueSSL -- error " << code;
426 return (code != 0) ? code : -1;
427 }
428
429 return 0;
430 }
431
Error(const char * context,int err,bool signal)432 void OpenSSLAdapter::Error(const char* context, int err, bool signal) {
433 RTC_LOG(LS_WARNING) << "OpenSSLAdapter::Error(" << context << ", " << err
434 << ")";
435 state_ = SSL_ERROR;
436 SetError(err);
437 if (signal) {
438 AsyncSocketAdapter::OnCloseEvent(this, err);
439 }
440 }
441
Cleanup()442 void OpenSSLAdapter::Cleanup() {
443 RTC_LOG(LS_INFO) << "OpenSSLAdapter::Cleanup";
444
445 state_ = SSL_NONE;
446 ssl_read_needs_write_ = false;
447 ssl_write_needs_read_ = false;
448 custom_cert_verifier_status_ = false;
449 pending_data_.Clear();
450
451 if (ssl_) {
452 SSL_free(ssl_);
453 ssl_ = nullptr;
454 }
455
456 if (ssl_ctx_) {
457 SSL_CTX_free(ssl_ctx_);
458 ssl_ctx_ = nullptr;
459 }
460 identity_.reset();
461
462 // Clear the DTLS timer
463 Thread::Current()->Clear(this, MSG_TIMEOUT);
464 }
465
DoSslWrite(const void * pv,size_t cb,int * error)466 int OpenSSLAdapter::DoSslWrite(const void* pv, size_t cb, int* error) {
467 // If we have pending data (that was previously only partially written by
468 // SSL_write), we shouldn't be attempting to write anything else.
469 RTC_DCHECK(pending_data_.empty() || pv == pending_data_.data());
470 RTC_DCHECK(error != nullptr);
471
472 ssl_write_needs_read_ = false;
473 int ret = SSL_write(ssl_, pv, checked_cast<int>(cb));
474 *error = SSL_get_error(ssl_, ret);
475 switch (*error) {
476 case SSL_ERROR_NONE:
477 // Success!
478 return ret;
479 case SSL_ERROR_WANT_READ:
480 RTC_LOG(LS_INFO) << " -- error want read";
481 ssl_write_needs_read_ = true;
482 SetError(EWOULDBLOCK);
483 break;
484 case SSL_ERROR_WANT_WRITE:
485 RTC_LOG(LS_INFO) << " -- error want write";
486 SetError(EWOULDBLOCK);
487 break;
488 case SSL_ERROR_ZERO_RETURN:
489 SetError(EWOULDBLOCK);
490 // do we need to signal closure?
491 break;
492 case SSL_ERROR_SSL:
493 LogSslError();
494 Error("SSL_write", ret ? ret : -1, false);
495 break;
496 default:
497 Error("SSL_write", ret ? ret : -1, false);
498 break;
499 }
500
501 return SOCKET_ERROR;
502 }
503
504 ///////////////////////////////////////////////////////////////////////////////
505 // AsyncSocket Implementation
506 ///////////////////////////////////////////////////////////////////////////////
507
Send(const void * pv,size_t cb)508 int OpenSSLAdapter::Send(const void* pv, size_t cb) {
509 switch (state_) {
510 case SSL_NONE:
511 return AsyncSocketAdapter::Send(pv, cb);
512 case SSL_WAIT:
513 case SSL_CONNECTING:
514 SetError(ENOTCONN);
515 return SOCKET_ERROR;
516 case SSL_CONNECTED:
517 break;
518 case SSL_ERROR:
519 default:
520 return SOCKET_ERROR;
521 }
522
523 int ret;
524 int error;
525
526 if (!pending_data_.empty()) {
527 ret = DoSslWrite(pending_data_.data(), pending_data_.size(), &error);
528 if (ret != static_cast<int>(pending_data_.size())) {
529 // We couldn't finish sending the pending data, so we definitely can't
530 // send any more data. Return with an EWOULDBLOCK error.
531 SetError(EWOULDBLOCK);
532 return SOCKET_ERROR;
533 }
534 // We completed sending the data previously passed into SSL_write! Now
535 // we're allowed to send more data.
536 pending_data_.Clear();
537 }
538
539 // OpenSSL will return an error if we try to write zero bytes
540 if (cb == 0) {
541 return 0;
542 }
543
544 ret = DoSslWrite(pv, cb, &error);
545
546 // If SSL_write fails with SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, this
547 // means the underlying socket is blocked on reading or (more typically)
548 // writing. When this happens, OpenSSL requires that the next call to
549 // SSL_write uses the same arguments (though, with
550 // SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, the actual buffer pointer may be
551 // different).
552 //
553 // However, after Send exits, we will have lost access to data the user of
554 // this class is trying to send, and there's no guarantee that the user of
555 // this class will call Send with the same arguements when it fails. So, we
556 // buffer the data ourselves. When we know the underlying socket is writable
557 // again from OnWriteEvent (or if Send is called again before that happens),
558 // we'll retry sending this buffered data.
559 if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
560 // Shouldn't be able to get to this point if we already have pending data.
561 RTC_DCHECK(pending_data_.empty());
562 RTC_LOG(LS_WARNING)
563 << "SSL_write couldn't write to the underlying socket; buffering data.";
564 pending_data_.SetData(static_cast<const uint8_t*>(pv), cb);
565 // Since we're taking responsibility for sending this data, return its full
566 // size. The user of this class can consider it sent.
567 return rtc::dchecked_cast<int>(cb);
568 }
569 return ret;
570 }
571
SendTo(const void * pv,size_t cb,const SocketAddress & addr)572 int OpenSSLAdapter::SendTo(const void* pv,
573 size_t cb,
574 const SocketAddress& addr) {
575 if (socket_->GetState() == Socket::CS_CONNECTED &&
576 addr == socket_->GetRemoteAddress()) {
577 return Send(pv, cb);
578 }
579
580 SetError(ENOTCONN);
581 return SOCKET_ERROR;
582 }
583
Recv(void * pv,size_t cb,int64_t * timestamp)584 int OpenSSLAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
585 switch (state_) {
586 case SSL_NONE:
587 return AsyncSocketAdapter::Recv(pv, cb, timestamp);
588 case SSL_WAIT:
589 case SSL_CONNECTING:
590 SetError(ENOTCONN);
591 return SOCKET_ERROR;
592 case SSL_CONNECTED:
593 break;
594 case SSL_ERROR:
595 default:
596 return SOCKET_ERROR;
597 }
598
599 // Don't trust OpenSSL with zero byte reads
600 if (cb == 0) {
601 return 0;
602 }
603
604 ssl_read_needs_write_ = false;
605 int code = SSL_read(ssl_, pv, checked_cast<int>(cb));
606 int error = SSL_get_error(ssl_, code);
607
608 switch (error) {
609 case SSL_ERROR_NONE:
610 return code;
611 case SSL_ERROR_WANT_READ:
612 SetError(EWOULDBLOCK);
613 break;
614 case SSL_ERROR_WANT_WRITE:
615 ssl_read_needs_write_ = true;
616 SetError(EWOULDBLOCK);
617 break;
618 case SSL_ERROR_ZERO_RETURN:
619 SetError(EWOULDBLOCK);
620 // do we need to signal closure?
621 break;
622 case SSL_ERROR_SSL:
623 LogSslError();
624 Error("SSL_read", (code ? code : -1), false);
625 break;
626 default:
627 Error("SSL_read", (code ? code : -1), false);
628 break;
629 }
630 return SOCKET_ERROR;
631 }
632
RecvFrom(void * pv,size_t cb,SocketAddress * paddr,int64_t * timestamp)633 int OpenSSLAdapter::RecvFrom(void* pv,
634 size_t cb,
635 SocketAddress* paddr,
636 int64_t* timestamp) {
637 if (socket_->GetState() == Socket::CS_CONNECTED) {
638 int ret = Recv(pv, cb, timestamp);
639 *paddr = GetRemoteAddress();
640 return ret;
641 }
642
643 SetError(ENOTCONN);
644 return SOCKET_ERROR;
645 }
646
Close()647 int OpenSSLAdapter::Close() {
648 Cleanup();
649 state_ = SSL_NONE;
650 return AsyncSocketAdapter::Close();
651 }
652
GetState() const653 Socket::ConnState OpenSSLAdapter::GetState() const {
654 ConnState state = socket_->GetState();
655 if ((state == CS_CONNECTED) &&
656 ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING))) {
657 state = CS_CONNECTING;
658 }
659 return state;
660 }
661
IsResumedSession()662 bool OpenSSLAdapter::IsResumedSession() {
663 return (ssl_ && SSL_session_reused(ssl_) == 1);
664 }
665
OnMessage(Message * msg)666 void OpenSSLAdapter::OnMessage(Message* msg) {
667 if (MSG_TIMEOUT == msg->message_id) {
668 RTC_LOG(LS_INFO) << "DTLS timeout expired";
669 DTLSv1_handle_timeout(ssl_);
670 ContinueSSL();
671 }
672 }
673
OnConnectEvent(AsyncSocket * socket)674 void OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) {
675 RTC_LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent";
676 if (state_ != SSL_WAIT) {
677 RTC_DCHECK(state_ == SSL_NONE);
678 AsyncSocketAdapter::OnConnectEvent(socket);
679 return;
680 }
681
682 state_ = SSL_CONNECTING;
683 if (int err = BeginSSL()) {
684 AsyncSocketAdapter::OnCloseEvent(socket, err);
685 }
686 }
687
OnReadEvent(AsyncSocket * socket)688 void OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) {
689 if (state_ == SSL_NONE) {
690 AsyncSocketAdapter::OnReadEvent(socket);
691 return;
692 }
693
694 if (state_ == SSL_CONNECTING) {
695 if (int err = ContinueSSL()) {
696 Error("ContinueSSL", err);
697 }
698 return;
699 }
700
701 if (state_ != SSL_CONNECTED) {
702 return;
703 }
704
705 // Don't let ourselves go away during the callbacks
706 // PRefPtr<OpenSSLAdapter> lock(this); // TODO(benwright): fix this
707 if (ssl_write_needs_read_) {
708 AsyncSocketAdapter::OnWriteEvent(socket);
709 }
710
711 AsyncSocketAdapter::OnReadEvent(socket);
712 }
713
OnWriteEvent(AsyncSocket * socket)714 void OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) {
715 if (state_ == SSL_NONE) {
716 AsyncSocketAdapter::OnWriteEvent(socket);
717 return;
718 }
719
720 if (state_ == SSL_CONNECTING) {
721 if (int err = ContinueSSL()) {
722 Error("ContinueSSL", err);
723 }
724 return;
725 }
726
727 if (state_ != SSL_CONNECTED) {
728 return;
729 }
730
731 // Don't let ourselves go away during the callbacks
732 // PRefPtr<OpenSSLAdapter> lock(this); // TODO(benwright): fix this
733
734 if (ssl_read_needs_write_) {
735 AsyncSocketAdapter::OnReadEvent(socket);
736 }
737
738 // If a previous SSL_write failed due to the underlying socket being blocked,
739 // this will attempt finishing the write operation.
740 if (!pending_data_.empty()) {
741 int error;
742 if (DoSslWrite(pending_data_.data(), pending_data_.size(), &error) ==
743 static_cast<int>(pending_data_.size())) {
744 pending_data_.Clear();
745 }
746 }
747
748 AsyncSocketAdapter::OnWriteEvent(socket);
749 }
750
OnCloseEvent(AsyncSocket * socket,int err)751 void OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
752 RTC_LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")";
753 AsyncSocketAdapter::OnCloseEvent(socket, err);
754 }
755
SSLPostConnectionCheck(SSL * ssl,const std::string & host)756 bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const std::string& host) {
757 bool is_valid_cert_name =
758 openssl::VerifyPeerCertMatchesHost(ssl, host) &&
759 (SSL_get_verify_result(ssl) == X509_V_OK || custom_cert_verifier_status_);
760
761 if (!is_valid_cert_name && ignore_bad_cert_) {
762 RTC_DLOG(LS_WARNING) << "Other TLS post connection checks failed. "
763 "ignore_bad_cert_ set to true. Overriding name "
764 "verification failure!";
765 is_valid_cert_name = true;
766 }
767 return is_valid_cert_name;
768 }
769
770 #if !defined(NDEBUG)
771
772 // We only use this for tracing and so it is only needed in debug mode
773
SSLInfoCallback(const SSL * s,int where,int ret)774 void OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) {
775 const char* str = "undefined";
776 int w = where & ~SSL_ST_MASK;
777 if (w & SSL_ST_CONNECT) {
778 str = "SSL_connect";
779 } else if (w & SSL_ST_ACCEPT) {
780 str = "SSL_accept";
781 }
782 if (where & SSL_CB_LOOP) {
783 RTC_DLOG(LS_VERBOSE) << str << ":" << SSL_state_string_long(s);
784 } else if (where & SSL_CB_ALERT) {
785 str = (where & SSL_CB_READ) ? "read" : "write";
786 RTC_DLOG(LS_INFO) << "SSL3 alert " << str << ":"
787 << SSL_alert_type_string_long(ret) << ":"
788 << SSL_alert_desc_string_long(ret);
789 } else if (where & SSL_CB_EXIT) {
790 if (ret == 0) {
791 RTC_DLOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s);
792 } else if (ret < 0) {
793 RTC_DLOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s);
794 }
795 }
796 }
797
798 #endif
799
SSLVerifyCallback(int ok,X509_STORE_CTX * store)800 int OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
801 #if !defined(NDEBUG)
802 if (!ok) {
803 char data[256];
804 X509* cert = X509_STORE_CTX_get_current_cert(store);
805 int depth = X509_STORE_CTX_get_error_depth(store);
806 int err = X509_STORE_CTX_get_error(store);
807
808 RTC_DLOG(LS_INFO) << "Error with certificate at depth: " << depth;
809 X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
810 RTC_DLOG(LS_INFO) << " issuer = " << data;
811 X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
812 RTC_DLOG(LS_INFO) << " subject = " << data;
813 RTC_DLOG(LS_INFO) << " err = " << err << ":"
814 << X509_verify_cert_error_string(err);
815 }
816 #endif
817 // Get our stream pointer from the store
818 SSL* ssl = reinterpret_cast<SSL*>(
819 X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx()));
820
821 OpenSSLAdapter* stream =
822 reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
823
824 if (!ok && stream->ssl_cert_verifier_ != nullptr) {
825 RTC_LOG(LS_INFO) << "Invoking SSL Verify Callback.";
826 const OpenSSLCertificate cert(X509_STORE_CTX_get_current_cert(store));
827 if (stream->ssl_cert_verifier_->Verify(cert)) {
828 stream->custom_cert_verifier_status_ = true;
829 RTC_LOG(LS_INFO) << "Validated certificate using custom callback";
830 ok = true;
831 } else {
832 RTC_LOG(LS_INFO) << "Failed to verify certificate using custom callback";
833 }
834 }
835
836 // Should only be used for debugging and development.
837 if (!ok && stream->ignore_bad_cert_) {
838 RTC_DLOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
839 ok = 1;
840 }
841
842 return ok;
843 }
844
NewSSLSessionCallback(SSL * ssl,SSL_SESSION * session)845 int OpenSSLAdapter::NewSSLSessionCallback(SSL* ssl, SSL_SESSION* session) {
846 OpenSSLAdapter* stream =
847 reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
848 RTC_DCHECK(stream->ssl_session_cache_);
849 RTC_LOG(LS_INFO) << "Caching SSL session for " << stream->ssl_host_name_;
850 stream->ssl_session_cache_->AddSession(stream->ssl_host_name_, session);
851 return 1; // We've taken ownership of the session; OpenSSL shouldn't free it.
852 }
853
CreateContext(SSLMode mode,bool enable_cache)854 SSL_CTX* OpenSSLAdapter::CreateContext(SSLMode mode, bool enable_cache) {
855 SSL_CTX* ctx =
856 SSL_CTX_new(mode == SSL_MODE_DTLS ? DTLS_method() : TLS_method());
857 if (ctx == nullptr) {
858 unsigned long error = ERR_get_error(); // NOLINT: type used by OpenSSL.
859 RTC_LOG(LS_WARNING) << "SSL_CTX creation failed: " << '"'
860 << ERR_reason_error_string(error)
861 << "\" "
862 "(error="
863 << error << ')';
864 return nullptr;
865 }
866
867 #ifndef WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS
868 if (!openssl::LoadBuiltinSSLRootCertificates(ctx)) {
869 RTC_LOG(LS_ERROR) << "SSL_CTX creation failed: Failed to load any trusted "
870 "ssl root certificates.";
871 SSL_CTX_free(ctx);
872 return nullptr;
873 }
874 #endif // WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS
875
876 #if !defined(NDEBUG)
877 SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
878 #endif
879
880 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback);
881 SSL_CTX_set_verify_depth(ctx, 4);
882 // Use defaults, but disable HMAC-SHA256 and HMAC-SHA384 ciphers
883 // (note that SHA256 and SHA384 only select legacy CBC ciphers).
884 // Additionally disable HMAC-SHA1 ciphers in ECDSA. These are the remaining
885 // CBC-mode ECDSA ciphers.
886 SSL_CTX_set_cipher_list(
887 ctx, "ALL:!SHA256:!SHA384:!aPSK:!ECDSA+SHA1:!ADH:!LOW:!EXP:!MD5");
888
889 if (mode == SSL_MODE_DTLS) {
890 SSL_CTX_set_read_ahead(ctx, 1);
891 }
892
893 if (enable_cache) {
894 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT);
895 SSL_CTX_sess_set_new_cb(ctx, &OpenSSLAdapter::NewSSLSessionCallback);
896 }
897
898 return ctx;
899 }
900
TransformAlpnProtocols(const std::vector<std::string> & alpn_protocols)901 std::string TransformAlpnProtocols(
902 const std::vector<std::string>& alpn_protocols) {
903 // Transforms the alpn_protocols list to the format expected by
904 // Open/BoringSSL. This requires joining the protocols into a single string
905 // and prepending a character with the size of the protocol string before
906 // each protocol.
907 std::string transformed_alpn;
908 for (const std::string& proto : alpn_protocols) {
909 if (proto.size() == 0 || proto.size() > 0xFF) {
910 RTC_LOG(LS_ERROR) << "OpenSSLAdapter::Error("
911 "TransformAlpnProtocols received proto with size "
912 << proto.size() << ")";
913 return "";
914 }
915 transformed_alpn += static_cast<char>(proto.size());
916 transformed_alpn += proto;
917 RTC_LOG(LS_VERBOSE) << "TransformAlpnProtocols: Adding proto: " << proto;
918 }
919 return transformed_alpn;
920 }
921
922 //////////////////////////////////////////////////////////////////////
923 // OpenSSLAdapterFactory
924 //////////////////////////////////////////////////////////////////////
925
926 OpenSSLAdapterFactory::OpenSSLAdapterFactory() = default;
927
928 OpenSSLAdapterFactory::~OpenSSLAdapterFactory() = default;
929
SetMode(SSLMode mode)930 void OpenSSLAdapterFactory::SetMode(SSLMode mode) {
931 RTC_DCHECK(!ssl_session_cache_);
932 ssl_mode_ = mode;
933 }
934
SetCertVerifier(SSLCertificateVerifier * ssl_cert_verifier)935 void OpenSSLAdapterFactory::SetCertVerifier(
936 SSLCertificateVerifier* ssl_cert_verifier) {
937 RTC_DCHECK(!ssl_session_cache_);
938 ssl_cert_verifier_ = ssl_cert_verifier;
939 }
940
CreateAdapter(AsyncSocket * socket)941 OpenSSLAdapter* OpenSSLAdapterFactory::CreateAdapter(AsyncSocket* socket) {
942 if (ssl_session_cache_ == nullptr) {
943 SSL_CTX* ssl_ctx = OpenSSLAdapter::CreateContext(ssl_mode_, true);
944 if (ssl_ctx == nullptr) {
945 return nullptr;
946 }
947 // The OpenSSLSessionCache will upref the ssl_ctx.
948 ssl_session_cache_ =
949 std::make_unique<OpenSSLSessionCache>(ssl_mode_, ssl_ctx);
950 SSL_CTX_free(ssl_ctx);
951 }
952 return new OpenSSLAdapter(socket, ssl_session_cache_.get(),
953 ssl_cert_verifier_);
954 }
955
956 } // namespace rtc
957