GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_crypto.cc Lines: 3334 3667 90.9 %
Date: 2020-06-24 22:13:30 Branches: 1743 2651 65.7 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_crypto.h"
23
#include "node_buffer.h"
24
#include "node_crypto_bio.h"
25
#include "node_crypto_common.h"
26
#include "node_crypto_clienthello-inl.h"
27
#include "node_crypto_groups.h"
28
#include "node_errors.h"
29
#include "node_mutex.h"
30
#include "node_process.h"
31
#include "allocated_buffer-inl.h"
32
#include "tls_wrap.h"  // TLSWrap
33
34
#include "async_wrap-inl.h"
35
#include "base_object-inl.h"
36
#include "env-inl.h"
37
#include "memory_tracker-inl.h"
38
#include "string_bytes.h"
39
#include "threadpoolwork-inl.h"
40
#include "util-inl.h"
41
#include "v8.h"
42
43
#include <openssl/ec.h>
44
#include <openssl/ecdh.h>
45
#ifndef OPENSSL_NO_ENGINE
46
# include <openssl/engine.h>
47
#endif  // !OPENSSL_NO_ENGINE
48
#include <openssl/evp.h>
49
#include <openssl/pem.h>
50
#include <openssl/x509v3.h>
51
#include <openssl/hmac.h>
52
#include <openssl/rand.h>
53
#include <openssl/pkcs12.h>
54
55
#include <cerrno>
56
#include <climits>  // INT_MAX
57
#include <cstring>
58
59
#include <algorithm>
60
#include <memory>
61
#include <utility>
62
#include <vector>
63
64
namespace node {
65
namespace crypto {
66
67
using node::THROW_ERR_TLS_INVALID_PROTOCOL_METHOD;
68
69
using v8::Array;
70
using v8::ArrayBufferView;
71
using v8::Boolean;
72
using v8::ConstructorBehavior;
73
using v8::Context;
74
using v8::DontDelete;
75
using v8::Exception;
76
using v8::External;
77
using v8::False;
78
using v8::Function;
79
using v8::FunctionCallback;
80
using v8::FunctionCallbackInfo;
81
using v8::FunctionTemplate;
82
using v8::HandleScope;
83
using v8::Int32;
84
using v8::Integer;
85
using v8::Isolate;
86
using v8::Just;
87
using v8::Local;
88
using v8::Maybe;
89
using v8::MaybeLocal;
90
using v8::NewStringType;
91
using v8::Nothing;
92
using v8::Null;
93
using v8::Object;
94
using v8::PropertyAttribute;
95
using v8::ReadOnly;
96
using v8::SideEffectType;
97
using v8::Signature;
98
using v8::String;
99
using v8::Uint32;
100
using v8::Undefined;
101
using v8::Value;
102
103
#ifdef OPENSSL_NO_OCB
104
# define IS_OCB_MODE(mode) false
105
#else
106
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
107
#endif
108
109
static const char* const root_certs[] = {
110
#include "node_root_certs.h"  // NOLINT(build/include_order)
111
};
112
113
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
114
115
static X509_STORE* root_cert_store;
116
117
static bool extra_root_certs_loaded = false;
118
119
// Just to generate static methods
120
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
121
                                           Local<FunctionTemplate> t);
122
template void SSLWrap<TLSWrap>::ConfigureSecureContext(SecureContext* sc);
123
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
124
template void SSLWrap<TLSWrap>::MemoryInfo(MemoryTracker* tracker) const;
125
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
126
    SSL* s,
127
    const unsigned char* key,
128
    int len,
129
    int* copy);
130
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
131
                                                  SSL_SESSION* sess);
132
template void SSLWrap<TLSWrap>::KeylogCallback(const SSL* s,
133
                                               const char* line);
134
template void SSLWrap<TLSWrap>::OnClientHello(
135
    void* arg,
136
    const ClientHelloParser::ClientHello& hello);
137
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
138
template void SSLWrap<TLSWrap>::DestroySSL();
139
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
140
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
141
template int SSLWrap<TLSWrap>::SelectALPNCallback(
142
    SSL* s,
143
    const unsigned char** out,
144
    unsigned char* outlen,
145
    const unsigned char* in,
146
    unsigned int inlen,
147
    void* arg);
148
149
template <typename T>
150
339884
void Decode(const FunctionCallbackInfo<Value>& args,
151
            void (*callback)(T*, const FunctionCallbackInfo<Value>&,
152
                             const char*, size_t)) {
153
  T* ctx;
154


339884
  ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder());
155
156


1019652
  if (args[0]->IsString()) {
157
676986
    StringBytes::InlineDecoder decoder;
158
338493
    Environment* env = Environment::GetCurrent(args);
159
338493
    enum encoding enc = ParseEncoding(env->isolate(), args[1], UTF8);
160


1015479
    if (decoder.Decode(env, args[0].As<String>(), enc).IsNothing())
161
      return;
162


338493
    callback(ctx, args, decoder.out(), decoder.size());
163
  } else {
164
1391
    ArrayBufferViewContents<char> buf(args[0]);
165
1391
    callback(ctx, args, buf.data(), buf.length());
166
  }
167
}
168
169
94
static int PasswordCallback(char* buf, int size, int rwflag, void* u) {
170
94
  const char* passphrase = static_cast<char*>(u);
171
94
  if (passphrase != nullptr) {
172
85
    size_t buflen = static_cast<size_t>(size);
173
85
    size_t len = strlen(passphrase);
174
85
    if (buflen < len)
175
1
      return -1;
176
84
    memcpy(buf, passphrase, len);
177
84
    return len;
178
  }
179
180
9
  return -1;
181
}
182
183
// Loads OpenSSL engine by engine id and returns it. The loaded engine
184
// gets a reference so remember the corresponding call to ENGINE_free.
185
// In case of error the appropriate js exception is scheduled
186
// and nullptr is returned.
187
#ifndef OPENSSL_NO_ENGINE
188
2
static ENGINE* LoadEngineById(const char* engine_id, char (*errmsg)[1024]) {
189
4
  MarkPopErrorOnReturn mark_pop_error_on_return;
190
191
2
  ENGINE* engine = ENGINE_by_id(engine_id);
192
193
2
  if (engine == nullptr) {
194
    // Engine not found, try loading dynamically.
195
2
    engine = ENGINE_by_id("dynamic");
196
2
    if (engine != nullptr) {
197

4
      if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", engine_id, 0) ||
198
2
          !ENGINE_ctrl_cmd_string(engine, "LOAD", nullptr, 0)) {
199
2
        ENGINE_free(engine);
200
2
        engine = nullptr;
201
      }
202
    }
203
  }
204
205
2
  if (engine == nullptr) {
206
2
    int err = ERR_get_error();
207
2
    if (err != 0) {
208
2
      ERR_error_string_n(err, *errmsg, sizeof(*errmsg));
209
    } else {
210
      snprintf(*errmsg, sizeof(*errmsg),
211
               "Engine \"%s\" was not found", engine_id);
212
    }
213
  }
214
215
4
  return engine;
216
}
217
#endif  // !OPENSSL_NO_ENGINE
218
219
// This callback is used to avoid the default passphrase callback in OpenSSL
220
// which will typically prompt for the passphrase. The prompting is designed
221
// for the OpenSSL CLI, but works poorly for Node.js because it involves
222
// synchronous interaction with the controlling terminal, something we never
223
// want, and use this function to avoid it.
224
static int NoPasswordCallback(char* buf, int size, int rwflag, void* u) {
225
  return 0;
226
}
227
228
229
// namespace node::crypto::error
230
namespace error {
231
77
Maybe<bool> Decorate(Environment* env, Local<Object> obj,
232
              unsigned long err) {  // NOLINT(runtime/int)
233
77
  if (err == 0) return Just(true);  // No decoration necessary.
234
235
66
  const char* ls = ERR_lib_error_string(err);
236
66
  const char* fs = ERR_func_error_string(err);
237
66
  const char* rs = ERR_reason_error_string(err);
238
239
66
  Isolate* isolate = env->isolate();
240
66
  Local<Context> context = isolate->GetCurrentContext();
241
242
66
  if (ls != nullptr) {
243
198
    if (obj->Set(context, env->library_string(),
244
264
                 OneByteString(isolate, ls)).IsNothing()) {
245
1
      return Nothing<bool>();
246
    }
247
  }
248
65
  if (fs != nullptr) {
249
195
    if (obj->Set(context, env->function_string(),
250
260
                 OneByteString(isolate, fs)).IsNothing()) {
251
      return Nothing<bool>();
252
    }
253
  }
254
65
  if (rs != nullptr) {
255
195
    if (obj->Set(context, env->reason_string(),
256
260
                 OneByteString(isolate, rs)).IsNothing()) {
257
      return Nothing<bool>();
258
    }
259
260
    // SSL has no API to recover the error name from the number, so we
261
    // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
262
    // which ends up being close to the original error macro name.
263
130
    std::string reason(rs);
264
265
1161
    for (auto& c : reason) {
266
1096
      if (c == ' ')
267
122
        c = '_';
268
      else
269
974
        c = ToUpper(c);
270
    }
271
272
#define OSSL_ERROR_CODES_MAP(V)                                               \
273
    V(SYS)                                                                    \
274
    V(BN)                                                                     \
275
    V(RSA)                                                                    \
276
    V(DH)                                                                     \
277
    V(EVP)                                                                    \
278
    V(BUF)                                                                    \
279
    V(OBJ)                                                                    \
280
    V(PEM)                                                                    \
281
    V(DSA)                                                                    \
282
    V(X509)                                                                   \
283
    V(ASN1)                                                                   \
284
    V(CONF)                                                                   \
285
    V(CRYPTO)                                                                 \
286
    V(EC)                                                                     \
287
    V(SSL)                                                                    \
288
    V(BIO)                                                                    \
289
    V(PKCS7)                                                                  \
290
    V(X509V3)                                                                 \
291
    V(PKCS12)                                                                 \
292
    V(RAND)                                                                   \
293
    V(DSO)                                                                    \
294
    V(ENGINE)                                                                 \
295
    V(OCSP)                                                                   \
296
    V(UI)                                                                     \
297
    V(COMP)                                                                   \
298
    V(ECDSA)                                                                  \
299
    V(ECDH)                                                                   \
300
    V(OSSL_STORE)                                                             \
301
    V(FIPS)                                                                   \
302
    V(CMS)                                                                    \
303
    V(TS)                                                                     \
304
    V(HMAC)                                                                   \
305
    V(CT)                                                                     \
306
    V(ASYNC)                                                                  \
307
    V(KDF)                                                                    \
308
    V(SM2)                                                                    \
309
    V(USER)                                                                   \
310
311
#define V(name) case ERR_LIB_##name: lib = #name "_"; break;
312
65
    const char* lib = "";
313
65
    const char* prefix = "OSSL_";
314









65
    switch (ERR_GET_LIB(err)) { OSSL_ERROR_CODES_MAP(V) }
315
#undef V
316
#undef OSSL_ERROR_CODES_MAP
317
    // Don't generate codes like "ERR_OSSL_SSL_".
318

65
    if (lib && strcmp(lib, "SSL_") == 0)
319
6
      prefix = "";
320
321
    // All OpenSSL reason strings fit in a single 80-column macro definition,
322
    // all prefix lengths are <= 10, and ERR_OSSL_ is 9, so 128 is more than
323
    // sufficient.
324
    char code[128];
325
65
    snprintf(code, sizeof(code), "ERR_%s%s%s", prefix, lib, reason.c_str());
326
327
195
    if (obj->Set(env->isolate()->GetCurrentContext(),
328
             env->code_string(),
329
325
             OneByteString(env->isolate(), code)).IsNothing())
330
      return Nothing<bool>();
331
  }
332
333
65
  return Just(true);
334
}
335
}  // namespace error
336
337
338
662
struct CryptoErrorVector : public std::vector<std::string> {
339
90
  inline void Capture() {
340
90
    clear();
341
127
    while (auto err = ERR_get_error()) {
342
      char buf[256];
343
37
      ERR_error_string_n(err, buf, sizeof(buf));
344
37
      push_back(buf);
345
37
    }
346
90
    std::reverse(begin(), end());
347
90
  }
348
349
94
  inline MaybeLocal<Value> ToException(
350
      Environment* env,
351
      Local<String> exception_string = Local<String>()) const {
352
94
    if (exception_string.IsEmpty()) {
353
16
      CryptoErrorVector copy(*this);
354
8
      if (copy.empty()) copy.push_back("no error");  // But possibly a bug...
355
      // Use last element as the error message, everything else goes
356
      // into the .opensslErrorStack property on the exception object.
357
      auto exception_string =
358
24
          String::NewFromUtf8(env->isolate(), copy.back().data(),
359
16
                              NewStringType::kNormal, copy.back().size())
360
8
          .ToLocalChecked();
361
8
      copy.pop_back();
362
8
      return copy.ToException(env, exception_string);
363
    }
364
365
86
    Local<Value> exception_v = Exception::Error(exception_string);
366
86
    CHECK(!exception_v.IsEmpty());
367
368
86
    if (!empty()) {
369
21
      CHECK(exception_v->IsObject());
370
21
      Local<Object> exception = exception_v.As<Object>();
371
      Maybe<bool> ok = exception->Set(env->context(),
372
                     env->openssl_error_stack(),
373
84
                     ToV8Value(env->context(), *this).ToLocalChecked());
374
21
      if (ok.IsNothing())
375
1
        return MaybeLocal<Value>();
376
    }
377
378
85
    return exception_v;
379
  }
380
};
381
382
383
78
void ThrowCryptoError(Environment* env,
384
                      unsigned long err,  // NOLINT(runtime/int)
385
                      // Default, only used if there is no SSL `err` which can
386
                      // be used to create a long-style message string.
387
                      const char* message) {
388
78
  char message_buffer[128] = {0};
389

78
  if (err != 0 || message == nullptr) {
390
67
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
391
67
    message = message_buffer;
392
  }
393
154
  HandleScope scope(env->isolate());
394
  Local<String> exception_string =
395
156
      String::NewFromUtf8(env->isolate(), message, NewStringType::kNormal)
396
78
      .ToLocalChecked();
397
154
  CryptoErrorVector errors;
398
78
  errors.Capture();
399
  Local<Value> exception;
400
156
  if (!errors.ToException(env, exception_string).ToLocal(&exception))
401
1
    return;
402
  Local<Object> obj;
403
231
  if (!exception->ToObject(env->context()).ToLocal(&obj))
404
    return;
405
154
  if (error::Decorate(env, obj, err).IsNothing())
406
1
    return;
407
76
  env->isolate()->ThrowException(exception);
408
}
409
410
411
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
412
// The entropy pool starts out empty and needs to fill up before the PRNG
413
// can be used securely.  Once the pool is filled, it never dries up again;
414
// its contents is stirred and reused when necessary.
415
//
416
// OpenSSL normally fills the pool automatically but not when someone starts
417
// generating random numbers before the pool is full: in that case OpenSSL
418
// keeps lowering the entropy estimate to thwart attackers trying to guess
419
// the initial state of the PRNG.
420
//
421
// When that happens, we will have to wait until enough entropy is available.
422
// That should normally never take longer than a few milliseconds.
423
//
424
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
425
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
426
// block under normal circumstances.
427
//
428
// The only time when /dev/urandom may conceivably block is right after boot,
429
// when the whole system is still low on entropy.  That's not something we can
430
// do anything about.
431
9296
inline void CheckEntropy() {
432
  for (;;) {
433
9296
    int status = RAND_status();
434
9296
    CHECK_GE(status, 0);  // Cannot fail.
435
9296
    if (status != 0)
436
18592
      break;
437
438
    // Give up, RAND_poll() not supported.
439
    if (RAND_poll() == 0)
440
      break;
441
  }
442
9296
}
443
444
445
9091
bool EntropySource(unsigned char* buffer, size_t length) {
446
  // Ensure that OpenSSL's PRNG is properly seeded.
447
9091
  CheckEntropy();
448
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
449
  // random. That's okay, it's still better than V8's stock source of entropy,
450
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
451
9091
  return RAND_bytes(buffer, length) != -1;
452
}
453
454
622
void SecureContext::Initialize(Environment* env, Local<Object> target) {
455
622
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
456
1866
  t->InstanceTemplate()->SetInternalFieldCount(
457
622
      SecureContext::kInternalFieldCount);
458
1244
  t->Inherit(BaseObject::GetConstructorTemplate(env));
459
  Local<String> secureContextString =
460
622
      FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext");
461
622
  t->SetClassName(secureContextString);
462
463
622
  env->SetProtoMethod(t, "init", Init);
464
622
  env->SetProtoMethod(t, "setKey", SetKey);
465
#ifndef OPENSSL_NO_ENGINE
466
622
  env->SetProtoMethod(t, "setEngineKey", SetEngineKey);
467
#endif  // !OPENSSL_NO_ENGINE
468
622
  env->SetProtoMethod(t, "setCert", SetCert);
469
622
  env->SetProtoMethod(t, "addCACert", AddCACert);
470
622
  env->SetProtoMethod(t, "addCRL", AddCRL);
471
622
  env->SetProtoMethod(t, "addRootCerts", AddRootCerts);
472
622
  env->SetProtoMethod(t, "setCipherSuites", SetCipherSuites);
473
622
  env->SetProtoMethod(t, "setCiphers", SetCiphers);
474
622
  env->SetProtoMethod(t, "setSigalgs", SetSigalgs);
475
622
  env->SetProtoMethod(t, "setECDHCurve", SetECDHCurve);
476
622
  env->SetProtoMethod(t, "setDHParam", SetDHParam);
477
622
  env->SetProtoMethod(t, "setMaxProto", SetMaxProto);
478
622
  env->SetProtoMethod(t, "setMinProto", SetMinProto);
479
622
  env->SetProtoMethod(t, "getMaxProto", GetMaxProto);
480
622
  env->SetProtoMethod(t, "getMinProto", GetMinProto);
481
622
  env->SetProtoMethod(t, "setOptions", SetOptions);
482
622
  env->SetProtoMethod(t, "setSessionIdContext", SetSessionIdContext);
483
622
  env->SetProtoMethod(t, "setSessionTimeout", SetSessionTimeout);
484
622
  env->SetProtoMethod(t, "close", Close);
485
622
  env->SetProtoMethod(t, "loadPKCS12", LoadPKCS12);
486
#ifndef OPENSSL_NO_ENGINE
487
622
  env->SetProtoMethod(t, "setClientCertEngine", SetClientCertEngine);
488
#endif  // !OPENSSL_NO_ENGINE
489
622
  env->SetProtoMethodNoSideEffect(t, "getTicketKeys", GetTicketKeys);
490
622
  env->SetProtoMethod(t, "setTicketKeys", SetTicketKeys);
491
622
  env->SetProtoMethod(t, "setFreeListLength", SetFreeListLength);
492
622
  env->SetProtoMethod(t, "enableTicketKeyCallback", EnableTicketKeyCallback);
493
622
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate<true>);
494
622
  env->SetProtoMethodNoSideEffect(t, "getIssuer", GetCertificate<false>);
