Sort #include lines
[folly.git] / folly / io / async / AsyncSSLSocket.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <iomanip>
20
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>
36
37 namespace folly {
38
39 /**
40  * A class for performing asynchronous I/O on an SSL connection.
41  *
42  * AsyncSSLSocket allows users to asynchronously wait for data on an
43  * SSL connection, and to asynchronously send data.
44  *
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.
49  *
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.
61  *
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.
68  */
69 class AsyncSSLSocket : public virtual AsyncSocket {
70  public:
71   typedef std::unique_ptr<AsyncSSLSocket, Destructor> UniquePtr;
72   using X509_deleter = folly::static_function_deleter<X509, &X509_free>;
73
74   class HandshakeCB {
75    public:
76     virtual ~HandshakeCB() = default;
77
78     /**
79      * handshakeVer() is invoked during handshaking to give the
80      * application chance to validate it's peer's certificate.
81      *
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.
88      *
89      * See the passages on verify_callback in SSL_CTX_set_verify(3)
90      * for more details.
91      */
92     virtual bool handshakeVer(AsyncSSLSocket* /*sock*/,
93                                  bool preverifyOk,
94                                  X509_STORE_CTX* /*ctx*/) noexcept {
95       return preverifyOk;
96     }
97
98     /**
99      * handshakeSuc() is called when a new SSL connection is
100      * established, i.e., after SSL_accept/connect() returns successfully.
101      *
102      * The HandshakeCB will be uninstalled before handshakeSuc()
103      * is called.
104      *
105      * @param sock  SSL socket on which the handshake was initiated
106      */
107     virtual void handshakeSuc(AsyncSSLSocket *sock) noexcept = 0;
108
109     /**
110      * handshakeErr() is called if an error occurs while
111      * establishing the SSL connection.
112      *
113      * The HandshakeCB will be uninstalled before handshakeErr()
114      * is called.
115      *
116      * @param sock  SSL socket on which the handshake was initiated
117      * @param ex  An exception representing the error.
118      */
119     virtual void handshakeErr(
120       AsyncSSLSocket *sock,
121       const AsyncSocketException& ex)
122       noexcept = 0;
123   };
124
125   class Timeout : public AsyncTimeout {
126    public:
127     Timeout(AsyncSSLSocket* sslSocket, EventBase* eventBase)
128         : AsyncTimeout(eventBase), sslSocket_(sslSocket) {}
129
130     bool scheduleTimeout(TimeoutManager::timeout_type timeout) {
131       timeout_ = timeout;
132       return AsyncTimeout::scheduleTimeout(timeout);
133     }
134
135     bool scheduleTimeout(uint32_t timeoutMs) {
136       return scheduleTimeout(std::chrono::milliseconds{timeoutMs});
137     }
138
139     TimeoutManager::timeout_type getTimeout() {
140       return timeout_;
141     }
142
143     void timeoutExpired() noexcept override {
144       sslSocket_->timeoutExpired(timeout_);
145     }
146
147    private:
148     AsyncSSLSocket* sslSocket_;
149     TimeoutManager::timeout_type timeout_;
150   };
151
152   /**
153    * Create a client AsyncSSLSocket
154    */
155   AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
156                  EventBase* evb, bool deferSecurityNegotiation = false);
157
158   /**
159    * Create a server/client AsyncSSLSocket from an already connected
160    * socket file descriptor.
161    *
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.
167    *
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
174    */
175   AsyncSSLSocket(
176       const std::shared_ptr<folly::SSLContext>& ctx,
177       EventBase* evb,
178       int fd,
179       bool server = true,
180       bool deferSecurityNegotiation = false);
181
182   /**
183    * Create a server/client AsyncSSLSocket from an already connected
184    * AsyncSocket.
185    */
186   AsyncSSLSocket(
187       const std::shared_ptr<folly::SSLContext>& ctx,
188       AsyncSocket::UniquePtr oldAsyncSocket,
189       bool server = true,
190       bool deferSecurityNegotiation = false);
191
192   /**
193    * Helper function to create a server/client shared_ptr<AsyncSSLSocket>.
194    */
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),
201       Destructor());
202   }
203
204   /**
205    * Helper function to create a client shared_ptr<AsyncSSLSocket>.
206    */
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),
212       Destructor());
213   }
214
215
216 #if FOLLY_OPENSSL_HAS_SNI
217   /**
218    * Create a client AsyncSSLSocket with tlsext_servername in
219    * the Client Hello message.
220    */
221   AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
222                   EventBase* evb,
223                  const std::string& serverName,
224                 bool deferSecurityNegotiation = false);
225
226   /**
227    * Create a client AsyncSSLSocket from an already connected
228    * socket file descriptor.
229    *
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.
235    *
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.
240    */
241   AsyncSSLSocket(
242       const std::shared_ptr<folly::SSLContext>& ctx,
243       EventBase* evb,
244       int fd,
245       const std::string& serverName,
246       bool deferSecurityNegotiation = false);
247
248   static std::shared_ptr<AsyncSSLSocket> newSocket(
249     const std::shared_ptr<folly::SSLContext>& ctx,
250     EventBase* evb,
251     const std::string& serverName,
252     bool deferSecurityNegotiation = false) {
253     return std::shared_ptr<AsyncSSLSocket>(
254       new AsyncSSLSocket(ctx, evb, serverName, deferSecurityNegotiation),
255       Destructor());
256   }
257 #endif // FOLLY_OPENSSL_HAS_SNI
258
259   /**
260    * TODO: implement support for SSL renegotiation.
261    *
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.
270    */
271
272   // Inherit TAsyncTransport methods from AsyncSocket except the
273   // following.
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;
283
284   std::string getSecurityProtocol() const override {
285     return "TLS";
286   }
287
288   void setEorTracking(bool track) override;
289   size_t getRawBytesWritten() const override;
290   size_t getRawBytesReceived() const override;
291   void enableClientHelloParsing();
292
293   /**
294    * Accept an SSL connection on the socket.
295    *
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
300    *
301    * @param callback callback object to invoke on success/failure
302    * @param timeout timeout for this function in milliseconds, or 0 for no
303    *                timeout
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
307    */
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);
313
314   /**
315    * Invoke SSL accept following an asynchronous session cache lookup
316    */
317   void restartSSLAccept();
318
319   /**
320    * Connect to the given address, invoking callback when complete or on error
321    *
322    * Note timeout applies to TCP + SSL connection time
323    */
324   void connect(ConnectCallback* callback,
325                const folly::SocketAddress& address,
326                int timeout = 0,
327                const OptionMap &options = emptyOptionMap,
328                const folly::SocketAddress& bindAddr = anyAddress())
329                noexcept override;
330
331   /**
332    * A variant of connect that allows the caller to specify
333    * the timeout for the regular connect and the ssl connect
334    * separately.
335    * connectTimeout is specified as the time to establish a TCP
336    * connection.
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.
345    */
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;
353
354   using AsyncSocket::connect;
355
356   /**
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
362    * are applied.
363    *
364    * @param callback callback object to invoke on success/failure
365    * @param timeout timeout for this function in milliseconds, or 0 for no
366    *                timeout
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().
372    */
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);
378
379   enum SSLStateEnum {
380     STATE_UNINIT,
381     STATE_UNENCRYPTED,
382     STATE_ACCEPTING,
383     STATE_CACHE_LOOKUP,
384     STATE_ASYNC_PENDING,
385     STATE_CONNECTING,
386     STATE_ESTABLISHED,
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,
391     STATE_CLOSED,
392     STATE_ERROR
393   };
394
395   SSLStateEnum getSSLState() const { return sslState_;}
396
397   /**
398    * Get a handle to the negotiated SSL session.  This increments the session
399    * refcount and must be deallocated by the caller.
400    */
401   SSL_SESSION *getSSLSession();
402
403   /**
404    * Get a handle to the SSL struct.
405    */
406   const SSL* getSSL() const;
407
408   /**
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.
412    *
413    * @param takeOwnership if true, AsyncSSLSocket will assume the caller's
414    *                      reference count to session.
415    */
416   void setSSLSession(SSL_SESSION *session, bool takeOwnership = false);
417
418   /**
419    * Get the name of the protocol selected by the client during
420    * Next Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
421    * (ALPN)
422    *
423    * Throw an exception if openssl does not support NPN
424    *
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
429    *                       of this string.
430    * @param protoNameLen   Length of the name.
431    * @param protoType      Whether this was an NPN or ALPN negotiation
432    */
433   virtual void getSelectedNextProtocol(
434       const unsigned char** protoName,
435       unsigned* protoLen,
436       SSLContext::NextProtocolType* protoType = nullptr) const;
437
438   /**
439    * Get the name of the protocol selected by the client during
440    * Next Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
441    * (ALPN)
442    *
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
447    *                       of this string.
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
451    */
452   virtual bool getSelectedNextProtocolNoThrow(
453       const unsigned char** protoName,
454       unsigned* protoLen,
455       SSLContext::NextProtocolType* protoType = nullptr) const;
456
457   /**
458    * Determine if the session specified during setSSLSession was reused
459    * or if the server rejected it and issued a new session.
460    */
461   virtual bool getSSLSessionReused() const;
462
463   /**
464    * true if the session was resumed using session ID
465    */
466   bool sessionIDResumed() const { return sessionIDResumed_; }
467
468   void setSessionIDResumed(bool resumed) {
469     sessionIDResumed_ = resumed;
470   }
471
472   /**
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.
476    */
477   virtual const char* getNegotiatedCipherName() const;
478
479   /**
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.
484    */
485   const char *getSSLServerName() const;
486
487   /**
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"
492    */
493   const char *getSSLServerNameNoThrow() const;
494
495   /**
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.
500    */
501   int getSSLVersion() const;
502
503   /**
504    * Get the signature algorithm used in the cert that is used for this
505    * connection.
506    */
507   const char *getSSLCertSigAlgName() const;
508
509   /**
510    * Get the certificate size used for this SSL connection.
511    */
512   int getSSLCertSize() const;
513
514   /**
515    * Get the certificate used for this SSL connection. May be null
516    */
517   const X509* getSelfCert() const override;
518
519   void attachEventBase(EventBase* eventBase) override {
520     AsyncSocket::attachEventBase(eventBase);
521     handshakeTimeout_.attachEventBase(eventBase);
522     connectionTimeout_.attachEventBase(eventBase);
523   }
524
525   void detachEventBase() override {
526     AsyncSocket::detachEventBase();
527     handshakeTimeout_.detachEventBase();
528     connectionTimeout_.detachEventBase();
529   }
530
531   bool isDetachable() const override {
532     return AsyncSocket::isDetachable() && !handshakeTimeout_.isScheduled();
533   }
534
535   virtual void attachTimeoutManager(TimeoutManager* manager) {
536     handshakeTimeout_.attachTimeoutManager(manager);
537   }
538
539   virtual void detachTimeoutManager() {
540     handshakeTimeout_.detachTimeoutManager();
541   }
542
543 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
544   /**
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();
548    */
549   void attachSSLContext(const std::shared_ptr<folly::SSLContext>& ctx);
550
551   /**
552    * Detaches the SSL context for this socket.
553    */
554   void detachSSLContext();
555 #endif
556
557 #if FOLLY_OPENSSL_HAS_SNI
558   /**
559    * Switch the SSLContext to continue the SSL handshake.
560    * It can only be used in server mode.
561    */
562   void switchServerSSLContext(
563     const std::shared_ptr<folly::SSLContext>& handshakeCtx);
564
565   /**
566    * Did server recognize/support the tlsext_hostname in Client Hello?
567    * It can only be used in client mode.
568    *
569    * @return true - tlsext_hostname is matched by the server
570    *         false - tlsext_hostname is not matched or
571    *                 is not supported by server
572    */
573   bool isServerNameMatch() const;
574
575   /**
576    * Set the SNI hostname that we'll advertise to the server in the
577    * ClientHello message.
578    */
579   void setServerName(std::string serverName) noexcept;
580 #endif // FOLLY_OPENSSL_HAS_SNI
581
582   void timeoutExpired(std::chrono::milliseconds timeout) noexcept;
583
584   /**
585    * Get the list of supported ciphers sent by the client in the client's
586    * preference order.
587    */
588   void getSSLClientCiphers(
589       std::string& clientCiphers,
590       bool convertToString = true) const;
591
592   /**
593    * Get the list of compression methods sent by the client in TLS Hello.
594    */
595   std::string getSSLClientComprMethods() const;
596
597   /**
598    * Get the list of TLS extensions sent by the client in the TLS Hello.
599    */
600   std::string getSSLClientExts() const;
601
602   std::string getSSLClientSigAlgs() const;
603
604   /**
605    * Get the list of versions in the supported versions extension (used to
606    * negotiate TLS 1.3).
607    */
608   std::string getSSLClientSupportedVersions() const;
609
610   std::string getSSLAlertsReceived() const;
611
612   /*
613    * Save an optional alert message generated during certificate verify
614    */
615   void setSSLCertVerificationAlert(std::string alert);
616
617   std::string getSSLCertVerificationAlert() const;
618
619   /**
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.
622    */
623   void getSSLSharedCiphers(std::string& sharedCiphers) const;
624
625   /**
626    * Get the list of ciphers supported by the server in the server's
627    * preference order.
628    */
629   void getSSLServerCiphers(std::string& serverCiphers) const;
630
631   /**
632    * Method to check if peer verfication is set.
633    *
634    * @return true if peer verification is required.
635    */
636   bool needsPeerVerification() const;
637
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);
646
647   // For unit-tests
648   ssl::ClientHelloInfo* getClientHelloInfo() const {
649     return clientHelloInfo_.get();
650   }
651
652   /**
653    * Returns the time taken to complete a handshake.
654    */
655   virtual std::chrono::nanoseconds getHandshakeTime() const {
656     return handshakeEndTime_ - handshakeStartTime_;
657   }
658
659   void setMinWriteSize(size_t minWriteSize) {
660     minWriteSize_ = minWriteSize;
661   }
662
663   size_t getMinWriteSize() const {
664     return minWriteSize_;
665   }
666
667   void setReadCB(ReadCallback* callback) override;
668
669   /**
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.
673    */
674   void setBufferMovableEnabled(bool enabled);
675
676   /**
677    * Returns the peer certificate, or nullptr if no peer certificate received.
678    */
679   ssl::X509UniquePtr getPeerCert() const override {
680     if (!ssl_) {
681       return nullptr;
682     }
683
684     X509* cert = SSL_get_peer_certificate(ssl_);
685     return ssl::X509UniquePtr(cert);
686   }
687
688   /**
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
693    * closed.
694    */
695   void forceCacheAddrOnFailure(bool force) { cacheAddrOnFailure_ = force; }
696
697   const std::string& getServiceIdentity() const { return serviceIdentity_; }
698
699   void setServiceIdentity(std::string serviceIdentity) {
700     serviceIdentity_ = std::move(serviceIdentity);
701   }
702
703   void setCertCacheHit(bool hit) {
704     certCacheHit_ = hit;
705   }
706
707   bool getCertCacheHit() const {
708     return certCacheHit_;
709   }
710
711   bool sessionResumptionAttempted() const {
712     return sessionResumptionAttempted_;
713   }
714
715   /**
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
719    * set.
720    */
721   std::chrono::milliseconds getTotalConnectTimeout() const {
722     return totalConnectTimeout_;
723   }
724
725  private:
726
727   void init();
728
729  protected:
730
731   /**
732    * Protected destructor.
733    *
734    * Users of AsyncSSLSocket must never delete it directly.  Instead, invoke
735    * destroy() instead.  (See the documentation in DelayedDestruction.h for
736    * more details.)
737    */
738   ~AsyncSSLSocket() override;
739
740   // Inherit event notification methods from AsyncSocket except
741   // the following.
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;
747
748   void invalidState(HandshakeCB* callback);
749   bool willBlock(int ret,
750                  int* sslErrorOut,
751                  unsigned long* errErrorOut) noexcept;
752
753   void checkForImmediateRead() noexcept override;
754   // AsyncSocket calls this at the wrong time for SSL
755   void handleInitialReadWrite() noexcept override {}
756
757   WriteResult interpretSSLError(int rc, int error);
758   ReadResult performRead(void** buf, size_t* buflen, size_t* offset) override;
759   WriteResult performWrite(
760       const iovec* vec,
761       uint32_t count,
762       WriteFlags flags,
763       uint32_t* countWritten,
764       uint32_t* partialWritten) override;
765
766   ssize_t performWriteIovec(const iovec* vec, uint32_t count,
767                             WriteFlags flags, uint32_t* countWritten,
768                             uint32_t* partialWritten);
769
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);
773   }
774
775   /**
776    * Apply verification options passed to sslConn/sslAccept or those set
777    * in the underlying SSLContext object.
778    *
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.
782    */
783   void applyVerificationOptions(SSL * ssl);
784
785   /**
786    * Sets up SSL with a custom write bio which intercepts all writes.
787    *
788    * @return true, if succeeds and false if there is an error creating the bio.
789    */
790   bool setupSSLBio();
791
792   /**
793    * A SSL_write wrapper that understand EOR
794    *
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
800    */
801   int eorAwareSSLWrite(SSL *ssl, const void *buf, int n, bool eor);
802
803   // Inherit error handling methods from AsyncSocket, plus the following.
804   void failHandshake(const char* fn, const AsyncSocketException& ex);
805
806   void invokeHandshakeErr(const AsyncSocketException& ex);
807   void invokeHandshakeCB();
808
809   void invokeConnectErr(const AsyncSocketException& ex) override;
810   void invokeConnectSuccess() override;
811   void scheduleConnectTimeout() override;
812
813   void startSSLConnect();
814
815   static void sslInfoCallback(const SSL *ssl, int type, int val);
816
817   // Whether the current write to the socket should use MSG_MORE.
818   bool corkCurrentWrite_{false};
819   // SSL related members.
820   bool server_{false};
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};
831   SSL* ssl_{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};
837
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};
841
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};
845
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_;
852 #endif
853
854   // a service identity that this socket/connection is associated with
855   std::string serviceIdentity_;
856
857   folly::SSLContext::SSLVerifyPeerEnum
858     verifyPeer_{folly::SSLContext::SSLVerifyPeerEnum::USE_CTX};
859
860   // Callback for SSL_CTX_set_verify()
861   static int sslVerifyCallback(int preverifyOk, X509_STORE_CTX* ctx);
862
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_;
869
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};
876
877   std::string sslVerificationAlert_;
878 };
879
880 } // namespace