GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_util.h Lines: 225 231 97.4 %
Date: 2021-11-04 03:14:03 Branches: 74 111 66.7 %

Line Branch Exec Source
1
#ifndef SRC_CRYPTO_CRYPTO_UTIL_H_
2
#define SRC_CRYPTO_CRYPTO_UTIL_H_
3
4
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5
6
#include "env.h"
7
#include "async_wrap.h"
8
#include "allocated_buffer.h"
9
#include "node_errors.h"
10
#include "node_external_reference.h"
11
#include "node_internals.h"
12
#include "util.h"
13
#include "v8.h"
14
#include "string_bytes.h"
15
16
#include <openssl/err.h>
17
#include <openssl/evp.h>
18
#include <openssl/ec.h>
19
#include <openssl/kdf.h>
20
#include <openssl/rsa.h>
21
#include <openssl/dsa.h>
22
#include <openssl/ssl.h>
23
#ifndef OPENSSL_NO_ENGINE
24
#  include <openssl/engine.h>
25
#endif  // !OPENSSL_NO_ENGINE
26
// The FIPS-related functions are only available
27
// when the OpenSSL itself was compiled with FIPS support.
28
#if defined(OPENSSL_FIPS) && OPENSSL_VERSION_MAJOR < 3
29
#  include <openssl/fips.h>
30
#endif  // OPENSSL_FIPS
31
32
#include <algorithm>
33
#include <memory>
34
#include <string>
35
#include <vector>
36
#include <climits>
37
#include <cstdio>
38
39
namespace node {
40
namespace crypto {
41
// Currently known sizes of commonly used OpenSSL struct sizes.
42
// OpenSSL considers it's various structs to be opaque and the
43
// sizes may change from one version of OpenSSL to another, so
44
// these values should not be trusted to remain static. These
45
// are provided to allow for some close to reasonable memory
46
// tracking.
47
constexpr size_t kSizeOf_DH = 144;
48
constexpr size_t kSizeOf_EC_KEY = 80;
49
constexpr size_t kSizeOf_EVP_CIPHER_CTX = 168;
50
constexpr size_t kSizeOf_EVP_MD_CTX = 48;
51
constexpr size_t kSizeOf_EVP_PKEY = 72;
52
constexpr size_t kSizeOf_EVP_PKEY_CTX = 80;
53
constexpr size_t kSizeOf_HMAC_CTX = 32;
54
55
// Define smart pointers for the most commonly used OpenSSL types:
56
using X509Pointer = DeleteFnPtr<X509, X509_free>;
57
using BIOPointer = DeleteFnPtr<BIO, BIO_free_all>;
58
using SSLCtxPointer = DeleteFnPtr<SSL_CTX, SSL_CTX_free>;
59
using SSLSessionPointer = DeleteFnPtr<SSL_SESSION, SSL_SESSION_free>;
60
using SSLPointer = DeleteFnPtr<SSL, SSL_free>;
61
using PKCS8Pointer = DeleteFnPtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_free>;
62
using EVPKeyPointer = DeleteFnPtr<EVP_PKEY, EVP_PKEY_free>;
63
using EVPKeyCtxPointer = DeleteFnPtr<EVP_PKEY_CTX, EVP_PKEY_CTX_free>;
64
using EVPMDPointer = DeleteFnPtr<EVP_MD_CTX, EVP_MD_CTX_free>;
65
using RSAPointer = DeleteFnPtr<RSA, RSA_free>;
66
using ECPointer = DeleteFnPtr<EC_KEY, EC_KEY_free>;
67
using BignumPointer = DeleteFnPtr<BIGNUM, BN_free>;
68
using BignumCtxPointer = DeleteFnPtr<BN_CTX, BN_CTX_free>;
69
using NetscapeSPKIPointer = DeleteFnPtr<NETSCAPE_SPKI, NETSCAPE_SPKI_free>;
70
using ECGroupPointer = DeleteFnPtr<EC_GROUP, EC_GROUP_free>;
71
using ECPointPointer = DeleteFnPtr<EC_POINT, EC_POINT_free>;
72
using ECKeyPointer = DeleteFnPtr<EC_KEY, EC_KEY_free>;
73
using DHPointer = DeleteFnPtr<DH, DH_free>;
74
using ECDSASigPointer = DeleteFnPtr<ECDSA_SIG, ECDSA_SIG_free>;
75
using HMACCtxPointer = DeleteFnPtr<HMAC_CTX, HMAC_CTX_free>;
76
using CipherCtxPointer = DeleteFnPtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free>;
77
using RsaPointer = DeleteFnPtr<RSA, RSA_free>;
78
using DsaPointer = DeleteFnPtr<DSA, DSA_free>;
79
using DsaSigPointer = DeleteFnPtr<DSA_SIG, DSA_SIG_free>;
80
81
// Our custom implementation of the certificate verify callback
82
// used when establishing a TLS handshake. Because we cannot perform
83
// I/O quickly enough with X509_STORE_CTX_ APIs in this callback,
84
// we ignore preverify_ok errors here and let the handshake continue.
85
// In other words, this VerifyCallback is a non-op. It is imperative
86
// that the user user Connection::VerifyError after the `secure`
87
// callback has been made.
88
extern int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx);
89
90
bool ProcessFipsOptions();
91
92
bool InitCryptoOnce(v8::Isolate* isolate);
93
void InitCryptoOnce();
94
95
void InitCrypto(v8::Local<v8::Object> target);
96
97
extern void UseExtraCaCerts(const std::string& file);
98
99
// Forcibly clear OpenSSL's error stack on return. This stops stale errors
100
// from popping up later in the lifecycle of crypto operations where they
101
// would cause spurious failures. It's a rather blunt method, though.
102
// ERR_clear_error() isn't necessarily cheap either.
103
struct ClearErrorOnReturn {
104
11152
  ~ClearErrorOnReturn() { ERR_clear_error(); }
105
};
106
107
// Pop errors from OpenSSL's error stack that were added
108
// between when this was constructed and destructed.
109
struct MarkPopErrorOnReturn {
110
21762
  MarkPopErrorOnReturn() { ERR_set_mark(); }
111
21761
  ~MarkPopErrorOnReturn() { ERR_pop_to_mark(); }
112
};
113
114
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
115
// The entropy pool starts out empty and needs to fill up before the PRNG
116
// can be used securely.  Once the pool is filled, it never dries up again;
117
// its contents is stirred and reused when necessary.
118
//
119
// OpenSSL normally fills the pool automatically but not when someone starts
120
// generating random numbers before the pool is full: in that case OpenSSL
121
// keeps lowering the entropy estimate to thwart attackers trying to guess
122
// the initial state of the PRNG.
123
//
124
// When that happens, we will have to wait until enough entropy is available.
125
// That should normally never take longer than a few milliseconds.
126
//
127
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
128
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
129
// block under normal circumstances.
130
//
131
// The only time when /dev/urandom may conceivably block is right after boot,
132
// when the whole system is still low on entropy.  That's not something we can
133
// do anything about.
134
void CheckEntropy();
135
136
// Generate length bytes of random data. If this returns false, the data
137
// may not be truly random but it's still generally good enough.
138
bool EntropySource(unsigned char* buffer, size_t length);
139
140
int PasswordCallback(char* buf, int size, int rwflag, void* u);
141
142
int NoPasswordCallback(char* buf, int size, int rwflag, void* u);
143
144
// Decode is used by the various stream-based crypto utilities to decode
145
// string input.
146
template <typename T>
147
3326
void Decode(const v8::FunctionCallbackInfo<v8::Value>& args,
148
            void (*callback)(T*, const v8::FunctionCallbackInfo<v8::Value>&,
149
                             const char*, size_t)) {
150
  T* ctx;
151
3326
  ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder());
152
153
6652
  if (args[0]->IsString()) {
154
1757
    StringBytes::InlineDecoder decoder;
155
1757
    Environment* env = Environment::GetCurrent(args);
156
1757
    enum encoding enc = ParseEncoding(env->isolate(), args[1], UTF8);
157
5271
    if (decoder.Decode(env, args[0].As<v8::String>(), enc).IsNothing())
158
      return;
159
1757
    callback(ctx, args, decoder.out(), decoder.size());
160
  } else {
161
1569
    ArrayBufferViewContents<char> buf(args[0]);
162
1569
    callback(ctx, args, buf.data(), buf.length());
163
  }
164
}
165
166
#define NODE_CRYPTO_ERROR_CODES_MAP(V)                                        \
167
    V(CIPHER_JOB_FAILED, "Cipher job failed")                                 \
