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