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-02-23 22:23:05 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
25789
  MarkPopErrorOnReturn() { ERR_set_mark(); }
71
25787
  ~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
2685
  inline void Reset() {
198
2685
    if (ctx_ != nullptr) {
199
1661
      env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
200
    }
201
2685
    ctx_.reset();
202
2685
    cert_.reset();
203
2685
    issuer_.reset();
204
2685
  }
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
11708
  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
23416
        cert_cb_running_(false) {
226
11708
    ssl_.reset(SSL_new(sc->ctx_.get()));
227
11708
    CHECK(ssl_);
228
11708
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
229
11708
  }
230
231
11569
  virtual ~SSLWrap() {
232
11569
    DestroySSL();
233
46276
  }
234
235
183
  inline void enable_session_callbacks() { session_callbacks_ = true; }
236
36796
  inline bool is_server() const { return kind_ == kServer; }
237
12720
  inline bool is_client() const { return kind_ == kClient; }
238
13414
  inline bool is_awaiting_new_session() const { return awaiting_new_session_; }
239
667
  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 IsInitFinished(const v8::FunctionCallbackInfo<v8::Value>& args);
284
  static void VerifyError(const v8::FunctionCallbackInfo<v8::Value>& args);
285
  static void GetCurrentCipher(const v8::FunctionCallbackInfo<v8::Value>& args);
286
  static void EndParser(const v8::FunctionCallbackInfo<v8::Value>& args);
287
  static void CertCbDone(const v8::FunctionCallbackInfo<v8::Value>& args);
288
  static void Renegotiate(const v8::FunctionCallbackInfo<v8::Value>& args);
289
  static void Shutdown(const v8::FunctionCallbackInfo<v8::Value>& args);
290
  static void GetTLSTicket(const v8::FunctionCallbackInfo<v8::Value>& args);
291
  static void NewSessionDone(const v8::FunctionCallbackInfo<v8::Value>& args);
292
  static void SetOCSPResponse(const v8::FunctionCallbackInfo<v8::Value>& args);
293
  static void RequestOCSP(const v8::FunctionCallbackInfo<v8::Value>& args);
294
  static void GetEphemeralKeyInfo(
295
      const v8::FunctionCallbackInfo<v8::Value>& args);
296
  static void GetProtocol(const v8::FunctionCallbackInfo<v8::Value>& args);
297
298
#ifdef SSL_set_max_send_fragment
299
  static void SetMaxSendFragment(
300
      const v8::FunctionCallbackInfo<v8::Value>& args);
301
#endif  // SSL_set_max_send_fragment
302
303
  static void GetALPNNegotiatedProto(
304
      const v8::FunctionCallbackInfo<v8::Value>& args);
305
  static void SetALPNProtocols(const v8::FunctionCallbackInfo<v8::Value>& args);
306
  static int SelectALPNCallback(SSL* s,
307
                                const unsigned char** out,
308
                                unsigned char* outlen,
309
                                const unsigned char* in,
310
                                unsigned int inlen,
311
                                void* arg);
312
  static int TLSExtStatusCallback(SSL* s, void* arg);
313
  static int SSLCertCallback(SSL* s, void* arg);
314
315
  void DestroySSL();
316
  void WaitForCertCb(CertCb cb, void* arg);
317
  void SetSNIContext(SecureContext* sc);
318
  int SetCACerts(SecureContext* sc);
319
320
883
  inline Environment* ssl_env() const {
321
883
    return env_;
322
  }
323
324
  Environment* const env_;
325
  Kind kind_;
326
  SSLSessionPointer next_sess_;
327
  SSLPointer ssl_;
328
  bool session_callbacks_;
329
  bool awaiting_new_session_;
330
331
  // SSL_set_cert_cb
332
  CertCb cert_cb_;
333
  void* cert_cb_arg_;
334
  bool cert_cb_running_;
335
336
  ClientHelloParser hello_parser_;
337
338
  Persistent<v8::Object> ocsp_response_;
