GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_util.h Lines: 241 250 96.4 %
Date: 2022-06-16 04:15:44 Branches: 80 117 68.4 %

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 "async_wrap.h"
7
#include "env.h"
8
#include "node_errors.h"
9
#include "node_external_reference.h"
10
#include "node_internals.h"
11
#include "string_bytes.h"
12
#include "util.h"
13
#include "v8.h"
14
15
#include <openssl/err.h>
16
#include <openssl/evp.h>
17
#include <openssl/ec.h>
18
#include <openssl/kdf.h>
19
#include <openssl/rsa.h>
20
#include <openssl/dsa.h>
21
#include <openssl/ssl.h>
22
#ifndef OPENSSL_NO_ENGINE
23
#  include <openssl/engine.h>
24
#endif  // !OPENSSL_NO_ENGINE
25
// The FIPS-related functions are only available
26
// when the OpenSSL itself was compiled with FIPS support.
27
#if defined(OPENSSL_FIPS) && OPENSSL_VERSION_MAJOR < 3
28
#  include <openssl/fips.h>
29
#endif  // OPENSSL_FIPS
30
31
#include <algorithm>
32
#include <climits>
33
#include <cstdio>
34
#include <memory>
35
#include <optional>
36
#include <string>
37
#include <vector>
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
11611
  ~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
23385
  MarkPopErrorOnReturn() { ERR_set_mark(); }
111
23384
  ~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
3698
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
3698
  ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder());
