GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/crypto/crypto_util.cc Lines: 291 329 88.4 %
Date: 2021-05-31 04:11:52 Branches: 132 240 55.0 %

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
#ifdef OPENSSL_FIPS
18
#if OPENSSL_VERSION_MAJOR >= 3
19
#include "openssl/provider.h"
20
#endif
21
#endif
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::Uint32;
42
using v8::Uint8Array;
43
using v8::Value;
44
45
namespace crypto {
46
2146
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
2146
  return 1;
61
}
62
63
15727
void CheckEntropy() {
64
  for (;;) {
65
15727
    int status = RAND_status();
66
15727
    CHECK_GE(status, 0);  // Cannot fail.
67
15727
    if (status != 0)
68
31454
      break;
69
70
    // Give up, RAND_poll() not supported.
71
    if (RAND_poll() == 0)
72
      break;
73
  }
74
15727
}
75
76
15331
bool EntropySource(unsigned char* buffer, size_t length) {
77
  // Ensure that OpenSSL's PRNG is properly seeded.
78
15331
  CheckEntropy();
79
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
80
  // random. That's okay, it's still better than V8's stock source of entropy,
81
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
82
15331
  return RAND_bytes(buffer, length) != -1;
83
}
84
85
103
int PasswordCallback(char* buf, int size, int rwflag, void* u) {
86
103
  const ByteSource* passphrase = *static_cast<const ByteSource**>(u);
87
103
  if (passphrase != nullptr) {
88
92
    size_t buflen = static_cast<size_t>(size);
89
92
    size_t len = passphrase->size();
90
92
    if (buflen < len)
91
1
      return -1;
92
91
    memcpy(buf, passphrase->get(), len);
93
91
    return len;
94
  }
95
96
11
  return -1;
97
}
98
99
// This callback is used to avoid the default passphrase callback in OpenSSL
100
// which will typically prompt for the passphrase. The prompting is designed
101
// for the OpenSSL CLI, but works poorly for Node.js because it involves
102
// synchronous interaction with the controlling terminal, something we never
103
// want, and use this function to avoid it.
104
int NoPasswordCallback(char* buf, int size, int rwflag, void* u) {
105
  return 0;
106
}
107
108
4071
void InitCryptoOnce() {
109
#ifndef OPENSSL_IS_BORINGSSL
110
4071
  OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
111
112
#if OPENSSL_VERSION_MAJOR < 3
113
  // --openssl-config=...
114
4071
  if (!per_process::cli_options->openssl_config.empty()) {
115
7
    const char* conf = per_process::cli_options->openssl_config.c_str();
116
7
    OPENSSL_INIT_set_config_filename(settings, conf);
117
  }
118
#endif
119
120
4071
  OPENSSL_init_ssl(0, settings);
121
4071
  OPENSSL_INIT_free(settings);
122
4071
  settings = nullptr;
123
#endif
124
125
#ifndef _WIN32
126
4071
  if (per_process::cli_options->secure_heap != 0) {
127

2
    switch (CRYPTO_secure_malloc_init(
128
1
                per_process::cli_options->secure_heap,
129
1
                static_cast<int>(per_process::cli_options->secure_heap_min))) {
130
      case 0:
131
        fprintf(stderr, "Unable to initialize openssl secure heap.\n");
132
        break;
133
      case 2:
134
        // Not a fatal error but worthy of a warning.
135
        fprintf(stderr, "Unable to memory map openssl secure heap.\n");
136
        break;
137
      case 1:
138
        // OK!
139
1
        break;
140
    }
141
  }
142
#endif
143
144
  /* Override FIPS settings in cnf file, if needed. */
145
4071
  unsigned long err = 0;  // NOLINT(runtime/int)
146

8136
  if (per_process::cli_options->enable_fips_crypto ||
147
4065
      per_process::cli_options->force_fips_crypto) {
148
#if OPENSSL_VERSION_MAJOR >= 3
149
    if (0 == EVP_default_properties_is_fips_enabled(nullptr) &&
150
        !EVP_default_properties_enable_fips(nullptr, 1)) {
151
#else
152

11
    if (0 == FIPS_mode() && !FIPS_mode_set(1)) {
153
#endif
154
11
      err = ERR_get_error();
155
    }
156
  }
157
4071
  if (0 != err) {
158
11
    auto* isolate = Isolate::GetCurrent();
159
11
    auto* env = Environment::GetCurrent(isolate);
160
11
    return ThrowCryptoError(env, err);
161
  }
162
163
  // Turn off compression. Saves memory and protects against CRIME attacks.
164
  // No-op with OPENSSL_NO_COMP builds of OpenSSL.
165
4060
  sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
166
167
#ifndef OPENSSL_NO_ENGINE
168
4060
  ERR_load_ENGINE_strings();
169
4060
  ENGINE_load_builtin_engines();
170
#endif  // !OPENSSL_NO_ENGINE
171
172
4060
  NodeBIO::GetMethod();
173
}
174
175
416
void GetFipsCrypto(const FunctionCallbackInfo<Value>& args) {
176
#if OPENSSL_VERSION_MAJOR >= 3
177
  args.GetReturnValue().Set(EVP_default_properties_is_fips_enabled(nullptr) ?
178
      1 : 0);
179
#else
180
1248
  args.GetReturnValue().Set(FIPS_mode() ? 1 : 0);
181
#endif
182
416
}
183
184
4
void SetFipsCrypto(const FunctionCallbackInfo<Value>& args) {
185
4
  CHECK(!per_process::cli_options->force_fips_crypto);
186
4
  Environment* env = Environment::GetCurrent(args);
187
12
  bool enable = args[0]->BooleanValue(env->isolate());
188
189
#if OPENSSL_VERSION_MAJOR >= 3
190
  if (enable == EVP_default_properties_is_fips_enabled(nullptr))
191
#else
192
4
  if (enable == FIPS_mode())
193
#endif
194
1
    return;  // No action needed.
195
196
#if OPENSSL_VERSION_MAJOR >= 3
197
  if (!EVP_default_properties_enable_fips(nullptr, enable)) {
198
#else
199
3
  if (!FIPS_mode_set(enable)) {
200
#endif
201
3
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
202
3
    return ThrowCryptoError(env, err);
203
  }
204
}
205
206
29
void TestFipsCrypto(const v8::FunctionCallbackInfo<v8::Value>& args) {
207
#ifdef OPENSSL_FIPS
208
#if OPENSSL_VERSION_MAJOR >= 3
209
  OSSL_PROVIDER* fips_provider = nullptr;
210
  if (OSSL_PROVIDER_available(nullptr, "fips")) {
211
    fips_provider = OSSL_PROVIDER_load(nullptr, "fips");
212
  }
213
  const auto enabled = fips_provider == nullptr ? 0 :
214
      OSSL_PROVIDER_self_test(fips_provider) ? 1 : 0;
215
#else
216
  const auto enabled = FIPS_selftest() ? 1 : 0;
217
#endif
218
#else  // OPENSSL_FIPS
219
29
  const auto enabled = 0;
220
#endif  // OPENSSL_FIPS
221
222
58
  args.GetReturnValue().Set(enabled);
223
29
}
224
225
116
void CryptoErrorStore::Capture() {
226
116
  errors_.clear();
227
171
  while (const uint32_t err = ERR_get_error()) {
228
    char buf[256];
229
55
    ERR_error_string_n(err, buf, sizeof(buf));
230
55
    errors_.emplace_back(buf);
231
55
  }
232
116
  std::reverse(std::begin(errors_), std::end(errors_));
233
116
}
234
235
2965
bool CryptoErrorStore::Empty() const {
236
2965
  return errors_.empty();
237
}
238
239
134
MaybeLocal<Value> CryptoErrorStore::ToException(
240
    Environment* env,
241
    Local<String> exception_string) const {
242
134
  if (exception_string.IsEmpty()) {
243
36
    CryptoErrorStore copy(*this);
244
18
    if (copy.Empty()) {
245
      // But possibly a bug...
246
      copy.Insert(NodeCryptoError::OK);
247
    }
248
    // Use last element as the error message, everything else goes
249
    // into the .opensslErrorStack property on the exception object.
250
18
    const std::string& last_error_string = copy.errors_.back();
251
    Local<String> exception_string;
252
36
    if (!String::NewFromUtf8(
253
            env->isolate(),
254
            last_error_string.data(),
255
            NewStringType::kNormal,
256
36
            last_error_string.size()).ToLocal(&exception_string)) {
257
      return MaybeLocal<Value>();
258
    }
259
18
    copy.errors_.pop_back();
260
18
    return copy.ToException(env, exception_string);
261
  }
262
263
116
  Local<Value> exception_v = Exception::Error(exception_string);
264
116
  CHECK(!exception_v.IsEmpty());
265
266
116
  if (!Empty()) {
267
25
    CHECK(exception_v->IsObject());
268
25
    Local<Object> exception = exception_v.As<Object>();
269
    Local<Value> stack;
270

100
    if (!ToV8Value(env->context(), errors_).ToLocal(&stack) ||
271
100
        exception->Set(env->context(), env->openssl_error_stack(), stack)
272
25
            .IsNothing()) {
273
1
      return MaybeLocal<Value>();
274
    }
275
  }
276
277
115
  return exception_v;
278
}
279
280
10852
ByteSource::ByteSource(ByteSource&& other) noexcept
281
10852
    : data_(other.data_),
282
10852
      allocated_data_(other.allocated_data_),
283
21704
      size_(other.size_) {
284
10852
  other.allocated_data_ = nullptr;
285
10852
}
286
287
80928
ByteSource::~ByteSource() {
288
40465
  OPENSSL_clear_free(allocated_data_, size_);
289
40463
}
290
291
void ByteSource::reset() {
292
  OPENSSL_clear_free(allocated_data_, size_);
293
  data_ = nullptr;
294
  size_ = 0;
295
}
296
297
9222
ByteSource& ByteSource::operator=(ByteSource&& other) noexcept {
298
9222
  if (&other != this) {
299
9222
    OPENSSL_clear_free(allocated_data_, size_);
300
9222
    data_ = other.data_;
301
9222
    allocated_data_ = other.allocated_data_;
302
9222
    other.allocated_data_ = nullptr;
303
9222
    size_ = other.size_;
304
  }
305
9222
  return *this;
306
}
307
308
1677
std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() {
309
  // It's ok for allocated_data_ to be nullptr but
310
  // only if size_ is zero.
311

1677
  CHECK_IMPLIES(size_ > 0, allocated_data_ != nullptr);
312
  std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore(
313
1677
      allocated_data_,
314
      size(),
315
5027
      [](void* data, size_t length, void* deleter_data) {
316
1675
        OPENSSL_clear_free(deleter_data, length);
317
8381
      }, allocated_data_);
318
1677
  CHECK(ptr);
319
1677
  allocated_data_ = nullptr;
320
1677
  data_ = nullptr;
321
1677
  size_ = 0;
322
1677
  return ptr;
323
}
324
325
1677
Local<ArrayBuffer> ByteSource::ToArrayBuffer(Environment* env) {
326
3354
  std::unique_ptr<BackingStore> store = ReleaseToBackingStore();
327
3354
  return ArrayBuffer::New(env->isolate(), std::move(store));
328
}
329
330
13753
const char* ByteSource::get() const {
331
13753
  return data_;
332
}
333
334
13509
size_t ByteSource::size() const {
335
13509
  return size_;
336
}
337
338
224
ByteSource ByteSource::FromBIO(const BIOPointer& bio) {
339
224
  CHECK(bio);
340
  BUF_MEM* bptr;
341
224
  BIO_get_mem_ptr(bio.get(), &bptr);
342
224
  char* data = MallocOpenSSL<char>(bptr->length);
343
224
  memcpy(data, bptr->data, bptr->length);
344
224
  return Allocated(data, bptr->length);
345
}
346
347
1139
ByteSource ByteSource::FromEncodedString(Environment* env,
348
                                         Local<String> key,
349
                                         enum encoding enc) {
350
1139
  size_t length = 0;
351
1139
  size_t actual = 0;
352
1139
  char* data = nullptr;
353
354

2278
  if (StringBytes::Size(env->isolate(), key, enc).To(&length) && length > 0) {
355
1139
    data = MallocOpenSSL<char>(length);
356
1139
    actual = StringBytes::Write(env->isolate(), data, length, key, enc);
357
358
1139
    CHECK(actual <= length);
359
360
1139
    if (actual == 0) {
361
      OPENSSL_clear_free(data, length);
362
      data = nullptr;
363
1139
    } else if (actual < length) {
364
      data = reinterpret_cast<char*>(OPENSSL_realloc(data, actual));
365
    }
366
  }
367
368
1139
  return Allocated(data, actual);
369
}
370
371
1857
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
372
                                          Local<Value> value) {
373
1857
  return IsAnyByteSource(value) ? FromBuffer(value)
374
1857
                                : FromString(env, value.As<String>());
375
}
376
377
24
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
378
                                  bool ntc) {
379
48
  CHECK(str->IsString());
380
48
  size_t size = str->Utf8Length(env->isolate());
381
24
  size_t alloc_size = ntc ? size + 1 : size;
382
24
  char* data = MallocOpenSSL<char>(alloc_size);
383
24
  int opts = String::NO_OPTIONS;
384
24
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
385
48
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
386
24
  return Allocated(data, size);
387
}
388
389
1859
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
390
3718
  ArrayBufferOrViewContents<char> buf(buffer);
