2 * Copyright 2017 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>
20 #include <folly/portability/Sockets.h>
22 #include <boost/noncopyable.hpp>
25 #include <openssl/asn1.h>
26 #include <openssl/err.h>
27 #include <openssl/ssl.h>
28 #include <sys/types.h>
31 #include <folly/Bits.h>
32 #include <folly/SocketAddress.h>
33 #include <folly/SpinLock.h>
34 #include <folly/io/Cursor.h>
35 #include <folly/io/IOBuf.h>
36 #include <folly/portability/OpenSSL.h>
37 #include <folly/portability/Unistd.h>
39 using folly::SocketAddress;
40 using folly::SSLContext;
42 using std::shared_ptr;
46 using folly::SpinLock;
47 using folly::SpinLockGuard;
48 using folly::io::Cursor;
49 using std::unique_ptr;
53 using folly::AsyncSocket;
54 using folly::AsyncSocketException;
55 using folly::AsyncSSLSocket;
56 using folly::Optional;
57 using folly::SSLContext;
58 // For OpenSSL portability API
59 using namespace folly::ssl;
60 using folly::ssl::OpenSSLUtils;
62 // We have one single dummy SSL context so that we can implement attach
63 // and detach methods in a thread safe fashion without modifying opnessl.
64 static SSLContext *dummyCtx = nullptr;
65 static SpinLock dummyCtxLock;
67 // If given min write size is less than this, buffer will be allocated on
68 // stack, otherwise it is allocated on heap
69 const size_t MAX_STACK_BUF_SIZE = 2048;
71 // This converts "illegal" shutdowns into ZERO_RETURN
72 inline bool zero_return(int error, int rc) {
73 return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
76 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
77 public AsyncSSLSocket::HandshakeCB {
80 AsyncSSLSocket *sslSocket_;
81 AsyncSSLSocket::ConnectCallback *callback_;
86 ~AsyncSSLSocketConnector() override {}
89 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
90 AsyncSocket::ConnectCallback *callback,
92 sslSocket_(sslSocket),
95 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
96 std::chrono::steady_clock::now().time_since_epoch()).count()) {
99 void connectSuccess() noexcept override {
100 VLOG(7) << "client socket connected";
102 int64_t timeoutLeft = 0;
104 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
105 std::chrono::steady_clock::now().time_since_epoch()).count();
107 timeoutLeft = timeout_ - (curTime - startTime_);
108 if (timeoutLeft <= 0) {
109 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
110 "SSL connect timed out");
116 sslSocket_->sslConn(this, std::chrono::milliseconds(timeoutLeft));
119 void connectErr(const AsyncSocketException& ex) noexcept override {
120 VLOG(1) << "TCP connect failed: " << ex.what();
125 void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
126 VLOG(7) << "client handshake success";
128 callback_->connectSuccess();
133 void handshakeErr(AsyncSSLSocket* /* socket */,
134 const AsyncSocketException& ex) noexcept override {
135 VLOG(1) << "client handshakeErr: " << ex.what();
140 void fail(const AsyncSocketException &ex) {
141 // fail is a noop if called twice
143 AsyncSSLSocket::ConnectCallback *cb = callback_;
147 sslSocket_->closeNow();
148 // closeNow can call handshakeErr if it hasn't been called already.
149 // So this may have been deleted, no member variable access beyond this
151 // Note that closeNow may invoke writeError callbacks if the socket had
152 // write data pending connection completion.
157 void setup_SSL_CTX(SSL_CTX *ctx) {
158 #ifdef SSL_MODE_RELEASE_BUFFERS
159 SSL_CTX_set_mode(ctx,
160 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
161 SSL_MODE_ENABLE_PARTIAL_WRITE
162 | SSL_MODE_RELEASE_BUFFERS
165 SSL_CTX_set_mode(ctx,
166 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
167 SSL_MODE_ENABLE_PARTIAL_WRITE
170 // SSL_CTX_set_mode is a Macro
171 #ifdef SSL_MODE_WRITE_IOVEC
172 SSL_CTX_set_mode(ctx,
173 SSL_CTX_get_mode(ctx)
174 | SSL_MODE_WRITE_IOVEC);
179 BIO_METHOD sslBioMethod;
181 void* initsslBioMethod(void) {
182 memcpy(&sslBioMethod, BIO_s_socket(), sizeof(sslBioMethod));
183 // override the bwrite method for MSG_EOR support
184 OpenSSLUtils::setCustomBioWriteMethod(
185 &sslBioMethod, AsyncSSLSocket::bioWrite);
186 OpenSSLUtils::setCustomBioReadMethod(&sslBioMethod, AsyncSSLSocket::bioRead);
188 // Note that the sslBioMethod.type and sslBioMethod.name are not
189 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
190 // then have specific handlings. The sslWriteBioWrite should be compatible
191 // with the one in openssl.
193 // Return something here to enable AsyncSSLSocket to call this method using
194 // a function-scoped static.
198 } // anonymous namespace
203 * Create a client AsyncSSLSocket
205 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
206 EventBase* evb, bool deferSecurityNegotiation) :
209 handshakeTimeout_(this, evb),
210 connectionTimeout_(this, evb) {
212 if (deferSecurityNegotiation) {
213 sslState_ = STATE_UNENCRYPTED;
218 * Create a server/client AsyncSSLSocket
220 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
221 EventBase* evb, int fd, bool server,
222 bool deferSecurityNegotiation) :
223 AsyncSocket(evb, fd),
226 handshakeTimeout_(this, evb),
227 connectionTimeout_(this, evb) {
228 noTransparentTls_ = true;
231 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
232 AsyncSSLSocket::sslInfoCallback);
234 if (deferSecurityNegotiation) {
235 sslState_ = STATE_UNENCRYPTED;
239 #if FOLLY_OPENSSL_HAS_SNI
241 * Create a client AsyncSSLSocket and allow tlsext_hostname
242 * to be sent in Client Hello.
244 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
246 const std::string& serverName,
247 bool deferSecurityNegotiation) :
248 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
249 tlsextHostname_ = serverName;
253 * Create a client AsyncSSLSocket from an already connected fd
254 * and allow tlsext_hostname to be sent in Client Hello.
256 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
257 EventBase* evb, int fd,
258 const std::string& serverName,
259 bool deferSecurityNegotiation) :
260 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
261 tlsextHostname_ = serverName;
263 #endif // FOLLY_OPENSSL_HAS_SNI
265 AsyncSSLSocket::~AsyncSSLSocket() {
266 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
267 << ", evb=" << eventBase_ << ", fd=" << fd_
268 << ", state=" << int(state_) << ", sslState="
269 << sslState_ << ", events=" << eventFlags_ << ")";
272 void AsyncSSLSocket::init() {
273 // Do this here to ensure we initialize this once before any use of
274 // AsyncSSLSocket instances and not as part of library load.
275 static const auto sslBioMethodInitializer = initsslBioMethod();
276 (void)sslBioMethodInitializer;
278 setup_SSL_CTX(ctx_->getSSLCtx());
281 void AsyncSSLSocket::closeNow() {
282 // Close the SSL connection.
283 if (ssl_ != nullptr && fd_ != -1) {
284 int rc = SSL_shutdown(ssl_);
286 rc = SSL_shutdown(ssl_);
293 if (sslSession_ != nullptr) {
294 SSL_SESSION_free(sslSession_);
295 sslSession_ = nullptr;
298 sslState_ = STATE_CLOSED;
300 if (handshakeTimeout_.isScheduled()) {
301 handshakeTimeout_.cancelTimeout();
304 DestructorGuard dg(this);
307 AsyncSocketException(
308 AsyncSocketException::END_OF_FILE,
309 "SSL connection closed locally"));
311 if (ssl_ != nullptr) {
317 AsyncSocket::closeNow();
320 void AsyncSSLSocket::shutdownWrite() {
321 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
323 // (Performing a full shutdown here is more desirable than doing nothing at
324 // all. The purpose of shutdownWrite() is normally to notify the other end
325 // of the connection that no more data will be sent. If we do nothing, the
326 // other end will never know that no more data is coming, and this may result
327 // in protocol deadlock.)
331 void AsyncSSLSocket::shutdownWriteNow() {
335 bool AsyncSSLSocket::good() const {
336 return (AsyncSocket::good() &&
337 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
338 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
341 // The TAsyncTransport definition of 'good' states that the transport is
342 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
343 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
344 // is connected but we haven't initiated the call to SSL_connect.
345 bool AsyncSSLSocket::connecting() const {
347 (AsyncSocket::connecting() ||
348 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
349 sslState_ == STATE_CONNECTING))));
352 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
353 const unsigned char* protoName = nullptr;
354 unsigned protoLength;
355 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
356 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
361 bool AsyncSSLSocket::isEorTrackingEnabled() const {
365 void AsyncSSLSocket::setEorTracking(bool track) {
366 if (trackEor_ != track) {
369 minEorRawByteNo_ = 0;
373 size_t AsyncSSLSocket::getRawBytesWritten() const {
374 // The bio(s) in the write path are in a chain
375 // each bio flushes to the next and finally written into the socket
376 // to get the rawBytesWritten on the socket,
377 // get the write bytes of the last bio
379 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
382 BIO* next = BIO_next(b);
383 while (next != NULL) {
388 return BIO_number_written(b);
391 size_t AsyncSSLSocket::getRawBytesReceived() const {
393 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
397 return BIO_number_read(b);
401 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
402 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
403 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
404 << "events=" << eventFlags_ << ", server=" << short(server_)
405 << "): " << "sslAccept/Connect() called in invalid "
406 << "state, handshake callback " << handshakeCallback_
407 << ", new callback " << callback;
408 assert(!handshakeTimeout_.isScheduled());
409 sslState_ = STATE_ERROR;
411 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
412 "sslAccept() called with socket in invalid state");
414 handshakeEndTime_ = std::chrono::steady_clock::now();
416 callback->handshakeErr(this, ex);
419 failHandshake(__func__, ex);
422 void AsyncSSLSocket::sslAccept(
423 HandshakeCB* callback,
424 std::chrono::milliseconds timeout,
425 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
426 DestructorGuard dg(this);
427 assert(eventBase_->isInEventBaseThread());
428 verifyPeer_ = verifyPeer;
430 // Make sure we're in the uninitialized state
431 if (!server_ || (sslState_ != STATE_UNINIT &&
432 sslState_ != STATE_UNENCRYPTED) ||
433 handshakeCallback_ != nullptr) {
434 return invalidState(callback);
437 // Cache local and remote socket addresses to keep them available
438 // after socket file descriptor is closed.
439 if (cacheAddrOnFailure_ && -1 != getFd()) {
440 cacheLocalPeerAddr();
443 handshakeStartTime_ = std::chrono::steady_clock::now();
444 // Make end time at least >= start time.
445 handshakeEndTime_ = handshakeStartTime_;
447 sslState_ = STATE_ACCEPTING;
448 handshakeCallback_ = callback;
450 if (timeout > std::chrono::milliseconds::zero()) {
451 handshakeTimeout_.scheduleTimeout(timeout);
454 /* register for a read operation (waiting for CLIENT HELLO) */
455 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
457 if (preReceivedData_) {
462 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
463 void AsyncSSLSocket::attachSSLContext(
464 const std::shared_ptr<SSLContext>& ctx) {
466 // Check to ensure we are in client mode. Changing a server's ssl
467 // context doesn't make sense since clients of that server would likely
468 // become confused when the server's context changes.
472 DCHECK(ctx->getSSLCtx());
475 // It's possible this could be attached before ssl_ is set up
480 // In order to call attachSSLContext, detachSSLContext must have been
481 // previously called.
482 // We need to update the initial_ctx if necessary
483 auto sslCtx = ctx->getSSLCtx();
484 SSL_CTX_up_ref(sslCtx);
485 #ifndef OPENSSL_NO_TLSEXT
486 // note that detachSSLContext has already freed ssl_->initial_ctx
487 ssl_->initial_ctx = sslCtx;
489 // Detach sets the socket's context to the dummy context. Thus we must acquire
491 SpinLockGuard guard(dummyCtxLock);
492 SSL_set_SSL_CTX(ssl_, sslCtx);
495 void AsyncSSLSocket::detachSSLContext() {
498 // It's possible for this to be called before ssl_ has been
503 // Detach the initial_ctx as well. Internally w/ OPENSSL_NO_TLSEXT
504 // it is used for session info. It will be reattached in attachSSLContext
505 #ifndef OPENSSL_NO_TLSEXT
506 if (ssl_->initial_ctx) {
507 SSL_CTX_free(ssl_->initial_ctx);
508 ssl_->initial_ctx = nullptr;
511 SpinLockGuard guard(dummyCtxLock);
512 if (nullptr == dummyCtx) {
513 // We need to lazily initialize the dummy context so we don't
514 // accidentally override any programmatic settings to openssl
515 dummyCtx = new SSLContext;
517 // We must remove this socket's references to its context right now
518 // since this socket could get passed to any thread. If the context has
519 // had its locking disabled, just doing a set in attachSSLContext()
520 // would not be thread safe.
521 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
525 #if FOLLY_OPENSSL_HAS_SNI
526 void AsyncSSLSocket::switchServerSSLContext(
527 const std::shared_ptr<SSLContext>& handshakeCtx) {
529 if (sslState_ != STATE_ACCEPTING) {
530 // We log it here and allow the switch.
531 // It should not affect our re-negotiation support (which
532 // is not supported now).
533 VLOG(6) << "fd=" << getFd()
534 << " renegotation detected when switching SSL_CTX";
537 setup_SSL_CTX(handshakeCtx->getSSLCtx());
538 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
539 AsyncSSLSocket::sslInfoCallback);
540 handshakeCtx_ = handshakeCtx;
541 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
544 bool AsyncSSLSocket::isServerNameMatch() const {
551 SSL_SESSION *ss = SSL_get_session(ssl_);
556 if(!ss->tlsext_hostname) {
559 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
562 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
563 tlsextHostname_ = std::move(serverName);
566 #endif // FOLLY_OPENSSL_HAS_SNI
568 void AsyncSSLSocket::timeoutExpired() noexcept {
569 if (state_ == StateEnum::ESTABLISHED &&
570 (sslState_ == STATE_CACHE_LOOKUP ||
571 sslState_ == STATE_ASYNC_PENDING)) {
572 sslState_ = STATE_ERROR;
573 // We are expecting a callback in restartSSLAccept. The cache lookup
574 // and rsa-call necessarily have pointers to this ssl socket, so delay
575 // the cleanup until he calls us back.
576 } else if (state_ == StateEnum::CONNECTING) {
577 assert(sslState_ == STATE_CONNECTING);
578 DestructorGuard dg(this);
579 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
580 "Fallback connect timed out during TFO");
581 failHandshake(__func__, ex);
583 assert(state_ == StateEnum::ESTABLISHED &&
584 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
585 DestructorGuard dg(this);
586 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
587 (sslState_ == STATE_CONNECTING) ?
588 "SSL connect timed out" : "SSL accept timed out");
589 failHandshake(__func__, ex);
593 int AsyncSSLSocket::getSSLExDataIndex() {
594 static auto index = SSL_get_ex_new_index(
595 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
599 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
600 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
601 getSSLExDataIndex()));
604 void AsyncSSLSocket::failHandshake(const char* /* fn */,
605 const AsyncSocketException& ex) {
607 if (handshakeTimeout_.isScheduled()) {
608 handshakeTimeout_.cancelTimeout();
610 invokeHandshakeErr(ex);
614 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
615 handshakeEndTime_ = std::chrono::steady_clock::now();
616 if (handshakeCallback_ != nullptr) {
617 HandshakeCB* callback = handshakeCallback_;
618 handshakeCallback_ = nullptr;
619 callback->handshakeErr(this, ex);
623 void AsyncSSLSocket::invokeHandshakeCB() {
624 handshakeEndTime_ = std::chrono::steady_clock::now();
625 if (handshakeTimeout_.isScheduled()) {
626 handshakeTimeout_.cancelTimeout();
628 if (handshakeCallback_) {
629 HandshakeCB* callback = handshakeCallback_;
630 handshakeCallback_ = nullptr;
631 callback->handshakeSuc(this);
635 void AsyncSSLSocket::cacheLocalPeerAddr() {
636 SocketAddress address;
638 getLocalAddress(&address);
639 getPeerAddress(&address);
640 } catch (const std::system_error& e) {
641 // The handle can be still valid while the connection is already closed.
642 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
648 void AsyncSSLSocket::connect(ConnectCallback* callback,
649 const folly::SocketAddress& address,
651 const OptionMap &options,
652 const folly::SocketAddress& bindAddr)
655 assert(state_ == StateEnum::UNINIT);
656 assert(sslState_ == STATE_UNINIT);
657 noTransparentTls_ = true;
658 AsyncSSLSocketConnector *connector =
659 new AsyncSSLSocketConnector(this, callback, timeout);
660 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
663 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
664 // apply the settings specified in verifyPeer_
665 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
666 if(ctx_->needsPeerVerification()) {
667 SSL_set_verify(ssl, ctx_->getVerificationMode(),
668 AsyncSSLSocket::sslVerifyCallback);
671 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
672 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
673 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
674 AsyncSSLSocket::sslVerifyCallback);
679 bool AsyncSSLSocket::setupSSLBio() {
680 auto sslBio = BIO_new(&sslBioMethod);
686 OpenSSLUtils::setBioAppData(sslBio, this);
687 OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE);
688 SSL_set_bio(ssl_, sslBio, sslBio);
692 void AsyncSSLSocket::sslConn(
693 HandshakeCB* callback,
694 std::chrono::milliseconds timeout,
695 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
696 DestructorGuard dg(this);
697 assert(eventBase_->isInEventBaseThread());
699 // Cache local and remote socket addresses to keep them available
700 // after socket file descriptor is closed.
701 if (cacheAddrOnFailure_ && -1 != getFd()) {
702 cacheLocalPeerAddr();
705 verifyPeer_ = verifyPeer;
707 // Make sure we're in the uninitialized state
708 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
709 STATE_UNENCRYPTED) ||
710 handshakeCallback_ != nullptr) {
711 return invalidState(callback);
714 sslState_ = STATE_CONNECTING;
715 handshakeCallback_ = callback;
718 ssl_ = ctx_->createSSL();
719 } catch (std::exception &e) {
720 sslState_ = STATE_ERROR;
721 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
722 "error calling SSLContext::createSSL()");
723 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
724 << fd_ << "): " << e.what();
725 return failHandshake(__func__, ex);
728 if (!setupSSLBio()) {
729 sslState_ = STATE_ERROR;
730 AsyncSocketException ex(
731 AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
732 return failHandshake(__func__, ex);
735 applyVerificationOptions(ssl_);
737 if (sslSession_ != nullptr) {
738 sessionResumptionAttempted_ = true;
739 SSL_set_session(ssl_, sslSession_);
740 SSL_SESSION_free(sslSession_);
741 sslSession_ = nullptr;
743 #if FOLLY_OPENSSL_HAS_SNI
744 if (tlsextHostname_.size()) {
745 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
749 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
751 handshakeConnectTimeout_ = timeout;
755 // This could be called multiple times, during normal ssl connections
756 // and after TFO fallback.
757 void AsyncSSLSocket::startSSLConnect() {
758 handshakeStartTime_ = std::chrono::steady_clock::now();
759 // Make end time at least >= start time.
760 handshakeEndTime_ = handshakeStartTime_;
761 if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) {
762 handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
767 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
768 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
769 return SSL_get1_session(ssl_);
775 const SSL* AsyncSSLSocket::getSSL() const {
779 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
780 sslSession_ = session;
781 if (!takeOwnership && session != nullptr) {
782 // Increment the reference count
783 // This API exists in BoringSSL and OpenSSL 1.1.0
784 SSL_SESSION_up_ref(session);
788 void AsyncSSLSocket::getSelectedNextProtocol(
789 const unsigned char** protoName,
791 SSLContext::NextProtocolType* protoType) const {
792 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
793 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
794 "NPN not supported");
798 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
799 const unsigned char** protoName,
801 SSLContext::NextProtocolType* protoType) const {
802 *protoName = nullptr;
804 #if FOLLY_OPENSSL_HAS_ALPN
805 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
808 *protoType = SSLContext::NextProtocolType::ALPN;
813 #ifdef OPENSSL_NPN_NEGOTIATED
814 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
816 *protoType = SSLContext::NextProtocolType::NPN;
825 bool AsyncSSLSocket::getSSLSessionReused() const {
826 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
827 return SSL_session_reused(ssl_);
832 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
833 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
837 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
838 if (ssl == nullptr) {
841 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
842 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
848 const char *AsyncSSLSocket::getSSLServerName() const {
849 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
850 return getSSLServerNameFromSSL(ssl_);
852 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
853 "SNI not supported");
857 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
858 return getSSLServerNameFromSSL(ssl_);
861 int AsyncSSLSocket::getSSLVersion() const {
862 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
865 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
866 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
868 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
869 return OBJ_nid2ln(nid);
874 int AsyncSSLSocket::getSSLCertSize() const {
876 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
878 EVP_PKEY *key = X509_get_pubkey(cert);
879 certSize = EVP_PKEY_bits(key);
885 const X509* AsyncSSLSocket::getSelfCert() const {
886 return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
889 bool AsyncSSLSocket::willBlock(int ret,
891 unsigned long* errErrorOut) noexcept {
893 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
894 if (error == SSL_ERROR_WANT_READ) {
895 // Register for read event if not already.
896 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
898 } else if (error == SSL_ERROR_WANT_WRITE) {
899 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
900 << ", state=" << int(state_) << ", sslState="
901 << sslState_ << ", events=" << eventFlags_ << "): "
902 << "SSL_ERROR_WANT_WRITE";
903 // Register for write event if not already.
904 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
906 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
907 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
908 // We will block but we can't register our own socket. The callback that
909 // triggered this code will re-call handleAccept at the appropriate time.
911 // We can only get here if the linked libssl.so has support for this feature
912 // as well, otherwise SSL_get_error cannot return our error code.
913 sslState_ = STATE_CACHE_LOOKUP;
915 // Unregister for all events while blocked here
916 updateEventRegistration(EventHandler::NONE,
917 EventHandler::READ | EventHandler::WRITE);
919 // The timeout (if set) keeps running here
923 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
924 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
926 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
927 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
930 // Our custom openssl function has kicked off an async request to do
931 // rsa/ecdsa private key operation. When that call returns, a callback will
932 // be invoked that will re-call handleAccept.
933 sslState_ = STATE_ASYNC_PENDING;
935 // Unregister for all events while blocked here
936 updateEventRegistration(
938 EventHandler::READ | EventHandler::WRITE
941 // The timeout (if set) keeps running here
944 unsigned long lastError = *errErrorOut = ERR_get_error();
945 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
946 << "state=" << state_ << ", "
947 << "sslState=" << sslState_ << ", "
948 << "events=" << std::hex << eventFlags_ << "): "
949 << "SSL error: " << error << ", "
950 << "errno: " << errno << ", "
951 << "ret: " << ret << ", "
952 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
953 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
954 << "func: " << ERR_func_error_string(lastError) << ", "
955 << "reason: " << ERR_reason_error_string(lastError);
960 void AsyncSSLSocket::checkForImmediateRead() noexcept {
961 // openssl may have buffered data that it read from the socket already.
962 // In this case we have to process it immediately, rather than waiting for
963 // the socket to become readable again.
964 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
965 AsyncSocket::handleRead();
970 AsyncSSLSocket::restartSSLAccept()
972 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
973 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
974 << "sslState=" << sslState_ << ", events=" << eventFlags_;
975 DestructorGuard dg(this);
977 sslState_ == STATE_CACHE_LOOKUP ||
978 sslState_ == STATE_ASYNC_PENDING ||
979 sslState_ == STATE_ERROR ||
980 sslState_ == STATE_CLOSED);
981 if (sslState_ == STATE_CLOSED) {
982 // I sure hope whoever closed this socket didn't delete it already,
983 // but this is not strictly speaking an error
986 if (sslState_ == STATE_ERROR) {
987 // go straight to fail if timeout expired during lookup
988 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
989 "SSL accept timed out");
990 failHandshake(__func__, ex);
993 sslState_ = STATE_ACCEPTING;
994 this->handleAccept();
998 AsyncSSLSocket::handleAccept() noexcept {
999 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1000 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1001 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1003 assert(state_ == StateEnum::ESTABLISHED &&
1004 sslState_ == STATE_ACCEPTING);
1006 /* lazily create the SSL structure */
1008 ssl_ = ctx_->createSSL();
1009 } catch (std::exception &e) {
1010 sslState_ = STATE_ERROR;
1011 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1012 "error calling SSLContext::createSSL()");
1013 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1014 << ", fd=" << fd_ << "): " << e.what();
1015 return failHandshake(__func__, ex);
1018 if (!setupSSLBio()) {
1019 sslState_ = STATE_ERROR;
1020 AsyncSocketException ex(
1021 AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1022 return failHandshake(__func__, ex);
1025 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1027 applyVerificationOptions(ssl_);
1030 if (server_ && parseClientHello_) {
1031 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1032 SSL_set_msg_callback_arg(ssl_, this);
1035 clearOpenSSLErrors();
1036 int ret = SSL_accept(ssl_);
1039 unsigned long errError;
1040 int errnoCopy = errno;
1041 if (willBlock(ret, &sslError, &errError)) {
1044 sslState_ = STATE_ERROR;
1045 SSLException ex(sslError, errError, ret, errnoCopy);
1046 return failHandshake(__func__, ex);
1050 handshakeComplete_ = true;
1051 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1053 // Move into STATE_ESTABLISHED in the normal case that we are in
1055 sslState_ = STATE_ESTABLISHED;
1057 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1058 << " successfully accepted; state=" << int(state_)
1059 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1061 // Remember the EventBase we are attached to, before we start invoking any
1062 // callbacks (since the callbacks may call detachEventBase()).
1063 EventBase* originalEventBase = eventBase_;
1065 // Call the accept callback.
1066 invokeHandshakeCB();
1068 // Note that the accept callback may have changed our state.
1069 // (set or unset the read callback, called write(), closed the socket, etc.)
1070 // The following code needs to handle these situations correctly.
1072 // If the socket has been closed, readCallback_ and writeReqHead_ will
1073 // always be nullptr, so that will prevent us from trying to read or write.
1075 // The main thing to check for is if eventBase_ is still originalEventBase.
1076 // If not, we have been detached from this event base, so we shouldn't
1077 // perform any more operations.
1078 if (eventBase_ != originalEventBase) {
1082 AsyncSocket::handleInitialReadWrite();
1085 void AsyncSSLSocket::clearOpenSSLErrors() {
1086 // Normally clearing out the error before calling into an openssl method
1087 // is a bad idea. However there might be other code that we don't control
1088 // calling into openssl in the same thread, which doesn't use openssl
1089 // correctly. We want to safe-guard ourselves from that code.
1090 // However touching the ERR stack each and every time has a cost of taking
1091 // a lock, so we only do this when we've opted in.
1092 if (clearOpenSSLErrors_) {
1098 AsyncSSLSocket::handleConnect() noexcept {
1099 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1100 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1101 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1103 if (state_ < StateEnum::ESTABLISHED) {
1104 return AsyncSocket::handleConnect();
1108 (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1109 sslState_ == STATE_CONNECTING);
1112 clearOpenSSLErrors();
1113 auto originalState = state_;
1114 int ret = SSL_connect(ssl_);
1117 unsigned long errError;
1118 int errnoCopy = errno;
1119 if (willBlock(ret, &sslError, &errError)) {
1120 // We fell back to connecting state due to TFO
1121 if (state_ == StateEnum::CONNECTING) {
1122 DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1123 if (handshakeTimeout_.isScheduled()) {
1124 handshakeTimeout_.cancelTimeout();
1129 sslState_ = STATE_ERROR;
1130 SSLException ex(sslError, errError, ret, errnoCopy);
1131 return failHandshake(__func__, ex);
1135 handshakeComplete_ = true;
1136 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1138 // Move into STATE_ESTABLISHED in the normal case that we are in
1139 // STATE_CONNECTING.
1140 sslState_ = STATE_ESTABLISHED;
1142 VLOG(3) << "AsyncSSLSocket " << this << ": "
1143 << "fd " << fd_ << " successfully connected; "
1144 << "state=" << int(state_) << ", sslState=" << sslState_
1145 << ", events=" << eventFlags_;
1147 // Remember the EventBase we are attached to, before we start invoking any
1148 // callbacks (since the callbacks may call detachEventBase()).
1149 EventBase* originalEventBase = eventBase_;
1151 // Call the handshake callback.
1152 invokeHandshakeCB();
1154 // Note that the connect callback may have changed our state.
1155 // (set or unset the read callback, called write(), closed the socket, etc.)
1156 // The following code needs to handle these situations correctly.
1158 // If the socket has been closed, readCallback_ and writeReqHead_ will
1159 // always be nullptr, so that will prevent us from trying to read or write.
1161 // The main thing to check for is if eventBase_ is still originalEventBase.
1162 // If not, we have been detached from this event base, so we shouldn't
1163 // perform any more operations.
1164 if (eventBase_ != originalEventBase) {
1168 AsyncSocket::handleInitialReadWrite();
1171 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1172 connectionTimeout_.cancelTimeout();
1173 AsyncSocket::invokeConnectErr(ex);
1174 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1175 if (handshakeTimeout_.isScheduled()) {
1176 handshakeTimeout_.cancelTimeout();
1178 // If we fell back to connecting state during TFO and the connection
1179 // failed, it would be an SSL failure as well.
1180 invokeHandshakeErr(ex);
1184 void AsyncSSLSocket::invokeConnectSuccess() {
1185 connectionTimeout_.cancelTimeout();
1186 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1187 assert(tfoAttempted_);
1188 // If we failed TFO, we'd fall back to trying to connect the socket,
1189 // to setup things like timeouts.
1192 // still invoke the base class since it re-sets the connect time.
1193 AsyncSocket::invokeConnectSuccess();
1196 void AsyncSSLSocket::scheduleConnectTimeout() {
1197 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1198 // We fell back from TFO, and need to set the timeouts.
1199 // We will not have a connect callback in this case, thus if the timer
1200 // expires we would have no-one to notify.
1201 // Thus we should reset even the connect timers to point to the handshake
1203 assert(connectCallback_ == nullptr);
1204 // We use a different connect timeout here than the handshake timeout, so
1205 // that we can disambiguate the 2 timers.
1206 if (connectTimeout_.count() > 0) {
1207 if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1208 throw AsyncSocketException(
1209 AsyncSocketException::INTERNAL_ERROR,
1210 withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1215 AsyncSocket::scheduleConnectTimeout();
1218 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1219 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1220 // turn on the buffer movable in openssl
1221 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1222 callback != nullptr && callback->isBufferMovable()) {
1223 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1224 isBufferMovable_ = true;
1228 AsyncSocket::setReadCB(callback);
1231 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1232 bufferMovableEnabled_ = enabled;
1235 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1236 CHECK(readCallback_);
1237 if (isBufferMovable_) {
1241 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1242 readCallback_->getReadBuffer(buf, buflen);
1247 AsyncSSLSocket::handleRead() noexcept {
1248 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1249 << ", state=" << int(state_) << ", "
1250 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1251 if (state_ < StateEnum::ESTABLISHED) {
1252 return AsyncSocket::handleRead();
1256 if (sslState_ == STATE_ACCEPTING) {
1261 else if (sslState_ == STATE_CONNECTING) {
1268 AsyncSocket::handleRead();
1271 AsyncSocket::ReadResult
1272 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1273 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1274 << ", buflen=" << *buflen;
1276 if (sslState_ == STATE_UNENCRYPTED) {
1277 return AsyncSocket::performRead(buf, buflen, offset);
1280 clearOpenSSLErrors();
1282 if (!isBufferMovable_) {
1283 bytes = SSL_read(ssl_, *buf, int(*buflen));
1285 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1287 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1291 if (server_ && renegotiateAttempted_) {
1292 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1293 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1294 << "): client intitiated SSL renegotiation not permitted";
1297 folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1300 int error = SSL_get_error(ssl_, bytes);
1301 if (error == SSL_ERROR_WANT_READ) {
1302 // The caller will register for read event if not already.
1303 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1304 return ReadResult(READ_BLOCKING);
1306 return ReadResult(READ_ERROR);
1308 } else if (error == SSL_ERROR_WANT_WRITE) {
1309 // TODO: Even though we are attempting to read data, SSL_read() may
1310 // need to write data if renegotiation is being performed. We currently
1311 // don't support this and just fail the read.
1312 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1313 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1314 << "): unsupported SSL renegotiation during read";
1317 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1319 if (zero_return(error, bytes)) {
1320 return ReadResult(bytes);
1322 long errError = ERR_get_error();
1323 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1324 << "state=" << state_ << ", "
1325 << "sslState=" << sslState_ << ", "
1326 << "events=" << std::hex << eventFlags_ << "): "
1327 << "bytes: " << bytes << ", "
1328 << "error: " << error << ", "
1329 << "errno: " << errno << ", "
1330 << "func: " << ERR_func_error_string(errError) << ", "
1331 << "reason: " << ERR_reason_error_string(errError);
1334 folly::make_unique<SSLException>(error, errError, bytes, errno));
1337 appBytesReceived_ += bytes;
1338 return ReadResult(bytes);
1342 void AsyncSSLSocket::handleWrite() noexcept {
1343 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1344 << ", state=" << int(state_) << ", "
1345 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1346 if (state_ < StateEnum::ESTABLISHED) {
1347 return AsyncSocket::handleWrite();
1350 if (sslState_ == STATE_ACCEPTING) {
1356 if (sslState_ == STATE_CONNECTING) {
1363 AsyncSocket::handleWrite();
1366 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1367 if (error == SSL_ERROR_WANT_READ) {
1368 // Even though we are attempting to write data, SSL_write() may
1369 // need to read data if renegotiation is being performed. We currently
1370 // don't support this and just fail the write.
1371 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1372 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1374 << "unsupported SSL renegotiation during write";
1377 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1379 if (zero_return(error, rc)) {
1380 return WriteResult(0);
1382 auto errError = ERR_get_error();
1383 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1384 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1385 << "SSL error: " << error << ", errno: " << errno
1386 << ", func: " << ERR_func_error_string(errError)
1387 << ", reason: " << ERR_reason_error_string(errError);
1390 folly::make_unique<SSLException>(error, errError, rc, errno));
1394 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1398 uint32_t* countWritten,
1399 uint32_t* partialWritten) {
1400 if (sslState_ == STATE_UNENCRYPTED) {
1401 return AsyncSocket::performWrite(
1402 vec, count, flags, countWritten, partialWritten);
1404 if (sslState_ != STATE_ESTABLISHED) {
1405 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1406 << ", sslState=" << sslState_
1407 << ", events=" << eventFlags_ << "): "
1408 << "TODO: AsyncSSLSocket currently does not support calling "
1409 << "write() before the handshake has fully completed";
1411 WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1414 // Declare a buffer used to hold small write requests. It could point to a
1415 // memory block either on stack or on heap. If it is on heap, we release it
1416 // manually when scope exits
1417 char* combinedBuf{nullptr};
1419 // Note, always keep this check consistent with what we do below
1420 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1421 delete[] combinedBuf;
1426 *partialWritten = 0;
1427 ssize_t totalWritten = 0;
1428 size_t bytesStolenFromNextBuffer = 0;
1429 for (uint32_t i = 0; i < count; i++) {
1430 const iovec* v = vec + i;
1431 size_t offset = bytesStolenFromNextBuffer;
1432 bytesStolenFromNextBuffer = 0;
1433 size_t len = v->iov_len - offset;
1439 buf = ((const char*)v->iov_base) + offset;
1442 uint32_t buffersStolen = 0;
1443 auto sslWriteBuf = buf;
1444 if ((len < minWriteSize_) && ((i + 1) < count)) {
1445 // Combine this buffer with part or all of the next buffers in
1446 // order to avoid really small-grained calls to SSL_write().
1447 // Each call to SSL_write() produces a separate record in
1448 // the egress SSL stream, and we've found that some low-end
1449 // mobile clients can't handle receiving an HTTP response
1450 // header and the first part of the response body in two
1451 // separate SSL records (even if those two records are in
1452 // the same TCP packet).
1454 if (combinedBuf == nullptr) {
1455 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1456 // Allocate the buffer on heap
1457 combinedBuf = new char[minWriteSize_];
1459 // Allocate the buffer on stack
1460 combinedBuf = (char*)alloca(minWriteSize_);
1463 assert(combinedBuf != nullptr);
1464 sslWriteBuf = combinedBuf;
1466 memcpy(combinedBuf, buf, len);
1468 // INVARIANT: i + buffersStolen == complete chunks serialized
1469 uint32_t nextIndex = i + buffersStolen + 1;
1470 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1471 minWriteSize_ - len);
1472 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1473 bytesStolenFromNextBuffer);
1474 len += bytesStolenFromNextBuffer;
1475 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1476 // couldn't steal the whole buffer
1479 bytesStolenFromNextBuffer = 0;
1482 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1485 // Advance any empty buffers immediately after.
1486 if (bytesStolenFromNextBuffer == 0) {
1487 while ((i + buffersStolen + 1) < count &&
1488 vec[i + buffersStolen + 1].iov_len == 0) {
1494 isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1495 bytes = eorAwareSSLWrite(
1499 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1502 int error = SSL_get_error(ssl_, int(bytes));
1503 if (error == SSL_ERROR_WANT_WRITE) {
1504 // The caller will register for write event if not already.
1505 *partialWritten = uint32_t(offset);
1506 return WriteResult(totalWritten);
1508 auto writeResult = interpretSSLError(int(bytes), error);
1509 if (writeResult.writeReturn < 0) {
1511 } // else fall through to below to correctly record totalWritten
1514 totalWritten += bytes;
1516 if (bytes == (ssize_t)len) {
1517 // The full iovec is written.
1518 (*countWritten) += 1 + buffersStolen;
1522 bytes += offset; // adjust bytes to account for all of v
1523 while (bytes >= (ssize_t)v->iov_len) {
1524 // We combined this buf with part or all of the next one, and
1525 // we managed to write all of this buf but not all of the bytes
1526 // from the next one that we'd hoped to write.
1527 bytes -= v->iov_len;
1531 *partialWritten = uint32_t(bytes);
1532 return WriteResult(totalWritten);
1536 return WriteResult(totalWritten);
1539 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1541 if (eor && trackEor_) {
1542 if (appEorByteNo_) {
1543 // cannot track for more than one app byte EOR
1544 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1546 appEorByteNo_ = appBytesWritten_ + n;
1549 // 1. It is fine to keep updating minEorRawByteNo_.
1550 // 2. It is _min_ in the sense that SSL record will add some overhead.
1551 minEorRawByteNo_ = getRawBytesWritten() + n;
1554 n = sslWriteImpl(ssl, buf, n);
1556 appBytesWritten_ += n;
1557 if (appEorByteNo_) {
1558 if (getRawBytesWritten() >= minEorRawByteNo_) {
1559 minEorRawByteNo_ = 0;
1561 if(appBytesWritten_ == appEorByteNo_) {
1564 CHECK(appBytesWritten_ < appEorByteNo_);
1571 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1572 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1573 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1574 sslSocket->renegotiateAttempted_ = true;
1576 if (where & SSL_CB_READ_ALERT) {
1577 const char* type = SSL_alert_type_string(ret);
1579 const char* desc = SSL_alert_desc_string(ret);
1580 sslSocket->alertsReceived_.emplace_back(
1581 *type, StringPiece(desc, std::strlen(desc)));
1586 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1590 AsyncSSLSocket* tsslSock;
1592 iov.iov_base = const_cast<char*>(in);
1594 memset(&msg, 0, sizeof(msg));
1598 auto appData = OpenSSLUtils::getBioAppData(b);
1601 tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1604 if (tsslSock->trackEor_ && tsslSock->minEorRawByteNo_ &&
1605 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1610 flags |= MSG_NOSIGNAL;
1614 if (tsslSock->corkCurrentWrite_) {
1619 auto result = tsslSock->sendSocketMessage(
1620 OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
1621 BIO_clear_retry_flags(b);
1622 if (!result.exception && result.writeReturn <= 0) {
1623 if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1624 BIO_set_retry_write(b);
1627 return int(result.writeReturn);
1630 int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) {
1634 BIO_clear_retry_flags(b);
1636 auto appData = OpenSSLUtils::getBioAppData(b);
1638 auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1640 if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) {
1641 VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock
1642 << ", reading pre-received data";
1644 Cursor cursor(sslSock->preReceivedData_.get());
1645 auto len = cursor.pullAtMost(out, outl);
1648 queue.append(std::move(sslSock->preReceivedData_));
1649 queue.trimStart(len);
1650 sslSock->preReceivedData_ = queue.move();
1653 auto result = recv(OpenSSLUtils::getBioFd(b, nullptr), out, outl, 0);
1654 if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) {
1655 BIO_set_retry_read(b);
1661 int AsyncSSLSocket::sslVerifyCallback(
1663 X509_STORE_CTX* x509Ctx) {
1664 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1665 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1666 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1668 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1669 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1670 return (self->handshakeCallback_) ?
1671 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1675 void AsyncSSLSocket::setPreReceivedData(std::unique_ptr<IOBuf> data) {
1676 CHECK(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED);
1677 CHECK(!preReceivedData_);
1678 preReceivedData_ = std::move(data);
1681 void AsyncSSLSocket::enableClientHelloParsing() {
1682 parseClientHello_ = true;
1683 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1686 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1687 SSL_set_msg_callback(ssl, nullptr);
1688 SSL_set_msg_callback_arg(ssl, nullptr);
1689 clientHelloInfo_->clientHelloBuf_.clear();
1692 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1699 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1701 sock->resetClientHelloParsing(ssl);
1704 if (contentType != SSL3_RT_HANDSHAKE) {
1711 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1712 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1714 Cursor cursor(clientHelloBuf.front());
1715 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1716 sock->resetClientHelloParsing(ssl);
1720 if (cursor.totalLength() < 3) {
1721 clientHelloBuf.trimEnd(len);
1722 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1726 uint32_t messageLength = cursor.read<uint8_t>();
1727 messageLength <<= 8;
1728 messageLength |= cursor.read<uint8_t>();
1729 messageLength <<= 8;
1730 messageLength |= cursor.read<uint8_t>();
1731 if (cursor.totalLength() < messageLength) {
1732 clientHelloBuf.trimEnd(len);
1733 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1737 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1738 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1740 cursor.skip(4); // gmt_unix_time
1741 cursor.skip(28); // random_bytes
1743 cursor.skip(cursor.read<uint8_t>()); // session_id
1745 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1746 for (int i = 0; i < cipherSuitesLength; i += 2) {
1747 sock->clientHelloInfo_->
1748 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1751 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1752 for (int i = 0; i < compressionMethodsLength; ++i) {
1753 sock->clientHelloInfo_->
1754 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1757 if (cursor.totalLength() > 0) {
1758 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1759 while (extensionsLength) {
1760 ssl::TLSExtension extensionType =
1761 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1762 sock->clientHelloInfo_->
1763 clientHelloExtensions_.push_back(extensionType);
1764 extensionsLength -= 2;
1765 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1766 extensionsLength -= 2;
1767 extensionsLength -= extensionDataLength;
1769 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1771 extensionDataLength -= 2;
1772 while (extensionDataLength) {
1773 ssl::HashAlgorithm hashAlg =
1774 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1775 ssl::SignatureAlgorithm sigAlg =
1776 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1777 extensionDataLength -= 2;
1778 sock->clientHelloInfo_->
1779 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1781 } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1783 extensionDataLength -= 1;
1784 while (extensionDataLength) {
1785 sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1786 cursor.readBE<uint16_t>());
1787 extensionDataLength -= 2;
1790 cursor.skip(extensionDataLength);
1794 } catch (std::out_of_range&) {
1795 // we'll use what we found and cleanup below.
1796 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1797 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1800 sock->resetClientHelloParsing(ssl);
1803 void AsyncSSLSocket::getSSLClientCiphers(
1804 std::string& clientCiphers,
1805 bool convertToString) const {
1806 std::string ciphers;
1808 if (parseClientHello_ == false
1809 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1815 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1823 bool nameFound = convertToString;
1825 if (convertToString) {
1826 const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1836 std::array<uint8_t, 2>{{
1837 static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1838 static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1840 /* append to ciphers = */ true);
1844 clientCiphers = std::move(ciphers);
1847 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1848 if (!parseClientHello_) {
1851 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1854 std::string AsyncSSLSocket::getSSLClientExts() const {
1855 if (!parseClientHello_) {
1858 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1861 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1862 if (!parseClientHello_) {
1866 std::string sigAlgs;
1867 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1868 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1870 sigAlgs.push_back(':');
1872 sigAlgs.append(folly::to<std::string>(
1873 clientHelloInfo_->clientHelloSigAlgs_[i].first));
1874 sigAlgs.push_back(',');
1875 sigAlgs.append(folly::to<std::string>(
1876 clientHelloInfo_->clientHelloSigAlgs_[i].second));
1882 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1883 if (!parseClientHello_) {
1886 return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1889 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1892 for (const auto& alert : alertsReceived_) {
1896 ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1902 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1903 char ciphersBuffer[1024];
1904 ciphersBuffer[0] = '\0';
1905 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1906 sharedCiphers = ciphersBuffer;
1909 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1910 serverCiphers = SSL_get_cipher_list(ssl_, 0);
1913 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1914 serverCiphers.append(":");
1915 serverCiphers.append(cipher);