152
153
7396
  if (args[0]->IsString()) {
154
1840
    StringBytes::InlineDecoder decoder;
155
1840
    Environment* env = Environment::GetCurrent(args);
156
1840
    enum encoding enc = ParseEncoding(env->isolate(), args[1], UTF8);
157
5520
    if (decoder.Decode(env, args[0].As<v8::String>(), enc).IsNothing())
158
      return;
159
1840
    callback(ctx, args, decoder.out(), decoder.size());
160
  } else {
161
1858
    ArrayBufferViewContents<char> buf(args[0]);
162
1858
    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
14
void CryptoErrorStore::Insert(const NodeCryptoError error, Args&&... args) {
204
14
  const char* error_string = nullptr;
205

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

15285
  CHECK_IMPLIES(mem == nullptr, count == 0);
219
15285
  return static_cast<T*>(mem);
220
}
221
222
// A helper class representing a read-only byte array. When deallocated, its
223
// contents are zeroed.
224
class ByteSource {
225
 public:
226
  class Builder {
227
   public:
228
    // Allocates memory using OpenSSL's memory allocator.
229
8724
    explicit Builder(size_t size)
230
8724
        : data_(MallocOpenSSL<char>(size)), size_(size) {}
231
232
    Builder(Builder&& other) = delete;
233
    Builder& operator=(Builder&& other) = delete;
234
    Builder(const Builder&) = delete;
235
    Builder& operator=(const Builder&) = delete;
236
237
8724
    ~Builder() { OPENSSL_clear_free(data_, size_); }
238
239
    // Returns the underlying non-const pointer.
240
    template <typename T>
241
16232
    T* data() {
242
16232
      return reinterpret_cast<T*>(data_);
243
    }
244
245
    // Returns the (allocated) size in bytes.
246
13
    size_t size() const { return size_; }
247
248
    // Finalizes the Builder and returns a read-only view that is optionally
249
    // truncated.
250
8648
    ByteSource release(std::optional<size_t> resize = std::nullopt) && {
251
8648
      if (resize) {
252
4577
        CHECK_LE(*resize, size_);
253
4577
        if (*resize == 0) {
254
1
          OPENSSL_clear_free(data_, size_);
255
1
          data_ = nullptr;
256
        }
257
4577
        size_ = *resize;
258
      }
259
8648
      ByteSource out = ByteSource::Allocated(data_, size_);
260
8648
      data_ = nullptr;
261
8648
      size_ = 0;
262
8648
      return out;
263
    }
264
265
   private:
266
    void* data_;
267
    size_t size_;
268
  };
269
270
21706
  ByteSource() = default;
271
  ByteSource(ByteSource&& other) noexcept;
272
  ~ByteSource();
273
274
  ByteSource& operator=(ByteSource&& other) noexcept;
275
276
  ByteSource(const ByteSource&) = delete;
277
  ByteSource& operator=(const ByteSource&) = delete;
278
279
  template <typename T = void>
280
40164
  const T* data() const {
281
40164
    return reinterpret_cast<const T*>(data_);
282
  }
283
284
25949
  size_t size() const { return size_; }
285
286
4520
  operator bool() const { return data_ != nullptr; }
287
288
2841
  BignumPointer ToBN() const {
289
2841
    return BignumPointer(BN_bin2bn(data<unsigned char>(), size(), nullptr));
290
  }
291
292
  // Creates a v8::BackingStore that takes over responsibility for
293
  // any allocated data. The ByteSource will be reset with size = 0
294
  // after being called.
295
  std::unique_ptr<v8::BackingStore> ReleaseToBackingStore();
296
297
  v8::Local<v8::ArrayBuffer> ToArrayBuffer(Environment* env);
298
299
  v8::MaybeLocal<v8::Uint8Array> ToBuffer(Environment* env);
300
301
  static ByteSource Allocated(void* data, size_t size);
302
  static ByteSource Foreign(const void* data, size_t size);
303
304
  static ByteSource FromEncodedString(Environment* env,
305
                                      v8::Local<v8::String> value,
306
                                      enum encoding enc = BASE64);
307
308
  static ByteSource FromStringOrBuffer(Environment* env,
309
                                       v8::Local<v8::Value> value);
310
311
  static ByteSource FromString(Environment* env,
312
                               v8::Local<v8::String> str,
313
                               bool ntc = false);
314
315
  static ByteSource FromBuffer(v8::Local<v8::Value> buffer,
316
                               bool ntc = false);
317
318
  static ByteSource FromBIO(const BIOPointer& bio);
319
320
  static ByteSource NullTerminatedCopy(Environment* env,
321
                                       v8::Local<v8::Value> value);
322
323
  static ByteSource FromSymmetricKeyObjectHandle(v8::Local<v8::Value> handle);
324
325
  static ByteSource FromSecretKeyBytes(
326
      Environment* env, v8::Local<v8::Value> value);
327
328
 private:
329
  const void* data_ = nullptr;
330
  void* allocated_data_ = nullptr;
331
  size_t size_ = 0;
332
333
21727
  ByteSource(const void* data, void* allocated_data, size_t size)
334
21727
      : data_(data), allocated_data_(allocated_data), size_(size) {}
335
};
336
337
enum CryptoJobMode {
338
  kCryptoJobAsync,
339
  kCryptoJobSync
340
};
341
342
CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args);
343
344
template <typename CryptoJobTraits>
345
class CryptoJob : public AsyncWrap, public ThreadPoolWork {
346
 public:
347
  using AdditionalParams = typename CryptoJobTraits::AdditionalParameters;
348
349
7686
  explicit CryptoJob(
350
      Environment* env,
351
      v8::Local<v8::Object> object,
352
      AsyncWrap::ProviderType type,
353
      CryptoJobMode mode,
354
      AdditionalParams&& params)
355
      : AsyncWrap(env, object, type),
356
        ThreadPoolWork(env),
357
        mode_(mode),
358
7686
        params_(std::move(params)) {
359
    // If the CryptoJob is async, then the instance will be
360
    // cleaned up when AfterThreadPoolWork is called.
361
7686
    if (mode == kCryptoJobSync) MakeWeak();
362
7686
  }
363
364
  bool IsNotIndicativeOfMemoryLeakAtExit() const override {
365
    // CryptoJobs run a work in the libuv thread pool and may still
366
    // exist when the event loop empties and starts to exit.
367
    return true;
368
  }
369
370
5881
  void AfterThreadPoolWork(int status) override {
371
5881
    Environment* env = AsyncWrap::env();
372
5881
    CHECK_EQ(mode_, kCryptoJobAsync);
373

5881
    CHECK(status == 0 || status == UV_ECANCELED);
374
5881
    std::unique_ptr<CryptoJob> ptr(this);
375
    // If the job was canceled do not execute the callback.
376
    // TODO(@jasnell): We should likely revisit skipping the
377
    // callback on cancel as that could leave the JS in a pending
378
    // state (e.g. unresolved promises...)
379
5881
    if (status == UV_ECANCELED) return;
380
5881
    v8::HandleScope handle_scope(env->isolate());
381
11762
    v8::Context::Scope context_scope(env->context());
382
383
    // TODO(tniessen): Remove the exception handling logic here as soon as we
384
    // can verify that no code path in ToResult will ever throw an exception.
385
    v8::Local<v8::Value> exception;
386
17643
    v8::Local<v8::Value> args[2];
387
    {
388
5881
      node::errors::TryCatchScope try_catch(env);
389
5881
      v8::Maybe<bool> ret = ptr->ToResult(&args[0], &args[1]);
390
5881
      if (!ret.IsJust()) {
391
4
        CHECK(try_catch.HasCaught());
392
4
        exception = try_catch.Exception();
393
5877
      } else if (!ret.FromJust()) {
394
        return;
395
      }
396
    }
397
398
5881
    if (exception.IsEmpty()) {
399
5877
      ptr->MakeCallback(env->ondone_string(), arraysize(args), args);
400
    } else {
401
4
      ptr->MakeCallback(env->ondone_string(), 1, &exception);
402
    }
403
  }
404
405
  virtual v8::Maybe<bool> ToResult(
406
      v8::Local<v8::Value>* err,
407
      v8::Local<v8::Value>* result) = 0;
408
409
7680
  CryptoJobMode mode() const { return mode_; }
410
411
7755
  CryptoErrorStore* errors() { return &errors_; }
412
413
12587
  AdditionalParams* params() { return &params_; }
414
415
6
  std::string MemoryInfoName() const override {
416
6
    return CryptoJobTraits::JobName;
417
  }
418
419
6
  void MemoryInfo(MemoryTracker* tracker) const override {
420
6
    tracker->TrackField("params", params_);
421
6
    tracker->TrackField("errors", errors_);
422
  }
423
424
7680
  static void Run(const v8::FunctionCallbackInfo<v8::Value>& args) {
425
7680
    Environment* env = Environment::GetCurrent(args);
426
427
    CryptoJob<CryptoJobTraits>* job;
428
13563
    ASSIGN_OR_RETURN_UNWRAP(&job, args.Holder());
429
7680
    if (job->mode() == kCryptoJobAsync)
430
5883
      return job->ScheduleWork();
431
432
5391
    v8::Local<v8::Value> ret[2];
433
1797
    env->PrintSyncTrace();
434
1797
    job->DoThreadPoolWork();
435
1797
    v8::Maybe<bool> result = job->ToResult(&ret[0], &ret[1]);
436

3588
    if (result.IsJust() && result.FromJust()) {
437
3582
      args.GetReturnValue().Set(
438
          v8::Array::New(env->isolate(), ret, arraysize(ret)));
439
    }
440
  }
441
442
35826
  static void Initialize(
443
      v8::FunctionCallback new_fn,
444
      Environment* env,
445
      v8::Local<v8::Object> target) {
446
35826
    v8::Local<v8::FunctionTemplate> job = env->NewFunctionTemplate(new_fn);
447
35826
    job->Inherit(AsyncWrap::GetConstructorTemplate(env));
448
71652
    job->InstanceTemplate()->SetInternalFieldCount(
449
        AsyncWrap::kInternalFieldCount);
450
35826
    env->SetProtoMethod(job, "run", Run);
451
35826
    env->SetConstructorFunction(target, CryptoJobTraits::JobName, job);
452
35826
  }
453
454
218610
  static void RegisterExternalReferences(v8::FunctionCallback new_fn,
455
                                         ExternalReferenceRegistry* registry) {
456
218610
    registry->Register(new_fn);
457
218610
    registry->Register(Run);
458
218610
  }
459
460
 private:
461
  const CryptoJobMode mode_;
462
  CryptoErrorStore errors_;
463
  AdditionalParams params_;
464
};
465
466
template <typename DeriveBitsTraits>
467
class DeriveBitsJob final : public CryptoJob<DeriveBitsTraits> {
468
 public:
469
  using AdditionalParams = typename DeriveBitsTraits::AdditionalParameters;
470
471
3894
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
472
3894
    Environment* env = Environment::GetCurrent(args);
473
474
3894
    CryptoJobMode mode = GetCryptoJobMode(args[0]);
475
476
3894
    AdditionalParams params;
477
7788
    if (DeriveBitsTraits::AdditionalConfig(mode, args, 1, &params)
478
            .IsNothing()) {
479
      // The DeriveBitsTraits::AdditionalConfig is responsible for
480
      // calling an appropriate THROW_CRYPTO_* variant reporting
481
      // whatever error caused initialization to fail.
482
73
      return;
483
    }
484
485
3821
    new DeriveBitsJob(env, args.This(), mode, std::move(params));
486
  }
