GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_util.cc Lines: 291 344 84.6 %
Date: 2022-12-31 04:22:30 Branches: 123 244 50.4 %

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

11467
  if (per_process::cli_options->enable_fips_crypto ||
99
5733
      per_process::cli_options->force_fips_crypto) {
100
#if OPENSSL_VERSION_MAJOR >= 3
101
2
    OSSL_PROVIDER* fips_provider = OSSL_PROVIDER_load(nullptr, "fips");
102
2
    if (fips_provider == nullptr)
103
2
      return false;
104
    OSSL_PROVIDER_unload(fips_provider);
105
106
    return EVP_default_properties_enable_fips(nullptr, 1) &&
107
           EVP_default_properties_is_fips_enabled(nullptr);
108
#else
109
    return FIPS_mode() == 0 && FIPS_mode_set(1);
110
#endif
111
  }
112
5732
  return true;
113
}
114
115
10775
bool InitCryptoOnce(Isolate* isolate) {
116
  static uv_once_t init_once = UV_ONCE_INIT;
117
21550
  TryCatch try_catch{isolate};
118
10775
  uv_once(&init_once, InitCryptoOnce);
119

10775
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
120
    try_catch.ReThrow();
121
    return false;
122
  }
123
10775
  return true;
124
}
125
126
// Protect accesses to FIPS state with a mutex. This should potentially
127
// be part of a larger mutex for global OpenSSL state.
128
static Mutex fips_mutex;
129
130
5714
void InitCryptoOnce() {
131
11428
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
132
11428
  Mutex::ScopedLock fips_lock(fips_mutex);
133
#ifndef OPENSSL_IS_BORINGSSL
134
5714
  OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
135
136
#if OPENSSL_VERSION_MAJOR < 3
137
  // --openssl-config=...
138
  if (!per_process::cli_options->openssl_config.empty()) {
139
    const char* conf = per_process::cli_options->openssl_config.c_str();
140
    OPENSSL_INIT_set_config_filename(settings, conf);
141
  }
142
#endif
143
144
#if OPENSSL_VERSION_MAJOR >= 3
145
  // --openssl-legacy-provider
146
5714
  if (per_process::cli_options->openssl_legacy_provider) {
147
1
    OSSL_PROVIDER* legacy_provider = OSSL_PROVIDER_load(nullptr, "legacy");
148
1
    if (legacy_provider == nullptr) {
149
      fprintf(stderr, "Unable to load legacy provider.\n");
150
    }
151
  }
152
#endif
153
154
5714
  OPENSSL_init_ssl(0, settings);
155
5714
  OPENSSL_INIT_free(settings);
156
5714
  settings = nullptr;
157
158
#ifndef _WIN32
159
5714
  if (per_process::cli_options->secure_heap != 0) {
160

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

5788
  CHECK_IMPLIES(size_ > 0, allocated_data_ != nullptr);
330
  std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore(
331
      allocated_data_,
332
      size(),
333
5783
      [](void* data, size_t length, void* deleter_data) {
334
5783
        OPENSSL_clear_free(deleter_data, length);
335
5788
      }, allocated_data_);
336
5788
  CHECK(ptr);
337
5788
  allocated_data_ = nullptr;
338
5788
  data_ = nullptr;
339
5788
  size_ = 0;
340
5788
  return ptr;
341
}
342
343
5788
Local<ArrayBuffer> ByteSource::ToArrayBuffer(Environment* env) {
344
5788
  std::unique_ptr<BackingStore> store = ReleaseToBackingStore();
345
5788
  return ArrayBuffer::New(env->isolate(), std::move(store));
346
}
347
348
17
MaybeLocal<Uint8Array> ByteSource::ToBuffer(Environment* env) {
349
17
  Local<ArrayBuffer> ab = ToArrayBuffer(env);
350
17
  return Buffer::New(env, ab, 0, ab->ByteLength());
351
}
352
353
556
ByteSource ByteSource::FromBIO(const BIOPointer& bio) {
354
556
  CHECK(bio);
355
  BUF_MEM* bptr;
356
556
  BIO_get_mem_ptr(bio.get(), &bptr);
357
556
  ByteSource::Builder out(bptr->length);
358
556
  memcpy(out.data<void>(), bptr->data, bptr->length);
359
556
  return std::move(out).release();
360
}
361
362
3116
ByteSource ByteSource::FromEncodedString(Environment* env,
363
                                         Local<String> key,
364
                                         enum encoding enc) {
365
3116
  size_t length = 0;
366
3116
  ByteSource out;
367
368

6232
  if (StringBytes::Size(env->isolate(), key, enc).To(&length) && length > 0) {
369
3116
    ByteSource::Builder buf(length);
370
    size_t actual =
371
3116
        StringBytes::Write(env->isolate(), buf.data<char>(), length, key, enc);
372
3116
    out = std::move(buf).release(actual);
373
  }
374
375
3116
  return out;
376
}
377
378
2755
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
379
                                          Local<Value> value) {
380
2755
  return IsAnyByteSource(value) ? FromBuffer(value)
381
2755
                                : FromString(env, value.As<String>());
382
}
383
384
24
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
385
                                  bool ntc) {
386
48
  CHECK(str->IsString());
387
24
  size_t size = str->Utf8Length(env->isolate());
388
24
  size_t alloc_size = ntc ? size + 1 : size;
389
24
  ByteSource::Builder out(alloc_size);
390
24
  int opts = String::NO_OPTIONS;
391
24
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
392
24
  str->WriteUtf8(env->isolate(), out.data<char>(), alloc_size, nullptr, opts);
393
24
  return std::move(out).release();
394
}
395
396
2757
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
397
2757
  ArrayBufferOrViewContents<char> buf(buffer);