495
496
#define SET_INTEGER_CONSTANTS(name, value)                                     \
497
    t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), name),                        \
498
           Integer::NewFromUnsigned(env->isolate(), value));
499
1866
  SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex);
500
1866
  SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex);
501
1866
  SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex);
502
1866
  SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex);
503
1866
  SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex);
504
505
#undef SET_INTEGER_CONSTANTS
506
507
  Local<FunctionTemplate> ctx_getter_templ =
508
      FunctionTemplate::New(env->isolate(),
509
                            CtxGetter,
510
                            Local<Value>(),
511
1244
                            Signature::New(env->isolate(), t));
512
513
514
2488
  t->PrototypeTemplate()->SetAccessorProperty(
515
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
516
      ctx_getter_templ,
517
      Local<FunctionTemplate>(),
518
622
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
519
520
1244
  target->Set(env->context(), secureContextString,
521
3110
              t->GetFunction(env->context()).ToLocalChecked()).Check();
522
622
  env->set_secure_context_constructor_template(t);
523
622
}
524
525
2299
SecureContext::SecureContext(Environment* env, Local<Object> wrap)
526
2299
    : BaseObject(env, wrap) {
527
2299
  MakeWeak();
528
2299
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
529
2299
}
530
531
3546
inline void SecureContext::Reset() {
532
3546
  if (ctx_ != nullptr) {
533
2233
    env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
534
  }
535
3546
  ctx_.reset();
536
3546
  cert_.reset();
537
3546
  issuer_.reset();
538
3546
}
539
540
6852
SecureContext::~SecureContext() {
541
2284
  Reset();
542
4568
}
543
544
2299
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
545
2299
  Environment* env = Environment::GetCurrent(args);
546
2299
  new SecureContext(env, args.This());
547
2299
}
548
549
// A maxVersion of 0 means "any", but OpenSSL may support TLS versions that
550
// Node.js doesn't, so pin the max to what we do support.
551
const int MAX_SUPPORTED_VERSION = TLS1_3_VERSION;
552
553
2297
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
554
  SecureContext* sc;
555
2346
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
556
2297
  Environment* env = sc->env();
557
558
2297
  CHECK_EQ(args.Length(), 3);
559
4594
  CHECK(args[1]->IsInt32());
560
4594
  CHECK(args[2]->IsInt32());
561
562
6891
  int min_version = args[1].As<Int32>()->Value();
563
6891
  int max_version = args[2].As<Int32>()->Value();
564
2297
  const SSL_METHOD* method = TLS_method();
565
566
2297
  if (max_version == 0)
567
    max_version = MAX_SUPPORTED_VERSION;
568
569
6891
  if (args[0]->IsString()) {
570
679
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
571
572
    // Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends
573
    // are still accepted.  They are OpenSSL's way of saying that all known
574
    // protocols below TLS 1.3 are supported unless explicitly disabled (which
575
    // we do below for SSLv2 and SSLv3.)
576
364
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
577
15
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
578
15
      return;
579
349
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
580
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
581
1
      return;
582
348
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
583
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
584
1
      return;
585
347
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
586
15
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
587
15
      return;
588
332
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
589
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
590
1
      return;
591
331
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
592
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
593
1
      return;
594
330
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
595
36
      max_version = TLS1_2_VERSION;
596
294
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
597
1
      max_version = TLS1_2_VERSION;
598
1
      method = TLS_server_method();
599
293
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
600
1
      max_version = TLS1_2_VERSION;
601
1
      method = TLS_client_method();
602
292
    } else if (strcmp(*sslmethod, "TLS_method") == 0) {
603
53
      min_version = 0;
604
53
      max_version = MAX_SUPPORTED_VERSION;
605
239
    } else if (strcmp(*sslmethod, "TLS_server_method") == 0) {
606
      min_version = 0;
607
      max_version = MAX_SUPPORTED_VERSION;
608
      method = TLS_server_method();
609
239
    } else if (strcmp(*sslmethod, "TLS_client_method") == 0) {
610
      min_version = 0;
611
      max_version = MAX_SUPPORTED_VERSION;
612
      method = TLS_client_method();
613
239
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
614
71
      min_version = TLS1_VERSION;
615
71
      max_version = TLS1_VERSION;
616
168
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
617
1
      min_version = TLS1_VERSION;
618
1
      max_version = TLS1_VERSION;
619
1
      method = TLS_server_method();
620
167
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
621
1
      min_version = TLS1_VERSION;
622
1
      max_version = TLS1_VERSION;
623
1
      method = TLS_client_method();
624
166
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
625
71
      min_version = TLS1_1_VERSION;
626
71
      max_version = TLS1_1_VERSION;
627
95
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
628
1
      min_version = TLS1_1_VERSION;
629
1
      max_version = TLS1_1_VERSION;
630
1
      method = TLS_server_method();
631
94
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
632
1
      min_version = TLS1_1_VERSION;
633
1
      max_version = TLS1_1_VERSION;
634
1
      method = TLS_client_method();
635
93
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
636
75
      min_version = TLS1_2_VERSION;
637
75
      max_version = TLS1_2_VERSION;
638
18
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
639
2
      min_version = TLS1_2_VERSION;
640
2
      max_version = TLS1_2_VERSION;
641
2
      method = TLS_server_method();
642
16
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
643
1
      min_version = TLS1_2_VERSION;
644
1
      max_version = TLS1_2_VERSION;
645
1
      method = TLS_client_method();
646
    } else {
647
30
      const std::string msg("Unknown method: ");
648
15
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, (msg + * sslmethod).c_str());
649
15
      return;
650
    }
651
  }
652
653
2248
  sc->ctx_.reset(SSL_CTX_new(method));
654
2248
  SSL_CTX_set_app_data(sc->ctx_.get(), sc);
655
656
  // Disable SSLv2 in the case when method == TLS_method() and the
657
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
658
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
659
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
660
2248
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv2);
661
2248
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv3);
662
663
  // Enable automatic cert chaining. This is enabled by default in OpenSSL, but
664
  // disabled by default in BoringSSL. Enable it explicitly to make the
665
  // behavior match when Node is built with BoringSSL.
666
2248
  SSL_CTX_clear_mode(sc->ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
667
668
  // SSL session cache configuration
669
2248
  SSL_CTX_set_session_cache_mode(sc->ctx_.get(),
670
                                 SSL_SESS_CACHE_CLIENT |
671
                                 SSL_SESS_CACHE_SERVER |
672
                                 SSL_SESS_CACHE_NO_INTERNAL |
673
2248
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
674
675
2248
  SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version);
676
2248
  SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version);
677
678
  // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was
679
  // exposed in the public API. To retain compatibility, install a callback
680
  // which restores the old algorithm.
681

6744
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
682

4496
      RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 ||
683
2248
      RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) {
684
    return env->ThrowError("Error generating ticket keys");
685
  }
686
2248
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
687
}
688
689
690
// Takes a string or buffer and loads it into a BIO.
691
// Caller responsible for BIO_free_all-ing the returned object.
692
2245
static BIOPointer LoadBIO(Environment* env, Local<Value> v) {
693
4490
  HandleScope scope(env->isolate());
694
695
4490
  if (v->IsString()) {
696
2630
    const node::Utf8Value s(env->isolate(), v);
697
1315
    return NodeBIO::NewFixed(*s, s.length());
698
  }
699
700
930
  if (v->IsArrayBufferView()) {
701
930
    ArrayBufferViewContents<char> buf(v.As<ArrayBufferView>());
702
930
    return NodeBIO::NewFixed(buf.data(), buf.length());
703
  }
704
705
  return nullptr;
706
}
707
708
709
824
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
710
824
  Environment* env = Environment::GetCurrent(args);
711
712
  SecureContext* sc;
713
834
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
714
715
824
  unsigned int len = args.Length();
716
824
  if (len < 1) {
717
    return THROW_ERR_MISSING_ARGS(env, "Private key argument is mandatory");
718
  }
719
720
824
  if (len > 2) {
721
    return env->ThrowError("Only private key and pass phrase are expected");
722
  }
723
724
824
  if (len == 2) {
725

2550
    if (args[1]->IsUndefined() || args[1]->IsNull())
726
798
      len = 1;
727
    else
728
78
      THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase");
729
  }
730
731
1636
  BIOPointer bio(LoadBIO(env, args[0]));
732
822
  if (!bio)
733
    return;
734
735
1636
  node::Utf8Value passphrase(env->isolate(), args[1]);
736
737
  EVPKeyPointer key(
738
      PEM_read_bio_PrivateKey(bio.get(),
739
                              nullptr,
740
                              PasswordCallback,
741
1636
                              *passphrase));
742
743
822
  if (!key) {
744
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
745
7
    return ThrowCryptoError(env, err, "PEM_read_bio_PrivateKey");
746
  }
747
748
815
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
749
750
815
  if (!rv) {
751
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
752
1
    return ThrowCryptoError(env, err, "SSL_CTX_use_PrivateKey");
753
  }
754
}
755
756
8
void SecureContext::SetSigalgs(const FunctionCallbackInfo<Value>& args) {
757
  SecureContext* sc;
758
8
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
759
8
  Environment* env = sc->env();
760
8
  ClearErrorOnReturn clear_error_on_return;
761
762
8
  CHECK_EQ(args.Length(), 1);
763
24
  CHECK(args[0]->IsString());
764
765
16
  const node::Utf8Value sigalgs(env->isolate(), args[0]);
766
767
8
  int rv = SSL_CTX_set1_sigalgs_list(sc->ctx_.get(), *sigalgs);
768
769
8
  if (rv == 0) {
770
    return ThrowCryptoError(env, ERR_get_error());
771
  }
772
}
773
774
#ifndef OPENSSL_NO_ENGINE
775
// Helpers for the smart pointer.
776
void ENGINE_free_fn(ENGINE* engine) { ENGINE_free(engine); }
777
778
void ENGINE_finish_and_free_fn(ENGINE* engine) {
779
  ENGINE_finish(engine);
780
  ENGINE_free(engine);
781
}
782
783
void SecureContext::SetEngineKey(const FunctionCallbackInfo<Value>& args) {
784
  Environment* env = Environment::GetCurrent(args);
785
786
  SecureContext* sc;
787
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
788
789
  CHECK_EQ(args.Length(), 2);
790
791
  char errmsg[1024];
792
  const node::Utf8Value engine_id(env->isolate(), args[1]);
793
  std::unique_ptr<ENGINE, std::function<void(ENGINE*)>> e =
794
                         { LoadEngineById(*engine_id, &errmsg),
795
                           ENGINE_free_fn };
796
  if (e.get() == nullptr) {
797
    return env->ThrowError(errmsg);
798
  }
799
800
  if (!ENGINE_init(e.get())) {
801
    return env->ThrowError("ENGINE_init");
802
  }
803
804
  e.get_deleter() = ENGINE_finish_and_free_fn;
805
806
  const node::Utf8Value key_name(env->isolate(), args[0]);
807
  EVPKeyPointer key(ENGINE_load_private_key(e.get(), *key_name,
808
                                            nullptr, nullptr));
809
810
  if (!key) {
811
    return ThrowCryptoError(env, ERR_get_error(), "ENGINE_load_private_key");
812
  }
813
814
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
815
816
  if (rv == 0) {
817
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_use_PrivateKey");
818
  }
819
820
  sc->private_key_engine_ = std::move(e);
821
}
822
#endif  // !OPENSSL_NO_ENGINE
823
824
852
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
825
                                  X509Pointer&& x,
826
                                  STACK_OF(X509)* extra_certs,