487
488
14501
  static void Initialize(
489
      Environment* env,
490
      v8::Local<v8::Object> target) {
491
14501
    CryptoJob<DeriveBitsTraits>::Initialize(New, env, target);
492
14501
  }
493
494
88485
  static void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
495
88485
    CryptoJob<DeriveBitsTraits>::RegisterExternalReferences(New, registry);
496
88485
  }
497
498
3821
  DeriveBitsJob(
499
      Environment* env,
500
      v8::Local<v8::Object> object,
501
      CryptoJobMode mode,
502
      AdditionalParams&& params)
503
      : CryptoJob<DeriveBitsTraits>(
504
            env,
505
            object,
506
            DeriveBitsTraits::Provider,
507
            mode,
508
3821
            std::move(params)) {}
509
510
3821
  void DoThreadPoolWork() override {
511
3821
    if (!DeriveBitsTraits::DeriveBits(
512
            AsyncWrap::env(),
513
3821
            *CryptoJob<DeriveBitsTraits>::params(), &out_)) {
514
14
      CryptoErrorStore* errors = CryptoJob<DeriveBitsTraits>::errors();
515
14
      errors->Capture();
516
14
      if (errors->Empty())
517
14
        errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
518
14
      return;
519
    }
520
3807
    success_ = true;
521
  }
