GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_util.cc Lines: 288 344 83.7 %
Date: 2021-11-08 04:13:55 Branches: 120 242 49.6 %

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
2151
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
2151
  return 1;
62
}
63
64
16707
void CheckEntropy() {
65
  for (;;) {
66
16707
    int status = RAND_status();
67
16707
    CHECK_GE(status, 0);  // Cannot fail.
68
16707
    if (status != 0)
69
16707
      break;
70
71
    // Give up, RAND_poll() not supported.
72
    if (RAND_poll() == 0)
73
      break;
74
  }
75
16707
}
76
77
16030
bool EntropySource(unsigned char* buffer, size_t length) {
78
  // Ensure that OpenSSL's PRNG is properly seeded.
79
16030
  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
16030
  return RAND_bytes(buffer, length) != -1;
84
}
85
86
104
int PasswordCallback(char* buf, int size, int rwflag, void* u) {
87
104
  const ByteSource* passphrase = *static_cast<const ByteSource**>(u);
88
104
  if (passphrase != nullptr) {
89
88
    size_t buflen = static_cast<size_t>(size);
90
88
    size_t len = passphrase->size();
91
88
    if (buflen < len)
92
4
      return -1;
93
84
    memcpy(buf, passphrase->get(), len);
94
84
    return len;
95
  }
96
97
16
  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
4875
bool ProcessFipsOptions() {
110
  /* Override FIPS settings in configuration file, if needed. */
111

9749
  if (per_process::cli_options->enable_fips_crypto ||
112
4874
      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
4873
  return true;
126
}
127
128
4316
bool InitCryptoOnce(Isolate* isolate) {
129
  static uv_once_t init_once = UV_ONCE_INIT;
130
8632
  TryCatch try_catch{isolate};
131
4316
  uv_once(&init_once, InitCryptoOnce);
132

4316
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
133
    try_catch.ReThrow();
134
    return false;
135
  }
136
4316
  return true;
137
}
138
139
4166
void InitCryptoOnce() {
140
#ifndef OPENSSL_IS_BORINGSSL
141
4166
  OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
142
143
#if OPENSSL_VERSION_MAJOR < 3
144
  // --openssl-config=...
145
  if (!per_process::cli_options->openssl_config.empty()) {
146
    const char* conf = per_process::cli_options->openssl_config.c_str();
147
    OPENSSL_INIT_set_config_filename(settings, conf);
148
  }
149
#endif
150
151
#if OPENSSL_VERSION_MAJOR >= 3
152
  // --openssl-legacy-provider
153
4166
  if (per_process::cli_options->openssl_legacy_provider) {
154
    OSSL_PROVIDER* legacy_provider = OSSL_PROVIDER_load(nullptr, "legacy");
155
    if (legacy_provider == nullptr) {
156
      fprintf(stderr, "Unable to load legacy provider.\n");
157
    }
158
  }
159
#endif
160
161
4166
  OPENSSL_init_ssl(0, settings);
162
4166
  OPENSSL_INIT_free(settings);
163
4166
  settings = nullptr;
164
165
#ifndef _WIN32
166
4166
  if (per_process::cli_options->secure_heap != 0) {
167

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

2950
  CHECK_IMPLIES(size_ > 0, allocated_data_ != nullptr);
335
  std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore(
336
2950
      allocated_data_,
337
      size(),
338
2946
      [](void* data, size_t length, void* deleter_data) {
339
2946
        OPENSSL_clear_free(deleter_data, length);
340
2950
      }, allocated_data_);
341
2950
  CHECK(ptr);
342
2950
  allocated_data_ = nullptr;
343
2950
  data_ = nullptr;
344
2950
  size_ = 0;
345
2950
  return ptr;
346
}
347
348
2950
Local<ArrayBuffer> ByteSource::ToArrayBuffer(Environment* env) {
349
2950
  std::unique_ptr<BackingStore> store = ReleaseToBackingStore();
350
2950
  return ArrayBuffer::New(env->isolate(), std::move(store));
351
}
352
353
19566
const char* ByteSource::get() const {
354
19566
  return data_;
355
}
356
357
25419
size_t ByteSource::size() const {
358
25419
  return size_;
359
}
360
361
503
ByteSource ByteSource::FromBIO(const BIOPointer& bio) {
362
503
  CHECK(bio);
363
  BUF_MEM* bptr;
364
503
  BIO_get_mem_ptr(bio.get(), &bptr);
365
503
  char* data = MallocOpenSSL<char>(bptr->length);
366
503
  memcpy(data, bptr->data, bptr->length);
367
503
  return Allocated(data, bptr->length);
368
}
369
370
3111
ByteSource ByteSource::FromEncodedString(Environment* env,
371
                                         Local<String> key,
372
                                         enum encoding enc) {
373
3111
  size_t length = 0;
374
3111
  size_t actual = 0;
375
3111
  char* data = nullptr;
376
377

6222
  if (StringBytes::Size(env->isolate(), key, enc).To(&length) && length > 0) {
378
3111
    data = MallocOpenSSL<char>(length);
379
3111
    actual = StringBytes::Write(env->isolate(), data, length, key, enc);
380
381
3111
    CHECK(actual <= length);
382
383
3111
    if (actual == 0) {
384
      OPENSSL_clear_free(data, length);
385
      data = nullptr;
386
3111
    } else if (actual < length) {
387
      data = reinterpret_cast<char*>(OPENSSL_realloc(data, actual));
388
    }
389
  }
390
391
3111
  return Allocated(data, actual);
392
}
393
394
2266
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
395
                                          Local<Value> value) {
396
2266
  return IsAnyByteSource(value) ? FromBuffer(value)
397
2266
                                : FromString(env, value.As<String>());
398
}
399
400
24
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
401
                                  bool ntc) {
402
48
  CHECK(str->IsString());
403
24
  size_t size = str->Utf8Length(env->isolate());
404
24
  size_t alloc_size = ntc ? size + 1 : size;
405
24
  char* data = MallocOpenSSL<char>(alloc_size);
406
24
  int opts = String::NO_OPTIONS;
407
24
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
408
24
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
409
24
  return Allocated(data, size);
410
}
411
412
2268
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
413
4536
  ArrayBufferOrViewContents<char> buf(buffer);