827
                                  X509Pointer* cert,
828
                                  X509Pointer* issuer_) {
829
852
  CHECK(!*issuer_);
830
852
  CHECK(!*cert);
831
852
  X509* issuer = nullptr;
832
833
852
  int ret = SSL_CTX_use_certificate(ctx, x.get());
834
835
852
  if (ret) {
836
    // If we could set up our certificate, now proceed to
837
    // the CA certificates.
838
852
    SSL_CTX_clear_extra_chain_certs(ctx);
839
840
1268
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
841
416
      X509* ca = sk_X509_value(extra_certs, i);
842
843
      // NOTE: Increments reference count on `ca`
844
416
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
845
        ret = 0;
846
        issuer = nullptr;
847
        break;
848
      }
849
      // Note that we must not free r if it was successfully
850
      // added to the chain (while we must free the main
851
      // certificate, since its reference count is increased
852
      // by SSL_CTX_use_certificate).
853
854
      // Find issuer
855

416
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
856
4
        continue;
857
858
412
      issuer = ca;
859
    }
860
  }
861
862
  // Try getting issuer from a cert store
863
852
  if (ret) {
864
852
    if (issuer == nullptr) {
865
440
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
866
440
      ret = ret < 0 ? 0 : 1;
867
      // NOTE: get_cert_store doesn't increment reference count,
868
      // no need to free `store`
869
    } else {
870
      // Increment issuer reference count
871
412
      issuer = X509_dup(issuer);
872
412
      if (issuer == nullptr) {
873
        ret = 0;
874
      }
875
    }
876
  }
877
878
852
  issuer_->reset(issuer);
879
880

852
  if (ret && x != nullptr) {
881
852
    cert->reset(X509_dup(x.get()));
882
852
    if (!*cert)
883
      ret = 0;
884
  }
885
852
  return ret;
886
}
887
888
889
// Read a file that contains our certificate in "PEM" format,
890
// possibly followed by a sequence of CA certificates that should be
891
// sent to the peer in the Certificate message.
892
//
893
// Taken from OpenSSL - edited for style.
894
840
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
895
                                  BIOPointer&& in,
896
                                  X509Pointer* cert,
897
                                  X509Pointer* issuer) {
898
  // Just to ensure that `ERR_peek_last_error` below will return only errors
899
  // that we are interested in
900
840
  ERR_clear_error();
901
902
  X509Pointer x(
903
1680
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
904
905
840
  if (!x)
906
    return 0;
907
908
840
  unsigned long err = 0;  // NOLINT(runtime/int)
909
910
1680
  StackOfX509 extra_certs(sk_X509_new_null());
911
840
  if (!extra_certs)
912
    return 0;
913
914
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
915
                                    nullptr,
916
                                    NoPasswordCallback,
917
1247
                                    nullptr)}) {
918
407
    if (sk_X509_push(extra_certs.get(), extra.get())) {
919
407
      extra.release();
920
407
      continue;
921
    }
922
923
    return 0;
924
407
  }
925
926
  // When the while loop ends, it's usually just EOF.
927
840
  err = ERR_peek_last_error();
928

1680
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
929
840
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
930
840
    ERR_clear_error();
931
  } else {
932
    // some real error
933
    return 0;
934
  }
935
936
840
  return SSL_CTX_use_certificate_chain(ctx,
937
840
                                       std::move(x),
938
                                       extra_certs.get(),
939
                                       cert,
940
840
                                       issuer);
941
}
942
943
944
840
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
945
840
  Environment* env = Environment::GetCurrent(args);
946
947
  SecureContext* sc;
948
840
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
949
950
840
  if (args.Length() != 1) {
951
    return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory");
952
  }
953
954
1680
  BIOPointer bio(LoadBIO(env, args[0]));
955
840
  if (!bio)
956
    return;
957
958
840
  sc->cert_.reset();
959
840
  sc->issuer_.reset();
960
961
2520
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(),
962
840
                                         std::move(bio),
963
840
                                         &sc->cert_,
964
1680
                                         &sc->issuer_);
965
966
840
  if (!rv) {
967
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
968
    return ThrowCryptoError(env, err, "SSL_CTX_use_certificate_chain");
969
  }
970
}
971
972
973
253
static X509_STORE* NewRootCertStore() {
974

253
  static std::vector<X509*> root_certs_vector;
975

253
  static Mutex root_certs_vector_mutex;
976
506
  Mutex::ScopedLock lock(root_certs_vector_mutex);
977
978
253
  if (root_certs_vector.empty()) {
979
34194
    for (size_t i = 0; i < arraysize(root_certs); i++) {
980
      X509* x509 =
981
67896
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
982
33948
                                              strlen(root_certs[i])).get(),
983
                            nullptr,   // no re-use of X509 structure
984
                            NoPasswordCallback,
985
33948
                            nullptr);  // no callback data
986
987
      // Parse errors from the built-in roots are fatal.
988
33948
      CHECK_NOT_NULL(x509);
989
990
33948
      root_certs_vector.push_back(x509);
991
    }
992
  }
993
994
253
  X509_STORE* store = X509_STORE_new();
995
253
  if (*system_cert_path != '\0') {
996
    X509_STORE_load_locations(store, system_cert_path, nullptr);
997
  }
998
999
506
  Mutex::ScopedLock cli_lock(node::per_process::cli_options_mutex);
1000
253
  if (per_process::cli_options->ssl_openssl_cert_store) {
1001
    X509_STORE_set_default_paths(store);
1002
  } else {
1003
35167
    for (X509* cert : root_certs_vector) {
1004
34914
      X509_up_ref(cert);
1005
34914
      X509_STORE_add_cert(store, cert);
1006
    }
1007
  }
1008
1009
506
  return store;
1010
}
1011
1012
1013
207
void GetRootCertificates(const FunctionCallbackInfo<Value>& args) {
1014
207
  Environment* env = Environment::GetCurrent(args);
1015
28773
  Local<Value> result[arraysize(root_certs)];
1016
1017
28773
  for (size_t i = 0; i < arraysize(root_certs); i++) {
1018
57132
    if (!String::NewFromOneByte(
1019
            env->isolate(),
1020
28566
            reinterpret_cast<const uint8_t*>(root_certs[i]),
1021
85698
            NewStringType::kNormal).ToLocal(&result[i])) {
1022
      return;
1023
    }
1024
  }
1025
1026
621
  args.GetReturnValue().Set(
1027
      Array::New(env->isolate(), result, arraysize(root_certs)));
1028
}
1029
1030
1031
553
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
1032
553
  Environment* env = Environment::GetCurrent(args);
1033
1034
  SecureContext* sc;
1035
553
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1036
553
  ClearErrorOnReturn clear_error_on_return;
1037
1038
553
  if (args.Length() != 1) {
1039
    return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory");
1040
  }
1041
1042
1106
  BIOPointer bio(LoadBIO(env, args[0]));
1043
553
  if (!bio)
1044
    return;
1045
1046
553
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1047
1446
  while (X509* x509 = PEM_read_bio_X509_AUX(
1048
1446
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1049
893
    if (cert_store == root_cert_store) {
1050
1
      cert_store = NewRootCertStore();
1051
1
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1052
    }
1053
893
    X509_STORE_add_cert(cert_store, x509);
1054
893
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
1055
893
    X509_free(x509);
1056
893
  }
1057
}
1058
1059
1060
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
1061
2
  Environment* env = Environment::GetCurrent(args);
1062
1063
  SecureContext* sc;
1064
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1065
1066
2
  if (args.Length() != 1) {
1067
    return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory");
1068
  }
1069
1070
1
  ClearErrorOnReturn clear_error_on_return;
1071
1072
3
  BIOPointer bio(LoadBIO(env, args[0]));
1073
2
  if (!bio)
1074
    return;
1075
1076
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
1077
3
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
1078
1079
2
  if (!crl)
1080
1
    return env->ThrowError("Failed to parse CRL");
1081
1082
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1083
1
  if (cert_store == root_cert_store) {
1084
    cert_store = NewRootCertStore();
1085
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1086
  }
1087
1088
1
  X509_STORE_add_crl(cert_store, crl.get());
1089
  X509_STORE_set_flags(cert_store,
1090
1
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1091
}
1092
1093
1094
4
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1095
    X509_STORE* store,
1096
    const char* file) {
1097
4
  ERR_clear_error();
1098
8
  MarkPopErrorOnReturn mark_pop_error_on_return;
1099
1100
8
  BIOPointer bio(BIO_new_file(file, "r"));
1101
4
  if (!bio)
1102
1
    return ERR_get_error();
1103
1104
  while (X509* x509 =
1105
6
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1106
3
    X509_STORE_add_cert(store, x509);
1107
3
    X509_free(x509);
1108
3
  }
1109
1110
3
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1111
  // Ignore error if its EOF/no start line found.
1112

6
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1113
3
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1114
3
    return 0;
1115
  }
1116
1117
  return err;
1118
}
1119
1120
1121
4
void UseExtraCaCerts(const std::string& file) {
1122
4
  ClearErrorOnReturn clear_error_on_return;
1123
1124
4
  if (root_cert_store == nullptr) {
1125
4
    root_cert_store = NewRootCertStore();
1126
1127
4
    if (!file.empty()) {
1128
4
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1129
                                           root_cert_store,
1130
4
                                           file.c_str());
1131
4
      if (err) {
1132
1
        fprintf(stderr,
1133
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
1134
                file.c_str(),
1135
1
                ERR_error_string(err, nullptr));
1136
      } else {
1137
3
        extra_root_certs_loaded = true;
1138
      }
1139
    }
1140
  }
1141
4
}
1142
1143
1144
3
static void IsExtraRootCertsFileLoaded(
1145
    const FunctionCallbackInfo<Value>& args) {
1146
9
  return args.GetReturnValue().Set(extra_root_certs_loaded);
1147
}
1148
1149
1150
1715
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
1151
  SecureContext* sc;
1152
1715
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1153
1715
  ClearErrorOnReturn clear_error_on_return;
1154
1155
1715
  if (root_cert_store == nullptr) {
1156
242
    root_cert_store = NewRootCertStore();
1157
  }
1158
1159
  // Increment reference count so global store is not deleted along with CTX.
1160
1715
  X509_STORE_up_ref(root_cert_store);
1161
1715
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
1162
}
1163
1164
1165
2172
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
1166
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
1167
#ifndef OPENSSL_IS_BORINGSSL
1168
  SecureContext* sc;
1169
2173
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1170
2172
  Environment* env = sc->env();
1171
2171
  ClearErrorOnReturn clear_error_on_return;
1172
1173
2172
  CHECK_EQ(args.Length(), 1);
1174
6516
  CHECK(args[0]->IsString());
1175
1176
4343
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1177
2172
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers)) {
1178
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1179
1
    return ThrowCryptoError(env, err, "Failed to set ciphers");
1180
  }
1181
#endif
1182
}
1183
1184
1185
2174
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
1186
  SecureContext* sc;
1187
2189
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1188
2174
  Environment* env = sc->env();
1189
2159
  ClearErrorOnReturn clear_error_on_return;
1190
1191
2174
  CHECK_EQ(args.Length(), 1);
1192
6522
  CHECK(args[0]->IsString());
1193
1194
4333
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1195
2174
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
1196
15
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1197
1198

15
    if (strlen(*ciphers) == 0 && ERR_GET_REASON(err) == SSL_R_NO_CIPHER_MATCH) {
1199
      // TLS1.2 ciphers were deliberately cleared, so don't consider
1200
      // SSL_R_NO_CIPHER_MATCH to be an error (this is how _set_cipher_suites()
1201
      // works). If the user actually sets a value (like "no-such-cipher"), then
1202
      // that's actually an error.
1203
11
      return;
1204
    }
1205
4
    return ThrowCryptoError(env, err, "Failed to set ciphers");
1206
  }
1207
}
1208
1209
1210
2167
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
1211
  SecureContext* sc;
1212
4327
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1213
2167
  Environment* env = sc->env();
1214
1215
2167
  if (args.Length() != 1)
1216
    return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory");
1217
1218
6501
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name");
1219
1220
2173
  node::Utf8Value curve(env->isolate(), args[0]);
1221
1222
2166
  if (strcmp(*curve, "auto") == 0)
1223
2156
    return;
1224
1225
10
  if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve))
1226
3
    return env->ThrowError("Failed to set ECDH curve");
1227
}
1228
1229
1230
10
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
1231
  SecureContext* sc;
1232
13
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
1233
10
  Environment* env = sc->env();
1234
7
  ClearErrorOnReturn clear_error_on_return;
1235
1236
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
1237
  // to be specified explicitly
1238
10
  if (args.Length() != 1)
1239
    return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory");
1240
1241
17
  DHPointer dh;
1242
  {
1243
20
    BIOPointer bio(LoadBIO(env, args[0]));
1244
10
    if (!bio)
1245
      return;
1246
1247
10
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
1248
  }
1249
1250
  // Invalid dhparam is silently discarded and DHE is no longer used.
1251
10
  if (!dh)
1252
1
    return;
1253
1254
  const BIGNUM* p;
1255
9
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
1256
9
  const int size = BN_num_bits(p);
1257
9
  if (size < 1024) {
1258
    return THROW_ERR_INVALID_ARG_VALUE(
1259
2
        env, "DH parameter is less than 1024 bits");
1260
7
  } else if (size < 2048) {
1261
9
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1262
        env->isolate(), "DH parameter is less than 2048 bits"));
1263
  }
1264
1265
7
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
1266
7
  int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get());
1267
1268
7
  if (!r)
1269
    return env->ThrowTypeError("Error setting temp DH parameter");
1270
}
1271
1272
1273
11
void SecureContext::SetMinProto(const FunctionCallbackInfo<Value>& args) {
1274
  SecureContext* sc;
1275
11
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1276
1277
11
  CHECK_EQ(args.Length(), 1);
1278
22
  CHECK(args[0]->IsInt32());
1279
1280
33
  int version = args[0].As<Int32>()->Value();
1281
1282
11
  CHECK(SSL_CTX_set_min_proto_version(sc->ctx_.get(), version));
1283
}
1284
1285
1286
46
void SecureContext::SetMaxProto(const FunctionCallbackInfo<Value>& args) {
1287
  SecureContext* sc;
1288
46
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1289
1290
46
  CHECK_EQ(args.Length(), 1);
1291
92
  CHECK(args[0]->IsInt32());
1292
1293
138
  int version = args[0].As<Int32>()->Value();
1294
1295
46
  CHECK(SSL_CTX_set_max_proto_version(sc->ctx_.get(), version));
1296
}
1297
1298
1299
57
void SecureContext::GetMinProto(const FunctionCallbackInfo<Value>& args) {
1300
  SecureContext* sc;
1301
57
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1302
1303
57
  CHECK_EQ(args.Length(), 0);
1304
1305
  long version =  // NOLINT(runtime/int)
1306
57
    SSL_CTX_get_min_proto_version(sc->ctx_.get());
1307
171
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1308
}
1309
1310
1311
76
void SecureContext::GetMaxProto(const FunctionCallbackInfo<Value>& args) {
1312
  SecureContext* sc;
1313
76
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1314
1315
76
  CHECK_EQ(args.Length(), 0);
1316
1317
  long version =  // NOLINT(runtime/int)
1318
76
    SSL_CTX_get_max_proto_version(sc->ctx_.get());
1319
228
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1320
}
1321
1322
1323
826
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1324
  SecureContext* sc;
