GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_crypto.h Lines: 94 115 81.7 %
Date: 2019-10-05 22:32:21 Branches: 17 30 56.7 %

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_NODE_CRYPTO_H_
23
#define SRC_NODE_CRYPTO_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
// ClientHelloParser
28
#include "node_crypto_clienthello.h"
29
30
#include "env.h"
31
#include "base_object.h"
32
#include "util.h"
33
34
#include "v8.h"
35
36
#include <openssl/err.h>
37
#include <openssl/ssl.h>
38
39
namespace node {
40
namespace crypto {
41
42
// Forcibly clear OpenSSL's error stack on return. This stops stale errors
43
// from popping up later in the lifecycle of crypto operations where they
44
// would cause spurious failures. It's a rather blunt method, though.
45
// ERR_clear_error() isn't necessarily cheap either.
46
struct ClearErrorOnReturn {
47
12753
  ~ClearErrorOnReturn() { ERR_clear_error(); }
48
};
49
50
// Pop errors from OpenSSL's error stack that were added
51
// between when this was constructed and destructed.
52
struct MarkPopErrorOnReturn {
53
18426
  MarkPopErrorOnReturn() { ERR_set_mark(); }
54
18425
  ~MarkPopErrorOnReturn() { ERR_pop_to_mark(); }
55
};
56
57
// Define smart pointers for the most commonly used OpenSSL types:
58
using X509Pointer = DeleteFnPtr<X509, X509_free>;
59
using BIOPointer = DeleteFnPtr<BIO, BIO_free_all>;
60
using SSLCtxPointer = DeleteFnPtr<SSL_CTX, SSL_CTX_free>;
61
using SSLSessionPointer = DeleteFnPtr<SSL_SESSION, SSL_SESSION_free>;
62
using SSLPointer = DeleteFnPtr<SSL, SSL_free>;
63
using PKCS8Pointer = DeleteFnPtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_free>;
64
using EVPKeyPointer = DeleteFnPtr<EVP_PKEY, EVP_PKEY_free>;
65
using EVPKeyCtxPointer = DeleteFnPtr<EVP_PKEY_CTX, EVP_PKEY_CTX_free>;
66
using EVPMDPointer = DeleteFnPtr<EVP_MD_CTX, EVP_MD_CTX_free>;
67
using RSAPointer = DeleteFnPtr<RSA, RSA_free>;
68
using ECPointer = DeleteFnPtr<EC_KEY, EC_KEY_free>;
69
using BignumPointer = DeleteFnPtr<BIGNUM, BN_free>;
70
using NetscapeSPKIPointer = DeleteFnPtr<NETSCAPE_SPKI, NETSCAPE_SPKI_free>;
71
using ECGroupPointer = DeleteFnPtr<EC_GROUP, EC_GROUP_free>;
72
using ECPointPointer = DeleteFnPtr<EC_POINT, EC_POINT_free>;
73
using ECKeyPointer = DeleteFnPtr<EC_KEY, EC_KEY_free>;
74
using DHPointer = DeleteFnPtr<DH, DH_free>;
75
76
extern int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx);
77
78
extern void UseExtraCaCerts(const std::string& file);
79
80
void InitCryptoOnce();
81
82
class SecureContext : public BaseObject {
83
 public:
84
6933
  ~SecureContext() override {
85
2311
    Reset();
86
4622
  }
87
88
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
89
90
  // TODO(joyeecheung): track the memory used by OpenSSL types
91
3
  SET_NO_MEMORY_INFO()
92
3
  SET_MEMORY_INFO_NAME(SecureContext)
93
3
  SET_SELF_SIZE(SecureContext)
94
95
  SSLCtxPointer ctx_;
96
  X509Pointer cert_;
97
  X509Pointer issuer_;
98
#ifndef OPENSSL_NO_ENGINE
99
  bool client_cert_engine_provided_ = false;
100
  std::unique_ptr<ENGINE, std::function<void(ENGINE*)>> private_key_engine_;
101
#endif  // !OPENSSL_NO_ENGINE
102
103
  static const int kMaxSessionSize = 10 * 1024;
104
105
  // See TicketKeyCallback
106
  static const int kTicketKeyReturnIndex = 0;
107
  static const int kTicketKeyHMACIndex = 1;
108
  static const int kTicketKeyAESIndex = 2;
109
  static const int kTicketKeyNameIndex = 3;
110
  static const int kTicketKeyIVIndex = 4;
111
112
  unsigned char ticket_key_name_[16];
113
  unsigned char ticket_key_aes_[16];
114
  unsigned char ticket_key_hmac_[16];
115
116
 protected:
117
  // OpenSSL structures are opaque. This is sizeof(SSL_CTX) for OpenSSL 1.1.1b:
118
  static const int64_t kExternalSize = 1024;
119
120
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
121
  static void Init(const v8::FunctionCallbackInfo<v8::Value>& args);
122
  static void SetKey(const v8::FunctionCallbackInfo<v8::Value>& args);
123
#ifndef OPENSSL_NO_ENGINE
124
  static void SetEngineKey(const v8::FunctionCallbackInfo<v8::Value>& args);
125
#endif  // !OPENSSL_NO_ENGINE
126
  static void SetCert(const v8::FunctionCallbackInfo<v8::Value>& args);
127
  static void AddCACert(const v8::FunctionCallbackInfo<v8::Value>& args);
128
  static void AddCRL(const v8::FunctionCallbackInfo<v8::Value>& args);
129
  static void AddRootCerts(const v8::FunctionCallbackInfo<v8::Value>& args);
130
  static void SetCipherSuites(const v8::FunctionCallbackInfo<v8::Value>& args);
131
  static void SetCiphers(const v8::FunctionCallbackInfo<v8::Value>& args);
132
  static void SetSigalgs(const v8::FunctionCallbackInfo<v8::Value>& args);
133
  static void SetECDHCurve(const v8::FunctionCallbackInfo<v8::Value>& args);
134
  static void SetDHParam(const v8::FunctionCallbackInfo<v8::Value>& args);
135
  static void SetOptions(const v8::FunctionCallbackInfo<v8::Value>& args);
136
  static void SetSessionIdContext(
137
      const v8::FunctionCallbackInfo<v8::Value>& args);
138
  static void SetSessionTimeout(
139
      const v8::FunctionCallbackInfo<v8::Value>& args);
140
  static void SetMinProto(const v8::FunctionCallbackInfo<v8::Value>& args);
141
  static void SetMaxProto(const v8::FunctionCallbackInfo<v8::Value>& args);
142
  static void GetMinProto(const v8::FunctionCallbackInfo<v8::Value>& args);
143
  static void GetMaxProto(const v8::FunctionCallbackInfo<v8::Value>& args);
144
  static void Close(const v8::FunctionCallbackInfo<v8::Value>& args);
145
  static void LoadPKCS12(const v8::FunctionCallbackInfo<v8::Value>& args);
146
#ifndef OPENSSL_NO_ENGINE
147
  static void SetClientCertEngine(
148
      const v8::FunctionCallbackInfo<v8::Value>& args);
149
#endif  // !OPENSSL_NO_ENGINE
150
  static void GetTicketKeys(const v8::FunctionCallbackInfo<v8::Value>& args);
151
  static void SetTicketKeys(const v8::FunctionCallbackInfo<v8::Value>& args);
152
  static void SetFreeListLength(
153
      const v8::FunctionCallbackInfo<v8::Value>& args);
154
  static void EnableTicketKeyCallback(
155
      const v8::FunctionCallbackInfo<v8::Value>& args);
156
  static void CtxGetter(const v8::FunctionCallbackInfo<v8::Value>& info);
157
158
  template <bool primary>
159
  static void GetCertificate(const v8::FunctionCallbackInfo<v8::Value>& args);
160
161
  static int TicketKeyCallback(SSL* ssl,
162
                               unsigned char* name,
163
                               unsigned char* iv,
164
                               EVP_CIPHER_CTX* ectx,
165
                               HMAC_CTX* hctx,
166
                               int enc);
167
168
  static int TicketCompatibilityCallback(SSL* ssl,
169
                                         unsigned char* name,
170
                                         unsigned char* iv,
171
                                         EVP_CIPHER_CTX* ectx,
172
                                         HMAC_CTX* hctx,
173
                                         int enc);
174
175
2335
  SecureContext(Environment* env, v8::Local<v8::Object> wrap)
176
2335
      : BaseObject(env, wrap) {
177
2335
    MakeWeak();
178
2335
    env->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
179
2335
  }
180
181
3629
  inline void Reset() {
182
3629
    if (ctx_ != nullptr) {
183
2266
      env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
184
    }
185
3629
    ctx_.reset();
186
3629
    cert_.reset();
187
3629
    issuer_.reset();
188
3629
  }
189
};
190
191
// SSLWrap implicitly depends on the inheriting class' handle having an
192
// internal pointer to the Base class.
193
template <class Base>
194
class SSLWrap {
195
 public:
196
  enum Kind {
197
    kClient,
198
    kServer
199
  };
200
201
12239
  SSLWrap(Environment* env, SecureContext* sc, Kind kind)
202
      : env_(env),
203
        kind_(kind),
204
        next_sess_(nullptr),
205
        session_callbacks_(false),
206
        awaiting_new_session_(false),
207
        cert_cb_(nullptr),
208
        cert_cb_arg_(nullptr),
209
24478
        cert_cb_running_(false) {
210
12239
    ssl_.reset(SSL_new(sc->ctx_.get()));
211
12239
    CHECK(ssl_);
212
12239
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
213
12239
  }
214
215
12171
  virtual ~SSLWrap() {
216
12171
    DestroySSL();
217
48684
  }
218
219
259
  inline void enable_session_callbacks() { session_callbacks_ = true; }
220
39291
  inline bool is_server() const { return kind_ == kServer; }
221
13458
  inline bool is_client() const { return kind_ == kClient; }
222
16116
  inline bool is_awaiting_new_session() const { return awaiting_new_session_; }
223
863
  inline bool is_waiting_cert_cb() const { return cert_cb_ != nullptr; }
224
225
 protected:
226
  typedef void (*CertCb)(void* arg);
227
228
  // OpenSSL structures are opaque. Estimate SSL memory size for OpenSSL 1.1.1b:
229
  //   SSL: 6224
230
  //   SSL->SSL3_STATE: 1040
231
  //   ...some buffers: 42 * 1024
232
  // NOTE: Actually it is much more than this
233
  static const int64_t kExternalSize = 6224 + 1040 + 42 * 1024;
234
235
  static void ConfigureSecureContext(SecureContext* sc);
236
  static void AddMethods(Environment* env, v8::Local<v8::FunctionTemplate> t);
237
238
  static SSL_SESSION* GetSessionCallback(SSL* s,
239
                                         const unsigned char* key,
240
                                         int len,
241
                                         int* copy);
242
  static int NewSessionCallback(SSL* s, SSL_SESSION* sess);
243
  static void KeylogCallback(const SSL* s, const char* line);
244
  static void OnClientHello(void* arg,
245
                            const ClientHelloParser::ClientHello& hello);
246
247
  static void GetPeerCertificate(
248
      const v8::FunctionCallbackInfo<v8::Value>& args);
249
  static void GetCertificate(const v8::FunctionCallbackInfo<v8::Value>& args);
250
  static void GetFinished(const v8::FunctionCallbackInfo<v8::Value>& args);
251
  static void GetPeerFinished(const v8::FunctionCallbackInfo<v8::Value>& args);
252
  static void GetSession(const v8::FunctionCallbackInfo<v8::Value>& args);
253
  static void SetSession(const v8::FunctionCallbackInfo<v8::Value>& args);
254
  static void LoadSession(const v8::FunctionCallbackInfo<v8::Value>& args);
255
  static void IsSessionReused(const v8::FunctionCallbackInfo<v8::Value>& args);
256
  static void VerifyError(const v8::FunctionCallbackInfo<v8::Value>& args);
257
  static void GetCipher(const v8::FunctionCallbackInfo<v8::Value>& args);
258
  static void GetSharedSigalgs(const v8::FunctionCallbackInfo<v8::Value>& args);
259
  static void EndParser(const v8::FunctionCallbackInfo<v8::Value>& args);
260
  static void CertCbDone(const v8::FunctionCallbackInfo<v8::Value>& args);
261
  static void Renegotiate(const v8::FunctionCallbackInfo<v8::Value>& args);
262
  static void GetTLSTicket(const v8::FunctionCallbackInfo<v8::Value>& args);
263
  static void NewSessionDone(const v8::FunctionCallbackInfo<v8::Value>& args);
264
  static void SetOCSPResponse(const v8::FunctionCallbackInfo<v8::Value>& args);
265
  static void RequestOCSP(const v8::FunctionCallbackInfo<v8::Value>& args);
266
  static void GetEphemeralKeyInfo(
267
      const v8::FunctionCallbackInfo<v8::Value>& args);
268
  static void GetProtocol(const v8::FunctionCallbackInfo<v8::Value>& args);
269
270
#ifdef SSL_set_max_send_fragment
271
  static void SetMaxSendFragment(
272
      const v8::FunctionCallbackInfo<v8::Value>& args);
273
#endif  // SSL_set_max_send_fragment
274
275
  static void GetALPNNegotiatedProto(
276
      const v8::FunctionCallbackInfo<v8::Value>& args);
277
  static void SetALPNProtocols(const v8::FunctionCallbackInfo<v8::Value>& args);
278
  static int SelectALPNCallback(SSL* s,
279
                                const unsigned char** out,
280
                                unsigned char* outlen,
281
                                const unsigned char* in,
282
                                unsigned int inlen,
283
                                void* arg);
284
  static int TLSExtStatusCallback(SSL* s, void* arg);
285
  static int SSLCertCallback(SSL* s, void* arg);
286
287
  void DestroySSL();
288
  void WaitForCertCb(CertCb cb, void* arg);
289
  void SetSNIContext(SecureContext* sc);
290
  int SetCACerts(SecureContext* sc);
291
292
2265
  inline Environment* ssl_env() const {
293
2265
    return env_;
294
  }
295
296
  Environment* const env_;
297
  Kind kind_;
298
  SSLSessionPointer next_sess_;
299
  SSLPointer ssl_;
300
  bool session_callbacks_;
301
  bool awaiting_new_session_;
302
303
  // SSL_set_cert_cb
304
  CertCb cert_cb_;
305
  void* cert_cb_arg_;
306
  bool cert_cb_running_;
307
308
  ClientHelloParser hello_parser_;
309
310
  v8::Global<v8::ArrayBufferView> ocsp_response_;
311
  v8::Global<v8::Value> sni_context_;
312
313
  friend class SecureContext;
314
};
315
316
// A helper class representing a read-only byte array. When deallocated, its
317
// contents are zeroed.
318
class ByteSource {
319
 public:
320
1271
  ByteSource() = default;
321
  ByteSource(ByteSource&& other);
322
  ~ByteSource();
323
324
  ByteSource& operator=(ByteSource&& other);
325
326
  const char* get() const;
327
  size_t size() const;
328
329
  static ByteSource FromStringOrBuffer(Environment* env,
330
                                       v8::Local<v8::Value> value);
331
332
  static ByteSource FromString(Environment* env,
333
                               v8::Local<v8::String> str,
334
                               bool ntc = false);
335
336
  static ByteSource FromBuffer(v8::Local<v8::Value> buffer,
337
                               bool ntc = false);
338
339
  static ByteSource NullTerminatedCopy(Environment* env,
340
                                       v8::Local<v8::Value> value);
341
342
  static ByteSource FromSymmetricKeyObject(v8::Local<v8::Value> handle);
343
344
  ByteSource(const ByteSource&) = delete;
345
  ByteSource& operator=(const ByteSource&) = delete;
346
347
 private:
348
  const char* data_ = nullptr;
349
  char* allocated_data_ = nullptr;
350
  size_t size_ = 0;
351
352
  ByteSource(const char* data, char* allocated_data, size_t size);
353
354
  static ByteSource Allocated(char* data, size_t size);
355
  static ByteSource Foreign(const char* data, size_t size);
356
};
357
358
enum PKEncodingType {
359
  // RSAPublicKey / RSAPrivateKey according to PKCS#1.
360
  kKeyEncodingPKCS1,
361
  // PrivateKeyInfo or EncryptedPrivateKeyInfo according to PKCS#8.
362
  kKeyEncodingPKCS8,
363
  // SubjectPublicKeyInfo according to X.509.
364
  kKeyEncodingSPKI,
365
  // ECPrivateKey according to SEC1.
366
  kKeyEncodingSEC1
367
};
368
369
enum PKFormatType {
370
  kKeyFormatDER,
371
  kKeyFormatPEM
372
};
373
374
1304
struct AsymmetricKeyEncodingConfig {
375
  bool output_key_object_;
376
  PKFormatType format_;
377
  v8::Maybe<PKEncodingType> type_ = v8::Nothing<PKEncodingType>();
378
};
379
380
typedef AsymmetricKeyEncodingConfig PublicKeyEncodingConfig;
381
382
7270
struct PrivateKeyEncodingConfig : public AsymmetricKeyEncodingConfig {
383
  const EVP_CIPHER* cipher_;
384
  ByteSource passphrase_;
385
};
386
387
enum KeyType {
388
  kKeyTypeSecret,
389
  kKeyTypePublic,
390
  kKeyTypePrivate
391
};
392
393
// This uses the built-in reference counter of OpenSSL to manage an EVP_PKEY
394
// which is slightly more efficient than using a shared pointer and easier to
395
// use.
396
1533
class ManagedEVPPKey {
397
 public:
398
64
  ManagedEVPPKey() = default;
399
  explicit ManagedEVPPKey(EVPKeyPointer&& pkey);
400
  ManagedEVPPKey(const ManagedEVPPKey& that);
401
  ManagedEVPPKey& operator=(const ManagedEVPPKey& that);
402
403
  operator bool() const;
404
  EVP_PKEY* get() const;
405
406
 private:
407
  EVPKeyPointer pkey_;
408
};
409
410
128
class KeyObject : public BaseObject {
411
 public:
412
  static v8::Local<v8::Function> Initialize(Environment* env,
413
                                            v8::Local<v8::Object> target);
414
415
  static v8::MaybeLocal<v8::Object> Create(Environment* env,
416
                                           KeyType type,
417
                                           const ManagedEVPPKey& pkey);
418
419
  // TODO(tniessen): track the memory used by OpenSSL types
420
  SET_NO_MEMORY_INFO()
421
  SET_MEMORY_INFO_NAME(KeyObject)
422
  SET_SELF_SIZE(KeyObject)
423
424
  KeyType GetKeyType() const;
425
426
  // These functions allow unprotected access to the raw key material and should
427
  // only be used to implement cryptograohic operations requiring the key.
428
  ManagedEVPPKey GetAsymmetricKey() const;
429
  const char* GetSymmetricKey() const;
430
  size_t GetSymmetricKeySize() const;
431
432
 protected:
433
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
434
435
  static void Init(const v8::FunctionCallbackInfo<v8::Value>& args);
436
  void InitSecret(v8::Local<v8::ArrayBufferView> abv);
437
  void InitPublic(const ManagedEVPPKey& pkey);
438
  void InitPrivate(const ManagedEVPPKey& pkey);
439
440
  static void GetAsymmetricKeyType(
441
      const v8::FunctionCallbackInfo<v8::Value>& args);
442
  v8::Local<v8::Value> GetAsymmetricKeyType() const;
443
444
  static void GetSymmetricKeySize(
445
      const v8::FunctionCallbackInfo<v8::Value>& args);
446
447
  static void Export(const v8::FunctionCallbackInfo<v8::Value>& args);
448
  v8::Local<v8::Value> ExportSecretKey() const;
449
  v8::MaybeLocal<v8::Value> ExportPublicKey(
450
      const PublicKeyEncodingConfig& config) const;
451
  v8::MaybeLocal<v8::Value> ExportPrivateKey(
452
      const PrivateKeyEncodingConfig& config) const;
453
454
64
  KeyObject(Environment* env,
455
            v8::Local<v8::Object> wrap,
456
            KeyType key_type)
457
      : BaseObject(env, wrap),
458
        key_type_(key_type),
459
64
        symmetric_key_(nullptr, nullptr) {
460
64
    MakeWeak();
461
64
  }
462
463
 private:
464
  const KeyType key_type_;
465
  std::unique_ptr<char, std::function<void(char*)>> symmetric_key_;
466
  unsigned int symmetric_key_len_;
467
  ManagedEVPPKey asymmetric_key_;
468
};
469
470
2514
class CipherBase : public BaseObject {
471
 public:
472
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
473
474
  // TODO(joyeecheung): track the memory used by OpenSSL types
475
  SET_NO_MEMORY_INFO()
476
  SET_MEMORY_INFO_NAME(CipherBase)
477
  SET_SELF_SIZE(CipherBase)
478
479
 protected:
480
  enum CipherKind {
481
    kCipher,
482
    kDecipher
483
  };
484
  enum UpdateResult {
485
    kSuccess,
486
    kErrorMessageSize,
487
    kErrorState
488
  };
489
  enum AuthTagState {
490
    kAuthTagUnknown,
491
    kAuthTagKnown,
492
    kAuthTagPassedToOpenSSL
493
  };
494
  static const unsigned kNoAuthTagLength = static_cast<unsigned>(-1);
495
496
  void CommonInit(const char* cipher_type,
497
                  const EVP_CIPHER* cipher,
498
                  const unsigned char* key,
499
                  int key_len,
500
                  const unsigned char* iv,
501
                  int iv_len,
502
                  unsigned int auth_tag_len);
503
  void Init(const char* cipher_type,
504
            const char* key_buf,
505
            int key_buf_len,
506
            unsigned int auth_tag_len);
507
  void InitIv(const char* cipher_type,
508
              const unsigned char* key,
509
              int key_len,
510
              const unsigned char* iv,
511
              int iv_len,
512
              unsigned int auth_tag_len);
513
  bool InitAuthenticated(const char* cipher_type, int iv_len,
514
                         unsigned int auth_tag_len);
515
  bool CheckCCMMessageLength(int message_len);
516
  UpdateResult Update(const char* data, int len, AllocatedBuffer* out);
517
  bool Final(AllocatedBuffer* out);
518
  bool SetAutoPadding(bool auto_padding);
519
520
  bool IsAuthenticatedMode() const;
521
  bool SetAAD(const char* data, unsigned int len, int plaintext_len);
522
  bool MaybePassAuthTagToOpenSSL();
523
524
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
525
  static void Init(const v8::FunctionCallbackInfo<v8::Value>& args);
526
  static void InitIv(const v8::FunctionCallbackInfo<v8::Value>& args);
527
  static void Update(const v8::FunctionCallbackInfo<v8::Value>& args);
528
  static void Final(const v8::FunctionCallbackInfo<v8::Value>& args);
529
  static void SetAutoPadding(const v8::FunctionCallbackInfo<v8::Value>& args);
530
531
  static void GetAuthTag(const v8::FunctionCallbackInfo<v8::Value>& args);
532
  static void SetAuthTag(const v8::FunctionCallbackInfo<v8::Value>& args);
533
  static void SetAAD(const v8::FunctionCallbackInfo<v8::Value>& args);
534
535
1257
  CipherBase(Environment* env,
536
             v8::Local<v8::Object> wrap,
537
             CipherKind kind)
538
      : BaseObject(env, wrap),
539
        ctx_(nullptr),
540
        kind_(kind),
541
        auth_tag_state_(kAuthTagUnknown),
542
        auth_tag_len_(kNoAuthTagLength),
543
1257
        pending_auth_failed_(false) {
544
1257
    MakeWeak();
545
1257
  }
546
547
 private:
548
  DeleteFnPtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free> ctx_;
549
  const CipherKind kind_;
550
  AuthTagState auth_tag_state_;
551
  unsigned int auth_tag_len_;
552
  char auth_tag_[EVP_GCM_TLS_TAG_LEN];
553
  bool pending_auth_failed_;
554
  int max_message_size_;
555
};
556
557
324
class Hmac : public BaseObject {
558
 public:
559
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
560
561
  // TODO(joyeecheung): track the memory used by OpenSSL types
562
  SET_NO_MEMORY_INFO()
563
  SET_MEMORY_INFO_NAME(Hmac)
564
  SET_SELF_SIZE(Hmac)
565
566
 protected:
567
  void HmacInit(const char* hash_type, const char* key, int key_len);
568
  bool HmacUpdate(const char* data, int len);
569
570
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
571
  static void HmacInit(const v8::FunctionCallbackInfo<v8::Value>& args);
572
  static void HmacUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
573
  static void HmacDigest(const v8::FunctionCallbackInfo<v8::Value>& args);
574
575
162
  Hmac(Environment* env, v8::Local<v8::Object> wrap)
576
      : BaseObject(env, wrap),
577
162
        ctx_(nullptr) {
578
162
    MakeWeak();
579
162
  }
580
581
 private:
582
  DeleteFnPtr<HMAC_CTX, HMAC_CTX_free> ctx_;
583
};
584
585
class Hash : public BaseObject {
586
 public:
587
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
588
589
  // TODO(joyeecheung): track the memory used by OpenSSL types
590
  SET_NO_MEMORY_INFO()
591
  SET_MEMORY_INFO_NAME(Hash)
592
  SET_SELF_SIZE(Hash)
593
594
  bool HashInit(const char* hash_type, v8::Maybe<unsigned int> xof_md_len);
595
  bool HashUpdate(const char* data, int len);
596
597
 protected:
598
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
599
  static void HashUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
600
  static void HashDigest(const v8::FunctionCallbackInfo<v8::Value>& args);
601
602
403218
  Hash(Environment* env, v8::Local<v8::Object> wrap)
603
      : BaseObject(env, wrap),
604
        mdctx_(nullptr),
605
        has_md_(false),
606
403218
        md_value_(nullptr) {
607
403218
    MakeWeak();
608
403218
  }
609
610
1209579
  ~Hash() override {
611
403193
    if (md_value_ != nullptr)
612
403176
      OPENSSL_clear_free(md_value_, md_len_);
613
806386
  }
614
615
 private:
616
  EVPMDPointer mdctx_;
617
  bool has_md_;
618
  unsigned int md_len_;
619
  unsigned char* md_value_;
620
};
621
622
715
class SignBase : public BaseObject {
623
 public:
624
  typedef enum {
625
    kSignOk,
626
    kSignUnknownDigest,
627
    kSignInit,
628
    kSignNotInitialised,
629
    kSignUpdate,
630
    kSignPrivateKey,
631
    kSignPublicKey
632
  } Error;
633
634
715
  SignBase(Environment* env, v8::Local<v8::Object> wrap)
635
715
      : BaseObject(env, wrap) {
636
715
  }
637
638
  Error Init(const char* sign_type);
639
  Error Update(const char* data, int len);
640
641
  // TODO(joyeecheung): track the memory used by OpenSSL types
642
  SET_NO_MEMORY_INFO()
643
  SET_MEMORY_INFO_NAME(SignBase)
644
  SET_SELF_SIZE(SignBase)
645
646
 protected:
647
  void CheckThrow(Error error);
648
649
  EVPMDPointer mdctx_;
650
};
651
652
270
class Sign : public SignBase {
653
 public:
654
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
655
656
112
  struct SignResult {
657
    Error error;
658
    AllocatedBuffer signature;
659
660
112
    explicit SignResult(
661
        Error err,
662
        AllocatedBuffer&& sig = AllocatedBuffer())
663
112
      : error(err), signature(std::move(sig)) {}
664
  };
665
666
  SignResult SignFinal(
667
      const ManagedEVPPKey& pkey,
668
      int padding,
669
      const v8::Maybe<int>& saltlen);
670
671
 protected:
672
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
673
  static void SignInit(const v8::FunctionCallbackInfo<v8::Value>& args);
674
  static void SignUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
675
  static void SignFinal(const v8::FunctionCallbackInfo<v8::Value>& args);
676
677
135
  Sign(Environment* env, v8::Local<v8::Object> wrap) : SignBase(env, wrap) {
678
135
    MakeWeak();
679
135
  }
680
};
681
682
1160
class Verify : public SignBase {
683
 public:
684
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
685
686
  Error VerifyFinal(const ManagedEVPPKey& key,
687
                    const char* sig,
688
                    int siglen,
689
                    int padding,
690
                    const v8::Maybe<int>& saltlen,
691
                    bool* verify_result);
692
693
 protected:
694
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
695
  static void VerifyInit(const v8::FunctionCallbackInfo<v8::Value>& args);
696
  static void VerifyUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
697
  static void VerifyFinal(const v8::FunctionCallbackInfo<v8::Value>& args);
698
699
580
  Verify(Environment* env, v8::Local<v8::Object> wrap) : SignBase(env, wrap) {
700
580
    MakeWeak();
701
580
  }
702
};
703
704
class PublicKeyCipher {
705
 public:
706
  typedef int (*EVP_PKEY_cipher_init_t)(EVP_PKEY_CTX* ctx);
707
  typedef int (*EVP_PKEY_cipher_t)(EVP_PKEY_CTX* ctx,
708
                                   unsigned char* out, size_t* outlen,
709
                                   const unsigned char* in, size_t inlen);
710
711
  enum Operation {
712
    kPublic,
713
    kPrivate
714
  };
715
716
  template <Operation operation,
717
            EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
718
            EVP_PKEY_cipher_t EVP_PKEY_cipher>
719
  static bool Cipher(Environment* env,
720
                     const ManagedEVPPKey& pkey,
721
                     int padding,
722
                     const EVP_MD* digest,
723
                     const void* oaep_label,
724
                     size_t oaep_label_size,
725
                     const unsigned char* data,
726
                     int len,
727
                     AllocatedBuffer* out);
728
729
  template <Operation operation,
730
            EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
731
            EVP_PKEY_cipher_t EVP_PKEY_cipher>
732
  static void Cipher(const v8::FunctionCallbackInfo<v8::Value>& args);
733
};
734
735
8126
class DiffieHellman : public BaseObject {
736
 public:
737
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
738
739
  bool Init(int primeLength, int g);
740
  bool Init(const char* p, int p_len, int g);
741
  bool Init(const char* p, int p_len, const char* g, int g_len);
742
743
 protected:
744
  static void DiffieHellmanGroup(
745
      const v8::FunctionCallbackInfo<v8::Value>& args);
746
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
747
  static void GenerateKeys(const v8::FunctionCallbackInfo<v8::Value>& args);
748
  static void GetPrime(const v8::FunctionCallbackInfo<v8::Value>& args);
749
  static void GetGenerator(const v8::FunctionCallbackInfo<v8::Value>& args);
750
  static void GetPublicKey(const v8::FunctionCallbackInfo<v8::Value>& args);
751
  static void GetPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
752
  static void ComputeSecret(const v8::FunctionCallbackInfo<v8::Value>& args);
753
  static void SetPublicKey(const v8::FunctionCallbackInfo<v8::Value>& args);
754
  static void SetPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
755
  static void VerifyErrorGetter(
756
      const v8::FunctionCallbackInfo<v8::Value>& args);
757
758
4063
  DiffieHellman(Environment* env, v8::Local<v8::Object> wrap)
759
      : BaseObject(env, wrap),
760
4063
        verifyError_(0) {
761
4063
    MakeWeak();
762
4063
  }
763
764
  // TODO(joyeecheung): track the memory used by OpenSSL types
765
  SET_NO_MEMORY_INFO()
766
  SET_MEMORY_INFO_NAME(DiffieHellman)
767
  SET_SELF_SIZE(DiffieHellman)
768
769
 private:
770
  static void GetField(const v8::FunctionCallbackInfo<v8::Value>& args,
771
                       const BIGNUM* (*get_field)(const DH*),
772
                       const char* err_if_null);
773
  static void SetKey(const v8::FunctionCallbackInfo<v8::Value>& args,
774
                     int (*set_field)(DH*, BIGNUM*), const char* what);
775
  bool VerifyContext();
776
777
  int verifyError_;
778
  DHPointer dh_;
779
};
780
781
class ECDH : public BaseObject {
782
 public:
783
30
  ~ECDH() override {
784
10
    group_ = nullptr;
785
20
  }
786
787
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
788
  static ECPointPointer BufferToPoint(Environment* env,
789
                                      const EC_GROUP* group,
790
                                      v8::Local<v8::Value> buf);
791
792
  // TODO(joyeecheung): track the memory used by OpenSSL types
793
  SET_NO_MEMORY_INFO()
794
  SET_MEMORY_INFO_NAME(ECDH)
795
  SET_SELF_SIZE(ECDH)
796
797
 protected:
798
10
  ECDH(Environment* env, v8::Local<v8::Object> wrap, ECKeyPointer&& key)
799
      : BaseObject(env, wrap),
800
10
        key_(std::move(key)),
801
20
        group_(EC_KEY_get0_group(key_.get())) {
802
10
    MakeWeak();
803
10
    CHECK_NOT_NULL(group_);
804
10
  }
805
806
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
807
  static void GenerateKeys(const v8::FunctionCallbackInfo<v8::Value>& args);
808
  static void ComputeSecret(const v8::FunctionCallbackInfo<v8::Value>& args);
809
  static void GetPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
810
  static void SetPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
811
  static void GetPublicKey(const v8::FunctionCallbackInfo<v8::Value>& args);
812
  static void SetPublicKey(const v8::FunctionCallbackInfo<v8::Value>& args);
813
814
  bool IsKeyPairValid();
815
  bool IsKeyValidForCurve(const BignumPointer& private_key);
816
817
  ECKeyPointer key_;
818
  const EC_GROUP* group_;
819
};
820
821
bool EntropySource(unsigned char* buffer, size_t length);
822
#ifndef OPENSSL_NO_ENGINE
823
void SetEngine(const v8::FunctionCallbackInfo<v8::Value>& args);
824
#endif  // !OPENSSL_NO_ENGINE
825
void InitCrypto(v8::Local<v8::Object> target);
826
827
}  // namespace crypto
828
}  // namespace node
829
830
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
831
832
#endif  // SRC_NODE_CRYPTO_H_