522
523
3821
  v8::Maybe<bool> ToResult(
524
      v8::Local<v8::Value>* err,
525
      v8::Local<v8::Value>* result) override {
526
3821
    Environment* env = AsyncWrap::env();
527
3821
    CryptoErrorStore* errors = CryptoJob<DeriveBitsTraits>::errors();
528
3821
    if (success_) {
529
3807
      CHECK(errors->Empty());
530
3807
      *err = v8::Undefined(env->isolate());
531
3807
      return DeriveBitsTraits::EncodeOutput(
532
          env,
533
3807
          *CryptoJob<DeriveBitsTraits>::params(),
534
          &out_,
535
3807
          result);
536
    }
537
538
14
    if (errors->Empty())
539
      errors->Capture();
540
14
    CHECK(!errors->Empty());
541
28
    *result = v8::Undefined(env->isolate());
542
28
    return v8::Just(errors->ToException(env).ToLocal(err));
543
  }
544
545
6
  SET_SELF_SIZE(DeriveBitsJob)
546
3
  void MemoryInfo(MemoryTracker* tracker) const override {
547
6
    tracker->TrackFieldWithSize("out", out_.size());
548
6
    CryptoJob<DeriveBitsTraits>::MemoryInfo(tracker);
549
  }
550
551
 private:
552
  ByteSource out_;
553
  bool success_ = false;
554
};
555
556
void ThrowCryptoError(Environment* env,
557
                      unsigned long err,  // NOLINT(runtime/int)
558
                      const char* message = nullptr);
559
560
#ifndef OPENSSL_NO_ENGINE
561
struct EnginePointer {
562
  ENGINE* engine = nullptr;
563
  bool finish_on_exit = false;
564
565
2490
  inline EnginePointer() = default;
566
567
13
  inline explicit EnginePointer(ENGINE* engine_, bool finish_on_exit_ = false)
568
13
    : engine(engine_),
569
13
      finish_on_exit(finish_on_exit_) {}
570
571
2
  inline EnginePointer(EnginePointer&& other) noexcept
572
2
      : engine(other.engine),
573
2
        finish_on_exit(other.finish_on_exit) {
574
2
    other.release();
575
2
  }
576
577
2496
  inline ~EnginePointer() { reset(); }
578
579
2
  inline EnginePointer& operator=(EnginePointer&& other) noexcept {
580
2
    if (this == &other) return *this;
581
2
    this->~EnginePointer();
582
2
    return *new (this) EnginePointer(std::move(other));
583
  }
584
585
35
  inline operator bool() const { return engine != nullptr; }
586
587
13
  inline ENGINE* get() { return engine; }
588
589
2498
  inline void reset(ENGINE* engine_ = nullptr, bool finish_on_exit_ = false) {
590
2498
    if (engine != nullptr) {
591
11
      if (finish_on_exit) {
592
        // This also does the equivalent of ENGINE_free.
593
        CHECK_EQ(ENGINE_finish(engine), 1);
594
      } else {
595
11
        CHECK_EQ(ENGINE_free(engine), 1);
596
      }
597
    }
598
2498
    engine = engine_;
599
2498
    finish_on_exit = finish_on_exit_;
600
2498
  }
601
602
2
  inline ENGINE* release() {
603
2
    ENGINE* ret = engine;
604
2
    engine = nullptr;
605
2
    finish_on_exit = false;
606
2
    return ret;
607
  }
608
};
609
610
EnginePointer LoadEngineById(const char* id, CryptoErrorStore* errors);
611
612
bool SetEngine(
613
    const char* id,
614
    uint32_t flags,
615
    CryptoErrorStore* errors = nullptr);
