henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 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 | #if HAVE_OPENSSL_SSL_H |
| 12 | |
| 13 | #include "webrtc/base/openssladapter.h" |
| 14 | |
| 15 | #if defined(WEBRTC_POSIX) |
| 16 | #include <unistd.h> |
| 17 | #endif |
| 18 | |
| 19 | // Must be included first before openssl headers. |
| 20 | #include "webrtc/base/win32.h" // NOLINT |
| 21 | |
| 22 | #include <openssl/bio.h> |
| 23 | #include <openssl/crypto.h> |
| 24 | #include <openssl/err.h> |
| 25 | #include <openssl/opensslv.h> |
| 26 | #include <openssl/rand.h> |
| 27 | #include <openssl/x509v3.h> |
| 28 | |
| 29 | #if HAVE_CONFIG_H |
| 30 | #include "config.h" |
| 31 | #endif // HAVE_CONFIG_H |
| 32 | |
| 33 | #include "webrtc/base/common.h" |
| 34 | #include "webrtc/base/logging.h" |
| 35 | #include "webrtc/base/openssl.h" |
| 36 | #include "webrtc/base/sslroots.h" |
| 37 | #include "webrtc/base/stringutils.h" |
| 38 | |
| 39 | // TODO: Use a nicer abstraction for mutex. |
| 40 | |
| 41 | #if defined(WEBRTC_WIN) |
| 42 | #define MUTEX_TYPE HANDLE |
| 43 | #define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL) |
| 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() |
| 48 | #elif defined(WEBRTC_POSIX) |
| 49 | #define MUTEX_TYPE pthread_mutex_t |
| 50 | #define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL) |
| 51 | #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 | |
| 59 | struct CRYPTO_dynlock_value { |
| 60 | MUTEX_TYPE mutex; |
| 61 | }; |
| 62 | |
| 63 | ////////////////////////////////////////////////////////////////////// |
| 64 | // SocketBIO |
| 65 | ////////////////////////////////////////////////////////////////////// |
| 66 | |
| 67 | static int socket_write(BIO* h, const char* buf, int num); |
| 68 | static int socket_read(BIO* h, char* buf, int size); |
| 69 | static int socket_puts(BIO* h, const char* str); |
| 70 | static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2); |
| 71 | static int socket_new(BIO* h); |
| 72 | static int socket_free(BIO* data); |
| 73 | |
| 74 | static BIO_METHOD methods_socket = { |
| 75 | BIO_TYPE_BIO, |
| 76 | "socket", |
| 77 | socket_write, |
| 78 | socket_read, |
| 79 | socket_puts, |
| 80 | 0, |
| 81 | socket_ctrl, |
| 82 | socket_new, |
| 83 | socket_free, |
| 84 | NULL, |
| 85 | }; |
| 86 | |
henrike@webrtc.org | c50bf7c | 2014-05-14 18:24:13 +0000 | [diff] [blame] | 87 | static BIO_METHOD* BIO_s_socket2() { return(&methods_socket); } |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 88 | |
henrike@webrtc.org | c50bf7c | 2014-05-14 18:24:13 +0000 | [diff] [blame] | 89 | static BIO* BIO_new_socket(rtc::AsyncSocket* socket) { |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 90 | BIO* ret = BIO_new(BIO_s_socket2()); |
| 91 | if (ret == NULL) { |
| 92 | return NULL; |
| 93 | } |
| 94 | ret->ptr = socket; |
| 95 | return ret; |
| 96 | } |
| 97 | |
| 98 | static int socket_new(BIO* b) { |
| 99 | b->shutdown = 0; |
| 100 | b->init = 1; |
| 101 | b->num = 0; // 1 means socket closed |
| 102 | b->ptr = 0; |
| 103 | return 1; |
| 104 | } |
| 105 | |
| 106 | static int socket_free(BIO* b) { |
| 107 | if (b == NULL) |
| 108 | return 0; |
| 109 | return 1; |
| 110 | } |
| 111 | |
| 112 | static int socket_read(BIO* b, char* out, int outl) { |
| 113 | if (!out) |
| 114 | return -1; |
| 115 | rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(b->ptr); |
| 116 | BIO_clear_retry_flags(b); |
| 117 | int result = socket->Recv(out, outl); |
| 118 | if (result > 0) { |
| 119 | return result; |
| 120 | } else if (result == 0) { |
| 121 | b->num = 1; |
| 122 | } else if (socket->IsBlocking()) { |
| 123 | BIO_set_retry_read(b); |
| 124 | } |
| 125 | return -1; |
| 126 | } |
| 127 | |
| 128 | static int socket_write(BIO* b, const char* in, int inl) { |
| 129 | if (!in) |
| 130 | return -1; |
| 131 | rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(b->ptr); |
| 132 | BIO_clear_retry_flags(b); |
| 133 | int result = socket->Send(in, inl); |
| 134 | if (result > 0) { |
| 135 | return result; |
| 136 | } else if (socket->IsBlocking()) { |
| 137 | BIO_set_retry_write(b); |
| 138 | } |
| 139 | return -1; |
| 140 | } |
| 141 | |
| 142 | static int socket_puts(BIO* b, const char* str) { |
| 143 | return socket_write(b, str, strlen(str)); |
| 144 | } |
| 145 | |
| 146 | static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) { |
henrike@webrtc.org | 14abcc7 | 2014-05-16 16:54:44 +0000 | [diff] [blame] | 147 | RTC_UNUSED(num); |
| 148 | RTC_UNUSED(ptr); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 149 | |
| 150 | switch (cmd) { |
| 151 | case BIO_CTRL_RESET: |
| 152 | return 0; |
| 153 | case BIO_CTRL_EOF: |
| 154 | return b->num; |
| 155 | case BIO_CTRL_WPENDING: |
| 156 | case BIO_CTRL_PENDING: |
| 157 | return 0; |
| 158 | case BIO_CTRL_FLUSH: |
| 159 | return 1; |
| 160 | default: |
| 161 | return 0; |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | ///////////////////////////////////////////////////////////////////////////// |
| 166 | // OpenSSLAdapter |
| 167 | ///////////////////////////////////////////////////////////////////////////// |
| 168 | |
| 169 | namespace rtc { |
| 170 | |
| 171 | // This array will store all of the mutexes available to OpenSSL. |
| 172 | static MUTEX_TYPE* mutex_buf = NULL; |
| 173 | |
| 174 | static void locking_function(int mode, int n, const char * file, int line) { |
| 175 | if (mode & CRYPTO_LOCK) { |
| 176 | MUTEX_LOCK(mutex_buf[n]); |
| 177 | } else { |
| 178 | MUTEX_UNLOCK(mutex_buf[n]); |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | static unsigned long id_function() { // NOLINT |
| 183 | // Use old-style C cast because THREAD_ID's type varies with the platform, |
| 184 | // in some cases requiring static_cast, and in others requiring |
| 185 | // reinterpret_cast. |
| 186 | return (unsigned long)THREAD_ID; // NOLINT |
| 187 | } |
| 188 | |
| 189 | static CRYPTO_dynlock_value* dyn_create_function(const char* file, int line) { |
| 190 | CRYPTO_dynlock_value* value = new CRYPTO_dynlock_value; |
| 191 | if (!value) |
| 192 | return NULL; |
| 193 | MUTEX_SETUP(value->mutex); |
| 194 | return value; |
| 195 | } |
| 196 | |
| 197 | static void dyn_lock_function(int mode, CRYPTO_dynlock_value* l, |
| 198 | const char* file, int line) { |
| 199 | if (mode & CRYPTO_LOCK) { |
| 200 | MUTEX_LOCK(l->mutex); |
| 201 | } else { |
| 202 | MUTEX_UNLOCK(l->mutex); |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | static void dyn_destroy_function(CRYPTO_dynlock_value* l, |
| 207 | const char* file, int line) { |
| 208 | MUTEX_CLEANUP(l->mutex); |
| 209 | delete l; |
| 210 | } |
| 211 | |
| 212 | VerificationCallback OpenSSLAdapter::custom_verify_callback_ = NULL; |
| 213 | |
| 214 | bool OpenSSLAdapter::InitializeSSL(VerificationCallback callback) { |
| 215 | if (!InitializeSSLThread() || !SSL_library_init()) |
| 216 | return false; |
| 217 | #if !defined(ADDRESS_SANITIZER) || !defined(WEBRTC_MAC) || defined(WEBRTC_IOS) |
| 218 | // Loading the error strings crashes mac_asan. Omit this debugging aid there. |
| 219 | SSL_load_error_strings(); |
| 220 | #endif |
| 221 | ERR_load_BIO_strings(); |
| 222 | OpenSSL_add_all_algorithms(); |
| 223 | RAND_poll(); |
| 224 | custom_verify_callback_ = callback; |
| 225 | return true; |
| 226 | } |
| 227 | |
| 228 | bool OpenSSLAdapter::InitializeSSLThread() { |
| 229 | mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()]; |
| 230 | if (!mutex_buf) |
| 231 | return false; |
| 232 | for (int i = 0; i < CRYPTO_num_locks(); ++i) |
| 233 | MUTEX_SETUP(mutex_buf[i]); |
| 234 | |
| 235 | // we need to cast our id_function to return an unsigned long -- pthread_t is |
| 236 | // a pointer |
| 237 | CRYPTO_set_id_callback(id_function); |
| 238 | CRYPTO_set_locking_callback(locking_function); |
| 239 | CRYPTO_set_dynlock_create_callback(dyn_create_function); |
| 240 | CRYPTO_set_dynlock_lock_callback(dyn_lock_function); |
| 241 | CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function); |
| 242 | return true; |
| 243 | } |
| 244 | |
| 245 | bool OpenSSLAdapter::CleanupSSL() { |
| 246 | if (!mutex_buf) |
| 247 | return false; |
| 248 | CRYPTO_set_id_callback(NULL); |
| 249 | CRYPTO_set_locking_callback(NULL); |
| 250 | CRYPTO_set_dynlock_create_callback(NULL); |
| 251 | CRYPTO_set_dynlock_lock_callback(NULL); |
| 252 | CRYPTO_set_dynlock_destroy_callback(NULL); |
| 253 | for (int i = 0; i < CRYPTO_num_locks(); ++i) |
| 254 | MUTEX_CLEANUP(mutex_buf[i]); |
| 255 | delete [] mutex_buf; |
| 256 | mutex_buf = NULL; |
| 257 | return true; |
| 258 | } |
| 259 | |
| 260 | OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket) |
| 261 | : SSLAdapter(socket), |
| 262 | state_(SSL_NONE), |
| 263 | ssl_read_needs_write_(false), |
| 264 | ssl_write_needs_read_(false), |
| 265 | restartable_(false), |
| 266 | ssl_(NULL), ssl_ctx_(NULL), |
| 267 | custom_verification_succeeded_(false) { |
| 268 | } |
| 269 | |
| 270 | OpenSSLAdapter::~OpenSSLAdapter() { |
| 271 | Cleanup(); |
| 272 | } |
| 273 | |
| 274 | int |
| 275 | OpenSSLAdapter::StartSSL(const char* hostname, bool restartable) { |
| 276 | if (state_ != SSL_NONE) |
| 277 | return -1; |
| 278 | |
| 279 | ssl_host_name_ = hostname; |
| 280 | restartable_ = restartable; |
| 281 | |
| 282 | if (socket_->GetState() != Socket::CS_CONNECTED) { |
| 283 | state_ = SSL_WAIT; |
| 284 | return 0; |
| 285 | } |
| 286 | |
| 287 | state_ = SSL_CONNECTING; |
| 288 | if (int err = BeginSSL()) { |
| 289 | Error("BeginSSL", err, false); |
| 290 | return err; |
| 291 | } |
| 292 | |
| 293 | return 0; |
| 294 | } |
| 295 | |
| 296 | int |
| 297 | OpenSSLAdapter::BeginSSL() { |
| 298 | LOG(LS_INFO) << "BeginSSL: " << ssl_host_name_; |
| 299 | ASSERT(state_ == SSL_CONNECTING); |
| 300 | |
| 301 | int err = 0; |
| 302 | BIO* bio = NULL; |
| 303 | |
| 304 | // First set up the context |
| 305 | if (!ssl_ctx_) |
| 306 | ssl_ctx_ = SetupSSLContext(); |
| 307 | |
| 308 | if (!ssl_ctx_) { |
| 309 | err = -1; |
| 310 | goto ssl_error; |
| 311 | } |
| 312 | |
| 313 | bio = BIO_new_socket(static_cast<AsyncSocketAdapter*>(socket_)); |
| 314 | if (!bio) { |
| 315 | err = -1; |
| 316 | goto ssl_error; |
| 317 | } |
| 318 | |
| 319 | ssl_ = SSL_new(ssl_ctx_); |
| 320 | if (!ssl_) { |
| 321 | err = -1; |
| 322 | goto ssl_error; |
| 323 | } |
| 324 | |
| 325 | SSL_set_app_data(ssl_, this); |
| 326 | |
| 327 | SSL_set_bio(ssl_, bio, bio); |
| 328 | SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE | |
| 329 | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); |
| 330 | |
| 331 | // the SSL object owns the bio now |
| 332 | bio = NULL; |
| 333 | |
| 334 | // Do the connect |
| 335 | err = ContinueSSL(); |
| 336 | if (err != 0) |
| 337 | goto ssl_error; |
| 338 | |
| 339 | return err; |
| 340 | |
| 341 | ssl_error: |
| 342 | Cleanup(); |
| 343 | if (bio) |
| 344 | BIO_free(bio); |
| 345 | |
| 346 | return err; |
| 347 | } |
| 348 | |
| 349 | int |
| 350 | OpenSSLAdapter::ContinueSSL() { |
| 351 | ASSERT(state_ == SSL_CONNECTING); |
| 352 | |
| 353 | int code = SSL_connect(ssl_); |
| 354 | switch (SSL_get_error(ssl_, code)) { |
| 355 | case SSL_ERROR_NONE: |
| 356 | if (!SSLPostConnectionCheck(ssl_, ssl_host_name_.c_str())) { |
| 357 | LOG(LS_ERROR) << "TLS post connection check failed"; |
| 358 | // make sure we close the socket |
| 359 | Cleanup(); |
| 360 | // The connect failed so return -1 to shut down the socket |
| 361 | return -1; |
| 362 | } |
| 363 | |
| 364 | state_ = SSL_CONNECTED; |
| 365 | AsyncSocketAdapter::OnConnectEvent(this); |
| 366 | #if 0 // TODO: worry about this |
| 367 | // Don't let ourselves go away during the callbacks |
| 368 | PRefPtr<OpenSSLAdapter> lock(this); |
| 369 | LOG(LS_INFO) << " -- onStreamReadable"; |
| 370 | AsyncSocketAdapter::OnReadEvent(this); |
| 371 | LOG(LS_INFO) << " -- onStreamWriteable"; |
| 372 | AsyncSocketAdapter::OnWriteEvent(this); |
| 373 | #endif |
| 374 | break; |
| 375 | |
| 376 | case SSL_ERROR_WANT_READ: |
| 377 | case SSL_ERROR_WANT_WRITE: |
| 378 | break; |
| 379 | |
| 380 | case SSL_ERROR_ZERO_RETURN: |
| 381 | default: |
| 382 | LOG(LS_WARNING) << "ContinueSSL -- error " << code; |
| 383 | return (code != 0) ? code : -1; |
| 384 | } |
| 385 | |
| 386 | return 0; |
| 387 | } |
| 388 | |
| 389 | void |
| 390 | OpenSSLAdapter::Error(const char* context, int err, bool signal) { |
| 391 | LOG(LS_WARNING) << "OpenSSLAdapter::Error(" |
| 392 | << context << ", " << err << ")"; |
| 393 | state_ = SSL_ERROR; |
| 394 | SetError(err); |
| 395 | if (signal) |
| 396 | AsyncSocketAdapter::OnCloseEvent(this, err); |
| 397 | } |
| 398 | |
| 399 | void |
| 400 | OpenSSLAdapter::Cleanup() { |
| 401 | LOG(LS_INFO) << "Cleanup"; |
| 402 | |
| 403 | state_ = SSL_NONE; |
| 404 | ssl_read_needs_write_ = false; |
| 405 | ssl_write_needs_read_ = false; |
| 406 | custom_verification_succeeded_ = false; |
| 407 | |
| 408 | if (ssl_) { |
| 409 | SSL_free(ssl_); |
| 410 | ssl_ = NULL; |
| 411 | } |
| 412 | |
| 413 | if (ssl_ctx_) { |
| 414 | SSL_CTX_free(ssl_ctx_); |
| 415 | ssl_ctx_ = NULL; |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // |
| 420 | // AsyncSocket Implementation |
| 421 | // |
| 422 | |
| 423 | int |
| 424 | OpenSSLAdapter::Send(const void* pv, size_t cb) { |
| 425 | //LOG(LS_INFO) << "OpenSSLAdapter::Send(" << cb << ")"; |
| 426 | |
| 427 | switch (state_) { |
| 428 | case SSL_NONE: |
| 429 | return AsyncSocketAdapter::Send(pv, cb); |
| 430 | |
| 431 | case SSL_WAIT: |
| 432 | case SSL_CONNECTING: |
| 433 | SetError(EWOULDBLOCK); |
| 434 | return SOCKET_ERROR; |
| 435 | |
| 436 | case SSL_CONNECTED: |
| 437 | break; |
| 438 | |
| 439 | case SSL_ERROR: |
| 440 | default: |
| 441 | return SOCKET_ERROR; |
| 442 | } |
| 443 | |
| 444 | // OpenSSL will return an error if we try to write zero bytes |
| 445 | if (cb == 0) |
| 446 | return 0; |
| 447 | |
| 448 | ssl_write_needs_read_ = false; |
| 449 | |
| 450 | int code = SSL_write(ssl_, pv, cb); |
| 451 | switch (SSL_get_error(ssl_, code)) { |
| 452 | case SSL_ERROR_NONE: |
| 453 | //LOG(LS_INFO) << " -- success"; |
| 454 | return code; |
| 455 | case SSL_ERROR_WANT_READ: |
| 456 | //LOG(LS_INFO) << " -- error want read"; |
| 457 | ssl_write_needs_read_ = true; |
| 458 | SetError(EWOULDBLOCK); |
| 459 | break; |
| 460 | case SSL_ERROR_WANT_WRITE: |
| 461 | //LOG(LS_INFO) << " -- error want write"; |
| 462 | SetError(EWOULDBLOCK); |
| 463 | break; |
| 464 | case SSL_ERROR_ZERO_RETURN: |
| 465 | //LOG(LS_INFO) << " -- remote side closed"; |
| 466 | SetError(EWOULDBLOCK); |
| 467 | // do we need to signal closure? |
| 468 | break; |
| 469 | default: |
| 470 | //LOG(LS_INFO) << " -- error " << code; |
| 471 | Error("SSL_write", (code ? code : -1), false); |
| 472 | break; |
| 473 | } |
| 474 | |
| 475 | return SOCKET_ERROR; |
| 476 | } |
| 477 | |
| 478 | int |
| 479 | OpenSSLAdapter::Recv(void* pv, size_t cb) { |
| 480 | //LOG(LS_INFO) << "OpenSSLAdapter::Recv(" << cb << ")"; |
| 481 | switch (state_) { |
| 482 | |
| 483 | case SSL_NONE: |
| 484 | return AsyncSocketAdapter::Recv(pv, cb); |
| 485 | |
| 486 | case SSL_WAIT: |
| 487 | case SSL_CONNECTING: |
| 488 | SetError(EWOULDBLOCK); |
| 489 | return SOCKET_ERROR; |
| 490 | |
| 491 | case SSL_CONNECTED: |
| 492 | break; |
| 493 | |
| 494 | case SSL_ERROR: |
| 495 | default: |
| 496 | return SOCKET_ERROR; |
| 497 | } |
| 498 | |
| 499 | // Don't trust OpenSSL with zero byte reads |
| 500 | if (cb == 0) |
| 501 | return 0; |
| 502 | |
| 503 | ssl_read_needs_write_ = false; |
| 504 | |
| 505 | int code = SSL_read(ssl_, pv, cb); |
| 506 | switch (SSL_get_error(ssl_, code)) { |
| 507 | case SSL_ERROR_NONE: |
| 508 | //LOG(LS_INFO) << " -- success"; |
| 509 | return code; |
| 510 | case SSL_ERROR_WANT_READ: |
| 511 | //LOG(LS_INFO) << " -- error want read"; |
| 512 | SetError(EWOULDBLOCK); |
| 513 | break; |
| 514 | case SSL_ERROR_WANT_WRITE: |
| 515 | //LOG(LS_INFO) << " -- error want write"; |
| 516 | ssl_read_needs_write_ = true; |
| 517 | SetError(EWOULDBLOCK); |
| 518 | break; |
| 519 | case SSL_ERROR_ZERO_RETURN: |
| 520 | //LOG(LS_INFO) << " -- remote side closed"; |
| 521 | SetError(EWOULDBLOCK); |
| 522 | // do we need to signal closure? |
| 523 | break; |
| 524 | default: |
| 525 | //LOG(LS_INFO) << " -- error " << code; |
| 526 | Error("SSL_read", (code ? code : -1), false); |
| 527 | break; |
| 528 | } |
| 529 | |
| 530 | return SOCKET_ERROR; |
| 531 | } |
| 532 | |
| 533 | int |
| 534 | OpenSSLAdapter::Close() { |
| 535 | Cleanup(); |
| 536 | state_ = restartable_ ? SSL_WAIT : SSL_NONE; |
| 537 | return AsyncSocketAdapter::Close(); |
| 538 | } |
| 539 | |
| 540 | Socket::ConnState |
| 541 | OpenSSLAdapter::GetState() const { |
| 542 | //if (signal_close_) |
| 543 | // return CS_CONNECTED; |
| 544 | ConnState state = socket_->GetState(); |
| 545 | if ((state == CS_CONNECTED) |
| 546 | && ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING))) |
| 547 | state = CS_CONNECTING; |
| 548 | return state; |
| 549 | } |
| 550 | |
| 551 | void |
| 552 | OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) { |
| 553 | LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent"; |
| 554 | if (state_ != SSL_WAIT) { |
| 555 | ASSERT(state_ == SSL_NONE); |
| 556 | AsyncSocketAdapter::OnConnectEvent(socket); |
| 557 | return; |
| 558 | } |
| 559 | |
| 560 | state_ = SSL_CONNECTING; |
| 561 | if (int err = BeginSSL()) { |
| 562 | AsyncSocketAdapter::OnCloseEvent(socket, err); |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | void |
| 567 | OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) { |
| 568 | //LOG(LS_INFO) << "OpenSSLAdapter::OnReadEvent"; |
| 569 | |
| 570 | if (state_ == SSL_NONE) { |
| 571 | AsyncSocketAdapter::OnReadEvent(socket); |
| 572 | return; |
| 573 | } |
| 574 | |
| 575 | if (state_ == SSL_CONNECTING) { |
| 576 | if (int err = ContinueSSL()) { |
| 577 | Error("ContinueSSL", err); |
| 578 | } |
| 579 | return; |
| 580 | } |
| 581 | |
| 582 | if (state_ != SSL_CONNECTED) |
| 583 | return; |
| 584 | |
| 585 | // Don't let ourselves go away during the callbacks |
| 586 | //PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this |
| 587 | if (ssl_write_needs_read_) { |
| 588 | //LOG(LS_INFO) << " -- onStreamWriteable"; |
| 589 | AsyncSocketAdapter::OnWriteEvent(socket); |
| 590 | } |
| 591 | |
| 592 | //LOG(LS_INFO) << " -- onStreamReadable"; |
| 593 | AsyncSocketAdapter::OnReadEvent(socket); |
| 594 | } |
| 595 | |
| 596 | void |
| 597 | OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) { |
| 598 | //LOG(LS_INFO) << "OpenSSLAdapter::OnWriteEvent"; |
| 599 | |
| 600 | if (state_ == SSL_NONE) { |
| 601 | AsyncSocketAdapter::OnWriteEvent(socket); |
| 602 | return; |
| 603 | } |
| 604 | |
| 605 | if (state_ == SSL_CONNECTING) { |
| 606 | if (int err = ContinueSSL()) { |
| 607 | Error("ContinueSSL", err); |
| 608 | } |
| 609 | return; |
| 610 | } |
| 611 | |
| 612 | if (state_ != SSL_CONNECTED) |
| 613 | return; |
| 614 | |
| 615 | // Don't let ourselves go away during the callbacks |
| 616 | //PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this |
| 617 | |
| 618 | if (ssl_read_needs_write_) { |
| 619 | //LOG(LS_INFO) << " -- onStreamReadable"; |
| 620 | AsyncSocketAdapter::OnReadEvent(socket); |
| 621 | } |
| 622 | |
| 623 | //LOG(LS_INFO) << " -- onStreamWriteable"; |
| 624 | AsyncSocketAdapter::OnWriteEvent(socket); |
| 625 | } |
| 626 | |
| 627 | void |
| 628 | OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) { |
| 629 | LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")"; |
| 630 | AsyncSocketAdapter::OnCloseEvent(socket, err); |
| 631 | } |
| 632 | |
| 633 | // This code is taken from the "Network Security with OpenSSL" |
| 634 | // sample in chapter 5 |
| 635 | |
| 636 | bool OpenSSLAdapter::VerifyServerName(SSL* ssl, const char* host, |
| 637 | bool ignore_bad_cert) { |
| 638 | if (!host) |
| 639 | return false; |
| 640 | |
| 641 | // Checking the return from SSL_get_peer_certificate here is not strictly |
| 642 | // necessary. With our setup, it is not possible for it to return |
| 643 | // NULL. However, it is good form to check the return. |
| 644 | X509* certificate = SSL_get_peer_certificate(ssl); |
| 645 | if (!certificate) |
| 646 | return false; |
| 647 | |
| 648 | // Logging certificates is extremely verbose. So it is disabled by default. |
| 649 | #ifdef LOG_CERTIFICATES |
| 650 | { |
| 651 | LOG(LS_INFO) << "Certificate from server:"; |
| 652 | BIO* mem = BIO_new(BIO_s_mem()); |
| 653 | X509_print_ex(mem, certificate, XN_FLAG_SEP_CPLUS_SPC, X509_FLAG_NO_HEADER); |
| 654 | BIO_write(mem, "\0", 1); |
| 655 | char* buffer; |
| 656 | BIO_get_mem_data(mem, &buffer); |
| 657 | LOG(LS_INFO) << buffer; |
| 658 | BIO_free(mem); |
| 659 | |
| 660 | char* cipher_description = |
| 661 | SSL_CIPHER_description(SSL_get_current_cipher(ssl), NULL, 128); |
| 662 | LOG(LS_INFO) << "Cipher: " << cipher_description; |
| 663 | OPENSSL_free(cipher_description); |
| 664 | } |
| 665 | #endif |
| 666 | |
| 667 | bool ok = false; |
| 668 | int extension_count = X509_get_ext_count(certificate); |
| 669 | for (int i = 0; i < extension_count; ++i) { |
| 670 | X509_EXTENSION* extension = X509_get_ext(certificate, i); |
| 671 | int extension_nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension)); |
| 672 | |
| 673 | if (extension_nid == NID_subject_alt_name) { |
| 674 | const X509V3_EXT_METHOD* meth = X509V3_EXT_get(extension); |
| 675 | if (!meth) |
| 676 | break; |
| 677 | |
| 678 | void* ext_str = NULL; |
| 679 | |
| 680 | // We assign this to a local variable, instead of passing the address |
| 681 | // directly to ASN1_item_d2i. |
| 682 | // See http://readlist.com/lists/openssl.org/openssl-users/0/4761.html. |
| 683 | unsigned char* ext_value_data = extension->value->data; |
| 684 | |
| 685 | const unsigned char **ext_value_data_ptr = |
| 686 | (const_cast<const unsigned char **>(&ext_value_data)); |
| 687 | |
| 688 | if (meth->it) { |
| 689 | ext_str = ASN1_item_d2i(NULL, ext_value_data_ptr, |
| 690 | extension->value->length, |
| 691 | ASN1_ITEM_ptr(meth->it)); |
| 692 | } else { |
| 693 | ext_str = meth->d2i(NULL, ext_value_data_ptr, extension->value->length); |
| 694 | } |
| 695 | |
| 696 | STACK_OF(CONF_VALUE)* value = meth->i2v(meth, ext_str, NULL); |
| 697 | for (int j = 0; j < sk_CONF_VALUE_num(value); ++j) { |
| 698 | CONF_VALUE* nval = sk_CONF_VALUE_value(value, j); |
| 699 | // The value for nval can contain wildcards |
| 700 | if (!strcmp(nval->name, "DNS") && string_match(host, nval->value)) { |
| 701 | ok = true; |
| 702 | break; |
| 703 | } |
| 704 | } |
| 705 | sk_CONF_VALUE_pop_free(value, X509V3_conf_free); |
| 706 | value = NULL; |
| 707 | |
| 708 | if (meth->it) { |
| 709 | ASN1_item_free(reinterpret_cast<ASN1_VALUE*>(ext_str), |
| 710 | ASN1_ITEM_ptr(meth->it)); |
| 711 | } else { |
| 712 | meth->ext_free(ext_str); |
| 713 | } |
| 714 | ext_str = NULL; |
| 715 | } |
| 716 | if (ok) |
| 717 | break; |
| 718 | } |
| 719 | |
| 720 | char data[256]; |
| 721 | X509_name_st* subject; |
| 722 | if (!ok |
| 723 | && ((subject = X509_get_subject_name(certificate)) != NULL) |
| 724 | && (X509_NAME_get_text_by_NID(subject, NID_commonName, |
| 725 | data, sizeof(data)) > 0)) { |
| 726 | data[sizeof(data)-1] = 0; |
| 727 | if (_stricmp(data, host) == 0) |
| 728 | ok = true; |
| 729 | } |
| 730 | |
| 731 | X509_free(certificate); |
| 732 | |
| 733 | // This should only ever be turned on for debugging and development. |
| 734 | if (!ok && ignore_bad_cert) { |
| 735 | LOG(LS_WARNING) << "TLS certificate check FAILED. " |
| 736 | << "Allowing connection anyway."; |
| 737 | ok = true; |
| 738 | } |
| 739 | |
| 740 | return ok; |
| 741 | } |
| 742 | |
| 743 | bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const char* host) { |
| 744 | bool ok = VerifyServerName(ssl, host, ignore_bad_cert()); |
| 745 | |
| 746 | if (ok) { |
| 747 | ok = (SSL_get_verify_result(ssl) == X509_V_OK || |
| 748 | custom_verification_succeeded_); |
| 749 | } |
| 750 | |
| 751 | if (!ok && ignore_bad_cert()) { |
| 752 | LOG(LS_INFO) << "Other TLS post connection checks failed."; |
| 753 | ok = true; |
| 754 | } |
| 755 | |
| 756 | return ok; |
| 757 | } |
| 758 | |
| 759 | #if _DEBUG |
| 760 | |
| 761 | // We only use this for tracing and so it is only needed in debug mode |
| 762 | |
| 763 | void |
| 764 | OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) { |
| 765 | const char* str = "undefined"; |
| 766 | int w = where & ~SSL_ST_MASK; |
| 767 | if (w & SSL_ST_CONNECT) { |
| 768 | str = "SSL_connect"; |
| 769 | } else if (w & SSL_ST_ACCEPT) { |
| 770 | str = "SSL_accept"; |
| 771 | } |
| 772 | if (where & SSL_CB_LOOP) { |
| 773 | LOG(LS_INFO) << str << ":" << SSL_state_string_long(s); |
| 774 | } else if (where & SSL_CB_ALERT) { |
| 775 | str = (where & SSL_CB_READ) ? "read" : "write"; |
| 776 | LOG(LS_INFO) << "SSL3 alert " << str |
| 777 | << ":" << SSL_alert_type_string_long(ret) |
| 778 | << ":" << SSL_alert_desc_string_long(ret); |
| 779 | } else if (where & SSL_CB_EXIT) { |
| 780 | if (ret == 0) { |
| 781 | LOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s); |
| 782 | } else if (ret < 0) { |
| 783 | LOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s); |
| 784 | } |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | #endif // _DEBUG |
| 789 | |
| 790 | int |
| 791 | OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) { |
| 792 | #if _DEBUG |
| 793 | if (!ok) { |
| 794 | char data[256]; |
| 795 | X509* cert = X509_STORE_CTX_get_current_cert(store); |
| 796 | int depth = X509_STORE_CTX_get_error_depth(store); |
| 797 | int err = X509_STORE_CTX_get_error(store); |
| 798 | |
| 799 | LOG(LS_INFO) << "Error with certificate at depth: " << depth; |
| 800 | X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data)); |
| 801 | LOG(LS_INFO) << " issuer = " << data; |
| 802 | X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data)); |
| 803 | LOG(LS_INFO) << " subject = " << data; |
| 804 | LOG(LS_INFO) << " err = " << err |
| 805 | << ":" << X509_verify_cert_error_string(err); |
| 806 | } |
| 807 | #endif |
| 808 | |
| 809 | // Get our stream pointer from the store |
| 810 | SSL* ssl = reinterpret_cast<SSL*>( |
| 811 | X509_STORE_CTX_get_ex_data(store, |
| 812 | SSL_get_ex_data_X509_STORE_CTX_idx())); |
| 813 | |
| 814 | OpenSSLAdapter* stream = |
| 815 | reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl)); |
| 816 | |
| 817 | if (!ok && custom_verify_callback_) { |
| 818 | void* cert = |
| 819 | reinterpret_cast<void*>(X509_STORE_CTX_get_current_cert(store)); |
| 820 | if (custom_verify_callback_(cert)) { |
| 821 | stream->custom_verification_succeeded_ = true; |
| 822 | LOG(LS_INFO) << "validated certificate using custom callback"; |
| 823 | ok = true; |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | // Should only be used for debugging and development. |
| 828 | if (!ok && stream->ignore_bad_cert()) { |
| 829 | LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain"; |
| 830 | ok = 1; |
| 831 | } |
| 832 | |
| 833 | return ok; |
| 834 | } |
| 835 | |
| 836 | bool OpenSSLAdapter::ConfigureTrustedRootCertificates(SSL_CTX* ctx) { |
| 837 | // Add the root cert that we care about to the SSL context |
| 838 | int count_of_added_certs = 0; |
| 839 | for (int i = 0; i < ARRAY_SIZE(kSSLCertCertificateList); i++) { |
| 840 | const unsigned char* cert_buffer = kSSLCertCertificateList[i]; |
| 841 | size_t cert_buffer_len = kSSLCertCertificateSizeList[i]; |
| 842 | X509* cert = d2i_X509(NULL, &cert_buffer, cert_buffer_len); |
| 843 | if (cert) { |
| 844 | int return_value = X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx), cert); |
| 845 | if (return_value == 0) { |
| 846 | LOG(LS_WARNING) << "Unable to add certificate."; |
| 847 | } else { |
| 848 | count_of_added_certs++; |
| 849 | } |
| 850 | X509_free(cert); |
| 851 | } |
| 852 | } |
| 853 | return count_of_added_certs > 0; |
| 854 | } |
| 855 | |
| 856 | SSL_CTX* |
| 857 | OpenSSLAdapter::SetupSSLContext() { |
| 858 | SSL_CTX* ctx = SSL_CTX_new(TLSv1_client_method()); |
| 859 | if (ctx == NULL) { |
| 860 | unsigned long error = ERR_get_error(); // NOLINT: type used by OpenSSL. |
| 861 | LOG(LS_WARNING) << "SSL_CTX creation failed: " |
| 862 | << '"' << ERR_reason_error_string(error) << "\" " |
| 863 | << "(error=" << error << ')'; |
| 864 | return NULL; |
| 865 | } |
| 866 | if (!ConfigureTrustedRootCertificates(ctx)) { |
| 867 | SSL_CTX_free(ctx); |
| 868 | return NULL; |
| 869 | } |
| 870 | |
| 871 | #ifdef _DEBUG |
| 872 | SSL_CTX_set_info_callback(ctx, SSLInfoCallback); |
| 873 | #endif |
| 874 | |
| 875 | SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback); |
| 876 | SSL_CTX_set_verify_depth(ctx, 4); |
| 877 | SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); |
| 878 | |
| 879 | return ctx; |
| 880 | } |
| 881 | |
| 882 | } // namespace rtc |
| 883 | |
| 884 | #endif // HAVE_OPENSSL_SSL_H |