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: 91 112 81.3 %
Date: 2019-05-05 22:32:45 Branches: 15 28 53.6 %

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