1325
826
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1326
  int64_t val;
1327
1328

2478
  if (args.Length() != 1 ||
1329
4130
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1330
    return THROW_ERR_INVALID_ARG_TYPE(
1331
        sc->env(), "Options must be an integer value");
1332
  }
1333
1334
826
  SSL_CTX_set_options(sc->ctx_.get(),
1335
826
                      static_cast<long>(val));  // NOLINT(runtime/int)
1336
}
1337
1338
1339
755
void SecureContext::SetSessionIdContext(
1340
    const FunctionCallbackInfo<Value>& args) {
1341
  SecureContext* sc;
1342
1510
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1343
755
  Environment* env = sc->env();
1344
1345
755
  if (args.Length() != 1) {
1346
    return THROW_ERR_MISSING_ARGS(
1347
        env, "Session ID context argument is mandatory");
1348
  }
1349
1350
2265
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1351
1352
755
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1353
  const unsigned char* sid_ctx =
1354
755
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1355
755
  unsigned int sid_ctx_len = sessionIdContext.length();
1356
1357
755
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1358
755
  if (r == 1)
1359
755
    return;
1360
1361
  BUF_MEM* mem;
1362
  Local<String> message;
1363
1364
  BIOPointer bio(BIO_new(BIO_s_mem()));
1365
  if (!bio) {
1366
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1367
                                    "SSL_CTX_set_session_id_context error");
1368
  } else {
1369
    ERR_print_errors(bio.get());
1370
    BIO_get_mem_ptr(bio.get(), &mem);
1371
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1372
  }
1373
1374
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1375
}
1376
1377
1378
2
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1379
  SecureContext* sc;
1380
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1381
1382

6
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1383
1
    return THROW_ERR_INVALID_ARG_TYPE(
1384
1
        sc->env(), "Session timeout must be a 32-bit integer");
1385
  }
1386
1387
3
  int32_t sessionTimeout = args[0].As<Int32>()->Value();
1388
1
  SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
1389
}
1390
1391
1392
1262
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1393
  SecureContext* sc;
1394
1262
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1395
1262
  sc->Reset();
1396
}
1397
1398
1399
// Takes .pfx or .p12 and password in string or buffer format
1400
18
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1401
18
  Environment* env = Environment::GetCurrent(args);
1402
1403
30
  std::vector<char> pass;
1404
18
  bool ret = false;
1405
1406
  SecureContext* sc;
1407
18
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1408
12
  ClearErrorOnReturn clear_error_on_return;
1409
1410
18
  if (args.Length() < 1) {
1411
    return THROW_ERR_MISSING_ARGS(env, "PFX certificate argument is mandatory");
1412
  }
1413
1414
30
  BIOPointer in(LoadBIO(env, args[0]));
1415
18
  if (!in)
1416
    return env->ThrowError("Unable to load BIO");
1417
1418
18
  if (args.Length() >= 2) {
1419
15
    THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase");
1420
30
    Local<ArrayBufferView> abv = args[1].As<ArrayBufferView>();
1421
15
    size_t passlen = abv->ByteLength();
1422
15
    pass.resize(passlen + 1);
1423
30
    abv->CopyContents(pass.data(), passlen);
1424
15
    pass[passlen] = '\0';
1425
  }
1426
1427
  // Free previous certs
1428
18
  sc->issuer_.reset();
1429
18
  sc->cert_.reset();
1430
1431
18
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1432
1433
30
  DeleteFnPtr<PKCS12, PKCS12_free> p12;
1434
30
  EVPKeyPointer pkey;
1435
30
  X509Pointer cert;
1436
30
  StackOfX509 extra_certs;
1437
1438
18
  PKCS12* p12_ptr = nullptr;
1439
18
  EVP_PKEY* pkey_ptr = nullptr;
1440
18
  X509* cert_ptr = nullptr;
1441
18
  STACK_OF(X509)* extra_certs_ptr = nullptr;
1442
36
  if (d2i_PKCS12_bio(in.get(), &p12_ptr) &&
1443
32
      (p12.reset(p12_ptr), true) &&  // Move ownership to the smart pointer.
1444
16
      PKCS12_parse(p12.get(), pass.data(),
1445
                   &pkey_ptr,
1446
                   &cert_ptr,
1447
                   &extra_certs_ptr) &&
1448
12
      (pkey.reset(pkey_ptr), cert.reset(cert_ptr),
1449
24
       extra_certs.reset(extra_certs_ptr), true) &&  // Move ownership.
1450
36
      SSL_CTX_use_certificate_chain(sc->ctx_.get(),
1451
12
                                    std::move(cert),
1452
                                    extra_certs.get(),
1453
12
                                    &sc->cert_,
1454

42
                                    &sc->issuer_) &&
1455
12
      SSL_CTX_use_PrivateKey(sc->ctx_.get(), pkey.get())) {
1456
    // Add CA certs too
1457
21
    for (int i = 0; i < sk_X509_num(extra_certs.get()); i++) {
1458
9
      X509* ca = sk_X509_value(extra_certs.get(), i);
1459
1460
9
      if (cert_store == root_cert_store) {
1461
6
        cert_store = NewRootCertStore();
1462
6
        SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1463
      }
1464
9
      X509_STORE_add_cert(cert_store, ca);
1465
9
      SSL_CTX_add_client_CA(sc->ctx_.get(), ca);
1466
    }
1467
12
    ret = true;
1468
  }
1469
1470
18
  if (!ret) {
1471
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1472
6
    const char* str = ERR_reason_error_string(err);
1473
6
    return env->ThrowError(str);
1474
  }
1475
}
1476
1477
1478
#ifndef OPENSSL_NO_ENGINE
1479
void SecureContext::SetClientCertEngine(
1480
    const FunctionCallbackInfo<Value>& args) {
1481
  Environment* env = Environment::GetCurrent(args);
1482
  CHECK_EQ(args.Length(), 1);
1483
  CHECK(args[0]->IsString());
1484
1485
  SecureContext* sc;
1486
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1487
1488
  MarkPopErrorOnReturn mark_pop_error_on_return;
1489
1490
  // SSL_CTX_set_client_cert_engine does not itself support multiple
1491
  // calls by cleaning up before overwriting the client_cert_engine
1492
  // internal context variable.
1493
  // Instead of trying to fix up this problem we in turn also do not
1494
  // support multiple calls to SetClientCertEngine.
1495
  if (sc->client_cert_engine_provided_) {
1496
    return env->ThrowError(
1497
        "Multiple calls to SetClientCertEngine are not allowed");
1498
  }
1499
1500
  const node::Utf8Value engine_id(env->isolate(), args[0]);
1501
  char errmsg[1024];
1502
  DeleteFnPtr<ENGINE, ENGINE_free_fn> engine(
1503
      LoadEngineById(*engine_id, &errmsg));
1504
1505
  if (!engine)
1506
    return env->ThrowError(errmsg);
1507
1508
  // Note that this takes another reference to `engine`.
1509
  int r = SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get());
1510
  if (r == 0)
1511
    return ThrowCryptoError(env, ERR_get_error());
1512
  sc->client_cert_engine_provided_ = true;
1513
}
1514
#endif  // !OPENSSL_NO_ENGINE
1515
1516
1517
10
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1518
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1519
1520
  SecureContext* wrap;
1521
10
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1522
1523
20
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1524
10
  memcpy(Buffer::Data(buff), wrap->ticket_key_name_, 16);
1525
10
  memcpy(Buffer::Data(buff) + 16, wrap->ticket_key_hmac_, 16);
1526
10
  memcpy(Buffer::Data(buff) + 32, wrap->ticket_key_aes_, 16);
1527
1528
20
  args.GetReturnValue().Set(buff);
1529
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1530
}
1531
1532
1533
25
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1534
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1535
  SecureContext* wrap;
1536
27
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1537
25
  Environment* env = wrap->env();
1538
1539
  // TODO(@sam-github) Move type and len check to js, and CHECK() in C++.
1540
25
  if (args.Length() < 1) {
1541
    return THROW_ERR_MISSING_ARGS(env, "Ticket keys argument is mandatory");
1542
  }
1543
1544
25
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Ticket keys");
1545
48
  ArrayBufferViewContents<char> buf(args[0].As<ArrayBufferView>());
1546
1547
24
  if (buf.length() != 48) {
1548
    return THROW_ERR_INVALID_ARG_VALUE(
1549
1
        env, "Ticket keys length must be 48 bytes");
1550
  }
1551
1552
23
  memcpy(wrap->ticket_key_name_, buf.data(), 16);
1553
23
  memcpy(wrap->ticket_key_hmac_, buf.data() + 16, 16);
1554
23
  memcpy(wrap->ticket_key_aes_, buf.data() + 32, 16);
1555
1556
46
  args.GetReturnValue().Set(true);
1557
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1558
}
1559
1560
1561
1288
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1562
1288
}
1563
1564
1565
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1566
// the regression test in test/parallel/test-https-resume-after-renew.js.
1567
1
void SecureContext::EnableTicketKeyCallback(
1568
    const FunctionCallbackInfo<Value>& args) {
1569
  SecureContext* wrap;
1570
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1571
1572
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback);
1573
}
1574
1575
1576
4
int SecureContext::TicketKeyCallback(SSL* ssl,
1577
                                     unsigned char* name,
1578
                                     unsigned char* iv,
1579
                                     EVP_CIPHER_CTX* ectx,
1580
                                     HMAC_CTX* hctx,
1581
                                     int enc) {
1582
  static const int kTicketPartSize = 16;
1583
1584
  SecureContext* sc = static_cast<SecureContext*>(
1585
4
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1586
1587
4
  Environment* env = sc->env();
1588
8
  HandleScope handle_scope(env->isolate());
1589
4
  Context::Scope context_scope(env->context());
1590
1591
  Local<Value> argv[] = {
1592
8
    Buffer::Copy(env,
1593
                 reinterpret_cast<char*>(name),
1594
                 kTicketPartSize).ToLocalChecked(),
1595
8
    Buffer::Copy(env,
1596
                 reinterpret_cast<char*>(iv),
1597
                 kTicketPartSize).ToLocalChecked(),
1598
    Boolean::New(env->isolate(), enc != 0)
1599
16
  };
1600
1601
8
  Local<Value> ret = node::MakeCallback(env->isolate(),
1602
                                        sc->object(),
1603
                                        env->ticketkeycallback_string(),
1604
4
                                        arraysize(argv),
1605
                                        argv,
1606
12
                                        {0, 0}).ToLocalChecked();
1607
4
  Local<Array> arr = ret.As<Array>();
1608
1609
  int r =
1610
8
      arr->Get(env->context(),
1611
12
               kTicketKeyReturnIndex).ToLocalChecked()
1612
12
               ->Int32Value(env->context()).FromJust();
1613
4
  if (r < 0)
1614
    return r;
1615
1616
8
  Local<Value> hmac = arr->Get(env->context(),
1617
8
                               kTicketKeyHMACIndex).ToLocalChecked();
1618
8
  Local<Value> aes = arr->Get(env->context(),
1619
8
                              kTicketKeyAESIndex).ToLocalChecked();
1620
4
  if (Buffer::Length(aes) != kTicketPartSize)
1621
    return -1;
1622
1623
4
  if (enc) {
1624
6
    Local<Value> name_val = arr->Get(env->context(),
1625
6
                                     kTicketKeyNameIndex).ToLocalChecked();
1626
6
    Local<Value> iv_val = arr->Get(env->context(),
1627
6
                                   kTicketKeyIVIndex).ToLocalChecked();
1628
1629

6
    if (Buffer::Length(name_val) != kTicketPartSize ||
1630
3
        Buffer::Length(iv_val) != kTicketPartSize) {
1631
      return -1;
1632
    }
1633
1634
6
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1635
6
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1636
  }
1637
1638
4
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1639
8
  HMAC_Init_ex(hctx,
1640
4
               hmac_buf.data(),
1641
4
               hmac_buf.length(),
1642
               EVP_sha256(),
1643
4
               nullptr);
1644
1645
4
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1646
4
  if (enc) {
1647
3
    EVP_EncryptInit_ex(ectx,
1648
                       EVP_aes_128_cbc(),
1649
                       nullptr,
1650
                       aes_key.data(),
1651
3
                       iv);
1652
  } else {
1653
1
    EVP_DecryptInit_ex(ectx,
1654
                       EVP_aes_128_cbc(),
1655
                       nullptr,
1656
                       aes_key.data(),
1657
1
                       iv);
1658
  }
1659
1660
4
  return r;
1661
}
1662
1663
1664
1159
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1665
                                               unsigned char* name,
1666
                                               unsigned char* iv,
1667
                                               EVP_CIPHER_CTX* ectx,
1668
                                               HMAC_CTX* hctx,
1669
                                               int enc) {
1670
  SecureContext* sc = static_cast<SecureContext*>(
1671
1159
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1672
1673
1159
  if (enc) {
1674
1105
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1675

3315
    if (RAND_bytes(iv, 16) <= 0 ||
1676
1105
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1677

2210
                           sc->ticket_key_aes_, iv) <= 0 ||
1678
1105
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1679
                     EVP_sha256(), nullptr) <= 0) {
1680
      return -1;
1681
    }
1682
1105
    return 1;
1683
  }
1684
1685
54
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1686
    // The ticket key name does not match. Discard the ticket.
1687
12
    return 0;
1688
  }
1689
1690
84
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1691

84
                         iv) <= 0 ||
1692
42
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1693
                   EVP_sha256(), nullptr) <= 0) {
1694
    return -1;
1695
  }
1696
42
  return 1;
1697
}
1698
1699
1700
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1701
  SecureContext* sc;
1702
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1703
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1704
4
  info.GetReturnValue().Set(ext);
1705
}
1706
1707
1708
template <bool primary>
1709
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1710
  SecureContext* wrap;
1711

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1712
6
  Environment* env = wrap->env();
1713
  X509* cert;
1714
1715
  if (primary)
1716
3
    cert = wrap->cert_.get();
1717
  else
1718
3
    cert = wrap->issuer_.get();
1719

6
  if (cert == nullptr)
1720
    return args.GetReturnValue().SetNull();
1721
1722
6
  int size = i2d_X509(cert, nullptr);
1723
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1724
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1725
6
      Buffer::Data(buff));
1726
6
  i2d_X509(cert, &serialized);
1727
1728
12
  args.GetReturnValue().Set(buff);
1729
}
1730
1731
1732
template <class Base>
1733
499
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1734
998
  HandleScope scope(env->isolate());
1735
1736
499
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
1737
499
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
1738
499
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
1739
499
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
1740
499
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
1741
499
  env->SetProtoMethod(t, "setSession", SetSession);
1742
499
  env->SetProtoMethod(t, "loadSession", LoadSession);
1743
499
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
1744
499
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
1745
499
  env->SetProtoMethodNoSideEffect(t, "getCipher", GetCipher);
1746
499
  env->SetProtoMethodNoSideEffect(t, "getSharedSigalgs", GetSharedSigalgs);
1747
499
  env->SetProtoMethodNoSideEffect(
1748
      t, "exportKeyingMaterial", ExportKeyingMaterial);
1749
499
  env->SetProtoMethod(t, "endParser", EndParser);