398
2757
  return ntc ? buf.ToNullTerminatedCopy() : buf.ToByteSource();
399
}
400
401
1561
ByteSource ByteSource::FromSecretKeyBytes(
402
    Environment* env,
403
    Local<Value> value) {
404
  // A key can be passed as a string, buffer or KeyObject with type 'secret'.
405
  // If it is a string, we need to convert it to a buffer. We are not doing that
406
  // in JS to avoid creating an unprotected copy on the heap.
407

3122
  return value->IsString() || IsAnyByteSource(value) ?
408
           ByteSource::FromStringOrBuffer(env, value) :
409
1561
           ByteSource::FromSymmetricKeyObjectHandle(value);
410
}
411
412
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
413
                                          Local<Value> value) {
414
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
415
                                    : FromString(env, value.As<String>(), true);
416
}
417
418
15
ByteSource ByteSource::FromSymmetricKeyObjectHandle(Local<Value> handle) {
419
15
  CHECK(handle->IsObject());
420
15
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(handle.As<Object>());
421
15
  CHECK_NOT_NULL(key);
422
15
  return Foreign(key->Data()->GetSymmetricKey(),
423
30
                 key->Data()->GetSymmetricKeySize());
424
}
425
426
26665
ByteSource ByteSource::Allocated(void* data, size_t size) {
427
26665
  return ByteSource(data, data, size);
428
}
429
430
5365
ByteSource ByteSource::Foreign(const void* data, size_t size) {
431
5365
  return ByteSource(data, nullptr, size);
432
}
433
434
namespace error {
435
147
Maybe<bool> Decorate(Environment* env, Local<Object> obj,
436
              unsigned long err) {  // NOLINT(runtime/int)
437
147
  if (err == 0) return Just(true);  // No decoration necessary.
438
439
135
  const char* ls = ERR_lib_error_string(err);
440
135
  const char* fs = ERR_func_error_string(err);
441
135
  const char* rs = ERR_reason_error_string(err);
442
443
135
  Isolate* isolate = env->isolate();
444
135
  Local<Context> context = isolate->GetCurrentContext();
445
446
135
  if (ls != nullptr) {
447
270
    if (obj->Set(context, env->library_string(),
448
540
                 OneByteString(isolate, ls)).IsNothing()) {
449
1
      return Nothing<bool>();
450
    }
451
  }
452
134
  if (fs != nullptr) {
453
    if (obj->Set(context, env->function_string(),
454
                 OneByteString(isolate, fs)).IsNothing()) {
455
      return Nothing<bool>();
456
    }
457
  }
458
134
  if (rs != nullptr) {
459
268
    if (obj->Set(context, env->reason_string(),
460
536
                 OneByteString(isolate, rs)).IsNothing()) {
461
      return Nothing<bool>();
462
    }
463
464
    // SSL has no API to recover the error name from the number, so we
465
    // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
466
    // which ends up being close to the original error macro name.
467
134
    std::string reason(rs);
468
469
2318
    for (auto& c : reason) {
470
2184
      if (c == ' ')
471
243
        c = '_';
472
      else
473
1941
        c = ToUpper(c);
474
    }
475
476
#define OSSL_ERROR_CODES_MAP(V)                                               \
477
    V(SYS)                                                                    \
478
    V(BN)                                                                     \
479
    V(RSA)                                                                    \
480
    V(DH)                                                                     \
481
    V(EVP)                                                                    \
482
    V(BUF)                                                                    \
483
    V(OBJ)                                                                    \
484
    V(PEM)                                                                    \
485
    V(DSA)                                                                    \
486
    V(X509)                                                                   \
487
    V(ASN1)                                                                   \
488
    V(CONF)                                                                   \
489
    V(CRYPTO)                                                                 \
490
    V(EC)                                                                     \
491
    V(SSL)                                                                    \
492
    V(BIO)                                                                    \
493
    V(PKCS7)                                                                  \
494
    V(X509V3)                                                                 \
495
    V(PKCS12)                                                                 \
496
    V(RAND)                                                                   \
497
    V(DSO)                                                                    \
498
    V(ENGINE)                                                                 \
499
    V(OCSP)                                                                   \
500
    V(UI)                                                                     \
501
    V(COMP)                                                                   \
502
    V(ECDSA)                                                                  \
503
    V(ECDH)                                                                   \
504
    V(OSSL_STORE)                                                             \
505
    V(FIPS)                                                                   \
506
    V(CMS)                                                                    \
507
    V(TS)                                                                     \
508
    V(HMAC)                                                                   \
509
    V(CT)                                                                     \
510
    V(ASYNC)                                                                  \
511
    V(KDF)                                                                    \
512
    V(SM2)                                                                    \
513
    V(USER)                                                                   \
514
515
#define V(name) case ERR_LIB_##name: lib = #name "_"; break;
516
134
    const char* lib = "";
517
134
    const char* prefix = "OSSL_";
518









134
    switch (ERR_GET_LIB(err)) { OSSL_ERROR_CODES_MAP(V) }
519
#undef V
520
#undef OSSL_ERROR_CODES_MAP
521
    // Don't generate codes like "ERR_OSSL_SSL_".
522

134
    if (lib && strcmp(lib, "SSL_") == 0)
523
6
      prefix = "";
524
525
    // All OpenSSL reason strings fit in a single 80-column macro definition,
526
    // all prefix lengths are <= 10, and ERR_OSSL_ is 9, so 128 is more than
527
    // sufficient.
528
    char code[128];
529
134
    snprintf(code, sizeof(code), "ERR_%s%s%s", prefix, lib, reason.c_str());
530
531
268
    if (obj->Set(env->isolate()->GetCurrentContext(),
532
             env->code_string(),
533
536
             OneByteString(env->isolate(), code)).IsNothing())
534
      return Nothing<bool>();
535
  }
536
537
134
  return Just(true);
538
}
539
}  // namespace error
540
541
147
void ThrowCryptoError(Environment* env,
542
                      unsigned long err,  // NOLINT(runtime/int)
543
                      // Default, only used if there is no SSL `err` which can
544
                      // be used to create a long-style message string.
545
                      const char* message) {
546
147
  char message_buffer[128] = {0};
547

147
  if (err != 0 || message == nullptr) {
548
135
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
549
135
    message = message_buffer;
550
  }
551
147
  HandleScope scope(env->isolate());
552
  Local<String> exception_string;
553
  Local<Value> exception;
554
  Local<Object> obj;
555
294
  if (!String::NewFromUtf8(env->isolate(), message).ToLocal(&exception_string))
556
    return;
557
147
  CryptoErrorStore errors;
558
147
  errors.Capture();
559
147
  if (!errors.ToException(env, exception_string).ToLocal(&exception) ||
560

588
      !exception->ToObject(env->context()).ToLocal(&obj) ||
561

441
      error::Decorate(env, obj, err).IsNothing()) {
562
1
    return;
563
  }
564
146
  env->isolate()->ThrowException(exception);
565
}
566
567
#ifndef OPENSSL_NO_ENGINE
568
11
EnginePointer LoadEngineById(const char* id, CryptoErrorStore* errors) {
569
22
  MarkPopErrorOnReturn mark_pop_error_on_return;
570
571
11
  EnginePointer engine(ENGINE_by_id(id));
572
11
  if (!engine) {
573
    // Engine not found, try loading dynamically.
574
2
    engine = EnginePointer(ENGINE_by_id("dynamic"));
575
2
    if (engine) {
576

4
      if (!ENGINE_ctrl_cmd_string(engine.get(), "SO_PATH", id, 0) ||
577
2
          !ENGINE_ctrl_cmd_string(engine.get(), "LOAD", nullptr, 0)) {
578
2
        engine.reset();
579
      }
580
    }
581
  }
582
583

11
  if (!engine && errors != nullptr) {
584
    errors->Capture();
585
    if (errors->Empty()) {
586
      errors->Insert(NodeCryptoError::ENGINE_NOT_FOUND, id);
587
    }
588
  }
589
590
11
  return engine;
591
}
592
593
11
bool SetEngine(const char* id, uint32_t flags, CryptoErrorStore* errors) {
594
11
  ClearErrorOnReturn clear_error_on_return;
595
22
  EnginePointer engine = LoadEngineById(id, errors);
596
11
  if (!engine)
597
2
    return false;
598
599
9
  if (!ENGINE_set_default(engine.get(), flags)) {
600
    if (errors != nullptr)
601
      errors->Capture();
602
    return false;
603
  }
604
605
9
  return true;
606
}
607
608
11
void SetEngine(const FunctionCallbackInfo<Value>& args) {
609
11
  Environment* env = Environment::GetCurrent(args);
610

33
  CHECK(args.Length() >= 2 && args[0]->IsString());
611
  uint32_t flags;
612
22
  if (!args[1]->Uint32Value(env->context()).To(&flags)) return;
613
614
11
  const node::Utf8Value engine_id(env->isolate(), args[0]);
615
616
22
  args.GetReturnValue().Set(SetEngine(*engine_id, flags));
617
}
618
#endif  // !OPENSSL_NO_ENGINE
619
620
2595
MaybeLocal<Value> EncodeBignum(
621
    Environment* env,
622
    const BIGNUM* bn,
623
    int size,
624
    Local<Value>* error) {
625
5190
  std::vector<uint8_t> buf(size);
626
2595
  CHECK_EQ(BN_bn2binpad(bn, buf.data(), size), size);
627
  return StringBytes::Encode(
628
      env->isolate(),
629
2595
      reinterpret_cast<const char*>(buf.data()),
630
      buf.size(),
631
      BASE64URL,
632
5190
      error);
633
}
634
635
2595
Maybe<bool> SetEncodedValue(
636
    Environment* env,
637
    Local<Object> target,
638
    Local<String> name,
639
    const BIGNUM* bn,
640
    int size) {
641
  Local<Value> value;
642
  Local<Value> error;
643
2595
  CHECK_NOT_NULL(bn);
644
2595
  if (size == 0)
645
2086
    size = BN_num_bytes(bn);
646
5190
  if (!EncodeBignum(env, bn, size, &error).ToLocal(&value)) {
647
    if (!error.IsEmpty())
648
      env->isolate()->ThrowException(error);
649
    return Nothing<bool>();
650
  }
651
2595
  return target->Set(env->context(), name, value);
652
}
653
654
529
bool SetRsaOaepLabel(const EVPKeyCtxPointer& ctx, const ByteSource& label) {
655
529
  if (label.size() != 0) {
656
    // OpenSSL takes ownership of the label, so we need to create a copy.
657
248
    void* label_copy = OPENSSL_memdup(label.data(), label.size());
658
248
    CHECK_NOT_NULL(label_copy);
659
248
    int ret = EVP_PKEY_CTX_set0_rsa_oaep_label(
660
248
        ctx.get(), static_cast<unsigned char*>(label_copy), label.size());
661
248
    if (ret <= 0) {
662
      OPENSSL_free(label_copy);
663
      return false;
664
    }
665
  }
666
529
  return true;
667
}
668
669
9711
CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args) {
670
9711
  CHECK(args->IsUint32());
671
9711
  uint32_t mode = args.As<v8::Uint32>()->Value();
672
9711
  CHECK_LE(mode, kCryptoJobSync);
673
9711
  return static_cast<CryptoJobMode>(mode);
674
}
675
676
namespace {
677
// SecureBuffer uses OPENSSL_secure_malloc to allocate a Uint8Array.
678
// Without --secure-heap, OpenSSL's secure heap is disabled,
679
// in which case this has the same semantics as
680
// using OPENSSL_malloc. However, if the secure heap is
681
// initialized, SecureBuffer will automatically use it.
682
4
void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
683
4
  CHECK(args[0]->IsUint32());
684
4
  Environment* env = Environment::GetCurrent(args);
685
8
  uint32_t len = args[0].As<Uint32>()->Value();
686
4
  void* data = OPENSSL_secure_zalloc(len);
687
4
  if (data == nullptr) {
688
    // There's no memory available for the allocation.
689
    // Return nothing.
690
    return;
691
  }
692
  std::shared_ptr<BackingStore> store =
693
4
      ArrayBuffer::NewBackingStore(
694
          data,
695
          len,
696
4
          [](void* data, size_t len, void* deleter_data) {
697
4
            OPENSSL_secure_clear_free(data, len);
698
4
          },
699
4
          data);
700
4
  Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store);
