GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_util.cc Lines: 297 355 83.7 %
Date: 2022-05-07 04:15:18 Branches: 119 242 49.2 %

Line Branch Exec Source
1
#include "crypto/crypto_util.h"
2
#include "crypto/crypto_bio.h"
3
#include "crypto/crypto_keys.h"
4
#include "allocated_buffer-inl.h"
5
#include "async_wrap-inl.h"
6
#include "env-inl.h"
7
#include "memory_tracker-inl.h"
8
#include "node_buffer.h"
9
#include "node_options-inl.h"
10
#include "string_bytes.h"
11
#include "threadpoolwork-inl.h"
12
#include "util-inl.h"
13
#include "v8.h"
14
15
#include "math.h"
16
17
#if OPENSSL_VERSION_MAJOR >= 3
18
#include "openssl/provider.h"
19
#endif
20
21
#include <openssl/rand.h>
22
23
namespace node {
24
25
using v8::ArrayBuffer;
26
using v8::BackingStore;
27
using v8::BigInt;
28
using v8::Context;
29
using v8::Exception;
30
using v8::FunctionCallbackInfo;
31
using v8::HandleScope;
32
using v8::Isolate;
33
using v8::Just;
34
using v8::Local;
35
using v8::Maybe;
36
using v8::MaybeLocal;
37
using v8::NewStringType;
38
using v8::Nothing;
39
using v8::Object;
40
using v8::String;
41
using v8::TryCatch;
42
using v8::Uint32;
43
using v8::Uint8Array;
44
using v8::Value;
45
46
namespace crypto {
47
2237
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
48
  // From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
49
  //
50
  //   If VerifyCallback returns 1, the verification process is continued. If
51
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
52
  //   terminated with respect to verification failures and the connection will
53
  //   be established. The calling process can however retrieve the error code
54
  //   of the last verification error using SSL_get_verify_result(3) or by
55
  //   maintaining its own error storage managed by VerifyCallback.
56
  //
57
  // Since we cannot perform I/O quickly enough with X509_STORE_CTX_ APIs in
58
  // this callback, we ignore all preverify_ok errors and let the handshake
59
  // continue. It is imperative that the user use Connection::VerifyError after
60
  // the 'secure' callback has been made.
61
2237
  return 1;
62
}
63
64
18330
void CheckEntropy() {
65
  for (;;) {
66
18330
    int status = RAND_status();
67
18330
    CHECK_GE(status, 0);  // Cannot fail.
68
18330
    if (status != 0)
69
18330
      break;
70
71
    // Give up, RAND_poll() not supported.
72
    if (RAND_poll() == 0)
73
      break;
74
  }
75
18330
}
76
77
17391
bool EntropySource(unsigned char* buffer, size_t length) {
78
  // Ensure that OpenSSL's PRNG is properly seeded.
79
17391
  CheckEntropy();
80
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
81
  // random. That's okay, it's still better than V8's stock source of entropy,
82
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
83
17391
  return RAND_bytes(buffer, length) != -1;
84
}
85
86
111
int PasswordCallback(char* buf, int size, int rwflag, void* u) {
87
111
  const ByteSource* passphrase = *static_cast<const ByteSource**>(u);
88
111
  if (passphrase != nullptr) {
89
91
    size_t buflen = static_cast<size_t>(size);
90
91
    size_t len = passphrase->size();
91
91
    if (buflen < len)
92
2
      return -1;
93
89
    memcpy(buf, passphrase->get(), len);
94
89
    return len;
95
  }
96
97
20
  return -1;
98
}
99
100
// This callback is used to avoid the default passphrase callback in OpenSSL
101
// which will typically prompt for the passphrase. The prompting is designed
102
// for the OpenSSL CLI, but works poorly for Node.js because it involves
103
// synchronous interaction with the controlling terminal, something we never
104
// want, and use this function to avoid it.
105
int NoPasswordCallback(char* buf, int size, int rwflag, void* u) {
106
  return 0;
107
}
108
109
5179
bool ProcessFipsOptions() {
110
  /* Override FIPS settings in configuration file, if needed. */
111

10357
  if (per_process::cli_options->enable_fips_crypto ||
112
5178
      per_process::cli_options->force_fips_crypto) {
113
#if OPENSSL_VERSION_MAJOR >= 3
114
2
    OSSL_PROVIDER* fips_provider = OSSL_PROVIDER_load(nullptr, "fips");
115
2
    if (fips_provider == nullptr)
116
2
      return false;
117
    OSSL_PROVIDER_unload(fips_provider);
118
119
    return EVP_default_properties_enable_fips(nullptr, 1) &&
120
           EVP_default_properties_is_fips_enabled(nullptr);
121
#else
122
    return FIPS_mode() == 0 && FIPS_mode_set(1);
123
#endif
124
  }
125
5177
  return true;
126
}
127
128
6018
bool InitCryptoOnce(Isolate* isolate) {
129
  static uv_once_t init_once = UV_ONCE_INIT;
130
12036
  TryCatch try_catch{isolate};
131
6018
  uv_once(&init_once, InitCryptoOnce);
132

6018
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
133
    try_catch.ReThrow();
134
    return false;
135
  }
136
6018
  return true;
137
}
138
139
// Protect accesses to FIPS state with a mutex. This should potentially
140
// be part of a larger mutex for global OpenSSL state.
141
static Mutex fips_mutex;
142
143
5185
void InitCryptoOnce() {
144
10370
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
145
10370
  Mutex::ScopedLock fips_lock(fips_mutex);
146
#ifndef OPENSSL_IS_BORINGSSL
147
5185
  OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
148
149
#if OPENSSL_VERSION_MAJOR < 3
150
  // --openssl-config=...
151
  if (!per_process::cli_options->openssl_config.empty()) {
152
    const char* conf = per_process::cli_options->openssl_config.c_str();
153
    OPENSSL_INIT_set_config_filename(settings, conf);
154
  }
155
#endif
156
157
#if OPENSSL_VERSION_MAJOR >= 3
158
  // --openssl-legacy-provider
159
5185
  if (per_process::cli_options->openssl_legacy_provider) {
160
    OSSL_PROVIDER* legacy_provider = OSSL_PROVIDER_load(nullptr, "legacy");
161
    if (legacy_provider == nullptr) {
162
      fprintf(stderr, "Unable to load legacy provider.\n");
163
    }
164
  }
165
#endif
166
167
5185
  OPENSSL_init_ssl(0, settings);
168
5185
  OPENSSL_INIT_free(settings);
169
5185
  settings = nullptr;
170
171
#ifndef _WIN32
172
5185
  if (per_process::cli_options->secure_heap != 0) {
173

1
    switch (CRYPTO_secure_malloc_init(
174
1
                per_process::cli_options->secure_heap,
175
1
                static_cast<int>(per_process::cli_options->secure_heap_min))) {
176
      case 0:
177
        fprintf(stderr, "Unable to initialize openssl secure heap.\n");
178
        break;
179
      case 2:
180
        // Not a fatal error but worthy of a warning.
181
        fprintf(stderr, "Unable to memory map openssl secure heap.\n");
182
        break;
183
1
      case 1:
184
        // OK!
185
1
        break;
186
    }
187
  }
188
#endif
189
190
#endif  // OPENSSL_IS_BORINGSSL
191
192
  // Turn off compression. Saves memory and protects against CRIME attacks.
193
  // No-op with OPENSSL_NO_COMP builds of OpenSSL.
194
5185
  sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
195
196
#ifndef OPENSSL_NO_ENGINE
197
5185
  ERR_load_ENGINE_strings();
198
5185
  ENGINE_load_builtin_engines();
199
#endif  // !OPENSSL_NO_ENGINE
200
201
5185
  NodeBIO::GetMethod();
202
5185
}
203
204
213
void GetFipsCrypto(const FunctionCallbackInfo<Value>& args) {
205
426
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
206
213
  Mutex::ScopedLock fips_lock(fips_mutex);
207
208
#if OPENSSL_VERSION_MAJOR >= 3
209
426
  args.GetReturnValue().Set(EVP_default_properties_is_fips_enabled(nullptr) ?
210
      1 : 0);
211
#else
212
  args.GetReturnValue().Set(FIPS_mode() ? 1 : 0);
213
#endif
214
213
}
215
216
void SetFipsCrypto(const FunctionCallbackInfo<Value>& args) {
217
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
218
  Mutex::ScopedLock fips_lock(fips_mutex);
219
220
  CHECK(!per_process::cli_options->force_fips_crypto);
221
  Environment* env = Environment::GetCurrent(args);
222
  // TODO(addaleax): This should not be possible to set from worker threads.
223
  // CHECK(env->owns_process_state());
224
  bool enable = args[0]->BooleanValue(env->isolate());
225
226
#if OPENSSL_VERSION_MAJOR >= 3
227
  if (enable == EVP_default_properties_is_fips_enabled(nullptr))
228
#else
229
  if (static_cast<int>(enable) == FIPS_mode())
230
#endif
231
    return;  // No action needed.
232
233
#if OPENSSL_VERSION_MAJOR >= 3
234
  if (!EVP_default_properties_enable_fips(nullptr, enable)) {
235
#else
236
  if (!FIPS_mode_set(enable)) {
237
#endif
238
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
239
    return ThrowCryptoError(env, err);
240
  }
241
}
242
243
5
void TestFipsCrypto(const v8::FunctionCallbackInfo<v8::Value>& args) {
244
10
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
245
5
  Mutex::ScopedLock fips_lock(fips_mutex);
246
247
#ifdef OPENSSL_FIPS
248
#if OPENSSL_VERSION_MAJOR >= 3
249
  OSSL_PROVIDER* fips_provider = nullptr;
250
  if (OSSL_PROVIDER_available(nullptr, "fips")) {
251
    fips_provider = OSSL_PROVIDER_load(nullptr, "fips");
252
  }
253
  const auto enabled = fips_provider == nullptr ? 0 :
254
      OSSL_PROVIDER_self_test(fips_provider) ? 1 : 0;
255
#else
256
  const auto enabled = FIPS_selftest() ? 1 : 0;
257
#endif
258
#else  // OPENSSL_FIPS
259
5
  const auto enabled = 0;
260
#endif  // OPENSSL_FIPS
261
262
10
  args.GetReturnValue().Set(enabled);
263
5
}
264
265
1512
void CryptoErrorStore::Capture() {
266
1512
  errors_.clear();
267
1605
  while (const uint32_t err = ERR_get_error()) {
268
    char buf[256];
269
93
    ERR_error_string_n(err, buf, sizeof(buf));
270
93
    errors_.emplace_back(buf);
271
93
  }
272
1512
  std::reverse(std::begin(errors_), std::end(errors_));
273
1512
}
274
275
6416
bool CryptoErrorStore::Empty() const {
276
6416
  return errors_.empty();
277
}
278
279
210
MaybeLocal<Value> CryptoErrorStore::ToException(
280
    Environment* env,
281
    Local<String> exception_string) const {
282
210
  if (exception_string.IsEmpty()) {
283
106
    CryptoErrorStore copy(*this);
284
53
    if (copy.Empty()) {
285
      // But possibly a bug...
286
      copy.Insert(NodeCryptoError::OK);
287
    }
288
    // Use last element as the error message, everything else goes
289
    // into the .opensslErrorStack property on the exception object.
290
53
    const std::string& last_error_string = copy.errors_.back();
291
    Local<String> exception_string;
292
53
    if (!String::NewFromUtf8(
293
            env->isolate(),
294
            last_error_string.data(),
295
            NewStringType::kNormal,
296
106
            last_error_string.size()).ToLocal(&exception_string)) {
297
      return MaybeLocal<Value>();
298
    }
299
53
    copy.errors_.pop_back();
300
53
    return copy.ToException(env, exception_string);
301
  }
302
303
157
  Local<Value> exception_v = Exception::Error(exception_string);
304
157
  CHECK(!exception_v.IsEmpty());
305
306
157
  if (!Empty()) {
307
26
    CHECK(exception_v->IsObject());
308
26
    Local<Object> exception = exception_v.As<Object>();
309
    Local<Value> stack;
310
78
    if (!ToV8Value(env->context(), errors_).ToLocal(&stack) ||
311
78
        exception->Set(env->context(), env->openssl_error_stack(), stack)
312
26
            .IsNothing()) {
313
      return MaybeLocal<Value>();
314
    }
315
  }
316
317
157
  return exception_v;
318
}
319
320
18391
ByteSource::ByteSource(ByteSource&& other) noexcept
321
18391
    : data_(other.data_),
322
18391
      allocated_data_(other.allocated_data_),
323
36782
      size_(other.size_) {
324
18391
  other.allocated_data_ = nullptr;
325
18391
}
326
327
125876
ByteSource::~ByteSource() {
328
62938
  OPENSSL_clear_free(allocated_data_, size_);
329
62938
}
330
331
void ByteSource::reset() {
332
  OPENSSL_clear_free(allocated_data_, size_);
333
  data_ = nullptr;
334
  size_ = 0;
335
}
336
337
11923
ByteSource& ByteSource::operator=(ByteSource&& other) noexcept {
338
11923
  if (&other != this) {
339
11923
    OPENSSL_clear_free(allocated_data_, size_);
340
11923
    data_ = other.data_;
341
11923
    allocated_data_ = other.allocated_data_;
342
11923
    other.allocated_data_ = nullptr;
343
11923
    size_ = other.size_;
344
  }
345
11923
  return *this;
346
}
347
348
2960
std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() {
349
  // It's ok for allocated_data_ to be nullptr but
350
  // only if size_ is zero.
351

2960
  CHECK_IMPLIES(size_ > 0, allocated_data_ != nullptr);
352
  std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore(
353
2960
      allocated_data_,
354
      size(),
355
2955
      [](void* data, size_t length, void* deleter_data) {
356
2955
        OPENSSL_clear_free(deleter_data, length);
357
2960
      }, allocated_data_);
358
2960
  CHECK(ptr);
359
2960
  allocated_data_ = nullptr;
360
2960
  data_ = nullptr;
361
2960
  size_ = 0;
362
2960
  return ptr;
363
}
364
365
2960
Local<ArrayBuffer> ByteSource::ToArrayBuffer(Environment* env) {
366
2960
  std::unique_ptr<BackingStore> store = ReleaseToBackingStore();
367
2960
  return ArrayBuffer::New(env->isolate(), std::move(store));
368
}
369
370
17
MaybeLocal<Uint8Array> ByteSource::ToBuffer(Environment* env) {
371
17
  Local<ArrayBuffer> ab = ToArrayBuffer(env);
372
17
  return Buffer::New(env, ab, 0, ab->ByteLength());
373
}
374
375
20187
const char* ByteSource::get() const {
376
20187
  return data_;
377
}
378
379
26310
size_t ByteSource::size() const {
380
26310
  return size_;
381
}
382
383
505
ByteSource ByteSource::FromBIO(const BIOPointer& bio) {
384
505
  CHECK(bio);
385
  BUF_MEM* bptr;
386
505
  BIO_get_mem_ptr(bio.get(), &bptr);
387
505
  char* data = MallocOpenSSL<char>(bptr->length);
388
505
  memcpy(data, bptr->data, bptr->length);
389
505
  return Allocated(data, bptr->length);
390
}
391
392
3111
ByteSource ByteSource::FromEncodedString(Environment* env,
393
                                         Local<String> key,
394
                                         enum encoding enc) {
395
3111
  size_t length = 0;
396
3111
  size_t actual = 0;
397
3111
  char* data = nullptr;
398
399

6222
  if (StringBytes::Size(env->isolate(), key, enc).To(&length) && length > 0) {
400
3111
    data = MallocOpenSSL<char>(length);
401
3111
    actual = StringBytes::Write(env->isolate(), data, length, key, enc);
402
403
3111
    CHECK(actual <= length);
404
405
3111
    if (actual == 0) {
406
      OPENSSL_clear_free(data, length);
407
      data = nullptr;
408
3111
    } else if (actual < length) {
409
      data = reinterpret_cast<char*>(OPENSSL_realloc(data, actual));
410
    }
411
  }
412
413
3111
  return Allocated(data, actual);
414
}
415
416
2685
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
417
                                          Local<Value> value) {
418
2685
  return IsAnyByteSource(value) ? FromBuffer(value)
419
2685
                                : FromString(env, value.As<String>());
420
}
421
422
24
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
423
                                  bool ntc) {
424
48
  CHECK(str->IsString());
425
24
  size_t size = str->Utf8Length(env->isolate());
426
24
  size_t alloc_size = ntc ? size + 1 : size;
427
24
  char* data = MallocOpenSSL<char>(alloc_size);
428
24
  int opts = String::NO_OPTIONS;
429
24
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
430
24
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
431
24
  return Allocated(data, size);
432
}
433
434
2687
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
435
5374
  ArrayBufferOrViewContents<char> buf(buffer);