168
    V(DERIVING_BITS_FAILED, "Deriving bits failed")                           \
169
    V(ENGINE_NOT_FOUND, "Engine \"%s\" was not found")                        \
170
    V(INVALID_KEY_TYPE, "Invalid key type")                                   \
171
    V(KEY_GENERATION_JOB_FAILED, "Key generation job failed")                 \
172
    V(OK, "Ok")                                                               \
173
174
enum class NodeCryptoError {
175
#define V(CODE, DESCRIPTION) CODE,
176
  NODE_CRYPTO_ERROR_CODES_MAP(V)
177
#undef V
178
};
179
180
// Utility struct used to harvest error information from openssl's error stack
181
struct CryptoErrorStore final : public MemoryRetainer {
182
 public:
183
  void Capture();
184
185
  bool Empty() const;
186
187
  template <typename... Args>
188
  void Insert(const NodeCryptoError error, Args&&... args);
189
190
  v8::MaybeLocal<v8::Value> ToException(
191
      Environment* env,
192
      v8::Local<v8::String> exception_string = v8::Local<v8::String>()) const;
193
194
3
  SET_NO_MEMORY_INFO()
195
3
  SET_MEMORY_INFO_NAME(CryptoErrorStore)
196
3
  SET_SELF_SIZE(CryptoErrorStore)
197
198
 private:
199
  std::vector<std::string> errors_;
200
};
201
202
template <typename... Args>
203
13
void CryptoErrorStore::Insert(const NodeCryptoError error, Args&&... args) {
204
13
  const char* error_string = nullptr;
205

13
  switch (error) {
206
#define V(CODE, DESCRIPTION) \
207
    case NodeCryptoError::CODE: error_string = DESCRIPTION; break;
208
13
    NODE_CRYPTO_ERROR_CODES_MAP(V)
209
#undef V
210
  }
211
13
  errors_.emplace_back(SPrintF(error_string,
212
                               std::forward<Args>(args)...));
213
13
}
214
215
template <typename T>
216
15646
T* MallocOpenSSL(size_t count) {
217
15646
  void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
218

15646
  CHECK_IMPLIES(mem == nullptr, count == 0);
219
15646
  return static_cast<T*>(mem);
220
}
221
222
template <typename T>
223
1419
T* ReallocOpenSSL(T* buf, size_t count) {
224
1419
  void* mem = OPENSSL_realloc(buf, MultiplyWithOverflowCheck(count, sizeof(T)));
225

1419
  CHECK_IMPLIES(mem == nullptr, count == 0);
226
1419
  return static_cast<T*>(mem);
227
}
228
229
// A helper class representing a read-only byte array. When deallocated, its
230
// contents are zeroed.
231
class ByteSource {
232
 public:
233
21300
  ByteSource() = default;
234
  ByteSource(ByteSource&& other) noexcept;
235
  ~ByteSource();
236
237
  ByteSource& operator=(ByteSource&& other) noexcept;
238
239
  const char* get() const;
240
241
  template <typename T>
242
6647
  const T* data() const { return reinterpret_cast<const T*>(get()); }
243
244
  size_t size() const;
245
246
4382
  operator bool() const { return data_ != nullptr; }
247
248
2841
  BignumPointer ToBN() const {
249
    return BignumPointer(BN_bin2bn(
250
2841
        reinterpret_cast<const unsigned char*>(get()),
251
2841
        size(),
252
2841
        nullptr));
253
  }
254
255
  // Creates a v8::BackingStore that takes over responsibility for
256
  // any allocated data. The ByteSource will be reset with size = 0
257
  // after being called.
258
  std::unique_ptr<v8::BackingStore> ReleaseToBackingStore();
259
260
  v8::Local<v8::ArrayBuffer> ToArrayBuffer(Environment* env);
261
262
  void reset();
263
264
  // Allows an Allocated ByteSource to be truncated.
265
1419
  void Resize(size_t newsize) {
266
1419
    CHECK_LE(newsize, size_);
267
1419
    CHECK_NOT_NULL(allocated_data_);
268
1419
    char* new_data_ = ReallocOpenSSL<char>(allocated_data_, newsize);
269
1419
    data_ = allocated_data_ = new_data_;
270
1419
    size_ = newsize;
271
1419
  }
272
273
  static ByteSource Allocated(char* data, size_t size);
274
  static ByteSource Foreign(const char* data, size_t size);
275
276
  static ByteSource FromEncodedString(Environment* env,
277
                                      v8::Local<v8::String> value,
278
                                      enum encoding enc = BASE64);
279
280
  static ByteSource FromStringOrBuffer(Environment* env,
281
                                       v8::Local<v8::Value> value);
282
283
  static ByteSource FromString(Environment* env,
284
                               v8::Local<v8::String> str,
285
                               bool ntc = false);
286
287
  static ByteSource FromBuffer(v8::Local<v8::Value> buffer,
288
                               bool ntc = false);
289
290
  static ByteSource FromBIO(const BIOPointer& bio);
291
292
  static ByteSource NullTerminatedCopy(Environment* env,
293
                                       v8::Local<v8::Value> value);
294
295
  static ByteSource FromSymmetricKeyObjectHandle(v8::Local<v8::Value> handle);
296
297
  ByteSource(const ByteSource&) = delete;
298
  ByteSource& operator=(const ByteSource&) = delete;
299
300
  static ByteSource FromSecretKeyBytes(
301
      Environment* env, v8::Local<v8::Value> value);
302
303
 private:
304
  const char* data_ = nullptr;
305
  char* allocated_data_ = nullptr;
306
  size_t size_ = 0;
307
308
  ByteSource(const char* data, char* allocated_data, size_t size);
309
};
310
311
enum CryptoJobMode {
312
  kCryptoJobAsync,
313
  kCryptoJobSync
314
};
315
316
CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args);
317
318
template <typename CryptoJobTraits>
319
class CryptoJob : public AsyncWrap, public ThreadPoolWork {
320
 public:
321
  using AdditionalParams = typename CryptoJobTraits::AdditionalParameters;
322
323
7153
  explicit CryptoJob(
324
      Environment* env,
325
      v8::Local<v8::Object> object,
326
      AsyncWrap::ProviderType type,
327
      CryptoJobMode mode,
328
      AdditionalParams&& params)
329
      : AsyncWrap(env, object, type),
330
        ThreadPoolWork(env),
331
        mode_(mode),
332
7153
        params_(std::move(params)) {
333
    // If the CryptoJob is async, then the instance will be
334
    // cleaned up when AfterThreadPoolWork is called.
335
7153
    if (mode == kCryptoJobSync) MakeWeak();
336
7153
  }
337
338
  bool IsNotIndicativeOfMemoryLeakAtExit() const override {
339
    // CryptoJobs run a work in the libuv thread pool and may still
340
    // exist when the event loop empties and starts to exit.
341
    return true;
342
  }
343
344
5859
  void AfterThreadPoolWork(int status) override {
345
5859
    Environment* env = AsyncWrap::env();
346
5859
    CHECK_EQ(mode_, kCryptoJobAsync);
347

5859
    CHECK(status == 0 || status == UV_ECANCELED);
348
5859
    std::unique_ptr<CryptoJob> ptr(this);
349
    // If the job was canceled do not execute the callback.
350
    // TODO(@jasnell): We should likely revisit skipping the
351
    // callback on cancel as that could leave the JS in a pending
352
    // state (e.g. unresolved promises...)
353
5859
    if (status == UV_ECANCELED) return;
354
5859
    v8::HandleScope handle_scope(env->isolate());
355
11718
    v8::Context::Scope context_scope(env->context());
356
357
    // TODO(tniessen): Remove the exception handling logic here as soon as we
358
    // can verify that no code path in ToResult will ever throw an exception.
359
    v8::Local<v8::Value> exception;
360
17577
    v8::Local<v8::Value> args[2];
361
    {
362
5859
      node::errors::TryCatchScope try_catch(env);
363
5859
      v8::Maybe<bool> ret = ptr->ToResult(&args[0], &args[1]);
364
5859
      if (!ret.IsJust()) {
365
4
        CHECK(try_catch.HasCaught());
366
4
        exception = try_catch.Exception();
367
5855
      } else if (!ret.FromJust()) {
368
        return;
369
      }
370
    }
371
372
5859
    if (exception.IsEmpty()) {
373
5855
      ptr->MakeCallback(env->ondone_string(), arraysize(args), args);
374
    } else {
375
4
      ptr->MakeCallback(env->ondone_string(), 1, &exception);
376
    }
377
  }
378
379
  virtual v8::Maybe<bool> ToResult(
380
      v8::Local<v8::Value>* err,
381
      v8::Local<v8::Value>* result) = 0;
382
383
7139
  CryptoJobMode mode() const { return mode_; }
384
385
7213
  CryptoErrorStore* errors() { return &errors_; }
386
387
11492
  AdditionalParams* params() { return &params_; }
388
389
6
  std::string MemoryInfoName() const override {
390
6
    return CryptoJobTraits::JobName;
391
  }
392
393
6
  void MemoryInfo(MemoryTracker* tracker) const override {
394
6
    tracker->TrackField("params", params_);
395
6
    tracker->TrackField("errors", errors_);
396
  }
397
398
7139
  static void Run(const v8::FunctionCallbackInfo<v8::Value>& args) {
399
7139
    Environment* env = Environment::GetCurrent(args);
400
401
    CryptoJob<CryptoJobTraits>* job;
402
13000
    ASSIGN_OR_RETURN_UNWRAP(&job, args.Holder());
403
7139
    if (job->mode() == kCryptoJobAsync)
404
5861
      return job->ScheduleWork();
405
406
3834
    v8::Local<v8::Value> ret[2];
407
1278
    env->PrintSyncTrace();
408
1278
    job->DoThreadPoolWork();
409
1278
    v8::Maybe<bool> result = job->ToResult(&ret[0], &ret[1]);
410

2550
    if (result.IsJust() && result.FromJust()) {
411
2544
      args.GetReturnValue().Set(
412
          v8::Array::New(env->isolate(), ret, arraysize(ret)));
413
    }
414
  }
415
416
180936
  static void Initialize(
417
      v8::FunctionCallback new_fn,
418
      Environment* env,
419
      v8::Local<v8::Object> target) {
420
180936
    v8::Local<v8::FunctionTemplate> job = env->NewFunctionTemplate(new_fn);
421
180936
    job->Inherit(AsyncWrap::GetConstructorTemplate(env));
422
361872
    job->InstanceTemplate()->SetInternalFieldCount(
423
        AsyncWrap::kInternalFieldCount);
424
180936
    env->SetProtoMethod(job, "run", Run);
425
180936
    env->SetConstructorFunction(target, CryptoJobTraits::JobName, job);
426
180936
  }
427
428
204120
  static void RegisterExternalReferences(v8::FunctionCallback new_fn,
429
                                         ExternalReferenceRegistry* registry) {
430
204120
    registry->Register(new_fn);
431
204120
    registry->Register(Run);
432
204120
  }
433
434
 private:
435
  const CryptoJobMode mode_;
436
  CryptoErrorStore errors_;
437
  AdditionalParams params_;
438
};
439
440
template <typename DeriveBitsTraits>
441
class DeriveBitsJob final : public CryptoJob<DeriveBitsTraits> {
442
 public:
443
  using AdditionalParams = typename DeriveBitsTraits::AdditionalParameters;
444
445
3396
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
446
3396
    Environment* env = Environment::GetCurrent(args);
447
448
3396
    CryptoJobMode mode = GetCryptoJobMode(args[0]);
449
450
3396
    AdditionalParams params;
451
6792
    if (DeriveBitsTraits::AdditionalConfig(mode, args, 1, &params)
452
            .IsNothing()) {
453
      // The DeriveBitsTraits::AdditionalConfig is responsible for
454
      // calling an appropriate THROW_CRYPTO_* variant reporting
455
      // whatever error caused initialization to fail.
456
71
      return;
457
    }
458
459
3325
    new DeriveBitsJob(env, args.This(), mode, std::move(params));
460
  }