701
8
  args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len));
702
}
703
704
4
void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) {
705
4
  Environment* env = Environment::GetCurrent(args);
706
4
  if (CRYPTO_secure_malloc_initialized())
707
8
    args.GetReturnValue().Set(
708
4
        BigInt::New(env->isolate(), CRYPTO_secure_used()));
709
4
}
710
}  // namespace
711
712
namespace Util {
713
5065
void Initialize(Environment* env, Local<Object> target) {
714
5065
  Local<Context> context = env->context();
715
#ifndef OPENSSL_NO_ENGINE
716
5065
  SetMethod(context, target, "setEngine", SetEngine);
717
#endif  // !OPENSSL_NO_ENGINE
718
719
5065
  SetMethodNoSideEffect(context, target, "getFipsCrypto", GetFipsCrypto);
720
5065
  SetMethod(context, target, "setFipsCrypto", SetFipsCrypto);
721
5065
  SetMethodNoSideEffect(context, target, "testFipsCrypto", TestFipsCrypto);
722
723
15195
  NODE_DEFINE_CONSTANT(target, kCryptoJobAsync);
724
10130
  NODE_DEFINE_CONSTANT(target, kCryptoJobSync);
725
726
5065
  SetMethod(context, target, "secureBuffer", SecureBuffer);
727
5065
  SetMethod(context, target, "secureHeapUsed", SecureHeapUsed);
728
5065
}
729
5718
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
730
#ifndef OPENSSL_NO_ENGINE
731
5718
  registry->Register(SetEngine);
732
#endif  // !OPENSSL_NO_ENGINE
733
734
5718
  registry->Register(GetFipsCrypto);
735
5718
  registry->Register(SetFipsCrypto);
736
5718
  registry->Register(TestFipsCrypto);
737
5718
  registry->Register(SecureBuffer);
738
5718
  registry->Register(SecureHeapUsed);
739
5718
}
740
741
}  // namespace Util
742
743
}  // namespace crypto
744
}  // namespace node