391
3718
  return ntc ? buf.ToNullTerminatedCopy() : buf.ToByteSource();
392
}
393
394
1348
ByteSource ByteSource::FromSecretKeyBytes(
395
    Environment* env,
396
    Local<Value> value) {
397
  // A key can be passed as a string, buffer or KeyObject with type 'secret'.
398
  // If it is a string, we need to convert it to a buffer. We are not doing that
399
  // in JS to avoid creating an unprotected copy on the heap.
400

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









83
    switch (ERR_GET_LIB(err)) { OSSL_ERROR_CODES_MAP(V) }
517
16
#undef V
518
#undef OSSL_ERROR_CODES_MAP
519
2
    // Don't generate codes like "ERR_OSSL_SSL_".
520

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

98
  if (err != 0 || message == nullptr) {
546
85
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
547
85
    message = message_buffer;
548
  }
549
194
  HandleScope scope(env->isolate());
550
  Local<String> exception_string;
551
  Local<Value> exception;
552
  Local<Object> obj;
553
196
  if (!String::NewFromUtf8(env->isolate(), message).ToLocal(&exception_string))
554
    return;
555
194
  CryptoErrorStore errors;
556
98
  errors.Capture();
557

489
  if (!errors.ToException(env, exception_string).ToLocal(&exception) ||
558

487
      !exception->ToObject(env->context()).ToLocal(&obj) ||
559
292
      error::Decorate(env, obj, err).IsNothing()) {
560
2
    return;
561
  }
562
96
  env->isolate()->ThrowException(exception);
563
}
564
565
#ifndef OPENSSL_NO_ENGINE
566
2
EnginePointer LoadEngineById(const char* id, CryptoErrorStore* errors) {
567
4
  MarkPopErrorOnReturn mark_pop_error_on_return;
568
569
2
  EnginePointer engine(ENGINE_by_id(id));
570
2
  if (!engine) {
571
    // Engine not found, try loading dynamically.
572
2
    engine = EnginePointer(ENGINE_by_id("dynamic"));
573
2
    if (engine) {
574

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

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

8
  CHECK(args.Length() >= 2 && args[0]->IsString());
610
  uint32_t flags;
611
8
  if (!args[1]->Uint32Value(env->context()).To(&flags)) return;
612
613
4
  const node::Utf8Value engine_id(env->isolate(), args[0]);
614
615
6
  args.GetReturnValue().Set(SetEngine(*engine_id, flags));
616
}
617
#endif  // !OPENSSL_NO_ENGINE
618
619
967
MaybeLocal<Value> EncodeBignum(
620
    Environment* env,
621
    const BIGNUM* bn,
622
    int size,
623
    Local<Value>* error) {
624
1934
  std::vector<uint8_t> buf(size);
625
967
  CHECK_EQ(BN_bn2binpad(bn, buf.data(), size), size);
626
  return StringBytes::Encode(
627
      env->isolate(),
628
967
      reinterpret_cast<const char*>(buf.data()),
629
      buf.size(),
630
      BASE64URL,
631
2901
      error);
632
}
633
634
967
Maybe<bool> SetEncodedValue(
635
    Environment* env,
636
    Local<Object> target,
637
    Local<String> name,
638
    const BIGNUM* bn,
639
    int size) {
640
  Local<Value> value;
641
  Local<Value> error;
642
967
  CHECK_NOT_NULL(bn);
643
967
  if (size == 0)
644
746
    size = BN_num_bytes(bn);
645
1934
  if (!EncodeBignum(env, bn, size, &error).ToLocal(&value)) {
646
    if (!error.IsEmpty())
647
      env->isolate()->ThrowException(error);
648
    return Nothing<bool>();
649
  }
650
1934
  return target->Set(env->context(), name, value);
651
}
652
653
3072
CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args) {
654
3072
  CHECK(args->IsUint32());
655
6144
  uint32_t mode = args.As<v8::Uint32>()->Value();
656
3072
  CHECK_LE(mode, kCryptoJobSync);
657
3072
  return static_cast<CryptoJobMode>(mode);
658
}
659
660
namespace {
661
// SecureBuffer uses openssl to allocate a Uint8Array using
662
// OPENSSL_secure_malloc. Because we do not yet actually
663
// make use of secure heap, this has the same semantics as
664
// using OPENSSL_malloc. However, if the secure heap is
665
// initialized, SecureBuffer will automatically use it.
666
2
void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
667
4
  CHECK(args[0]->IsUint32());
668
2
  Environment* env = Environment::GetCurrent(args);
669
6
  uint32_t len = args[0].As<Uint32>()->Value();
670
2
  char* data = static_cast<char*>(OPENSSL_secure_malloc(len));
671
2
  if (data == nullptr) {
672
    // There's no memory available for the allocation.
673
    // Return nothing.
674
    return;
675
  }
676
2
  memset(data, 0, len);
677
  std::shared_ptr<BackingStore> store =
678
4
      ArrayBuffer::NewBackingStore(
679
          data,
680
          len,
681
6
          [](void* data, size_t len, void* deleter_data) {
682
2
            OPENSSL_secure_clear_free(data, len);
683
6
          },
684
4
          data);
685
2
  Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store);
686
6
  args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len));