414
2268
  return ntc ? buf.ToNullTerminatedCopy() : buf.ToByteSource();
415
}
416
417
1147
ByteSource ByteSource::FromSecretKeyBytes(
418
    Environment* env,
419
    Local<Value> value) {
420
  // A key can be passed as a string, buffer or KeyObject with type 'secret'.
421
  // If it is a string, we need to convert it to a buffer. We are not doing that
422
  // in JS to avoid creating an unprotected copy on the heap.
423

2294
  return value->IsString() || IsAnyByteSource(value) ?
424
           ByteSource::FromStringOrBuffer(env, value) :
425
1147
           ByteSource::FromSymmetricKeyObjectHandle(value);
426
}
427
428
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
429
                                          Local<Value> value) {
430
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
431
                                    : FromString(env, value.As<String>(), true);
432
}
433
434
14
ByteSource ByteSource::FromSymmetricKeyObjectHandle(Local<Value> handle) {
435
14
  CHECK(handle->IsObject());
436
14
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(handle.As<Object>());
437
14
  CHECK_NOT_NULL(key);
438
14
  return Foreign(key->Data()->GetSymmetricKey(),
439
28
                 key->Data()->GetSymmetricKeySize());
440
}
441
442
21307
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
443
    : data_(data),
444
      allocated_data_(allocated_data),
445
21307
      size_(size) {}
