1 // Copyright Joyent, Inc. and other Node contributors. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a 4 // copy of this software and associated documentation files (the 5 // "Software"), to deal in the Software without restriction, including 6 // without limitation the rights to use, copy, modify, merge, publish, 7 // distribute, sublicense, and/or sell copies of the Software, and to permit 8 // persons to whom the Software is furnished to do so, subject to the 9 // following conditions: 10 // 11 // The above copyright notice and this permission notice shall be included 12 // in all copies or substantial portions of the Software. 13 // 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 21 22 #ifndef SRC_CRYPTO_CRYPTO_TLS_H_ 23 #define SRC_CRYPTO_CRYPTO_TLS_H_ 24 25 #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS 26 27 #include "crypto/crypto_context.h" 28 #include "crypto/crypto_clienthello.h" 29 30 #include "async_wrap.h" 31 #include "stream_wrap.h" 32 #include "v8.h" 33 34 #include <openssl/ssl.h> 35 36 #include <string> 37 #include <vector> 38 39 namespace node { 40 namespace crypto { 41 42 class TLSWrap : public AsyncWrap, 43 public StreamBase, 44 public StreamListener { 45 public: 46 enum class Kind { 47 kClient, 48 kServer 49 }; 50 51 enum class UnderlyingStreamWriteStatus { kHasActive, kVacancy }; 52 53 static void Initialize(v8::Local<v8::Object> target, 54 v8::Local<v8::Value> unused, 55 v8::Local<v8::Context> context, 56 void* priv); 57 static void RegisterExternalReferences(ExternalReferenceRegistry* registry); 58 59 ~TLSWrap() override; 60 is_cert_cb_running()61 bool is_cert_cb_running() const { return cert_cb_running_; } is_waiting_cert_cb()62 bool is_waiting_cert_cb() const { return cert_cb_ != nullptr; } has_session_callbacks()63 bool has_session_callbacks() const { return session_callbacks_; } 64 void set_cert_cb_running(bool on = true) { cert_cb_running_ = on; } 65 void set_awaiting_new_session(bool on = true) { awaiting_new_session_ = on; } enable_session_callbacks()66 void enable_session_callbacks() { session_callbacks_ = true; } is_server()67 bool is_server() const { return kind_ == Kind::kServer; } is_client()68 bool is_client() const { return kind_ == Kind::kClient; } is_awaiting_new_session()69 bool is_awaiting_new_session() const { return awaiting_new_session_; } 70 71 // Implement StreamBase: 72 bool IsAlive() override; 73 bool IsClosing() override; 74 bool IsIPCPipe() override; 75 int GetFD() override; 76 ShutdownWrap* CreateShutdownWrap( 77 v8::Local<v8::Object> req_wrap_object) override; 78 AsyncWrap* GetAsyncWrap() override; 79 80 81 // Implement StreamResource: 82 int ReadStart() override; // Exposed to JS 83 int ReadStop() override; // Exposed to JS 84 int DoShutdown(ShutdownWrap* req_wrap) override; 85 int DoWrite(WriteWrap* w, 86 uv_buf_t* bufs, 87 size_t count, 88 uv_stream_t* send_handle) override; 89 // Return error_ string or nullptr if it's empty. 90 const char* Error() const override; 91 // Reset error_ string to empty. Not related to "clear text". 92 void ClearError() override; 93 94 v8::MaybeLocal<v8::ArrayBufferView> ocsp_response() const; 95 void ClearOcspResponse(); 96 SSL_SESSION* ReleaseSession(); 97 98 // Called by the done() callback of the 'newSession' event. 99 void NewSessionDoneCb(); 100 101 // Implement MemoryRetainer: 102 void MemoryInfo(MemoryTracker* tracker) const override; 103 SET_MEMORY_INFO_NAME(TLSWrap) 104 SET_SELF_SIZE(TLSWrap) 105 106 std::string diagnostic_name() const override; 107 108 private: 109 // OpenSSL structures are opaque. Estimate SSL memory size for OpenSSL 1.1.1b: 110 // SSL: 6224 111 // SSL->SSL3_STATE: 1040 112 // ...some buffers: 42 * 1024 113 // NOTE: Actually it is much more than this 114 static constexpr int64_t kExternalSize = 6224 + 1040 + 42 * 1024; 115 116 static constexpr int kClearOutChunkSize = 16384; 117 118 // Maximum number of bytes for hello parser 119 static constexpr int kMaxHelloLength = 16384; 120 121 // Usual ServerHello + Certificate size 122 static constexpr int kInitialClientBufferLength = 4096; 123 124 // Maximum number of buffers passed to uv_write() 125 static constexpr int kSimultaneousBufferCount = 10; 126 127 typedef void (*CertCb)(void* arg); 128 129 // Alternative to StreamListener::stream(), that returns a StreamBase instead 130 // of a StreamResource. underlying_stream()131 StreamBase* underlying_stream() const { 132 return static_cast<StreamBase*>(stream()); 133 } 134 135 void WaitForCertCb(CertCb cb, void* arg); 136 137 TLSWrap(Environment* env, 138 v8::Local<v8::Object> obj, 139 Kind kind, 140 StreamBase* stream, 141 SecureContext* sc, 142 UnderlyingStreamWriteStatus under_stream_ws); 143 144 static void SSLInfoCallback(const SSL* ssl_, int where, int ret); 145 void InitSSL(); 146 // SSL has a "clear" text (unencrypted) side (to/from the node API) and 147 // encrypted ("enc") text side (to/from the underlying socket/stream). 148 // On each side data flows "in" or "out" of SSL context. 149 // 150 // EncIn() doesn't exist. Encrypted data is pushed from underlying stream into 151 // enc_in_ via the stream listener's OnStreamAlloc()/OnStreamRead() interface. 152 void EncOut(); // Write encrypted data from enc_out_ to underlying stream. 153 void ClearIn(); // SSL_write() clear data "in" to SSL. 154 void ClearOut(); // SSL_read() clear text "out" from SSL. 155 void Destroy(); 156 157 // Call Done() on outstanding WriteWrap request. 158 void InvokeQueued(int status, const char* error_str = nullptr); 159 160 // Drive the SSL state machine by attempting to SSL_read() and SSL_write() to 161 // it. Transparent handshakes mean SSL_read() might trigger I/O on the 162 // underlying stream even if there is no clear text to read or write. 163 void Cycle(); 164 165 // Implement StreamListener: 166 // Returns buf that points into enc_in_. 167 uv_buf_t OnStreamAlloc(size_t size) override; 168 void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override; 169 void OnStreamAfterWrite(WriteWrap* w, int status) override; 170 171 int SetCACerts(SecureContext* sc); 172 173 static int SelectSNIContextCallback(SSL* s, int* ad, void* arg); 174 175 static void CertCbDone(const v8::FunctionCallbackInfo<v8::Value>& args); 176 static void DestroySSL(const v8::FunctionCallbackInfo<v8::Value>& args); 177 static void EnableCertCb(const v8::FunctionCallbackInfo<v8::Value>& args); 178 static void EnableALPNCb(const v8::FunctionCallbackInfo<v8::Value>& args); 179 static void EnableKeylogCallback( 180 const v8::FunctionCallbackInfo<v8::Value>& args); 181 static void EnableSessionCallbacks( 182 const v8::FunctionCallbackInfo<v8::Value>& args); 183 static void EnableTrace(const v8::FunctionCallbackInfo<v8::Value>& args); 184 static void EndParser(const v8::FunctionCallbackInfo<v8::Value>& args); 185 static void ExportKeyingMaterial( 186 const v8::FunctionCallbackInfo<v8::Value>& args); 187 static void GetALPNNegotiatedProto( 188 const v8::FunctionCallbackInfo<v8::Value>& args); 189 static void GetCertificate(const v8::FunctionCallbackInfo<v8::Value>& args); 190 static void GetX509Certificate( 191 const v8::FunctionCallbackInfo<v8::Value>& args); 192 static void GetCipher(const v8::FunctionCallbackInfo<v8::Value>& args); 193 static void GetEphemeralKeyInfo( 194 const v8::FunctionCallbackInfo<v8::Value>& args); 195 static void GetFinished(const v8::FunctionCallbackInfo<v8::Value>& args); 196 static void GetPeerCertificate( 197 const v8::FunctionCallbackInfo<v8::Value>& args); 198 static void GetPeerX509Certificate( 199 const v8::FunctionCallbackInfo<v8::Value>& args); 200 static void GetPeerFinished(const v8::FunctionCallbackInfo<v8::Value>& args); 201 static void GetProtocol(const v8::FunctionCallbackInfo<v8::Value>& args); 202 static void GetServername(const v8::FunctionCallbackInfo<v8::Value>& args); 203 static void GetSession(const v8::FunctionCallbackInfo<v8::Value>& args); 204 static void GetSharedSigalgs(const v8::FunctionCallbackInfo<v8::Value>& args); 205 static void GetTLSTicket(const v8::FunctionCallbackInfo<v8::Value>& args); 206 static void GetWriteQueueSize( 207 const v8::FunctionCallbackInfo<v8::Value>& info); 208 static void IsSessionReused(const v8::FunctionCallbackInfo<v8::Value>& args); 209 static void LoadSession(const v8::FunctionCallbackInfo<v8::Value>& args); 210 static void NewSessionDone(const v8::FunctionCallbackInfo<v8::Value>& args); 211 static void OnClientHelloParseEnd(void* arg); 212 static void Receive(const v8::FunctionCallbackInfo<v8::Value>& args); 213 static void Renegotiate(const v8::FunctionCallbackInfo<v8::Value>& args); 214 static void RequestOCSP(const v8::FunctionCallbackInfo<v8::Value>& args); 215 static void SetALPNProtocols(const v8::FunctionCallbackInfo<v8::Value>& args); 216 static void SetOCSPResponse(const v8::FunctionCallbackInfo<v8::Value>& args); 217 static void SetServername(const v8::FunctionCallbackInfo<v8::Value>& args); 218 static void SetSession(const v8::FunctionCallbackInfo<v8::Value>& args); 219 static void SetVerifyMode(const v8::FunctionCallbackInfo<v8::Value>& args); 220 static void Start(const v8::FunctionCallbackInfo<v8::Value>& args); 221 static void VerifyError(const v8::FunctionCallbackInfo<v8::Value>& args); 222 static void Wrap(const v8::FunctionCallbackInfo<v8::Value>& args); 223 static void WritesIssuedByPrevListenerDone( 224 const v8::FunctionCallbackInfo<v8::Value>& args); 225 226 #ifdef SSL_set_max_send_fragment 227 static void SetMaxSendFragment( 228 const v8::FunctionCallbackInfo<v8::Value>& args); 229 #endif // SSL_set_max_send_fragment 230 231 #ifndef OPENSSL_NO_PSK 232 static void EnablePskCallback( 233 const v8::FunctionCallbackInfo<v8::Value>& args); 234 static void SetPskIdentityHint( 235 const v8::FunctionCallbackInfo<v8::Value>& args); 236 static unsigned int PskServerCallback(SSL* s, 237 const char* identity, 238 unsigned char* psk, 239 unsigned int max_psk_len); 240 static unsigned int PskClientCallback(SSL* s, 241 const char* hint, 242 char* identity, 243 unsigned int max_identity_len, 244 unsigned char* psk, 245 unsigned int max_psk_len); 246 #endif 247 248 Environment* const env_; 249 Kind kind_; 250 SSLSessionPointer next_sess_; 251 SSLPointer ssl_; 252 ClientHelloParser hello_parser_; 253 v8::Global<v8::ArrayBufferView> ocsp_response_; 254 BaseObjectPtr<SecureContext> sni_context_; 255 BaseObjectPtr<SecureContext> sc_; 256 257 // BIO buffers hold encrypted data. 258 BIO* enc_in_ = nullptr; // StreamListener fills this for SSL_read(). 259 BIO* enc_out_ = nullptr; // SSL_write()/handshake fills this for EncOut(). 260 // Waiting for ClearIn() to pass to SSL_write(). 261 std::unique_ptr<v8::BackingStore> pending_cleartext_input_; 262 size_t write_size_ = 0; 263 BaseObjectPtr<AsyncWrap> current_write_; 264 BaseObjectPtr<AsyncWrap> current_empty_write_; 265 std::string error_; 266 267 bool session_callbacks_ = false; 268 bool awaiting_new_session_ = false; 269 bool in_dowrite_ = false; 270 bool started_ = false; 271 bool shutdown_ = false; 272 bool cert_cb_running_ = false; 273 bool eof_ = false; 274 275 // TODO(@jasnell): These state flags should be revisited. 276 // The established_ flag indicates that the handshake is 277 // completed. The write_callback_scheduled_ flag is less 278 // clear -- once it is set to true, it is never set to 279 // false and it is only set to true after established_ 280 // is set to true, so it's likely redundant. 281 bool established_ = false; 282 bool write_callback_scheduled_ = false; 283 284 int cycle_depth_ = 0; 285 286 // SSL_set_cert_cb 287 CertCb cert_cb_ = nullptr; 288 void* cert_cb_arg_ = nullptr; 289 290 BIOPointer bio_trace_; 291 292 bool has_active_write_issued_by_prev_listener_ = false; 293 294 public: 295 std::vector<unsigned char> alpn_protos_; // Accessed by SelectALPNCallback. 296 bool alpn_callback_enabled_ = false; // Accessed by SelectALPNCallback. 297 }; 298 299 } // namespace crypto 300 } // namespace node 301 302 #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS 303 304 #endif // SRC_CRYPTO_CRYPTO_TLS_H_ 305