436
2687
  return ntc ? buf.ToNullTerminatedCopy() : buf.ToByteSource();
437
}
438
439
1558
ByteSource ByteSource::FromSecretKeyBytes(
440
    Environment* env,
441
    Local<Value> value) {
442
  // A key can be passed as a string, buffer or KeyObject with type 'secret'.
443
  // If it is a string, we need to convert it to a buffer. We are not doing that
444
  // in JS to avoid creating an unprotected copy on the heap.
445

3116
  return value->IsString() || IsAnyByteSource(value) ?
446
           ByteSource::FromStringOrBuffer(env, value) :
447
1558
           ByteSource::FromSymmetricKeyObjectHandle(value);
448
}
449
450
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
451
                                          Local<Value> value) {
452
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
453
                                    : FromString(env, value.As<String>(), true);
454
}
455
456
14
ByteSource ByteSource::FromSymmetricKeyObjectHandle(Local<Value> handle) {
457
14
  CHECK(handle->IsObject());
458
14
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(handle.As<Object>());
459
14
  CHECK_NOT_NULL(key);
460
14
  return Foreign(key->Data()->GetSymmetricKey(),
461
28
                 key->Data()->GetSymmetricKeySize());
462
}
463
464
21924
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
465
    : data_(data),
466
      allocated_data_(allocated_data),
