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