GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.h Lines: 11 13 84.6 %
Date: 2021-09-21 04:13:38 Branches: 0 0 - %

Line Branch Exec Source
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 "allocated_buffer.h"
31
#include "async_wrap.h"
32
#include "stream_wrap.h"
33
#include "v8.h"
34
35
#include <openssl/ssl.h>
36
37
#include <string>
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
  static void Initialize(v8::Local<v8::Object> target,
52
                         v8::Local<v8::Value> unused,
53
                         v8::Local<v8::Context> context,
54
                         void* priv);
55
56
  ~TLSWrap() override;
57
58
50
  bool is_cert_cb_running() const { return cert_cb_running_; }
59
890
  bool is_waiting_cert_cb() const { return cert_cb_ != nullptr; }
60
1787
  bool has_session_callbacks() const { return session_callbacks_; }
61
25
  void set_cert_cb_running(bool on = true) { cert_cb_running_ = on; }
62
8
  void set_awaiting_new_session(bool on = true) { awaiting_new_session_ = on; }
63
208
  void enable_session_callbacks() { session_callbacks_ = true; }
64
39186
  bool is_server() const { return kind_ == Kind::kServer; }
65
13327
  bool is_client() const { return kind_ == Kind::kClient; }
66
15703
  bool is_awaiting_new_session() const { return awaiting_new_session_; }
67
68
  // Implement StreamBase:
69
  bool IsAlive() override;
70
  bool IsClosing() override;
71
  bool IsIPCPipe() override;
72
  int GetFD() override;
73
  ShutdownWrap* CreateShutdownWrap(
74
      v8::Local<v8::Object> req_wrap_object) override;
75
  AsyncWrap* GetAsyncWrap() override;
76
77
78
  // Implement StreamResource:
79
  int ReadStart() override;  // Exposed to JS
80
  int ReadStop() override;   // Exposed to JS
81
  int DoShutdown(ShutdownWrap* req_wrap) override;
82
  int DoWrite(WriteWrap* w,
83
              uv_buf_t* bufs,
84
              size_t count,
85
              uv_stream_t* send_handle) override;
86
  // Return error_ string or nullptr if it's empty.
87
  const char* Error() const override;
88
  // Reset error_ string to empty. Not related to "clear text".
89
  void ClearError() override;
90
91
  v8::MaybeLocal<v8::ArrayBufferView> ocsp_response() const;
92
  void ClearOcspResponse();
93
  SSL_SESSION* ReleaseSession();
94
95
  // Called by the done() callback of the 'newSession' event.
96
  void NewSessionDoneCb();
97
98
  // Implement MemoryRetainer:
99
  void MemoryInfo(MemoryTracker* tracker) const override;
100
  SET_MEMORY_INFO_NAME(TLSWrap)
101
  SET_SELF_SIZE(TLSWrap)
102
103
  std::string diagnostic_name() const override;
104
105
 private:
106
  // OpenSSL structures are opaque. Estimate SSL memory size for OpenSSL 1.1.1b:
107
  //   SSL: 6224
108
  //   SSL->SSL3_STATE: 1040
109
  //   ...some buffers: 42 * 1024
110
  // NOTE: Actually it is much more than this
111
  static constexpr int64_t kExternalSize = 6224 + 1040 + 42 * 1024;
112
113
  static constexpr int kClearOutChunkSize = 16384;
114
115
  // Maximum number of bytes for hello parser
116
  static constexpr int kMaxHelloLength = 16384;
117
118
  // Usual ServerHello + Certificate size
119
  static constexpr int kInitialClientBufferLength = 4096;
120
121
  // Maximum number of buffers passed to uv_write()
122
  static constexpr int kSimultaneousBufferCount = 10;
123
124
  typedef void (*CertCb)(void* arg);
125
126
  // Alternative to StreamListener::stream(), that returns a StreamBase instead
127
  // of a StreamResource.
128
57057
  StreamBase* underlying_stream() const {
129
57057
    return static_cast<StreamBase*>(stream());
130
  }
131
132
  void WaitForCertCb(CertCb cb, void* arg);
133
134
  TLSWrap(Environment* env,
135
          v8::Local<v8::Object> obj,
136
          Kind kind,
137
          StreamBase* stream,
138
          SecureContext* sc);
