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