467
21924
      size_(size) {}
468
469
16819
ByteSource ByteSource::Allocated(char* data, size_t size) {
470
16819
  return ByteSource(data, data, size);
471
}
472
473
5105
ByteSource ByteSource::Foreign(const char* data, size_t size) {
474
5105
  return ByteSource(data, nullptr, size);
475
}
476
477
namespace error {
478
104
Maybe<bool> Decorate(Environment* env, Local<Object> obj,
479
              unsigned long err) {  // NOLINT(runtime/int)
480
104
  if (err == 0) return Just(true);  // No decoration necessary.
481
482
93
  const char* ls = ERR_lib_error_string(err);
483
93
  const char* fs = ERR_func_error_string(err);
484
93
  const char* rs = ERR_reason_error_string(err);
485
486
93
  Isolate* isolate = env->isolate();
487
93
  Local<Context> context = isolate->GetCurrentContext();
488
489
93
  if (ls != nullptr) {
490
186
    if (obj->Set(context, env->library_string(),
491
372
                 OneByteString(isolate, ls)).IsNothing()) {
492
1
      return Nothing<bool>();
493
    }
494
  }
495
92
  if (fs != nullptr) {
496
    if (obj->Set(context, env->function_string(),
497
                 OneByteString(isolate, fs)).IsNothing()) {
498
      return Nothing<bool>();
499
    }
500
  }
501
92
  if (rs != nullptr) {
502
184
    if (obj->Set(context, env->reason_string(),
503
368
                 OneByteString(isolate, rs)).IsNothing()) {
504
      return Nothing<bool>();
505
    }
506
507
    // SSL has no API to recover the error name from the number, so we
508
    // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
509
    // which ends up being close to the original error macro name.
510
92
    std::string reason(rs);
511
512
1754
    for (auto& c : reason) {
513
1662
      if (c == ' ')
514
183
        c = '_';
515
      else
516
1479
        c = ToUpper(c);
517
    }
518
519
#define OSSL_ERROR_CODES_MAP(V)                                               \
520
    V(SYS)                                                                    \
521
    V(BN)                                                                     \
522
    V(RSA)                                                                    \
523
    V(DH)                                                                     \
524
    V(EVP)                                                                    \
525
    V(BUF)                                                                    \
526
    V(OBJ)                                                                    \
527
    V(PEM)                                                                    \
528
    V(DSA)                                                                    \
529
    V(X509)                                                                   \
530
    V(ASN1)                                                                   \
531
    V(CONF)                                                                   \
532
    V(CRYPTO)                                                                 \
533
    V(EC)                                                                     \
534
    V(SSL)                                                                    \
535
    V(BIO)                                                                    \
536
    V(PKCS7)                                                                  \
537
    V(X509V3)                                                                 \
538
    V(PKCS12)                                                                 \
539
    V(RAND)                                                                   \
540
    V(DSO)                                                                    \
541
    V(ENGINE)                                                                 \
542
    V(OCSP)                                                                   \
543
    V(UI)                                                                     \
544
    V(COMP)                                                                   \
545
    V(ECDSA)                                                                  \
546
    V(ECDH)                                                                   \
547
    V(OSSL_STORE)                                                             \
548
    V(FIPS)                                                                   \
549
    V(CMS)                                                                    \
550
    V(TS)                                                                     \
551
    V(HMAC)                                                                   \
552
    V(CT)                                                                     \
553
    V(ASYNC)                                                                  \
554
    V(KDF)                                                                    \
555
    V(SM2)                                                                    \
556
    V(USER)                                                                   \
557
558
#define V(name) case ERR_LIB_##name: lib = #name "_"; break;
559
92
    const char* lib = "";
560
92
    const char* prefix = "OSSL_";
561









92
    switch (ERR_GET_LIB(err)) { OSSL_ERROR_CODES_MAP(V) }
562
#undef V
563
#undef OSSL_ERROR_CODES_MAP
564
    // Don't generate codes like "ERR_OSSL_SSL_".
565

92
    if (lib && strcmp(lib, "SSL_") == 0)
566
6
      prefix = "";
567
568
    // All OpenSSL reason strings fit in a single 80-column macro definition,
569
    // all prefix lengths are <= 10, and ERR_OSSL_ is 9, so 128 is more than
570
    // sufficient.
571
    char code[128];
572
92
    snprintf(code, sizeof(code), "ERR_%s%s%s", prefix, lib, reason.c_str());
573
574
184
    if (obj->Set(env->isolate()->GetCurrentContext(),
575
             env->code_string(),
576
368
             OneByteString(env->isolate(), code)).IsNothing())
577
      return Nothing<bool>();
578
  }
579
580
92
  return Just(true);
581
}
582
}  // namespace error
583
584
104
void ThrowCryptoError(Environment* env,
585
                      unsigned long err,  // NOLINT(runtime/int)
586
                      // Default, only used if there is no SSL `err` which can
587
                      // be used to create a long-style message string.
588
                      const char* message) {
589
104
  char message_buffer[128] = {0};
590

104
  if (err != 0 || message == nullptr) {
591
93
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
592
93
    message = message_buffer;
593
  }
594
104
  HandleScope scope(env->isolate());
595
  Local<String> exception_string;
596
  Local<Value> exception;
597
  Local<Object> obj;
598
208
  if (!String::NewFromUtf8(env->isolate(), message).ToLocal(&exception_string))
599
    return;
600
104
  CryptoErrorStore errors;
601
104
  errors.Capture();
602
104
  if (!errors.ToException(env, exception_string).ToLocal(&exception) ||
603

416
      !exception->ToObject(env->context()).ToLocal(&obj) ||
604

312
      error::Decorate(env, obj, err).IsNothing()) {
605
1
    return;
606
  }
607
103
  env->isolate()->ThrowException(exception);
608
}
609
610
#ifndef OPENSSL_NO_ENGINE
611
11
EnginePointer LoadEngineById(const char* id, CryptoErrorStore* errors) {
612
22
  MarkPopErrorOnReturn mark_pop_error_on_return;
613
614
11
  EnginePointer engine(ENGINE_by_id(id));
615
11
  if (!engine) {
616
    // Engine not found, try loading dynamically.
617
2
    engine = EnginePointer(ENGINE_by_id("dynamic"));
618
2
    if (engine) {
619

4
      if (!ENGINE_ctrl_cmd_string(engine.get(), "SO_PATH", id, 0) ||
620
2
          !ENGINE_ctrl_cmd_string(engine.get(), "LOAD", nullptr, 0)) {
621
2
        engine.reset();
622
      }
623
    }
624
  }
625
626

11
  if (!engine && errors != nullptr) {
627
    errors->Capture();
628
    if (errors->Empty()) {
629
      errors->Insert(NodeCryptoError::ENGINE_NOT_FOUND, id);
630
    }
631
  }
632
633
11
  return engine;
634
}
635
636
11
bool SetEngine(const char* id, uint32_t flags, CryptoErrorStore* errors) {
637
11
  ClearErrorOnReturn clear_error_on_return;
638
22
  EnginePointer engine = LoadEngineById(id, errors);
639
11
  if (!engine)
640
2
    return false;
641
642
9
  if (!ENGINE_set_default(engine.get(), flags)) {
643
    if (errors != nullptr)
644
      errors->Capture();
645
    return false;
646
  }
647
648
9
  return true;
649
}
650
651
11
void SetEngine(const FunctionCallbackInfo<Value>& args) {
652
11
  Environment* env = Environment::GetCurrent(args);
653

33
  CHECK(args.Length() >= 2 && args[0]->IsString());
654
  uint32_t flags;
655
22
  if (!args[1]->Uint32Value(env->context()).To(&flags)) return;
656
657
11
  const node::Utf8Value engine_id(env->isolate(), args[0]);
658
659
22
  args.GetReturnValue().Set(SetEngine(*engine_id, flags));
660
}
661
#endif  // !OPENSSL_NO_ENGINE
662
663
2603
MaybeLocal<Value> EncodeBignum(
664
    Environment* env,
665
    const BIGNUM* bn,
666
    int size,
667
    Local<Value>* error) {
668
5206
  std::vector<uint8_t> buf(size);
669
2603
  CHECK_EQ(BN_bn2binpad(bn, buf.data(), size), size);
670
  return StringBytes::Encode(
671
      env->isolate(),
672
2603
      reinterpret_cast<const char*>(buf.data()),
673
      buf.size(),
674
      BASE64URL,
675
5206
      error);
676
}
677
678
2603
Maybe<bool> SetEncodedValue(
679
    Environment* env,
680
    Local<Object> target,
681
    Local<String> name,
682
    const BIGNUM* bn,
683
    int size) {
684
  Local<Value> value;
685
  Local<Value> error;
686
2603
  CHECK_NOT_NULL(bn);
687
2603
  if (size == 0)
688
2094
    size = BN_num_bytes(bn);
689
5206
  if (!EncodeBignum(env, bn, size, &error).ToLocal(&value)) {
690
    if (!error.IsEmpty())
691
      env->isolate()->ThrowException(error);
692
    return Nothing<bool>();
693
  }
694
2603
  return target->Set(env->context(), name, value);
695
}
696
697
5293
CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args) {
698
5293
  CHECK(args->IsUint32());
699
5293
  uint32_t mode = args.As<v8::Uint32>()->Value();
700
5293
  CHECK_LE(mode, kCryptoJobSync);
701
5293
  return static_cast<CryptoJobMode>(mode);
702
}
703
704
namespace {
705
// SecureBuffer uses openssl to allocate a Uint8Array using
706
// OPENSSL_secure_malloc. Because we do not yet actually
707
// make use of secure heap, this has the same semantics as
708
// using OPENSSL_malloc. However, if the secure heap is
709
// initialized, SecureBuffer will automatically use it.
710
4
void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
711
4
  CHECK(args[0]->IsUint32());
712
4
  Environment* env = Environment::GetCurrent(args);
713
8
  uint32_t len = args[0].As<Uint32>()->Value();
714
4
  char* data = static_cast<char*>(OPENSSL_secure_malloc(len));
715
4
  if (data == nullptr) {
716
    // There's no memory available for the allocation.
717
    // Return nothing.
718
    return;
719
  }
720
4
  memset(data, 0, len);
721
  std::shared_ptr<BackingStore> store =
722
4
      ArrayBuffer::NewBackingStore(
723
          data,
724
          len,
725
4
          [](void* data, size_t len, void* deleter_data) {
726
4
            OPENSSL_secure_clear_free(data, len);
727
4
          },
728
4
          data);
729
4
  Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store);