139
140
  static void SSLInfoCallback(const SSL* ssl_, int where, int ret);
141
  void InitSSL();
142
  // SSL has a "clear" text (unencrypted) side (to/from the node API) and
143
  // encrypted ("enc") text side (to/from the underlying socket/stream).
144
  // On each side data flows "in" or "out" of SSL context.
145
  //
146
  // EncIn() doesn't exist. Encrypted data is pushed from underlying stream into
147
  // enc_in_ via the stream listener's OnStreamAlloc()/OnStreamRead() interface.
148
  void EncOut();  // Write encrypted data from enc_out_ to underlying stream.
149
  void ClearIn();  // SSL_write() clear data "in" to SSL.
150
  void ClearOut();  // SSL_read() clear text "out" from SSL.
151
  void Destroy();
152
153
  // Call Done() on outstanding WriteWrap request.
154
  void InvokeQueued(int status, const char* error_str = nullptr);
155
156
  // Drive the SSL state machine by attempting to SSL_read() and SSL_write() to
157
  // it. Transparent handshakes mean SSL_read() might trigger I/O on the
158
  // underlying stream even if there is no clear text to read or write.
159
  void Cycle();
160
161
  // Implement StreamListener:
162
  // Returns buf that points into enc_in_.
163
  uv_buf_t OnStreamAlloc(size_t size) override;
164
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
165
  void OnStreamAfterWrite(WriteWrap* w, int status) override;
166
167
  int SetCACerts(SecureContext* sc);
168
169
  v8::MaybeLocal<v8::Value> GetSSLError(int status, int* err, std::string* msg);
170
171
  static int SelectSNIContextCallback(SSL* s, int* ad, void* arg);
172
173
  static void CertCbDone(const v8::FunctionCallbackInfo<v8::Value>& args);
174
  static void DestroySSL(const v8::FunctionCallbackInfo<v8::Value>& args);
175
  static void EnableCertCb(const v8::FunctionCallbackInfo<v8::Value>& args);
176
  static void EnableKeylogCallback(
177
      const v8::FunctionCallbackInfo<v8::Value>& args);
178
  static void EnableSessionCallbacks(
179
      const v8::FunctionCallbackInfo<v8::Value>& args);
180
  static void EnableTrace(const v8::FunctionCallbackInfo<v8::Value>& args);
181
  static void EndParser(const v8::FunctionCallbackInfo<v8::Value>& args);
182
  static void ExportKeyingMaterial(
183
      const v8::FunctionCallbackInfo<v8::Value>& args);
184
  static void GetALPNNegotiatedProto(
185
      const v8::FunctionCallbackInfo<v8::Value>& args);
186
  static void GetCertificate(const v8::FunctionCallbackInfo<v8::Value>& args);
187
  static void GetX509Certificate(
188
      const v8::FunctionCallbackInfo<v8::Value>& args);
189
  static void GetCipher(const v8::FunctionCallbackInfo<v8::Value>& args);
190
  static void GetEphemeralKeyInfo(
191
      const v8::FunctionCallbackInfo<v8::Value>& args);
192
  static void GetFinished(const v8::FunctionCallbackInfo<v8::Value>& args);
193
  static void GetPeerCertificate(
194
      const v8::FunctionCallbackInfo<v8::Value>& args);
195
  static void GetPeerX509Certificate(
196
      const v8::FunctionCallbackInfo<v8::Value>& args);
197
  static void GetPeerFinished(const v8::FunctionCallbackInfo<v8::Value>& args);
198
  static void GetProtocol(const v8::FunctionCallbackInfo<v8::Value>& args);
199
  static void GetServername(const v8::FunctionCallbackInfo<v8::Value>& args);
200
  static void GetSession(const v8::FunctionCallbackInfo<v8::Value>& args);
201
  static void GetSharedSigalgs(const v8::FunctionCallbackInfo<v8::Value>& args);
202
  static void GetTLSTicket(const v8::FunctionCallbackInfo<v8::Value>& args);
203
  static void GetWriteQueueSize(
204
      const v8::FunctionCallbackInfo<v8::Value>& info);
205
  static void IsSessionReused(const v8::FunctionCallbackInfo<v8::Value>& args);
206
  static void LoadSession(const v8::FunctionCallbackInfo<v8::Value>& args);