1750
499
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1751
499
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1752
499
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
1753
499
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1754
499
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1755
499
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1756
499
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
1757
                                  GetEphemeralKeyInfo);
1758
499
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
1759
1760
#ifdef SSL_set_max_send_fragment
1761
499
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1762
#endif  // SSL_set_max_send_fragment
1763
1764
499
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
1765
                                  GetALPNNegotiatedProto);
1766
499
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1767
499
}
1768
1769
1770
template <class Base>
1771
12187
void SSLWrap<Base>::ConfigureSecureContext(SecureContext* sc) {
1772
  // OCSP stapling
1773
12187
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
1774
12187
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
1775
12187
}
1776
1777
1778
template <class Base>
1779
97
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1780
                                               const unsigned char* key,
1781
                                               int len,
1782
                                               int* copy) {
1783
97
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1784
1785
97
  *copy = 0;
1786
97
  return w->next_sess_.release();
1787
}
1788
1789
1790
template <class Base>
1791
1724
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1792
1724
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1793
1724
  Environment* env = w->ssl_env();
1794
3448
  HandleScope handle_scope(env->isolate());
1795
1724
  Context::Scope context_scope(env->context());
1796
1797
1724
  if (!w->session_callbacks_)
1798
1435
    return 0;
1799
1800
  // Check if session is small enough to be stored
1801
289
  int size = i2d_SSL_SESSION(sess, nullptr);
1802
289
  if (size > SecureContext::kMaxSessionSize)
1803
    return 0;
1804
1805
  // Serialize session
1806
578
  Local<Object> session = Buffer::New(env, size).ToLocalChecked();
1807
  unsigned char* session_data = reinterpret_cast<unsigned char*>(
1808
289
      Buffer::Data(session));
1809
289
  memset(session_data, 0, size);
1810
289
  i2d_SSL_SESSION(sess, &session_data);
1811
1812
  unsigned int session_id_length;
1813
  const unsigned char* session_id_data = SSL_SESSION_get_id(sess,
1814
289
                                                            &session_id_length);
1815
578
  Local<Object> session_id = Buffer::Copy(
1816
      env,
1817
      reinterpret_cast<const char*>(session_id_data),
1818
289
      session_id_length).ToLocalChecked();
1819
867
  Local<Value> argv[] = { session_id, session };
1820
  // On servers, we pause the handshake until callback of 'newSession', which
1821
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
1822
289
  if (w->is_server())
1823
8
    w->awaiting_new_session_ = true;
1824
289
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1825
1826
289
  return 0;
1827
}
1828
1829
1830
template <class Base>
1831
32
void SSLWrap<Base>::KeylogCallback(const SSL* s, const char* line) {
1832
32
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1833
32
  Environment* env = w->ssl_env();
1834
64
  HandleScope handle_scope(env->isolate());
1835
32
  Context::Scope context_scope(env->context());
1836
1837
32
  const size_t size = strlen(line);
1838
64
  Local<Value> line_bf = Buffer::Copy(env, line, 1 + size).ToLocalChecked();
1839
32
  char* data = Buffer::Data(line_bf);
1840
32
  data[size] = '\n';
1841
32
  w->MakeCallback(env->onkeylog_string(), 1, &line_bf);
1842
32
}
1843
1844
1845
template <class Base>
1846
20
void SSLWrap<Base>::OnClientHello(void* arg,
1847
                                  const ClientHelloParser::ClientHello& hello) {
1848
20
  Base* w = static_cast<Base*>(arg);
1849
20
  Environment* env = w->ssl_env();
1850
40
  HandleScope handle_scope(env->isolate());
1851
20
  Local<Context> context = env->context();
1852
  Context::Scope context_scope(context);
1853
1854
20
  Local<Object> hello_obj = Object::New(env->isolate());
1855
60
  Local<Object> buff = Buffer::Copy(
1856
      env,
1857
20
      reinterpret_cast<const char*>(hello.session_id()),
1858
40
      hello.session_size()).ToLocalChecked();
1859
60
  hello_obj->Set(context, env->session_id_string(), buff).Check();
1860
20
  if (hello.servername() == nullptr) {
1861
8
    hello_obj->Set(context,
1862
                   env->servername_string(),
1863
                   String::Empty(env->isolate())).Check();
1864
  } else {
1865
18
    Local<String> servername = OneByteString(env->isolate(),
1866
                                             hello.servername(),
1867
36
                                             hello.servername_size());
1868
54
    hello_obj->Set(context, env->servername_string(), servername).Check();
1869
  }
1870
80
  hello_obj->Set(context,
1871
                 env->tls_ticket_string(),
1872
20
                 Boolean::New(env->isolate(), hello.has_ticket())).Check();
1873
1874
40
  Local<Value> argv[] = { hello_obj };
1875
20
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1876
20
}
1877
1878
template <class Base>
1879
436
void SSLWrap<Base>::GetPeerCertificate(
1880
    const FunctionCallbackInfo<Value>& args) {
1881
  Base* w;
1882
436
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1883
436
  Environment* env = w->ssl_env();
1884
1885

1308
  bool abbreviated = args.Length() < 1 || !args[0]->IsTrue();
1886
1887
  Local<Value> ret;
1888
872
  if (GetPeerCert(env, w->ssl_, abbreviated, w->is_server()).ToLocal(&ret))
1889
872
    args.GetReturnValue().Set(ret);
1890
}
1891
1892
1893
template <class Base>
1894
12
void SSLWrap<Base>::GetCertificate(
1895
    const FunctionCallbackInfo<Value>& args) {
1896
  Base* w;
1897
12
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1898
12
  Environment* env = w->ssl_env();
1899
1900
  Local<Value> ret;
1901
24
  if (GetCert(env, w->ssl_).ToLocal(&ret))
1902
24
    args.GetReturnValue().Set(ret);
1903
}
1904
1905
1906
template <class Base>
1907
3
void SSLWrap<Base>::GetFinished(const FunctionCallbackInfo<Value>& args) {
1908
3
  Environment* env = Environment::GetCurrent(args);
1909
1910
  Base* w;
1911
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1912
1913
  // We cannot just pass nullptr to SSL_get_finished()
1914
  // because it would further be propagated to memcpy(),
1915
  // where the standard requirements as described in ISO/IEC 9899:2011
1916
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1917
  // Thus, we use a dummy byte.
1918
  char dummy[1];
1919
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
1920
3
  if (len == 0)
1921
1
    return;
1922
1923
4
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, len);
1924
2
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf.data(), len));
1925
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
1926
}
1927
1928
1929
template <class Base>
1930
3
void SSLWrap<Base>::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
1931
3
  Environment* env = Environment::GetCurrent(args);
1932
1933
  Base* w;
1934
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1935
1936
  // We cannot just pass nullptr to SSL_get_peer_finished()
1937
  // because it would further be propagated to memcpy(),
1938
  // where the standard requirements as described in ISO/IEC 9899:2011
1939
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1940
  // Thus, we use a dummy byte.
1941
  char dummy[1];
1942
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
1943
3
  if (len == 0)
1944
1
    return;
1945
1946
4
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, len);
1947
2
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf.data(), len));
1948
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
1949
}
1950
1951
1952
template <class Base>
1953
19
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1954
19
  Environment* env = Environment::GetCurrent(args);
1955
1956
  Base* w;
1957
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1958
1959
19
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
1960
19
  if (sess == nullptr)
1961
    return;
1962
1963
19
  int slen = i2d_SSL_SESSION(sess, nullptr);
1964
19
  if (slen <= 0)
1965
    return;  // Invalid or malformed session.
1966
1967
38
  AllocatedBuffer sbuf = AllocatedBuffer::AllocateManaged(env, slen);
1968
19
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf.data());
1969
19
  CHECK_LT(0, i2d_SSL_SESSION(sess, &p));
1970
57
  args.GetReturnValue().Set(sbuf.ToBuffer().ToLocalChecked());
1971
}
1972
1973
1974
template <class Base>
1975
130
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1976
130
  Environment* env = Environment::GetCurrent(args);
1977
1978
  Base* w;
1979
130
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1980
1981
130
  if (args.Length() < 1)
1982
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
1983
1984
130
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
1985
1986
260
  SSLSessionPointer sess = GetTLSSession(args[0]);
1987
130
  if (sess == nullptr)
1988
    return;
1989
1990
130
  if (!SetTLSSession(w->ssl_, sess))
1991
    return env->ThrowError("SSL_set_session error");
1992
}
1993
1994
1995
template <class Base>
1996
10
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1997
  Base* w;
1998
10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1999
2000
  // TODO(@sam-github) check arg length and types in js, and CHECK in c++
2001

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2002
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
2003
2004
10
    const unsigned char* p = sbuf.data();
2005
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
2006
2007
    // Setup next session and move hello to the BIO buffer
2008
10
    w->next_sess_.reset(sess);
2009
  }
2010
}
2011
2012
2013
template <class Base>
2014
477
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2015
  Base* w;
2016
477
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2017
477
  bool yes = SSL_session_reused(w->ssl_.get());
2018
1431
  args.GetReturnValue().Set(yes);
2019
}
2020
2021
2022
template <class Base>
2023
19
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2024
  Base* w;
2025
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2026
19
  w->hello_parser_.End();
2027
}
2028
2029
2030
template <class Base>
2031
92
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2032
  Base* w;
2033
93
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2034
2035
91
  ClearErrorOnReturn clear_error_on_return;
2036
2037
92
  if (SSL_renegotiate(w->ssl_.get()) != 1) {
2038
1
    return ThrowCryptoError(w->ssl_env(), ERR_get_error());
2039
  }
2040
}
2041
2042
2043
template <class Base>
2044
18
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2045
  Base* w;
2046
18
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2047
18
  Environment* env = w->ssl_env();
2048
2049
18
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2050
18
  if (sess == nullptr)
2051
    return;
2052
2053
  const unsigned char* ticket;
2054
  size_t length;
2055
18
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2056
2057
18
  if (ticket == nullptr)
2058
    return;
2059
2060
36
  Local<Object> buff = Buffer::Copy(
2061
18
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2062
2063
36
  args.GetReturnValue().Set(buff);
2064
}
2065
2066
2067
template <class Base>
2068
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2069
  Base* w;
2070
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2071
8
  w->awaiting_new_session_ = false;
2072
8
  w->NewSessionDoneCb();
2073
}
2074
2075
2076
template <class Base>
2077
2
void SSLWrap<Base>::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
2078
  Base* w;
2079
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2080
2
  Environment* env = w->env();
2081
2082
2
  if (args.Length() < 1)
2083
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
2084
2085
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
2086
2087
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
2088
}
2089
2090
2091
template <class Base>
2092
4
void SSLWrap<Base>::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
2093
  Base* w;
2094
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2095
2096
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
2097
}
2098
2099
2100
template <class Base>
2101
817
void SSLWrap<Base>::GetEphemeralKeyInfo(
2102
    const FunctionCallbackInfo<Value>& args) {
2103
  Base* w;
2104
824
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2105
817
  Environment* env = Environment::GetCurrent(args);
2106
2107
817
  CHECK(w->ssl_);
2108
2109
  // tmp key is available on only client
2110
817
  if (w->is_server())
2111
14
    return args.GetReturnValue().SetNull();
2112
2113
  Local<Object> ret;
2114
1620
  if (GetEphemeralKey(env, w->ssl_).ToLocal(&ret))
2115
1620
    args.GetReturnValue().Set(ret);
2116
2117
  // TODO(@sam-github) semver-major: else return ThrowCryptoError(env,
2118
  // ERR_get_error())
2119
}
2120
2121
2122
#ifdef SSL_set_max_send_fragment
2123
template <class Base>
2124
3
void SSLWrap<Base>::SetMaxSendFragment(
2125
    const FunctionCallbackInfo<Value>& args) {
2126

9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2127
2128
  Base* w;
2129
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2130
2131
12
  int rv = SSL_set_max_send_fragment(
2132
      w->ssl_.get(),
2133
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2134
6
  args.GetReturnValue().Set(rv);
2135
}
2136
#endif  // SSL_set_max_send_fragment
2137
2138
2139
template <class Base>
2140
880
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2141
  Base* w;
2142
1347
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2143
2144
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2145
  // peer certificate is questionable but it's compatible with what was
2146
  // here before.
2147
  long x509_verify_error =  // NOLINT(runtime/int)
2148
880
      VerifyPeerCertificate(w->ssl_, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT);
2149
2150
880
  if (x509_verify_error == X509_V_OK)
2151
934
    return args.GetReturnValue().SetNull();
2152
2153
413
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2154
413
  const char* code = reason;
2155
413
  code = X509ErrorCode(x509_verify_error);
2156
2157
413
  Isolate* isolate = args.GetIsolate();
2158
413
  Local<String> reason_string = OneByteString(isolate, reason);
2159
413
  Local<Value> exception_value = Exception::Error(reason_string);
2160
  Local<Object> exception_object =
2161
1239
    exception_value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2162
  exception_object->Set(w->env()->context(), w->env()->code_string(),
2163
2065
                        OneByteString(isolate, code)).Check();
2164
826
  args.GetReturnValue().Set(exception_object);
2165
}
2166
2167
2168
template <class Base>
2169
49
void SSLWrap<Base>::GetCipher(const FunctionCallbackInfo<Value>& args) {
2170
  Base* w;
2171
49
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2172
49
  Environment* env = w->ssl_env();
2173
2174
49
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get());
2175
49
  if (c == nullptr)
2176
    return;
2177
2178
  Local<Object> ret;
2179
98
  if (GetCipherInfo(env, w->ssl_).ToLocal(&ret))
2180
98
    args.GetReturnValue().Set(ret);
2181
}
2182
2183
2184
template <class Base>
2185
2
void SSLWrap<Base>::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
2186
  Base* w;
2187
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2188
2
  Environment* env = w->ssl_env();
2189
2190
2
  SSL* ssl = w->ssl_.get();
2191
  int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
2192
2
                                    nullptr);
2193
4
  MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
2194
2195
5
  for (int i = 0; i < nsig; i++) {
2196
    int hash_nid;
2197
    int sign_nid;
2198
6
    std::string sig_with_md;
2199
2200
3
    SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
2201
                           nullptr);
2202
2203

3
    switch (sign_nid) {
2204
      case EVP_PKEY_RSA:
2205
        sig_with_md = "RSA+";
2206
        break;
2207
2208
      case EVP_PKEY_RSA_PSS:
2209
2
        sig_with_md = "RSA-PSS+";
2210
2
        break;
2211
2212
      case EVP_PKEY_DSA:
2213
        sig_with_md = "DSA+";
2214
        break;
2215
2216
      case EVP_PKEY_EC:
2217
1
        sig_with_md = "ECDSA+";
2218
1
        break;
2219
2220
      case NID_ED25519:
2221
        sig_with_md = "Ed25519+";
2222
        break;
2223
2224
      case NID_ED448:
2225
        sig_with_md = "Ed448+";
2226
        break;
2227
#ifndef OPENSSL_NO_GOST
2228
      case NID_id_GostR3410_2001:
2229
        sig_with_md = "gost2001+";
2230
        break;
2231
2232
      case NID_id_GostR3410_2012_256:
2233
        sig_with_md = "gost2012_256+";
2234
        break;
2235
2236
      case NID_id_GostR3410_2012_512:
2237
        sig_with_md = "gost2012_512+";
2238
        break;
2239
#endif  // !OPENSSL_NO_GOST
2240
      default:
2241
        const char* sn = OBJ_nid2sn(sign_nid);
2242
2243
        if (sn != nullptr) {
2244
          sig_with_md = std::string(sn) + "+";
2245
        } else {
2246
          sig_with_md = "UNDEF+";
2247
        }
2248
        break;
2249
    }
