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.
21 #include <folly/Bits.h>
22 #include <folly/Optional.h>
23 #include <folly/String.h>
24 #include <folly/io/Cursor.h>
25 #include <folly/io/IOBuf.h>
26 #include <folly/io/async/AsyncSocket.h>
27 #include <folly/io/async/AsyncTimeout.h>
28 #include <folly/io/async/SSLContext.h>
29 #include <folly/io/async/TimeoutManager.h>
30 #include <folly/io/async/ssl/OpenSSLUtils.h>
31 #include <folly/io/async/ssl/SSLErrors.h>
32 #include <folly/io/async/ssl/TLSDefinitions.h>
33 #include <folly/portability/OpenSSL.h>
34 #include <folly/portability/Sockets.h>
35 #include <folly/ssl/OpenSSLPtrTypes.h>
40 * A class for performing asynchronous I/O on an SSL connection.
42 * AsyncSSLSocket allows users to asynchronously wait for data on an
43 * SSL connection, and to asynchronously send data.
45 * The APIs for reading and writing are intentionally asymmetric.
46 * Waiting for data to read is a persistent API: a callback is
47 * installed, and is notified whenever new data is available. It
48 * continues to be notified of new events until it is uninstalled.
50 * AsyncSSLSocket does not provide read timeout functionality,
51 * because it typically cannot determine when the timeout should be
52 * active. Generally, a timeout should only be enabled when
53 * processing is blocked waiting on data from the remote endpoint.
54 * For server connections, the timeout should not be active if the
55 * server is currently processing one or more outstanding requests for
56 * this connection. For client connections, the timeout should not be
57 * active if there are no requests pending on the connection.
58 * Additionally, if a client has multiple pending requests, it will
59 * ususally want a separate timeout for each request, rather than a
60 * single read timeout.
62 * The write API is fairly intuitive: a user can request to send a
63 * block of data, and a callback will be informed once the entire
64 * block has been transferred to the kernel, or on error.
65 * AsyncSSLSocket does provide a send timeout, since most callers
66 * want to give up if the remote end stops responding and no further
67 * progress can be made sending the data.
69 class AsyncSSLSocket : public virtual AsyncSocket {
71 typedef std::unique_ptr<AsyncSSLSocket, Destructor> UniquePtr;
72 using X509_deleter = folly::static_function_deleter<X509, &X509_free>;
76 virtual ~HandshakeCB() = default;
79 * handshakeVer() is invoked during handshaking to give the
80 * application chance to validate it's peer's certificate.
82 * Note that OpenSSL performs only rudimentary internal
83 * consistency verification checks by itself. Any other validation
84 * like whether or not the certificate was issued by a trusted CA.
85 * The default implementation of this callback mimics what what
86 * OpenSSL does internally if SSL_VERIFY_PEER is set with no
87 * verification callback.
89 * See the passages on verify_callback in SSL_CTX_set_verify(3)
92 virtual bool handshakeVer(AsyncSSLSocket* /*sock*/,
94 X509_STORE_CTX* /*ctx*/) noexcept {
99 * handshakeSuc() is called when a new SSL connection is
100 * established, i.e., after SSL_accept/connect() returns successfully.
102 * The HandshakeCB will be uninstalled before handshakeSuc()
105 * @param sock SSL socket on which the handshake was initiated
107 virtual void handshakeSuc(AsyncSSLSocket *sock) noexcept = 0;
110 * handshakeErr() is called if an error occurs while
111 * establishing the SSL connection.
113 * The HandshakeCB will be uninstalled before handshakeErr()
116 * @param sock SSL socket on which the handshake was initiated
117 * @param ex An exception representing the error.
119 virtual void handshakeErr(
120 AsyncSSLSocket *sock,
121 const AsyncSocketException& ex)
125 class Timeout : public AsyncTimeout {
127 Timeout(AsyncSSLSocket* sslSocket, EventBase* eventBase)
128 : AsyncTimeout(eventBase), sslSocket_(sslSocket) {}
130 bool scheduleTimeout(TimeoutManager::timeout_type timeout) {
132 return AsyncTimeout::scheduleTimeout(timeout);
135 bool scheduleTimeout(uint32_t timeoutMs) {
136 return scheduleTimeout(std::chrono::milliseconds{timeoutMs});
139 TimeoutManager::timeout_type getTimeout() {
143 void timeoutExpired() noexcept override {
144 sslSocket_->timeoutExpired(timeout_);
148 AsyncSSLSocket* sslSocket_;
149 TimeoutManager::timeout_type timeout_;
153 * Create a client AsyncSSLSocket
155 AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
156 EventBase* evb, bool deferSecurityNegotiation = false);
159 * Create a server/client AsyncSSLSocket from an already connected
160 * socket file descriptor.
162 * Note that while AsyncSSLSocket enables TCP_NODELAY for sockets it creates
163 * when connecting, it does not change the socket options when given an
164 * existing file descriptor. If callers want TCP_NODELAY enabled when using
165 * this version of the constructor, they need to explicitly call
166 * setNoDelay(true) after the constructor returns.
168 * @param ctx SSL context for this connection.
169 * @param evb EventBase that will manage this socket.
170 * @param fd File descriptor to take over (should be a connected socket).
171 * @param server Is socket in server mode?
172 * @param deferSecurityNegotiation
173 * unencrypted data can be sent before sslConn/Accept
176 const std::shared_ptr<folly::SSLContext>& ctx,
180 bool deferSecurityNegotiation = false);
183 * Create a server/client AsyncSSLSocket from an already connected
187 const std::shared_ptr<folly::SSLContext>& ctx,
188 AsyncSocket::UniquePtr oldAsyncSocket,
190 bool deferSecurityNegotiation = false);
193 * Helper function to create a server/client shared_ptr<AsyncSSLSocket>.
195 static std::shared_ptr<AsyncSSLSocket> newSocket(
196 const std::shared_ptr<folly::SSLContext>& ctx,
197 EventBase* evb, int fd, bool server=true,
198 bool deferSecurityNegotiation = false) {
199 return std::shared_ptr<AsyncSSLSocket>(
200 new AsyncSSLSocket(ctx, evb, fd, server, deferSecurityNegotiation),
205 * Helper function to create a client shared_ptr<AsyncSSLSocket>.
207 static std::shared_ptr<AsyncSSLSocket> newSocket(
208 const std::shared_ptr<folly::SSLContext>& ctx,
209 EventBase* evb, bool deferSecurityNegotiation = false) {
210 return std::shared_ptr<AsyncSSLSocket>(
211 new AsyncSSLSocket(ctx, evb, deferSecurityNegotiation),
216 #if FOLLY_OPENSSL_HAS_SNI
218 * Create a client AsyncSSLSocket with tlsext_servername in
219 * the Client Hello message.
221 AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
223 const std::string& serverName,
224 bool deferSecurityNegotiation = false);
227 * Create a client AsyncSSLSocket from an already connected
228 * socket file descriptor.
230 * Note that while AsyncSSLSocket enables TCP_NODELAY for sockets it creates
231 * when connecting, it does not change the socket options when given an
232 * existing file descriptor. If callers want TCP_NODELAY enabled when using
233 * this version of the constructor, they need to explicitly call
234 * setNoDelay(true) after the constructor returns.
236 * @param ctx SSL context for this connection.
237 * @param evb EventBase that will manage this socket.
238 * @param fd File descriptor to take over (should be a connected socket).
239 * @param serverName tlsext_hostname that will be sent in ClientHello.
242 const std::shared_ptr<folly::SSLContext>& ctx,
245 const std::string& serverName,
246 bool deferSecurityNegotiation = false);
248 static std::shared_ptr<AsyncSSLSocket> newSocket(
249 const std::shared_ptr<folly::SSLContext>& ctx,
251 const std::string& serverName,
252 bool deferSecurityNegotiation = false) {
253 return std::shared_ptr<AsyncSSLSocket>(
254 new AsyncSSLSocket(ctx, evb, serverName, deferSecurityNegotiation),
257 #endif // FOLLY_OPENSSL_HAS_SNI
260 * TODO: implement support for SSL renegotiation.
262 * This involves proper handling of the SSL_ERROR_WANT_READ/WRITE
263 * code as a result of SSL_write/read(), instead of returning an
264 * error. In that case, the READ/WRITE event should be registered,
265 * and a flag (e.g., writeBlockedOnRead) should be set to indiciate
266 * the condition. In the next invocation of read/write callback, if
267 * the flag is on, performWrite()/performRead() should be called in
268 * addition to the normal call to performRead()/performWrite(), and
269 * the flag should be reset.
272 // Inherit TAsyncTransport methods from AsyncSocket except the
274 // See the documentation in TAsyncTransport.h
275 // TODO: implement graceful shutdown in close()
276 // TODO: implement detachSSL() that returns the SSL connection
277 void closeNow() override;
278 void shutdownWrite() override;
279 void shutdownWriteNow() override;
280 bool good() const override;
281 bool connecting() const override;
282 std::string getApplicationProtocol() noexcept override;
284 std::string getSecurityProtocol() const override {
288 void setEorTracking(bool track) override;
289 size_t getRawBytesWritten() const override;
290 size_t getRawBytesReceived() const override;
291 void enableClientHelloParsing();
294 * Accept an SSL connection on the socket.
296 * The callback will be invoked and uninstalled when an SSL
297 * connection has been established on the underlying socket.
298 * The value of verifyPeer determines the client verification method.
299 * By default, its set to use the value in the underlying context
301 * @param callback callback object to invoke on success/failure
302 * @param timeout timeout for this function in milliseconds, or 0 for no
304 * @param verifyPeer SSLVerifyPeerEnum uses the options specified in the
305 * context by default, can be set explcitly to override the
306 * method in the context
308 virtual void sslAccept(
309 HandshakeCB* callback,
310 std::chrono::milliseconds timeout = std::chrono::milliseconds::zero(),
311 const folly::SSLContext::SSLVerifyPeerEnum& verifyPeer =
312 folly::SSLContext::SSLVerifyPeerEnum::USE_CTX);
315 * Invoke SSL accept following an asynchronous session cache lookup
317 void restartSSLAccept();
320 * Connect to the given address, invoking callback when complete or on error
322 * Note timeout applies to TCP + SSL connection time
324 void connect(ConnectCallback* callback,
325 const folly::SocketAddress& address,
327 const OptionMap &options = emptyOptionMap,
328 const folly::SocketAddress& bindAddr = anyAddress())
332 * A variant of connect that allows the caller to specify
333 * the timeout for the regular connect and the ssl connect
335 * connectTimeout is specified as the time to establish a TCP
337 * totalConnectTimeout defines the
338 * time it takes from starting the TCP connection to the time
339 * the ssl connection is established. The reason the timeout is
340 * defined this way is because user's rarely need to specify the SSL
341 * timeout independently of the connect timeout. It allows us to
342 * bound the time for a connect and SSL connection in
343 * a finer grained manner than if timeout was just defined
344 * independently for SSL.
346 virtual void connect(
347 ConnectCallback* callback,
348 const folly::SocketAddress& address,
349 std::chrono::milliseconds connectTimeout,
350 std::chrono::milliseconds totalConnectTimeout,
351 const OptionMap& options = emptyOptionMap,
352 const folly::SocketAddress& bindAddr = anyAddress()) noexcept;
354 using AsyncSocket::connect;
357 * Initiate an SSL connection on the socket
358 * The callback will be invoked and uninstalled when an SSL connection
359 * has been establshed on the underlying socket.
360 * The verification option verifyPeer is applied if it's passed explicitly.
361 * If it's not, the options in SSLContext set on the underlying SSLContext
364 * @param callback callback object to invoke on success/failure
365 * @param timeout timeout for this function in milliseconds, or 0 for no
367 * @param verifyPeer SSLVerifyPeerEnum uses the options specified in the
368 * context by default, can be set explcitly to override the
369 * method in the context. If verification is turned on sets
370 * SSL_VERIFY_PEER and invokes
371 * HandshakeCB::handshakeVer().
373 virtual void sslConn(
374 HandshakeCB* callback,
375 std::chrono::milliseconds timeout = std::chrono::milliseconds::zero(),
376 const folly::SSLContext::SSLVerifyPeerEnum& verifyPeer =
377 folly::SSLContext::SSLVerifyPeerEnum::USE_CTX);
387 STATE_REMOTE_CLOSED, /// remote end closed; we can still write
388 STATE_CLOSING, ///< close() called, but waiting on writes to complete
389 /// close() called with pending writes, before connect() has completed
390 STATE_CONNECTING_CLOSING,
395 SSLStateEnum getSSLState() const { return sslState_;}
398 * Get a handle to the negotiated SSL session. This increments the session
399 * refcount and must be deallocated by the caller.
401 SSL_SESSION *getSSLSession();
404 * Get a handle to the SSL struct.
406 const SSL* getSSL() const;
409 * Set the SSL session to be used during sslConn. AsyncSSLSocket will
410 * hold a reference to the session until it is destroyed or released by the
411 * underlying SSL structure.
413 * @param takeOwnership if true, AsyncSSLSocket will assume the caller's
414 * reference count to session.
416 void setSSLSession(SSL_SESSION *session, bool takeOwnership = false);
419 * Get the name of the protocol selected by the client during
420 * Next Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
423 * Throw an exception if openssl does not support NPN
425 * @param protoName Name of the protocol (not guaranteed to be
426 * null terminated); will be set to nullptr if
427 * the client did not negotiate a protocol.
428 * Note: the AsyncSSLSocket retains ownership
430 * @param protoNameLen Length of the name.
431 * @param protoType Whether this was an NPN or ALPN negotiation
433 virtual void getSelectedNextProtocol(
434 const unsigned char** protoName,
436 SSLContext::NextProtocolType* protoType = nullptr) const;
439 * Get the name of the protocol selected by the client during
440 * Next Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
443 * @param protoName Name of the protocol (not guaranteed to be
444 * null terminated); will be set to nullptr if
445 * the client did not negotiate a protocol.
446 * Note: the AsyncSSLSocket retains ownership
448 * @param protoNameLen Length of the name.
449 * @param protoType Whether this was an NPN or ALPN negotiation
450 * @return false if openssl does not support NPN
452 virtual bool getSelectedNextProtocolNoThrow(
453 const unsigned char** protoName,
455 SSLContext::NextProtocolType* protoType = nullptr) const;
458 * Determine if the session specified during setSSLSession was reused
459 * or if the server rejected it and issued a new session.
461 virtual bool getSSLSessionReused() const;
464 * true if the session was resumed using session ID
466 bool sessionIDResumed() const { return sessionIDResumed_; }
468 void setSessionIDResumed(bool resumed) {
469 sessionIDResumed_ = resumed;
473 * Get the negociated cipher name for this SSL connection.
474 * Returns the cipher used or the constant value "NONE" when no SSL session
475 * has been established.
477 virtual const char* getNegotiatedCipherName() const;
480 * Get the server name for this SSL connection.
481 * Returns the server name used or the constant value "NONE" when no SSL
482 * session has been established.
483 * If openssl has no SNI support, throw TTransportException.
485 const char *getSSLServerName() const;
488 * Get the server name for this SSL connection.
489 * Returns the server name used or the constant value "NONE" when no SSL
490 * session has been established.
491 * If openssl has no SNI support, return "NONE"
493 const char *getSSLServerNameNoThrow() const;
496 * Get the SSL version for this connection.
497 * Possible return values are SSL2_VERSION, SSL3_VERSION, TLS1_VERSION,
498 * with hexa representations 0x200, 0x300, 0x301,
499 * or 0 if no SSL session has been established.
501 int getSSLVersion() const;
504 * Get the signature algorithm used in the cert that is used for this
507 const char *getSSLCertSigAlgName() const;
510 * Get the certificate size used for this SSL connection.
512 int getSSLCertSize() const;
515 * Get the certificate used for this SSL connection. May be null
517 const X509* getSelfCert() const override;
519 void attachEventBase(EventBase* eventBase) override {
520 AsyncSocket::attachEventBase(eventBase);
521 handshakeTimeout_.attachEventBase(eventBase);
522 connectionTimeout_.attachEventBase(eventBase);
525 void detachEventBase() override {
526 AsyncSocket::detachEventBase();
527 handshakeTimeout_.detachEventBase();
528 connectionTimeout_.detachEventBase();
531 bool isDetachable() const override {
532 return AsyncSocket::isDetachable() && !handshakeTimeout_.isScheduled();
535 virtual void attachTimeoutManager(TimeoutManager* manager) {
536 handshakeTimeout_.attachTimeoutManager(manager);
539 virtual void detachTimeoutManager() {
540 handshakeTimeout_.detachTimeoutManager();
543 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
545 * This function will set the SSL context for this socket to the
546 * argument. This should only be used on client SSL Sockets that have
547 * already called detachSSLContext();
549 void attachSSLContext(const std::shared_ptr<folly::SSLContext>& ctx);
552 * Detaches the SSL context for this socket.
554 void detachSSLContext();
557 #if FOLLY_OPENSSL_HAS_SNI
559 * Switch the SSLContext to continue the SSL handshake.
560 * It can only be used in server mode.
562 void switchServerSSLContext(
563 const std::shared_ptr<folly::SSLContext>& handshakeCtx);
566 * Did server recognize/support the tlsext_hostname in Client Hello?
567 * It can only be used in client mode.
569 * @return true - tlsext_hostname is matched by the server
570 * false - tlsext_hostname is not matched or
571 * is not supported by server
573 bool isServerNameMatch() const;
576 * Set the SNI hostname that we'll advertise to the server in the
577 * ClientHello message.
579 void setServerName(std::string serverName) noexcept;
580 #endif // FOLLY_OPENSSL_HAS_SNI
582 void timeoutExpired(std::chrono::milliseconds timeout) noexcept;
585 * Get the list of supported ciphers sent by the client in the client's
588 void getSSLClientCiphers(
589 std::string& clientCiphers,
590 bool convertToString = true) const;
593 * Get the list of compression methods sent by the client in TLS Hello.
595 std::string getSSLClientComprMethods() const;
598 * Get the list of TLS extensions sent by the client in the TLS Hello.
600 std::string getSSLClientExts() const;
602 std::string getSSLClientSigAlgs() const;
605 * Get the list of versions in the supported versions extension (used to
606 * negotiate TLS 1.3).
608 std::string getSSLClientSupportedVersions() const;
610 std::string getSSLAlertsReceived() const;
613 * Save an optional alert message generated during certificate verify
615 void setSSLCertVerificationAlert(std::string alert);
617 std::string getSSLCertVerificationAlert() const;
620 * Get the list of shared ciphers between the server and the client.
621 * Works well for only SSLv2, not so good for SSLv3 or TLSv1.
623 void getSSLSharedCiphers(std::string& sharedCiphers) const;
626 * Get the list of ciphers supported by the server in the server's
629 void getSSLServerCiphers(std::string& serverCiphers) const;
632 * Method to check if peer verfication is set.
634 * @return true if peer verification is required.
636 bool needsPeerVerification() const;
638 static int getSSLExDataIndex();
639 static AsyncSSLSocket* getFromSSL(const SSL *ssl);
640 static int bioWrite(BIO* b, const char* in, int inl);
641 static int bioRead(BIO* b, char* out, int outl);
642 void resetClientHelloParsing(SSL *ssl);
643 static void clientHelloParsingCallback(int write_p, int version,
644 int content_type, const void *buf, size_t len, SSL *ssl, void *arg);
645 static const char* getSSLServerNameFromSSL(SSL* ssl);
648 ssl::ClientHelloInfo* getClientHelloInfo() const {
649 return clientHelloInfo_.get();
653 * Returns the time taken to complete a handshake.
655 virtual std::chrono::nanoseconds getHandshakeTime() const {
656 return handshakeEndTime_ - handshakeStartTime_;
659 void setMinWriteSize(size_t minWriteSize) {
660 minWriteSize_ = minWriteSize;
663 size_t getMinWriteSize() const {
664 return minWriteSize_;
667 void setReadCB(ReadCallback* callback) override;
670 * Tries to enable the buffer movable experimental feature in openssl.
671 * This is not guaranteed to succeed in case openssl does not have
672 * the experimental feature built in.
674 void setBufferMovableEnabled(bool enabled);
677 * Returns the peer certificate, or nullptr if no peer certificate received.
679 ssl::X509UniquePtr getPeerCert() const override {
684 X509* cert = SSL_get_peer_certificate(ssl_);
685 return ssl::X509UniquePtr(cert);
689 * Force AsyncSSLSocket object to cache local and peer socket addresses.
690 * If called with "true" before connect() this function forces full local
691 * and remote socket addresses to be cached in the socket object and available
692 * through getLocalAddress()/getPeerAddress() methods even after the socket is
695 void forceCacheAddrOnFailure(bool force) { cacheAddrOnFailure_ = force; }
697 const std::string& getServiceIdentity() const { return serviceIdentity_; }
699 void setServiceIdentity(std::string serviceIdentity) {
700 serviceIdentity_ = std::move(serviceIdentity);
703 void setCertCacheHit(bool hit) {
707 bool getCertCacheHit() const {
708 return certCacheHit_;
711 bool sessionResumptionAttempted() const {
712 return sessionResumptionAttempted_;
716 * If the SSL socket was used to connect as well
717 * as establish an SSL connection, this gives the total
718 * timeout for the connect + SSL connection that was
721 std::chrono::milliseconds getTotalConnectTimeout() const {
722 return totalConnectTimeout_;
732 * Protected destructor.
734 * Users of AsyncSSLSocket must never delete it directly. Instead, invoke
735 * destroy() instead. (See the documentation in DelayedDestruction.h for
738 ~AsyncSSLSocket() override;
740 // Inherit event notification methods from AsyncSocket except
742 void prepareReadBuffer(void** buf, size_t* buflen) override;
743 void handleRead() noexcept override;
744 void handleWrite() noexcept override;
745 void handleAccept() noexcept;
746 void handleConnect() noexcept override;
748 void invalidState(HandshakeCB* callback);
749 bool willBlock(int ret,
751 unsigned long* errErrorOut) noexcept;
753 void checkForImmediateRead() noexcept override;
754 // AsyncSocket calls this at the wrong time for SSL
755 void handleInitialReadWrite() noexcept override {}
757 WriteResult interpretSSLError(int rc, int error);
758 ReadResult performRead(void** buf, size_t* buflen, size_t* offset) override;
759 WriteResult performWrite(
763 uint32_t* countWritten,
764 uint32_t* partialWritten) override;
766 ssize_t performWriteIovec(const iovec* vec, uint32_t count,
767 WriteFlags flags, uint32_t* countWritten,
768 uint32_t* partialWritten);
770 // This virtual wrapper around SSL_write exists solely for testing/mockability
771 virtual int sslWriteImpl(SSL *ssl, const void *buf, int n) {
772 return SSL_write(ssl, buf, n);
776 * Apply verification options passed to sslConn/sslAccept or those set
777 * in the underlying SSLContext object.
779 * @param ssl pointer to the SSL object on which verification options will be
780 * applied. If verifyPeer_ was explicitly set either via sslConn/sslAccept,
781 * those options override the settings in the underlying SSLContext.
783 void applyVerificationOptions(SSL * ssl);
786 * Sets up SSL with a custom write bio which intercepts all writes.
788 * @return true, if succeeds and false if there is an error creating the bio.
793 * A SSL_write wrapper that understand EOR
795 * @param ssl: SSL* object
796 * @param buf: Buffer to be written
797 * @param n: Number of bytes to be written
798 * @param eor: Does the last byte (buf[n-1]) have the app-last-byte?
799 * @return: The number of app bytes successfully written to the socket
801 int eorAwareSSLWrite(SSL *ssl, const void *buf, int n, bool eor);
803 // Inherit error handling methods from AsyncSocket, plus the following.
804 void failHandshake(const char* fn, const AsyncSocketException& ex);
806 void invokeHandshakeErr(const AsyncSocketException& ex);
807 void invokeHandshakeCB();
809 void invokeConnectErr(const AsyncSocketException& ex) override;
810 void invokeConnectSuccess() override;
811 void scheduleConnectTimeout() override;
813 void startSSLConnect();
815 static void sslInfoCallback(const SSL *ssl, int type, int val);
817 // Whether the current write to the socket should use MSG_MORE.
818 bool corkCurrentWrite_{false};
819 // SSL related members.
821 // Used to prevent client-initiated renegotiation. Note that AsyncSSLSocket
822 // doesn't fully support renegotiation, so we could just fail all attempts
823 // to enforce this. Once it is supported, we should make it an option
824 // to disable client-initiated renegotiation.
825 bool handshakeComplete_{false};
826 bool renegotiateAttempted_{false};
827 SSLStateEnum sslState_{STATE_UNINIT};
828 std::shared_ptr<folly::SSLContext> ctx_;
829 // Callback for SSL_accept() or SSL_connect()
830 HandshakeCB* handshakeCallback_{nullptr};
832 SSL_SESSION *sslSession_{nullptr};
833 Timeout handshakeTimeout_;
834 Timeout connectionTimeout_;
835 // whether the SSL session was resumed using session ID or not
836 bool sessionIDResumed_{false};
838 // The app byte num that we are tracking for the MSG_EOR
839 // Only one app EOR byte can be tracked.
840 size_t appEorByteNo_{0};
842 // Try to avoid calling SSL_write() for buffers smaller than this.
843 // It doesn't take effect when it is 0.
844 size_t minWriteSize_{1500};
846 // When openssl is about to sendmsg() across the minEorRawBytesNo_,
847 // it will pass MSG_EOR to sendmsg().
848 size_t minEorRawByteNo_{0};
849 #if FOLLY_OPENSSL_HAS_SNI
850 std::shared_ptr<folly::SSLContext> handshakeCtx_;
851 std::string tlsextHostname_;
854 // a service identity that this socket/connection is associated with
855 std::string serviceIdentity_;
857 folly::SSLContext::SSLVerifyPeerEnum
858 verifyPeer_{folly::SSLContext::SSLVerifyPeerEnum::USE_CTX};
860 // Callback for SSL_CTX_set_verify()
861 static int sslVerifyCallback(int preverifyOk, X509_STORE_CTX* ctx);
863 bool parseClientHello_{false};
864 bool cacheAddrOnFailure_{false};
865 bool bufferMovableEnabled_{false};
866 bool certCacheHit_{false};
867 std::unique_ptr<ssl::ClientHelloInfo> clientHelloInfo_;
868 std::vector<std::pair<char, StringPiece>> alertsReceived_;
870 // Time taken to complete the ssl handshake.
871 std::chrono::steady_clock::time_point handshakeStartTime_;
872 std::chrono::steady_clock::time_point handshakeEndTime_;
873 std::chrono::milliseconds handshakeConnectTimeout_{0};
874 bool sessionResumptionAttempted_{false};
875 std::chrono::milliseconds totalConnectTimeout_{0};
877 std::string sslVerificationAlert_;