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