730
8
  args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len));
731
}
732
733
4
void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) {
734
4
  Environment* env = Environment::GetCurrent(args);
735
4
  if (CRYPTO_secure_malloc_initialized())
736
8
    args.GetReturnValue().Set(
737
4
        BigInt::New(env->isolate(), CRYPTO_secure_used()));
738
4
}
739
}  // namespace
740
741
namespace Util {
742
849
void Initialize(Environment* env, Local<Object> target) {
743
#ifndef OPENSSL_NO_ENGINE
744
849
  env->SetMethod(target, "setEngine", SetEngine);
745
#endif  // !OPENSSL_NO_ENGINE
746
747
849
  env->SetMethodNoSideEffect(target, "getFipsCrypto", GetFipsCrypto);
748
849
  env->SetMethod(target, "setFipsCrypto", SetFipsCrypto);
749
849
  env->SetMethodNoSideEffect(target, "testFipsCrypto", TestFipsCrypto);
750
751
2547
  NODE_DEFINE_CONSTANT(target, kCryptoJobAsync);
752
1698
  NODE_DEFINE_CONSTANT(target, kCryptoJobSync);
753
754
849
  env->SetMethod(target, "secureBuffer", SecureBuffer);
755
849
  env->SetMethod(target, "secureHeapUsed", SecureHeapUsed);
756
849
}
757
5175
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
758
#ifndef OPENSSL_NO_ENGINE
759
5175
  registry->Register(SetEngine);
760
#endif  // !OPENSSL_NO_ENGINE
761
762
5175
  registry->Register(GetFipsCrypto);
763
5175
  registry->Register(SetFipsCrypto);
764
5175
  registry->Register(TestFipsCrypto);
765
5175
  registry->Register(SecureBuffer);
766
5175
  registry->Register(SecureHeapUsed);
767
5175
}
768
769
}  // namespace Util
770
771
}  // namespace crypto
772
}  // namespace node