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