Make DestructorCheck::Safety no-copy, no-move
[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/Optional.h>
22 #include <folly/String.h>
23 #include <folly/io/async/AsyncSocket.h>
24 #include <folly/io/async/AsyncTimeout.h>
25 #include <folly/io/async/SSLContext.h>
26 #include <folly/io/async/TimeoutManager.h>
27 #include <folly/ssl/OpenSSLPtrTypes.h>
28 #include <folly/io/async/ssl/OpenSSLUtils.h>
29 #include <folly/io/async/ssl/SSLErrors.h>
30 #include <folly/io/async/ssl/TLSDefinitions.h>
31
32 #include <folly/Bits.h>
33 #include <folly/io/IOBuf.h>
34 #include <folly/io/Cursor.h>
35 #include <folly/portability/OpenSSL.h>
36 #include <folly/portability/Sockets.h>
37
38 namespace folly {
39
40 /**
41  * A class for performing asynchronous I/O on an SSL connection.
42  *
43  * AsyncSSLSocket allows users to asynchronously wait for data on an
44  * SSL connection, and to asynchronously send data.
45  *
46  * The APIs for reading and writing are intentionally asymmetric.
47  * Waiting for data to read is a persistent API: a callback is
48  * installed, and is notified whenever new data is available.  It
49  * continues to be notified of new events until it is uninstalled.
50  *
51  * AsyncSSLSocket does not provide read timeout functionality,
52  * because it typically cannot determine when the timeout should be
53  * active.  Generally, a timeout should only be enabled when
54  * processing is blocked waiting on data from the remote endpoint.
55  * For server connections, the timeout should not be active if the
56  * server is currently processing one or more outstanding requests for
57  * this connection.  For client connections, the timeout should not be
58  * active if there are no requests pending on the connection.
59  * Additionally, if a client has multiple pending requests, it will
60  * ususally want a separate timeout for each request, rather than a
61  * single read timeout.
62  *
63  * The write API is fairly intuitive: a user can request to send a
64  * block of data, and a callback will be informed once the entire
65  * block has been transferred to the kernel, or on error.
66  * AsyncSSLSocket does provide a send timeout, since most callers
67  * want to give up if the remote end stops responding and no further
68  * progress can be made sending the data.
69  */
70 class AsyncSSLSocket : public virtual AsyncSocket {
71  public:
72   typedef std::unique_ptr<AsyncSSLSocket, Destructor> UniquePtr;
73   using X509_deleter = folly::static_function_deleter<X509, &X509_free>;
74
75   class HandshakeCB {
76    public:
77     virtual ~HandshakeCB() = default;
78
79     /**
80      * handshakeVer() is invoked during handshaking to give the
81      * application chance to validate it's peer's certificate.
82      *
83      * Note that OpenSSL performs only rudimentary internal
84      * consistency verification checks by itself. Any other validation
85      * like whether or not the certificate was issued by a trusted CA.
86      * The default implementation of this callback mimics what what
87      * OpenSSL does internally if SSL_VERIFY_PEER is set with no
88      * verification callback.
89      *
90      * See the passages on verify_callback in SSL_CTX_set_verify(3)
91      * for more details.
92      */
93     virtual bool handshakeVer(AsyncSSLSocket* /*sock*/,
94                                  bool preverifyOk,
95                                  X509_STORE_CTX* /*ctx*/) noexcept {
96       return preverifyOk;
97     }
98
99     /**
100      * handshakeSuc() is called when a new SSL connection is
101      * established, i.e., after SSL_accept/connect() returns successfully.
102      *
103      * The HandshakeCB will be uninstalled before handshakeSuc()
104      * is called.
105      *
106      * @param sock  SSL socket on which the handshake was initiated
107      */
108     virtual void handshakeSuc(AsyncSSLSocket *sock) noexcept = 0;
109
110     /**
111      * handshakeErr() is called if an error occurs while
112      * establishing the SSL connection.
113      *
114      * The HandshakeCB will be uninstalled before handshakeErr()
115      * is called.
116      *
117      * @param sock  SSL socket on which the handshake was initiated
118      * @param ex  An exception representing the error.
119      */
120     virtual void handshakeErr(
121       AsyncSSLSocket *sock,
122       const AsyncSocketException& ex)
123       noexcept = 0;
124   };
125
126   class Timeout : public AsyncTimeout {
127    public:
128     Timeout(AsyncSSLSocket* sslSocket, EventBase* eventBase)
129         : AsyncTimeout(eventBase), sslSocket_(sslSocket) {}
130
131     bool scheduleTimeout(TimeoutManager::timeout_type timeout) {
132       timeout_ = timeout;
133       return AsyncTimeout::scheduleTimeout(timeout);
134     }
135
136     bool scheduleTimeout(uint32_t timeoutMs) {
137       return scheduleTimeout(std::chrono::milliseconds{timeoutMs});
138     }
139
140     TimeoutManager::timeout_type getTimeout() {
141       return timeout_;
142     }
143
144     void timeoutExpired() noexcept override {
145       sslSocket_->timeoutExpired(timeout_);
146     }
147
148    private:
149     AsyncSSLSocket* sslSocket_;
150     TimeoutManager::timeout_type timeout_;
151   };
152
153   /**
154    * Create a client AsyncSSLSocket
155    */
156   AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
157                  EventBase* evb, bool deferSecurityNegotiation = false);
158
159   /**
160    * Create a server/client AsyncSSLSocket from an already connected
161    * socket file descriptor.
162    *
163    * Note that while AsyncSSLSocket enables TCP_NODELAY for sockets it creates
164    * when connecting, it does not change the socket options when given an
165    * existing file descriptor.  If callers want TCP_NODELAY enabled when using
166    * this version of the constructor, they need to explicitly call
167    * setNoDelay(true) after the constructor returns.
168    *
169    * @param ctx             SSL context for this connection.
170    * @param evb EventBase that will manage this socket.
171    * @param fd  File descriptor to take over (should be a connected socket).
172    * @param server Is socket in server mode?
173    * @param deferSecurityNegotiation
174    *          unencrypted data can be sent before sslConn/Accept
175    */
176   AsyncSSLSocket(
177       const std::shared_ptr<folly::SSLContext>& ctx,
178       EventBase* evb,
179       int fd,
180       bool server = true,
181       bool deferSecurityNegotiation = false);
182
183   /**
184    * Create a server/client AsyncSSLSocket from an already connected
185    * AsyncSocket.
186    */
187   AsyncSSLSocket(
188       const std::shared_ptr<folly::SSLContext>& ctx,
189       AsyncSocket::UniquePtr oldAsyncSocket,
190       bool server = true,
191       bool deferSecurityNegotiation = false);
192
193   /**
194    * Helper function to create a server/client shared_ptr<AsyncSSLSocket>.
195    */
196   static std::shared_ptr<AsyncSSLSocket> newSocket(
197     const std::shared_ptr<folly::SSLContext>& ctx,
198     EventBase* evb, int fd, bool server=true,
199     bool deferSecurityNegotiation = false) {
200     return std::shared_ptr<AsyncSSLSocket>(
201       new AsyncSSLSocket(ctx, evb, fd, server, deferSecurityNegotiation),
202       Destructor());
203   }
204
205   /**
206    * Helper function to create a client shared_ptr<AsyncSSLSocket>.
207    */
208   static std::shared_ptr<AsyncSSLSocket> newSocket(
209     const std::shared_ptr<folly::SSLContext>& ctx,
210     EventBase* evb, bool deferSecurityNegotiation = false) {
211     return std::shared_ptr<AsyncSSLSocket>(
212       new AsyncSSLSocket(ctx, evb, deferSecurityNegotiation),
213       Destructor());
214   }
215
216
217 #if FOLLY_OPENSSL_HAS_SNI
218   /**
219    * Create a client AsyncSSLSocket with tlsext_servername in
220    * the Client Hello message.
221    */
222   AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
223                   EventBase* evb,
224                  const std::string& serverName,
225                 bool deferSecurityNegotiation = false);
226
227   /**
228    * Create a client AsyncSSLSocket from an already connected
229    * socket file descriptor.
230    *
231    * Note that while AsyncSSLSocket enables TCP_NODELAY for sockets it creates
232    * when connecting, it does not change the socket options when given an
233    * existing file descriptor.  If callers want TCP_NODELAY enabled when using
234    * this version of the constructor, they need to explicitly call
235    * setNoDelay(true) after the constructor returns.
236    *
237    * @param ctx  SSL context for this connection.
238    * @param evb  EventBase that will manage this socket.
239    * @param fd   File descriptor to take over (should be a connected socket).
240    * @param serverName tlsext_hostname that will be sent in ClientHello.
241    */
242   AsyncSSLSocket(
243       const std::shared_ptr<folly::SSLContext>& ctx,
244       EventBase* evb,
245       int fd,
246       const std::string& serverName,
247       bool deferSecurityNegotiation = false);
248
249   static std::shared_ptr<AsyncSSLSocket> newSocket(
250     const std::shared_ptr<folly::SSLContext>& ctx,
251     EventBase* evb,
252     const std::string& serverName,
253     bool deferSecurityNegotiation = false) {
254     return std::shared_ptr<AsyncSSLSocket>(
255       new AsyncSSLSocket(ctx, evb, serverName, deferSecurityNegotiation),
256       Destructor());
257   }
258 #endif // FOLLY_OPENSSL_HAS_SNI
259
260   /**
261    * TODO: implement support for SSL renegotiation.
262    *
263    * This involves proper handling of the SSL_ERROR_WANT_READ/WRITE
264    * code as a result of SSL_write/read(), instead of returning an
265    * error. In that case, the READ/WRITE event should be registered,
266    * and a flag (e.g., writeBlockedOnRead) should be set to indiciate
267    * the condition. In the next invocation of read/write callback, if
268    * the flag is on, performWrite()/performRead() should be called in
269    * addition to the normal call to performRead()/performWrite(), and
270    * the flag should be reset.
271    */
272
273   // Inherit TAsyncTransport methods from AsyncSocket except the
274   // following.
275   // See the documentation in TAsyncTransport.h
276   // TODO: implement graceful shutdown in close()
277   // TODO: implement detachSSL() that returns the SSL connection
278   void closeNow() override;
279   void shutdownWrite() override;
280   void shutdownWriteNow() override;
281   bool good() const override;
282   bool connecting() const override;
283   std::string getApplicationProtocol() noexcept override;
284
285   std::string getSecurityProtocol() const override {
286     return "TLS";
287   }
288
289   void setEorTracking(bool track) override;
290   size_t getRawBytesWritten() const override;
291   size_t getRawBytesReceived() const override;
292   void enableClientHelloParsing();
293
294   /**
295    * Accept an SSL connection on the socket.
296    *
297    * The callback will be invoked and uninstalled when an SSL
298    * connection has been established on the underlying socket.
299    * The value of verifyPeer determines the client verification method.
300    * By default, its set to use the value in the underlying context
301    *
302    * @param callback callback object to invoke on success/failure
303    * @param timeout timeout for this function in milliseconds, or 0 for no
304    *                timeout
305    * @param verifyPeer  SSLVerifyPeerEnum uses the options specified in the
306    *                context by default, can be set explcitly to override the
307    *                method in the context
308    */
309   virtual void sslAccept(
310       HandshakeCB* callback,
311       std::chrono::milliseconds timeout = std::chrono::milliseconds::zero(),
312       const folly::SSLContext::SSLVerifyPeerEnum& verifyPeer =
313           folly::SSLContext::SSLVerifyPeerEnum::USE_CTX);
314
315   /**
316    * Invoke SSL accept following an asynchronous session cache lookup
317    */
318   void restartSSLAccept();
319
320   /**
321    * Connect to the given address, invoking callback when complete or on error
322    *
323    * Note timeout applies to TCP + SSL connection time
324    */
325   void connect(ConnectCallback* callback,
326                const folly::SocketAddress& address,
327                int timeout = 0,
328                const OptionMap &options = emptyOptionMap,
329                const folly::SocketAddress& bindAddr = anyAddress())
330                noexcept override;
331
332   /**
333    * A variant of connect that allows the caller to specify
334    * the timeout for the regular connect and the ssl connect
335    * separately.
336    * connectTimeout is specified as the time to establish a TCP
337    * connection.
338    * totalConnectTimeout defines the
339    * time it takes from starting the TCP connection to the time
340    * the ssl connection is established. The reason the timeout is
341    * defined this way is because user's rarely need to specify the SSL
342    * timeout independently of the connect timeout. It allows us to
343    * bound the time for a connect and SSL connection in
344    * a finer grained manner than if timeout was just defined
345    * independently for SSL.
346    */
347   virtual void connect(
348       ConnectCallback* callback,
349       const folly::SocketAddress& address,
350       std::chrono::milliseconds connectTimeout,
351       std::chrono::milliseconds totalConnectTimeout,
352       const OptionMap& options = emptyOptionMap,
353       const folly::SocketAddress& bindAddr = anyAddress()) noexcept;
354
355   using AsyncSocket::connect;
356
357   /**
358    * Initiate an SSL connection on the socket
359    * The callback will be invoked and uninstalled when an SSL connection
360    * has been establshed on the underlying socket.
361    * The verification option verifyPeer is applied if it's passed explicitly.
362    * If it's not, the options in SSLContext set on the underlying SSLContext
363    * are applied.
364    *
365    * @param callback callback object to invoke on success/failure
366    * @param timeout timeout for this function in milliseconds, or 0 for no
367    *                timeout
368    * @param verifyPeer  SSLVerifyPeerEnum uses the options specified in the
369    *                context by default, can be set explcitly to override the
370    *                method in the context. If verification is turned on sets
371    *                SSL_VERIFY_PEER and invokes
372    *                HandshakeCB::handshakeVer().
373    */
374   virtual void sslConn(
375       HandshakeCB* callback,
376       std::chrono::milliseconds timeout = std::chrono::milliseconds::zero(),
377       const folly::SSLContext::SSLVerifyPeerEnum& verifyPeer =
378           folly::SSLContext::SSLVerifyPeerEnum::USE_CTX);
379
380   enum SSLStateEnum {
381     STATE_UNINIT,
382     STATE_UNENCRYPTED,
383     STATE_ACCEPTING,
384     STATE_CACHE_LOOKUP,
385     STATE_ASYNC_PENDING,
386     STATE_CONNECTING,
387     STATE_ESTABLISHED,
388     STATE_REMOTE_CLOSED, /// remote end closed; we can still write
389     STATE_CLOSING,       ///< close() called, but waiting on writes to complete
390     /// close() called with pending writes, before connect() has completed
391     STATE_CONNECTING_CLOSING,
392     STATE_CLOSED,
393     STATE_ERROR
394   };
395
396   SSLStateEnum getSSLState() const { return sslState_;}
397
398   /**
399    * Get a handle to the negotiated SSL session.  This increments the session
400    * refcount and must be deallocated by the caller.
401    */
402   SSL_SESSION *getSSLSession();
403
404   /**
405    * Get a handle to the SSL struct.
406    */
407   const SSL* getSSL() const;
408
409   /**
410    * Set the SSL session to be used during sslConn.  AsyncSSLSocket will
411    * hold a reference to the session until it is destroyed or released by the
412    * underlying SSL structure.
413    *
414    * @param takeOwnership if true, AsyncSSLSocket will assume the caller's
415    *                      reference count to session.
416    */
417   void setSSLSession(SSL_SESSION *session, bool takeOwnership = false);
418
419   /**
420    * Get the name of the protocol selected by the client during
421    * Next Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
422    * (ALPN)
423    *
424    * Throw an exception if openssl does not support NPN
425    *
426    * @param protoName      Name of the protocol (not guaranteed to be
427    *                       null terminated); will be set to nullptr if
428    *                       the client did not negotiate a protocol.
429    *                       Note: the AsyncSSLSocket retains ownership
430    *                       of this string.
431    * @param protoNameLen   Length of the name.
432    * @param protoType      Whether this was an NPN or ALPN negotiation
433    */
434   virtual void getSelectedNextProtocol(
435       const unsigned char** protoName,
436       unsigned* protoLen,
437       SSLContext::NextProtocolType* protoType = nullptr) const;
438
439   /**
440    * Get the name of the protocol selected by the client during
441    * Next Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
442    * (ALPN)
443    *
444    * @param protoName      Name of the protocol (not guaranteed to be
445    *                       null terminated); will be set to nullptr if
446    *                       the client did not negotiate a protocol.
447    *                       Note: the AsyncSSLSocket retains ownership
448    *                       of this string.
449    * @param protoNameLen   Length of the name.
450    * @param protoType      Whether this was an NPN or ALPN negotiation
451    * @return false if openssl does not support NPN
452    */
453   virtual bool getSelectedNextProtocolNoThrow(
454       const unsigned char** protoName,
455       unsigned* protoLen,
456       SSLContext::NextProtocolType* protoType = nullptr) const;
457
458   /**
459    * Determine if the session specified during setSSLSession was reused
460    * or if the server rejected it and issued a new session.
461    */
462   virtual bool getSSLSessionReused() const;
463
464   /**
465    * true if the session was resumed using session ID
466    */
467   bool sessionIDResumed() const { return sessionIDResumed_; }
468
469   void setSessionIDResumed(bool resumed) {
470     sessionIDResumed_ = resumed;
471   }
472
473   /**
474    * Get the negociated cipher name for this SSL connection.
475    * Returns the cipher used or the constant value "NONE" when no SSL session
476    * has been established.
477    */
478   virtual const char* getNegotiatedCipherName() const;
479
480   /**
481    * Get the server name for this SSL connection.
482    * Returns the server name used or the constant value "NONE" when no SSL
483    * session has been established.
484    * If openssl has no SNI support, throw TTransportException.
485    */
486   const char *getSSLServerName() const;
487
488   /**
489    * Get the server name for this SSL connection.
490    * Returns the server name used or the constant value "NONE" when no SSL
491    * session has been established.
492    * If openssl has no SNI support, return "NONE"
493    */
494   const char *getSSLServerNameNoThrow() const;
495
496   /**
497    * Get the SSL version for this connection.
498    * Possible return values are SSL2_VERSION, SSL3_VERSION, TLS1_VERSION,
499    * with hexa representations 0x200, 0x300, 0x301,
500    * or 0 if no SSL session has been established.
501    */
502   int getSSLVersion() const;
503
504   /**
505    * Get the signature algorithm used in the cert that is used for this
506    * connection.
507    */
508   const char *getSSLCertSigAlgName() const;
509
510   /**
511    * Get the certificate size used for this SSL connection.
512    */
513   int getSSLCertSize() const;
514
515   /**
516    * Get the certificate used for this SSL connection. May be null
517    */
518   const X509* getSelfCert() const override;
519
520   void attachEventBase(EventBase* eventBase) override {
521     AsyncSocket::attachEventBase(eventBase);
522     handshakeTimeout_.attachEventBase(eventBase);
523     connectionTimeout_.attachEventBase(eventBase);
524   }
525
526   void detachEventBase() override {
527     AsyncSocket::detachEventBase();
528     handshakeTimeout_.detachEventBase();
529     connectionTimeout_.detachEventBase();
530   }
531
532   bool isDetachable() const override {
533     return AsyncSocket::isDetachable() && !handshakeTimeout_.isScheduled();
534   }
535
536   virtual void attachTimeoutManager(TimeoutManager* manager) {
537     handshakeTimeout_.attachTimeoutManager(manager);
538   }
539
540   virtual void detachTimeoutManager() {
541     handshakeTimeout_.detachTimeoutManager();
542   }
543
544 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
545   /**
546    * This function will set the SSL context for this socket to the
547    * argument. This should only be used on client SSL Sockets that have
548    * already called detachSSLContext();
549    */
550   void attachSSLContext(const std::shared_ptr<folly::SSLContext>& ctx);
551
552   /**
553    * Detaches the SSL context for this socket.
554    */
555   void detachSSLContext();
556 #endif
557
558 #if FOLLY_OPENSSL_HAS_SNI
559   /**
560    * Switch the SSLContext to continue the SSL handshake.
561    * It can only be used in server mode.
562    */
563   void switchServerSSLContext(
564     const std::shared_ptr<folly::SSLContext>& handshakeCtx);
565
566   /**
567    * Did server recognize/support the tlsext_hostname in Client Hello?
568    * It can only be used in client mode.
569    *
570    * @return true - tlsext_hostname is matched by the server
571    *         false - tlsext_hostname is not matched or
572    *                 is not supported by server
573    */
574   bool isServerNameMatch() const;
575
576   /**
577    * Set the SNI hostname that we'll advertise to the server in the
578    * ClientHello message.
579    */
580   void setServerName(std::string serverName) noexcept;
581 #endif // FOLLY_OPENSSL_HAS_SNI
582
583   void timeoutExpired(std::chrono::milliseconds timeout) noexcept;
584
585   /**
586    * Get the list of supported ciphers sent by the client in the client's
587    * preference order.
588    */
589   void getSSLClientCiphers(
590       std::string& clientCiphers,
591       bool convertToString = true) const;
592
593   /**
594    * Get the list of compression methods sent by the client in TLS Hello.
595    */
596   std::string getSSLClientComprMethods() const;
597
598   /**
599    * Get the list of TLS extensions sent by the client in the TLS Hello.
600    */
601   std::string getSSLClientExts() const;
602
603   std::string getSSLClientSigAlgs() const;
604
605   /**
606    * Get the list of versions in the supported versions extension (used to
607    * negotiate TLS 1.3).
608    */
609   std::string getSSLClientSupportedVersions() const;
610
611   std::string getSSLAlertsReceived() const;
612
613   /*
614    * Save an optional alert message generated during certificate verify
615    */
616   void setSSLCertVerificationAlert(std::string alert);
617
618   std::string getSSLCertVerificationAlert() const;
619
620   /**
621    * Get the list of shared ciphers between the server and the client.
622    * Works well for only SSLv2, not so good for SSLv3 or TLSv1.
623    */
624   void getSSLSharedCiphers(std::string& sharedCiphers) const;
625
626   /**
627    * Get the list of ciphers supported by the server in the server's
628    * preference order.
629    */
630   void getSSLServerCiphers(std::string& serverCiphers) const;
631
632   /**
633    * Method to check if peer verfication is set.
634    *
635    * @return true if peer verification is required.
636    */
637   bool needsPeerVerification() const;
638
639   static int getSSLExDataIndex();
640   static AsyncSSLSocket* getFromSSL(const SSL *ssl);
641   static int bioWrite(BIO* b, const char* in, int inl);
642   static int bioRead(BIO* b, char* out, int outl);
643   void resetClientHelloParsing(SSL *ssl);
644   static void clientHelloParsingCallback(int write_p, int version,
645       int content_type, const void *buf, size_t len, SSL *ssl, void *arg);
646   static const char* getSSLServerNameFromSSL(SSL* ssl);
647
648   // For unit-tests
649   ssl::ClientHelloInfo* getClientHelloInfo() const {
650     return clientHelloInfo_.get();
651   }
652
653   /**
654    * Returns the time taken to complete a handshake.
655    */
656   virtual std::chrono::nanoseconds getHandshakeTime() const {
657     return handshakeEndTime_ - handshakeStartTime_;
658   }
659
660   void setMinWriteSize(size_t minWriteSize) {
661     minWriteSize_ = minWriteSize;
662   }
663
664   size_t getMinWriteSize() const {
665     return minWriteSize_;
666   }
667
668   void setReadCB(ReadCallback* callback) override;
669
670   /**
671    * Tries to enable the buffer movable experimental feature in openssl.
672    * This is not guaranteed to succeed in case openssl does not have
673    * the experimental feature built in.
674    */
675   void setBufferMovableEnabled(bool enabled);
676
677   /**
678    * Returns the peer certificate, or nullptr if no peer certificate received.
679    */
680   ssl::X509UniquePtr getPeerCert() const override {
681     if (!ssl_) {
682       return nullptr;
683     }
684
685     X509* cert = SSL_get_peer_certificate(ssl_);
686     return ssl::X509UniquePtr(cert);
687   }
688
689   /**
690    * Force AsyncSSLSocket object to cache local and peer socket addresses.
691    * If called with "true" before connect() this function forces full local
692    * and remote socket addresses to be cached in the socket object and available
693    * through getLocalAddress()/getPeerAddress() methods even after the socket is
694    * closed.
695    */
696   void forceCacheAddrOnFailure(bool force) { cacheAddrOnFailure_ = force; }
697
698   const std::string& getServiceIdentity() const { return serviceIdentity_; }
699
700   void setServiceIdentity(std::string serviceIdentity) {
701     serviceIdentity_ = std::move(serviceIdentity);
702   }
703
704   void setCertCacheHit(bool hit) {
705     certCacheHit_ = hit;
706   }
707
708   bool getCertCacheHit() const {
709     return certCacheHit_;
710   }
711
712   bool sessionResumptionAttempted() const {
713     return sessionResumptionAttempted_;
714   }
715
716   /**
717    * If the SSL socket was used to connect as well
718    * as establish an SSL connection, this gives the total
719    * timeout for the connect + SSL connection that was
720    * set.
721    */
722   std::chrono::milliseconds getTotalConnectTimeout() const {
723     return totalConnectTimeout_;
724   }
725
726  private:
727
728   void init();
729
730  protected:
731
732   /**
733    * Protected destructor.
734    *
735    * Users of AsyncSSLSocket must never delete it directly.  Instead, invoke
736    * destroy() instead.  (See the documentation in DelayedDestruction.h for
737    * more details.)
738    */
739   ~AsyncSSLSocket() override;
740
741   // Inherit event notification methods from AsyncSocket except
742   // the following.
743   void prepareReadBuffer(void** buf, size_t* buflen) override;
744   void handleRead() noexcept override;
745   void handleWrite() noexcept override;
746   void handleAccept() noexcept;
747   void handleConnect() noexcept override;
748
749   void invalidState(HandshakeCB* callback);
750   bool willBlock(int ret,
751                  int* sslErrorOut,
752                  unsigned long* errErrorOut) noexcept;
753
754   void checkForImmediateRead() noexcept override;
755   // AsyncSocket calls this at the wrong time for SSL
756   void handleInitialReadWrite() noexcept override {}
757
758   WriteResult interpretSSLError(int rc, int error);
759   ReadResult performRead(void** buf, size_t* buflen, size_t* offset) override;
760   WriteResult performWrite(
761       const iovec* vec,
762       uint32_t count,
763       WriteFlags flags,
764       uint32_t* countWritten,
765       uint32_t* partialWritten) override;
766
767   ssize_t performWriteIovec(const iovec* vec, uint32_t count,
768                             WriteFlags flags, uint32_t* countWritten,
769                             uint32_t* partialWritten);
770
771   // This virtual wrapper around SSL_write exists solely for testing/mockability
772   virtual int sslWriteImpl(SSL *ssl, const void *buf, int n) {
773     return SSL_write(ssl, buf, n);
774   }
775
776   /**
777    * Apply verification options passed to sslConn/sslAccept or those set
778    * in the underlying SSLContext object.
779    *
780    * @param ssl pointer to the SSL object on which verification options will be
781    * applied. If verifyPeer_ was explicitly set either via sslConn/sslAccept,
782    * those options override the settings in the underlying SSLContext.
783    */
784   void applyVerificationOptions(SSL * ssl);
785
786   /**
787    * Sets up SSL with a custom write bio which intercepts all writes.
788    *
789    * @return true, if succeeds and false if there is an error creating the bio.
790    */
791   bool setupSSLBio();
792
793   /**
794    * A SSL_write wrapper that understand EOR
795    *
796    * @param ssl: SSL* object
797    * @param buf: Buffer to be written
798    * @param n:   Number of bytes to be written
799    * @param eor: Does the last byte (buf[n-1]) have the app-last-byte?
800    * @return:    The number of app bytes successfully written to the socket
801    */
802   int eorAwareSSLWrite(SSL *ssl, const void *buf, int n, bool eor);
803
804   // Inherit error handling methods from AsyncSocket, plus the following.
805   void failHandshake(const char* fn, const AsyncSocketException& ex);
806
807   void invokeHandshakeErr(const AsyncSocketException& ex);
808   void invokeHandshakeCB();
809
810   void invokeConnectErr(const AsyncSocketException& ex) override;
811   void invokeConnectSuccess() override;
812   void scheduleConnectTimeout() override;
813
814   void cacheLocalPeerAddr();
815
816   void startSSLConnect();
817
818   static void sslInfoCallback(const SSL *ssl, int type, int val);
819
820   // Whether the current write to the socket should use MSG_MORE.
821   bool corkCurrentWrite_{false};
822   // SSL related members.
823   bool server_{false};
824   // Used to prevent client-initiated renegotiation.  Note that AsyncSSLSocket
825   // doesn't fully support renegotiation, so we could just fail all attempts
826   // to enforce this.  Once it is supported, we should make it an option
827   // to disable client-initiated renegotiation.
828   bool handshakeComplete_{false};
829   bool renegotiateAttempted_{false};
830   SSLStateEnum sslState_{STATE_UNINIT};
831   std::shared_ptr<folly::SSLContext> ctx_;
832   // Callback for SSL_accept() or SSL_connect()
833   HandshakeCB* handshakeCallback_{nullptr};
834   SSL* ssl_{nullptr};
835   SSL_SESSION *sslSession_{nullptr};
836   Timeout handshakeTimeout_;
837   Timeout connectionTimeout_;
838   // whether the SSL session was resumed using session ID or not
839   bool sessionIDResumed_{false};
840
841   // The app byte num that we are tracking for the MSG_EOR
842   // Only one app EOR byte can be tracked.
843   size_t appEorByteNo_{0};
844
845   // Try to avoid calling SSL_write() for buffers smaller than this.
846   // It doesn't take effect when it is 0.
847   size_t minWriteSize_{1500};
848
849   // When openssl is about to sendmsg() across the minEorRawBytesNo_,
850   // it will pass MSG_EOR to sendmsg().
851   size_t minEorRawByteNo_{0};
852 #if FOLLY_OPENSSL_HAS_SNI
853   std::shared_ptr<folly::SSLContext> handshakeCtx_;
854   std::string tlsextHostname_;
855 #endif
856
857   // a service identity that this socket/connection is associated with
858   std::string serviceIdentity_;
859
860   folly::SSLContext::SSLVerifyPeerEnum
861     verifyPeer_{folly::SSLContext::SSLVerifyPeerEnum::USE_CTX};
862
863   // Callback for SSL_CTX_set_verify()
864   static int sslVerifyCallback(int preverifyOk, X509_STORE_CTX* ctx);
865
866   bool parseClientHello_{false};
867   bool cacheAddrOnFailure_{false};
868   bool bufferMovableEnabled_{false};
869   bool certCacheHit_{false};
870   std::unique_ptr<ssl::ClientHelloInfo> clientHelloInfo_;
871   std::vector<std::pair<char, StringPiece>> alertsReceived_;
872
873   // Time taken to complete the ssl handshake.
874   std::chrono::steady_clock::time_point handshakeStartTime_;
875   std::chrono::steady_clock::time_point handshakeEndTime_;
876   std::chrono::milliseconds handshakeConnectTimeout_{0};
877   bool sessionResumptionAttempted_{false};
878   std::chrono::milliseconds totalConnectTimeout_{0};
879
880   std::string sslVerificationAlert_;
881 };
882
883 } // namespace