339
  Persistent<v8::Value> sni_context_;
340
341
  friend class SecureContext;
342
};
343
344
// A helper class representing a read-only byte array. When deallocated, its
345
// contents are zeroed.
346
class ByteSource {
347
 public:
348
361
  ByteSource() = default;
349
  ByteSource(ByteSource&& other);
350
  ~ByteSource();
351
352
  ByteSource& operator=(ByteSource&& other);
353
354
  const char* get() const;
355
  size_t size() const;
356
357
  static ByteSource FromStringOrBuffer(Environment* env,
358
                                       v8::Local<v8::Value> value);
359
360
  static ByteSource FromString(Environment* env,
361
                               v8::Local<v8::String> str,
362
                               bool ntc = false);
363
364
  static ByteSource FromBuffer(v8::Local<v8::Value> buffer,
365
                               bool ntc = false);
366
367
  static ByteSource NullTerminatedCopy(Environment* env,
368
                                       v8::Local<v8::Value> value);
369
370
  static ByteSource FromSymmetricKeyObject(v8::Local<v8::Value> handle);
371
372
 private:
373
  const char* data_ = nullptr;
374
  char* allocated_data_ = nullptr;
375
  size_t size_ = 0;
376
377
  ByteSource(const char* data, char* allocated_data, size_t size);
378
379
  static ByteSource Allocated(char* data, size_t size);
380
  static ByteSource Foreign(const char* data, size_t size);
381
382
  DISALLOW_COPY_AND_ASSIGN(ByteSource);
383
};
384
385
enum PKEncodingType {
386
  // RSAPublicKey / RSAPrivateKey according to PKCS#1.
387
  kKeyEncodingPKCS1,
388
  // PrivateKeyInfo or EncryptedPrivateKeyInfo according to PKCS#8.
389
  kKeyEncodingPKCS8,
390
  // SubjectPublicKeyInfo according to X.509.
391
  kKeyEncodingSPKI,
392
  // ECPrivateKey according to SEC1.
393
  kKeyEncodingSEC1
394
};
395
396
enum PKFormatType {
397
  kKeyFormatDER,
398
  kKeyFormatPEM
399
};
400
401
378
struct AsymmetricKeyEncodingConfig {
402
  bool output_key_object_;
403
  PKFormatType format_;
404
  v8::Maybe<PKEncodingType> type_ = v8::Nothing<PKEncodingType>();
405
};
406
407
typedef AsymmetricKeyEncodingConfig PublicKeyEncodingConfig;
408
409
2030
struct PrivateKeyEncodingConfig : public AsymmetricKeyEncodingConfig {
410
  const EVP_CIPHER* cipher_;
411
  ByteSource passphrase_;
412
};
413
414
enum KeyType {
415
  kKeyTypeSecret,
416
  kKeyTypePublic,
417
  kKeyTypePrivate
418
};
419
420
// This uses the built-in reference counter of OpenSSL to manage an EVP_PKEY
421
// which is slightly more efficient than using a shared pointer and easier to
422
// use.
423
class ManagedEVPPKey {
424
 public:
425
  ManagedEVPPKey();
426
  explicit ManagedEVPPKey(EVP_PKEY* pkey);
427
  ManagedEVPPKey(const ManagedEVPPKey& key);
428
  ManagedEVPPKey(ManagedEVPPKey&& key);
429
  ~ManagedEVPPKey();
430
431
  ManagedEVPPKey& operator=(const ManagedEVPPKey& key);
432
  ManagedEVPPKey& operator=(ManagedEVPPKey&& key);
433
434
  operator bool() const;
435
  EVP_PKEY* get() const;
436
437
 private:
438
  EVP_PKEY* pkey_;
439
};
440
441
42
class KeyObject : public BaseObject {
442
 public:
443
  static v8::Local<v8::Function> Initialize(Environment* env,
444
                                            v8::Local<v8::Object> target);
445
446
  static v8::MaybeLocal<v8::Object> Create(Environment* env,
447
                                           KeyType type,
448
                                           const ManagedEVPPKey& pkey);
449
450
  // TODO(tniessen): track the memory used by OpenSSL types
451
  SET_NO_MEMORY_INFO()
452
  SET_MEMORY_INFO_NAME(KeyObject)
453
  SET_SELF_SIZE(KeyObject)
454
455
  KeyType GetKeyType() const;
456
457
  // These functions allow unprotected access to the raw key material and should
458
  // only be used to implement cryptograohic operations requiring the key.
459
  ManagedEVPPKey GetAsymmetricKey() const;
460
  const char* GetSymmetricKey() const;
461
  size_t GetSymmetricKeySize() const;
462
463
 protected:
464
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
465
466
  static void Init(const v8::FunctionCallbackInfo<v8::Value>& args);
467
  void InitSecret(const char* key, size_t key_len);
468
  void InitPublic(const ManagedEVPPKey& pkey);
469
  void InitPrivate(const ManagedEVPPKey& pkey);
470
471
  static void GetAsymmetricKeyType(
472
      const v8::FunctionCallbackInfo<v8::Value>& args);
473
  v8::Local<v8::String> GetAsymmetricKeyType() const;
474
475
  static void GetSymmetricKeySize(
476
      const v8::FunctionCallbackInfo<v8::Value>& args);
477
478
  static void Export(const v8::FunctionCallbackInfo<v8::Value>& args);
479
  v8::Local<v8::Value> ExportSecretKey() const;
480
  v8::MaybeLocal<v8::Value> ExportPublicKey(
481
      const PublicKeyEncodingConfig& config) const;
482
  v8::MaybeLocal<v8::Value> ExportPrivateKey(
483
      const PrivateKeyEncodingConfig& config) const;
484
485
21
  KeyObject(Environment* env,
486
            v8::Local<v8::Object> wrap,
487
            KeyType key_type)
488
      : BaseObject(env, wrap),
489
        key_type_(key_type),
490
21
        symmetric_key_(nullptr, nullptr) {
491
21
    MakeWeak();
492
21
  }
493
494
 private:
495
  const KeyType key_type_;
496
  std::unique_ptr<char, std::function<void(char*)>> symmetric_key_;
497
  unsigned int symmetric_key_len_;
498
  ManagedEVPPKey asymmetric_key_;
499
};
500
501
2504
class CipherBase : public BaseObject {
502
 public:
503
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
504
505
  // TODO(joyeecheung): track the memory used by OpenSSL types
506
  SET_NO_MEMORY_INFO()
507
  SET_MEMORY_INFO_NAME(CipherBase)
508
  SET_SELF_SIZE(CipherBase)
509
510
 protected:
511
  enum CipherKind {
512
    kCipher,
513
    kDecipher
514
  };
515
  enum UpdateResult {
516
    kSuccess,
517
    kErrorMessageSize,
518
    kErrorState
519
  };
520
  enum AuthTagState {
521
    kAuthTagUnknown,
522
    kAuthTagKnown,
523
    kAuthTagPassedToOpenSSL
524
  };
525
  static const unsigned kNoAuthTagLength = static_cast<unsigned>(-1);
526
527
  void CommonInit(const char* cipher_type,
528
                  const EVP_CIPHER* cipher,
529
                  const unsigned char* key,
530
                  int key_len,
531
                  const unsigned char* iv,
532
                  int iv_len,
533
                  unsigned int auth_tag_len);
534
  void Init(const char* cipher_type,
535
            const char* key_buf,
536
            int key_buf_len,
537
            unsigned int auth_tag_len);
538
  void InitIv(const char* cipher_type,
539
              const unsigned char* key,
540
              int key_len,
541
              const unsigned char* iv,
542
              int iv_len,
543
              unsigned int auth_tag_len);
544
  bool InitAuthenticated(const char* cipher_type, int iv_len,
545
                         unsigned int auth_tag_len);
546
  bool CheckCCMMessageLength(int message_len);
547
  UpdateResult Update(const char* data, int len, unsigned char** out,
548
                      int* out_len);
549
  bool Final(unsigned char** out, int* out_len);
550
  bool SetAutoPadding(bool auto_padding);
551
552
  bool IsAuthenticatedMode() const;
553
  bool SetAAD(const char* data, unsigned int len, int plaintext_len);
554
  bool MaybePassAuthTagToOpenSSL();
555
556
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
557
  static void Init(const v8::FunctionCallbackInfo<v8::Value>& args);
558
  static void InitIv(const v8::FunctionCallbackInfo<v8::Value>& args);
559
  static void Update(const v8::FunctionCallbackInfo<v8::Value>& args);
560
  static void Final(const v8::FunctionCallbackInfo<v8::Value>& args);
561
  static void SetAutoPadding(const v8::FunctionCallbackInfo<v8::Value>& args);
562
563
  static void GetAuthTag(const v8::FunctionCallbackInfo<v8::Value>& args);
564
  static void SetAuthTag(const v8::FunctionCallbackInfo<v8::Value>& args);
565
  static void SetAAD(const v8::FunctionCallbackInfo<v8::Value>& args);
566
567
1252
  CipherBase(Environment* env,
568
             v8::Local<v8::Object> wrap,
569
             CipherKind kind)
570
      : BaseObject(env, wrap),
571
        ctx_(nullptr),
572
        kind_(kind),
573
        auth_tag_state_(kAuthTagUnknown),
574
        auth_tag_len_(kNoAuthTagLength),
575
1252
        pending_auth_failed_(false) {
576
1252
    MakeWeak();
577
1252
  }
578
579
 private:
580
  DeleteFnPtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free> ctx_;
581
  const CipherKind kind_;
582
  AuthTagState auth_tag_state_;
583
  unsigned int auth_tag_len_;
584
  char auth_tag_[EVP_GCM_TLS_TAG_LEN];
585
  bool pending_auth_failed_;
586
  int max_message_size_;
587
};
588
589
320
class Hmac : public BaseObject {
590
 public:
591
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
592
593
  // TODO(joyeecheung): track the memory used by OpenSSL types
594
  SET_NO_MEMORY_INFO()
595
  SET_MEMORY_INFO_NAME(Hmac)
596
  SET_SELF_SIZE(Hmac)
597
598
 protected:
599
  void HmacInit(const char* hash_type, const char* key, int key_len);
600
  bool HmacUpdate(const char* data, int len);
601
602
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
603
  static void HmacInit(const v8::FunctionCallbackInfo<v8::Value>& args);
604
  static void HmacUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
605
  static void HmacDigest(const v8::FunctionCallbackInfo<v8::Value>& args);
606
607
160
  Hmac(Environment* env, v8::Local<v8::Object> wrap)
608
      : BaseObject(env, wrap),
609
160
        ctx_(nullptr) {
610
160
    MakeWeak();
611
160
  }
612
613
 private:
614
  DeleteFnPtr<HMAC_CTX, HMAC_CTX_free> ctx_;
615
};
616
617
1588
class Hash : public BaseObject {
618
 public:
619
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
620
621
  // TODO(joyeecheung): track the memory used by OpenSSL types
622
  SET_NO_MEMORY_INFO()
623
  SET_MEMORY_INFO_NAME(Hash)
624
  SET_SELF_SIZE(Hash)
625
626
  bool HashInit(const char* hash_type);
627
  bool HashUpdate(const char* data, int len);
628
629
 protected:
630
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
631
  static void HashUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
632
  static void HashDigest(const v8::FunctionCallbackInfo<v8::Value>& args);
633
634
817
  Hash(Environment* env, v8::Local<v8::Object> wrap)
635
      : BaseObject(env, wrap),
636
817
        mdctx_(nullptr) {
637
817
    MakeWeak();
638
817
  }
639
640
 private:
641
  EVPMDPointer mdctx_;
642
};
643
644
305
class SignBase : public BaseObject {
645
 public:
646
  typedef enum {
647
    kSignOk,
648
    kSignUnknownDigest,
649
    kSignInit,
650
    kSignNotInitialised,
651
    kSignUpdate,
652
    kSignPrivateKey,
653
    kSignPublicKey
654
  } Error;
655
656
305
  SignBase(Environment* env, v8::Local<v8::Object> wrap)
657
305
      : BaseObject(env, wrap) {
658
305
  }
659
660
  Error Init(const char* sign_type);
661
  Error Update(const char* data, int len);
662
663
  // TODO(joyeecheung): track the memory used by OpenSSL types
664
  SET_NO_MEMORY_INFO()
665
  SET_MEMORY_INFO_NAME(SignBase)
666
  SET_SELF_SIZE(SignBase)
667
668
 protected:
669
  void CheckThrow(Error error);
670
671
  EVPMDPointer mdctx_;
672
};
673
674
166
class Sign : public SignBase {
675
 public:
676
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
677
678
54
  struct SignResult {
679
    Error error;
680
    MallocedBuffer<unsigned char> signature;
681
682
54
    explicit SignResult(
683
        Error err,
684
        MallocedBuffer<unsigned char>&& sig = MallocedBuffer<unsigned char>())
685
54
      : error(err), signature(std::move(sig)) {}
686
  };
687
688
  SignResult SignFinal(
689
      const ManagedEVPPKey& pkey,
690
      int padding,
691
      int saltlen);
692
693
 protected:
694
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
695
  static void SignInit(const v8::FunctionCallbackInfo<v8::Value>& args);
696
  static void SignUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
697
  static void SignFinal(const v8::FunctionCallbackInfo<v8::Value>& args);
698
699
83
  Sign(Environment* env, v8::Local<v8::Object> wrap) : SignBase(env, wrap) {
700
83
    MakeWeak();
701
83
  }
702
};
703
704
444
class Verify : public SignBase {
705
 public:
706
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
707
708
  Error VerifyFinal(const ManagedEVPPKey& key,
709
                    const char* sig,
710
                    int siglen,
711
                    int padding,
712
                    int saltlen,
713
                    bool* verify_result);
714
715
 protected:
716
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
717
  static void VerifyInit(const v8::FunctionCallbackInfo<v8::Value>& args);
718
  static void VerifyUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
719
  static void VerifyFinal(const v8::FunctionCallbackInfo<v8::Value>& args);
720
721
222
  Verify(Environment* env, v8::Local<v8::Object> wrap) : SignBase(env, wrap) {
722
222
    MakeWeak();
723
222
  }
724
};
725
726
class PublicKeyCipher {
727
 public:
728
  typedef int (*EVP_PKEY_cipher_init_t)(EVP_PKEY_CTX* ctx);
729
  typedef int (*EVP_PKEY_cipher_t)(EVP_PKEY_CTX* ctx,
730
                                   unsigned char* out, size_t* outlen,
731
                                   const unsigned char* in, size_t inlen);
732
733
  enum Operation {
734
    kPublic,
735
    kPrivate
736
  };
737
738
  template <Operation operation,
739
            EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
740
            EVP_PKEY_cipher_t EVP_PKEY_cipher>
741
  static bool Cipher(const ManagedEVPPKey& pkey,
742
                     int padding,
743
                     const unsigned char* data,
744
                     int len,
745
                     unsigned char** out,
746
                     size_t* out_len);
747
748
  template <Operation operation,
749
            EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
750
            EVP_PKEY_cipher_t EVP_PKEY_cipher>
751
  static void Cipher(const v8::FunctionCallbackInfo<v8::Value>& args);
752
};
753
754
8128
class DiffieHellman : public BaseObject {
755
 public:
756
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
757
758
  bool Init(int primeLength, int g);
759
  bool Init(const char* p, int p_len, int g);
760
  bool Init(const char* p, int p_len, const char* g, int g_len);
761
762
 protected:
763
  static void DiffieHellmanGroup(
764
      const v8::FunctionCallbackInfo<v8::Value>& args);
765
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
766
  static void GenerateKeys(const v8::FunctionCallbackInfo<v8::Value>& args);
767
  static void GetPrime(const v8::FunctionCallbackInfo<v8::Value>& args);
768
  static void GetGenerator(const v8::FunctionCallbackInfo<v8::Value>& args);
769
  static void GetPublicKey(const v8::FunctionCallbackInfo<v8::Value>& args);
770
  static void GetPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
771
  static void ComputeSecret(const v8::FunctionCallbackInfo<v8::Value>& args);
772
  static void SetPublicKey(const v8::FunctionCallbackInfo<v8::Value>& args);
773
  static void SetPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
774
  static void VerifyErrorGetter(
775
      const v8::FunctionCallbackInfo<v8::Value>& args);
776
777
4064
  DiffieHellman(Environment* env, v8::Local<v8::Object> wrap)
778
      : BaseObject(env, wrap),
779
4064
        verifyError_(0) {
780
4064
    MakeWeak();
781
4064
  }
782
783
  // TODO(joyeecheung): track the memory used by OpenSSL types
784
  SET_NO_MEMORY_INFO()
785
  SET_MEMORY_INFO_NAME(DiffieHellman)
786
  SET_SELF_SIZE(DiffieHellman)
787
788
 private:
789
  static void GetField(const v8::FunctionCallbackInfo<v8::Value>& args,
790
                       const BIGNUM* (*get_field)(const DH*),
791
                       const char* err_if_null);
792
  static void SetKey(const v8::FunctionCallbackInfo<v8::Value>& args,
793
                     int (*set_field)(DH*, BIGNUM*), const char* what);
794
  bool VerifyContext();
795
796
  int verifyError_;
797
  DHPointer dh_;
798
};
799
800
class ECDH : public BaseObject {
801
 public:
802
30
  ~ECDH() override {
803
10
    group_ = nullptr;
804
20
  }
805
806
  static void Initialize(Environment* env, v8::Local<v8::Object> target);
807
  static ECPointPointer BufferToPoint(Environment* env,
808
                                      const EC_GROUP* group,
809
                                      char* data,
810
                                      size_t len);
811
812
  // TODO(joyeecheung): track the memory used by OpenSSL types
813
  SET_NO_MEMORY_INFO()
814
  SET_MEMORY_INFO_NAME(ECDH)
815
  SET_SELF_SIZE(ECDH)
816
817
 protected:
818
10
  ECDH(Environment* env, v8::Local<v8::Object> wrap, ECKeyPointer&& key)
819
      : BaseObject(env, wrap),
820
10
        key_(std::move(key)),
821
20
        group_(EC_KEY_get0_group(key_.get())) {
822
10
    MakeWeak();
823
10
    CHECK_NOT_NULL(group_);
824
10
  }
825
826
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
827
  static void GenerateKeys(const v8::FunctionCallbackInfo<v8::Value>& args);
828
  static void ComputeSecret(const v8::FunctionCallbackInfo<v8::Value>& args);
829
  static void GetPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
830
  static void SetPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
831
  static void GetPublicKey(const v8::FunctionCallbackInfo<v8::Value>& args);
832
  static void SetPublicKey(const v8::FunctionCallbackInfo<v8::Value>& args);
833
834
  bool IsKeyPairValid();
835
  bool IsKeyValidForCurve(const BignumPointer& private_key);
836
837
  ECKeyPointer key_;
838
  const EC_GROUP* group_;
839
};
840
841
bool EntropySource(unsigned char* buffer, size_t length);
842
#ifndef OPENSSL_NO_ENGINE
843
void SetEngine(const v8::FunctionCallbackInfo<v8::Value>& args);
844
#endif  // !OPENSSL_NO_ENGINE
845
void InitCrypto(v8::Local<v8::Object> target);
846
847
}  // namespace crypto
848
}  // namespace node
849
850
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
851
852
#endif  // SRC_NODE_CRYPTO_H_