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/err.h>
26 #include <openssl/asn1.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(
110 AsyncSocketException::TIMED_OUT,
111 folly::sformat("SSL connect timed out after {}ms", timeout_));
117 sslSocket_->sslConn(this, std::chrono::milliseconds(timeoutLeft));
120 void connectErr(const AsyncSocketException& ex) noexcept override {
121 VLOG(1) << "TCP connect failed: " << ex.what();
126 void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
127 VLOG(7) << "client handshake success";
129 callback_->connectSuccess();
134 void handshakeErr(AsyncSSLSocket* /* socket */,
135 const AsyncSocketException& ex) noexcept override {
136 VLOG(1) << "client handshakeErr: " << ex.what();
141 void fail(const AsyncSocketException &ex) {
142 // fail is a noop if called twice
144 AsyncSSLSocket::ConnectCallback *cb = callback_;
148 sslSocket_->closeNow();
149 // closeNow can call handshakeErr if it hasn't been called already.
150 // So this may have been deleted, no member variable access beyond this
152 // Note that closeNow may invoke writeError callbacks if the socket had
153 // write data pending connection completion.
158 void setup_SSL_CTX(SSL_CTX *ctx) {
159 #ifdef SSL_MODE_RELEASE_BUFFERS
160 SSL_CTX_set_mode(ctx,
161 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
162 SSL_MODE_ENABLE_PARTIAL_WRITE
163 | SSL_MODE_RELEASE_BUFFERS
166 SSL_CTX_set_mode(ctx,
167 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
168 SSL_MODE_ENABLE_PARTIAL_WRITE
171 // SSL_CTX_set_mode is a Macro
172 #ifdef SSL_MODE_WRITE_IOVEC
173 SSL_CTX_set_mode(ctx,
174 SSL_CTX_get_mode(ctx)
175 | SSL_MODE_WRITE_IOVEC);
180 BIO_METHOD sslBioMethod;
182 void* initsslBioMethod(void) {
183 memcpy(&sslBioMethod, BIO_s_socket(), sizeof(sslBioMethod));
184 // override the bwrite method for MSG_EOR support
185 OpenSSLUtils::setCustomBioWriteMethod(
186 &sslBioMethod, AsyncSSLSocket::bioWrite);
187 OpenSSLUtils::setCustomBioReadMethod(&sslBioMethod, AsyncSSLSocket::bioRead);
189 // Note that the sslBioMethod.type and sslBioMethod.name are not
190 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
191 // then have specific handlings. The sslWriteBioWrite should be compatible
192 // with the one in openssl.
194 // Return something here to enable AsyncSSLSocket to call this method using
195 // a function-scoped static.
199 } // anonymous namespace
204 * Create a client AsyncSSLSocket
206 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
207 EventBase* evb, bool deferSecurityNegotiation) :
210 handshakeTimeout_(this, evb),
211 connectionTimeout_(this, evb) {
213 if (deferSecurityNegotiation) {
214 sslState_ = STATE_UNENCRYPTED;
219 * Create a server/client AsyncSSLSocket
221 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
222 EventBase* evb, int fd, bool server,
223 bool deferSecurityNegotiation) :
224 AsyncSocket(evb, fd),
227 handshakeTimeout_(this, evb),
228 connectionTimeout_(this, evb) {
229 noTransparentTls_ = true;
232 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
233 AsyncSSLSocket::sslInfoCallback);
235 if (deferSecurityNegotiation) {
236 sslState_ = STATE_UNENCRYPTED;
240 #if FOLLY_OPENSSL_HAS_SNI
242 * Create a client AsyncSSLSocket and allow tlsext_hostname
243 * to be sent in Client Hello.
245 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
247 const std::string& serverName,
248 bool deferSecurityNegotiation) :
249 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
250 tlsextHostname_ = serverName;
254 * Create a client AsyncSSLSocket from an already connected fd
255 * and allow tlsext_hostname to be sent in Client Hello.
257 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
258 EventBase* evb, int fd,
259 const std::string& serverName,
260 bool deferSecurityNegotiation) :
261 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
262 tlsextHostname_ = serverName;
264 #endif // FOLLY_OPENSSL_HAS_SNI
266 AsyncSSLSocket::~AsyncSSLSocket() {
267 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
268 << ", evb=" << eventBase_ << ", fd=" << fd_
269 << ", state=" << int(state_) << ", sslState="
270 << sslState_ << ", events=" << eventFlags_ << ")";
273 void AsyncSSLSocket::init() {
274 // Do this here to ensure we initialize this once before any use of
275 // AsyncSSLSocket instances and not as part of library load.
276 static const auto sslBioMethodInitializer = initsslBioMethod();
277 (void)sslBioMethodInitializer;
279 setup_SSL_CTX(ctx_->getSSLCtx());
282 void AsyncSSLSocket::closeNow() {
283 // Close the SSL connection.
284 if (ssl_ != nullptr && fd_ != -1) {
285 int rc = SSL_shutdown(ssl_);
287 rc = SSL_shutdown(ssl_);
294 if (sslSession_ != nullptr) {
295 SSL_SESSION_free(sslSession_);
296 sslSession_ = nullptr;
299 sslState_ = STATE_CLOSED;
301 if (handshakeTimeout_.isScheduled()) {
302 handshakeTimeout_.cancelTimeout();
305 DestructorGuard dg(this);
308 AsyncSocketException(
309 AsyncSocketException::END_OF_FILE,
310 "SSL connection closed locally"));
312 if (ssl_ != nullptr) {
318 AsyncSocket::closeNow();
321 void AsyncSSLSocket::shutdownWrite() {
322 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
324 // (Performing a full shutdown here is more desirable than doing nothing at
325 // all. The purpose of shutdownWrite() is normally to notify the other end
326 // of the connection that no more data will be sent. If we do nothing, the
327 // other end will never know that no more data is coming, and this may result
328 // in protocol deadlock.)
332 void AsyncSSLSocket::shutdownWriteNow() {
336 bool AsyncSSLSocket::good() const {
337 return (AsyncSocket::good() &&
338 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
339 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
342 // The TAsyncTransport definition of 'good' states that the transport is
343 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
344 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
345 // is connected but we haven't initiated the call to SSL_connect.
346 bool AsyncSSLSocket::connecting() const {
348 (AsyncSocket::connecting() ||
349 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
350 sslState_ == STATE_CONNECTING))));
353 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
354 const unsigned char* protoName = nullptr;
355 unsigned protoLength;
356 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
357 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
362 void AsyncSSLSocket::setEorTracking(bool track) {
363 if (isEorTrackingEnabled() != track) {
364 AsyncSocket::setEorTracking(track);
366 minEorRawByteNo_ = 0;
370 size_t AsyncSSLSocket::getRawBytesWritten() const {
371 // The bio(s) in the write path are in a chain
372 // each bio flushes to the next and finally written into the socket
373 // to get the rawBytesWritten on the socket,
374 // get the write bytes of the last bio
376 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
379 BIO* next = BIO_next(b);
380 while (next != NULL) {
385 return BIO_number_written(b);
388 size_t AsyncSSLSocket::getRawBytesReceived() const {
390 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
394 return BIO_number_read(b);
398 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
399 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
400 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
401 << "events=" << eventFlags_ << ", server=" << short(server_)
402 << "): " << "sslAccept/Connect() called in invalid "
403 << "state, handshake callback " << handshakeCallback_
404 << ", new callback " << callback;
405 assert(!handshakeTimeout_.isScheduled());
406 sslState_ = STATE_ERROR;
408 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
409 "sslAccept() called with socket in invalid state");
411 handshakeEndTime_ = std::chrono::steady_clock::now();
413 callback->handshakeErr(this, ex);
416 failHandshake(__func__, ex);
419 void AsyncSSLSocket::sslAccept(
420 HandshakeCB* callback,
421 std::chrono::milliseconds timeout,
422 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
423 DestructorGuard dg(this);
424 assert(eventBase_->isInEventBaseThread());
425 verifyPeer_ = verifyPeer;
427 // Make sure we're in the uninitialized state
428 if (!server_ || (sslState_ != STATE_UNINIT &&
429 sslState_ != STATE_UNENCRYPTED) ||
430 handshakeCallback_ != nullptr) {
431 return invalidState(callback);
434 // Cache local and remote socket addresses to keep them available
435 // after socket file descriptor is closed.
436 if (cacheAddrOnFailure_ && -1 != getFd()) {
437 cacheLocalPeerAddr();
440 handshakeStartTime_ = std::chrono::steady_clock::now();
441 // Make end time at least >= start time.
442 handshakeEndTime_ = handshakeStartTime_;
444 sslState_ = STATE_ACCEPTING;
445 handshakeCallback_ = callback;
447 if (timeout > std::chrono::milliseconds::zero()) {
448 handshakeTimeout_.scheduleTimeout(timeout);
451 /* register for a read operation (waiting for CLIENT HELLO) */
452 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
454 if (preReceivedData_) {
459 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
460 void AsyncSSLSocket::attachSSLContext(
461 const std::shared_ptr<SSLContext>& ctx) {
463 // Check to ensure we are in client mode. Changing a server's ssl
464 // context doesn't make sense since clients of that server would likely
465 // become confused when the server's context changes.
469 DCHECK(ctx->getSSLCtx());
472 // It's possible this could be attached before ssl_ is set up
477 // In order to call attachSSLContext, detachSSLContext must have been
478 // previously called.
479 // We need to update the initial_ctx if necessary
480 auto sslCtx = ctx->getSSLCtx();
481 SSL_CTX_up_ref(sslCtx);
482 #ifndef OPENSSL_NO_TLSEXT
483 // note that detachSSLContext has already freed ssl_->initial_ctx
484 ssl_->initial_ctx = sslCtx;
486 // Detach sets the socket's context to the dummy context. Thus we must acquire
488 SpinLockGuard guard(dummyCtxLock);
489 SSL_set_SSL_CTX(ssl_, sslCtx);
492 void AsyncSSLSocket::detachSSLContext() {
495 // It's possible for this to be called before ssl_ has been
500 // Detach the initial_ctx as well. Internally w/ OPENSSL_NO_TLSEXT
501 // it is used for session info. It will be reattached in attachSSLContext
502 #ifndef OPENSSL_NO_TLSEXT
503 if (ssl_->initial_ctx) {
504 SSL_CTX_free(ssl_->initial_ctx);
505 ssl_->initial_ctx = nullptr;
508 SpinLockGuard guard(dummyCtxLock);
509 if (nullptr == dummyCtx) {
510 // We need to lazily initialize the dummy context so we don't
511 // accidentally override any programmatic settings to openssl
512 dummyCtx = new SSLContext;
514 // We must remove this socket's references to its context right now
515 // since this socket could get passed to any thread. If the context has
516 // had its locking disabled, just doing a set in attachSSLContext()
517 // would not be thread safe.
518 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
522 #if FOLLY_OPENSSL_HAS_SNI
523 void AsyncSSLSocket::switchServerSSLContext(
524 const std::shared_ptr<SSLContext>& handshakeCtx) {
526 if (sslState_ != STATE_ACCEPTING) {
527 // We log it here and allow the switch.
528 // It should not affect our re-negotiation support (which
529 // is not supported now).
530 VLOG(6) << "fd=" << getFd()
531 << " renegotation detected when switching SSL_CTX";
534 setup_SSL_CTX(handshakeCtx->getSSLCtx());
535 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
536 AsyncSSLSocket::sslInfoCallback);
537 handshakeCtx_ = handshakeCtx;
538 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
541 bool AsyncSSLSocket::isServerNameMatch() const {
548 SSL_SESSION *ss = SSL_get_session(ssl_);
553 if(!ss->tlsext_hostname) {
556 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
559 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
560 tlsextHostname_ = std::move(serverName);
563 #endif // FOLLY_OPENSSL_HAS_SNI
565 void AsyncSSLSocket::timeoutExpired(
566 std::chrono::milliseconds timeout) noexcept {
567 if (state_ == StateEnum::ESTABLISHED &&
568 (sslState_ == STATE_CACHE_LOOKUP || sslState_ == STATE_ASYNC_PENDING)) {
569 sslState_ = STATE_ERROR;
570 // We are expecting a callback in restartSSLAccept. The cache lookup
571 // and rsa-call necessarily have pointers to this ssl socket, so delay
572 // the cleanup until he calls us back.
573 } else if (state_ == StateEnum::CONNECTING) {
574 assert(sslState_ == STATE_CONNECTING);
575 DestructorGuard dg(this);
576 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
577 "Fallback connect timed out during TFO");
578 failHandshake(__func__, ex);
580 assert(state_ == StateEnum::ESTABLISHED &&
581 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
582 DestructorGuard dg(this);
583 AsyncSocketException ex(
584 AsyncSocketException::TIMED_OUT,
586 "SSL {} timed out after {}ms",
587 (sslState_ == STATE_CONNECTING) ? "connect" : "accept",
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(
649 ConnectCallback* callback,
650 const folly::SocketAddress& address,
652 const OptionMap& options,
653 const folly::SocketAddress& bindAddr) noexcept {
654 auto timeoutChrono = std::chrono::milliseconds(timeout);
655 connect(callback, address, timeoutChrono, timeoutChrono, options, bindAddr);
658 void AsyncSSLSocket::connect(
659 ConnectCallback* callback,
660 const folly::SocketAddress& address,
661 std::chrono::milliseconds connectTimeout,
662 std::chrono::milliseconds totalConnectTimeout,
663 const OptionMap& options,
664 const folly::SocketAddress& bindAddr) noexcept {
666 assert(state_ == StateEnum::UNINIT);
667 assert(sslState_ == STATE_UNINIT);
668 noTransparentTls_ = true;
669 AsyncSSLSocketConnector* connector =
670 new AsyncSSLSocketConnector(this, callback, totalConnectTimeout.count());
671 AsyncSocket::connect(
672 connector, address, connectTimeout.count(), options, bindAddr);
675 bool AsyncSSLSocket::needsPeerVerification() const {
676 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
677 return ctx_->needsPeerVerification();
680 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
681 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
684 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
685 // apply the settings specified in verifyPeer_
686 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
687 if(ctx_->needsPeerVerification()) {
688 SSL_set_verify(ssl, ctx_->getVerificationMode(),
689 AsyncSSLSocket::sslVerifyCallback);
692 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
693 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
694 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
695 AsyncSSLSocket::sslVerifyCallback);
700 bool AsyncSSLSocket::setupSSLBio() {
701 auto sslBio = BIO_new(&sslBioMethod);
707 OpenSSLUtils::setBioAppData(sslBio, this);
708 OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE);
709 SSL_set_bio(ssl_, sslBio, sslBio);
713 void AsyncSSLSocket::sslConn(
714 HandshakeCB* callback,
715 std::chrono::milliseconds timeout,
716 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
717 DestructorGuard dg(this);
718 assert(eventBase_->isInEventBaseThread());
720 // Cache local and remote socket addresses to keep them available
721 // after socket file descriptor is closed.
722 if (cacheAddrOnFailure_ && -1 != getFd()) {
723 cacheLocalPeerAddr();
726 verifyPeer_ = verifyPeer;
728 // Make sure we're in the uninitialized state
729 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
730 STATE_UNENCRYPTED) ||
731 handshakeCallback_ != nullptr) {
732 return invalidState(callback);
735 sslState_ = STATE_CONNECTING;
736 handshakeCallback_ = callback;
739 ssl_ = ctx_->createSSL();
740 } catch (std::exception &e) {
741 sslState_ = STATE_ERROR;
742 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
743 "error calling SSLContext::createSSL()");
744 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
745 << fd_ << "): " << e.what();
746 return failHandshake(__func__, ex);
749 if (!setupSSLBio()) {
750 sslState_ = STATE_ERROR;
751 AsyncSocketException ex(
752 AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
753 return failHandshake(__func__, ex);
756 applyVerificationOptions(ssl_);
758 if (sslSession_ != nullptr) {
759 sessionResumptionAttempted_ = true;
760 SSL_set_session(ssl_, sslSession_);
761 SSL_SESSION_free(sslSession_);
762 sslSession_ = nullptr;
764 #if FOLLY_OPENSSL_HAS_SNI
765 if (tlsextHostname_.size()) {
766 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
770 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
772 handshakeConnectTimeout_ = timeout;
776 // This could be called multiple times, during normal ssl connections
777 // and after TFO fallback.
778 void AsyncSSLSocket::startSSLConnect() {
779 handshakeStartTime_ = std::chrono::steady_clock::now();
780 // Make end time at least >= start time.
781 handshakeEndTime_ = handshakeStartTime_;
782 if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) {
783 handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
788 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
789 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
790 return SSL_get1_session(ssl_);
796 const SSL* AsyncSSLSocket::getSSL() const {
800 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
801 sslSession_ = session;
802 if (!takeOwnership && session != nullptr) {
803 // Increment the reference count
804 // This API exists in BoringSSL and OpenSSL 1.1.0
805 SSL_SESSION_up_ref(session);
809 void AsyncSSLSocket::getSelectedNextProtocol(
810 const unsigned char** protoName,
812 SSLContext::NextProtocolType* protoType) const {
813 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
814 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
815 "NPN not supported");
819 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
820 const unsigned char** protoName,
822 SSLContext::NextProtocolType* protoType) const {
823 *protoName = nullptr;
825 #if FOLLY_OPENSSL_HAS_ALPN
826 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
829 *protoType = SSLContext::NextProtocolType::ALPN;
834 #ifdef OPENSSL_NPN_NEGOTIATED
835 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
837 *protoType = SSLContext::NextProtocolType::NPN;
846 bool AsyncSSLSocket::getSSLSessionReused() const {
847 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
848 return SSL_session_reused(ssl_);
853 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
854 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
858 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
859 if (ssl == nullptr) {
862 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
863 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
869 const char *AsyncSSLSocket::getSSLServerName() const {
870 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
871 return getSSLServerNameFromSSL(ssl_);
873 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
874 "SNI not supported");
878 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
879 return getSSLServerNameFromSSL(ssl_);
882 int AsyncSSLSocket::getSSLVersion() const {
883 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
886 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
887 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
889 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
890 return OBJ_nid2ln(nid);
895 int AsyncSSLSocket::getSSLCertSize() const {
897 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
899 EVP_PKEY *key = X509_get_pubkey(cert);
900 certSize = EVP_PKEY_bits(key);
906 const X509* AsyncSSLSocket::getSelfCert() const {
907 return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
910 bool AsyncSSLSocket::willBlock(int ret,
912 unsigned long* errErrorOut) noexcept {
914 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
915 if (error == SSL_ERROR_WANT_READ) {
916 // Register for read event if not already.
917 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
919 } else if (error == SSL_ERROR_WANT_WRITE) {
920 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
921 << ", state=" << int(state_) << ", sslState="
922 << sslState_ << ", events=" << eventFlags_ << "): "
923 << "SSL_ERROR_WANT_WRITE";
924 // Register for write event if not already.
925 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
927 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
928 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
929 // We will block but we can't register our own socket. The callback that
930 // triggered this code will re-call handleAccept at the appropriate time.
932 // We can only get here if the linked libssl.so has support for this feature
933 // as well, otherwise SSL_get_error cannot return our error code.
934 sslState_ = STATE_CACHE_LOOKUP;
936 // Unregister for all events while blocked here
937 updateEventRegistration(EventHandler::NONE,
938 EventHandler::READ | EventHandler::WRITE);
940 // The timeout (if set) keeps running here
944 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
945 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
947 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
948 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
951 // Our custom openssl function has kicked off an async request to do
952 // rsa/ecdsa private key operation. When that call returns, a callback will
953 // be invoked that will re-call handleAccept.
954 sslState_ = STATE_ASYNC_PENDING;
956 // Unregister for all events while blocked here
957 updateEventRegistration(
959 EventHandler::READ | EventHandler::WRITE
962 // The timeout (if set) keeps running here
965 unsigned long lastError = *errErrorOut = ERR_get_error();
966 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
967 << "state=" << state_ << ", "
968 << "sslState=" << sslState_ << ", "
969 << "events=" << std::hex << eventFlags_ << "): "
970 << "SSL error: " << error << ", "
971 << "errno: " << errno << ", "
972 << "ret: " << ret << ", "
973 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
974 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
975 << "func: " << ERR_func_error_string(lastError) << ", "
976 << "reason: " << ERR_reason_error_string(lastError);
981 void AsyncSSLSocket::checkForImmediateRead() noexcept {
982 // openssl may have buffered data that it read from the socket already.
983 // In this case we have to process it immediately, rather than waiting for
984 // the socket to become readable again.
985 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
986 AsyncSocket::handleRead();
991 AsyncSSLSocket::restartSSLAccept()
993 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
994 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
995 << "sslState=" << sslState_ << ", events=" << eventFlags_;
996 DestructorGuard dg(this);
998 sslState_ == STATE_CACHE_LOOKUP ||
999 sslState_ == STATE_ASYNC_PENDING ||
1000 sslState_ == STATE_ERROR ||
1001 sslState_ == STATE_CLOSED);
1002 if (sslState_ == STATE_CLOSED) {
1003 // I sure hope whoever closed this socket didn't delete it already,
1004 // but this is not strictly speaking an error
1007 if (sslState_ == STATE_ERROR) {
1008 // go straight to fail if timeout expired during lookup
1009 AsyncSocketException ex(
1010 AsyncSocketException::TIMED_OUT, "SSL accept timed out");
1011 failHandshake(__func__, ex);
1014 sslState_ = STATE_ACCEPTING;
1015 this->handleAccept();
1019 AsyncSSLSocket::handleAccept() noexcept {
1020 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1021 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1022 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1024 assert(state_ == StateEnum::ESTABLISHED &&
1025 sslState_ == STATE_ACCEPTING);
1027 /* lazily create the SSL structure */
1029 ssl_ = ctx_->createSSL();
1030 } catch (std::exception &e) {
1031 sslState_ = STATE_ERROR;
1032 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1033 "error calling SSLContext::createSSL()");
1034 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1035 << ", fd=" << fd_ << "): " << e.what();
1036 return failHandshake(__func__, ex);
1039 if (!setupSSLBio()) {
1040 sslState_ = STATE_ERROR;
1041 AsyncSocketException ex(
1042 AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1043 return failHandshake(__func__, ex);
1046 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1048 applyVerificationOptions(ssl_);
1051 if (server_ && parseClientHello_) {
1052 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1053 SSL_set_msg_callback_arg(ssl_, this);
1056 int ret = SSL_accept(ssl_);
1059 unsigned long errError;
1060 int errnoCopy = errno;
1061 if (willBlock(ret, &sslError, &errError)) {
1064 sslState_ = STATE_ERROR;
1065 SSLException ex(sslError, errError, ret, errnoCopy);
1066 return failHandshake(__func__, ex);
1070 handshakeComplete_ = true;
1071 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1073 // Move into STATE_ESTABLISHED in the normal case that we are in
1075 sslState_ = STATE_ESTABLISHED;
1077 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1078 << " successfully accepted; state=" << int(state_)
1079 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1081 // Remember the EventBase we are attached to, before we start invoking any
1082 // callbacks (since the callbacks may call detachEventBase()).
1083 EventBase* originalEventBase = eventBase_;
1085 // Call the accept callback.
1086 invokeHandshakeCB();
1088 // Note that the accept callback may have changed our state.
1089 // (set or unset the read callback, called write(), closed the socket, etc.)
1090 // The following code needs to handle these situations correctly.
1092 // If the socket has been closed, readCallback_ and writeReqHead_ will
1093 // always be nullptr, so that will prevent us from trying to read or write.
1095 // The main thing to check for is if eventBase_ is still originalEventBase.
1096 // If not, we have been detached from this event base, so we shouldn't
1097 // perform any more operations.
1098 if (eventBase_ != originalEventBase) {
1102 AsyncSocket::handleInitialReadWrite();
1106 AsyncSSLSocket::handleConnect() noexcept {
1107 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1108 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1109 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1111 if (state_ < StateEnum::ESTABLISHED) {
1112 return AsyncSocket::handleConnect();
1116 (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1117 sslState_ == STATE_CONNECTING);
1120 auto originalState = state_;
1121 int ret = SSL_connect(ssl_);
1124 unsigned long errError;
1125 int errnoCopy = errno;
1126 if (willBlock(ret, &sslError, &errError)) {
1127 // We fell back to connecting state due to TFO
1128 if (state_ == StateEnum::CONNECTING) {
1129 DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1130 if (handshakeTimeout_.isScheduled()) {
1131 handshakeTimeout_.cancelTimeout();
1136 sslState_ = STATE_ERROR;
1137 SSLException ex(sslError, errError, ret, errnoCopy);
1138 return failHandshake(__func__, ex);
1142 handshakeComplete_ = true;
1143 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1145 // Move into STATE_ESTABLISHED in the normal case that we are in
1146 // STATE_CONNECTING.
1147 sslState_ = STATE_ESTABLISHED;
1149 VLOG(3) << "AsyncSSLSocket " << this << ": "
1150 << "fd " << fd_ << " successfully connected; "
1151 << "state=" << int(state_) << ", sslState=" << sslState_
1152 << ", events=" << eventFlags_;
1154 // Remember the EventBase we are attached to, before we start invoking any
1155 // callbacks (since the callbacks may call detachEventBase()).
1156 EventBase* originalEventBase = eventBase_;
1158 // Call the handshake callback.
1159 invokeHandshakeCB();
1161 // Note that the connect callback may have changed our state.
1162 // (set or unset the read callback, called write(), closed the socket, etc.)
1163 // The following code needs to handle these situations correctly.
1165 // If the socket has been closed, readCallback_ and writeReqHead_ will
1166 // always be nullptr, so that will prevent us from trying to read or write.
1168 // The main thing to check for is if eventBase_ is still originalEventBase.
1169 // If not, we have been detached from this event base, so we shouldn't
1170 // perform any more operations.
1171 if (eventBase_ != originalEventBase) {
1175 AsyncSocket::handleInitialReadWrite();
1178 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1179 connectionTimeout_.cancelTimeout();
1180 AsyncSocket::invokeConnectErr(ex);
1181 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1182 if (handshakeTimeout_.isScheduled()) {
1183 handshakeTimeout_.cancelTimeout();
1185 // If we fell back to connecting state during TFO and the connection
1186 // failed, it would be an SSL failure as well.
1187 invokeHandshakeErr(ex);
1191 void AsyncSSLSocket::invokeConnectSuccess() {
1192 connectionTimeout_.cancelTimeout();
1193 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1194 assert(tfoAttempted_);
1195 // If we failed TFO, we'd fall back to trying to connect the socket,
1196 // to setup things like timeouts.
1199 // still invoke the base class since it re-sets the connect time.
1200 AsyncSocket::invokeConnectSuccess();
1203 void AsyncSSLSocket::scheduleConnectTimeout() {
1204 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1205 // We fell back from TFO, and need to set the timeouts.
1206 // We will not have a connect callback in this case, thus if the timer
1207 // expires we would have no-one to notify.
1208 // Thus we should reset even the connect timers to point to the handshake
1210 assert(connectCallback_ == nullptr);
1211 // We use a different connect timeout here than the handshake timeout, so
1212 // that we can disambiguate the 2 timers.
1213 if (connectTimeout_.count() > 0) {
1214 if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1215 throw AsyncSocketException(
1216 AsyncSocketException::INTERNAL_ERROR,
1217 withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1222 AsyncSocket::scheduleConnectTimeout();
1225 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1226 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1227 // turn on the buffer movable in openssl
1228 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1229 callback != nullptr && callback->isBufferMovable()) {
1230 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1231 isBufferMovable_ = true;
1235 AsyncSocket::setReadCB(callback);
1238 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1239 bufferMovableEnabled_ = enabled;
1242 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1243 CHECK(readCallback_);
1244 if (isBufferMovable_) {
1248 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1249 readCallback_->getReadBuffer(buf, buflen);
1254 AsyncSSLSocket::handleRead() noexcept {
1255 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1256 << ", state=" << int(state_) << ", "
1257 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1258 if (state_ < StateEnum::ESTABLISHED) {
1259 return AsyncSocket::handleRead();
1263 if (sslState_ == STATE_ACCEPTING) {
1268 else if (sslState_ == STATE_CONNECTING) {
1275 AsyncSocket::handleRead();
1278 AsyncSocket::ReadResult
1279 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1280 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1281 << ", buflen=" << *buflen;
1283 if (sslState_ == STATE_UNENCRYPTED) {
1284 return AsyncSocket::performRead(buf, buflen, offset);
1288 if (!isBufferMovable_) {
1289 bytes = SSL_read(ssl_, *buf, int(*buflen));
1291 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1293 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1297 if (server_ && renegotiateAttempted_) {
1298 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1299 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1300 << "): client intitiated SSL renegotiation not permitted";
1303 folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1306 int error = SSL_get_error(ssl_, bytes);
1307 if (error == SSL_ERROR_WANT_READ) {
1308 // The caller will register for read event if not already.
1309 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1310 return ReadResult(READ_BLOCKING);
1312 return ReadResult(READ_ERROR);
1314 } else if (error == SSL_ERROR_WANT_WRITE) {
1315 // TODO: Even though we are attempting to read data, SSL_read() may
1316 // need to write data if renegotiation is being performed. We currently
1317 // don't support this and just fail the read.
1318 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1319 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1320 << "): unsupported SSL renegotiation during read";
1323 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1325 if (zero_return(error, bytes)) {
1326 return ReadResult(bytes);
1328 auto errError = ERR_get_error();
1329 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1330 << "state=" << state_ << ", "
1331 << "sslState=" << sslState_ << ", "
1332 << "events=" << std::hex << eventFlags_ << "): "
1333 << "bytes: " << bytes << ", "
1334 << "error: " << error << ", "
1335 << "errno: " << errno << ", "
1336 << "func: " << ERR_func_error_string(errError) << ", "
1337 << "reason: " << ERR_reason_error_string(errError);
1340 folly::make_unique<SSLException>(error, errError, bytes, errno));
1343 appBytesReceived_ += bytes;
1344 return ReadResult(bytes);
1348 void AsyncSSLSocket::handleWrite() noexcept {
1349 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1350 << ", state=" << int(state_) << ", "
1351 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1352 if (state_ < StateEnum::ESTABLISHED) {
1353 return AsyncSocket::handleWrite();
1356 if (sslState_ == STATE_ACCEPTING) {
1362 if (sslState_ == STATE_CONNECTING) {
1369 AsyncSocket::handleWrite();
1372 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1373 if (error == SSL_ERROR_WANT_READ) {
1374 // Even though we are attempting to write data, SSL_write() may
1375 // need to read data if renegotiation is being performed. We currently
1376 // don't support this and just fail the write.
1377 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1378 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1380 << "unsupported SSL renegotiation during write";
1383 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1385 if (zero_return(error, rc)) {
1386 return WriteResult(0);
1388 auto errError = ERR_get_error();
1389 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1390 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1391 << "SSL error: " << error << ", errno: " << errno
1392 << ", func: " << ERR_func_error_string(errError)
1393 << ", reason: " << ERR_reason_error_string(errError);
1396 folly::make_unique<SSLException>(error, errError, rc, errno));
1400 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1404 uint32_t* countWritten,
1405 uint32_t* partialWritten) {
1406 if (sslState_ == STATE_UNENCRYPTED) {
1407 return AsyncSocket::performWrite(
1408 vec, count, flags, countWritten, partialWritten);
1410 if (sslState_ != STATE_ESTABLISHED) {
1411 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1412 << ", sslState=" << sslState_
1413 << ", events=" << eventFlags_ << "): "
1414 << "TODO: AsyncSSLSocket currently does not support calling "
1415 << "write() before the handshake has fully completed";
1417 WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1420 // Declare a buffer used to hold small write requests. It could point to a
1421 // memory block either on stack or on heap. If it is on heap, we release it
1422 // manually when scope exits
1423 char* combinedBuf{nullptr};
1425 // Note, always keep this check consistent with what we do below
1426 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1427 delete[] combinedBuf;
1432 *partialWritten = 0;
1433 ssize_t totalWritten = 0;
1434 size_t bytesStolenFromNextBuffer = 0;
1435 for (uint32_t i = 0; i < count; i++) {
1436 const iovec* v = vec + i;
1437 size_t offset = bytesStolenFromNextBuffer;
1438 bytesStolenFromNextBuffer = 0;
1439 size_t len = v->iov_len - offset;
1445 buf = ((const char*)v->iov_base) + offset;
1448 uint32_t buffersStolen = 0;
1449 auto sslWriteBuf = buf;
1450 if ((len < minWriteSize_) && ((i + 1) < count)) {
1451 // Combine this buffer with part or all of the next buffers in
1452 // order to avoid really small-grained calls to SSL_write().
1453 // Each call to SSL_write() produces a separate record in
1454 // the egress SSL stream, and we've found that some low-end
1455 // mobile clients can't handle receiving an HTTP response
1456 // header and the first part of the response body in two
1457 // separate SSL records (even if those two records are in
1458 // the same TCP packet).
1460 if (combinedBuf == nullptr) {
1461 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1462 // Allocate the buffer on heap
1463 combinedBuf = new char[minWriteSize_];
1465 // Allocate the buffer on stack
1466 combinedBuf = (char*)alloca(minWriteSize_);
1469 assert(combinedBuf != nullptr);
1470 sslWriteBuf = combinedBuf;
1472 memcpy(combinedBuf, buf, len);
1474 // INVARIANT: i + buffersStolen == complete chunks serialized
1475 uint32_t nextIndex = i + buffersStolen + 1;
1476 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1477 minWriteSize_ - len);
1478 if (bytesStolenFromNextBuffer > 0) {
1479 assert(vec[nextIndex].iov_base != nullptr);
1482 vec[nextIndex].iov_base,
1483 bytesStolenFromNextBuffer);
1485 len += bytesStolenFromNextBuffer;
1486 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1487 // couldn't steal the whole buffer
1490 bytesStolenFromNextBuffer = 0;
1493 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1496 // Advance any empty buffers immediately after.
1497 if (bytesStolenFromNextBuffer == 0) {
1498 while ((i + buffersStolen + 1) < count &&
1499 vec[i + buffersStolen + 1].iov_len == 0) {
1505 isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1506 bytes = eorAwareSSLWrite(
1510 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1513 int error = SSL_get_error(ssl_, int(bytes));
1514 if (error == SSL_ERROR_WANT_WRITE) {
1515 // The caller will register for write event if not already.
1516 *partialWritten = uint32_t(offset);
1517 return WriteResult(totalWritten);
1519 auto writeResult = interpretSSLError(int(bytes), error);
1520 if (writeResult.writeReturn < 0) {
1522 } // else fall through to below to correctly record totalWritten
1525 totalWritten += bytes;
1527 if (bytes == (ssize_t)len) {
1528 // The full iovec is written.
1529 (*countWritten) += 1 + buffersStolen;
1533 bytes += offset; // adjust bytes to account for all of v
1534 while (bytes >= (ssize_t)v->iov_len) {
1535 // We combined this buf with part or all of the next one, and
1536 // we managed to write all of this buf but not all of the bytes
1537 // from the next one that we'd hoped to write.
1538 bytes -= v->iov_len;
1542 *partialWritten = uint32_t(bytes);
1543 return WriteResult(totalWritten);
1547 return WriteResult(totalWritten);
1550 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1552 if (eor && isEorTrackingEnabled()) {
1553 if (appEorByteNo_) {
1554 // cannot track for more than one app byte EOR
1555 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1557 appEorByteNo_ = appBytesWritten_ + n;
1560 // 1. It is fine to keep updating minEorRawByteNo_.
1561 // 2. It is _min_ in the sense that SSL record will add some overhead.
1562 minEorRawByteNo_ = getRawBytesWritten() + n;
1565 n = sslWriteImpl(ssl, buf, n);
1567 appBytesWritten_ += n;
1568 if (appEorByteNo_) {
1569 if (getRawBytesWritten() >= minEorRawByteNo_) {
1570 minEorRawByteNo_ = 0;
1572 if(appBytesWritten_ == appEorByteNo_) {
1575 CHECK(appBytesWritten_ < appEorByteNo_);
1582 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1583 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1584 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1585 sslSocket->renegotiateAttempted_ = true;
1587 if (where & SSL_CB_READ_ALERT) {
1588 const char* type = SSL_alert_type_string(ret);
1590 const char* desc = SSL_alert_desc_string(ret);
1591 sslSocket->alertsReceived_.emplace_back(
1592 *type, StringPiece(desc, std::strlen(desc)));
1597 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1601 AsyncSSLSocket* tsslSock;
1603 iov.iov_base = const_cast<char*>(in);
1604 iov.iov_len = size_t(inl);
1605 memset(&msg, 0, sizeof(msg));
1609 auto appData = OpenSSLUtils::getBioAppData(b);
1612 tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1615 if (tsslSock->isEorTrackingEnabled() && tsslSock->minEorRawByteNo_ &&
1616 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1621 flags |= MSG_NOSIGNAL;
1625 if (tsslSock->corkCurrentWrite_) {
1630 auto result = tsslSock->sendSocketMessage(
1631 OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
1632 BIO_clear_retry_flags(b);
1633 if (!result.exception && result.writeReturn <= 0) {
1634 if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1635 BIO_set_retry_write(b);
1638 return int(result.writeReturn);
1641 int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) {
1645 BIO_clear_retry_flags(b);
1647 auto appData = OpenSSLUtils::getBioAppData(b);
1649 auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1651 if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) {
1652 VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock
1653 << ", reading pre-received data";
1655 Cursor cursor(sslSock->preReceivedData_.get());
1656 auto len = cursor.pullAtMost(out, outl);
1659 queue.append(std::move(sslSock->preReceivedData_));
1660 queue.trimStart(len);
1661 sslSock->preReceivedData_ = queue.move();
1664 auto result = recv(OpenSSLUtils::getBioFd(b, nullptr), out, outl, 0);
1665 if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) {
1666 BIO_set_retry_read(b);
1672 int AsyncSSLSocket::sslVerifyCallback(
1674 X509_STORE_CTX* x509Ctx) {
1675 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1676 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1677 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1679 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1680 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1681 return (self->handshakeCallback_) ?
1682 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1686 void AsyncSSLSocket::setPreReceivedData(std::unique_ptr<IOBuf> data) {
1687 CHECK(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED);
1688 CHECK(!preReceivedData_);
1689 preReceivedData_ = std::move(data);
1692 void AsyncSSLSocket::enableClientHelloParsing() {
1693 parseClientHello_ = true;
1694 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1697 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1698 SSL_set_msg_callback(ssl, nullptr);
1699 SSL_set_msg_callback_arg(ssl, nullptr);
1700 clientHelloInfo_->clientHelloBuf_.clear();
1703 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1710 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1712 sock->resetClientHelloParsing(ssl);
1715 if (contentType != SSL3_RT_HANDSHAKE) {
1722 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1723 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1725 Cursor cursor(clientHelloBuf.front());
1726 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1727 sock->resetClientHelloParsing(ssl);
1731 if (cursor.totalLength() < 3) {
1732 clientHelloBuf.trimEnd(len);
1733 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1737 uint32_t messageLength = cursor.read<uint8_t>();
1738 messageLength <<= 8;
1739 messageLength |= cursor.read<uint8_t>();
1740 messageLength <<= 8;
1741 messageLength |= cursor.read<uint8_t>();
1742 if (cursor.totalLength() < messageLength) {
1743 clientHelloBuf.trimEnd(len);
1744 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1748 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1749 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1751 cursor.skip(4); // gmt_unix_time
1752 cursor.skip(28); // random_bytes
1754 cursor.skip(cursor.read<uint8_t>()); // session_id
1756 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1757 for (int i = 0; i < cipherSuitesLength; i += 2) {
1758 sock->clientHelloInfo_->
1759 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1762 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1763 for (int i = 0; i < compressionMethodsLength; ++i) {
1764 sock->clientHelloInfo_->
1765 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1768 if (cursor.totalLength() > 0) {
1769 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1770 while (extensionsLength) {
1771 ssl::TLSExtension extensionType =
1772 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1773 sock->clientHelloInfo_->
1774 clientHelloExtensions_.push_back(extensionType);
1775 extensionsLength -= 2;
1776 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1777 extensionsLength -= 2;
1778 extensionsLength -= extensionDataLength;
1780 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1782 extensionDataLength -= 2;
1783 while (extensionDataLength) {
1784 ssl::HashAlgorithm hashAlg =
1785 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1786 ssl::SignatureAlgorithm sigAlg =
1787 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1788 extensionDataLength -= 2;
1789 sock->clientHelloInfo_->
1790 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1792 } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1794 extensionDataLength -= 1;
1795 while (extensionDataLength) {
1796 sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1797 cursor.readBE<uint16_t>());
1798 extensionDataLength -= 2;
1801 cursor.skip(extensionDataLength);
1805 } catch (std::out_of_range&) {
1806 // we'll use what we found and cleanup below.
1807 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1808 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1811 sock->resetClientHelloParsing(ssl);
1814 void AsyncSSLSocket::getSSLClientCiphers(
1815 std::string& clientCiphers,
1816 bool convertToString) const {
1817 std::string ciphers;
1819 if (parseClientHello_ == false
1820 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1826 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1834 bool nameFound = convertToString;
1836 if (convertToString) {
1837 const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1847 std::array<uint8_t, 2>{{
1848 static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1849 static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1851 /* append to ciphers = */ true);
1855 clientCiphers = std::move(ciphers);
1858 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1859 if (!parseClientHello_) {
1862 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1865 std::string AsyncSSLSocket::getSSLClientExts() const {
1866 if (!parseClientHello_) {
1869 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1872 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1873 if (!parseClientHello_) {
1877 std::string sigAlgs;
1878 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1879 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1881 sigAlgs.push_back(':');
1883 sigAlgs.append(folly::to<std::string>(
1884 clientHelloInfo_->clientHelloSigAlgs_[i].first));
1885 sigAlgs.push_back(',');
1886 sigAlgs.append(folly::to<std::string>(
1887 clientHelloInfo_->clientHelloSigAlgs_[i].second));
1893 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1894 if (!parseClientHello_) {
1897 return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1900 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1903 for (const auto& alert : alertsReceived_) {
1907 ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1913 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1914 char ciphersBuffer[1024];
1915 ciphersBuffer[0] = '\0';
1916 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1917 sharedCiphers = ciphersBuffer;
1920 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1921 serverCiphers = SSL_get_cipher_list(ssl_, 0);
1924 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1925 serverCiphers.append(":");
1926 serverCiphers.append(cipher);