2 * Copyright 2015 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.
19 #include <arpa/inet.h>
21 #include <openssl/ssl.h>
23 #include <folly/Optional.h>
24 #include <folly/String.h>
25 #include <folly/io/async/AsyncSocket.h>
26 #include <folly/io/async/SSLContext.h>
27 #include <folly/io/async/AsyncTimeout.h>
28 #include <folly/io/async/TimeoutManager.h>
30 #include <folly/Bits.h>
31 #include <folly/io/IOBuf.h>
32 #include <folly/io/Cursor.h>
36 class SSLException: public folly::AsyncSocketException {
38 SSLException(int sslError, int errno_copy);
40 int getSSLError() const { return error_; }
48 * A class for performing asynchronous I/O on an SSL connection.
50 * AsyncSSLSocket allows users to asynchronously wait for data on an
51 * SSL connection, and to asynchronously send data.
53 * The APIs for reading and writing are intentionally asymmetric.
54 * Waiting for data to read is a persistent API: a callback is
55 * installed, and is notified whenever new data is available. It
56 * continues to be notified of new events until it is uninstalled.
58 * AsyncSSLSocket does not provide read timeout functionality,
59 * because it typically cannot determine when the timeout should be
60 * active. Generally, a timeout should only be enabled when
61 * processing is blocked waiting on data from the remote endpoint.
62 * For server connections, the timeout should not be active if the
63 * server is currently processing one or more outstanding requests for
64 * this connection. For client connections, the timeout should not be
65 * active if there are no requests pending on the connection.
66 * Additionally, if a client has multiple pending requests, it will
67 * ususally want a separate timeout for each request, rather than a
68 * single read timeout.
70 * The write API is fairly intuitive: a user can request to send a
71 * block of data, and a callback will be informed once the entire
72 * block has been transferred to the kernel, or on error.
73 * AsyncSSLSocket does provide a send timeout, since most callers
74 * want to give up if the remote end stops responding and no further
75 * progress can be made sending the data.
77 class AsyncSSLSocket : public virtual AsyncSocket {
79 typedef std::unique_ptr<AsyncSSLSocket, Destructor> UniquePtr;
80 using X509_deleter = folly::static_function_deleter<X509, &X509_free>;
84 virtual ~HandshakeCB() = default;
87 * handshakeVer() is invoked during handshaking to give the
88 * application chance to validate it's peer's certificate.
90 * Note that OpenSSL performs only rudimentary internal
91 * consistency verification checks by itself. Any other validation
92 * like whether or not the certificate was issued by a trusted CA.
93 * The default implementation of this callback mimics what what
94 * OpenSSL does internally if SSL_VERIFY_PEER is set with no
95 * verification callback.
97 * See the passages on verify_callback in SSL_CTX_set_verify(3)
100 virtual bool handshakeVer(AsyncSSLSocket* /*sock*/,
102 X509_STORE_CTX* /*ctx*/) noexcept {
107 * handshakeSuc() is called when a new SSL connection is
108 * established, i.e., after SSL_accept/connect() returns successfully.
110 * The HandshakeCB will be uninstalled before handshakeSuc()
113 * @param sock SSL socket on which the handshake was initiated
115 virtual void handshakeSuc(AsyncSSLSocket *sock) noexcept = 0;
118 * handshakeErr() is called if an error occurs while
119 * establishing the SSL connection.
121 * The HandshakeCB will be uninstalled before handshakeErr()
124 * @param sock SSL socket on which the handshake was initiated
125 * @param ex An exception representing the error.
127 virtual void handshakeErr(
128 AsyncSSLSocket *sock,
129 const AsyncSocketException& ex)
133 class HandshakeTimeout : public AsyncTimeout {
135 HandshakeTimeout(AsyncSSLSocket* sslSocket, EventBase* eventBase)
136 : AsyncTimeout(eventBase)
137 , sslSocket_(sslSocket) {}
139 virtual void timeoutExpired() noexcept {
140 sslSocket_->timeoutExpired();
144 AsyncSSLSocket* sslSocket_;
149 * These are passed to the application via errno, packed in an SSL err which
150 * are outside the valid errno range. The values are chosen to be unique
151 * against values in ssl.h
154 SSL_CLIENT_RENEGOTIATION_ATTEMPT = 900,
155 SSL_INVALID_RENEGOTIATION = 901,
156 SSL_EARLY_WRITE = 902
160 * Create a client AsyncSSLSocket
162 AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
163 EventBase* evb, bool deferSecurityNegotiation = false);
166 * Create a server/client AsyncSSLSocket from an already connected
167 * socket file descriptor.
169 * Note that while AsyncSSLSocket enables TCP_NODELAY for sockets it creates
170 * when connecting, it does not change the socket options when given an
171 * existing file descriptor. If callers want TCP_NODELAY enabled when using
172 * this version of the constructor, they need to explicitly call
173 * setNoDelay(true) after the constructor returns.
175 * @param ctx SSL context for this connection.
176 * @param evb EventBase that will manage this socket.
177 * @param fd File descriptor to take over (should be a connected socket).
178 * @param server Is socket in server mode?
179 * @param deferSecurityNegotiation
180 * unencrypted data can be sent before sslConn/Accept
182 AsyncSSLSocket(const std::shared_ptr<folly::SSLContext>& ctx,
183 EventBase* evb, int fd,
184 bool server = true, bool deferSecurityNegotiation = false);
188 * Helper function to create a server/client shared_ptr<AsyncSSLSocket>.
190 static std::shared_ptr<AsyncSSLSocket> newSocket(
191 const std::shared_ptr<folly::SSLContext>& ctx,
192 EventBase* evb, int fd, bool server=true,
193 bool deferSecurityNegotiation = false) {
194 return std::shared_ptr<AsyncSSLSocket>(
195 new AsyncSSLSocket(ctx, evb, fd, server, deferSecurityNegotiation),
200 * Helper function to create a client shared_ptr<AsyncSSLSocket>.
202 static std::shared_ptr<AsyncSSLSocket> newSocket(
203 const std::shared_ptr<folly::SSLContext>& ctx,
204 EventBase* evb, bool deferSecurityNegotiation = false) {
205 return std::shared_ptr<AsyncSSLSocket>(
206 new AsyncSSLSocket(ctx, evb, deferSecurityNegotiation),
211 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
213 * Create a client AsyncSSLSocket with tlsext_servername in
214 * the Client Hello message.
216 AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
218 const std::string& serverName,
219 bool deferSecurityNegotiation = false);
222 * Create a client AsyncSSLSocket from an already connected
223 * socket file descriptor.
225 * Note that while AsyncSSLSocket enables TCP_NODELAY for sockets it creates
226 * when connecting, it does not change the socket options when given an
227 * existing file descriptor. If callers want TCP_NODELAY enabled when using
228 * this version of the constructor, they need to explicitly call
229 * setNoDelay(true) after the constructor returns.
231 * @param ctx SSL context for this connection.
232 * @param evb EventBase that will manage this socket.
233 * @param fd File descriptor to take over (should be a connected socket).
234 * @param serverName tlsext_hostname that will be sent in ClientHello.
236 AsyncSSLSocket(const std::shared_ptr<folly::SSLContext>& ctx,
239 const std::string& serverName,
240 bool deferSecurityNegotiation = false);
242 static std::shared_ptr<AsyncSSLSocket> newSocket(
243 const std::shared_ptr<folly::SSLContext>& ctx,
245 const std::string& serverName,
246 bool deferSecurityNegotiation = false) {
247 return std::shared_ptr<AsyncSSLSocket>(
248 new AsyncSSLSocket(ctx, evb, serverName, deferSecurityNegotiation),
254 * TODO: implement support for SSL renegotiation.
256 * This involves proper handling of the SSL_ERROR_WANT_READ/WRITE
257 * code as a result of SSL_write/read(), instead of returning an
258 * error. In that case, the READ/WRITE event should be registered,
259 * and a flag (e.g., writeBlockedOnRead) should be set to indiciate
260 * the condition. In the next invocation of read/write callback, if
261 * the flag is on, performWrite()/performRead() should be called in
262 * addition to the normal call to performRead()/performWrite(), and
263 * the flag should be reset.
266 // Inherit TAsyncTransport methods from AsyncSocket except the
268 // See the documentation in TAsyncTransport.h
269 // TODO: implement graceful shutdown in close()
270 // TODO: implement detachSSL() that returns the SSL connection
271 virtual void closeNow() override;
272 virtual void shutdownWrite() override;
273 virtual void shutdownWriteNow() override;
274 virtual bool good() const override;
275 virtual bool connecting() const override;
277 bool isEorTrackingEnabled() const override;
278 virtual void setEorTracking(bool track) override;
279 virtual size_t getRawBytesWritten() const override;
280 virtual size_t getRawBytesReceived() const override;
281 void enableClientHelloParsing();
284 * Accept an SSL connection on the socket.
286 * The callback will be invoked and uninstalled when an SSL
287 * connection has been established on the underlying socket.
288 * The value of verifyPeer determines the client verification method.
289 * By default, its set to use the value in the underlying context
291 * @param callback callback object to invoke on success/failure
292 * @param timeout timeout for this function in milliseconds, or 0 for no
294 * @param verifyPeer SSLVerifyPeerEnum uses the options specified in the
295 * context by default, can be set explcitly to override the
296 * method in the context
298 virtual void sslAccept(HandshakeCB* callback, uint32_t timeout = 0,
299 const folly::SSLContext::SSLVerifyPeerEnum& verifyPeer =
300 folly::SSLContext::SSLVerifyPeerEnum::USE_CTX);
303 * Invoke SSL accept following an asynchronous session cache lookup
305 void restartSSLAccept();
308 * Connect to the given address, invoking callback when complete or on error
310 * Note timeout applies to TCP + SSL connection time
312 void connect(ConnectCallback* callback,
313 const folly::SocketAddress& address,
315 const OptionMap &options = emptyOptionMap,
316 const folly::SocketAddress& bindAddr = anyAddress())
319 using AsyncSocket::connect;
322 * Initiate an SSL connection on the socket
323 * The callback will be invoked and uninstalled when an SSL connection
324 * has been establshed on the underlying socket.
325 * The verification option verifyPeer is applied if it's passed explicitly.
326 * If it's not, the options in SSLContext set on the underlying SSLContext
329 * @param callback callback object to invoke on success/failure
330 * @param timeout timeout for this function in milliseconds, or 0 for no
332 * @param verifyPeer SSLVerifyPeerEnum uses the options specified in the
333 * context by default, can be set explcitly to override the
334 * method in the context. If verification is turned on sets
335 * SSL_VERIFY_PEER and invokes
336 * HandshakeCB::handshakeVer().
338 virtual void sslConn(HandshakeCB *callback, uint64_t timeout = 0,
339 const folly::SSLContext::SSLVerifyPeerEnum& verifyPeer =
340 folly::SSLContext::SSLVerifyPeerEnum::USE_CTX);
347 STATE_RSA_ASYNC_PENDING,
350 STATE_REMOTE_CLOSED, /// remote end closed; we can still write
351 STATE_CLOSING, ///< close() called, but waiting on writes to complete
352 /// close() called with pending writes, before connect() has completed
353 STATE_CONNECTING_CLOSING,
358 SSLStateEnum getSSLState() const { return sslState_;}
361 * Get a handle to the negotiated SSL session. This increments the session
362 * refcount and must be deallocated by the caller.
364 SSL_SESSION *getSSLSession();
367 * Set the SSL session to be used during sslConn. AsyncSSLSocket will
368 * hold a reference to the session until it is destroyed or released by the
369 * underlying SSL structure.
371 * @param takeOwnership if true, AsyncSSLSocket will assume the caller's
372 * reference count to session.
374 void setSSLSession(SSL_SESSION *session, bool takeOwnership = false);
377 * Get the name of the protocol selected by the client during
378 * Next Protocol Negotiation (NPN)
380 * Throw an exception if openssl does not support NPN
382 * @param protoName Name of the protocol (not guaranteed to be
383 * null terminated); will be set to nullptr if
384 * the client did not negotiate a protocol.
385 * Note: the AsyncSSLSocket retains ownership
387 * @param protoNameLen Length of the name.
389 virtual void getSelectedNextProtocol(const unsigned char** protoName,
390 unsigned* protoLen) const;
393 * Get the name of the protocol selected by the client during
394 * Next Protocol Negotiation (NPN)
396 * @param protoName Name of the protocol (not guaranteed to be
397 * null terminated); will be set to nullptr if
398 * the client did not negotiate a protocol.
399 * Note: the AsyncSSLSocket retains ownership
401 * @param protoNameLen Length of the name.
402 * @return false if openssl does not support NPN
404 virtual bool getSelectedNextProtocolNoThrow(const unsigned char** protoName,
405 unsigned* protoLen) const;
408 * Determine if the session specified during setSSLSession was reused
409 * or if the server rejected it and issued a new session.
411 bool getSSLSessionReused() const;
414 * true if the session was resumed using session ID
416 bool sessionIDResumed() const { return sessionIDResumed_; }
418 void setSessionIDResumed(bool resumed) {
419 sessionIDResumed_ = resumed;
423 * Get the negociated cipher name for this SSL connection.
424 * Returns the cipher used or the constant value "NONE" when no SSL session
425 * has been established.
427 const char *getNegotiatedCipherName() const;
430 * Get the server name for this SSL connection.
431 * Returns the server name used or the constant value "NONE" when no SSL
432 * session has been established.
433 * If openssl has no SNI support, throw TTransportException.
435 const char *getSSLServerName() const;
438 * Get the server name for this SSL connection.
439 * Returns the server name used or the constant value "NONE" when no SSL
440 * session has been established.
441 * If openssl has no SNI support, return "NONE"
443 const char *getSSLServerNameNoThrow() const;
446 * Get the SSL version for this connection.
447 * Possible return values are SSL2_VERSION, SSL3_VERSION, TLS1_VERSION,
448 * with hexa representations 0x200, 0x300, 0x301,
449 * or 0 if no SSL session has been established.
451 int getSSLVersion() const;
454 * Get the signature algorithm used in the cert that is used for this
457 const char *getSSLCertSigAlgName() const;
460 * Get the certificate size used for this SSL connection.
462 int getSSLCertSize() const;
464 /* Get the number of bytes read from the wire (including protocol
465 * overhead). Returns 0 once the connection has been closed.
467 unsigned long getBytesRead() const {
468 if (ssl_ != nullptr) {
469 return BIO_number_read(SSL_get_rbio(ssl_));
474 /* Get the number of bytes written to the wire (including protocol
475 * overhead). Returns 0 once the connection has been closed.
477 unsigned long getBytesWritten() const {
478 if (ssl_ != nullptr) {
479 return BIO_number_written(SSL_get_wbio(ssl_));
484 virtual void attachEventBase(EventBase* eventBase) override {
485 AsyncSocket::attachEventBase(eventBase);
486 handshakeTimeout_.attachEventBase(eventBase);
489 virtual void detachEventBase() override {
490 AsyncSocket::detachEventBase();
491 handshakeTimeout_.detachEventBase();
494 virtual bool isDetachable() const override {
495 return AsyncSocket::isDetachable() && !handshakeTimeout_.isScheduled();
498 virtual void attachTimeoutManager(TimeoutManager* manager) {
499 handshakeTimeout_.attachTimeoutManager(manager);
502 virtual void detachTimeoutManager() {
503 handshakeTimeout_.detachTimeoutManager();
506 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
508 * This function will set the SSL context for this socket to the
509 * argument. This should only be used on client SSL Sockets that have
510 * already called detachSSLContext();
512 void attachSSLContext(const std::shared_ptr<folly::SSLContext>& ctx);
515 * Detaches the SSL context for this socket.
517 void detachSSLContext();
520 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
522 * Switch the SSLContext to continue the SSL handshake.
523 * It can only be used in server mode.
525 void switchServerSSLContext(
526 const std::shared_ptr<folly::SSLContext>& handshakeCtx);
529 * Did server recognize/support the tlsext_hostname in Client Hello?
530 * It can only be used in client mode.
532 * @return true - tlsext_hostname is matched by the server
533 * false - tlsext_hostname is not matched or
534 * is not supported by server
536 bool isServerNameMatch() const;
539 * Set the SNI hostname that we'll advertise to the server in the
540 * ClientHello message.
542 void setServerName(std::string serverName) noexcept;
545 void timeoutExpired() noexcept;
548 * Get the list of supported ciphers sent by the client in the client's
551 void getSSLClientCiphers(std::string& clientCiphers) const {
552 std::stringstream ciphersStream;
553 std::string cipherName;
555 if (parseClientHello_ == false
556 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
561 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
563 // OpenSSL expects code as a big endian char array
564 auto cipherCode = htons(originalCipherCode);
566 #if defined(SSL_OP_NO_TLSv1_2)
567 const SSL_CIPHER* cipher =
568 TLSv1_2_method()->get_cipher_by_char((unsigned char*)&cipherCode);
569 #elif defined(SSL_OP_NO_TLSv1_1)
570 const SSL_CIPHER* cipher =
571 TLSv1_1_method()->get_cipher_by_char((unsigned char*)&cipherCode);
572 #elif defined(SSL_OP_NO_TLSv1)
573 const SSL_CIPHER* cipher =
574 TLSv1_method()->get_cipher_by_char((unsigned char*)&cipherCode);
576 const SSL_CIPHER* cipher =
577 SSLv3_method()->get_cipher_by_char((unsigned char*)&cipherCode);
580 if (cipher == nullptr) {
581 ciphersStream << std::setfill('0') << std::setw(4) << std::hex
582 << originalCipherCode << ":";
584 ciphersStream << SSL_CIPHER_get_name(cipher) << ":";
588 clientCiphers = ciphersStream.str();
589 clientCiphers.erase(clientCiphers.end() - 1);
593 * Get the list of compression methods sent by the client in TLS Hello.
595 std::string getSSLClientComprMethods() const {
596 if (!parseClientHello_) {
599 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
603 * Get the list of TLS extensions sent by the client in the TLS Hello.
605 std::string getSSLClientExts() const {
606 if (!parseClientHello_) {
609 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
612 std::string getSSLClientSigAlgs() const {
613 if (!parseClientHello_) {
618 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
619 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
621 sigAlgs.push_back(':');
623 sigAlgs.append(folly::to<std::string>(
624 clientHelloInfo_->clientHelloSigAlgs_[i].first));
625 sigAlgs.push_back(',');
626 sigAlgs.append(folly::to<std::string>(
627 clientHelloInfo_->clientHelloSigAlgs_[i].second));
634 * Get the list of shared ciphers between the server and the client.
635 * Works well for only SSLv2, not so good for SSLv3 or TLSv1.
637 void getSSLSharedCiphers(std::string& sharedCiphers) const {
638 char ciphersBuffer[1024];
639 ciphersBuffer[0] = '\0';
640 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
641 sharedCiphers = ciphersBuffer;
645 * Get the list of ciphers supported by the server in the server's
648 void getSSLServerCiphers(std::string& serverCiphers) const {
649 serverCiphers = SSL_get_cipher_list(ssl_, 0);
652 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
653 serverCiphers.append(":");
654 serverCiphers.append(cipher);
659 static int getSSLExDataIndex();
660 static AsyncSSLSocket* getFromSSL(const SSL *ssl);
661 static int eorAwareBioWrite(BIO *b, const char *in, int inl);
662 void resetClientHelloParsing(SSL *ssl);
663 static void clientHelloParsingCallback(int write_p, int version,
664 int content_type, const void *buf, size_t len, SSL *ssl, void *arg);
666 // http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
667 enum class TLSExtension: uint16_t {
669 MAX_FRAGMENT_LENGTH = 1,
670 CLIENT_CERTIFICATE_URL = 2,
678 SUPPORTED_GROUPS = 10,
679 EC_POINT_FORMATS = 11,
681 SIGNATURE_ALGORITHMS = 13,
684 APPLICATION_LAYER_PROTOCOL_NEGOTIATION = 16,
685 STATUS_REQUEST_V2 = 17,
686 SIGNED_CERTIFICATE_TIMESTAMP = 18,
687 CLIENT_CERTIFICATE_TYPE = 19,
688 SERVER_CERTIFICATE_TYPE = 20,
690 ENCRYPT_THEN_MAC = 22,
691 EXTENDED_MASTER_SECRET = 23,
693 RENEGOTIATION_INFO = 65281
696 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-18
697 enum class HashAlgorithm: uint8_t {
707 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-16
708 enum class SignatureAlgorithm: uint8_t {
715 struct ClientHelloInfo {
716 folly::IOBufQueue clientHelloBuf_;
717 uint8_t clientHelloMajorVersion_;
718 uint8_t clientHelloMinorVersion_;
719 std::vector<uint16_t> clientHelloCipherSuites_;
720 std::vector<uint8_t> clientHelloCompressionMethods_;
721 std::vector<TLSExtension> clientHelloExtensions_;
723 std::pair<HashAlgorithm, SignatureAlgorithm>> clientHelloSigAlgs_;
727 ClientHelloInfo* getClientHelloInfo() const {
728 return clientHelloInfo_.get();
732 * Returns the time taken to complete a handshake.
734 std::chrono::nanoseconds getHandshakeTime() const {
735 return handshakeEndTime_ - handshakeStartTime_;
738 void setMinWriteSize(size_t minWriteSize) {
739 minWriteSize_ = minWriteSize;
742 size_t getMinWriteSize() const {
743 return minWriteSize_;
746 void setReadCB(ReadCallback* callback) override;
749 * Returns the peer certificate, or nullptr if no peer certificate received.
751 std::unique_ptr<X509, X509_deleter> getPeerCert() const {
756 X509* cert = SSL_get_peer_certificate(ssl_);
757 return std::unique_ptr<X509, X509_deleter>(cert);
767 * Protected destructor.
769 * Users of AsyncSSLSocket must never delete it directly. Instead, invoke
770 * destroy() instead. (See the documentation in DelayedDestruction.h for
775 // Inherit event notification methods from AsyncSocket except
777 void prepareReadBuffer(void** buf, size_t* buflen) noexcept override;
778 void handleRead() noexcept override;
779 void handleWrite() noexcept override;
780 void handleAccept() noexcept;
781 void handleConnect() noexcept override;
783 void invalidState(HandshakeCB* callback);
784 bool willBlock(int ret, int *errorOut) noexcept;
786 virtual void checkForImmediateRead() noexcept override;
787 // AsyncSocket calls this at the wrong time for SSL
788 void handleInitialReadWrite() noexcept override {}
790 int interpretSSLError(int rc, int error);
791 ssize_t performRead(void** buf, size_t* buflen, size_t* offset) override;
792 ssize_t performWrite(const iovec* vec, uint32_t count, WriteFlags flags,
793 uint32_t* countWritten, uint32_t* partialWritten)
796 ssize_t performWriteIovec(const iovec* vec, uint32_t count,
797 WriteFlags flags, uint32_t* countWritten,
798 uint32_t* partialWritten);
800 // This virtual wrapper around SSL_write exists solely for testing/mockability
801 virtual int sslWriteImpl(SSL *ssl, const void *buf, int n) {
802 return SSL_write(ssl, buf, n);
806 * Apply verification options passed to sslConn/sslAccept or those set
807 * in the underlying SSLContext object.
809 * @param ssl pointer to the SSL object on which verification options will be
810 * applied. If verifyPeer_ was explicitly set either via sslConn/sslAccept,
811 * those options override the settings in the underlying SSLContext.
813 void applyVerificationOptions(SSL * ssl);
816 * A SSL_write wrapper that understand EOR
818 * @param ssl: SSL* object
819 * @param buf: Buffer to be written
820 * @param n: Number of bytes to be written
821 * @param eor: Does the last byte (buf[n-1]) have the app-last-byte?
822 * @return: The number of app bytes successfully written to the socket
824 int eorAwareSSLWrite(SSL *ssl, const void *buf, int n, bool eor);
826 // Inherit error handling methods from AsyncSocket, plus the following.
827 void failHandshake(const char* fn, const AsyncSocketException& ex);
829 void invokeHandshakeErr(const AsyncSocketException& ex);
830 void invokeHandshakeCB();
832 static void sslInfoCallback(const SSL *ssl, int type, int val);
834 // Whether we've applied the TCP_CORK option to the socket
836 // SSL related members.
838 // Used to prevent client-initiated renegotiation. Note that AsyncSSLSocket
839 // doesn't fully support renegotiation, so we could just fail all attempts
840 // to enforce this. Once it is supported, we should make it an option
841 // to disable client-initiated renegotiation.
842 bool handshakeComplete_{false};
843 bool renegotiateAttempted_{false};
844 SSLStateEnum sslState_{STATE_UNINIT};
845 std::shared_ptr<folly::SSLContext> ctx_;
846 // Callback for SSL_accept() or SSL_connect()
847 HandshakeCB* handshakeCallback_{nullptr};
849 SSL_SESSION *sslSession_{nullptr};
850 HandshakeTimeout handshakeTimeout_;
851 // whether the SSL session was resumed using session ID or not
852 bool sessionIDResumed_{false};
854 // The app byte num that we are tracking for the MSG_EOR
855 // Only one app EOR byte can be tracked.
856 size_t appEorByteNo_{0};
858 // Try to avoid calling SSL_write() for buffers smaller than this.
859 // It doesn't take effect when it is 0.
860 size_t minWriteSize_{1500};
862 // When openssl is about to sendmsg() across the minEorRawBytesNo_,
863 // it will pass MSG_EOR to sendmsg().
864 size_t minEorRawByteNo_{0};
865 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
866 std::shared_ptr<folly::SSLContext> handshakeCtx_;
867 std::string tlsextHostname_;
869 folly::SSLContext::SSLVerifyPeerEnum
870 verifyPeer_{folly::SSLContext::SSLVerifyPeerEnum::USE_CTX};
872 // Callback for SSL_CTX_set_verify()
873 static int sslVerifyCallback(int preverifyOk, X509_STORE_CTX* ctx);
875 bool parseClientHello_{false};
876 std::unique_ptr<ClientHelloInfo> clientHelloInfo_;
878 // Time taken to complete the ssl handshake.
879 std::chrono::steady_clock::time_point handshakeStartTime_;
880 std::chrono::steady_clock::time_point handshakeEndTime_;