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 <sys/types.h>
28 #include <folly/Bits.h>
29 #include <folly/SocketAddress.h>
30 #include <folly/SpinLock.h>
31 #include <folly/io/Cursor.h>
32 #include <folly/io/IOBuf.h>
33 #include <folly/portability/OpenSSL.h>
35 using folly::SocketAddress;
36 using folly::SSLContext;
38 using std::shared_ptr;
42 using folly::SpinLock;
43 using folly::SpinLockGuard;
44 using folly::io::Cursor;
45 using std::unique_ptr;
49 using folly::AsyncSocket;
50 using folly::AsyncSocketException;
51 using folly::AsyncSSLSocket;
52 using folly::Optional;
53 using folly::SSLContext;
54 // For OpenSSL portability API
55 using namespace folly::ssl;
56 using folly::ssl::OpenSSLUtils;
59 // We have one single dummy SSL context so that we can implement attach
60 // and detach methods in a thread safe fashion without modifying opnessl.
61 static SSLContext *dummyCtx = nullptr;
62 static SpinLock dummyCtxLock;
64 // If given min write size is less than this, buffer will be allocated on
65 // stack, otherwise it is allocated on heap
66 const size_t MAX_STACK_BUF_SIZE = 2048;
68 // This converts "illegal" shutdowns into ZERO_RETURN
69 inline bool zero_return(int error, int rc) {
70 return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
73 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
74 public AsyncSSLSocket::HandshakeCB {
77 AsyncSSLSocket *sslSocket_;
78 AsyncSSLSocket::ConnectCallback *callback_;
83 ~AsyncSSLSocketConnector() override {}
86 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
87 AsyncSocket::ConnectCallback *callback,
89 sslSocket_(sslSocket),
92 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
93 std::chrono::steady_clock::now().time_since_epoch()).count()) {
96 void connectSuccess() noexcept override {
97 VLOG(7) << "client socket connected";
99 int64_t timeoutLeft = 0;
101 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
102 std::chrono::steady_clock::now().time_since_epoch()).count();
104 timeoutLeft = timeout_ - (curTime - startTime_);
105 if (timeoutLeft <= 0) {
106 AsyncSocketException ex(
107 AsyncSocketException::TIMED_OUT,
108 folly::sformat("SSL connect timed out after {}ms", timeout_));
114 sslSocket_->sslConn(this, std::chrono::milliseconds(timeoutLeft));
117 void connectErr(const AsyncSocketException& ex) noexcept override {
118 VLOG(1) << "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 VLOG(1) << "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 void setup_SSL_CTX(SSL_CTX *ctx) {
156 #ifdef SSL_MODE_RELEASE_BUFFERS
157 SSL_CTX_set_mode(ctx,
158 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
159 SSL_MODE_ENABLE_PARTIAL_WRITE
160 | SSL_MODE_RELEASE_BUFFERS
163 SSL_CTX_set_mode(ctx,
164 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
165 SSL_MODE_ENABLE_PARTIAL_WRITE
168 // SSL_CTX_set_mode is a Macro
169 #ifdef SSL_MODE_WRITE_IOVEC
170 SSL_CTX_set_mode(ctx,
171 SSL_CTX_get_mode(ctx)
172 | SSL_MODE_WRITE_IOVEC);
177 // Note: This is a Leaky Meyer's Singleton. The reason we can't use a non-leaky
178 // thing is because we will be setting this BIO_METHOD* inside BIOs owned by
179 // various SSL objects which may get callbacks even during teardown. We may
180 // eventually try to fix this
181 static BIO_METHOD* getSSLBioMethod() {
182 static auto const instance = OpenSSLUtils::newSocketBioMethod().release();
186 void* initsslBioMethod(void) {
187 auto sslBioMethod = getSSLBioMethod();
188 // override the bwrite method for MSG_EOR support
189 OpenSSLUtils::setCustomBioWriteMethod(sslBioMethod, AsyncSSLSocket::bioWrite);
190 OpenSSLUtils::setCustomBioReadMethod(sslBioMethod, AsyncSSLSocket::bioRead);
192 // Note that the sslBioMethod.type and sslBioMethod.name are not
193 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
194 // then have specific handlings. The sslWriteBioWrite should be compatible
195 // with the one in openssl.
197 // Return something here to enable AsyncSSLSocket to call this method using
198 // a function-scoped static.
202 } // anonymous namespace
207 * Create a client AsyncSSLSocket
209 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
210 EventBase* evb, bool deferSecurityNegotiation) :
213 handshakeTimeout_(this, evb),
214 connectionTimeout_(this, evb) {
216 if (deferSecurityNegotiation) {
217 sslState_ = STATE_UNENCRYPTED;
222 * Create a server/client AsyncSSLSocket
224 AsyncSSLSocket::AsyncSSLSocket(
225 const shared_ptr<SSLContext>& ctx,
229 bool deferSecurityNegotiation)
230 : AsyncSocket(evb, fd),
233 handshakeTimeout_(this, evb),
234 connectionTimeout_(this, evb) {
235 noTransparentTls_ = true;
238 SSL_CTX_set_info_callback(
239 ctx_->getSSLCtx(), AsyncSSLSocket::sslInfoCallback);
241 if (deferSecurityNegotiation) {
242 sslState_ = STATE_UNENCRYPTED;
246 AsyncSSLSocket::AsyncSSLSocket(
247 const shared_ptr<SSLContext>& ctx,
248 AsyncSocket::UniquePtr oldAsyncSocket,
250 bool deferSecurityNegotiation)
251 : AsyncSocket(std::move(oldAsyncSocket)),
254 handshakeTimeout_(this, AsyncSocket::getEventBase()),
255 connectionTimeout_(this, AsyncSocket::getEventBase()) {
256 noTransparentTls_ = true;
259 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
260 AsyncSSLSocket::sslInfoCallback);
262 if (deferSecurityNegotiation) {
263 sslState_ = STATE_UNENCRYPTED;
267 #if FOLLY_OPENSSL_HAS_SNI
269 * Create a client AsyncSSLSocket and allow tlsext_hostname
270 * to be sent in Client Hello.
272 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
274 const std::string& serverName,
275 bool deferSecurityNegotiation) :
276 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
277 tlsextHostname_ = serverName;
281 * Create a client AsyncSSLSocket from an already connected fd
282 * and allow tlsext_hostname to be sent in Client Hello.
284 AsyncSSLSocket::AsyncSSLSocket(
285 const shared_ptr<SSLContext>& ctx,
288 const std::string& serverName,
289 bool deferSecurityNegotiation)
290 : AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
291 tlsextHostname_ = serverName;
293 #endif // FOLLY_OPENSSL_HAS_SNI
295 AsyncSSLSocket::~AsyncSSLSocket() {
296 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
297 << ", evb=" << eventBase_ << ", fd=" << fd_
298 << ", state=" << int(state_) << ", sslState="
299 << sslState_ << ", events=" << eventFlags_ << ")";
302 void AsyncSSLSocket::init() {
303 // Do this here to ensure we initialize this once before any use of
304 // AsyncSSLSocket instances and not as part of library load.
305 static const auto sslBioMethodInitializer = initsslBioMethod();
306 (void)sslBioMethodInitializer;
308 setup_SSL_CTX(ctx_->getSSLCtx());
311 void AsyncSSLSocket::closeNow() {
312 // Close the SSL connection.
313 if (ssl_ != nullptr && fd_ != -1) {
314 int rc = SSL_shutdown(ssl_);
316 rc = SSL_shutdown(ssl_);
323 if (sslSession_ != nullptr) {
324 SSL_SESSION_free(sslSession_);
325 sslSession_ = nullptr;
328 sslState_ = STATE_CLOSED;
330 if (handshakeTimeout_.isScheduled()) {
331 handshakeTimeout_.cancelTimeout();
334 DestructorGuard dg(this);
337 AsyncSocketException(
338 AsyncSocketException::END_OF_FILE,
339 "SSL connection closed locally"));
341 if (ssl_ != nullptr) {
347 AsyncSocket::closeNow();
350 void AsyncSSLSocket::shutdownWrite() {
351 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
353 // (Performing a full shutdown here is more desirable than doing nothing at
354 // all. The purpose of shutdownWrite() is normally to notify the other end
355 // of the connection that no more data will be sent. If we do nothing, the
356 // other end will never know that no more data is coming, and this may result
357 // in protocol deadlock.)
361 void AsyncSSLSocket::shutdownWriteNow() {
365 bool AsyncSSLSocket::good() const {
366 return (AsyncSocket::good() &&
367 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
368 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
371 // The TAsyncTransport definition of 'good' states that the transport is
372 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
373 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
374 // is connected but we haven't initiated the call to SSL_connect.
375 bool AsyncSSLSocket::connecting() const {
377 (AsyncSocket::connecting() ||
378 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
379 sslState_ == STATE_CONNECTING))));
382 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
383 const unsigned char* protoName = nullptr;
384 unsigned protoLength;
385 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
386 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
391 void AsyncSSLSocket::setEorTracking(bool track) {
392 if (isEorTrackingEnabled() != track) {
393 AsyncSocket::setEorTracking(track);
395 minEorRawByteNo_ = 0;
399 size_t AsyncSSLSocket::getRawBytesWritten() const {
400 // The bio(s) in the write path are in a chain
401 // each bio flushes to the next and finally written into the socket
402 // to get the rawBytesWritten on the socket,
403 // get the write bytes of the last bio
405 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
408 BIO* next = BIO_next(b);
409 while (next != nullptr) {
414 return BIO_number_written(b);
417 size_t AsyncSSLSocket::getRawBytesReceived() const {
419 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
423 return BIO_number_read(b);
427 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
428 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
429 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
430 << "events=" << eventFlags_ << ", server=" << short(server_)
431 << "): " << "sslAccept/Connect() called in invalid "
432 << "state, handshake callback " << handshakeCallback_
433 << ", new callback " << callback;
434 assert(!handshakeTimeout_.isScheduled());
435 sslState_ = STATE_ERROR;
437 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
438 "sslAccept() called with socket in invalid state");
440 handshakeEndTime_ = std::chrono::steady_clock::now();
442 callback->handshakeErr(this, ex);
445 failHandshake(__func__, ex);
448 void AsyncSSLSocket::sslAccept(
449 HandshakeCB* callback,
450 std::chrono::milliseconds timeout,
451 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
452 DestructorGuard dg(this);
453 assert(eventBase_->isInEventBaseThread());
454 verifyPeer_ = verifyPeer;
456 // Make sure we're in the uninitialized state
457 if (!server_ || (sslState_ != STATE_UNINIT &&
458 sslState_ != STATE_UNENCRYPTED) ||
459 handshakeCallback_ != nullptr) {
460 return invalidState(callback);
463 // Cache local and remote socket addresses to keep them available
464 // after socket file descriptor is closed.
465 if (cacheAddrOnFailure_ && -1 != getFd()) {
466 cacheLocalPeerAddr();
469 handshakeStartTime_ = std::chrono::steady_clock::now();
470 // Make end time at least >= start time.
471 handshakeEndTime_ = handshakeStartTime_;
473 sslState_ = STATE_ACCEPTING;
474 handshakeCallback_ = callback;
476 if (timeout > std::chrono::milliseconds::zero()) {
477 handshakeTimeout_.scheduleTimeout(timeout);
480 /* register for a read operation (waiting for CLIENT HELLO) */
481 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
483 checkForImmediateRead();
486 void AsyncSSLSocket::attachSSLContext(
487 const std::shared_ptr<SSLContext>& ctx) {
489 // Check to ensure we are in client mode. Changing a server's ssl
490 // context doesn't make sense since clients of that server would likely
491 // become confused when the server's context changes.
495 DCHECK(ctx->getSSLCtx());
498 // It's possible this could be attached before ssl_ is set up
503 // In order to call attachSSLContext, detachSSLContext must have been
504 // previously called.
505 // We need to update the initial_ctx if necessary
506 auto sslCtx = ctx->getSSLCtx();
507 SSL_CTX_up_ref(sslCtx);
509 // The 'initial_ctx' inside an SSL* points to the context that it was created
510 // with, which is also where session callbacks and servername callbacks
512 // When we switch to a different SSL_CTX, we want to update the initial_ctx as
513 // well so that any callbacks don't go to a different object
514 // NOTE: this will only work if we have access to ssl_ internals, so it may
516 // OpenSSL version >= 1.1.0
517 OpenSSLUtils::setSSLInitialCtx(ssl_, sslCtx);
518 // Detach sets the socket's context to the dummy context. Thus we must acquire
520 SpinLockGuard guard(dummyCtxLock);
521 SSL_set_SSL_CTX(ssl_, sslCtx);
524 void AsyncSSLSocket::detachSSLContext() {
527 // It's possible for this to be called before ssl_ has been
532 // The 'initial_ctx' inside an SSL* points to the context that it was created
533 // with, which is also where session callbacks and servername callbacks
535 // Detach the initial_ctx as well. It will be reattached in attachSSLContext
536 // it is used for session info.
537 // NOTE: this will only work if we have access to ssl_ internals, so it may
539 // OpenSSL version >= 1.1.0
540 SSL_CTX* initialCtx = OpenSSLUtils::getSSLInitialCtx(ssl_);
542 SSL_CTX_free(initialCtx);
543 OpenSSLUtils::setSSLInitialCtx(ssl_, nullptr);
546 SpinLockGuard guard(dummyCtxLock);
547 if (nullptr == dummyCtx) {
548 // We need to lazily initialize the dummy context so we don't
549 // accidentally override any programmatic settings to openssl
550 dummyCtx = new SSLContext;
552 // We must remove this socket's references to its context right now
553 // since this socket could get passed to any thread. If the context has
554 // had its locking disabled, just doing a set in attachSSLContext()
555 // would not be thread safe.
556 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
559 #if FOLLY_OPENSSL_HAS_SNI
560 void AsyncSSLSocket::switchServerSSLContext(
561 const std::shared_ptr<SSLContext>& handshakeCtx) {
563 if (sslState_ != STATE_ACCEPTING) {
564 // We log it here and allow the switch.
565 // It should not affect our re-negotiation support (which
566 // is not supported now).
567 VLOG(6) << "fd=" << getFd()
568 << " renegotation detected when switching SSL_CTX";
571 setup_SSL_CTX(handshakeCtx->getSSLCtx());
572 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
573 AsyncSSLSocket::sslInfoCallback);
574 handshakeCtx_ = handshakeCtx;
575 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
578 bool AsyncSSLSocket::isServerNameMatch() const {
585 SSL_SESSION *ss = SSL_get_session(ssl_);
590 auto tlsextHostname = SSL_SESSION_get0_hostname(ss);
591 return (tlsextHostname && !tlsextHostname_.compare(tlsextHostname));
594 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
595 tlsextHostname_ = std::move(serverName);
598 #endif // FOLLY_OPENSSL_HAS_SNI
600 void AsyncSSLSocket::timeoutExpired(
601 std::chrono::milliseconds timeout) noexcept {
602 if (state_ == StateEnum::ESTABLISHED &&
603 (sslState_ == STATE_CACHE_LOOKUP || sslState_ == STATE_ASYNC_PENDING)) {
604 sslState_ = STATE_ERROR;
605 // We are expecting a callback in restartSSLAccept. The cache lookup
606 // and rsa-call necessarily have pointers to this ssl socket, so delay
607 // the cleanup until he calls us back.
608 } else if (state_ == StateEnum::CONNECTING) {
609 assert(sslState_ == STATE_CONNECTING);
610 DestructorGuard dg(this);
611 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
612 "Fallback connect timed out during TFO");
613 failHandshake(__func__, ex);
615 assert(state_ == StateEnum::ESTABLISHED &&
616 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
617 DestructorGuard dg(this);
618 AsyncSocketException ex(
619 AsyncSocketException::TIMED_OUT,
621 "SSL {} timed out after {}ms",
622 (sslState_ == STATE_CONNECTING) ? "connect" : "accept",
624 failHandshake(__func__, ex);
628 int AsyncSSLSocket::getSSLExDataIndex() {
629 static auto index = SSL_get_ex_new_index(
630 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
634 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
635 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
636 getSSLExDataIndex()));
639 void AsyncSSLSocket::failHandshake(const char* /* fn */,
640 const AsyncSocketException& ex) {
642 if (handshakeTimeout_.isScheduled()) {
643 handshakeTimeout_.cancelTimeout();
645 invokeHandshakeErr(ex);
649 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
650 handshakeEndTime_ = std::chrono::steady_clock::now();
651 if (handshakeCallback_ != nullptr) {
652 HandshakeCB* callback = handshakeCallback_;
653 handshakeCallback_ = nullptr;
654 callback->handshakeErr(this, ex);
658 void AsyncSSLSocket::invokeHandshakeCB() {
659 handshakeEndTime_ = std::chrono::steady_clock::now();
660 if (handshakeTimeout_.isScheduled()) {
661 handshakeTimeout_.cancelTimeout();
663 if (handshakeCallback_) {
664 HandshakeCB* callback = handshakeCallback_;
665 handshakeCallback_ = nullptr;
666 callback->handshakeSuc(this);
670 void AsyncSSLSocket::cacheLocalPeerAddr() {
671 SocketAddress address;
673 getLocalAddress(&address);
674 getPeerAddress(&address);
675 } catch (const std::system_error& e) {
676 // The handle can be still valid while the connection is already closed.
677 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
683 void AsyncSSLSocket::connect(
684 ConnectCallback* callback,
685 const folly::SocketAddress& address,
687 const OptionMap& options,
688 const folly::SocketAddress& bindAddr) noexcept {
689 auto timeoutChrono = std::chrono::milliseconds(timeout);
690 connect(callback, address, timeoutChrono, timeoutChrono, options, bindAddr);
693 void AsyncSSLSocket::connect(
694 ConnectCallback* callback,
695 const folly::SocketAddress& address,
696 std::chrono::milliseconds connectTimeout,
697 std::chrono::milliseconds totalConnectTimeout,
698 const OptionMap& options,
699 const folly::SocketAddress& bindAddr) noexcept {
701 assert(state_ == StateEnum::UNINIT);
702 assert(sslState_ == STATE_UNINIT);
703 noTransparentTls_ = true;
704 totalConnectTimeout_ = totalConnectTimeout;
705 AsyncSSLSocketConnector* connector = new AsyncSSLSocketConnector(
706 this, callback, int(totalConnectTimeout.count()));
707 AsyncSocket::connect(
708 connector, address, int(connectTimeout.count()), options, bindAddr);
711 bool AsyncSSLSocket::needsPeerVerification() const {
712 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
713 return ctx_->needsPeerVerification();
716 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
717 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
720 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
721 // apply the settings specified in verifyPeer_
722 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
723 if(ctx_->needsPeerVerification()) {
724 SSL_set_verify(ssl, ctx_->getVerificationMode(),
725 AsyncSSLSocket::sslVerifyCallback);
728 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
729 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
730 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
731 AsyncSSLSocket::sslVerifyCallback);
736 bool AsyncSSLSocket::setupSSLBio() {
737 auto sslBio = BIO_new(getSSLBioMethod());
743 OpenSSLUtils::setBioAppData(sslBio, this);
744 OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE);
745 SSL_set_bio(ssl_, sslBio, sslBio);
749 void AsyncSSLSocket::sslConn(
750 HandshakeCB* callback,
751 std::chrono::milliseconds timeout,
752 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
753 DestructorGuard dg(this);
754 assert(eventBase_->isInEventBaseThread());
756 // Cache local and remote socket addresses to keep them available
757 // after socket file descriptor is closed.
758 if (cacheAddrOnFailure_ && -1 != getFd()) {
759 cacheLocalPeerAddr();
762 verifyPeer_ = verifyPeer;
764 // Make sure we're in the uninitialized state
765 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
766 STATE_UNENCRYPTED) ||
767 handshakeCallback_ != nullptr) {
768 return invalidState(callback);
771 sslState_ = STATE_CONNECTING;
772 handshakeCallback_ = callback;
775 ssl_ = ctx_->createSSL();
776 } catch (std::exception &e) {
777 sslState_ = STATE_ERROR;
778 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
779 "error calling SSLContext::createSSL()");
780 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
781 << fd_ << "): " << e.what();
782 return failHandshake(__func__, ex);
785 if (!setupSSLBio()) {
786 sslState_ = STATE_ERROR;
787 AsyncSocketException ex(
788 AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
789 return failHandshake(__func__, ex);
792 applyVerificationOptions(ssl_);
794 if (sslSession_ != nullptr) {
795 sessionResumptionAttempted_ = true;
796 SSL_set_session(ssl_, sslSession_);
797 SSL_SESSION_free(sslSession_);
798 sslSession_ = nullptr;
800 #if FOLLY_OPENSSL_HAS_SNI
801 if (tlsextHostname_.size()) {
802 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
806 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
808 handshakeConnectTimeout_ = timeout;
812 // This could be called multiple times, during normal ssl connections
813 // and after TFO fallback.
814 void AsyncSSLSocket::startSSLConnect() {
815 handshakeStartTime_ = std::chrono::steady_clock::now();
816 // Make end time at least >= start time.
817 handshakeEndTime_ = handshakeStartTime_;
818 if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) {
819 handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
824 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
825 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
826 return SSL_get1_session(ssl_);
832 const SSL* AsyncSSLSocket::getSSL() const {
836 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
837 sslSession_ = session;
838 if (!takeOwnership && session != nullptr) {
839 // Increment the reference count
840 // This API exists in BoringSSL and OpenSSL 1.1.0
841 SSL_SESSION_up_ref(session);
845 void AsyncSSLSocket::getSelectedNextProtocol(
846 const unsigned char** protoName,
848 SSLContext::NextProtocolType* protoType) const {
849 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
850 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
851 "NPN not supported");
855 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
856 const unsigned char** protoName,
858 SSLContext::NextProtocolType* protoType) const {
859 *protoName = nullptr;
861 #if FOLLY_OPENSSL_HAS_ALPN
862 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
865 *protoType = SSLContext::NextProtocolType::ALPN;
870 #ifdef OPENSSL_NPN_NEGOTIATED
871 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
873 *protoType = SSLContext::NextProtocolType::NPN;
882 bool AsyncSSLSocket::getSSLSessionReused() const {
883 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
884 return SSL_session_reused(ssl_);
889 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
890 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
894 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
895 if (ssl == nullptr) {
898 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
899 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
905 const char *AsyncSSLSocket::getSSLServerName() const {
906 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
907 return getSSLServerNameFromSSL(ssl_);
909 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
910 "SNI not supported");
914 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
915 return getSSLServerNameFromSSL(ssl_);
918 int AsyncSSLSocket::getSSLVersion() const {
919 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
922 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
923 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
925 int nid = X509_get_signature_nid(cert);
926 return OBJ_nid2ln(nid);
931 int AsyncSSLSocket::getSSLCertSize() const {
933 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
935 EVP_PKEY *key = X509_get_pubkey(cert);
936 certSize = EVP_PKEY_bits(key);
942 const X509* AsyncSSLSocket::getSelfCert() const {
943 return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
946 bool AsyncSSLSocket::willBlock(int ret,
948 unsigned long* errErrorOut) noexcept {
950 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
951 if (error == SSL_ERROR_WANT_READ) {
952 // Register for read event if not already.
953 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
955 } else if (error == SSL_ERROR_WANT_WRITE) {
956 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
957 << ", state=" << int(state_) << ", sslState="
958 << sslState_ << ", events=" << eventFlags_ << "): "
959 << "SSL_ERROR_WANT_WRITE";
960 // Register for write event if not already.
961 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
963 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
964 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
965 // We will block but we can't register our own socket. The callback that
966 // triggered this code will re-call handleAccept at the appropriate time.
968 // We can only get here if the linked libssl.so has support for this feature
969 // as well, otherwise SSL_get_error cannot return our error code.
970 sslState_ = STATE_CACHE_LOOKUP;
972 // Unregister for all events while blocked here
973 updateEventRegistration(EventHandler::NONE,
974 EventHandler::READ | EventHandler::WRITE);
976 // The timeout (if set) keeps running here
980 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
981 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
983 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
984 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
987 // Our custom openssl function has kicked off an async request to do
988 // rsa/ecdsa private key operation. When that call returns, a callback will
989 // be invoked that will re-call handleAccept.
990 sslState_ = STATE_ASYNC_PENDING;
992 // Unregister for all events while blocked here
993 updateEventRegistration(
995 EventHandler::READ | EventHandler::WRITE
998 // The timeout (if set) keeps running here
1001 unsigned long lastError = *errErrorOut = ERR_get_error();
1002 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1003 << "state=" << state_ << ", "
1004 << "sslState=" << sslState_ << ", "
1005 << "events=" << std::hex << eventFlags_ << "): "
1006 << "SSL error: " << error << ", "
1007 << "errno: " << errno << ", "
1008 << "ret: " << ret << ", "
1009 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
1010 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
1011 << "func: " << ERR_func_error_string(lastError) << ", "
1012 << "reason: " << ERR_reason_error_string(lastError);
1017 void AsyncSSLSocket::checkForImmediateRead() noexcept {
1018 // openssl may have buffered data that it read from the socket already.
1019 // In this case we have to process it immediately, rather than waiting for
1020 // the socket to become readable again.
1021 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
1022 AsyncSocket::handleRead();
1024 AsyncSocket::checkForImmediateRead();
1029 AsyncSSLSocket::restartSSLAccept()
1031 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
1032 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1033 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1034 DestructorGuard dg(this);
1036 sslState_ == STATE_CACHE_LOOKUP ||
1037 sslState_ == STATE_ASYNC_PENDING ||
1038 sslState_ == STATE_ERROR ||
1039 sslState_ == STATE_CLOSED);
1040 if (sslState_ == STATE_CLOSED) {
1041 // I sure hope whoever closed this socket didn't delete it already,
1042 // but this is not strictly speaking an error
1045 if (sslState_ == STATE_ERROR) {
1046 // go straight to fail if timeout expired during lookup
1047 AsyncSocketException ex(
1048 AsyncSocketException::TIMED_OUT, "SSL accept timed out");
1049 failHandshake(__func__, ex);
1052 sslState_ = STATE_ACCEPTING;
1053 this->handleAccept();
1057 AsyncSSLSocket::handleAccept() noexcept {
1058 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1059 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1060 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1062 assert(state_ == StateEnum::ESTABLISHED &&
1063 sslState_ == STATE_ACCEPTING);
1065 /* lazily create the SSL structure */
1067 ssl_ = ctx_->createSSL();
1068 } catch (std::exception &e) {
1069 sslState_ = STATE_ERROR;
1070 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1071 "error calling SSLContext::createSSL()");
1072 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1073 << ", fd=" << fd_ << "): " << e.what();
1074 return failHandshake(__func__, ex);
1077 if (!setupSSLBio()) {
1078 sslState_ = STATE_ERROR;
1079 AsyncSocketException ex(
1080 AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1081 return failHandshake(__func__, ex);
1084 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1086 applyVerificationOptions(ssl_);
1089 if (server_ && parseClientHello_) {
1090 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1091 SSL_set_msg_callback_arg(ssl_, this);
1094 int ret = SSL_accept(ssl_);
1097 unsigned long errError;
1098 int errnoCopy = errno;
1099 if (willBlock(ret, &sslError, &errError)) {
1102 sslState_ = STATE_ERROR;
1103 SSLException ex(sslError, errError, ret, errnoCopy);
1104 return failHandshake(__func__, ex);
1108 handshakeComplete_ = true;
1109 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1111 // Move into STATE_ESTABLISHED in the normal case that we are in
1113 sslState_ = STATE_ESTABLISHED;
1115 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1116 << " successfully accepted; state=" << int(state_)
1117 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1119 // Remember the EventBase we are attached to, before we start invoking any
1120 // callbacks (since the callbacks may call detachEventBase()).
1121 EventBase* originalEventBase = eventBase_;
1123 // Call the accept callback.
1124 invokeHandshakeCB();
1126 // Note that the accept callback may have changed our state.
1127 // (set or unset the read callback, called write(), closed the socket, etc.)
1128 // The following code needs to handle these situations correctly.
1130 // If the socket has been closed, readCallback_ and writeReqHead_ will
1131 // always be nullptr, so that will prevent us from trying to read or write.
1133 // The main thing to check for is if eventBase_ is still originalEventBase.
1134 // If not, we have been detached from this event base, so we shouldn't
1135 // perform any more operations.
1136 if (eventBase_ != originalEventBase) {
1140 AsyncSocket::handleInitialReadWrite();
1144 AsyncSSLSocket::handleConnect() noexcept {
1145 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1146 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1147 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1149 if (state_ < StateEnum::ESTABLISHED) {
1150 return AsyncSocket::handleConnect();
1154 (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1155 sslState_ == STATE_CONNECTING);
1158 auto originalState = state_;
1159 int ret = SSL_connect(ssl_);
1162 unsigned long errError;
1163 int errnoCopy = errno;
1164 if (willBlock(ret, &sslError, &errError)) {
1165 // We fell back to connecting state due to TFO
1166 if (state_ == StateEnum::CONNECTING) {
1167 DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1168 if (handshakeTimeout_.isScheduled()) {
1169 handshakeTimeout_.cancelTimeout();
1174 sslState_ = STATE_ERROR;
1175 SSLException ex(sslError, errError, ret, errnoCopy);
1176 return failHandshake(__func__, ex);
1180 handshakeComplete_ = true;
1181 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1183 // Move into STATE_ESTABLISHED in the normal case that we are in
1184 // STATE_CONNECTING.
1185 sslState_ = STATE_ESTABLISHED;
1187 VLOG(3) << "AsyncSSLSocket " << this << ": "
1188 << "fd " << fd_ << " successfully connected; "
1189 << "state=" << int(state_) << ", sslState=" << sslState_
1190 << ", events=" << eventFlags_;
1192 // Remember the EventBase we are attached to, before we start invoking any
1193 // callbacks (since the callbacks may call detachEventBase()).
1194 EventBase* originalEventBase = eventBase_;
1196 // Call the handshake callback.
1197 invokeHandshakeCB();
1199 // Note that the connect callback may have changed our state.
1200 // (set or unset the read callback, called write(), closed the socket, etc.)
1201 // The following code needs to handle these situations correctly.
1203 // If the socket has been closed, readCallback_ and writeReqHead_ will
1204 // always be nullptr, so that will prevent us from trying to read or write.
1206 // The main thing to check for is if eventBase_ is still originalEventBase.
1207 // If not, we have been detached from this event base, so we shouldn't
1208 // perform any more operations.
1209 if (eventBase_ != originalEventBase) {
1213 AsyncSocket::handleInitialReadWrite();
1216 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1217 connectionTimeout_.cancelTimeout();
1218 AsyncSocket::invokeConnectErr(ex);
1219 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1220 if (handshakeTimeout_.isScheduled()) {
1221 handshakeTimeout_.cancelTimeout();
1223 // If we fell back to connecting state during TFO and the connection
1224 // failed, it would be an SSL failure as well.
1225 invokeHandshakeErr(ex);
1229 void AsyncSSLSocket::invokeConnectSuccess() {
1230 connectionTimeout_.cancelTimeout();
1231 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1232 assert(tfoAttempted_);
1233 // If we failed TFO, we'd fall back to trying to connect the socket,
1234 // to setup things like timeouts.
1237 // still invoke the base class since it re-sets the connect time.
1238 AsyncSocket::invokeConnectSuccess();
1241 void AsyncSSLSocket::scheduleConnectTimeout() {
1242 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1243 // We fell back from TFO, and need to set the timeouts.
1244 // We will not have a connect callback in this case, thus if the timer
1245 // expires we would have no-one to notify.
1246 // Thus we should reset even the connect timers to point to the handshake
1248 assert(connectCallback_ == nullptr);
1249 // We use a different connect timeout here than the handshake timeout, so
1250 // that we can disambiguate the 2 timers.
1251 if (connectTimeout_.count() > 0) {
1252 if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1253 throw AsyncSocketException(
1254 AsyncSocketException::INTERNAL_ERROR,
1255 withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1260 AsyncSocket::scheduleConnectTimeout();
1263 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1264 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1265 // turn on the buffer movable in openssl
1266 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1267 callback != nullptr && callback->isBufferMovable()) {
1268 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1269 isBufferMovable_ = true;
1273 AsyncSocket::setReadCB(callback);
1276 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1277 bufferMovableEnabled_ = enabled;
1280 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1281 CHECK(readCallback_);
1282 if (isBufferMovable_) {
1286 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1287 readCallback_->getReadBuffer(buf, buflen);
1292 AsyncSSLSocket::handleRead() noexcept {
1293 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1294 << ", state=" << int(state_) << ", "
1295 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1296 if (state_ < StateEnum::ESTABLISHED) {
1297 return AsyncSocket::handleRead();
1301 if (sslState_ == STATE_ACCEPTING) {
1306 else if (sslState_ == STATE_CONNECTING) {
1313 AsyncSocket::handleRead();
1316 AsyncSocket::ReadResult
1317 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1318 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1319 << ", buflen=" << *buflen;
1321 if (sslState_ == STATE_UNENCRYPTED) {
1322 return AsyncSocket::performRead(buf, buflen, offset);
1326 if (!isBufferMovable_) {
1327 bytes = SSL_read(ssl_, *buf, int(*buflen));
1329 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1331 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1335 if (server_ && renegotiateAttempted_) {
1336 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1337 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1338 << "): client intitiated SSL renegotiation not permitted";
1341 std::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1344 int error = SSL_get_error(ssl_, bytes);
1345 if (error == SSL_ERROR_WANT_READ) {
1346 // The caller will register for read event if not already.
1347 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1348 return ReadResult(READ_BLOCKING);
1350 return ReadResult(READ_ERROR);
1352 } else if (error == SSL_ERROR_WANT_WRITE) {
1353 // TODO: Even though we are attempting to read data, SSL_read() may
1354 // need to write data if renegotiation is being performed. We currently
1355 // don't support this and just fail the read.
1356 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1357 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1358 << "): unsupported SSL renegotiation during read";
1361 std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1363 if (zero_return(error, bytes)) {
1364 return ReadResult(bytes);
1366 auto errError = ERR_get_error();
1367 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1368 << "state=" << state_ << ", "
1369 << "sslState=" << sslState_ << ", "
1370 << "events=" << std::hex << eventFlags_ << "): "
1371 << "bytes: " << bytes << ", "
1372 << "error: " << error << ", "
1373 << "errno: " << errno << ", "
1374 << "func: " << ERR_func_error_string(errError) << ", "
1375 << "reason: " << ERR_reason_error_string(errError);
1378 std::make_unique<SSLException>(error, errError, bytes, errno));
1381 appBytesReceived_ += bytes;
1382 return ReadResult(bytes);
1386 void AsyncSSLSocket::handleWrite() noexcept {
1387 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1388 << ", state=" << int(state_) << ", "
1389 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1390 if (state_ < StateEnum::ESTABLISHED) {
1391 return AsyncSocket::handleWrite();
1394 if (sslState_ == STATE_ACCEPTING) {
1400 if (sslState_ == STATE_CONNECTING) {
1407 AsyncSocket::handleWrite();
1410 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1411 if (error == SSL_ERROR_WANT_READ) {
1412 // Even though we are attempting to write data, SSL_write() may
1413 // need to read data if renegotiation is being performed. We currently
1414 // don't support this and just fail the write.
1415 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1416 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1418 << "unsupported SSL renegotiation during write";
1421 std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1423 if (zero_return(error, rc)) {
1424 return WriteResult(0);
1426 auto errError = ERR_get_error();
1427 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1428 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1429 << "SSL error: " << error << ", errno: " << errno
1430 << ", func: " << ERR_func_error_string(errError)
1431 << ", reason: " << ERR_reason_error_string(errError);
1434 std::make_unique<SSLException>(error, errError, rc, errno));
1438 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1442 uint32_t* countWritten,
1443 uint32_t* partialWritten) {
1444 if (sslState_ == STATE_UNENCRYPTED) {
1445 return AsyncSocket::performWrite(
1446 vec, count, flags, countWritten, partialWritten);
1448 if (sslState_ != STATE_ESTABLISHED) {
1449 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1450 << ", sslState=" << sslState_
1451 << ", events=" << eventFlags_ << "): "
1452 << "TODO: AsyncSSLSocket currently does not support calling "
1453 << "write() before the handshake has fully completed";
1455 WRITE_ERROR, std::make_unique<SSLException>(SSLError::EARLY_WRITE));
1458 // Declare a buffer used to hold small write requests. It could point to a
1459 // memory block either on stack or on heap. If it is on heap, we release it
1460 // manually when scope exits
1461 char* combinedBuf{nullptr};
1463 // Note, always keep this check consistent with what we do below
1464 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1465 delete[] combinedBuf;
1470 *partialWritten = 0;
1471 ssize_t totalWritten = 0;
1472 size_t bytesStolenFromNextBuffer = 0;
1473 for (uint32_t i = 0; i < count; i++) {
1474 const iovec* v = vec + i;
1475 size_t offset = bytesStolenFromNextBuffer;
1476 bytesStolenFromNextBuffer = 0;
1477 size_t len = v->iov_len - offset;
1483 buf = ((const char*)v->iov_base) + offset;
1486 uint32_t buffersStolen = 0;
1487 auto sslWriteBuf = buf;
1488 if ((len < minWriteSize_) && ((i + 1) < count)) {
1489 // Combine this buffer with part or all of the next buffers in
1490 // order to avoid really small-grained calls to SSL_write().
1491 // Each call to SSL_write() produces a separate record in
1492 // the egress SSL stream, and we've found that some low-end
1493 // mobile clients can't handle receiving an HTTP response
1494 // header and the first part of the response body in two
1495 // separate SSL records (even if those two records are in
1496 // the same TCP packet).
1498 if (combinedBuf == nullptr) {
1499 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1500 // Allocate the buffer on heap
1501 combinedBuf = new char[minWriteSize_];
1503 // Allocate the buffer on stack
1504 combinedBuf = (char*)alloca(minWriteSize_);
1507 assert(combinedBuf != nullptr);
1508 sslWriteBuf = combinedBuf;
1510 memcpy(combinedBuf, buf, len);
1512 // INVARIANT: i + buffersStolen == complete chunks serialized
1513 uint32_t nextIndex = i + buffersStolen + 1;
1514 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1515 minWriteSize_ - len);
1516 if (bytesStolenFromNextBuffer > 0) {
1517 assert(vec[nextIndex].iov_base != nullptr);
1520 vec[nextIndex].iov_base,
1521 bytesStolenFromNextBuffer);
1523 len += bytesStolenFromNextBuffer;
1524 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1525 // couldn't steal the whole buffer
1528 bytesStolenFromNextBuffer = 0;
1531 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1534 // Advance any empty buffers immediately after.
1535 if (bytesStolenFromNextBuffer == 0) {
1536 while ((i + buffersStolen + 1) < count &&
1537 vec[i + buffersStolen + 1].iov_len == 0) {
1543 isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1544 bytes = eorAwareSSLWrite(
1548 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1551 int error = SSL_get_error(ssl_, int(bytes));
1552 if (error == SSL_ERROR_WANT_WRITE) {
1553 // The caller will register for write event if not already.
1554 *partialWritten = uint32_t(offset);
1555 return WriteResult(totalWritten);
1557 auto writeResult = interpretSSLError(int(bytes), error);
1558 if (writeResult.writeReturn < 0) {
1560 } // else fall through to below to correctly record totalWritten
1563 totalWritten += bytes;
1565 if (bytes == (ssize_t)len) {
1566 // The full iovec is written.
1567 (*countWritten) += 1 + buffersStolen;
1571 bytes += offset; // adjust bytes to account for all of v
1572 while (bytes >= (ssize_t)v->iov_len) {
1573 // We combined this buf with part or all of the next one, and
1574 // we managed to write all of this buf but not all of the bytes
1575 // from the next one that we'd hoped to write.
1576 bytes -= v->iov_len;
1580 *partialWritten = uint32_t(bytes);
1581 return WriteResult(totalWritten);
1585 return WriteResult(totalWritten);
1588 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1590 if (eor && isEorTrackingEnabled()) {
1591 if (appEorByteNo_) {
1592 // cannot track for more than one app byte EOR
1593 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1595 appEorByteNo_ = appBytesWritten_ + n;
1598 // 1. It is fine to keep updating minEorRawByteNo_.
1599 // 2. It is _min_ in the sense that SSL record will add some overhead.
1600 minEorRawByteNo_ = getRawBytesWritten() + n;
1603 n = sslWriteImpl(ssl, buf, n);
1605 appBytesWritten_ += n;
1606 if (appEorByteNo_) {
1607 if (getRawBytesWritten() >= minEorRawByteNo_) {
1608 minEorRawByteNo_ = 0;
1610 if(appBytesWritten_ == appEorByteNo_) {
1613 CHECK(appBytesWritten_ < appEorByteNo_);
1620 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1621 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1622 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1623 sslSocket->renegotiateAttempted_ = true;
1625 if (where & SSL_CB_READ_ALERT) {
1626 const char* type = SSL_alert_type_string(ret);
1628 const char* desc = SSL_alert_desc_string(ret);
1629 sslSocket->alertsReceived_.emplace_back(
1630 *type, StringPiece(desc, std::strlen(desc)));
1635 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1638 AsyncSSLSocket* tsslSock;
1640 iov.iov_base = const_cast<char*>(in);
1641 iov.iov_len = size_t(inl);
1642 memset(&msg, 0, sizeof(msg));
1646 auto appData = OpenSSLUtils::getBioAppData(b);
1649 tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1652 WriteFlags flags = WriteFlags::NONE;
1653 if (tsslSock->isEorTrackingEnabled() && tsslSock->minEorRawByteNo_ &&
1654 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1655 flags |= WriteFlags::EOR;
1658 if (tsslSock->corkCurrentWrite_) {
1659 flags |= WriteFlags::CORK;
1662 int msg_flags = tsslSock->getSendMsgParamsCB()->getFlags(flags);
1663 msg.msg_controllen =
1664 tsslSock->getSendMsgParamsCB()->getAncillaryDataSize(flags);
1665 CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
1666 msg.msg_controllen);
1667 if (msg.msg_controllen != 0) {
1668 msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
1669 tsslSock->getSendMsgParamsCB()->getAncillaryData(flags, msg.msg_control);
1672 auto result = tsslSock->sendSocketMessage(
1673 OpenSSLUtils::getBioFd(b, nullptr), &msg, msg_flags);
1674 BIO_clear_retry_flags(b);
1675 if (!result.exception && result.writeReturn <= 0) {
1676 if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1677 BIO_set_retry_write(b);
1680 return int(result.writeReturn);
1683 int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) {
1687 BIO_clear_retry_flags(b);
1689 auto appData = OpenSSLUtils::getBioAppData(b);
1691 auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1693 if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) {
1694 VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock
1695 << ", reading pre-received data";
1697 Cursor cursor(sslSock->preReceivedData_.get());
1698 auto len = cursor.pullAtMost(out, outl);
1701 queue.append(std::move(sslSock->preReceivedData_));
1702 queue.trimStart(len);
1703 sslSock->preReceivedData_ = queue.move();
1704 return static_cast<int>(len);
1706 auto result = int(recv(OpenSSLUtils::getBioFd(b, nullptr), out, outl, 0));
1707 if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) {
1708 BIO_set_retry_read(b);
1714 int AsyncSSLSocket::sslVerifyCallback(
1716 X509_STORE_CTX* x509Ctx) {
1717 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1718 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1719 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1721 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1722 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1723 return (self->handshakeCallback_) ?
1724 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1728 void AsyncSSLSocket::enableClientHelloParsing() {
1729 parseClientHello_ = true;
1730 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1733 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1734 SSL_set_msg_callback(ssl, nullptr);
1735 SSL_set_msg_callback_arg(ssl, nullptr);
1736 clientHelloInfo_->clientHelloBuf_.clear();
1739 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1746 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1748 sock->resetClientHelloParsing(ssl);
1751 if (contentType != SSL3_RT_HANDSHAKE) {
1758 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1759 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1761 Cursor cursor(clientHelloBuf.front());
1762 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1763 sock->resetClientHelloParsing(ssl);
1767 if (cursor.totalLength() < 3) {
1768 clientHelloBuf.trimEnd(len);
1769 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1773 uint32_t messageLength = cursor.read<uint8_t>();
1774 messageLength <<= 8;
1775 messageLength |= cursor.read<uint8_t>();
1776 messageLength <<= 8;
1777 messageLength |= cursor.read<uint8_t>();
1778 if (cursor.totalLength() < messageLength) {
1779 clientHelloBuf.trimEnd(len);
1780 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1784 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1785 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1787 cursor.skip(4); // gmt_unix_time
1788 cursor.skip(28); // random_bytes
1790 cursor.skip(cursor.read<uint8_t>()); // session_id
1792 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1793 for (int i = 0; i < cipherSuitesLength; i += 2) {
1794 sock->clientHelloInfo_->
1795 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1798 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1799 for (int i = 0; i < compressionMethodsLength; ++i) {
1800 sock->clientHelloInfo_->
1801 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1804 if (cursor.totalLength() > 0) {
1805 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1806 while (extensionsLength) {
1807 ssl::TLSExtension extensionType =
1808 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1809 sock->clientHelloInfo_->
1810 clientHelloExtensions_.push_back(extensionType);
1811 extensionsLength -= 2;
1812 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1813 extensionsLength -= 2;
1814 extensionsLength -= extensionDataLength;
1816 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1818 extensionDataLength -= 2;
1819 while (extensionDataLength) {
1820 ssl::HashAlgorithm hashAlg =
1821 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1822 ssl::SignatureAlgorithm sigAlg =
1823 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1824 extensionDataLength -= 2;
1825 sock->clientHelloInfo_->
1826 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1828 } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1830 extensionDataLength -= 1;
1831 while (extensionDataLength) {
1832 sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1833 cursor.readBE<uint16_t>());
1834 extensionDataLength -= 2;
1837 cursor.skip(extensionDataLength);
1841 } catch (std::out_of_range&) {
1842 // we'll use what we found and cleanup below.
1843 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1844 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1847 sock->resetClientHelloParsing(ssl);
1850 void AsyncSSLSocket::getSSLClientCiphers(
1851 std::string& clientCiphers,
1852 bool convertToString) const {
1853 std::string ciphers;
1855 if (parseClientHello_ == false
1856 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1862 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1870 bool nameFound = convertToString;
1872 if (convertToString) {
1873 const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1883 std::array<uint8_t, 2>{{
1884 static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1885 static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1887 /* append to ciphers = */ true);
1891 clientCiphers = std::move(ciphers);
1894 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1895 if (!parseClientHello_) {
1898 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1901 std::string AsyncSSLSocket::getSSLClientExts() const {
1902 if (!parseClientHello_) {
1905 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1908 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1909 if (!parseClientHello_) {
1913 std::string sigAlgs;
1914 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1915 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1917 sigAlgs.push_back(':');
1919 sigAlgs.append(folly::to<std::string>(
1920 clientHelloInfo_->clientHelloSigAlgs_[i].first));
1921 sigAlgs.push_back(',');
1922 sigAlgs.append(folly::to<std::string>(
1923 clientHelloInfo_->clientHelloSigAlgs_[i].second));
1929 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1930 if (!parseClientHello_) {
1933 return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1936 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1939 for (const auto& alert : alertsReceived_) {
1943 ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1949 void AsyncSSLSocket::setSSLCertVerificationAlert(std::string alert) {
1950 sslVerificationAlert_ = std::move(alert);
1953 std::string AsyncSSLSocket::getSSLCertVerificationAlert() const {
1954 return sslVerificationAlert_;
1957 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1958 char ciphersBuffer[1024];
1959 ciphersBuffer[0] = '\0';
1960 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1961 sharedCiphers = ciphersBuffer;
1964 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1965 serverCiphers = SSL_get_cipher_list(ssl_, 0);
1968 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1969 serverCiphers.append(":");
1970 serverCiphers.append(cipher);