461
462
73236
  static void Initialize(
463
      Environment* env,
464
      v8::Local<v8::Object> target) {
465
73236
    CryptoJob<DeriveBitsTraits>::Initialize(New, env, target);
466
73236
  }
467
468
82620
  static void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
469
82620
    CryptoJob<DeriveBitsTraits>::RegisterExternalReferences(New, registry);
470
82620
  }
471
472
3325
  DeriveBitsJob(
473
      Environment* env,
474
      v8::Local<v8::Object> object,
475
      CryptoJobMode mode,
476
      AdditionalParams&& params)
477
      : CryptoJob<DeriveBitsTraits>(
478
            env,
479
            object,
480
            DeriveBitsTraits::Provider,
481
            mode,
482
3325
            std::move(params)) {}
483
484
3325
  void DoThreadPoolWork() override {
485
3325
    if (!DeriveBitsTraits::DeriveBits(
486
            AsyncWrap::env(),
487
3325
            *CryptoJob<DeriveBitsTraits>::params(), &out_)) {
488
13
      CryptoErrorStore* errors = CryptoJob<DeriveBitsTraits>::errors();
489
13
      errors->Capture();
490
13
      if (errors->Empty())
491
13
        errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
492
13
      return;
493
    }
494
3312
    success_ = true;
495
  }