2250
2251
3
    const char* sn_hash = OBJ_nid2sn(hash_nid);
2252
3
    if (sn_hash != nullptr) {
2253
3
      sig_with_md += std::string(sn_hash);
2254
    } else {
2255
      sig_with_md += "UNDEF";
2256
    }
2257
6
    ret_arr[i] = OneByteString(env->isolate(), sig_with_md.c_str());
2258
  }
2259
2260
6
  args.GetReturnValue().Set(
2261
                 Array::New(env->isolate(), ret_arr.out(), ret_arr.length()));
2262
}
2263
2264
template <class Base>
2265
3
void SSLWrap<Base>::ExportKeyingMaterial(
2266
    const FunctionCallbackInfo<Value>& args) {
2267
6
  CHECK(args[0]->IsInt32());
2268
9
  CHECK(args[1]->IsString());
2269
2270
  Base* w;
2271
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2272
3
  Environment* env = w->ssl_env();
2273
2274
9
  uint32_t olen = args[0].As<Uint32>()->Value();
2275
6
  node::Utf8Value label(env->isolate(), args[1]);
2276
2277
6
  AllocatedBuffer out = AllocatedBuffer::AllocateManaged(env, olen);
2278
2279
6
  ByteSource context;
2280
9
  bool use_context = !args[2]->IsUndefined();
2281
3
  if (use_context)
2282
2
    context = ByteSource::FromBuffer(args[2]);
2283
2284
12
  if (SSL_export_keying_material(w->ssl_.get(),
2285
3
                                 reinterpret_cast<unsigned char*>(out.data()),
2286
                                 olen,
2287
3
                                 *label,
2288
                                 label.length(),
2289
                                 reinterpret_cast<const unsigned char*>(
2290
3
                                     context.get()),
2291
                                 context.size(),
2292
                                 use_context) != 1) {
2293
    return ThrowCryptoError(env, ERR_get_error(), "SSL_export_keying_material");
2294
  }
2295
2296
9
  args.GetReturnValue().Set(out.ToBuffer().ToLocalChecked());
2297
}
2298
2299
template <class Base>
2300
547
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2301
  Base* w;
2302
547
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2303
2304
547
  const char* tls_version = SSL_get_version(w->ssl_.get());
2305
1641
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2306
}
2307
2308
2309
template <class Base>
2310
26
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2311
                                      const unsigned char** out,
2312
                                      unsigned char* outlen,
2313
                                      const unsigned char* in,
2314
                                      unsigned int inlen,
2315
                                      void* arg) {
2316
26
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2317
26
  Environment* env = w->env();
2318
52
  HandleScope handle_scope(env->isolate());
2319
26
  Context::Scope context_scope(env->context());
2320
2321
  Local<Value> alpn_buffer =
2322
52
      w->object()->GetPrivate(
2323
          env->context(),
2324
78
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2325
26
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
2326
26
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2327
26
                                     alpn_protos.data(), alpn_protos.length(),
2328
26
                                     in, inlen);
2329
  // According to 3.2. Protocol Selection of RFC7301, fatal
2330
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2331
  // support it yet. See
2332
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2333
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2334
52
                                          : SSL_TLSEXT_ERR_NOACK;
2335
}
2336
2337
2338
template <class Base>
2339
1630
void SSLWrap<Base>::GetALPNNegotiatedProto(
2340
    const FunctionCallbackInfo<Value>& args) {
2341
  Base* w;
2342
1630
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2343
2344
  const unsigned char* alpn_proto;
2345
  unsigned int alpn_proto_len;
2346
2347
1630
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2348
2349
  Local<Value> result;
2350
1630
  if (alpn_proto_len == 0) {
2351
3164
    result = False(args.GetIsolate());
2352

90
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
2353
42
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
2354
84
    result = w->env()->h2_string();
2355

8
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
2356
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
2357
4
    result = w->env()->http_1_1_string();
2358
  } else {
2359
12
    result = OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len);
2360
  }
2361
2362
3260
  args.GetReturnValue().Set(result);
2363
}
2364
2365
2366
template <class Base>
2367
205
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2368
  Base* w;
2369
205
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2370
205
  Environment* env = w->env();
2371

410
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2372
    return env->ThrowTypeError("Must give a Buffer as first argument");
2373
2374
205
  if (w->is_client()) {
2375
31
    CHECK(SetALPN(w->ssl_, args[0]));
2376
  } else {
2377
522
    CHECK(
2378
        w->object()->SetPrivate(
2379
            env->context(),
2380
            env->alpn_buffer_private_symbol(),
2381
            args[0]).FromJust());
2382
    // Server should select ALPN protocol from list of advertised by client
2383
174
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2384
                               SelectALPNCallback,
2385
                               nullptr);
2386
  }
2387
}
2388
2389
2390
template <class Base>
2391
8
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2392
8
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2393
8
  Environment* env = w->env();
2394
16
  HandleScope handle_scope(env->isolate());
2395
2396
8
  if (w->is_client()) {
2397
    // Incoming response
2398
    Local<Value> arg;
2399
8
    MaybeLocal<Value> ret = GetSSLOCSPResponse(env, s, Null(env->isolate()));
2400
4
    if (ret.ToLocal(&arg))
2401
4
      w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2402
2403
    // No async acceptance is possible, so always return 1 to accept the
2404
    // response.  The listener for 'OCSPResponse' event has no control over
2405
    // return value, but it can .destroy() the connection if the response is not
2406
    // acceptable.
2407
4
    return 1;
2408
  } else {
2409
    // Outgoing response
2410
8
    if (w->ocsp_response_.IsEmpty())
2411
2
      return SSL_TLSEXT_ERR_NOACK;
2412
2413
2
    Local<ArrayBufferView> obj = PersistentToLocal::Default(env->isolate(),
2414
2
                                                            w->ocsp_response_);
2415
2
    size_t len = obj->ByteLength();
2416
2417
    // OpenSSL takes control of the pointer after accepting it
2418
2
    unsigned char* data = MallocOpenSSL<unsigned char>(len);
2419
2
    obj->CopyContents(data, len);
2420
2421
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2422
      OPENSSL_free(data);
2423
2
    w->ocsp_response_.Reset();
2424
2425
2
    return SSL_TLSEXT_ERR_OK;
2426
  }
2427
}
2428
2429
2430
template <class Base>
2431
22
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2432
22
  cert_cb_ = cb;
2433
22
  cert_cb_arg_ = arg;
2434
22
}
2435
2436
2437
template <class Base>
2438
879
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2439
879
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2440
2441
879
  if (!w->is_server())
2442
41
    return 1;
2443
2444
838
  if (!w->is_waiting_cert_cb())
2445
816
    return 1;
2446
2447
22
  if (w->cert_cb_running_)
2448
    // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
2449
    // handshake will continue after certcb is done.
2450
    return -1;
2451
2452
22
  Environment* env = w->env();
2453
22
  Local<Context> context = env->context();
2454
44
  HandleScope handle_scope(env->isolate());
2455
  Context::Scope context_scope(context);
2456
22
  w->cert_cb_running_ = true;
2457
2458
22
  Local<Object> info = Object::New(env->isolate());
2459
2460
22
  const char* servername = GetServerName(s);
2461
22
  if (servername == nullptr) {
2462
16
    info->Set(context,
2463
              env->servername_string(),
2464
              String::Empty(env->isolate())).Check();
2465
  } else {
2466
18
    Local<String> str = OneByteString(env->isolate(), servername,
2467
36
                                      strlen(servername));
2468
54
    info->Set(context, env->servername_string(), str).Check();
2469
  }
2470
2471
22
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
2472
88
  info->Set(context, env->ocsp_request_string(),
2473
            Boolean::New(env->isolate(), ocsp)).Check();
2474
2475
44
  Local<Value> argv[] = { info };
2476
22
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2477
2478
22
  if (!w->cert_cb_running_)
2479
10
    return 1;
2480
2481
  // Performing async action, wait...
2482
12
  return -1;
2483
}
2484
2485
2486
template <class Base>
2487
19
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2488
  Base* w;
2489
21
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2490
19
  Environment* env = w->env();
2491
2492

19
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2493
2494
19
  Local<Object> object = w->object();
2495
76
  Local<Value> ctx = object->Get(env->context(),
2496
19
                                 env->sni_context_string()).ToLocalChecked();
2497
19
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2498
2499
  // Not an object, probably undefined or null
2500
19
  if (!ctx->IsObject())
2501
8
    goto fire_cb;
2502
2503
11
  if (cons->HasInstance(ctx)) {
2504
9
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
2505
9
    CHECK_NOT_NULL(sc);
2506
    // Store the SNI context for later use.
2507
9
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
2508
2509


9
    if (UseSNIContext(w->ssl_, w->sni_context_) && !w->SetCACerts(sc)) {
2510
      // Not clear why sometimes we throw error, and sometimes we call
2511
      // onerror(). Both cause .destroy(), but onerror does a bit more.
2512
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2513
      return ThrowCryptoError(env, err, "CertCbDone");
2514
    }
2515
  } else {
2516
    // Failure: incorrect SNI context object
2517
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2518
2
    w->MakeCallback(env->onerror_string(), 1, &err);
2519
2
    return;
2520
  }
2521
2522
 fire_cb:
2523
  CertCb cb;
2524
  void* arg;
2525
2526
17
  cb = w->cert_cb_;
2527
17
  arg = w->cert_cb_arg_;
2528
2529
17
  w->cert_cb_running_ = false;
2530
17
  w->cert_cb_ = nullptr;
2531
17
  w->cert_cb_arg_ = nullptr;
2532
2533
17
  cb(arg);
2534
}
2535
2536
2537
template <class Base>
2538
24281
void SSLWrap<Base>::DestroySSL() {
2539
24281
  if (!ssl_)
2540
12105
    return;
2541
2542
12176
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2543
12176
  ssl_.reset();
2544
}
2545
2546
2547
template <class Base>
2548
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2549
8
  int err = SSL_set1_verify_cert_store(ssl_.get(),
2550
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
2551
8
  if (err != 1)
2552
    return err;
2553
2554
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2555
8
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
2556
2557
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2558
8
  SSL_set_client_CA_list(ssl_.get(), list);
2559
8
  return 1;
2560
}
2561
2562
template <class Base>
2563
void SSLWrap<Base>::MemoryInfo(MemoryTracker* tracker) const {
2564
  tracker->TrackField("ocsp_response", ocsp_response_);
2565
  tracker->TrackField("sni_context", sni_context_);
2566
}
2567
2568
1939
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2569
  // From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
2570
  //
2571
  //   If VerifyCallback returns 1, the verification process is continued. If
2572
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
2573
  //   terminated with respect to verification failures and the connection will
2574
  //   be established. The calling process can however retrieve the error code
2575
  //   of the last verification error using SSL_get_verify_result(3) or by
2576
  //   maintaining its own error storage managed by VerifyCallback.
2577
  //
2578
  // Since we cannot perform I/O quickly enough with X509_STORE_CTX_ APIs in
2579
  // this callback, we ignore all preverify_ok errors and let the handshake
2580
  // continue. It is imperative that the user use Connection::VerifyError after
2581
  // the 'secure' callback has been made.
2582
1939
  return 1;
2583
}
2584
2585
3474
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
2586
3474
  const int mode = EVP_CIPHER_mode(cipher);
2587
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
2588
  // but its mode is 0 which doesn't indicate
2589
6901
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
2590
6202
         mode == EVP_CIPH_CCM_MODE ||
2591

7591
         mode == EVP_CIPH_GCM_MODE ||
2592
4816
         IS_OCB_MODE(mode);
2593
}
2594
2595
1538
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
2596
1538
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
2597
1538
  return IsSupportedAuthenticatedMode(cipher);
2598
}
2599
2600
enum class ParseKeyResult {
2601
  kParseKeyOk,
2602
  kParseKeyNotRecognized,
2603
  kParseKeyNeedPassphrase,
2604
  kParseKeyFailed
2605
};
2606
2607
2927
static ParseKeyResult TryParsePublicKey(
2608
    EVPKeyPointer* pkey,
2609
    const BIOPointer& bp,
2610
    const char* name,
2611
    // NOLINTNEXTLINE(runtime/int)
2612
    const std::function<EVP_PKEY*(const unsigned char** p, long l)>& parse) {
2613
  unsigned char* der_data;
2614
  long der_len;  // NOLINT(runtime/int)
2615
2616
  // This skips surrounding data and decodes PEM to DER.
2617
  {
2618
3799
    MarkPopErrorOnReturn mark_pop_error_on_return;
2619
2927
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
2620
                           bp.get(), nullptr, nullptr) != 1)
2621
2055
      return ParseKeyResult::kParseKeyNotRecognized;
2622
  }
2623
2624
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
2625
872
  const unsigned char* p = der_data;
2626
872
  pkey->reset(parse(&p, der_len));
2627
872
  OPENSSL_clear_free(der_data, der_len);
2628
2629
872
  return *pkey ? ParseKeyResult::kParseKeyOk :
2630
1744
                 ParseKeyResult::kParseKeyFailed;
2631
}
2632
2633
1062
static ParseKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
2634
                                        const char* key_pem,
2635
                                        int key_pem_len) {
2636
2124
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
2637
1062
  if (!bp)
2638
    return ParseKeyResult::kParseKeyFailed;
2639
2640
  ParseKeyResult ret;
2641
2642
  // Try parsing as a SubjectPublicKeyInfo first.
2643
2124
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
2644
122
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2645
        return d2i_PUBKEY(nullptr, p, l);
2646
1184
      });
2647
1062
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
2648
122
    return ret;
2649
2650
  // Maybe it is PKCS#1.
2651
940
  CHECK(BIO_reset(bp.get()));
2652
1880
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
2653
15
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2654
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
2655
955
      });
2656
940
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
2657
15
    return ret;
2658
2659
  // X.509 fallback.
2660
925
  CHECK(BIO_reset(bp.get()));
2661
1850
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
2662
735
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2663
1470
        X509Pointer x509(d2i_X509(nullptr, p, l));
2664
1470
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
2665
925
      });
2666
}
2667
2668
22
static ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
2669
                                     const PublicKeyEncodingConfig& config,
2670
                                     const char* key,
2671
                                     size_t key_len) {
2672
22
  if (config.format_ == kKeyFormatPEM) {
2673
    return ParsePublicKeyPEM(pkey, key, key_len);
2674
  } else {
2675
22
    CHECK_EQ(config.format_, kKeyFormatDER);
2676
2677
22
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2678
44
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2679
22
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2680
    } else {
2681
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2682
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
2683
    }
2684
2685
22
    return *pkey ? ParseKeyResult::kParseKeyOk :
2686
44
                   ParseKeyResult::kParseKeyFailed;
2687
  }
2688
}
2689
2690
57
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
2691
                                               BIO* bio,