616
617
void SetEngine(const v8::FunctionCallbackInfo<v8::Value>& args);
618
#endif  // !OPENSSL_NO_ENGINE
619
620
void GetFipsCrypto(const v8::FunctionCallbackInfo<v8::Value>& args);
621
622
void SetFipsCrypto(const v8::FunctionCallbackInfo<v8::Value>& args);
623
624
void TestFipsCrypto(const v8::FunctionCallbackInfo<v8::Value>& args);
625
626
class CipherPushContext {
627
 public:
628
7
  inline explicit CipherPushContext(Environment* env) : env_(env) {}
629
630
581
  inline void push_back(const char* str) {
631
581
    list_.emplace_back(OneByteString(env_->isolate(), str));
632
581
  }
633
634
7
  inline v8::Local<v8::Array> ToJSArray() {
635
7
    return v8::Array::New(env_->isolate(), list_.data(), list_.size());
636
  }
637
638
 private:
639
  std::vector<v8::Local<v8::Value>> list_;
640
  Environment* env_;
641
};
642
643
#if OPENSSL_VERSION_MAJOR >= 3
644
template <class TypeName,
645
          TypeName* fetch_type(OSSL_LIB_CTX*, const char*, const char*),
646
          void free_type(TypeName*),
647
          const TypeName* getbyname(const char*),
648
          const char* getname(const TypeName*)>
