blob: eec80216dafa9dd7d9b7c52ae8bdbb9e4e5b6086 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
kjellandere96c45b2017-06-30 10:45:21 -070011#include "webrtc/rtc_base/openssladapter.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
13#if defined(WEBRTC_POSIX)
14#include <unistd.h>
15#endif
16
17// Must be included first before openssl headers.
kjellandere96c45b2017-06-30 10:45:21 -070018#include "webrtc/rtc_base/win32.h" // NOLINT
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019
20#include <openssl/bio.h>
21#include <openssl/crypto.h>
22#include <openssl/err.h>
23#include <openssl/opensslv.h>
24#include <openssl/rand.h>
henrike@webrtc.orgd5a05062014-06-30 20:38:56 +000025#include <openssl/x509.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026#include <openssl/x509v3.h>
27
kjellandere96c45b2017-06-30 10:45:21 -070028#include "webrtc/rtc_base/arraysize.h"
29#include "webrtc/rtc_base/checks.h"
30#include "webrtc/rtc_base/logging.h"
31#include "webrtc/rtc_base/openssl.h"
32#include "webrtc/rtc_base/safe_conversions.h"
33#include "webrtc/rtc_base/sslroots.h"
34#include "webrtc/rtc_base/stringutils.h"
35#include "webrtc/rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010037#ifndef OPENSSL_IS_BORINGSSL
38
39// TODO: Use a nicer abstraction for mutex.
40
41#if defined(WEBRTC_WIN)
42 #define MUTEX_TYPE HANDLE
deadbeef37f5ecf2017-02-27 14:06:41 -080043#define MUTEX_SETUP(x) (x) = CreateMutex(nullptr, FALSE, nullptr)
44#define MUTEX_CLEANUP(x) CloseHandle(x)
45#define MUTEX_LOCK(x) WaitForSingleObject((x), INFINITE)
46#define MUTEX_UNLOCK(x) ReleaseMutex(x)
47#define THREAD_ID GetCurrentThreadId()
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010048#elif defined(WEBRTC_POSIX)
49 #define MUTEX_TYPE pthread_mutex_t
deadbeef37f5ecf2017-02-27 14:06:41 -080050 #define MUTEX_SETUP(x) pthread_mutex_init(&(x), nullptr)
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +010051 #define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
52 #define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
53 #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
54 #define THREAD_ID pthread_self()
55#else
56 #error You must define mutex operations appropriate for your platform!
57#endif
58
59struct CRYPTO_dynlock_value {
60 MUTEX_TYPE mutex;
61};
62
63#endif // #ifndef OPENSSL_IS_BORINGSSL
64
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065//////////////////////////////////////////////////////////////////////
66// SocketBIO
67//////////////////////////////////////////////////////////////////////
68
69static int socket_write(BIO* h, const char* buf, int num);
70static int socket_read(BIO* h, char* buf, int size);
71static int socket_puts(BIO* h, const char* str);
72static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2);
73static int socket_new(BIO* h);
74static int socket_free(BIO* data);
75
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +000076// TODO(davidben): This should be const once BoringSSL is assumed.
77static BIO_METHOD methods_socket = {
deadbeef37f5ecf2017-02-27 14:06:41 -080078 BIO_TYPE_BIO, "socket", socket_write, socket_read, socket_puts, 0,
79 socket_ctrl, socket_new, socket_free, nullptr,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080};
81
davidben@webrtc.org36d5c3c2015-01-22 23:06:17 +000082static BIO_METHOD* BIO_s_socket2() { return(&methods_socket); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083
henrike@webrtc.orgc50bf7c2014-05-14 18:24:13 +000084static BIO* BIO_new_socket(rtc::AsyncSocket* socket) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085 BIO* ret = BIO_new(BIO_s_socket2());
deadbeef37f5ecf2017-02-27 14:06:41 -080086 if (ret == nullptr) {
87 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088 }
89 ret->ptr = socket;
90 return ret;
91}
92
93static int socket_new(BIO* b) {
94 b->shutdown = 0;
95 b->init = 1;
96 b->num = 0; // 1 means socket closed
97 b->ptr = 0;
98 return 1;
99}
100
101static int socket_free(BIO* b) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800102 if (b == nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103 return 0;
104 return 1;
105}
106
107static int socket_read(BIO* b, char* out, int outl) {
108 if (!out)
109 return -1;
110 rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(b->ptr);
111 BIO_clear_retry_flags(b);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200112 int result = socket->Recv(out, outl, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113 if (result > 0) {
114 return result;
115 } else if (result == 0) {
116 b->num = 1;
117 } else if (socket->IsBlocking()) {
118 BIO_set_retry_read(b);
119 }
120 return -1;
121}
122
123static int socket_write(BIO* b, const char* in, int inl) {
124 if (!in)
125 return -1;
126 rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(b->ptr);
127 BIO_clear_retry_flags(b);
128 int result = socket->Send(in, inl);
129 if (result > 0) {
130 return result;
131 } else if (socket->IsBlocking()) {
132 BIO_set_retry_write(b);
133 }
134 return -1;
135}
136
137static int socket_puts(BIO* b, const char* str) {
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000138 return socket_write(b, str, rtc::checked_cast<int>(strlen(str)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139}
140
141static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 switch (cmd) {
143 case BIO_CTRL_RESET:
144 return 0;
145 case BIO_CTRL_EOF:
146 return b->num;
147 case BIO_CTRL_WPENDING:
148 case BIO_CTRL_PENDING:
149 return 0;
150 case BIO_CTRL_FLUSH:
151 return 1;
152 default:
153 return 0;
154 }
155}
156
deadbeefed3b9862017-06-02 10:33:16 -0700157static void LogSslError() {
158 // Walk down the error stack to find the SSL error.
159 uint32_t error_code;
160 const char* file;
161 int line;
162 do {
163 error_code = ERR_get_error_line(&file, &line);
164 if (ERR_GET_LIB(error_code) == ERR_LIB_SSL) {
165 LOG(LS_ERROR) << "ERR_LIB_SSL: " << error_code << ", " << file << ":"
166 << line;
167 break;
168 }
169 } while (error_code != 0);
170}
171
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172/////////////////////////////////////////////////////////////////////////////
173// OpenSSLAdapter
174/////////////////////////////////////////////////////////////////////////////
175
176namespace rtc {
177
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100178#ifndef OPENSSL_IS_BORINGSSL
179
180// This array will store all of the mutexes available to OpenSSL.
deadbeef37f5ecf2017-02-27 14:06:41 -0800181static MUTEX_TYPE* mutex_buf = nullptr;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100182
183static void locking_function(int mode, int n, const char * file, int line) {
184 if (mode & CRYPTO_LOCK) {
185 MUTEX_LOCK(mutex_buf[n]);
186 } else {
187 MUTEX_UNLOCK(mutex_buf[n]);
188 }
189}
190
191static unsigned long id_function() { // NOLINT
192 // Use old-style C cast because THREAD_ID's type varies with the platform,
193 // in some cases requiring static_cast, and in others requiring
194 // reinterpret_cast.
195 return (unsigned long)THREAD_ID; // NOLINT
196}
197
198static CRYPTO_dynlock_value* dyn_create_function(const char* file, int line) {
199 CRYPTO_dynlock_value* value = new CRYPTO_dynlock_value;
200 if (!value)
deadbeef37f5ecf2017-02-27 14:06:41 -0800201 return nullptr;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100202 MUTEX_SETUP(value->mutex);
203 return value;
204}
205
206static void dyn_lock_function(int mode, CRYPTO_dynlock_value* l,
207 const char* file, int line) {
208 if (mode & CRYPTO_LOCK) {
209 MUTEX_LOCK(l->mutex);
210 } else {
211 MUTEX_UNLOCK(l->mutex);
212 }
213}
214
215static void dyn_destroy_function(CRYPTO_dynlock_value* l,
216 const char* file, int line) {
217 MUTEX_CLEANUP(l->mutex);
218 delete l;
219}
220
221#endif // #ifndef OPENSSL_IS_BORINGSSL
222
deadbeef37f5ecf2017-02-27 14:06:41 -0800223VerificationCallback OpenSSLAdapter::custom_verify_callback_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224
225bool OpenSSLAdapter::InitializeSSL(VerificationCallback callback) {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100226 if (!InitializeSSLThread() || !SSL_library_init())
227 return false;
228#if !defined(ADDRESS_SANITIZER) || !defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
229 // Loading the error strings crashes mac_asan. Omit this debugging aid there.
230 SSL_load_error_strings();
231#endif
232 ERR_load_BIO_strings();
233 OpenSSL_add_all_algorithms();
234 RAND_poll();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000235 custom_verify_callback_ = callback;
236 return true;
237}
238
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100239bool OpenSSLAdapter::InitializeSSLThread() {
240 // BoringSSL is doing the locking internally, so the callbacks are not used
241 // in this case (and are no-ops anyways).
242#ifndef OPENSSL_IS_BORINGSSL
243 mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
244 if (!mutex_buf)
245 return false;
246 for (int i = 0; i < CRYPTO_num_locks(); ++i)
247 MUTEX_SETUP(mutex_buf[i]);
248
249 // we need to cast our id_function to return an unsigned long -- pthread_t is
250 // a pointer
251 CRYPTO_set_id_callback(id_function);
252 CRYPTO_set_locking_callback(locking_function);
253 CRYPTO_set_dynlock_create_callback(dyn_create_function);
254 CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
255 CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
256#endif // #ifndef OPENSSL_IS_BORINGSSL
257 return true;
258}
259
260bool OpenSSLAdapter::CleanupSSL() {
261#ifndef OPENSSL_IS_BORINGSSL
262 if (!mutex_buf)
263 return false;
deadbeef37f5ecf2017-02-27 14:06:41 -0800264 CRYPTO_set_id_callback(nullptr);
265 CRYPTO_set_locking_callback(nullptr);
266 CRYPTO_set_dynlock_create_callback(nullptr);
267 CRYPTO_set_dynlock_lock_callback(nullptr);
268 CRYPTO_set_dynlock_destroy_callback(nullptr);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100269 for (int i = 0; i < CRYPTO_num_locks(); ++i)
270 MUTEX_CLEANUP(mutex_buf[i]);
271 delete [] mutex_buf;
deadbeef37f5ecf2017-02-27 14:06:41 -0800272 mutex_buf = nullptr;
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100273#endif // #ifndef OPENSSL_IS_BORINGSSL
274 return true;
275}
276
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket)
deadbeef37f5ecf2017-02-27 14:06:41 -0800278 : SSLAdapter(socket),
279 state_(SSL_NONE),
280 ssl_read_needs_write_(false),
281 ssl_write_needs_read_(false),
282 restartable_(false),
283 ssl_(nullptr),
284 ssl_ctx_(nullptr),
285 ssl_mode_(SSL_MODE_TLS),
286 custom_verification_succeeded_(false) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287
288OpenSSLAdapter::~OpenSSLAdapter() {
289 Cleanup();
290}
291
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000292void
293OpenSSLAdapter::SetMode(SSLMode mode) {
nisseede5da42017-01-12 05:15:36 -0800294 RTC_DCHECK(state_ == SSL_NONE);
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000295 ssl_mode_ = mode;
296}
297
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298int
299OpenSSLAdapter::StartSSL(const char* hostname, bool restartable) {
300 if (state_ != SSL_NONE)
301 return -1;
302
303 ssl_host_name_ = hostname;
304 restartable_ = restartable;
305
306 if (socket_->GetState() != Socket::CS_CONNECTED) {
307 state_ = SSL_WAIT;
308 return 0;
309 }
310
311 state_ = SSL_CONNECTING;
312 if (int err = BeginSSL()) {
313 Error("BeginSSL", err, false);
314 return err;
315 }
316
317 return 0;
318}
319
320int
321OpenSSLAdapter::BeginSSL() {
322 LOG(LS_INFO) << "BeginSSL: " << ssl_host_name_;
nisseede5da42017-01-12 05:15:36 -0800323 RTC_DCHECK(state_ == SSL_CONNECTING);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324
325 int err = 0;
deadbeef37f5ecf2017-02-27 14:06:41 -0800326 BIO* bio = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000327
328 // First set up the context
329 if (!ssl_ctx_)
330 ssl_ctx_ = SetupSSLContext();
331
332 if (!ssl_ctx_) {
333 err = -1;
334 goto ssl_error;
335 }
336
Peter Boström0b518bf2016-01-27 12:35:40 +0100337 bio = BIO_new_socket(socket_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000338 if (!bio) {
339 err = -1;
340 goto ssl_error;
341 }
342
343 ssl_ = SSL_new(ssl_ctx_);
344 if (!ssl_) {
345 err = -1;
346 goto ssl_error;
347 }
348
349 SSL_set_app_data(ssl_, this);
350
351 SSL_set_bio(ssl_, bio, bio);
deadbeefed3b9862017-06-02 10:33:16 -0700352 // SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER allows different buffers to be passed
353 // into SSL_write when a record could only be partially transmitted (and thus
354 // requires another call to SSL_write to finish transmission). This allows us
355 // to copy the data into our own buffer when this occurs, since the original
356 // buffer can't safely be accessed after control exits Send.
357 // TODO(deadbeef): Do we want SSL_MODE_ENABLE_PARTIAL_WRITE? It doesn't
358 // appear Send handles partial writes properly, though maybe we never notice
359 // since we never send more than 16KB at once..
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000360 SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
361 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
362
Emad Omaradab1d2d2017-06-16 15:43:11 -0700363 // Enable SNI.
364 if (!ssl_host_name_.empty()) {
365 SSL_set_tlsext_host_name(ssl_, ssl_host_name_.c_str());
366 }
367
Emad Omaracb79d232017-07-20 16:34:34 -0700368 // Set a couple common TLS extensions; even though we don't use them yet.
369 // TODO(emadomara) Add ALPN extension.
370 SSL_enable_ocsp_stapling(ssl_);
371 SSL_enable_signed_cert_timestamps(ssl_);
372
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000373 // the SSL object owns the bio now
deadbeef37f5ecf2017-02-27 14:06:41 -0800374 bio = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375
376 // Do the connect
377 err = ContinueSSL();
378 if (err != 0)
379 goto ssl_error;
380
381 return err;
382
383ssl_error:
384 Cleanup();
385 if (bio)
386 BIO_free(bio);
387
388 return err;
389}
390
391int
392OpenSSLAdapter::ContinueSSL() {
nisseede5da42017-01-12 05:15:36 -0800393 RTC_DCHECK(state_ == SSL_CONNECTING);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000394
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000395 // Clear the DTLS timer
396 Thread::Current()->Clear(this, MSG_TIMEOUT);
397
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000398 int code = SSL_connect(ssl_);
399 switch (SSL_get_error(ssl_, code)) {
400 case SSL_ERROR_NONE:
401 if (!SSLPostConnectionCheck(ssl_, ssl_host_name_.c_str())) {
402 LOG(LS_ERROR) << "TLS post connection check failed";
403 // make sure we close the socket
404 Cleanup();
405 // The connect failed so return -1 to shut down the socket
406 return -1;
407 }
408
409 state_ = SSL_CONNECTED;
410 AsyncSocketAdapter::OnConnectEvent(this);
411#if 0 // TODO: worry about this
412 // Don't let ourselves go away during the callbacks
413 PRefPtr<OpenSSLAdapter> lock(this);
414 LOG(LS_INFO) << " -- onStreamReadable";
415 AsyncSocketAdapter::OnReadEvent(this);
416 LOG(LS_INFO) << " -- onStreamWriteable";
417 AsyncSocketAdapter::OnWriteEvent(this);
418#endif
419 break;
420
421 case SSL_ERROR_WANT_READ:
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000422 LOG(LS_VERBOSE) << " -- error want read";
423 struct timeval timeout;
424 if (DTLSv1_get_timeout(ssl_, &timeout)) {
425 int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
426
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700427 Thread::Current()->PostDelayed(RTC_FROM_HERE, delay, this, MSG_TIMEOUT,
428 0);
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000429 }
430 break;
431
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000432 case SSL_ERROR_WANT_WRITE:
433 break;
434
435 case SSL_ERROR_ZERO_RETURN:
436 default:
437 LOG(LS_WARNING) << "ContinueSSL -- error " << code;
438 return (code != 0) ? code : -1;
439 }
440
441 return 0;
442}
443
444void
445OpenSSLAdapter::Error(const char* context, int err, bool signal) {
446 LOG(LS_WARNING) << "OpenSSLAdapter::Error("
447 << context << ", " << err << ")";
448 state_ = SSL_ERROR;
449 SetError(err);
450 if (signal)
451 AsyncSocketAdapter::OnCloseEvent(this, err);
452}
453
454void
455OpenSSLAdapter::Cleanup() {
456 LOG(LS_INFO) << "Cleanup";
457
458 state_ = SSL_NONE;
459 ssl_read_needs_write_ = false;
460 ssl_write_needs_read_ = false;
461 custom_verification_succeeded_ = false;
deadbeefed3b9862017-06-02 10:33:16 -0700462 pending_data_.Clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000463
464 if (ssl_) {
465 SSL_free(ssl_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800466 ssl_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000467 }
468
469 if (ssl_ctx_) {
470 SSL_CTX_free(ssl_ctx_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800471 ssl_ctx_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000472 }
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000473
474 // Clear the DTLS timer
475 Thread::Current()->Clear(this, MSG_TIMEOUT);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000476}
477
deadbeefed3b9862017-06-02 10:33:16 -0700478int OpenSSLAdapter::DoSslWrite(const void* pv, size_t cb, int* error) {
479 // If we have pending data (that was previously only partially written by
480 // SSL_write), we shouldn't be attempting to write anything else.
481 RTC_DCHECK(pending_data_.empty() || pv == pending_data_.data());
482 RTC_DCHECK(error != nullptr);
483
484 ssl_write_needs_read_ = false;
485 int ret = SSL_write(ssl_, pv, checked_cast<int>(cb));
486 *error = SSL_get_error(ssl_, ret);
487 switch (*error) {
488 case SSL_ERROR_NONE:
489 // Success!
490 return ret;
491 case SSL_ERROR_WANT_READ:
492 LOG(LS_INFO) << " -- error want read";
493 ssl_write_needs_read_ = true;
494 SetError(EWOULDBLOCK);
495 break;
496 case SSL_ERROR_WANT_WRITE:
497 LOG(LS_INFO) << " -- error want write";
498 SetError(EWOULDBLOCK);
499 break;
500 case SSL_ERROR_ZERO_RETURN:
501 // LOG(LS_INFO) << " -- remote side closed";
502 SetError(EWOULDBLOCK);
503 // do we need to signal closure?
504 break;
505 case SSL_ERROR_SSL:
506 LogSslError();
507 Error("SSL_write", ret ? ret : -1, false);
508 break;
509 default:
510 LOG(LS_WARNING) << "Unknown error from SSL_write: " << *error;
511 Error("SSL_write", ret ? ret : -1, false);
512 break;
513 }
514
515 return SOCKET_ERROR;
516}
517
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000518//
519// AsyncSocket Implementation
520//
521
522int
523OpenSSLAdapter::Send(const void* pv, size_t cb) {
524 //LOG(LS_INFO) << "OpenSSLAdapter::Send(" << cb << ")";
525
526 switch (state_) {
527 case SSL_NONE:
528 return AsyncSocketAdapter::Send(pv, cb);
529
530 case SSL_WAIT:
531 case SSL_CONNECTING:
skvladc309e0e2016-07-28 17:15:20 -0700532 SetError(ENOTCONN);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000533 return SOCKET_ERROR;
534
535 case SSL_CONNECTED:
536 break;
537
538 case SSL_ERROR:
539 default:
540 return SOCKET_ERROR;
541 }
542
deadbeefed3b9862017-06-02 10:33:16 -0700543 int ret;
544 int error;
545
546 if (!pending_data_.empty()) {
547 ret = DoSslWrite(pending_data_.data(), pending_data_.size(), &error);
548 if (ret != static_cast<int>(pending_data_.size())) {
549 // We couldn't finish sending the pending data, so we definitely can't
550 // send any more data. Return with an EWOULDBLOCK error.
551 SetError(EWOULDBLOCK);
552 return SOCKET_ERROR;
553 }
554 // We completed sending the data previously passed into SSL_write! Now
555 // we're allowed to send more data.
556 pending_data_.Clear();
557 }
558
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000559 // OpenSSL will return an error if we try to write zero bytes
560 if (cb == 0)
561 return 0;
562
deadbeefed3b9862017-06-02 10:33:16 -0700563 ret = DoSslWrite(pv, cb, &error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000564
deadbeefed3b9862017-06-02 10:33:16 -0700565 // If SSL_write fails with SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, this
566 // means the underlying socket is blocked on reading or (more typically)
567 // writing. When this happens, OpenSSL requires that the next call to
568 // SSL_write uses the same arguments (though, with
569 // SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, the actual buffer pointer may be
570 // different).
571 //
572 // However, after Send exits, we will have lost access to data the user of
573 // this class is trying to send, and there's no guarantee that the user of
574 // this class will call Send with the same arguements when it fails. So, we
575 // buffer the data ourselves. When we know the underlying socket is writable
576 // again from OnWriteEvent (or if Send is called again before that happens),
577 // we'll retry sending this buffered data.
deadbeefe5dce2b2017-06-02 11:52:06 -0700578 if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
579 // Shouldn't be able to get to this point if we already have pending data.
580 RTC_DCHECK(pending_data_.empty());
deadbeefed3b9862017-06-02 10:33:16 -0700581 LOG(LS_WARNING)
582 << "SSL_write couldn't write to the underlying socket; buffering data.";
583 pending_data_.SetData(static_cast<const uint8_t*>(pv), cb);
584 // Since we're taking responsibility for sending this data, return its full
585 // size. The user of this class can consider it sent.
586 return cb;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000587 }
588
deadbeefed3b9862017-06-02 10:33:16 -0700589 return ret;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000590}
591
592int
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000593OpenSSLAdapter::SendTo(const void* pv, size_t cb, const SocketAddress& addr) {
594 if (socket_->GetState() == Socket::CS_CONNECTED &&
595 addr == socket_->GetRemoteAddress()) {
596 return Send(pv, cb);
597 }
598
599 SetError(ENOTCONN);
600
601 return SOCKET_ERROR;
602}
603
Stefan Holmer9131efd2016-05-23 18:19:26 +0200604int OpenSSLAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000605 //LOG(LS_INFO) << "OpenSSLAdapter::Recv(" << cb << ")";
606 switch (state_) {
607
608 case SSL_NONE:
Stefan Holmer9131efd2016-05-23 18:19:26 +0200609 return AsyncSocketAdapter::Recv(pv, cb, timestamp);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000610
611 case SSL_WAIT:
612 case SSL_CONNECTING:
skvladc309e0e2016-07-28 17:15:20 -0700613 SetError(ENOTCONN);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000614 return SOCKET_ERROR;
615
616 case SSL_CONNECTED:
617 break;
618
619 case SSL_ERROR:
620 default:
621 return SOCKET_ERROR;
622 }
623
624 // Don't trust OpenSSL with zero byte reads
625 if (cb == 0)
626 return 0;
627
628 ssl_read_needs_write_ = false;
629
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +0000630 int code = SSL_read(ssl_, pv, checked_cast<int>(cb));
deadbeefed3b9862017-06-02 10:33:16 -0700631 int error = SSL_get_error(ssl_, code);
632 switch (error) {
633 case SSL_ERROR_NONE:
634 // LOG(LS_INFO) << " -- success";
635 return code;
636 case SSL_ERROR_WANT_READ:
637 // LOG(LS_INFO) << " -- error want read";
638 SetError(EWOULDBLOCK);
639 break;
640 case SSL_ERROR_WANT_WRITE:
641 // LOG(LS_INFO) << " -- error want write";
642 ssl_read_needs_write_ = true;
643 SetError(EWOULDBLOCK);
644 break;
645 case SSL_ERROR_ZERO_RETURN:
646 // LOG(LS_INFO) << " -- remote side closed";
647 SetError(EWOULDBLOCK);
648 // do we need to signal closure?
649 break;
650 case SSL_ERROR_SSL:
651 LogSslError();
652 Error("SSL_read", (code ? code : -1), false);
653 break;
654 default:
655 LOG(LS_WARNING) << "Unknown error from SSL_read: " << error;
656 Error("SSL_read", (code ? code : -1), false);
657 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000658 }
659
660 return SOCKET_ERROR;
661}
662
Stefan Holmer9131efd2016-05-23 18:19:26 +0200663int OpenSSLAdapter::RecvFrom(void* pv,
664 size_t cb,
665 SocketAddress* paddr,
666 int64_t* timestamp) {
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000667 if (socket_->GetState() == Socket::CS_CONNECTED) {
Stefan Holmer9131efd2016-05-23 18:19:26 +0200668 int ret = Recv(pv, cb, timestamp);
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000669
670 *paddr = GetRemoteAddress();
671
672 return ret;
673 }
674
675 SetError(ENOTCONN);
676
677 return SOCKET_ERROR;
678}
679
680int
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000681OpenSSLAdapter::Close() {
682 Cleanup();
683 state_ = restartable_ ? SSL_WAIT : SSL_NONE;
684 return AsyncSocketAdapter::Close();
685}
686
687Socket::ConnState
688OpenSSLAdapter::GetState() const {
689 //if (signal_close_)
690 // return CS_CONNECTED;
691 ConnState state = socket_->GetState();
692 if ((state == CS_CONNECTED)
693 && ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
694 state = CS_CONNECTING;
695 return state;
696}
697
698void
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +0000699OpenSSLAdapter::OnMessage(Message* msg) {
700 if (MSG_TIMEOUT == msg->message_id) {
701 LOG(LS_INFO) << "DTLS timeout expired";
702 DTLSv1_handle_timeout(ssl_);
703 ContinueSSL();
704 }
705}
706
707void
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000708OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) {
709 LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent";
710 if (state_ != SSL_WAIT) {
nisseede5da42017-01-12 05:15:36 -0800711 RTC_DCHECK(state_ == SSL_NONE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000712 AsyncSocketAdapter::OnConnectEvent(socket);
713 return;
714 }
715
716 state_ = SSL_CONNECTING;
717 if (int err = BeginSSL()) {
718 AsyncSocketAdapter::OnCloseEvent(socket, err);
719 }
720}
721
722void
723OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) {
724 //LOG(LS_INFO) << "OpenSSLAdapter::OnReadEvent";
725
726 if (state_ == SSL_NONE) {
727 AsyncSocketAdapter::OnReadEvent(socket);
728 return;
729 }
730
731 if (state_ == SSL_CONNECTING) {
732 if (int err = ContinueSSL()) {
733 Error("ContinueSSL", err);
734 }
735 return;
736 }
737
738 if (state_ != SSL_CONNECTED)
739 return;
740
741 // Don't let ourselves go away during the callbacks
742 //PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
743 if (ssl_write_needs_read_) {
744 //LOG(LS_INFO) << " -- onStreamWriteable";
745 AsyncSocketAdapter::OnWriteEvent(socket);
746 }
747
748 //LOG(LS_INFO) << " -- onStreamReadable";
749 AsyncSocketAdapter::OnReadEvent(socket);
750}
751
752void
753OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) {
754 //LOG(LS_INFO) << "OpenSSLAdapter::OnWriteEvent";
755
756 if (state_ == SSL_NONE) {
757 AsyncSocketAdapter::OnWriteEvent(socket);
758 return;
759 }
760
761 if (state_ == SSL_CONNECTING) {
762 if (int err = ContinueSSL()) {
763 Error("ContinueSSL", err);
764 }
765 return;
766 }
767
768 if (state_ != SSL_CONNECTED)
769 return;
770
771 // Don't let ourselves go away during the callbacks
772 //PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
773
774 if (ssl_read_needs_write_) {
775 //LOG(LS_INFO) << " -- onStreamReadable";
776 AsyncSocketAdapter::OnReadEvent(socket);
777 }
778
deadbeefed3b9862017-06-02 10:33:16 -0700779 // If a previous SSL_write failed due to the underlying socket being blocked,
780 // this will attempt finishing the write operation.
781 if (!pending_data_.empty()) {
782 int error;
783 if (DoSslWrite(pending_data_.data(), pending_data_.size(), &error) ==
784 static_cast<int>(pending_data_.size())) {
785 pending_data_.Clear();
786 }
787 }
788
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000789 //LOG(LS_INFO) << " -- onStreamWriteable";
790 AsyncSocketAdapter::OnWriteEvent(socket);
791}
792
793void
794OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
795 LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")";
796 AsyncSocketAdapter::OnCloseEvent(socket, err);
797}
798
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000799bool OpenSSLAdapter::VerifyServerName(SSL* ssl, const char* host,
800 bool ignore_bad_cert) {
801 if (!host)
802 return false;
803
804 // Checking the return from SSL_get_peer_certificate here is not strictly
805 // necessary. With our setup, it is not possible for it to return
deadbeef37f5ecf2017-02-27 14:06:41 -0800806 // null. However, it is good form to check the return.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000807 X509* certificate = SSL_get_peer_certificate(ssl);
808 if (!certificate)
809 return false;
810
811 // Logging certificates is extremely verbose. So it is disabled by default.
812#ifdef LOG_CERTIFICATES
813 {
814 LOG(LS_INFO) << "Certificate from server:";
815 BIO* mem = BIO_new(BIO_s_mem());
816 X509_print_ex(mem, certificate, XN_FLAG_SEP_CPLUS_SPC, X509_FLAG_NO_HEADER);
817 BIO_write(mem, "\0", 1);
818 char* buffer;
819 BIO_get_mem_data(mem, &buffer);
820 LOG(LS_INFO) << buffer;
821 BIO_free(mem);
822
823 char* cipher_description =
deadbeef37f5ecf2017-02-27 14:06:41 -0800824 SSL_CIPHER_description(SSL_get_current_cipher(ssl), nullptr, 128);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000825 LOG(LS_INFO) << "Cipher: " << cipher_description;
826 OPENSSL_free(cipher_description);
827 }
828#endif
829
830 bool ok = false;
davidben4ef903d2017-02-17 13:04:43 -0800831 GENERAL_NAMES* names = reinterpret_cast<GENERAL_NAMES*>(
832 X509_get_ext_d2i(certificate, NID_subject_alt_name, nullptr, nullptr));
833 if (names) {
834 for (size_t i = 0; i < sk_GENERAL_NAME_num(names); i++) {
835 const GENERAL_NAME* name = sk_GENERAL_NAME_value(names, i);
836 if (name->type != GEN_DNS)
837 continue;
838 std::string value(
839 reinterpret_cast<const char*>(ASN1_STRING_data(name->d.dNSName)),
840 ASN1_STRING_length(name->d.dNSName));
841 // string_match takes NUL-terminated strings, so check for embedded NULs.
842 if (value.find('\0') != std::string::npos)
843 continue;
844 if (string_match(host, value.c_str())) {
845 ok = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000846 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000847 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000848 }
davidben4ef903d2017-02-17 13:04:43 -0800849 GENERAL_NAMES_free(names);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000850 }
851
852 char data[256];
henrike@webrtc.orgd5a05062014-06-30 20:38:56 +0000853 X509_NAME* subject;
deadbeef37f5ecf2017-02-27 14:06:41 -0800854 if (!ok && ((subject = X509_get_subject_name(certificate)) != nullptr) &&
855 (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) >
856 0)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000857 data[sizeof(data)-1] = 0;
858 if (_stricmp(data, host) == 0)
859 ok = true;
860 }
861
862 X509_free(certificate);
863
864 // This should only ever be turned on for debugging and development.
865 if (!ok && ignore_bad_cert) {
866 LOG(LS_WARNING) << "TLS certificate check FAILED. "
867 << "Allowing connection anyway.";
868 ok = true;
869 }
870
871 return ok;
872}
873
874bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const char* host) {
875 bool ok = VerifyServerName(ssl, host, ignore_bad_cert());
876
877 if (ok) {
878 ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
879 custom_verification_succeeded_);
880 }
881
882 if (!ok && ignore_bad_cert()) {
883 LOG(LS_INFO) << "Other TLS post connection checks failed.";
884 ok = true;
885 }
886
887 return ok;
888}
889
tfarinaa41ab932015-10-30 16:08:48 -0700890#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000891
892// We only use this for tracing and so it is only needed in debug mode
893
894void
895OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) {
896 const char* str = "undefined";
897 int w = where & ~SSL_ST_MASK;
898 if (w & SSL_ST_CONNECT) {
899 str = "SSL_connect";
900 } else if (w & SSL_ST_ACCEPT) {
901 str = "SSL_accept";
902 }
903 if (where & SSL_CB_LOOP) {
904 LOG(LS_INFO) << str << ":" << SSL_state_string_long(s);
905 } else if (where & SSL_CB_ALERT) {
906 str = (where & SSL_CB_READ) ? "read" : "write";
907 LOG(LS_INFO) << "SSL3 alert " << str
908 << ":" << SSL_alert_type_string_long(ret)
909 << ":" << SSL_alert_desc_string_long(ret);
910 } else if (where & SSL_CB_EXIT) {
911 if (ret == 0) {
912 LOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s);
913 } else if (ret < 0) {
914 LOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s);
915 }
916 }
917}
918
tfarinaa41ab932015-10-30 16:08:48 -0700919#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000920
921int
922OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
tfarinaa41ab932015-10-30 16:08:48 -0700923#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000924 if (!ok) {
925 char data[256];
926 X509* cert = X509_STORE_CTX_get_current_cert(store);
927 int depth = X509_STORE_CTX_get_error_depth(store);
928 int err = X509_STORE_CTX_get_error(store);
929
930 LOG(LS_INFO) << "Error with certificate at depth: " << depth;
931 X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
932 LOG(LS_INFO) << " issuer = " << data;
933 X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
934 LOG(LS_INFO) << " subject = " << data;
935 LOG(LS_INFO) << " err = " << err
936 << ":" << X509_verify_cert_error_string(err);
937 }
938#endif
939
940 // Get our stream pointer from the store
941 SSL* ssl = reinterpret_cast<SSL*>(
942 X509_STORE_CTX_get_ex_data(store,
943 SSL_get_ex_data_X509_STORE_CTX_idx()));
944
945 OpenSSLAdapter* stream =
946 reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
947
948 if (!ok && custom_verify_callback_) {
949 void* cert =
950 reinterpret_cast<void*>(X509_STORE_CTX_get_current_cert(store));
951 if (custom_verify_callback_(cert)) {
952 stream->custom_verification_succeeded_ = true;
953 LOG(LS_INFO) << "validated certificate using custom callback";
954 ok = true;
955 }
956 }
957
958 // Should only be used for debugging and development.
959 if (!ok && stream->ignore_bad_cert()) {
960 LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
961 ok = 1;
962 }
963
964 return ok;
965}
966
967bool OpenSSLAdapter::ConfigureTrustedRootCertificates(SSL_CTX* ctx) {
968 // Add the root cert that we care about to the SSL context
969 int count_of_added_certs = 0;
tfarina5237aaf2015-11-10 23:44:30 -0800970 for (size_t i = 0; i < arraysize(kSSLCertCertificateList); i++) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000971 const unsigned char* cert_buffer = kSSLCertCertificateList[i];
972 size_t cert_buffer_len = kSSLCertCertificateSizeList[i];
deadbeef37f5ecf2017-02-27 14:06:41 -0800973 X509* cert =
974 d2i_X509(nullptr, &cert_buffer, checked_cast<long>(cert_buffer_len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000975 if (cert) {
976 int return_value = X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx), cert);
977 if (return_value == 0) {
978 LOG(LS_WARNING) << "Unable to add certificate.";
979 } else {
980 count_of_added_certs++;
981 }
982 X509_free(cert);
983 }
984 }
985 return count_of_added_certs > 0;
986}
987
988SSL_CTX*
989OpenSSLAdapter::SetupSSLContext() {
Emad Omarac6de0c92017-06-21 16:40:56 -0700990 // Use (D)TLS 1.2.
991 // Note: BoringSSL supports a range of versions by setting max/min version
992 // (Default V1.0 to V1.2). However (D)TLSv1_2_client_method functions used
993 // below in OpenSSL only support V1.2.
994 SSL_CTX* ctx = nullptr;
995#ifdef OPENSSL_IS_BORINGSSL
996 ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ? DTLS_method() : TLS_method());
997#else
998 ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ? DTLSv1_2_client_method()
999 : TLSv1_2_client_method());
1000#endif // OPENSSL_IS_BORINGSSL
deadbeef37f5ecf2017-02-27 14:06:41 -08001001 if (ctx == nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001002 unsigned long error = ERR_get_error(); // NOLINT: type used by OpenSSL.
1003 LOG(LS_WARNING) << "SSL_CTX creation failed: "
1004 << '"' << ERR_reason_error_string(error) << "\" "
1005 << "(error=" << error << ')';
deadbeef37f5ecf2017-02-27 14:06:41 -08001006 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001007 }
1008 if (!ConfigureTrustedRootCertificates(ctx)) {
1009 SSL_CTX_free(ctx);
deadbeef37f5ecf2017-02-27 14:06:41 -08001010 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001011 }
1012
tfarinaa41ab932015-10-30 16:08:48 -07001013#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001014 SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
1015#endif
1016
1017 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback);
1018 SSL_CTX_set_verify_depth(ctx, 4);
Emad Omarac6de0c92017-06-21 16:40:56 -07001019 // Use defaults, but disable HMAC-SHA256 and HMAC-SHA384 ciphers
1020 // (note that SHA256 and SHA384 only select legacy CBC ciphers).
1021 // Additionally disable HMAC-SHA1 ciphers in ECDSA. These are the remaining
1022 // CBC-mode ECDSA ciphers.
1023 SSL_CTX_set_cipher_list(
1024 ctx, "ALL:!SHA256:!SHA384:!aPSK:!ECDSA+SHA1:!ADH:!LOW:!EXP:!MD5");
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001025
pthatcher@webrtc.orga9b1ec02014-12-29 23:00:14 +00001026 if (ssl_mode_ == SSL_MODE_DTLS) {
1027 SSL_CTX_set_read_ahead(ctx, 1);
1028 }
1029
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001030 return ctx;
1031}
1032
1033} // namespace rtc