2692
                                               PKFormatType format) {
2693
  BUF_MEM* bptr;
2694
57
  BIO_get_mem_ptr(bio, &bptr);
2695
57
  if (format == kKeyFormatPEM) {
2696
    // PEM is an ASCII format, so we will return it as a string.
2697
141
    return String::NewFromUtf8(env->isolate(), bptr->data,
2698
                               NewStringType::kNormal,
2699
141
                               bptr->length).ToLocalChecked();
2700
  } else {
2701
10
    CHECK_EQ(format, kKeyFormatDER);
2702
    // DER is binary, return it as a buffer.
2703
20
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
2704
  }
2705
}
2706
2707
30
static bool WritePublicKeyInner(EVP_PKEY* pkey,
2708
                                const BIOPointer& bio,
2709
                                const PublicKeyEncodingConfig& config) {
2710
60
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2711
    // PKCS#1 is only valid for RSA keys.
2712
13
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
2713
26
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
2714
13
    if (config.format_ == kKeyFormatPEM) {
2715
      // Encode PKCS#1 as PEM.
2716
7
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
2717
    } else {
2718
      // Encode PKCS#1 as DER.
2719
6
      CHECK_EQ(config.format_, kKeyFormatDER);
2720
6
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
2721
    }
2722
  } else {
2723
34
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2724
17
    if (config.format_ == kKeyFormatPEM) {
2725
      // Encode SPKI as PEM.
2726
17
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
2727
    } else {
2728
      // Encode SPKI as DER.
2729
      CHECK_EQ(config.format_, kKeyFormatDER);
2730
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
2731
    }
2732
  }
2733
}
2734
2735
30
static MaybeLocal<Value> WritePublicKey(Environment* env,
2736
                                        EVP_PKEY* pkey,
2737
                                        const PublicKeyEncodingConfig& config) {
2738
60
  BIOPointer bio(BIO_new(BIO_s_mem()));
2739
30
  CHECK(bio);
2740
2741
30
  if (!WritePublicKeyInner(pkey, bio, config)) {
2742
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
2743
    return MaybeLocal<Value>();
2744
  }
2745
60
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
2746
}
2747
2748
58
static bool IsASN1Sequence(const unsigned char* data, size_t size,
2749
                           size_t* data_offset, size_t* data_size) {
2750

58
  if (size < 2 || data[0] != 0x30)
2751
    return false;
2752
2753
58
  if (data[1] & 0x80) {
2754
    // Long form.
2755
38
    size_t n_bytes = data[1] & ~0x80;
2756

38
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
2757
      return false;
2758
38
    size_t length = 0;
2759
114
    for (size_t i = 0; i < n_bytes; i++)
2760
76
      length = (length << 8) | data[i + 2];
2761
38
    *data_offset = 2 + n_bytes;
2762
38
    *data_size = std::min(size - 2 - n_bytes, length);
2763
  } else {
2764
    // Short form.
2765
20
    *data_offset = 2;
2766
20
    *data_size = std::min<size_t>(size - 2, data[1]);
2767
  }
2768
2769
58
  return true;
2770
}
2771
2772
32
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
2773
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
2774
  size_t offset, len;
2775
32
  if (!IsASN1Sequence(data, size, &offset, &len))
2776
    return false;
2777
2778
  // An RSAPrivateKey sequence always starts with a single-byte integer whose
2779
  // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
2780
  // (which is the product of two primes and therefore at least 4), so we can
2781
  // decide the type of the structure based on the first three bytes of the
2782
  // sequence.
2783
64
  return len >= 3 &&
2784
64
         data[offset] == 2 &&
2785

74
         data[offset + 1] == 1 &&
2786
42
         !(data[offset + 2] & 0xfe);
2787
}
2788
2789
26
static bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
2790
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
2791
  size_t offset, len;
2792
26
  if (!IsASN1Sequence(data, size, &offset, &len))
2793
    return false;
2794
2795
  // A PrivateKeyInfo sequence always starts with an integer whereas an
2796
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
2797

52
  return len >= 1 &&
2798
52
         data[offset] != 2;
2799
}
2800
2801
397
static ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
2802
                                      const PrivateKeyEncodingConfig& config,
2803
                                      const char* key,
2804
                                      size_t key_len) {
2805
  // OpenSSL needs a non-const pointer, that's why the const_cast is required.
2806
397
  char* const passphrase = const_cast<char*>(config.passphrase_.get());
2807
2808
397
  if (config.format_ == kKeyFormatPEM) {
2809
719
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
2810
360
    if (!bio)
2811
1
      return ParseKeyResult::kParseKeyFailed;
2812
2813
359
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
2814
                                        nullptr,
2815
                                        PasswordCallback,
2816
359
                                        passphrase));
2817
  } else {
2818
37
    CHECK_EQ(config.format_, kKeyFormatDER);
2819
2820
74
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2821
11
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2822
11
      pkey->reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2823
52
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
2824
52
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
2825
26
      if (!bio)
2826
        return ParseKeyResult::kParseKeyFailed;
2827
2828
26
      if (IsEncryptedPrivateKeyInfo(
2829
              reinterpret_cast<const unsigned char*>(key), key_len)) {
2830
17
        pkey->reset(d2i_PKCS8PrivateKey_bio(bio.get(),
2831
                                            nullptr,
2832
                                            PasswordCallback,
2833
17
                                            passphrase));
2834
      } else {
2835
18
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
2836
9
        if (p8inf)
2837
9
          pkey->reset(EVP_PKCS82PKEY(p8inf.get()));
2838
      }
2839
    } else {
2840
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
2841
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2842
      pkey->reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
2843
    }
2844
  }
2845
2846
  // OpenSSL can fail to parse the key but still return a non-null pointer.
2847
396
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
2848
396
  if (err != 0)
2849
19
    pkey->reset();
2850
2851
396
  if (*pkey)
2852
377
    return ParseKeyResult::kParseKeyOk;
2853

30
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
2854
11
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
2855
10
    if (config.passphrase_.get() == nullptr)
2856
9
      return ParseKeyResult::kParseKeyNeedPassphrase;
2857
  }
2858
10
  return ParseKeyResult::kParseKeyFailed;
2859
}
2860
2861
2506
ByteSource::ByteSource(ByteSource&& other)
2862
2506
      : data_(other.data_),
2863
2506
        allocated_data_(other.allocated_data_),
2864
5012
        size_(other.size_) {
2865
2506
  other.allocated_data_ = nullptr;
2866
2506
}
2867
2868
15334
ByteSource::~ByteSource() {
2869
7667
  OPENSSL_clear_free(allocated_data_, size_);
2870
7667
}
2871
2872
109
ByteSource& ByteSource::operator=(ByteSource&& other) {
2873
109
  if (&other != this) {
2874
109
    OPENSSL_clear_free(allocated_data_, size_);
2875
109
    data_ = other.data_;
2876
109
    allocated_data_ = other.allocated_data_;
2877
109
    other.allocated_data_ = nullptr;
2878
109
    size_ = other.size_;
2879
  }
2880
109
  return *this;
2881
}
2882
2883
4349
const char* ByteSource::get() const {
2884
4349
  return data_;
2885
}
2886
2887
3938
size_t ByteSource::size() const {
2888
3938
  return size_;
2889
}
2890
2891
2624
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
2892
                                          Local<Value> value) {
2893
2624
  return Buffer::HasInstance(value) ? FromBuffer(value)
2894
3010
                                    : FromString(env, value.As<String>());
2895
}
2896
2897
461
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
2898
                                  bool ntc) {
2899
922
  CHECK(str->IsString());
2900
922
  size_t size = str->Utf8Length(env->isolate());
2901
461
  size_t alloc_size = ntc ? size + 1 : size;
2902
461
  char* data = MallocOpenSSL<char>(alloc_size);
2903
461
  int opts = String::NO_OPTIONS;
2904
461
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
2905
922
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
2906
461
  return Allocated(data, size);
2907
}
2908
2909
2251
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
2910
2251
  CHECK(buffer->IsArrayBufferView());
2911
2251
  Local<ArrayBufferView> abv = buffer.As<ArrayBufferView>();
2912
2251
  size_t size = abv->ByteLength();
2913
2251
  if (ntc) {
2914
11
    char* data = MallocOpenSSL<char>(size + 1);
2915
11
    abv->CopyContents(data, size);
2916
11
    data[size] = 0;
2917
11
    return Allocated(data, size);
2918
  }
2919
2240
  return Foreign(Buffer::Data(buffer), size);
2920
}
2921
2922
86
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
2923
                                          Local<Value> value) {
2924
86
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
2925
161
                                    : FromString(env, value.As<String>(), true);
2926
}
2927
2928
14
ByteSource ByteSource::FromSymmetricKeyObjectHandle(Local<Value> handle) {
2929
14
  CHECK(handle->IsObject());
2930
14
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(handle.As<Object>());
2931
14
  CHECK_NOT_NULL(key);
2932
14
  return Foreign(key->Data()->GetSymmetricKey(),
2933
28
                 key->Data()->GetSymmetricKeySize());
2934
}
2935
2936
3796
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
2937
      : data_(data),
2938
        allocated_data_(allocated_data),
2939
3796
        size_(size) {}
2940
2941
480
ByteSource ByteSource::Allocated(char* data, size_t size) {
2942
480
  return ByteSource(data, data, size);
2943
}
2944
2945
3316
ByteSource ByteSource::Foreign(const char* data, size_t size) {
2946
3316
  return ByteSource(data, nullptr, size);
2947
}
2948
2949
enum KeyEncodingContext {
2950
  kKeyContextInput,
2951
  kKeyContextExport,
2952
  kKeyContextGenerate
2953
};
2954
2955
1410
static void GetKeyFormatAndTypeFromJs(
2956
    AsymmetricKeyEncodingConfig* config,
2957
    const FunctionCallbackInfo<Value>& args,
2958
    unsigned int* offset,
2959
    KeyEncodingContext context) {
2960
  // During key pair generation, it is possible not to specify a key encoding,
2961
  // which will lead to a key object being returned.
2962
5640
  if (args[*offset]->IsUndefined()) {
2963
60
    CHECK_EQ(context, kKeyContextGenerate);
2964
240
    CHECK(args[*offset + 1]->IsUndefined());
2965
60
    config->output_key_object_ = true;
2966
  } else {
2967
1350
    config->output_key_object_ = false;
2968
2969
4050
    CHECK(args[*offset]->IsInt32());
2970
1350
    config->format_ = static_cast<PKFormatType>(
2971
6750
        args[*offset].As<Int32>()->Value());
2972
2973
4050
    if (args[*offset + 1]->IsInt32()) {
2974
236
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
2975
708
          args[*offset + 1].As<Int32>()->Value()));
2976
    } else {
2977

1232
      CHECK(context == kKeyContextInput && config->format_ == kKeyFormatPEM);
2978
4928
      CHECK(args[*offset + 1]->IsNullOrUndefined());
2979
1232
      config->type_ = Nothing<PKEncodingType>();
2980
    }
2981
  }
2982
2983
1410
  *offset += 2;
2984
1410
}
2985
2986
61
static PublicKeyEncodingConfig GetPublicKeyEncodingFromJs(
2987
    const FunctionCallbackInfo<Value>& args,
2988
    unsigned int* offset,
2989
    KeyEncodingContext context) {
2990
61
  PublicKeyEncodingConfig result;
2991
61
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
2992
61
  return result;
2993
}
2994
2995
1291
static inline ManagedEVPPKey GetParsedKey(Environment* env,
2996
                                          EVPKeyPointer&& pkey,
2997
                                          ParseKeyResult ret,
2998
                                          const char* default_msg) {
2999
1291
  switch (ret) {
3000
    case ParseKeyResult::kParseKeyOk:
3001
1271
      CHECK(pkey);
3002
1271
      break;
3003
    case ParseKeyResult::kParseKeyNeedPassphrase:
3004
      THROW_ERR_MISSING_PASSPHRASE(env,
3005
9
                                   "Passphrase required for encrypted key");
3006
9
      break;
3007
    default:
3008
11
      ThrowCryptoError(env, ERR_get_error(), default_msg);
3009
  }
3010
3011
1291
  return ManagedEVPPKey(std::move(pkey));
3012
}
3013
3014
1349
static NonCopyableMaybe<PrivateKeyEncodingConfig> GetPrivateKeyEncodingFromJs(
3015
    const FunctionCallbackInfo<Value>& args,
3016
    unsigned int* offset,
3017
    KeyEncodingContext context) {
3018
1349
  Environment* env = Environment::GetCurrent(args);
3019
3020
2698
  PrivateKeyEncodingConfig result;
3021
1349
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3022
3023
1349
  if (result.output_key_object_) {
3024
30
    if (context != kKeyContextInput)
3025
30
      (*offset)++;
3026
  } else {
3027
1319
    bool needs_passphrase = false;
3028
1319
    if (context != kKeyContextInput) {
3029
112
      if (args[*offset]->IsString()) {
3030
        String::Utf8Value cipher_name(env->isolate(),
3031
35
                                      args[*offset].As<String>());
3032
9
        result.cipher_ = EVP_get_cipherbyname(*cipher_name);
3033
9
        if (result.cipher_ == nullptr) {
3034
1
          THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env);
3035
1
          return NonCopyableMaybe<PrivateKeyEncodingConfig>();
3036
        }
3037
8
        needs_passphrase = true;
3038
      } else {
3039
76
        CHECK(args[*offset]->IsNullOrUndefined());
3040
19
        result.cipher_ = nullptr;
3041
      }
3042
27
      (*offset)++;
3043
    }
3044
3045

6515
    if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3046

86
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
3047
3048
172
      result.passphrase_ = ByteSource::NullTerminatedCopy(env, args[*offset]);
3049
    } else {
3050

4928
      CHECK(args[*offset]->IsNullOrUndefined() && !needs_passphrase);
3051
    }
3052
  }
3053
3054
1348
  (*offset)++;
3055
1348
  return NonCopyableMaybe<PrivateKeyEncodingConfig>(std::move(result));
3056
}
3057
3058
212
static ManagedEVPPKey GetPrivateKeyFromJs(
3059
    const FunctionCallbackInfo<Value>& args,
3060
    unsigned int* offset,
3061
    bool allow_key_object) {
3062

981
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3063
179
    Environment* env = Environment::GetCurrent(args);
3064
537
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3065
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3066
358
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3067
179
    if (config.IsEmpty())
3068
      return ManagedEVPPKey();
3069
3070
358
    EVPKeyPointer pkey;
3071
    ParseKeyResult ret =
3072
179
        ParsePrivateKey(&pkey, config.Release(), key.get(), key.size());
3073
179
    return GetParsedKey(env, std::move(pkey), ret,
3074
179
                        "Failed to read private key");
3075
  } else {
3076

99
    CHECK(args[*offset]->IsObject() && allow_key_object);
3077
    KeyObjectHandle* key;
3078
99
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
3079
33
    CHECK_EQ(key->Data()->GetKeyType(), kKeyTypePrivate);
3080
33
    (*offset) += 4;
3081
33
    return key->Data()->GetAsymmetricKey();
3082
  }
