2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/io/async/AsyncSSLSocket.h>
19 #include <folly/io/async/EventBase.h>
21 #include <boost/noncopyable.hpp>
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
26 #include <openssl/err.h>
27 #include <openssl/asn1.h>
28 #include <openssl/ssl.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
34 #include <folly/Bits.h>
35 #include <folly/SocketAddress.h>
36 #include <folly/SpinLock.h>
37 #include <folly/io/IOBuf.h>
38 #include <folly/io/Cursor.h>
40 using folly::SocketAddress;
41 using folly::SSLContext;
43 using std::shared_ptr;
47 using folly::SpinLock;
48 using folly::SpinLockGuard;
49 using folly::io::Cursor;
50 using std::unique_ptr;
54 using folly::AsyncSocket;
55 using folly::AsyncSocketException;
56 using folly::AsyncSSLSocket;
57 using folly::Optional;
58 using folly::SSLContext;
60 // We have one single dummy SSL context so that we can implement attach
61 // and detach methods in a thread safe fashion without modifying opnessl.
62 static SSLContext *dummyCtx = nullptr;
63 static SpinLock dummyCtxLock;
65 // If given min write size is less than this, buffer will be allocated on
66 // stack, otherwise it is allocated on heap
67 const size_t MAX_STACK_BUF_SIZE = 2048;
69 // This converts "illegal" shutdowns into ZERO_RETURN
70 inline bool zero_return(int error, int rc) {
71 return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
74 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
75 public AsyncSSLSocket::HandshakeCB {
78 AsyncSSLSocket *sslSocket_;
79 AsyncSSLSocket::ConnectCallback *callback_;
84 ~AsyncSSLSocketConnector() override {}
87 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
88 AsyncSocket::ConnectCallback *callback,
90 sslSocket_(sslSocket),
93 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
94 std::chrono::steady_clock::now().time_since_epoch()).count()) {
97 void connectSuccess() noexcept override {
98 VLOG(7) << "client socket connected";
100 int64_t timeoutLeft = 0;
102 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
103 std::chrono::steady_clock::now().time_since_epoch()).count();
105 timeoutLeft = timeout_ - (curTime - startTime_);
106 if (timeoutLeft <= 0) {
107 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
108 "SSL connect timed out");
114 sslSocket_->sslConn(this, timeoutLeft);
117 void connectErr(const AsyncSocketException& ex) noexcept override {
118 LOG(ERROR) << "TCP connect failed: " << ex.what();
123 void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
124 VLOG(7) << "client handshake success";
126 callback_->connectSuccess();
131 void handshakeErr(AsyncSSLSocket* /* socket */,
132 const AsyncSocketException& ex) noexcept override {
133 LOG(ERROR) << "client handshakeErr: " << ex.what();
138 void fail(const AsyncSocketException &ex) {
139 // fail is a noop if called twice
141 AsyncSSLSocket::ConnectCallback *cb = callback_;
145 sslSocket_->closeNow();
146 // closeNow can call handshakeErr if it hasn't been called already.
147 // So this may have been deleted, no member variable access beyond this
149 // Note that closeNow may invoke writeError callbacks if the socket had
150 // write data pending connection completion.
155 // XXX: implement an equivalent to corking for platforms with TCP_NOPUSH?
156 #ifdef TCP_CORK // Linux-only
158 * Utility class that corks a TCP socket upon construction or uncorks
159 * the socket upon destruction
161 class CorkGuard : private boost::noncopyable {
163 CorkGuard(int fd, bool multipleWrites, bool haveMore, bool* corked):
164 fd_(fd), haveMore_(haveMore), corked_(corked) {
166 // socket is already corked; nothing to do
169 if (multipleWrites || haveMore) {
170 // We are performing multiple writes in this performWrite() call,
171 // and/or there are more calls to performWrite() that will be invoked
172 // later, so enable corking
174 setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
181 // more data to come; don't uncork yet
185 // socket isn't corked; nothing to do
190 setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
200 class CorkGuard : private boost::noncopyable {
202 CorkGuard(int, bool, bool, bool*) {}
206 void setup_SSL_CTX(SSL_CTX *ctx) {
207 #ifdef SSL_MODE_RELEASE_BUFFERS
208 SSL_CTX_set_mode(ctx,
209 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
210 SSL_MODE_ENABLE_PARTIAL_WRITE
211 | SSL_MODE_RELEASE_BUFFERS
214 SSL_CTX_set_mode(ctx,
215 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
216 SSL_MODE_ENABLE_PARTIAL_WRITE
219 // SSL_CTX_set_mode is a Macro
220 #ifdef SSL_MODE_WRITE_IOVEC
221 SSL_CTX_set_mode(ctx,
222 SSL_CTX_get_mode(ctx)
223 | SSL_MODE_WRITE_IOVEC);
228 BIO_METHOD eorAwareBioMethod;
230 void* initEorBioMethod(void) {
231 memcpy(&eorAwareBioMethod, BIO_s_socket(), sizeof(eorAwareBioMethod));
232 // override the bwrite method for MSG_EOR support
233 eorAwareBioMethod.bwrite = AsyncSSLSocket::eorAwareBioWrite;
235 // Note that the eorAwareBioMethod.type and eorAwareBioMethod.name are not
236 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
237 // then have specific handlings. The eorAwareBioWrite should be compatible
238 // with the one in openssl.
240 // Return something here to enable AsyncSSLSocket to call this method using
241 // a function-scoped static.
245 } // anonymous namespace
250 * Create a client AsyncSSLSocket
252 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
253 EventBase* evb, bool deferSecurityNegotiation) :
256 handshakeTimeout_(this, evb) {
258 if (deferSecurityNegotiation) {
259 sslState_ = STATE_UNENCRYPTED;
264 * Create a server/client AsyncSSLSocket
266 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
267 EventBase* evb, int fd, bool server,
268 bool deferSecurityNegotiation) :
269 AsyncSocket(evb, fd),
272 handshakeTimeout_(this, evb) {
275 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
276 AsyncSSLSocket::sslInfoCallback);
278 if (deferSecurityNegotiation) {
279 sslState_ = STATE_UNENCRYPTED;
283 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
285 * Create a client AsyncSSLSocket and allow tlsext_hostname
286 * to be sent in Client Hello.
288 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
290 const std::string& serverName,
291 bool deferSecurityNegotiation) :
292 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
293 tlsextHostname_ = serverName;
297 * Create a client AsyncSSLSocket from an already connected fd
298 * and allow tlsext_hostname to be sent in Client Hello.
300 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
301 EventBase* evb, int fd,
302 const std::string& serverName,
303 bool deferSecurityNegotiation) :
304 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
305 tlsextHostname_ = serverName;
309 AsyncSSLSocket::~AsyncSSLSocket() {
310 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
311 << ", evb=" << eventBase_ << ", fd=" << fd_
312 << ", state=" << int(state_) << ", sslState="
313 << sslState_ << ", events=" << eventFlags_ << ")";
316 void AsyncSSLSocket::init() {
317 // Do this here to ensure we initialize this once before any use of
318 // AsyncSSLSocket instances and not as part of library load.
319 static const auto eorAwareBioMethodInitializer = initEorBioMethod();
320 (void)eorAwareBioMethodInitializer;
322 setup_SSL_CTX(ctx_->getSSLCtx());
325 void AsyncSSLSocket::closeNow() {
326 // Close the SSL connection.
327 if (ssl_ != nullptr && fd_ != -1) {
328 int rc = SSL_shutdown(ssl_);
330 rc = SSL_shutdown(ssl_);
337 if (sslSession_ != nullptr) {
338 SSL_SESSION_free(sslSession_);
339 sslSession_ = nullptr;
342 sslState_ = STATE_CLOSED;
344 if (handshakeTimeout_.isScheduled()) {
345 handshakeTimeout_.cancelTimeout();
348 DestructorGuard dg(this);
351 AsyncSocketException(
352 AsyncSocketException::END_OF_FILE,
353 "SSL connection closed locally"));
355 if (ssl_ != nullptr) {
361 AsyncSocket::closeNow();
364 void AsyncSSLSocket::shutdownWrite() {
365 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
367 // (Performing a full shutdown here is more desirable than doing nothing at
368 // all. The purpose of shutdownWrite() is normally to notify the other end
369 // of the connection that no more data will be sent. If we do nothing, the
370 // other end will never know that no more data is coming, and this may result
371 // in protocol deadlock.)
375 void AsyncSSLSocket::shutdownWriteNow() {
379 bool AsyncSSLSocket::good() const {
380 return (AsyncSocket::good() &&
381 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
382 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
385 // The TAsyncTransport definition of 'good' states that the transport is
386 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
387 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
388 // is connected but we haven't initiated the call to SSL_connect.
389 bool AsyncSSLSocket::connecting() const {
391 (AsyncSocket::connecting() ||
392 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
393 sslState_ == STATE_CONNECTING))));
396 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
397 const unsigned char* protoName = nullptr;
398 unsigned protoLength;
399 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
400 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
405 bool AsyncSSLSocket::isEorTrackingEnabled() const {
406 if (ssl_ == nullptr) {
409 const BIO *wb = SSL_get_wbio(ssl_);
410 return wb && wb->method == &eorAwareBioMethod;
413 void AsyncSSLSocket::setEorTracking(bool track) {
414 BIO *wb = SSL_get_wbio(ssl_);
416 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
417 "setting EOR tracking without an initialized "
422 if (wb->method != &eorAwareBioMethod) {
423 // only do this if we didn't
424 wb->method = &eorAwareBioMethod;
425 BIO_set_app_data(wb, this);
427 minEorRawByteNo_ = 0;
429 } else if (wb->method == &eorAwareBioMethod) {
430 wb->method = BIO_s_socket();
431 BIO_set_app_data(wb, nullptr);
433 minEorRawByteNo_ = 0;
435 CHECK(wb->method == BIO_s_socket());
439 size_t AsyncSSLSocket::getRawBytesWritten() const {
441 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
445 return BIO_number_written(b);
448 size_t AsyncSSLSocket::getRawBytesReceived() const {
450 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
454 return BIO_number_read(b);
458 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
459 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
460 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
461 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
462 << "sslAccept/Connect() called in invalid "
463 << "state, handshake callback " << handshakeCallback_ << ", new callback "
465 assert(!handshakeTimeout_.isScheduled());
466 sslState_ = STATE_ERROR;
468 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
469 "sslAccept() called with socket in invalid state");
471 handshakeEndTime_ = std::chrono::steady_clock::now();
473 callback->handshakeErr(this, ex);
476 // Check the socket state not the ssl state here.
477 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
478 failHandshake(__func__, ex);
482 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
483 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
484 DestructorGuard dg(this);
485 assert(eventBase_->isInEventBaseThread());
486 verifyPeer_ = verifyPeer;
488 // Make sure we're in the uninitialized state
489 if (!server_ || (sslState_ != STATE_UNINIT &&
490 sslState_ != STATE_UNENCRYPTED) ||
491 handshakeCallback_ != nullptr) {
492 return invalidState(callback);
495 // Cache local and remote socket addresses to keep them available
496 // after socket file descriptor is closed.
497 if (cacheAddrOnFailure_ && -1 != getFd()) {
498 cacheLocalPeerAddr();
501 handshakeStartTime_ = std::chrono::steady_clock::now();
502 // Make end time at least >= start time.
503 handshakeEndTime_ = handshakeStartTime_;
505 sslState_ = STATE_ACCEPTING;
506 handshakeCallback_ = callback;
509 handshakeTimeout_.scheduleTimeout(timeout);
512 /* register for a read operation (waiting for CLIENT HELLO) */
513 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
516 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
517 void AsyncSSLSocket::attachSSLContext(
518 const std::shared_ptr<SSLContext>& ctx) {
520 // Check to ensure we are in client mode. Changing a server's ssl
521 // context doesn't make sense since clients of that server would likely
522 // become confused when the server's context changes.
526 DCHECK(ctx->getSSLCtx());
529 // In order to call attachSSLContext, detachSSLContext must have been
530 // previously called which sets the socket's context to the dummy
531 // context. Thus we must acquire this lock.
532 SpinLockGuard guard(dummyCtxLock);
533 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
536 void AsyncSSLSocket::detachSSLContext() {
539 // We aren't using the initial_ctx for now, and it can introduce race
540 // conditions in the destructor of the SSL object.
541 #ifndef OPENSSL_NO_TLSEXT
542 if (ssl_->initial_ctx) {
543 SSL_CTX_free(ssl_->initial_ctx);
544 ssl_->initial_ctx = nullptr;
547 SpinLockGuard guard(dummyCtxLock);
548 if (nullptr == dummyCtx) {
549 // We need to lazily initialize the dummy context so we don't
550 // accidentally override any programmatic settings to openssl
551 dummyCtx = new SSLContext;
553 // We must remove this socket's references to its context right now
554 // since this socket could get passed to any thread. If the context has
555 // had its locking disabled, just doing a set in attachSSLContext()
556 // would not be thread safe.
557 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
561 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
562 void AsyncSSLSocket::switchServerSSLContext(
563 const std::shared_ptr<SSLContext>& handshakeCtx) {
565 if (sslState_ != STATE_ACCEPTING) {
566 // We log it here and allow the switch.
567 // It should not affect our re-negotiation support (which
568 // is not supported now).
569 VLOG(6) << "fd=" << getFd()
570 << " renegotation detected when switching SSL_CTX";
573 setup_SSL_CTX(handshakeCtx->getSSLCtx());
574 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
575 AsyncSSLSocket::sslInfoCallback);
576 handshakeCtx_ = handshakeCtx;
577 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
580 bool AsyncSSLSocket::isServerNameMatch() const {
587 SSL_SESSION *ss = SSL_get_session(ssl_);
592 if(!ss->tlsext_hostname) {
595 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
598 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
599 tlsextHostname_ = std::move(serverName);
604 void AsyncSSLSocket::timeoutExpired() noexcept {
605 if (state_ == StateEnum::ESTABLISHED &&
606 (sslState_ == STATE_CACHE_LOOKUP ||
607 sslState_ == STATE_ASYNC_PENDING)) {
608 sslState_ = STATE_ERROR;
609 // We are expecting a callback in restartSSLAccept. The cache lookup
610 // and rsa-call necessarily have pointers to this ssl socket, so delay
611 // the cleanup until he calls us back.
613 assert(state_ == StateEnum::ESTABLISHED &&
614 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
615 DestructorGuard dg(this);
616 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
617 (sslState_ == STATE_CONNECTING) ?
618 "SSL connect timed out" : "SSL accept timed out");
619 failHandshake(__func__, ex);
623 int AsyncSSLSocket::getSSLExDataIndex() {
624 static auto index = SSL_get_ex_new_index(
625 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
629 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
630 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
631 getSSLExDataIndex()));
634 void AsyncSSLSocket::failHandshake(const char* /* fn */,
635 const AsyncSocketException& ex) {
637 if (handshakeTimeout_.isScheduled()) {
638 handshakeTimeout_.cancelTimeout();
640 invokeHandshakeErr(ex);
644 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
645 handshakeEndTime_ = std::chrono::steady_clock::now();
646 if (handshakeCallback_ != nullptr) {
647 HandshakeCB* callback = handshakeCallback_;
648 handshakeCallback_ = nullptr;
649 callback->handshakeErr(this, ex);
653 void AsyncSSLSocket::invokeHandshakeCB() {
654 handshakeEndTime_ = std::chrono::steady_clock::now();
655 if (handshakeTimeout_.isScheduled()) {
656 handshakeTimeout_.cancelTimeout();
658 if (handshakeCallback_) {
659 HandshakeCB* callback = handshakeCallback_;
660 handshakeCallback_ = nullptr;
661 callback->handshakeSuc(this);
665 void AsyncSSLSocket::cacheLocalPeerAddr() {
666 SocketAddress address;
668 getLocalAddress(&address);
669 getPeerAddress(&address);
670 } catch (const std::system_error& e) {
671 // The handle can be still valid while the connection is already closed.
672 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
678 void AsyncSSLSocket::connect(ConnectCallback* callback,
679 const folly::SocketAddress& address,
681 const OptionMap &options,
682 const folly::SocketAddress& bindAddr)
685 assert(state_ == StateEnum::UNINIT);
686 assert(sslState_ == STATE_UNINIT);
687 AsyncSSLSocketConnector *connector =
688 new AsyncSSLSocketConnector(this, callback, timeout);
689 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
692 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
693 // apply the settings specified in verifyPeer_
694 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
695 if(ctx_->needsPeerVerification()) {
696 SSL_set_verify(ssl, ctx_->getVerificationMode(),
697 AsyncSSLSocket::sslVerifyCallback);
700 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
701 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
702 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
703 AsyncSSLSocket::sslVerifyCallback);
708 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
709 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
710 DestructorGuard dg(this);
711 assert(eventBase_->isInEventBaseThread());
713 // Cache local and remote socket addresses to keep them available
714 // after socket file descriptor is closed.
715 if (cacheAddrOnFailure_ && -1 != getFd()) {
716 cacheLocalPeerAddr();
719 verifyPeer_ = verifyPeer;
721 // Make sure we're in the uninitialized state
722 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
723 STATE_UNENCRYPTED) ||
724 handshakeCallback_ != nullptr) {
725 return invalidState(callback);
728 handshakeStartTime_ = std::chrono::steady_clock::now();
729 // Make end time at least >= start time.
730 handshakeEndTime_ = handshakeStartTime_;
732 sslState_ = STATE_CONNECTING;
733 handshakeCallback_ = callback;
736 ssl_ = ctx_->createSSL();
737 } catch (std::exception &e) {
738 sslState_ = STATE_ERROR;
739 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
740 "error calling SSLContext::createSSL()");
741 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
742 << fd_ << "): " << e.what();
743 return failHandshake(__func__, ex);
746 applyVerificationOptions(ssl_);
748 SSL_set_fd(ssl_, fd_);
749 if (sslSession_ != nullptr) {
750 SSL_set_session(ssl_, sslSession_);
751 SSL_SESSION_free(sslSession_);
752 sslSession_ = nullptr;
754 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
755 if (tlsextHostname_.size()) {
756 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
760 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
763 handshakeTimeout_.scheduleTimeout(timeout);
769 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
770 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
771 return SSL_get1_session(ssl_);
777 const SSL* AsyncSSLSocket::getSSL() const {
781 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
782 sslSession_ = session;
783 if (!takeOwnership && session != nullptr) {
784 // Increment the reference count
785 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
789 void AsyncSSLSocket::getSelectedNextProtocol(
790 const unsigned char** protoName,
792 SSLContext::NextProtocolType* protoType) const {
793 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
794 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
795 "NPN not supported");
799 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
800 const unsigned char** protoName,
802 SSLContext::NextProtocolType* protoType) const {
803 *protoName = nullptr;
805 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
806 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
809 *protoType = SSLContext::NextProtocolType::ALPN;
814 #ifdef OPENSSL_NPN_NEGOTIATED
815 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
817 *protoType = SSLContext::NextProtocolType::NPN;
826 bool AsyncSSLSocket::getSSLSessionReused() const {
827 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
828 return SSL_session_reused(ssl_);
833 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
834 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
838 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
839 if (ssl == nullptr) {
842 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
843 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
849 const char *AsyncSSLSocket::getSSLServerName() const {
850 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
851 return getSSLServerNameFromSSL(ssl_);
853 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
854 "SNI not supported");
858 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
859 return getSSLServerNameFromSSL(ssl_);
862 int AsyncSSLSocket::getSSLVersion() const {
863 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
866 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
867 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
869 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
870 return OBJ_nid2ln(nid);
875 int AsyncSSLSocket::getSSLCertSize() const {
877 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
879 EVP_PKEY *key = X509_get_pubkey(cert);
880 certSize = EVP_PKEY_bits(key);
886 bool AsyncSSLSocket::willBlock(int ret,
888 unsigned long* errErrorOut) noexcept {
890 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
891 if (error == SSL_ERROR_WANT_READ) {
892 // Register for read event if not already.
893 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
895 } else if (error == SSL_ERROR_WANT_WRITE) {
896 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
897 << ", state=" << int(state_) << ", sslState="
898 << sslState_ << ", events=" << eventFlags_ << "): "
899 << "SSL_ERROR_WANT_WRITE";
900 // Register for write event if not already.
901 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
903 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
904 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
905 // We will block but we can't register our own socket. The callback that
906 // triggered this code will re-call handleAccept at the appropriate time.
908 // We can only get here if the linked libssl.so has support for this feature
909 // as well, otherwise SSL_get_error cannot return our error code.
910 sslState_ = STATE_CACHE_LOOKUP;
912 // Unregister for all events while blocked here
913 updateEventRegistration(EventHandler::NONE,
914 EventHandler::READ | EventHandler::WRITE);
916 // The timeout (if set) keeps running here
920 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
921 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
923 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
924 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
927 // Our custom openssl function has kicked off an async request to do
928 // rsa/ecdsa private key operation. When that call returns, a callback will
929 // be invoked that will re-call handleAccept.
930 sslState_ = STATE_ASYNC_PENDING;
932 // Unregister for all events while blocked here
933 updateEventRegistration(
935 EventHandler::READ | EventHandler::WRITE
938 // The timeout (if set) keeps running here
941 unsigned long lastError = *errErrorOut = ERR_get_error();
942 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
943 << "state=" << state_ << ", "
944 << "sslState=" << sslState_ << ", "
945 << "events=" << std::hex << eventFlags_ << "): "
946 << "SSL error: " << error << ", "
947 << "errno: " << errno << ", "
948 << "ret: " << ret << ", "
949 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
950 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
951 << "func: " << ERR_func_error_string(lastError) << ", "
952 << "reason: " << ERR_reason_error_string(lastError);
957 void AsyncSSLSocket::checkForImmediateRead() noexcept {
958 // openssl may have buffered data that it read from the socket already.
959 // In this case we have to process it immediately, rather than waiting for
960 // the socket to become readable again.
961 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
962 AsyncSocket::handleRead();
967 AsyncSSLSocket::restartSSLAccept()
969 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
970 << ", state=" << int(state_) << ", "
971 << "sslState=" << sslState_ << ", events=" << eventFlags_;
972 DestructorGuard dg(this);
974 sslState_ == STATE_CACHE_LOOKUP ||
975 sslState_ == STATE_ASYNC_PENDING ||
976 sslState_ == STATE_ERROR ||
977 sslState_ == STATE_CLOSED
979 if (sslState_ == STATE_CLOSED) {
980 // I sure hope whoever closed this socket didn't delete it already,
981 // but this is not strictly speaking an error
984 if (sslState_ == STATE_ERROR) {
985 // go straight to fail if timeout expired during lookup
986 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
987 "SSL accept timed out");
988 failHandshake(__func__, ex);
991 sslState_ = STATE_ACCEPTING;
992 this->handleAccept();
996 AsyncSSLSocket::handleAccept() noexcept {
997 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
998 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
999 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1001 assert(state_ == StateEnum::ESTABLISHED &&
1002 sslState_ == STATE_ACCEPTING);
1004 /* lazily create the SSL structure */
1006 ssl_ = ctx_->createSSL();
1007 } catch (std::exception &e) {
1008 sslState_ = STATE_ERROR;
1009 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1010 "error calling SSLContext::createSSL()");
1011 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1012 << ", fd=" << fd_ << "): " << e.what();
1013 return failHandshake(__func__, ex);
1015 SSL_set_fd(ssl_, fd_);
1016 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1018 applyVerificationOptions(ssl_);
1021 if (server_ && parseClientHello_) {
1022 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1023 SSL_set_msg_callback_arg(ssl_, this);
1026 int ret = SSL_accept(ssl_);
1029 unsigned long errError;
1030 int errnoCopy = errno;
1031 if (willBlock(ret, &sslError, &errError)) {
1034 sslState_ = STATE_ERROR;
1035 SSLException ex(sslError, errError, ret, errnoCopy);
1036 return failHandshake(__func__, ex);
1040 handshakeComplete_ = true;
1041 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1043 // Move into STATE_ESTABLISHED in the normal case that we are in
1045 sslState_ = STATE_ESTABLISHED;
1047 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1048 << " successfully accepted; state=" << int(state_)
1049 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1051 // Remember the EventBase we are attached to, before we start invoking any
1052 // callbacks (since the callbacks may call detachEventBase()).
1053 EventBase* originalEventBase = eventBase_;
1055 // Call the accept callback.
1056 invokeHandshakeCB();
1058 // Note that the accept callback may have changed our state.
1059 // (set or unset the read callback, called write(), closed the socket, etc.)
1060 // The following code needs to handle these situations correctly.
1062 // If the socket has been closed, readCallback_ and writeReqHead_ will
1063 // always be nullptr, so that will prevent us from trying to read or write.
1065 // The main thing to check for is if eventBase_ is still originalEventBase.
1066 // If not, we have been detached from this event base, so we shouldn't
1067 // perform any more operations.
1068 if (eventBase_ != originalEventBase) {
1072 AsyncSocket::handleInitialReadWrite();
1076 AsyncSSLSocket::handleConnect() noexcept {
1077 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1078 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1079 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1081 if (state_ < StateEnum::ESTABLISHED) {
1082 return AsyncSocket::handleConnect();
1085 assert(state_ == StateEnum::ESTABLISHED &&
1086 sslState_ == STATE_CONNECTING);
1089 int ret = SSL_connect(ssl_);
1092 unsigned long errError;
1093 int errnoCopy = errno;
1094 if (willBlock(ret, &sslError, &errError)) {
1097 sslState_ = STATE_ERROR;
1098 SSLException ex(sslError, errError, ret, errnoCopy);
1099 return failHandshake(__func__, ex);
1103 handshakeComplete_ = true;
1104 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1106 // Move into STATE_ESTABLISHED in the normal case that we are in
1107 // STATE_CONNECTING.
1108 sslState_ = STATE_ESTABLISHED;
1110 VLOG(3) << "AsyncSSLSocket " << this << ": "
1111 << "fd " << fd_ << " successfully connected; "
1112 << "state=" << int(state_) << ", sslState=" << sslState_
1113 << ", events=" << eventFlags_;
1115 // Remember the EventBase we are attached to, before we start invoking any
1116 // callbacks (since the callbacks may call detachEventBase()).
1117 EventBase* originalEventBase = eventBase_;
1119 // Call the handshake callback.
1120 invokeHandshakeCB();
1122 // Note that the connect callback may have changed our state.
1123 // (set or unset the read callback, called write(), closed the socket, etc.)
1124 // The following code needs to handle these situations correctly.
1126 // If the socket has been closed, readCallback_ and writeReqHead_ will
1127 // always be nullptr, so that will prevent us from trying to read or write.
1129 // The main thing to check for is if eventBase_ is still originalEventBase.
1130 // If not, we have been detached from this event base, so we shouldn't
1131 // perform any more operations.
1132 if (eventBase_ != originalEventBase) {
1136 AsyncSocket::handleInitialReadWrite();
1139 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1140 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1141 // turn on the buffer movable in openssl
1142 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1143 callback != nullptr && callback->isBufferMovable()) {
1144 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1145 isBufferMovable_ = true;
1149 AsyncSocket::setReadCB(callback);
1152 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1153 bufferMovableEnabled_ = enabled;
1156 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1157 CHECK(readCallback_);
1158 if (isBufferMovable_) {
1162 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1163 readCallback_->getReadBuffer(buf, buflen);
1168 AsyncSSLSocket::handleRead() noexcept {
1169 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1170 << ", state=" << int(state_) << ", "
1171 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1172 if (state_ < StateEnum::ESTABLISHED) {
1173 return AsyncSocket::handleRead();
1177 if (sslState_ == STATE_ACCEPTING) {
1182 else if (sslState_ == STATE_CONNECTING) {
1189 AsyncSocket::handleRead();
1192 AsyncSocket::ReadResult
1193 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1194 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1195 << ", buflen=" << *buflen;
1197 if (sslState_ == STATE_UNENCRYPTED) {
1198 return AsyncSocket::performRead(buf, buflen, offset);
1202 if (!isBufferMovable_) {
1203 bytes = SSL_read(ssl_, *buf, *buflen);
1205 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1207 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1211 if (server_ && renegotiateAttempted_) {
1212 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1213 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1214 << "): client intitiated SSL renegotiation not permitted";
1217 folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1220 int error = SSL_get_error(ssl_, bytes);
1221 if (error == SSL_ERROR_WANT_READ) {
1222 // The caller will register for read event if not already.
1223 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1224 return ReadResult(READ_BLOCKING);
1226 return ReadResult(READ_ERROR);
1228 } else if (error == SSL_ERROR_WANT_WRITE) {
1229 // TODO: Even though we are attempting to read data, SSL_read() may
1230 // need to write data if renegotiation is being performed. We currently
1231 // don't support this and just fail the read.
1232 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1233 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1234 << "): unsupported SSL renegotiation during read";
1237 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1239 if (zero_return(error, bytes)) {
1240 return ReadResult(bytes);
1242 long errError = ERR_get_error();
1243 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1244 << "state=" << state_ << ", "
1245 << "sslState=" << sslState_ << ", "
1246 << "events=" << std::hex << eventFlags_ << "): "
1247 << "bytes: " << bytes << ", "
1248 << "error: " << error << ", "
1249 << "errno: " << errno << ", "
1250 << "func: " << ERR_func_error_string(errError) << ", "
1251 << "reason: " << ERR_reason_error_string(errError);
1254 folly::make_unique<SSLException>(error, errError, bytes, errno));
1257 appBytesReceived_ += bytes;
1258 return ReadResult(bytes);
1262 void AsyncSSLSocket::handleWrite() noexcept {
1263 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1264 << ", state=" << int(state_) << ", "
1265 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1266 if (state_ < StateEnum::ESTABLISHED) {
1267 return AsyncSocket::handleWrite();
1270 if (sslState_ == STATE_ACCEPTING) {
1276 if (sslState_ == STATE_CONNECTING) {
1283 AsyncSocket::handleWrite();
1286 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1287 if (error == SSL_ERROR_WANT_READ) {
1288 // Even though we are attempting to write data, SSL_write() may
1289 // need to read data if renegotiation is being performed. We currently
1290 // don't support this and just fail the write.
1291 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1292 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1294 << "unsupported SSL renegotiation during write";
1297 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1299 if (zero_return(error, rc)) {
1300 return WriteResult(0);
1302 auto errError = ERR_get_error();
1303 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1304 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1305 << "SSL error: " << error << ", errno: " << errno
1306 << ", func: " << ERR_func_error_string(errError)
1307 << ", reason: " << ERR_reason_error_string(errError);
1310 folly::make_unique<SSLException>(error, errError, rc, errno));
1314 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1318 uint32_t* countWritten,
1319 uint32_t* partialWritten) {
1320 if (sslState_ == STATE_UNENCRYPTED) {
1321 return AsyncSocket::performWrite(
1322 vec, count, flags, countWritten, partialWritten);
1324 if (sslState_ != STATE_ESTABLISHED) {
1325 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1326 << ", sslState=" << sslState_
1327 << ", events=" << eventFlags_ << "): "
1328 << "TODO: AsyncSSLSocket currently does not support calling "
1329 << "write() before the handshake has fully completed";
1331 WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1334 bool cork = isSet(flags, WriteFlags::CORK);
1335 CorkGuard guard(fd_, count > 1, cork, &corked_);
1337 // Declare a buffer used to hold small write requests. It could point to a
1338 // memory block either on stack or on heap. If it is on heap, we release it
1339 // manually when scope exits
1340 char* combinedBuf{nullptr};
1342 // Note, always keep this check consistent with what we do below
1343 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1344 delete[] combinedBuf;
1349 *partialWritten = 0;
1350 ssize_t totalWritten = 0;
1351 size_t bytesStolenFromNextBuffer = 0;
1352 for (uint32_t i = 0; i < count; i++) {
1353 const iovec* v = vec + i;
1354 size_t offset = bytesStolenFromNextBuffer;
1355 bytesStolenFromNextBuffer = 0;
1356 size_t len = v->iov_len - offset;
1362 buf = ((const char*)v->iov_base) + offset;
1365 uint32_t buffersStolen = 0;
1366 if ((len < minWriteSize_) && ((i + 1) < count)) {
1367 // Combine this buffer with part or all of the next buffers in
1368 // order to avoid really small-grained calls to SSL_write().
1369 // Each call to SSL_write() produces a separate record in
1370 // the egress SSL stream, and we've found that some low-end
1371 // mobile clients can't handle receiving an HTTP response
1372 // header and the first part of the response body in two
1373 // separate SSL records (even if those two records are in
1374 // the same TCP packet).
1376 if (combinedBuf == nullptr) {
1377 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1378 // Allocate the buffer on heap
1379 combinedBuf = new char[minWriteSize_];
1381 // Allocate the buffer on stack
1382 combinedBuf = (char*)alloca(minWriteSize_);
1385 assert(combinedBuf != nullptr);
1387 memcpy(combinedBuf, buf, len);
1389 // INVARIANT: i + buffersStolen == complete chunks serialized
1390 uint32_t nextIndex = i + buffersStolen + 1;
1391 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1392 minWriteSize_ - len);
1393 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1394 bytesStolenFromNextBuffer);
1395 len += bytesStolenFromNextBuffer;
1396 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1397 // couldn't steal the whole buffer
1400 bytesStolenFromNextBuffer = 0;
1403 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1404 bytes = eorAwareSSLWrite(
1405 ssl_, combinedBuf, len,
1406 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1409 bytes = eorAwareSSLWrite(ssl_, buf, len,
1410 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1414 int error = SSL_get_error(ssl_, bytes);
1415 if (error == SSL_ERROR_WANT_WRITE) {
1416 // The caller will register for write event if not already.
1417 *partialWritten = offset;
1418 return WriteResult(totalWritten);
1420 auto writeResult = interpretSSLError(bytes, error);
1421 if (writeResult.writeReturn < 0) {
1423 } // else fall through to below to correctly record totalWritten
1426 totalWritten += bytes;
1428 if (bytes == (ssize_t)len) {
1429 // The full iovec is written.
1430 (*countWritten) += 1 + buffersStolen;
1434 bytes += offset; // adjust bytes to account for all of v
1435 while (bytes >= (ssize_t)v->iov_len) {
1436 // We combined this buf with part or all of the next one, and
1437 // we managed to write all of this buf but not all of the bytes
1438 // from the next one that we'd hoped to write.
1439 bytes -= v->iov_len;
1443 *partialWritten = bytes;
1444 return WriteResult(totalWritten);
1448 return WriteResult(totalWritten);
1451 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1453 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1454 if (appEorByteNo_) {
1455 // cannot track for more than one app byte EOR
1456 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1458 appEorByteNo_ = appBytesWritten_ + n;
1461 // 1. It is fine to keep updating minEorRawByteNo_.
1462 // 2. It is _min_ in the sense that SSL record will add some overhead.
1463 minEorRawByteNo_ = getRawBytesWritten() + n;
1466 n = sslWriteImpl(ssl, buf, n);
1468 appBytesWritten_ += n;
1469 if (appEorByteNo_) {
1470 if (getRawBytesWritten() >= minEorRawByteNo_) {
1471 minEorRawByteNo_ = 0;
1473 if(appBytesWritten_ == appEorByteNo_) {
1476 CHECK(appBytesWritten_ < appEorByteNo_);
1483 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1484 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1485 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1486 sslSocket->renegotiateAttempted_ = true;
1488 if (where & SSL_CB_READ_ALERT) {
1489 const char* type = SSL_alert_type_string(ret);
1491 const char* desc = SSL_alert_desc_string(ret);
1492 sslSocket->alertsReceived_.emplace_back(
1493 *type, StringPiece(desc, std::strlen(desc)));
1498 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1503 AsyncSSLSocket *tsslSock;
1505 iov.iov_base = const_cast<char *>(in);
1507 memset(&msg, 0, sizeof(msg));
1512 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1514 tsslSock->minEorRawByteNo_ &&
1515 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1519 ret = sendmsg(b->num, &msg, flags);
1520 BIO_clear_retry_flags(b);
1522 if (BIO_sock_should_retry(ret))
1523 BIO_set_retry_write(b);
1528 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1529 X509_STORE_CTX* x509Ctx) {
1530 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1531 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1532 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1534 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1535 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1536 return (self->handshakeCallback_) ?
1537 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1541 void AsyncSSLSocket::enableClientHelloParsing() {
1542 parseClientHello_ = true;
1543 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1546 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1547 SSL_set_msg_callback(ssl, nullptr);
1548 SSL_set_msg_callback_arg(ssl, nullptr);
1549 clientHelloInfo_->clientHelloBuf_.clear();
1552 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1559 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1561 sock->resetClientHelloParsing(ssl);
1564 if (contentType != SSL3_RT_HANDSHAKE) {
1571 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1572 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1574 Cursor cursor(clientHelloBuf.front());
1575 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1576 sock->resetClientHelloParsing(ssl);
1580 if (cursor.totalLength() < 3) {
1581 clientHelloBuf.trimEnd(len);
1582 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1586 uint32_t messageLength = cursor.read<uint8_t>();
1587 messageLength <<= 8;
1588 messageLength |= cursor.read<uint8_t>();
1589 messageLength <<= 8;
1590 messageLength |= cursor.read<uint8_t>();
1591 if (cursor.totalLength() < messageLength) {
1592 clientHelloBuf.trimEnd(len);
1593 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1597 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1598 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1600 cursor.skip(4); // gmt_unix_time
1601 cursor.skip(28); // random_bytes
1603 cursor.skip(cursor.read<uint8_t>()); // session_id
1605 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1606 for (int i = 0; i < cipherSuitesLength; i += 2) {
1607 sock->clientHelloInfo_->
1608 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1611 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1612 for (int i = 0; i < compressionMethodsLength; ++i) {
1613 sock->clientHelloInfo_->
1614 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1617 if (cursor.totalLength() > 0) {
1618 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1619 while (extensionsLength) {
1620 ssl::TLSExtension extensionType =
1621 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1622 sock->clientHelloInfo_->
1623 clientHelloExtensions_.push_back(extensionType);
1624 extensionsLength -= 2;
1625 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1626 extensionsLength -= 2;
1628 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1630 extensionDataLength -= 2;
1631 while (extensionDataLength) {
1632 ssl::HashAlgorithm hashAlg =
1633 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1634 ssl::SignatureAlgorithm sigAlg =
1635 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1636 extensionDataLength -= 2;
1637 sock->clientHelloInfo_->
1638 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1641 cursor.skip(extensionDataLength);
1642 extensionsLength -= extensionDataLength;
1646 } catch (std::out_of_range& e) {
1647 // we'll use what we found and cleanup below.
1648 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1649 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1652 sock->resetClientHelloParsing(ssl);