496
497
3325
  v8::Maybe<bool> ToResult(
498
      v8::Local<v8::Value>* err,
499
      v8::Local<v8::Value>* result) override {
500
3325
    Environment* env = AsyncWrap::env();
501
3325
    CryptoErrorStore* errors = CryptoJob<DeriveBitsTraits>::errors();
502
3325
    if (success_) {
503
3312
      CHECK(errors->Empty());
504
3312
      *err = v8::Undefined(env->isolate());
505
3312
      return DeriveBitsTraits::EncodeOutput(
506
          env,
507
3312
          *CryptoJob<DeriveBitsTraits>::params(),
508
          &out_,
509
3312
          result);
510
    }
511
512
13
    if (errors->Empty())
513
      errors->Capture();
514
13
    CHECK(!errors->Empty());
515
26
    *result = v8::Undefined(env->isolate());
516
26
    return v8::Just(errors->ToException(env).ToLocal(err));
517
  }
518
519
6
  SET_SELF_SIZE(DeriveBitsJob)
520
3
  void MemoryInfo(MemoryTracker* tracker) const override {
521
6
    tracker->TrackFieldWithSize("out", out_.size());
522
6
    CryptoJob<DeriveBitsTraits>::MemoryInfo(tracker);
523
  }
524
525
 private:
526
  ByteSource out_;
527
  bool success_ = false;
528
};
529
530
void ThrowCryptoError(Environment* env,
531
                      unsigned long err,  // NOLINT(runtime/int)
532
                      const char* message = nullptr);
533
534
#ifndef OPENSSL_NO_ENGINE
535
struct EnginePointer {
536
  ENGINE* engine = nullptr;
537
  bool finish_on_exit = false;
538
539
2358
  inline EnginePointer() = default;
540
541
16
  inline explicit EnginePointer(ENGINE* engine_, bool finish_on_exit_ = false)
542
16
    : engine(engine_),
543
16
      finish_on_exit(finish_on_exit_) {}
544
545
2
  inline EnginePointer(EnginePointer&& other) noexcept
546
2
      : engine(other.engine),
547
2
        finish_on_exit(other.finish_on_exit) {
548
2
    other.release();
549
2
  }
550
551
2367
  inline ~EnginePointer() { reset(); }
552
553
2
  inline EnginePointer& operator=(EnginePointer&& other) noexcept {
554
2
    if (this == &other) return *this;
555
2
    this->~EnginePointer();
556
2
    return *new (this) EnginePointer(std::move(other));
557
  }
558
559
44
  inline operator bool() const { return engine != nullptr; }
560
561
16
  inline ENGINE* get() { return engine; }
562
563
2369
  inline void reset(ENGINE* engine_ = nullptr, bool finish_on_exit_ = false) {
564
2369
    if (engine != nullptr) {
565
14
      if (finish_on_exit) {
566
        // This also does the equivalent of ENGINE_free.
567
        CHECK_EQ(ENGINE_finish(engine), 1);
568
      } else {
569
14
        CHECK_EQ(ENGINE_free(engine), 1);
570
      }
571
    }
572
2369
    engine = engine_;
573
2369
    finish_on_exit = finish_on_exit_;
574
2369
  }
575
576
2
  inline ENGINE* release() {
577
2
    ENGINE* ret = engine;
578
2
    engine = nullptr;
579
2
    finish_on_exit = false;
580
2
    return ret;
581
  }
582
};
583
584
EnginePointer LoadEngineById(const char* id, CryptoErrorStore* errors);
585
586
bool SetEngine(
587
    const char* id,
588
    uint32_t flags,
589
    CryptoErrorStore* errors = nullptr);