3083
}
3084
3085
1215
static ManagedEVPPKey GetPublicOrPrivateKeyFromJs(
3086
    const FunctionCallbackInfo<Value>& args,
3087
    unsigned int* offset) {
3088

5863
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3089
1112
    Environment* env = Environment::GetCurrent(args);
3090
3336
    ByteSource data = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3091
    NonCopyableMaybe<PrivateKeyEncodingConfig> config_ =
3092
2224
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3093
1112
    if (config_.IsEmpty())
3094
      return ManagedEVPPKey();
3095
3096
    ParseKeyResult ret;
3097
2224
    PrivateKeyEncodingConfig config = config_.Release();
3098
2224
    EVPKeyPointer pkey;
3099
1112
    if (config.format_ == kKeyFormatPEM) {
3100
      // For PEM, we can easily determine whether it is a public or private key
3101
      // by looking for the respective PEM tags.
3102
1062
      ret = ParsePublicKeyPEM(&pkey, data.get(), data.size());
3103
1062
      if (ret == ParseKeyResult::kParseKeyNotRecognized) {
3104
190
        ret = ParsePrivateKey(&pkey, config, data.get(), data.size());
3105
      }
3106
    } else {
3107
      // For DER, the type determines how to parse it. SPKI, PKCS#8 and SEC1 are
3108
      // easy, but PKCS#1 can be a public key or a private key.
3109
      bool is_public;
3110

50
      switch (config.type_.ToChecked()) {
3111
        case kKeyEncodingPKCS1:
3112
64
          is_public = !IsRSAPrivateKey(
3113
32
              reinterpret_cast<const unsigned char*>(data.get()), data.size());
3114
32
          break;
3115
        case kKeyEncodingSPKI:
3116
          is_public = true;
3117
          break;
3118
        case kKeyEncodingPKCS8:
3119
        case kKeyEncodingSEC1:
3120
18
          is_public = false;
3121
18
          break;
3122
        default:
3123
          UNREACHABLE("Invalid key encoding type");
3124
      }
3125
3126
50
      if (is_public) {
3127
22
        ret = ParsePublicKey(&pkey, config, data.get(), data.size());
3128
      } else {
3129
28
        ret = ParsePrivateKey(&pkey, config, data.get(), data.size());
3130
      }
3131
    }
3132
3133
1112
    return GetParsedKey(env, std::move(pkey), ret,
3134
1112
                        "Failed to read asymmetric key");
3135
  } else {
3136
309
    CHECK(args[*offset]->IsObject());
3137
309
    KeyObjectHandle* key = Unwrap<KeyObjectHandle>(args[*offset].As<Object>());
3138
103
    CHECK_NOT_NULL(key);
3139
103
    CHECK_NE(key->Data()->GetKeyType(), kKeyTypeSecret);
3140
103
    (*offset) += 4;
3141
103
    return key->Data()->GetAsymmetricKey();
3142
  }
3143
}
3144
3145
27
static MaybeLocal<Value> WritePrivateKey(
3146
    Environment* env,
3147
    EVP_PKEY* pkey,
3148
    const PrivateKeyEncodingConfig& config) {
3149
54
  BIOPointer bio(BIO_new(BIO_s_mem()));
3150
27
  CHECK(bio);
3151
3152
  bool err;
3153
3154
54
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3155
    // PKCS#1 is only permitted for RSA keys.
3156
11
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
3157
3158
22
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
3159
11
    if (config.format_ == kKeyFormatPEM) {
3160
      // Encode PKCS#1 as PEM.
3161
10
      const char* pass = config.passphrase_.get();
3162
20
      err = PEM_write_bio_RSAPrivateKey(
3163
                bio.get(), rsa.get(),
3164
10
                config.cipher_,
3165
                reinterpret_cast<unsigned char*>(const_cast<char*>(pass)),
3166
10
                config.passphrase_.size(),
3167
                nullptr, nullptr) != 1;
3168
    } else {
3169
      // Encode PKCS#1 as DER. This does not permit encryption.
3170
1
      CHECK_EQ(config.format_, kKeyFormatDER);
3171
1
      CHECK_NULL(config.cipher_);
3172
1
      err = i2d_RSAPrivateKey_bio(bio.get(), rsa.get()) != 1;
3173
    }
3174
32
  } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
3175
12
    if (config.format_ == kKeyFormatPEM) {
3176
      // Encode PKCS#8 as PEM.
3177
18
      err = PEM_write_bio_PKCS8PrivateKey(
3178
                bio.get(), pkey,
3179
9
                config.cipher_,
3180
9
                const_cast<char*>(config.passphrase_.get()),
3181
9
                config.passphrase_.size(),
3182
                nullptr, nullptr) != 1;
3183
    } else {
3184
      // Encode PKCS#8 as DER.
3185
3
      CHECK_EQ(config.format_, kKeyFormatDER);
3186
6
      err = i2d_PKCS8PrivateKey_bio(
3187
                bio.get(), pkey,
3188
3
                config.cipher_,
3189
3
                const_cast<char*>(config.passphrase_.get()),
3190
3
                config.passphrase_.size(),
3191
                nullptr, nullptr) != 1;
3192
    }
3193
  } else {
3194
8
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
3195
3196
    // SEC1 is only permitted for EC keys.
3197
4
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_EC);
3198
3199
8
    ECKeyPointer ec_key(EVP_PKEY_get1_EC_KEY(pkey));
3200
4
    if (config.format_ == kKeyFormatPEM) {
3201
      // Encode SEC1 as PEM.
3202
4
      const char* pass = config.passphrase_.get();
3203
8
      err = PEM_write_bio_ECPrivateKey(
3204
                bio.get(), ec_key.get(),
3205
4
                config.cipher_,
3206
                reinterpret_cast<unsigned char*>(const_cast<char*>(pass)),
3207
4
                config.passphrase_.size(),
3208
                nullptr, nullptr) != 1;
3209
    } else {
3210
      // Encode SEC1 as DER. This does not permit encryption.
3211
      CHECK_EQ(config.format_, kKeyFormatDER);
3212
      CHECK_NULL(config.cipher_);
3213
      err = i2d_ECPrivateKey_bio(bio.get(), ec_key.get()) != 1;
3214
    }
3215
  }
3216
3217
27
  if (err) {
3218
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode private key");
3219
    return MaybeLocal<Value>();
3220
  }
3221
54
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
3222
}
3223
3224
1383
ManagedEVPPKey::ManagedEVPPKey(EVPKeyPointer&& pkey) : pkey_(std::move(pkey)) {}
3225
3226
413
ManagedEVPPKey::ManagedEVPPKey(const ManagedEVPPKey& that) {
3227
413
  *this = that;
3228
413
}
3229
3230
504
ManagedEVPPKey& ManagedEVPPKey::operator=(const ManagedEVPPKey& that) {
3231
504
  pkey_.reset(that.get());
3232
3233
504
  if (pkey_)
3234
499
    EVP_PKEY_up_ref(pkey_.get());
3235
3236
504
  return *this;
3237
}
3238
3239
1573
ManagedEVPPKey::operator bool() const {
3240
1573
  return !!pkey_;
3241
}
3242
3243
5524
EVP_PKEY* ManagedEVPPKey::get() const {
3244
5524
  return pkey_.get();
3245
}
3246
3247
14
std::shared_ptr<KeyObjectData> KeyObjectData::CreateSecret(
3248
    Local<ArrayBufferView> abv) {
3249
14
  size_t key_len = abv->ByteLength();
3250
14
  char* mem = MallocOpenSSL<char>(key_len);
3251
14
  abv->CopyContents(mem, key_len);
3252
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(
3253
28
      std::unique_ptr<char, std::function<void(char*)>>(mem,
3254
14
          [key_len](char* p) {
3255
14
            OPENSSL_clear_free(p, key_len);
3256
14
          }),
3257
28
      key_len));
3258
}
3259
3260
100
std::shared_ptr<KeyObjectData> KeyObjectData::CreateAsymmetric(
3261
    KeyType key_type,
3262
    const ManagedEVPPKey& pkey) {
3263
100
  CHECK(pkey);
3264
100
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(key_type, pkey));
3265
}
3266
3267
206
KeyType KeyObjectData::GetKeyType() const {
3268
206
  return key_type_;
3269
}
3270
3271
279
ManagedEVPPKey KeyObjectData::GetAsymmetricKey() const {
3272
279
  CHECK_NE(key_type_, kKeyTypeSecret);
3273
279
  return asymmetric_key_;
3274
}
3275
3276
19
const char* KeyObjectData::GetSymmetricKey() const {
3277
19
  CHECK_EQ(key_type_, kKeyTypeSecret);
3278
19
  return symmetric_key_.get();
3279
}
3280
3281
20
size_t KeyObjectData::GetSymmetricKeySize() const {
3282
20
  CHECK_EQ(key_type_, kKeyTypeSecret);
3283
20
  return symmetric_key_len_;
3284
}
3285
3286
622
Local<Function> KeyObjectHandle::Initialize(Environment* env,
3287
                                            Local<Object> target) {
3288
622
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3289
1866
  t->InstanceTemplate()->SetInternalFieldCount(
3290
622
      KeyObjectHandle::kInternalFieldCount);
3291
1244
  t->Inherit(BaseObject::GetConstructorTemplate(env));
3292
3293
622
  env->SetProtoMethod(t, "init", Init);
3294
  env->SetProtoMethodNoSideEffect(t, "getSymmetricKeySize",
3295
622
                                  GetSymmetricKeySize);
3296
  env->SetProtoMethodNoSideEffect(t, "getAsymmetricKeyType",
3297
622
                                  GetAsymmetricKeyType);
3298
622
  env->SetProtoMethod(t, "export", Export);
3299
3300
1866
  auto function = t->GetFunction(env->context()).ToLocalChecked();
3301
1244
  target->Set(env->context(),
3302
              FIXED_ONE_BYTE_STRING(env->isolate(), "KeyObjectHandle"),
3303
2488
              function).Check();
3304
3305
622
  return function;
3306
}
3307
3308
66
MaybeLocal<Object> KeyObjectHandle::Create(
3309
    Environment* env,
3310
    std::shared_ptr<KeyObjectData> data) {
3311
  Local<Object> obj;
3312
198
  if (!env->crypto_key_object_handle_constructor()
3313
198
           ->NewInstance(env->context(), 0, nullptr)
3314
66
           .ToLocal(&obj)) {
3315
    return MaybeLocal<Object>();
3316
  }
3317
3318
66
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(obj);
3319
66
  CHECK_NOT_NULL(key);
3320
66
  key->data_ = data;
3321
66
  return obj;
3322
}
3323
3324
519
const std::shared_ptr<KeyObjectData>& KeyObjectHandle::Data() {
3325
519
  return data_;
3326
}
3327
3328
125
void KeyObjectHandle::New(const FunctionCallbackInfo<Value>& args) {
3329
125
  CHECK(args.IsConstructCall());
3330
125
  Environment* env = Environment::GetCurrent(args);
3331
125
  new KeyObjectHandle(env, args.This());
3332
125
}
3333
3334
125
KeyObjectHandle::KeyObjectHandle(Environment* env,
3335
125
                                 Local<Object> wrap)
3336
125
    : BaseObject(env, wrap) {
3337
125
  MakeWeak();
3338
125
}
3339
3340
59
void KeyObjectHandle::Init(const FunctionCallbackInfo<Value>& args) {
3341
  KeyObjectHandle* key;
3342
64
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3343
113
  MarkPopErrorOnReturn mark_pop_error_on_return;
3344
3345
118
  CHECK(args[0]->IsInt32());
3346
177
  KeyType type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
3347
3348
  unsigned int offset;
3349
113
  ManagedEVPPKey pkey;
3350
3351

59
  switch (type) {
3352
  case kKeyTypeSecret:
3353
14
    CHECK_EQ(args.Length(), 2);
3354
28
    CHECK(args[1]->IsArrayBufferView());
3355
28
    key->data_ = KeyObjectData::CreateSecret(args[1].As<ArrayBufferView>());
3356
14
    break;
3357
  case kKeyTypePublic:
3358
23
    CHECK_EQ(args.Length(), 4);
3359
3360
23
    offset = 1;
3361
23
    pkey = GetPublicOrPrivateKeyFromJs(args, &offset);
3362
23
    if (!pkey)
3363
      return;
3364
23
    key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
3365
23
    break;
3366
  case kKeyTypePrivate:
3367
22
    CHECK_EQ(args.Length(), 5);
3368
3369
22
    offset = 1;
3370
22
    pkey = GetPrivateKeyFromJs(args, &offset, false);
3371
22
    if (!pkey)
3372
5
      return;
3373
17
    key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
3374
17
    break;
3375
  default:
3376
    CHECK(false);
3377
  }
3378
}
3379
3380
84
Local<Value> KeyObjectHandle::GetAsymmetricKeyType() const {
3381
168
  const ManagedEVPPKey& key = data_->GetAsymmetricKey();
3382


84
  switch (EVP_PKEY_id(key.get())) {
3383
  case EVP_PKEY_RSA:
3384
32
    return env()->crypto_rsa_string();
3385
  case EVP_PKEY_RSA_PSS:
3386
16
    return env()->crypto_rsa_pss_string();
3387
  case EVP_PKEY_DSA:
3388
4
    return env()->crypto_dsa_string();
3389
  case EVP_PKEY_DH:
3390
44
    return env()->crypto_dh_string();
3391
  case EVP_PKEY_EC:
3392
12
    return env()->crypto_ec_string();
3393
  case EVP_PKEY_ED25519:
3394
10
    return env()->crypto_ed25519_string();
3395
  case EVP_PKEY_ED448:
3396
10
    return env()->crypto_ed448_string();
3397
  case EVP_PKEY_X25519:
3398
20
    return env()->crypto_x25519_string();
3399
  case EVP_PKEY_X448:
3400
20
    return env()->crypto_x448_string();
3401
  default:
3402
    return Undefined(env()->isolate());
3403
  }
3404
}
3405
3406
84
void KeyObjectHandle::GetAsymmetricKeyType(
3407
    const FunctionCallbackInfo<Value>& args) {
3408
  KeyObjectHandle* key;
3409
84
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3410
3411
252
  args.GetReturnValue().Set(key->GetAsymmetricKeyType());
3412
}
3413
3414
1
void KeyObjectHandle::GetSymmetricKeySize(
3415
    const FunctionCallbackInfo<Value>& args) {
3416
  KeyObjectHandle* key;
3417
1
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3418
3
  args.GetReturnValue().Set(
3419
1
      static_cast<uint32_t>(key->Data()->GetSymmetricKeySize()));
3420
}
3421
3422
30
void KeyObjectHandle::Export(const FunctionCallbackInfo<Value>& args) {
3423
  KeyObjectHandle* key;
3424
30
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3425
3426
30
  KeyType type = key->Data()->GetKeyType();
3427
3428
  MaybeLocal<Value> result;
3429
30
  if (type == kKeyTypeSecret) {
3430
10
    result = key->ExportSecretKey();
3431
25
  } else if (type == kKeyTypePublic) {
3432
14
    unsigned int offset = 0;
3433
    PublicKeyEncodingConfig config =
3434
14
        GetPublicKeyEncodingFromJs(args, &offset, kKeyContextExport);
3435
14
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
3436
14
    result = key->ExportPublicKey(config);
3437
  } else {
3438
11
    CHECK_EQ(type, kKeyTypePrivate);
3439
11
    unsigned int offset = 0;
3440
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3441
22
        GetPrivateKeyEncodingFromJs(args, &offset, kKeyContextExport);
3442
11
    if (config.IsEmpty())
3443
      return;
3444
11