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: 102 123 82.9 %
Date: 2020-02-19 22:14:06 Branches: 6 8 75.0 %

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