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