590
591
void SetEngine(const v8::FunctionCallbackInfo<v8::Value>& args);
592
#endif  // !OPENSSL_NO_ENGINE
593
594
void GetFipsCrypto(const v8::FunctionCallbackInfo<v8::Value>& args);
595
596
void SetFipsCrypto(const v8::FunctionCallbackInfo<v8::Value>& args);
597
598
void TestFipsCrypto(const v8::FunctionCallbackInfo<v8::Value>& args);
599
600
class CipherPushContext {
601
 public:
602
7
  inline explicit CipherPushContext(Environment* env) : env_(env) {}
603
604
761
  inline void push_back(const char* str) {
605
761
    list_.emplace_back(OneByteString(env_->isolate(), str));
606
761
  }
607
608
7
  inline v8::Local<v8::Array> ToJSArray() {
609
7
    return v8::Array::New(env_->isolate(), list_.data(), list_.size());
610
  }
611
612
 private:
613
  std::vector<v8::Local<v8::Value>> list_;
614
  Environment* env_;
615
};
616
617
template <class TypeName>
618
761
void array_push_back(const TypeName* md,
619
                     const char* from,
620
                     const char* to,
621
                     void* arg) {
622
761
  static_cast<CipherPushContext*>(arg)->push_back(from);
623
761
}
624
625
128959
inline bool IsAnyByteSource(v8::Local<v8::Value> arg) {
626
135512
  return arg->IsArrayBufferView() ||
627

142065
         arg->IsArrayBuffer() ||
628
133390
         arg->IsSharedArrayBuffer();
629
}
630
631
template <typename T>
632
class ArrayBufferOrViewContents {
633
 public:
634
  ArrayBufferOrViewContents() = default;
635
636
217410
  inline explicit ArrayBufferOrViewContents(v8::Local<v8::Value> buf) {
637
217410
    CHECK(IsAnyByteSource(buf));
638
217410
    if (buf->IsArrayBufferView()) {
639
215556
      auto view = buf.As<v8::ArrayBufferView>();
640
215556
      offset_ = view->ByteOffset();
641
215556
      length_ = view->ByteLength();
642
431112
      store_ = view->Buffer()->GetBackingStore();
643
1854
    } else if (buf->IsArrayBuffer()) {
644
1838
      auto ab = buf.As<v8::ArrayBuffer>();
645
1838
      offset_ = 0;
646
1838
      length_ = ab->ByteLength();
647
1838
      store_ = ab->GetBackingStore();
648
    } else {
649
16
      auto sab = buf.As<v8::SharedArrayBuffer>();
650
16
      offset_ = 0;
651
16
      length_ = sab->ByteLength();
652
16
      store_ = sab->GetBackingStore();
653
    }
654
217410
  }
655
656
13037
  inline const T* data() const {
657
    // Ideally, these would return nullptr if IsEmpty() or length_ is zero,
658
    // but some of the openssl API react badly if given a nullptr even when
659
    // length is zero, so we have to return something.
660
13037
    if (size() == 0)
661
99
      return &buf;
662
12938
    return reinterpret_cast<T*>(store_->Data()) + offset_;
663
  }
664
665
102954
  inline T* data() {
666
    // Ideally, these would return nullptr if IsEmpty() or length_ is zero,
667
    // but some of the openssl API react badly if given a nullptr even when
668
    // length is zero, so we have to return something.
669
102954
    if (size() == 0)
670
3
      return &buf;
671
102951
    return reinterpret_cast<T*>(store_->Data()) + offset_;
672
  }
673
674
669366
  inline size_t size() const { return length_; }
675
676
  // In most cases, input buffer sizes passed in to openssl need to
677
  // be limited to <= INT_MAX. This utility method helps us check.
678
213203
  inline bool CheckSizeInt32() { return size() <= INT_MAX; }
679
680
4575
  inline ByteSource ToByteSource() const {
681
4575
    return ByteSource::Foreign(data(), size());
682
  }
683
684
6943
  inline ByteSource ToCopy() const {
685
6943
    if (size() == 0) return ByteSource();
686
6342
    char* buf = MallocOpenSSL<char>(size());
687
6342
    CHECK_NOT_NULL(buf);
688
6342
    memcpy(buf, data(), size());
689
6342
    return ByteSource::Allocated(buf, size());
690
  }
691
692
88
  inline ByteSource ToNullTerminatedCopy() const {
693
88
    if (size() == 0) return ByteSource();
694
88
    char* buf = MallocOpenSSL<char>(size() + 1);
695
88
    CHECK_NOT_NULL(buf);
696
88
    buf[size()] = 0;
697
88
    memcpy(buf, data(), size());
698
88
    return ByteSource::Allocated(buf, size());
699
  }
700
701
  template <typename M>
702
85
  void CopyTo(M* dest, size_t len) const {
703
    static_assert(sizeof(M) == 1, "sizeof(M) must equal 1");
704
85
    len = std::min(len, size());
705

85
    if (len > 0 && data() != nullptr)
706
85
      memcpy(dest, data(), len);
707
85
  }
708
709
 private:
710
  T buf = 0;
711
  size_t offset_ = 0;
712
  size_t length_ = 0;
713
  std::shared_ptr<v8::BackingStore> store_;
714
};
715
716
template <typename T>
717
std::vector<T> CopyBuffer(const ArrayBufferOrViewContents<T>& buf) {
718
  std::vector<T> vec;
719
  vec->resize(buf.size());
720
  if (vec->size() > 0 && buf.data() != nullptr)
721
    memcpy(vec->data(), buf.data(), vec->size());
722
  return vec;
723
}
724
725
template <typename T>
726
std::vector<T> CopyBuffer(v8::Local<v8::Value> buf) {
727
  return CopyBuffer(ArrayBufferOrViewContents<T>(buf));
728
}
729
730
v8::MaybeLocal<v8::Value> EncodeBignum(
731
    Environment* env,
732
    const BIGNUM* bn,
733
    int size,
734
    v8::Local<v8::Value>* error);
735
736
v8::Maybe<bool> SetEncodedValue(
737
    Environment* env,
738
    v8::Local<v8::Object> target,
739
    v8::Local<v8::String> name,
740
    const BIGNUM* bn,
741
    int size = 0);
742
743
namespace Util {
744
void Initialize(Environment* env, v8::Local<v8::Object> target);
745
void RegisterExternalReferences(ExternalReferenceRegistry* registry);
746
}  // namespace Util
747
748
}  // namespace crypto
749
}  // namespace node
750
751
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
752
#endif  // SRC_CRYPTO_CRYPTO_UTIL_H_