207
  static void NewSessionDone(const v8::FunctionCallbackInfo<v8::Value>& args);
208
  static void OnClientHelloParseEnd(void* arg);
209
  static void Receive(const v8::FunctionCallbackInfo<v8::Value>& args);
210
  static void Renegotiate(const v8::FunctionCallbackInfo<v8::Value>& args);
211
  static void RequestOCSP(const v8::FunctionCallbackInfo<v8::Value>& args);
212
  static void SetALPNProtocols(const v8::FunctionCallbackInfo<v8::Value>& args);
213
  static void SetOCSPResponse(const v8::FunctionCallbackInfo<v8::Value>& args);
214
  static void SetServername(const v8::FunctionCallbackInfo<v8::Value>& args);
215
  static void SetSession(const v8::FunctionCallbackInfo<v8::Value>& args);
216
  static void SetVerifyMode(const v8::FunctionCallbackInfo<v8::Value>& args);
217
  static void Start(const v8::FunctionCallbackInfo<v8::Value>& args);
218
  static void VerifyError(const v8::FunctionCallbackInfo<v8::Value>& args);
219
  static void Wrap(const v8::FunctionCallbackInfo<v8::Value>& args);
220
221
#ifdef SSL_set_max_send_fragment
222
  static void SetMaxSendFragment(
223
      const v8::FunctionCallbackInfo<v8::Value>& args);
224
#endif  // SSL_set_max_send_fragment
225
226
#ifndef OPENSSL_NO_PSK
227
  static void EnablePskCallback(
228
      const v8::FunctionCallbackInfo<v8::Value>& args);
229
  static void SetPskIdentityHint(
230
      const v8::FunctionCallbackInfo<v8::Value>& args);
231
  static unsigned int PskServerCallback(SSL* s,
232
                                        const char* identity,
233
                                        unsigned char* psk,
234
                                        unsigned int max_psk_len);
235
  static unsigned int PskClientCallback(SSL* s,
236
                                        const char* hint,
237
                                        char* identity,
238
                                        unsigned int max_identity_len,
239
                                        unsigned char* psk,
240
                                        unsigned int max_psk_len);
241
#endif
242
243
  Environment* const env_;
244
  Kind kind_;
245
  SSLSessionPointer next_sess_;
246
  SSLPointer ssl_;
247
  ClientHelloParser hello_parser_;
248
  v8::Global<v8::ArrayBufferView> ocsp_response_;
249
  BaseObjectPtr<SecureContext> sni_context_;
250
  BaseObjectPtr<SecureContext> sc_;
251
252
  // BIO buffers hold encrypted data.
253
  BIO* enc_in_ = nullptr;   // StreamListener fills this for SSL_read().
254
  BIO* enc_out_ = nullptr;  // SSL_write()/handshake fills this for EncOut().
255
  // Waiting for ClearIn() to pass to SSL_write().
256
  AllocatedBuffer pending_cleartext_input_;
257
  size_t write_size_ = 0;
258
  BaseObjectPtr<AsyncWrap> current_write_;
259
  BaseObjectPtr<AsyncWrap> current_empty_write_;
260
  std::string error_;
261
262
  bool session_callbacks_ = false;
263
  bool awaiting_new_session_ = false;
264
  bool in_dowrite_ = false;
265
  bool started_ = false;
266
  bool shutdown_ = false;
267
  bool cert_cb_running_ = false;
268
  bool eof_ = false;
269
270
  // TODO(@jasnell): These state flags should be revisited.
271
  // The established_ flag indicates that the handshake is
272
  // completed. The write_callback_scheduled_ flag is less
273
  // clear -- once it is set to true, it is never set to
274
  // false and it is only set to true after established_
275
  // is set to true, so it's likely redundant.
276
  bool established_ = false;
277
  bool write_callback_scheduled_ = false;
278
279
  int cycle_depth_ = 0;
280
281
  // SSL_set_cert_cb
282
  CertCb cert_cb_ = nullptr;
283
  void* cert_cb_arg_ = nullptr;
284
285
  BIOPointer bio_trace_;
286
};
287
288
}  // namespace crypto
289
}  // namespace node
290
291
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
292
293
#endif  // SRC_CRYPTO_CRYPTO_TLS_H_