649
761
void array_push_back(const TypeName* evp_ref,
650
                     const char* from,
651
                     const char* to,
652
                     void* arg) {
653
761
  if (!from)
654
    return;
655
656
761
  const TypeName* real_instance = getbyname(from);
657
761
  if (!real_instance)
658
    return;
659
660
761
  const char* real_name = getname(real_instance);
661
761
  if (!real_name)
662
    return;
663
664
  // EVP_*_fetch() does not support alias names, so we need to pass it the
665
  // real/original algorithm name.
666
  // We use EVP_*_fetch() as a filter here because it will only return an
667
  // instance if the algorithm is supported by the public OpenSSL APIs (some
668
  // algorithms are used internally by OpenSSL and are also passed to this
669
  // callback).
670
761
  TypeName* fetched = fetch_type(nullptr, real_name, nullptr);
671
761
  if (!fetched)
672
180
    return;
673
674
581
  free_type(fetched);
675
581
  static_cast<CipherPushContext*>(arg)->push_back(from);
676
}
677
#else
678
template <class TypeName>
679
void array_push_back(const TypeName* evp_ref,
680
                     const char* from,
681
                     const char* to,
682
                     void* arg) {
683
  if (!from)
684
    return;
685
  static_cast<CipherPushContext*>(arg)->push_back(from);
686
}
687
#endif
688
689
131352
inline bool IsAnyByteSource(v8::Local<v8::Value> arg) {
690
138371
  return arg->IsArrayBufferView() ||
691

145390
         arg->IsArrayBuffer() ||
692
135748
         arg->IsSharedArrayBuffer();
693
}
694
695
template <typename T>
696
class ArrayBufferOrViewContents {
697
 public:
698
  ArrayBufferOrViewContents() = default;
699
700
219455
  inline explicit ArrayBufferOrViewContents(v8::Local<v8::Value> buf) {
701
219455
    CHECK(IsAnyByteSource(buf));
702
219455
    if (buf->IsArrayBufferView()) {
703
217100
      auto view = buf.As<v8::ArrayBufferView>();
704
217100
      offset_ = view->ByteOffset();
705
217100
      length_ = view->ByteLength();
706
434200
      store_ = view->Buffer()->GetBackingStore();
707
2355
    } else if (buf->IsArrayBuffer()) {
708
2339
      auto ab = buf.As<v8::ArrayBuffer>();
709
2339
      offset_ = 0;
710
2339
      length_ = ab->ByteLength();
711
2339
      store_ = ab->GetBackingStore();
712
    } else {
713
16
      auto sab = buf.As<v8::SharedArrayBuffer>();
714
16
      offset_ = 0;
715
16
      length_ = sab->ByteLength();
716
16
      store_ = sab->GetBackingStore();
717
    }
718
219455
  }
719
720
14286
  inline const T* data() const {
721
    // Ideally, these would return nullptr if IsEmpty() or length_ is zero,
722
    // but some of the openssl API react badly if given a nullptr even when
723
    // length is zero, so we have to return something.
724
14286
    if (size() == 0)
725
131
      return &buf;
726
14155
    return reinterpret_cast<T*>(store_->Data()) + offset_;
727
  }
728
729
103245
  inline T* data() {
730
    // Ideally, these would return nullptr if IsEmpty() or length_ is zero,
731
    // but some of the openssl API react badly if given a nullptr even when
732
    // length is zero, so we have to return something.
733
103245
    if (size() == 0)
734
3
      return &buf;
735
103242
    return reinterpret_cast<T*>(store_->Data()) + offset_;
736
  }
737
738
675777
  inline size_t size() const { return length_; }
739
740
  // In most cases, input buffer sizes passed in to openssl need to
741
  // be limited to <= INT_MAX. This utility method helps us check.
742
214311
  inline bool CheckSizeInt32() { return size() <= INT_MAX; }
743
744
5003
  inline ByteSource ToByteSource() const {
745
5003
    return ByteSource::Foreign(data(), size());
746
  }
747
748
6889
  inline ByteSource ToCopy() const {
749
6889
    if (size() == 0) return ByteSource();
750
6291
    char* buf = MallocOpenSSL<char>(size());
751
6291
    CHECK_NOT_NULL(buf);
752
6291
    memcpy(buf, data(), size());
753
6291
    return ByteSource::Allocated(buf, size());
754
  }
755
756
95
  inline ByteSource ToNullTerminatedCopy() const {
757
95
    if (size() == 0) return ByteSource();
758
88
    char* buf = MallocOpenSSL<char>(size() + 1);
759
88
    CHECK_NOT_NULL(buf);
760
88
    buf[size()] = 0;
761
88
    memcpy(buf, data(), size());
762
88
    return ByteSource::Allocated(buf, size());
763
  }
764
765
  template <typename M>
766
104
  void CopyTo(M* dest, size_t len) const {
767
    static_assert(sizeof(M) == 1, "sizeof(M) must equal 1");
768
104
    len = std::min(len, size());
769

104
    if (len > 0 && data() != nullptr)
770
104
      memcpy(dest, data(), len);
771
104
  }
772
773
 private:
774
  T buf = 0;
775
  size_t offset_ = 0;
776
  size_t length_ = 0;
777
  std::shared_ptr<v8::BackingStore> store_;
778
};
779
780
template <typename T>
781
std::vector<T> CopyBuffer(const ArrayBufferOrViewContents<T>& buf) {
782
  std::vector<T> vec;
783
  vec->resize(buf.size());
784
  if (vec->size() > 0 && buf.data() != nullptr)
785
    memcpy(vec->data(), buf.data(), vec->size());
786
  return vec;
787
}
788
789
template <typename T>
790
std::vector<T> CopyBuffer(v8::Local<v8::Value> buf) {
791
  return CopyBuffer(ArrayBufferOrViewContents<T>(buf));
792
}
793
794
v8::MaybeLocal<v8::Value> EncodeBignum(
795
    Environment* env,
796
    const BIGNUM* bn,
797
    int size,
798
    v8::Local<v8::Value>* error);
799
800
v8::Maybe<bool> SetEncodedValue(
801
    Environment* env,
802
    v8::Local<v8::Object> target,
803
    v8::Local<v8::String> name,
804
    const BIGNUM* bn,
805
    int size = 0);
806
807
namespace Util {
808
void Initialize(Environment* env, v8::Local<v8::Object> target);
809
void RegisterExternalReferences(ExternalReferenceRegistry* registry);
810
}  // namespace Util
811
812
}  // namespace crypto
813
}  // namespace node
814
815
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
816
#endif  // SRC_CRYPTO_CRYPTO_UTIL_H_