687
}
688
689
4
void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) {
690
4
  Environment* env = Environment::GetCurrent(args);
691
4
  if (CRYPTO_secure_malloc_initialized())
692
12
    args.GetReturnValue().Set(
693
4
        BigInt::New(env->isolate(), CRYPTO_secure_used()));
694
4
}
695
}  // namespace
696
697
namespace Util {
698
4165
void Initialize(Environment* env, Local<Object> target) {
699
#ifndef OPENSSL_NO_ENGINE
700
4165
  env->SetMethod(target, "setEngine", SetEngine);
701
#endif  // !OPENSSL_NO_ENGINE
702
703
4165
  env->SetMethodNoSideEffect(target, "getFipsCrypto", GetFipsCrypto);
704
4165
  env->SetMethod(target, "setFipsCrypto", SetFipsCrypto);
705
4165
  env->SetMethodNoSideEffect(target, "testFipsCrypto", TestFipsCrypto);
706
707
16660
  NODE_DEFINE_CONSTANT(target, kCryptoJobAsync);
708
4165
  NODE_DEFINE_CONSTANT(target, kCryptoJobSync);
709
8330
710
8330
  env->SetMethod(target, "secureBuffer", SecureBuffer);
711
24990
  env->SetMethod(target, "secureHeapUsed", SecureHeapUsed);
712
12495
}
713
}  // namespace Util
714
715
}  // namespace crypto
716

14520
}  // namespace node