446
447
16642
ByteSource ByteSource::Allocated(char* data, size_t size) {
448
16642
  return ByteSource(data, data, size);
449
}
450
451
4665
ByteSource ByteSource::Foreign(const char* data, size_t size) {
452
4665
  return ByteSource(data, nullptr, size);
453
}
454
455
namespace error {
456
100
Maybe<bool> Decorate(Environment* env, Local<Object> obj,
457
              unsigned long err) {  // NOLINT(runtime/int)
458
100
  if (err == 0) return Just(true);  // No decoration necessary.
459
460
89
  const char* ls = ERR_lib_error_string(err);
461
89
  const char* fs = ERR_func_error_string(err);
462
89
  const char* rs = ERR_reason_error_string(err);
463
464
89
  Isolate* isolate = env->isolate();
465
89
  Local<Context> context = isolate->GetCurrentContext();
466
467
89
  if (ls != nullptr) {
468
178
    if (obj->Set(context, env->library_string(),
469
356
                 OneByteString(isolate, ls)).IsNothing()) {
470
1
      return Nothing<bool>();
471
    }
472
  }
473
88
  if (fs != nullptr) {
474
    if (obj->Set(context, env->function_string(),
475
                 OneByteString(isolate, fs)).IsNothing()) {
476
      return Nothing<bool>();
477
    }
478
  }
479
88
  if (rs != nullptr) {
480
176
    if (obj->Set(context, env->reason_string(),
481
352
                 OneByteString(isolate, rs)).IsNothing()) {
482
      return Nothing<bool>();
483
    }
484
485
    // SSL has no API to recover the error name from the number, so we
486
    // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
487
    // which ends up being close to the original error macro name.
488
88
    std::string reason(rs);
489
490
1675
    for (auto& c : reason) {
491
1587
      if (c == ' ')
492
173
        c = '_';
493
      else
494
1414
        c = ToUpper(c);
495
    }
496
497
#define OSSL_ERROR_CODES_MAP(V)                                               \
498
    V(SYS)                                                                    \
499
    V(BN)                                                                     \
500
    V(RSA)                                                                    \
501
    V(DH)                                                                     \
502
    V(EVP)                                                                    \
503
    V(BUF)                                                                    \
504
    V(OBJ)                                                                    \
505
    V(PEM)                                                                    \
506
    V(DSA)                                                                    \
507
    V(X509)                                                                   \
508
    V(ASN1)                                                                   \
509
    V(CONF)                                                                   \
510
    V(CRYPTO)                                                                 \
511
    V(EC)                                                                     \
512
    V(SSL)                                                                    \
513
    V(BIO)                                                                    \
514
    V(PKCS7)                                                                  \
515
    V(X509V3)                                                                 \
516
    V(PKCS12)                                                                 \
517
    V(RAND)                                                                   \
518
    V(DSO)                                                                    \
519
    V(ENGINE)                                                                 \
520
    V(OCSP)                                                                   \
521
    V(UI)                                                                     \
522
    V(COMP)                                                                   \
523
    V(ECDSA)                                                                  \
524
    V(ECDH)                                                                   \
525
    V(OSSL_STORE)                                                             \
526
    V(FIPS)                                                                   \
527
    V(CMS)                                                                    \
528
    V(TS)                                                                     \
529
    V(HMAC)                                                                   \
530
    V(CT)                                                                     \
531
    V(ASYNC)                                                                  \
532
    V(KDF)                                                                    \
533
    V(SM2)                                                                    \
534
    V(USER)                                                                   \
535
536
#define V(name) case ERR_LIB_##name: lib = #name "_"; break;
537
88
    const char* lib = "";
538
88
    const char* prefix = "OSSL_";
539









88
    switch (ERR_GET_LIB(err)) { OSSL_ERROR_CODES_MAP(V) }
540
#undef V
541
#undef OSSL_ERROR_CODES_MAP
542
    // Don't generate codes like "ERR_OSSL_SSL_".
543

88
    if (lib && strcmp(lib, "SSL_") == 0)
544
6
      prefix = "";
545
546
    // All OpenSSL reason strings fit in a single 80-column macro definition,
547
    // all prefix lengths are <= 10, and ERR_OSSL_ is 9, so 128 is more than
548
    // sufficient.
549
    char code[128];
550
88
    snprintf(code, sizeof(code), "ERR_%s%s%s", prefix, lib, reason.c_str());
551
552
176
    if (obj->Set(env->isolate()->GetCurrentContext(),
553
             env->code_string(),
554
352
             OneByteString(env->isolate(), code)).IsNothing())
555
      return Nothing<bool>();
556
  }
557
558
88
  return Just(true);
559
}
560
}  // namespace error
561
562
100
void ThrowCryptoError(Environment* env,
563
                      unsigned long err,  // NOLINT(runtime/int)
564
                      // Default, only used if there is no SSL `err` which can
565
                      // be used to create a long-style message string.
566
                      const char* message) {
567
100
  char message_buffer[128] = {0};
568

100
  if (err != 0 || message == nullptr) {
569
89
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
570
89
    message = message_buffer;
571
  }
572
100
  HandleScope scope(env->isolate());
573
  Local<String> exception_string;
574
  Local<Value> exception;
575
  Local<Object> obj;
576
200
  if (!String::NewFromUtf8(env->isolate(), message).ToLocal(&exception_string))
577
    return;
578
100
  CryptoErrorStore errors;
579
100
  errors.Capture();
580
100
  if (!errors.ToException(env, exception_string).ToLocal(&exception) ||
581

400
      !exception->ToObject(env->context()).ToLocal(&obj) ||
582

300
      error::Decorate(env, obj, err).IsNothing()) {
583
1
    return;
584
  }
585
99
  env->isolate()->ThrowException(exception);
586
}
587
588
#ifndef OPENSSL_NO_ENGINE
589
14
EnginePointer LoadEngineById(const char* id, CryptoErrorStore* errors) {
590
28
  MarkPopErrorOnReturn mark_pop_error_on_return;
591
592
14
  EnginePointer engine(ENGINE_by_id(id));
593
14
  if (!engine) {
594
    // Engine not found, try loading dynamically.
595
2
    engine = EnginePointer(ENGINE_by_id("dynamic"));
596
2
    if (engine) {
597

4
      if (!ENGINE_ctrl_cmd_string(engine.get(), "SO_PATH", id, 0) ||
598
2
          !ENGINE_ctrl_cmd_string(engine.get(), "LOAD", nullptr, 0)) {
599
2
        engine.reset();
600
      }
601
    }
602
  }
603
604

14
  if (!engine && errors != nullptr) {
605
    if (ERR_get_error() != 0) {
606
      errors->Capture();
607
    } else {
608
      errors->Insert(NodeCryptoError::ENGINE_NOT_FOUND, id);
609
    }
610
  }
611
612
14
  return engine;
613
}
614
615
14
bool SetEngine(const char* id, uint32_t flags, CryptoErrorStore* errors) {
616
14
  ClearErrorOnReturn clear_error_on_return;
617
28
  EnginePointer engine = LoadEngineById(id, errors);
618
14
  if (!engine)
619
2
    return false;
620
621
12
  if (!ENGINE_set_default(engine.get(), flags)) {
622
    if (errors != nullptr)
623
      errors->Capture();
624
    return false;
625
  }
626
627
12
  return true;
628
}
629
630
14
void SetEngine(const FunctionCallbackInfo<Value>& args) {
631
14
  Environment* env = Environment::GetCurrent(args);
632

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