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: 3283 3614 90.8 %
Date: 2020-05-27 22:15:15 Branches: 1734 2639 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 "tls_wrap.h"  // TLSWrap
32
33
#include "async_wrap-inl.h"
34
#include "base_object-inl.h"
35
#include "env-inl.h"
36
#include "memory_tracker-inl.h"
37
#include "string_bytes.h"
38
#include "threadpoolwork-inl.h"
39
#include "util-inl.h"
40
#include "v8.h"
41
42
#include <openssl/ec.h>
43
#include <openssl/ecdh.h>
44
#ifndef OPENSSL_NO_ENGINE
45
# include <openssl/engine.h>
46
#endif  // !OPENSSL_NO_ENGINE
47
#include <openssl/evp.h>
48
#include <openssl/pem.h>
49
#include <openssl/x509v3.h>
50
#include <openssl/hmac.h>
51
#include <openssl/rand.h>
52
#include <openssl/pkcs12.h>
53
54
#include <cerrno>
55
#include <climits>  // INT_MAX
56
#include <cstring>
57
58
#include <algorithm>
59
#include <memory>
60
#include <utility>
61
#include <vector>
62
63
namespace node {
64
namespace crypto {
65
66
using node::THROW_ERR_TLS_INVALID_PROTOCOL_METHOD;
67
68
using v8::Array;
69
using v8::ArrayBufferView;
70
using v8::Boolean;
71
using v8::ConstructorBehavior;
72
using v8::Context;
73
using v8::DontDelete;
74
using v8::Exception;
75
using v8::External;
76
using v8::False;
77
using v8::Function;
78
using v8::FunctionCallback;
79
using v8::FunctionCallbackInfo;
80
using v8::FunctionTemplate;
81
using v8::HandleScope;
82
using v8::Int32;
83
using v8::Integer;
84
using v8::Isolate;
85
using v8::Just;
86
using v8::Local;
87
using v8::Maybe;
88
using v8::MaybeLocal;
89
using v8::NewStringType;
90
using v8::Nothing;
91
using v8::Null;
92
using v8::Object;
93
using v8::PropertyAttribute;
94
using v8::ReadOnly;
95
using v8::SideEffectType;
96
using v8::Signature;
97
using v8::String;
98
using v8::Uint32;
99
using v8::Undefined;
100
using v8::Value;
101
102
#ifdef OPENSSL_NO_OCB
103
# define IS_OCB_MODE(mode) false
104
#else
105
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
106
#endif
107
108
static const char* const root_certs[] = {
109
#include "node_root_certs.h"  // NOLINT(build/include_order)
110
};
111
112
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
113
114
static X509_STORE* root_cert_store;
115
116
static bool extra_root_certs_loaded = false;
117
118
// Just to generate static methods
119
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
120
                                           Local<FunctionTemplate> t);
121
template void SSLWrap<TLSWrap>::ConfigureSecureContext(SecureContext* sc);
122
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
123
template void SSLWrap<TLSWrap>::MemoryInfo(MemoryTracker* tracker) const;
124
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
125
    SSL* s,
126
    const unsigned char* key,
127
    int len,
128
    int* copy);
129
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
130
                                                  SSL_SESSION* sess);
131
template void SSLWrap<TLSWrap>::KeylogCallback(const SSL* s,
132
                                               const char* line);
133
template void SSLWrap<TLSWrap>::OnClientHello(
134
    void* arg,
135
    const ClientHelloParser::ClientHello& hello);
136
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
137
template void SSLWrap<TLSWrap>::DestroySSL();
138
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
139
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
140
template int SSLWrap<TLSWrap>::SelectALPNCallback(
141
    SSL* s,
142
    const unsigned char** out,
143
    unsigned char* outlen,
144
    const unsigned char* in,
145
    unsigned int inlen,
146
    void* arg);
147
148
template <typename T>
149
335004
void Decode(const FunctionCallbackInfo<Value>& args,
150
            void (*callback)(T*, const FunctionCallbackInfo<Value>&,
151
                             const char*, size_t)) {
152
  T* ctx;
153


335004
  ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder());
154
155


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


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


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

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









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

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

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

6717
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
680

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

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

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

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

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

251
  static std::vector<X509*> root_certs_vector;
973

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

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

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

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

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

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

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

3306
    if (RAND_bytes(iv, 16) <= 0 ||
1674
1102
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1675

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

58
  switch (key->key_type_) {
3330
  case kKeyTypeSecret:
3331
13
    CHECK_EQ(args.Length(), 1);
3332
26
    CHECK(args[0]->IsArrayBufferView());
3333
26
    key->InitSecret(args[0].As<ArrayBufferView>());
3334
13
    break;
3335
  case kKeyTypePublic:
3336
23
    CHECK_EQ(args.Length(), 3);
3337
3338
23
    offset = 0;
3339
23
    pkey = GetPublicOrPrivateKeyFromJs(args, &offset);
3340
23
    if (!pkey)
3341
      return;
3342
23
    key->InitPublic(pkey);
3343
23
    break;
3344
  case kKeyTypePrivate:
3345
22
    CHECK_EQ(args.Length(), 4);
3346
3347
22
    offset = 0;
3348
22
    pkey = GetPrivateKeyFromJs(args, &offset, false);
3349
22
    if (!pkey)
3350
5
      return;
3351
17
    key->InitPrivate(pkey);
3352
17
    break;
3353
  default:
3354
    CHECK(false);
3355
  }
3356
}
3357
3358
13
void KeyObject::InitSecret(Local<ArrayBufferView> abv) {
3359
13
  CHECK_EQ(this->key_type_, kKeyTypeSecret);
3360
3361
13
  size_t key_len = abv->ByteLength();
3362
13
  char* mem = MallocOpenSSL<char>(key_len);
3363
13
  abv->CopyContents(mem, key_len);
3364
26
  this->symmetric_key_ = std::unique_ptr<char, std::function<void(char*)>>(mem,
3365
13
      [key_len](char* p) {
3366
13
        OPENSSL_clear_free(p, key_len);
3367
26
      });
3368
13
  this->symmetric_key_len_ = key_len;
3369
13
}
3370
3371
52
void KeyObject::InitPublic(const ManagedEVPPKey& pkey) {
3372
52
  CHECK_EQ(this->key_type_, kKeyTypePublic);
3373
52
  CHECK(pkey);
3374
52
  this->asymmetric_key_ = pkey;
3375
52
}
3376
3377
46
void KeyObject::InitPrivate(const ManagedEVPPKey& pkey) {
3378
46
  CHECK_EQ(this->key_type_, kKeyTypePrivate);
3379
46
  CHECK(pkey);
3380
46
  this->asymmetric_key_ = pkey;
3381
46
}
3382
3383
78
Local<Value> KeyObject::GetAsymmetricKeyType() const {
3384
78
  CHECK_NE(this->key_type_, kKeyTypeSecret);
3385


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