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: 2928 3216 91.0 %
Date: 2019-03-02 22:23:06 Branches: 1501 2297 65.3 %

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.h"
24
#include "node_buffer.h"
25
#include "node_constants.h"
26
#include "node_crypto_bio.h"
27
#include "node_crypto_clienthello-inl.h"
28
#include "node_crypto_groups.h"
29
#include "node_errors.h"
30
#include "node_mutex.h"
31
#include "node_process.h"
32
#include "tls_wrap.h"  // TLSWrap
33
34
#include "async_wrap-inl.h"
35
#include "env-inl.h"
36
#include "string_bytes.h"
37
#include "util-inl.h"
38
#include "v8.h"
39
40
#include <cerrno>
41
#include <climits>  // INT_MAX
42
#include <cstring>
43
44
#include <algorithm>
45
#include <memory>
46
#include <utility>
47
#include <vector>
48
49
static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
50
                                 | ASN1_STRFLGS_UTF8_CONVERT
51
                                 | XN_FLAG_SEP_MULTILINE
52
                                 | XN_FLAG_FN_SN;
53
54
namespace node {
55
namespace crypto {
56
57
using node::THROW_ERR_TLS_INVALID_PROTOCOL_METHOD;
58
59
using v8::Array;
60
using v8::ArrayBufferView;
61
using v8::Boolean;
62
using v8::ConstructorBehavior;
63
using v8::Context;
64
using v8::DontDelete;
65
using v8::EscapableHandleScope;
66
using v8::Exception;
67
using v8::External;
68
using v8::Function;
69
using v8::FunctionCallback;
70
using v8::FunctionCallbackInfo;
71
using v8::FunctionTemplate;
72
using v8::HandleScope;
73
using v8::Int32;
74
using v8::Integer;
75
using v8::Isolate;
76
using v8::Just;
77
using v8::Local;
78
using v8::Maybe;
79
using v8::MaybeLocal;
80
using v8::NewStringType;
81
using v8::Nothing;
82
using v8::Null;
83
using v8::Object;
84
using v8::PropertyAttribute;
85
using v8::ReadOnly;
86
using v8::SideEffectType;
87
using v8::Signature;
88
using v8::String;
89
using v8::Uint32;
90
using v8::Undefined;
91
using v8::Value;
92
93
#ifdef OPENSSL_NO_OCB
94
# define IS_OCB_MODE(mode) false
95
#else
96
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
97
#endif
98
99
struct StackOfX509Deleter {
100
720
  void operator()(STACK_OF(X509)* p) const { sk_X509_pop_free(p, X509_free); }
101
};
102
using StackOfX509 = std::unique_ptr<STACK_OF(X509), StackOfX509Deleter>;
103
104
struct StackOfXASN1Deleter {
105
18
  void operator()(STACK_OF(ASN1_OBJECT)* p) const {
106
18
    sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
107
18
  }
108
};
109
using StackOfASN1 = std::unique_ptr<STACK_OF(ASN1_OBJECT), StackOfXASN1Deleter>;
110
111
// OPENSSL_free is a macro, so we need a wrapper function.
112
struct OpenSSLBufferDeleter {
113
527
  void operator()(char* pointer) const { OPENSSL_free(pointer); }
114
};
115
using OpenSSLBuffer = std::unique_ptr<char[], OpenSSLBufferDeleter>;
116
117
static const char* const root_certs[] = {
118
#include "node_root_certs.h"  // NOLINT(build/include_order)
119
};
120
121
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
122
123
static X509_STORE* root_cert_store;
124
125
static bool extra_root_certs_loaded = false;
126
127
// Just to generate static methods
128
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
129
                                           Local<FunctionTemplate> t);
130
template void SSLWrap<TLSWrap>::ConfigureSecureContext(SecureContext* sc);
131
template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc);
132
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
133
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
134
    SSL* s,
135
    const unsigned char* key,
136
    int len,
137
    int* copy);
138
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
139
                                                  SSL_SESSION* sess);
140
template void SSLWrap<TLSWrap>::OnClientHello(
141
    void* arg,
142
    const ClientHelloParser::ClientHello& hello);
143
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
144
template void SSLWrap<TLSWrap>::DestroySSL();
145
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
146
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
147
template int SSLWrap<TLSWrap>::SelectALPNCallback(
148
    SSL* s,
149
    const unsigned char** out,
150
    unsigned char* outlen,
151
    const unsigned char* in,
152
    unsigned int inlen,
153
    void* arg);
154
155
156
50
static int PasswordCallback(char* buf, int size, int rwflag, void* u) {
157
50
  if (u) {
158
42
    size_t buflen = static_cast<size_t>(size);
159
42
    size_t len = strlen(static_cast<const char*>(u));
160
42
    len = len > buflen ? buflen : len;
161
42
    memcpy(buf, u, len);
162
42
    return len;
163
  }
164
165
8
  return 0;
166
}
167
168
// Loads OpenSSL engine by engine id and returns it. The loaded engine
169
// gets a reference so remember the corresponding call to ENGINE_free.
170
// In case of error the appropriate js exception is scheduled
171
// and nullptr is returned.
172
#ifndef OPENSSL_NO_ENGINE
173
2
static ENGINE* LoadEngineById(const char* engine_id, char (*errmsg)[1024]) {
174
2
  MarkPopErrorOnReturn mark_pop_error_on_return;
175
176
2
  ENGINE* engine = ENGINE_by_id(engine_id);
177
178
2
  if (engine == nullptr) {
179
    // Engine not found, try loading dynamically.
180
2
    engine = ENGINE_by_id("dynamic");
181
2
    if (engine != nullptr) {
182

4
      if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", engine_id, 0) ||
183
2
          !ENGINE_ctrl_cmd_string(engine, "LOAD", nullptr, 0)) {
184
2
        ENGINE_free(engine);
185
2
        engine = nullptr;
186
      }
187
    }
188
  }
189
190
2
  if (engine == nullptr) {
191
2
    int err = ERR_get_error();
192
2
    if (err != 0) {
193
2
      ERR_error_string_n(err, *errmsg, sizeof(*errmsg));
194
    } else {
195
      snprintf(*errmsg, sizeof(*errmsg),
196
               "Engine \"%s\" was not found", engine_id);
197
    }
198
  }
199
200
2
  return engine;
201
}
202
#endif  // !OPENSSL_NO_ENGINE
203
204
// This callback is used to avoid the default passphrase callback in OpenSSL
205
// which will typically prompt for the passphrase. The prompting is designed
206
// for the OpenSSL CLI, but works poorly for Node.js because it involves
207
// synchronous interaction with the controlling terminal, something we never
208
// want, and use this function to avoid it.
209
static int NoPasswordCallback(char* buf, int size, int rwflag, void* u) {
210
  return 0;
211
}
212
213
214
346
struct CryptoErrorVector : public std::vector<std::string> {
215
57
  inline void Capture() {
216
57
    clear();
217
114
    while (auto err = ERR_get_error()) {
218
      char buf[256];
219
57
      ERR_error_string_n(err, buf, sizeof(buf));
220
57
      push_back(buf);
221
    }
222
57
    std::reverse(begin(), end());
223
57
  }
224
225
61
  inline Local<Value> ToException(
226
      Environment* env,
227
      Local<String> exception_string = Local<String>()) const {
228
61
    if (exception_string.IsEmpty()) {
229
8
      CryptoErrorVector copy(*this);
230
8
      if (copy.empty()) copy.push_back("no error");  // But possibly a bug...
231
      // Use last element as the error message, everything else goes
232
      // into the .opensslErrorStack property on the exception object.
233
      auto exception_string =
234
8
          String::NewFromUtf8(env->isolate(), copy.back().data(),
235
16
                              NewStringType::kNormal, copy.back().size())
236
16
          .ToLocalChecked();
237
8
      copy.pop_back();
238
8
      return copy.ToException(env, exception_string);
239
    }
240
241
53
    Local<Value> exception_v = Exception::Error(exception_string);
242
53
    CHECK(!exception_v.IsEmpty());
243
244
53
    if (!empty()) {
245
19
      CHECK(exception_v->IsObject());
246
19
      Local<Object> exception = exception_v.As<Object>();
247
      exception->Set(env->context(),
248
                     env->openssl_error_stack(),
249
95
                     ToV8Value(env->context(), *this).ToLocalChecked())
250
38
          .FromJust();
251
    }
252
253
53
    return exception_v;
254
  }
255
};
256
257
258
45
void ThrowCryptoError(Environment* env,
259
                      unsigned long err,  // NOLINT(runtime/int)
260
                      const char* message = nullptr) {
261
45
  char message_buffer[128] = {0};
262

45
  if (err != 0 || message == nullptr) {
263
35
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
264
35
    message = message_buffer;
265
  }
266
45
  HandleScope scope(env->isolate());
267
  auto exception_string =
268
45
      String::NewFromUtf8(env->isolate(), message, NewStringType::kNormal)
269
90
      .ToLocalChecked();
270
90
  CryptoErrorVector errors;
271
45
  errors.Capture();
272
45
  auto exception = errors.ToException(env, exception_string);
273
90
  env->isolate()->ThrowException(exception);
274
45
}
275
276
277
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
278
// The entropy pool starts out empty and needs to fill up before the PRNG
279
// can be used securely.  Once the pool is filled, it never dries up again;
280
// its contents is stirred and reused when necessary.
281
//
282
// OpenSSL normally fills the pool automatically but not when someone starts
283
// generating random numbers before the pool is full: in that case OpenSSL
284
// keeps lowering the entropy estimate to thwart attackers trying to guess
285
// the initial state of the PRNG.
286
//
287
// When that happens, we will have to wait until enough entropy is available.
288
// That should normally never take longer than a few milliseconds.
289
//
290
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
291
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
292
// block under normal circumstances.
293
//
294
// The only time when /dev/urandom may conceivably block is right after boot,
295
// when the whole system is still low on entropy.  That's not something we can
296
// do anything about.
297
8831
inline void CheckEntropy() {
298
  for (;;) {
299
8831
    int status = RAND_status();
300
8831
    CHECK_GE(status, 0);  // Cannot fail.
301
8831
    if (status != 0)
302
17662
      break;
303
304
    // Give up, RAND_poll() not supported.
305
    if (RAND_poll() == 0)
306
      break;
307
  }
308
8831
}
309
310
311
8744
bool EntropySource(unsigned char* buffer, size_t length) {
312
  // Ensure that OpenSSL's PRNG is properly seeded.
313
8744
  CheckEntropy();
314
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
315
  // random. That's okay, it's still better than V8's stock source of entropy,
316
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
317
8744
  return RAND_bytes(buffer, length) != -1;
318
}
319
320
321
template <typename T>
322
451
static T* MallocOpenSSL(size_t count) {
323
451
  void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
324



451
  CHECK_IMPLIES(mem == nullptr, count == 0);
325
451
  return static_cast<T*>(mem);
326
}
327
328
329
578
void SecureContext::Initialize(Environment* env, Local<Object> target) {
330
578
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
331
1156
  t->InstanceTemplate()->SetInternalFieldCount(1);
332
  Local<String> secureContextString =
333
578
      FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext");
334
578
  t->SetClassName(secureContextString);
335
336
578
  env->SetProtoMethod(t, "init", Init);
337
578
  env->SetProtoMethod(t, "setKey", SetKey);
338
578
  env->SetProtoMethod(t, "setCert", SetCert);
339
578
  env->SetProtoMethod(t, "addCACert", AddCACert);
340
578
  env->SetProtoMethod(t, "addCRL", AddCRL);
341
578
  env->SetProtoMethod(t, "addRootCerts", AddRootCerts);
342
578
  env->SetProtoMethod(t, "setCiphers", SetCiphers);
343
578
  env->SetProtoMethod(t, "setECDHCurve", SetECDHCurve);
344
578
  env->SetProtoMethod(t, "setDHParam", SetDHParam);
345
578
  env->SetProtoMethod(t, "setOptions", SetOptions);
346
578
  env->SetProtoMethod(t, "setSessionIdContext", SetSessionIdContext);
347
578
  env->SetProtoMethod(t, "setSessionTimeout", SetSessionTimeout);
348
578
  env->SetProtoMethod(t, "close", Close);
349
578
  env->SetProtoMethod(t, "loadPKCS12", LoadPKCS12);
350
#ifndef OPENSSL_NO_ENGINE
351
578
  env->SetProtoMethod(t, "setClientCertEngine", SetClientCertEngine);
352
#endif  // !OPENSSL_NO_ENGINE
353
578
  env->SetProtoMethodNoSideEffect(t, "getTicketKeys", GetTicketKeys);
354
578
  env->SetProtoMethod(t, "setTicketKeys", SetTicketKeys);
355
578
  env->SetProtoMethod(t, "setFreeListLength", SetFreeListLength);
356
578
  env->SetProtoMethod(t, "enableTicketKeyCallback", EnableTicketKeyCallback);
357
578
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate<true>);
358
578
  env->SetProtoMethodNoSideEffect(t, "getIssuer", GetCertificate<false>);
359
360
#define SET_INTEGER_CONSTANTS(name, value)                                     \
361
    t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), name),                        \
362
           Integer::NewFromUnsigned(env->isolate(), value));
363
1734
  SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex);
364
1734
  SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex);
365
1734
  SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex);
366
1734
  SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex);
367
1734
  SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex);
368
369
#undef SET_INTEGER_CONSTANTS
370
371
  Local<FunctionTemplate> ctx_getter_templ =
372
      FunctionTemplate::New(env->isolate(),
373
                            CtxGetter,
374
                            env->as_external(),
375
1156
                            Signature::New(env->isolate(), t));
376
377
378
1734
  t->PrototypeTemplate()->SetAccessorProperty(
379
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
380
      ctx_getter_templ,
381
      Local<FunctionTemplate>(),
382
1734
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
383
384
  target->Set(env->context(), secureContextString,
385
2890
              t->GetFunction(env->context()).ToLocalChecked()).FromJust();
386
578
  env->set_secure_context_constructor_template(t);
387
578
}
388
389
390
1703
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
391
1703
  Environment* env = Environment::GetCurrent(args);
392
1703
  new SecureContext(env, args.This());
393
1703
}
394
395
396
1703
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
397
  SecureContext* sc;
398
1728
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
399
1703
  Environment* env = sc->env();
400
401
1703
  CHECK_EQ(args.Length(), 3);
402
3406
  CHECK(args[1]->IsInt32());
403
3406
  CHECK(args[2]->IsInt32());
404
405
5109
  int min_version = args[1].As<Int32>()->Value();
406
5109
  int max_version = args[2].As<Int32>()->Value();
407
1703
  const SSL_METHOD* method = TLS_method();
408
409
5109
  if (args[0]->IsString()) {
410
183
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
411
412
    // Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends
413
    // are still accepted.  They are OpenSSL's way of saying that all known
414
    // protocols are supported unless explicitly disabled (which we do below
415
    // for SSLv2 and SSLv3.)
416
183
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
417
7
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
418
7
      return;
419
176
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
420
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
421
1
      return;
422
175
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
423
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
424
1
      return;
425
174
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
426
7
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
427
7
      return;
428
167
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
429
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
430
1
      return;
431
166
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
432
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
433
1
      return;
434
165
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
435
      // noop
436
149
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
437
1
      method = TLS_server_method();
438
148
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
439
1
      method = TLS_client_method();
440
147
    } else if (strcmp(*sslmethod, "TLS_method") == 0) {
441
22
      min_version = 0;
442
22
      max_version = 0;
443
125
    } else if (strcmp(*sslmethod, "TLS_server_method") == 0) {
444
      min_version = 0;
445
      max_version = 0;
446
      method = TLS_server_method();
447
125
    } else if (strcmp(*sslmethod, "TLS_client_method") == 0) {
448
      min_version = 0;
449
      max_version = 0;
450
      method = TLS_client_method();
451
125
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
452
33
      min_version = TLS1_VERSION;
453
33
      max_version = TLS1_VERSION;
454
92
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
455
1
      min_version = TLS1_VERSION;
456
1
      max_version = TLS1_VERSION;
457
1
      method = TLS_server_method();
458
91
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
459
1
      min_version = TLS1_VERSION;
460
1
      max_version = TLS1_VERSION;
461
1
      method = TLS_client_method();
462
90
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
463
33
      min_version = TLS1_1_VERSION;
464
33
      max_version = TLS1_1_VERSION;
465
57
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
466
1
      min_version = TLS1_1_VERSION;
467
1
      max_version = TLS1_1_VERSION;
468
1
      method = TLS_server_method();
469
56
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
470
1
      min_version = TLS1_1_VERSION;
471
1
      max_version = TLS1_1_VERSION;
472
1
      method = TLS_client_method();
473
55
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
474
45
      min_version = TLS1_2_VERSION;
475
45
      max_version = TLS1_2_VERSION;
476
10
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
477
2
      min_version = TLS1_2_VERSION;
478
2
      max_version = TLS1_2_VERSION;
479
2
      method = TLS_server_method();
480
8
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
481
1
      min_version = TLS1_2_VERSION;
482
1
      max_version = TLS1_2_VERSION;
483
1
      method = TLS_client_method();
484
    } else {
485
7
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "Unknown method");
486
7
      return;
487
158
    }
488
  }
489
490
1678
  sc->ctx_.reset(SSL_CTX_new(method));
491
1678
  SSL_CTX_set_app_data(sc->ctx_.get(), sc);
492
493
  // Disable SSLv2 in the case when method == TLS_method() and the
494
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
495
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
496
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
497
1678
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv2);
498
1678
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv3);
499
500
  // Enable automatic cert chaining. This is enabled by default in OpenSSL, but
501
  // disabled by default in BoringSSL. Enable it explicitly to make the
502
  // behavior match when Node is built with BoringSSL.
503
1678
  SSL_CTX_clear_mode(sc->ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
504
505
  // SSL session cache configuration
506
1678
  SSL_CTX_set_session_cache_mode(sc->ctx_.get(),
507
                                 SSL_SESS_CACHE_CLIENT |
508
                                 SSL_SESS_CACHE_SERVER |
509
                                 SSL_SESS_CACHE_NO_INTERNAL |
510
1678
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
511
512
1678
  SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version);
513
514
1678
  if (max_version == 0) {
515
    // Selecting some secureProtocol methods allows the TLS version to be "any
516
    // supported", but we don't support TLSv1.3, even if OpenSSL does.
517
22
    max_version = TLS1_2_VERSION;
518
  }
519
1678
  SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version);
520
521
  // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was
522
  // exposed in the public API. To retain compatibility, install a callback
523
  // which restores the old algorithm.
524

5034
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
525

3356
      RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 ||
526
1678
      RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) {
527
    return env->ThrowError("Error generating ticket keys");
528
  }
529
1678
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
530
}
531
532
533
// Takes a string or buffer and loads it into a BIO.
534
// Caller responsible for BIO_free_all-ing the returned object.
535
1385
static BIOPointer LoadBIO(Environment* env, Local<Value> v) {
536
1385
  HandleScope scope(env->isolate());
537
538
2770
  if (v->IsString()) {
539
535
    const node::Utf8Value s(env->isolate(), v);
540
535
    return NodeBIO::NewFixed(*s, s.length());
541
  }
542
543
850
  if (v->IsArrayBufferView()) {
544
850
    ArrayBufferViewContents<char> buf(v.As<ArrayBufferView>());
545
850
    return NodeBIO::NewFixed(buf.data(), buf.length());
546
  }
547
548
  return nullptr;
549
}
550
551
552
518
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
553
518
  Environment* env = Environment::GetCurrent(args);
554
555
  SecureContext* sc;
556
528
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
557
558
518
  unsigned int len = args.Length();
559
518
  if (len < 1) {
560
    return THROW_ERR_MISSING_ARGS(env, "Private key argument is mandatory");
561
  }
562
563
518
  if (len > 2) {
564
    return env->ThrowError("Only private key and pass phrase are expected");
565
  }
566
567
518
  if (len == 2) {
568


2150
    if (args[1]->IsUndefined() || args[1]->IsNull())
569
492
      len = 1;
570
    else
571
78
      THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase");
572
  }
573
574
516
  BIOPointer bio(LoadBIO(env, args[0]));
575
516
  if (!bio)
576
    return;
577
578
1024
  node::Utf8Value passphrase(env->isolate(), args[1]);
579
580
  EVPKeyPointer key(
581
      PEM_read_bio_PrivateKey(bio.get(),
582
                              nullptr,
583
                              PasswordCallback,
584

1024
                              len == 1 ? nullptr : *passphrase));
585
586
516
  if (!key) {
587
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
588
7
    if (!err) {
589
      return env->ThrowError("PEM_read_bio_PrivateKey");
590
    }
591
7
    return ThrowCryptoError(env, err);
592
  }
593
594
509
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
595
596
509
  if (!rv) {
597
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
598
1
    if (!err)
599
      return env->ThrowError("SSL_CTX_use_PrivateKey");
600
1
    return ThrowCryptoError(env, err);
601
508
  }
602
}
603
604
605
556
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
606
556
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
607
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
608
556
      X509_STORE_CTX_new());
609
1112
  return store_ctx.get() != nullptr &&
610

1112
         X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
611
1112
         X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1;
612
}
613
614
615
546
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
616
                                  X509Pointer&& x,
617
                                  STACK_OF(X509)* extra_certs,
618
                                  X509Pointer* cert,
619
                                  X509Pointer* issuer_) {
620
546
  CHECK(!*issuer_);
621
546
  CHECK(!*cert);
622
546
  X509* issuer = nullptr;
623
624
546
  int ret = SSL_CTX_use_certificate(ctx, x.get());
625
626
546
  if (ret) {
627
    // If we could set up our certificate, now proceed to
628
    // the CA certificates.
629
546
    SSL_CTX_clear_extra_chain_certs(ctx);
630
631
694
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
632
148
      X509* ca = sk_X509_value(extra_certs, i);
633
634
      // NOTE: Increments reference count on `ca`
635
148
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
636
        ret = 0;
637
        issuer = nullptr;
638
        break;
639
      }
640
      // Note that we must not free r if it was successfully
641
      // added to the chain (while we must free the main
642
      // certificate, since its reference count is increased
643
      // by SSL_CTX_use_certificate).
644
645
      // Find issuer
646

148
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
647
4
        continue;
648
649
144
      issuer = ca;
650
    }
651
  }
652
653
  // Try getting issuer from a cert store
654
546
  if (ret) {
655
546
    if (issuer == nullptr) {
656
402
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
657
402
      ret = ret < 0 ? 0 : 1;
658
      // NOTE: get_cert_store doesn't increment reference count,
659
      // no need to free `store`
660
    } else {
661
      // Increment issuer reference count
662
144
      issuer = X509_dup(issuer);
663
144
      if (issuer == nullptr) {
664
        ret = 0;
665
      }
666
    }
667
  }
668
669
546
  issuer_->reset(issuer);
670
671

546
  if (ret && x != nullptr) {
672
546
    cert->reset(X509_dup(x.get()));
673
546
    if (!*cert)
674
      ret = 0;
675
  }
676
546
  return ret;
677
}
678
679
680
// Read a file that contains our certificate in "PEM" format,
681
// possibly followed by a sequence of CA certificates that should be
682
// sent to the peer in the Certificate message.
683
//
684
// Taken from OpenSSL - edited for style.
685
534
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
686
                                  BIOPointer&& in,
687
                                  X509Pointer* cert,
688
                                  X509Pointer* issuer) {
689
  // Just to ensure that `ERR_peek_last_error` below will return only errors
690
  // that we are interested in
691
534
  ERR_clear_error();
692
693
  X509Pointer x(
694
534
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
695
696
534
  if (!x)
697
    return 0;
698
699
534
  unsigned long err = 0;  // NOLINT(runtime/int)
700
701
1068
  StackOfX509 extra_certs(sk_X509_new_null());
702
534
  if (!extra_certs)
703
    return 0;
704
705
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
706
                                    nullptr,
707
                                    NoPasswordCallback,
708
673
                                    nullptr)}) {
709
139
    if (sk_X509_push(extra_certs.get(), extra.get())) {
710
139
      extra.release();
711
139
      continue;
712
    }
713
714
    return 0;
715
  }
716
717
  // When the while loop ends, it's usually just EOF.
718
534
  err = ERR_peek_last_error();
719

1068
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
720
534
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
721
534
    ERR_clear_error();
722
  } else {
723
    // some real error
724
    return 0;
725
  }
726
727
  return SSL_CTX_use_certificate_chain(ctx,
728
534
                                       std::move(x),
729
                                       extra_certs.get(),
730
                                       cert,
731
1602
                                       issuer);
732
}
733
734
735
534
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
736
534
  Environment* env = Environment::GetCurrent(args);
737
738
  SecureContext* sc;
739
534
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
740
741
534
  if (args.Length() != 1) {
742
    return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory");
743
  }
744
745
534
  BIOPointer bio(LoadBIO(env, args[0]));
746
534
  if (!bio)
747
    return;
748
749
534
  sc->cert_.reset();
750
534
  sc->issuer_.reset();
751
752
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(),
753
534
                                         std::move(bio),
754
                                         &sc->cert_,
755
1068
                                         &sc->issuer_);
756
757
534
  if (!rv) {
758
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
759
    if (!err) {
760
      return env->ThrowError("SSL_CTX_use_certificate_chain");
761
    }
762
    return ThrowCryptoError(env, err);
763
534
  }
764
}
765
766
767
229
static X509_STORE* NewRootCertStore() {
768

229
  static std::vector<X509*> root_certs_vector;
769

229
  static Mutex root_certs_vector_mutex;
770
229
  Mutex::ScopedLock lock(root_certs_vector_mutex);
771
772
229
  if (root_certs_vector.empty()) {
773
30056
    for (size_t i = 0; i < arraysize(root_certs); i++) {
774
      X509* x509 =
775
29835
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
776
29835
                                              strlen(root_certs[i])).get(),
777
                            nullptr,   // no re-use of X509 structure
778
                            NoPasswordCallback,
779
59670
                            nullptr);  // no callback data
780
781
      // Parse errors from the built-in roots are fatal.
782
29835
      CHECK_NOT_NULL(x509);
783
784
29835
      root_certs_vector.push_back(x509);
785
    }
786
  }
787
788
229
  X509_STORE* store = X509_STORE_new();
789
229
  if (*system_cert_path != '\0') {
790
    X509_STORE_load_locations(store, system_cert_path, nullptr);
791
  }
792
229
  if (per_process::cli_options->ssl_openssl_cert_store) {
793
    X509_STORE_set_default_paths(store);
794
  } else {
795
31144
    for (X509* cert : root_certs_vector) {
796
30915
      X509_up_ref(cert);
797
30915
      X509_STORE_add_cert(store, cert);
798
    }
799
  }
800
801
229
  return store;
802
}
803
804
805
305
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
806
305
  Environment* env = Environment::GetCurrent(args);
807
808
  SecureContext* sc;
809
305
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
810
  ClearErrorOnReturn clear_error_on_return;
811
812
305
  if (args.Length() != 1) {
813
    return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory");
814
  }
815
816
610
  BIOPointer bio(LoadBIO(env, args[0]));
817
305
  if (!bio)
818
    return;
819
820
305
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
821
  while (X509* x509 = PEM_read_bio_X509_AUX(
822
710
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
823
405
    if (cert_store == root_cert_store) {
824
2
      cert_store = NewRootCertStore();
825
2
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
826
    }
827
405
    X509_STORE_add_cert(cert_store, x509);
828
405
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
829
405
    X509_free(x509);
830
305
  }
831
}
832
833
834
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
835
2
  Environment* env = Environment::GetCurrent(args);
836
837
  SecureContext* sc;
838
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
839
840
2
  if (args.Length() != 1) {
841
    return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory");
842
  }
843
844
  ClearErrorOnReturn clear_error_on_return;
845
846
3
  BIOPointer bio(LoadBIO(env, args[0]));
847
2
  if (!bio)
848
    return;
849
850
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
851
3
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
852
853
2
  if (!crl)
854
1
    return env->ThrowError("Failed to parse CRL");
855
856
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
857
1
  if (cert_store == root_cert_store) {
858
    cert_store = NewRootCertStore();
859
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
860
  }
861
862
1
  X509_STORE_add_crl(cert_store, crl.get());
863
  X509_STORE_set_flags(cert_store,
864
2
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
865
}
866
867
868
3
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
869
    X509_STORE* store,
870
    const char* file) {
871
3
  ERR_clear_error();
872
3
  MarkPopErrorOnReturn mark_pop_error_on_return;
873
874
6
  BIOPointer bio(BIO_new_file(file, "r"));
875
3
  if (!bio)
876
1
    return ERR_get_error();
877
878
  while (X509* x509 =
879
4
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
880
2
    X509_STORE_add_cert(store, x509);
881
2
    X509_free(x509);
882
  }
883
884
2
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
885
  // Ignore error if its EOF/no start line found.
886

4
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
887
2
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
888
2
    return 0;
889
  }
890
891
3
  return err;
892
}
893
894
895
3
void UseExtraCaCerts(const std::string& file) {
896
  ClearErrorOnReturn clear_error_on_return;
897
898
3
  if (root_cert_store == nullptr) {
899
3
    root_cert_store = NewRootCertStore();
900
901
3
    if (!file.empty()) {
902
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
903
                                           root_cert_store,
904
3
                                           file.c_str());
905
3
      if (err) {
906
        fprintf(stderr,
907
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
908
                file.c_str(),
909
1
                ERR_error_string(err, nullptr));
910
      } else {
911
2
        extra_root_certs_loaded = true;
912
      }
913
    }
914
3
  }
915
3
}
916
917
918
static void IsExtraRootCertsFileLoaded(
919
    const FunctionCallbackInfo<Value>& args) {
920
  return args.GetReturnValue().Set(extra_root_certs_loaded);
921
}
922
923
924
1394
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
925
  SecureContext* sc;
926
2788
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
927
  ClearErrorOnReturn clear_error_on_return;
928
929
1394
  if (root_cert_store == nullptr) {
930
218
    root_cert_store = NewRootCertStore();
931
  }
932
933
  // Increment reference count so global store is not deleted along with CTX.
934
1394
  X509_STORE_up_ref(root_cert_store);
935
1394
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
936
}
937
938
939
1614
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
940
  SecureContext* sc;
941
1620
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
942
1614
  Environment* env = sc->env();
943
  ClearErrorOnReturn clear_error_on_return;
944
945
1614
  if (args.Length() != 1) {
946
    return THROW_ERR_MISSING_ARGS(env, "Ciphers argument is mandatory");
947
  }
948
949
4842
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Ciphers");
950
951
  // Note: set_ciphersuites() is for TLSv1.3 and was introduced in openssl
952
  // 1.1.1, set_cipher_list() is for TLSv1.2 and earlier.
953
  //
954
  // In openssl 1.1.0, set_cipher_list() would error if it resulted in no
955
  // TLSv1.2 (and earlier) cipher suites, and there is no TLSv1.3 support.
956
  //
957
  // In openssl 1.1.1, set_cipher_list() will not error if it results in no
958
  // TLSv1.2 cipher suites if there are any TLSv1.3 cipher suites, which there
959
  // are by default. There will be an error later, during the handshake, but
960
  // that results in an async error event, rather than a sync error thrown,
961
  // which is a semver-major change for the tls API.
962
  //
963
  // Since we don't currently support TLSv1.3, work around this by removing the
964
  // TLSv1.3 cipher suites, so we get backwards compatible synchronous errors.
965
3220
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
966
1612
  if (
967
#ifdef TLS1_3_VERSION
968

3224
      !SSL_CTX_set_ciphersuites(sc->ctx_.get(), "") ||
969
#endif
970
1612
      !SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
971
4
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
972
4
    if (!err) {
973
      return env->ThrowError("Failed to set ciphers");
974
    }
975
4
    return ThrowCryptoError(env, err);
976
1608
  }
977
}
978
979
980
1605
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
981
  SecureContext* sc;
982
3204
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
983
1605
  Environment* env = sc->env();
984
985
1605
  if (args.Length() != 1)
986
    return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory");
987
988
4815
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name");
989
990
1604
  node::Utf8Value curve(env->isolate(), args[0]);
991
992
1604
  if (strcmp(*curve, "auto") == 0)
993
1595
    return;
994
995
9
  if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve))
996
3
    return env->ThrowError("Failed to set ECDH curve");
997
}
998
999
1000
10
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
1001
  SecureContext* sc;
1002
13
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
1003
10
  Environment* env = sc->env();
1004
  ClearErrorOnReturn clear_error_on_return;
1005
1006
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
1007
  // to be specified explicitly
1008
10
  if (args.Length() != 1)
1009
    return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory");
1010
1011
17
  DHPointer dh;
1012
  {
1013
10
    BIOPointer bio(LoadBIO(env, args[0]));
1014
10
    if (!bio)
1015
      return;
1016
1017
10
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
1018
  }
1019
1020
  // Invalid dhparam is silently discarded and DHE is no longer used.
1021
10
  if (!dh)
1022
1
    return;
1023
1024
  const BIGNUM* p;
1025
9
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
1026
9
  const int size = BN_num_bits(p);
1027
9
  if (size < 1024) {
1028
    return THROW_ERR_INVALID_ARG_VALUE(
1029
2
        env, "DH parameter is less than 1024 bits");
1030
7
  } else if (size < 2048) {
1031
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1032
9
        env->isolate(), "DH parameter is less than 2048 bits"));
1033
  }
1034
1035
7
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
1036
7
  int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get());
1037
1038
7
  if (!r)
1039
7
    return env->ThrowTypeError("Error setting temp DH parameter");
1040
}
1041
1042
1043
522
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1044
  SecureContext* sc;
1045
522
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1046
  int64_t val;
1047
1048

2610
  if (args.Length() != 1 ||
1049

3132
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1050
    return THROW_ERR_INVALID_ARG_TYPE(
1051
        sc->env(), "Options must be an integer value");
1052
  }
1053
1054
  SSL_CTX_set_options(sc->ctx_.get(),
1055
522
                      static_cast<long>(val));  // NOLINT(runtime/int)
1056
}
1057
1058
1059
454
void SecureContext::SetSessionIdContext(
1060
    const FunctionCallbackInfo<Value>& args) {
1061
  SecureContext* sc;
1062
908
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1063
454
  Environment* env = sc->env();
1064
1065
454
  if (args.Length() != 1) {
1066
    return THROW_ERR_MISSING_ARGS(
1067
        env, "Session ID context argument is mandatory");
1068
  }
1069
1070
1362
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1071
1072
454
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1073
  const unsigned char* sid_ctx =
1074
454
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1075
454
  unsigned int sid_ctx_len = sessionIdContext.length();
1076
1077
454
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1078
454
  if (r == 1)
1079
454
    return;
1080
1081
  BUF_MEM* mem;
1082
  Local<String> message;
1083
1084
  BIOPointer bio(BIO_new(BIO_s_mem()));
1085
  if (!bio) {
1086
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1087
                                    "SSL_CTX_set_session_id_context error");
1088
  } else {
1089
    ERR_print_errors(bio.get());
1090
    BIO_get_mem_ptr(bio.get(), &mem);
1091
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1092
  }
1093
1094
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1095
}
1096
1097
1098
2
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1099
  SecureContext* sc;
1100
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1101
1102


8
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1103
    return THROW_ERR_INVALID_ARG_TYPE(
1104
1
        sc->env(), "Session timeout must be a 32-bit integer");
1105
  }
1106
1107
3
  int32_t sessionTimeout = args[0].As<Int32>()->Value();
1108
1
  SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
1109
}
1110
1111
1112
1038
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1113
  SecureContext* sc;
1114
2076
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1115
1038
  sc->Reset();
1116
}
1117
1118
1119
// Takes .pfx or .p12 and password in string or buffer format
1120
18
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1121
18
  Environment* env = Environment::GetCurrent(args);
1122
1123
18
  std::vector<char> pass;
1124
18
  bool ret = false;
1125
1126
  SecureContext* sc;
1127
18
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1128
12
  ClearErrorOnReturn clear_error_on_return;
1129
1130
18
  if (args.Length() < 1) {
1131
    return THROW_ERR_MISSING_ARGS(env, "PFX certificate argument is mandatory");
1132
  }
1133
1134
30
  BIOPointer in(LoadBIO(env, args[0]));
1135
18
  if (!in)
1136
    return env->ThrowError("Unable to load BIO");
1137
1138
18
  if (args.Length() >= 2) {
1139
15
    THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase");
1140
30
    Local<ArrayBufferView> abv = args[1].As<ArrayBufferView>();
1141
15
    size_t passlen = abv->ByteLength();
1142
15
    pass.resize(passlen + 1);
1143
30
    abv->CopyContents(pass.data(), passlen);
1144
15
    pass[passlen] = '\0';
1145
  }
1146
1147
  // Free previous certs
1148
18
  sc->issuer_.reset();
1149
18
  sc->cert_.reset();
1150
1151
18
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1152
1153
30
  DeleteFnPtr<PKCS12, PKCS12_free> p12;
1154
30
  EVPKeyPointer pkey;
1155
30
  X509Pointer cert;
1156
30
  StackOfX509 extra_certs;
1157
1158
18
  PKCS12* p12_ptr = nullptr;
1159
18
  EVP_PKEY* pkey_ptr = nullptr;
1160
18
  X509* cert_ptr = nullptr;
1161
18
  STACK_OF(X509)* extra_certs_ptr = nullptr;
1162
36
  if (d2i_PKCS12_bio(in.get(), &p12_ptr) &&
1163
32
      (p12.reset(p12_ptr), true) &&  // Move ownership to the smart pointer.
1164
16
      PKCS12_parse(p12.get(), pass.data(),
1165
                   &pkey_ptr,
1166
                   &cert_ptr,
1167
16
                   &extra_certs_ptr) &&
1168
12
      (pkey.reset(pkey_ptr), cert.reset(cert_ptr),
1169
24
       extra_certs.reset(extra_certs_ptr), true) &&  // Move ownership.
1170
      SSL_CTX_use_certificate_chain(sc->ctx_.get(),
1171
12
                                    std::move(cert),
1172
                                    extra_certs.get(),
1173
                                    &sc->cert_,
1174

54
                                    &sc->issuer_) &&
1175
12
      SSL_CTX_use_PrivateKey(sc->ctx_.get(), pkey.get())) {
1176
    // Add CA certs too
1177
21
    for (int i = 0; i < sk_X509_num(extra_certs.get()); i++) {
1178
9
      X509* ca = sk_X509_value(extra_certs.get(), i);
1179
1180
9
      if (cert_store == root_cert_store) {
1181
6
        cert_store = NewRootCertStore();
1182
6
        SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1183
      }
1184
9
      X509_STORE_add_cert(cert_store, ca);
1185
9
      SSL_CTX_add_client_CA(sc->ctx_.get(), ca);
1186
    }
1187
12
    ret = true;
1188
  }
1189
1190
18
  if (!ret) {
1191
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1192
6
    const char* str = ERR_reason_error_string(err);
1193
6
    return env->ThrowError(str);
1194
12
  }
1195
}
1196
1197
1198
#ifndef OPENSSL_NO_ENGINE
1199
// Helper for the smart pointer.
1200
void ENGINE_free_fn(ENGINE* engine) { ENGINE_free(engine); }
1201
1202
void SecureContext::SetClientCertEngine(
1203
    const FunctionCallbackInfo<Value>& args) {
1204
  Environment* env = Environment::GetCurrent(args);
1205
  CHECK_EQ(args.Length(), 1);
1206
  CHECK(args[0]->IsString());
1207
1208
  SecureContext* sc;
1209
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1210
1211
  MarkPopErrorOnReturn mark_pop_error_on_return;
1212
1213
  // SSL_CTX_set_client_cert_engine does not itself support multiple
1214
  // calls by cleaning up before overwriting the client_cert_engine
1215
  // internal context variable.
1216
  // Instead of trying to fix up this problem we in turn also do not
1217
  // support multiple calls to SetClientCertEngine.
1218
  if (sc->client_cert_engine_provided_) {
1219
    return env->ThrowError(
1220
        "Multiple calls to SetClientCertEngine are not allowed");
1221
  }
1222
1223
  const node::Utf8Value engine_id(env->isolate(), args[0]);
1224
  char errmsg[1024];
1225
  DeleteFnPtr<ENGINE, ENGINE_free_fn> engine(
1226
      LoadEngineById(*engine_id, &errmsg));
1227
1228
  if (!engine)
1229
    return env->ThrowError(errmsg);
1230
1231
  // Note that this takes another reference to `engine`.
1232
  int r = SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get());
1233
  if (r == 0)
1234
    return ThrowCryptoError(env, ERR_get_error());
1235
  sc->client_cert_engine_provided_ = true;
1236
}
1237
#endif  // !OPENSSL_NO_ENGINE
1238
1239
1240
7
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1241
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1242
1243
  SecureContext* wrap;
1244
14
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1245
1246
14
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1247
7
  memcpy(Buffer::Data(buff), wrap->ticket_key_name_, 16);
1248
7
  memcpy(Buffer::Data(buff) + 16, wrap->ticket_key_hmac_, 16);
1249
7
  memcpy(Buffer::Data(buff) + 32, wrap->ticket_key_aes_, 16);
1250
1251
14
  args.GetReturnValue().Set(buff);
1252
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1253
}
1254
1255
1256
16
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1257
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1258
  SecureContext* wrap;
1259
18
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1260
16
  Environment* env = wrap->env();
1261
1262
16
  if (args.Length() < 1) {
1263
    return THROW_ERR_MISSING_ARGS(env, "Ticket keys argument is mandatory");
1264
  }
1265
1266
16
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Ticket keys");
1267
30
  ArrayBufferViewContents<char> buf(args[0].As<ArrayBufferView>());
1268
1269
15
  if (buf.length() != 48) {
1270
    return THROW_ERR_INVALID_ARG_VALUE(
1271
1
        env, "Ticket keys length must be 48 bytes");
1272
  }
1273
1274
14
  memcpy(wrap->ticket_key_name_, buf.data(), 16);
1275
14
  memcpy(wrap->ticket_key_hmac_, buf.data() + 16, 16);
1276
14
  memcpy(wrap->ticket_key_aes_, buf.data() + 32, 16);
1277
1278
28
  args.GetReturnValue().Set(true);
1279
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1280
}
1281
1282
1283
1060
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1284
1060
}
1285
1286
1287
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1288
// the regression test in test/parallel/test-https-resume-after-renew.js.
1289
1
void SecureContext::EnableTicketKeyCallback(
1290
    const FunctionCallbackInfo<Value>& args) {
1291
  SecureContext* wrap;
1292
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1293
1294
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback);
1295
}
1296
1297
1298
3
int SecureContext::TicketKeyCallback(SSL* ssl,
1299
                                     unsigned char* name,
1300
                                     unsigned char* iv,
1301
                                     EVP_CIPHER_CTX* ectx,
1302
                                     HMAC_CTX* hctx,
1303
                                     int enc) {
1304
  static const int kTicketPartSize = 16;
1305
1306
  SecureContext* sc = static_cast<SecureContext*>(
1307
3
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1308
1309
3
  Environment* env = sc->env();
1310
3
  HandleScope handle_scope(env->isolate());
1311
3
  Context::Scope context_scope(env->context());
1312
1313
  Local<Value> argv[] = {
1314
    Buffer::Copy(env,
1315
                 reinterpret_cast<char*>(name),
1316
                 kTicketPartSize).ToLocalChecked(),
1317
    Buffer::Copy(env,
1318
                 reinterpret_cast<char*>(iv),
1319
                 kTicketPartSize).ToLocalChecked(),
1320
    Boolean::New(env->isolate(), enc != 0)
1321
12
  };
1322
1323
  Local<Value> ret = node::MakeCallback(env->isolate(),
1324
                                        sc->object(),
1325
                                        env->ticketkeycallback_string(),
1326
3
                                        arraysize(argv),
1327
                                        argv,
1328
9
                                        {0, 0}).ToLocalChecked();
1329
3
  Local<Array> arr = ret.As<Array>();
1330
1331
  int r =
1332
3
      arr->Get(env->context(),
1333
9
               kTicketKeyReturnIndex).ToLocalChecked()
1334
12
               ->Int32Value(env->context()).FromJust();
1335
3
  if (r < 0)
1336
    return r;
1337
1338
3
  Local<Value> hmac = arr->Get(env->context(),
1339
9
                               kTicketKeyHMACIndex).ToLocalChecked();
1340
3
  Local<Value> aes = arr->Get(env->context(),
1341
9
                              kTicketKeyAESIndex).ToLocalChecked();
1342
3
  if (Buffer::Length(aes) != kTicketPartSize)
1343
    return -1;
1344
1345
3
  if (enc) {
1346
2
    Local<Value> name_val = arr->Get(env->context(),
1347
6
                                     kTicketKeyNameIndex).ToLocalChecked();
1348
2
    Local<Value> iv_val = arr->Get(env->context(),
1349
6
                                   kTicketKeyIVIndex).ToLocalChecked();
1350
1351

4
    if (Buffer::Length(name_val) != kTicketPartSize ||
1352
2
        Buffer::Length(iv_val) != kTicketPartSize) {
1353
      return -1;
1354
    }
1355
1356
4
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1357
4
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1358
  }
1359
1360
3
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1361
  HMAC_Init_ex(hctx,
1362
3
               hmac_buf.data(),
1363
3
               hmac_buf.length(),
1364
               EVP_sha256(),
1365
9
               nullptr);
1366
1367
3
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1368
3
  if (enc) {
1369
    EVP_EncryptInit_ex(ectx,
1370
                       EVP_aes_128_cbc(),
1371
                       nullptr,
1372
                       aes_key.data(),
1373
2
                       iv);
1374
  } else {
1375
    EVP_DecryptInit_ex(ectx,
1376
                       EVP_aes_128_cbc(),
1377
                       nullptr,
1378
                       aes_key.data(),
1379
1
                       iv);
1380
  }
1381
1382
6
  return r;
1383
}
1384
1385
1386
641
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1387
                                               unsigned char* name,
1388
                                               unsigned char* iv,
1389
                                               EVP_CIPHER_CTX* ectx,
1390
                                               HMAC_CTX* hctx,
1391
                                               int enc) {
1392
  SecureContext* sc = static_cast<SecureContext*>(
1393
641
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1394
1395
641
  if (enc) {
1396
596
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1397

1788
    if (RAND_bytes(iv, 16) <= 0 ||
1398
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1399

1192
                           sc->ticket_key_aes_, iv) <= 0 ||
1400
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1401
596
                     EVP_sha256(), nullptr) <= 0) {
1402
      return -1;
1403
    }
1404
596
    return 1;
1405
  }
1406
1407
45
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1408
    // The ticket key name does not match. Discard the ticket.
1409
9
    return 0;
1410
  }
1411
1412
36
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1413

72
                         iv) <= 0 ||
1414
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1415
36
                   EVP_sha256(), nullptr) <= 0) {
1416
    return -1;
1417
  }
1418
36
  return 1;
1419
}
1420
1421
1422
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1423
  SecureContext* sc;
1424
4
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1425
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1426
4
  info.GetReturnValue().Set(ext);
1427
}
1428
1429
1430
template <bool primary>
1431
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1432
  SecureContext* wrap;
1433

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1434
6
  Environment* env = wrap->env();
1435
  X509* cert;
1436
1437
  if (primary)
1438
3
    cert = wrap->cert_.get();
1439
  else
1440
3
    cert = wrap->issuer_.get();
1441

6
  if (cert == nullptr)
1442
    return args.GetReturnValue().SetNull();
1443
1444
6
  int size = i2d_X509(cert, nullptr);
1445
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1446
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1447
6
      Buffer::Data(buff));
1448
6
  i2d_X509(cert, &serialized);
1449
1450
12
  args.GetReturnValue().Set(buff);
1451
}
1452
1453
1454
template <class Base>
1455
455
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1456
455
  HandleScope scope(env->isolate());
1457
1458
455
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
1459
455
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
1460
455
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
1461
455
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
1462
455
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
1463
455
  env->SetProtoMethod(t, "setSession", SetSession);
1464
455
  env->SetProtoMethod(t, "loadSession", LoadSession);
1465
455
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
1466
455
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
1467
455
  env->SetProtoMethodNoSideEffect(t, "getCurrentCipher", GetCurrentCipher);
1468
455
  env->SetProtoMethod(t, "endParser", EndParser);
1469
455
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1470
455
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1471
455
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
1472
455
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1473
455
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1474
455
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1475
455
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
1476
                                  GetEphemeralKeyInfo);
1477
455
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
1478
1479
#ifdef SSL_set_max_send_fragment
1480
455
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1481
#endif  // SSL_set_max_send_fragment
1482
1483
455
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
1484
                                  GetALPNNegotiatedProto);
1485
455
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1486
455
}
1487
1488
1489
template <class Base>
1490
11707
void SSLWrap<Base>::ConfigureSecureContext(SecureContext* sc) {
1491
  // OCSP stapling
1492
11707
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
1493
11707
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
1494
11707
}
1495
1496
1497
template <class Base>
1498
46
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1499
                                               const unsigned char* key,
1500
                                               int len,
1501
                                               int* copy) {
1502
46
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1503
1504
46
  *copy = 0;
1505
46
  return w->next_sess_.release();
1506
}
1507
1508
1509
template <class Base>
1510
585
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1511
585
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1512
585
  Environment* env = w->ssl_env();
1513
585
  HandleScope handle_scope(env->isolate());
1514
585
  Context::Scope context_scope(env->context());
1515
1516
585
  if (!w->session_callbacks_)
1517
415
    return 0;
1518
1519
  // Check if session is small enough to be stored
1520
170
  int size = i2d_SSL_SESSION(sess, nullptr);
1521
170
  if (size > SecureContext::kMaxSessionSize)
1522
    return 0;
1523
1524
  // Serialize session
1525
340
  Local<Object> session = Buffer::New(env, size).ToLocalChecked();
1526
  unsigned char* session_data = reinterpret_cast<unsigned char*>(
1527
170
      Buffer::Data(session));
1528
170
  memset(session_data, 0, size);
1529
170
  i2d_SSL_SESSION(sess, &session_data);
1530
1531
  unsigned int session_id_length;
1532
  const unsigned char* session_id_data = SSL_SESSION_get_id(sess,
1533
170
                                                            &session_id_length);
1534
  Local<Object> session_id = Buffer::Copy(
1535
      env,
1536
      reinterpret_cast<const char*>(session_id_data),
1537
340
      session_id_length).ToLocalChecked();
1538
510
  Local<Value> argv[] = { session_id, session };
1539
  // On servers, we pause the handshake until callback of 'newSession', which
1540
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
1541
170
  if (w->is_server())
1542
8
    w->awaiting_new_session_ = true;
1543
170
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1544
1545
755
  return 0;
1546
}
1547
1548
1549
template <class Base>
1550
20
void SSLWrap<Base>::OnClientHello(void* arg,
1551
                                  const ClientHelloParser::ClientHello& hello) {
1552
20
  Base* w = static_cast<Base*>(arg);
1553
20
  Environment* env = w->ssl_env();
1554
20
  HandleScope handle_scope(env->isolate());
1555
20
  Local<Context> context = env->context();
1556
  Context::Scope context_scope(context);
1557
1558
20
  Local<Object> hello_obj = Object::New(env->isolate());
1559
  Local<Object> buff = Buffer::Copy(
1560
      env,
1561
20
      reinterpret_cast<const char*>(hello.session_id()),
1562
60
      hello.session_size()).ToLocalChecked();
1563
60
  hello_obj->Set(context, env->session_id_string(), buff).FromJust();
1564
20
  if (hello.servername() == nullptr) {
1565
    hello_obj->Set(context,
1566
                   env->servername_string(),
1567
8
                   String::Empty(env->isolate())).FromJust();
1568
  } else {
1569
    Local<String> servername = OneByteString(env->isolate(),
1570
                                             hello.servername(),
1571
18
                                             hello.servername_size());
1572
54
    hello_obj->Set(context, env->servername_string(), servername).FromJust();
1573
  }
1574
  hello_obj->Set(context,
1575
                 env->tls_ticket_string(),
1576
80
                 Boolean::New(env->isolate(), hello.has_ticket())).FromJust();
1577
1578
40
  Local<Value> argv[] = { hello_obj };
1579
40
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1580
20
}
1581
1582
1583
91
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1584
91
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1585
1586
91
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1587
81
    return false;
1588
1589
10
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
1590
10
  if (names == nullptr)
1591
    return false;
1592
1593
39
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1594
29
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1595
1596
29
    if (i != 0)
1597
19
      BIO_write(out, ", ", 2);
1598
1599
29
    if (gen->type == GEN_DNS) {
1600
26
      ASN1_IA5STRING* name = gen->d.dNSName;
1601
1602
26
      BIO_write(out, "DNS:", 4);
1603
26
      BIO_write(out, name->data, name->length);
1604
    } else {
1605
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1606
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
1607
3
      if (nval == nullptr)
1608
        return false;
1609
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1610
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1611
    }
1612
  }
1613
10
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1614
1615
10
  return true;
1616
}
1617
1618
1619
1050
static void AddFingerprintDigest(const unsigned char* md,
1620
                                 unsigned int md_size,
1621
                                 char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) {
1622
  unsigned int i;
1623
1050
  const char hex[] = "0123456789ABCDEF";
1624
1625
28350
  for (i = 0; i < md_size; i++) {
1626
27300
    (*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4];
1627
27300
    (*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)];
1628
27300
    (*fingerprint)[(3*i)+2] = ':';
1629
  }
1630
1631
1050
  if (md_size > 0) {
1632
1050
    (*fingerprint)[(3*(md_size-1))+2] = '\0';
1633
  } else {
1634
    (*fingerprint)[0] = '\0';
1635
  }
1636
1050
}
1637
1638
1639
60
static MaybeLocal<Object> ECPointToBuffer(Environment* env,
1640
                                          const EC_GROUP* group,
1641
                                          const EC_POINT* point,
1642
                                          point_conversion_form_t form,
1643
                                          const char** error) {
1644
60
  size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, nullptr);
1645
60
  if (len == 0) {
1646
    if (error != nullptr) *error = "Failed to get public key length";
1647
    return MaybeLocal<Object>();
1648
  }
1649
60
  AllocatedBuffer buf = env->AllocateManaged(len);
1650
  len = EC_POINT_point2oct(group,
1651
                           point,
1652
                           form,
1653
60
                           reinterpret_cast<unsigned char*>(buf.data()),
1654
                           buf.size(),
1655
120
                           nullptr);
1656
60
  if (len == 0) {
1657
    if (error != nullptr) *error = "Failed to get public key";
1658
    return MaybeLocal<Object>();
1659
  }
1660
60
  return buf.ToBuffer();
1661
}
1662
1663
1664
525
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1665
525
  EscapableHandleScope scope(env->isolate());
1666
525
  Local<Context> context = env->context();
1667
525
  Local<Object> info = Object::New(env->isolate());
1668
1669
1050
  BIOPointer bio(BIO_new(BIO_s_mem()));
1670
  BUF_MEM* mem;
1671
525
  if (X509_NAME_print_ex(bio.get(),
1672
525
                         X509_get_subject_name(cert),
1673
                         0,
1674
525
                         X509_NAME_FLAGS) > 0) {
1675
525
    BIO_get_mem_ptr(bio.get(), &mem);
1676
    info->Set(context, env->subject_string(),
1677
              String::NewFromUtf8(env->isolate(), mem->data,
1678
                                  NewStringType::kNormal,
1679
2100
                                  mem->length).ToLocalChecked()).FromJust();
1680
  }
1681
525
  USE(BIO_reset(bio.get()));
1682
1683
525
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1684
525
  if (X509_NAME_print_ex(bio.get(), issuer_name, 0, X509_NAME_FLAGS) > 0) {
1685
525
    BIO_get_mem_ptr(bio.get(), &mem);
1686
    info->Set(context, env->issuer_string(),
1687
              String::NewFromUtf8(env->isolate(), mem->data,
1688
                                  NewStringType::kNormal,
1689
2100
                                  mem->length).ToLocalChecked()).FromJust();
1690
  }
1691
525
  USE(BIO_reset(bio.get()));
1692
1693
525
  int nids[] = { NID_subject_alt_name, NID_info_access };
1694
  Local<String> keys[] = { env->subjectaltname_string(),
1695
525
                           env->infoaccess_string() };
1696
525
  CHECK_EQ(arraysize(nids), arraysize(keys));
1697
1575
  for (size_t i = 0; i < arraysize(nids); i++) {
1698
1050
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1699
1050
    if (index < 0)
1700
959
      continue;
1701
1702
91
    X509_EXTENSION* ext = X509_get_ext(cert, index);
1703
91
    CHECK_NOT_NULL(ext);
1704
1705
91
    if (!SafeX509ExtPrint(bio.get(), ext)) {
1706
81
      CHECK_EQ(1, X509V3_EXT_print(bio.get(), ext, 0, 0));
1707
    }
1708
1709
91
    BIO_get_mem_ptr(bio.get(), &mem);
1710
    info->Set(context, keys[i],
1711
              String::NewFromUtf8(env->isolate(), mem->data,
1712
                                  NewStringType::kNormal,
1713
273
                                  mem->length).ToLocalChecked()).FromJust();
1714
1715
91
    USE(BIO_reset(bio.get()));
1716
  }
1717
1718
1050
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1719
1050
  RSAPointer rsa;
1720
1050
  ECPointer ec;
1721
525
  if (pkey) {
1722
525
    switch (EVP_PKEY_id(pkey.get())) {
1723
      case EVP_PKEY_RSA:
1724
491
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1725
491
        break;
1726
      case EVP_PKEY_EC:
1727
34
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1728
34
        break;
1729
    }
1730
  }
1731
1732
525
  if (rsa) {
1733
    const BIGNUM* n;
1734
    const BIGNUM* e;
1735
491
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1736
491
    BN_print(bio.get(), n);
1737
491
    BIO_get_mem_ptr(bio.get(), &mem);
1738
    info->Set(context, env->modulus_string(),
1739
              String::NewFromUtf8(env->isolate(), mem->data,
1740
                                  NewStringType::kNormal,
1741
1964
                                  mem->length).ToLocalChecked()).FromJust();
1742
491
    USE(BIO_reset(bio.get()));
1743
1744
491
    int bits = BN_num_bits(n);
1745
    info->Set(context, env->bits_string(),
1746
1964
              Integer::New(env->isolate(), bits)).FromJust();
1747
1748
491
    uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
1749
491
    uint32_t lo = static_cast<uint32_t>(exponent_word);
1750
491
    uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
1751
491
    if (hi == 0) {
1752
491
      BIO_printf(bio.get(), "0x%x", lo);
1753
    } else {
1754
      BIO_printf(bio.get(), "0x%x%08x", hi, lo);
1755
    }
1756
491
    BIO_get_mem_ptr(bio.get(), &mem);
1757
    info->Set(context, env->exponent_string(),
1758
              String::NewFromUtf8(env->isolate(), mem->data,
1759
                                  NewStringType::kNormal,
1760
1964
                                  mem->length).ToLocalChecked()).FromJust();
1761
491
    USE(BIO_reset(bio.get()));
1762
1763
491
    int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
1764
491
    CHECK_GE(size, 0);
1765
982
    Local<Object> pubbuff = Buffer::New(env, size).ToLocalChecked();
1766
    unsigned char* pubserialized =
1767
491
        reinterpret_cast<unsigned char*>(Buffer::Data(pubbuff));
1768
491
    i2d_RSA_PUBKEY(rsa.get(), &pubserialized);
1769
1964
    info->Set(env->context(), env->pubkey_string(), pubbuff).FromJust();
1770
34
  } else if (ec) {
1771
34
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1772
34
    if (group != nullptr) {
1773
34
      int bits = EC_GROUP_order_bits(group);
1774
34
      if (bits > 0) {
1775
        info->Set(context, env->bits_string(),
1776
136
                  Integer::New(env->isolate(), bits)).FromJust();
1777
      }
1778
    }
1779
1780
34
    const EC_POINT* pubkey = EC_KEY_get0_public_key(ec.get());
1781
    Local<Object> buf;
1782

136
    if (pubkey != nullptr &&
1783
        ECPointToBuffer(
1784
34
            env, group, pubkey, EC_KEY_get_conv_form(ec.get()), nullptr)
1785
136
            .ToLocal(&buf)) {
1786
102
      info->Set(context, env->pubkey_string(), buf).FromJust();
1787
    }
1788
1789
34
    const int nid = EC_GROUP_get_curve_name(group);
1790
34
    if (nid != 0) {
1791
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1792
1793
34
      if (const char* sn = OBJ_nid2sn(nid)) {
1794
        info->Set(context, env->asn1curve_string(),
1795
136
                  OneByteString(env->isolate(), sn)).FromJust();
1796
      }
1797
1798
34
      if (const char* nist = EC_curve_nid2nist(nid)) {
1799
        info->Set(context, env->nistcurve_string(),
1800
136
                  OneByteString(env->isolate(), nist)).FromJust();
1801
      }
1802
    } else {
1803
      // Unnamed curves can be described by their mathematical properties,
1804
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
1805
    }
1806
  }
1807
1808
525
  pkey.reset();
1809
525
  rsa.reset();
1810
525
  ec.reset();
1811
1812
525
  ASN1_TIME_print(bio.get(), X509_get_notBefore(cert));
1813
525
  BIO_get_mem_ptr(bio.get(), &mem);
1814
  info->Set(context, env->valid_from_string(),
1815
            String::NewFromUtf8(env->isolate(), mem->data,
1816
                                NewStringType::kNormal,
1817
2100
                                mem->length).ToLocalChecked()).FromJust();
1818
525
  USE(BIO_reset(bio.get()));
1819
1820
525
  ASN1_TIME_print(bio.get(), X509_get_notAfter(cert));
1821
525
  BIO_get_mem_ptr(bio.get(), &mem);
1822
  info->Set(context, env->valid_to_string(),
1823
            String::NewFromUtf8(env->isolate(), mem->data,
1824
                                NewStringType::kNormal,
1825
2100
                                mem->length).ToLocalChecked()).FromJust();
1826
525
  bio.reset();
1827
1828
  unsigned char md[EVP_MAX_MD_SIZE];
1829
  unsigned int md_size;
1830
  char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
1831
525
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1832
525
      AddFingerprintDigest(md, md_size, &fingerprint);
1833
      info->Set(context, env->fingerprint_string(),
1834
2100
                OneByteString(env->isolate(), fingerprint)).FromJust();
1835
  }
1836
525
  if (X509_digest(cert, EVP_sha256(), md, &md_size)) {
1837
525
      AddFingerprintDigest(md, md_size, &fingerprint);
1838
      info->Set(context, env->fingerprint256_string(),
1839
2100
                OneByteString(env->isolate(), fingerprint)).FromJust();
1840
  }
1841
1842
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
1843
525
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
1844
525
  if (eku) {
1845
18
    Local<Array> ext_key_usage = Array::New(env->isolate());
1846
    char buf[256];
1847
1848
18
    int j = 0;
1849
50
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku.get()); i++) {
1850
32
      if (OBJ_obj2txt(buf,
1851
                      sizeof(buf),
1852
32
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
1853
32
        ext_key_usage->Set(context,
1854
                           j++,
1855
128
                           OneByteString(env->isolate(), buf)).FromJust();
1856
      }
1857
    }
1858
1859
18
    eku.reset();
1860
54
    info->Set(context, env->ext_key_usage_string(), ext_key_usage).FromJust();
1861
  }
1862
1863
525
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1864
525
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
1865
525
    if (bn) {
1866
525
      OpenSSLBuffer buf(BN_bn2hex(bn.get()));
1867
525
      if (buf) {
1868
        info->Set(context, env->serial_number_string(),
1869
2100
                  OneByteString(env->isolate(), buf.get())).FromJust();
1870
525
      }
1871
525
    }
1872
  }
1873
1874
  // Raw DER certificate
1875
525
  int size = i2d_X509(cert, nullptr);
1876
1050
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1877
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1878
525
      Buffer::Data(buff));
1879
525
  i2d_X509(cert, &serialized);
1880
1575
  info->Set(context, env->raw_string(), buff).FromJust();
1881
1882
1050
  return scope.Escape(info);
1883
}
1884
1885
1886
179
static Local<Object> AddIssuerChainToObject(X509Pointer* cert,
1887
                                            Local<Object> object,
1888
                                            StackOfX509&& peer_certs,
1889
                                            Environment* const env) {
1890
179
  Local<Context> context = env->isolate()->GetCurrentContext();
1891
179
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
1892
  for (;;) {
1893
    int i;
1894
382
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
1895
140
      X509* ca = sk_X509_value(peer_certs.get(), i);
1896
140
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
1897
2
        continue;
1898
1899
138
      Local<Object> ca_info = X509ToObject(env, ca);
1900
414
      object->Set(context, env->issuercert_string(), ca_info).FromJust();
1901
138
      object = ca_info;
1902
1903
      // NOTE: Intentionally freeing cert that is not used anymore.
1904
      // Delete cert and continue aggregating issuers.
1905
138
      cert->reset(sk_X509_delete(peer_certs.get(), i));
1906
138
      break;
1907
    }
1908
1909
    // Issuer not found, break out of the loop.
1910
189
    if (i == sk_X509_num(peer_certs.get()))
1911
179
      break;
1912
10
  }
1913
179
  return object;
1914
}
1915
1916
1917
179
static StackOfX509 CloneSSLCerts(X509Pointer&& cert,
1918
                                 const STACK_OF(X509)* const ssl_certs) {
1919
179
  StackOfX509 peer_certs(sk_X509_new(nullptr));
1920
179
  if (cert)
1921
    sk_X509_push(peer_certs.get(), cert.release());
1922
498
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
1923
319
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
1924

319
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
1925
      return StackOfX509();
1926
    // `cert` is now managed by the stack.
1927
319
    cert.release();
1928
319
  }
1929
179
  return peer_certs;
1930
}
1931
1932
1933
179
static Local<Object> GetLastIssuedCert(X509Pointer* cert,
1934
                                       const SSLPointer& ssl,
1935
                                       Local<Object> issuer_chain,
1936
                                       Environment* const env) {
1937
179
  Local<Context> context = env->isolate()->GetCurrentContext();
1938
512
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
1939
    X509* ca;
1940
154
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
1941
      break;
1942
1943
154
    Local<Object> ca_info = X509ToObject(env, ca);
1944
462
    issuer_chain->Set(context, env->issuercert_string(), ca_info).FromJust();
1945
154
    issuer_chain = ca_info;
1946
1947
    // Delete previous cert and continue aggregating issuers.
1948
154
    cert->reset(ca);
1949
  }
1950
179
  return issuer_chain;
1951
}
1952
1953
1954
template <class Base>
1955
225
void SSLWrap<Base>::GetPeerCertificate(
1956
    const FunctionCallbackInfo<Value>& args) {
1957
  Base* w;
1958
450
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1959
225
  Environment* env = w->ssl_env();
1960
1961
  ClearErrorOnReturn clear_error_on_return;
1962
1963
  Local<Object> result;
1964
  // Used to build the issuer certificate chain.
1965
  Local<Object> issuer_chain;
1966
1967
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1968
  // contains the `peer_certificate`, but on server it doesn't.
1969
  X509Pointer cert(
1970
450
      w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) : nullptr);
1971
225
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_.get());
1972


225
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
1973
3
    goto done;
1974
1975
  // Short result requested.
1976


888
  if (args.Length() < 1 || !args[0]->IsTrue()) {
1977
43
    result = X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
1978
43
    goto done;
1979
  }
1980
1981
358
  if (auto peer_certs = CloneSSLCerts(std::move(cert), ssl_certs)) {
1982
    // First and main certificate.
1983
179
    X509Pointer cert(sk_X509_value(peer_certs.get(), 0));
1984
179
    CHECK(cert);
1985
179
    result = X509ToObject(env, cert.release());
1986
1987
179
    issuer_chain =
1988
179
        AddIssuerChainToObject(&cert, result, std::move(peer_certs), env);
1989
179
    issuer_chain = GetLastIssuedCert(&cert, w->ssl_, issuer_chain, env);
1990
    // Last certificate should be self-signed.
1991
179
    if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK)
1992
      issuer_chain->Set(env->context(),
1993
                        env->issuercert_string(),
1994
716
                        issuer_chain).FromJust();
1995
  }
1996
1997
 done:
1998
675
  args.GetReturnValue().Set(result);
1999
}
2000
2001
2002
template <class Base>
2003
12
void SSLWrap<Base>::GetCertificate(
2004
    const FunctionCallbackInfo<Value>& args) {
2005
  Base* w;
2006
24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2007
12
  Environment* env = w->ssl_env();
2008
2009
  ClearErrorOnReturn clear_error_on_return;
2010
2011
  Local<Object> result;
2012
2013
12
  X509* cert = SSL_get_certificate(w->ssl_.get());
2014
2015
12
  if (cert != nullptr)
2016
11
    result = X509ToObject(env, cert);
2017
2018
24
  args.GetReturnValue().Set(result);
2019
}
2020
2021
2022
template <class Base>
2023
3
void SSLWrap<Base>::GetFinished(const FunctionCallbackInfo<Value>& args) {
2024
3
  Environment* env = Environment::GetCurrent(args);
2025
2026
  Base* w;
2027
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2028
2029
  // We cannot just pass nullptr to SSL_get_finished()
2030
  // because it would further be propagated to memcpy(),
2031
  // where the standard requirements as described in ISO/IEC 9899:2011
2032
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2033
  // Thus, we use a dummy byte.
2034
  char dummy[1];
2035
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
2036
3
  if (len == 0)
2037
1
    return;
2038
2039
2
  AllocatedBuffer buf = env->AllocateManaged(len);
2040
2
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf.data(), len));
2041
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
2042
}
2043
2044
2045
template <class Base>
2046
3
void SSLWrap<Base>::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
2047
3
  Environment* env = Environment::GetCurrent(args);
2048
2049
  Base* w;
2050
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2051
2052
  // We cannot just pass nullptr to SSL_get_peer_finished()
2053
  // because it would further be propagated to memcpy(),
2054
  // where the standard requirements as described in ISO/IEC 9899:2011
2055
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2056
  // Thus, we use a dummy byte.
2057
  char dummy[1];
2058
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
2059
3
  if (len == 0)
2060
1
    return;
2061
2062
2
  AllocatedBuffer buf = env->AllocateManaged(len);
2063
2
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf.data(), len));
2064
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
2065
}
2066
2067
2068
template <class Base>
2069
15
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
2070
15
  Environment* env = Environment::GetCurrent(args);
2071
2072
  Base* w;
2073
15
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2074
2075
15
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2076
15
  if (sess == nullptr)
2077
    return;
2078
2079
15
  int slen = i2d_SSL_SESSION(sess, nullptr);
2080
15
  CHECK_GT(slen, 0);
2081
2082
15
  AllocatedBuffer sbuf = env->AllocateManaged(slen);
2083
15
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf.data());
2084
15
  i2d_SSL_SESSION(sess, &p);
2085
45
  args.GetReturnValue().Set(sbuf.ToBuffer().ToLocalChecked());
2086
}
2087
2088
2089
template <class Base>
2090
80
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
2091
80
  Environment* env = Environment::GetCurrent(args);
2092
2093
  Base* w;
2094
80
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2095
2096
80
  if (args.Length() < 1) {
2097
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
2098
  }
2099
2100
80
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
2101
160
  ArrayBufferViewContents<unsigned char> sbuf(args[0].As<ArrayBufferView>());
2102
2103
80
  const unsigned char* p = sbuf.data();
2104
80
  SSLSessionPointer sess(d2i_SSL_SESSION(nullptr, &p, sbuf.length()));
2105
2106
80
  if (sess == nullptr)
2107
    return;
2108
2109
80
  int r = SSL_set_session(w->ssl_.get(), sess.get());
2110
2111
80
  if (!r)
2112
    return env->ThrowError("SSL_set_session error");
2113
}
2114
2115
2116
template <class Base>
2117
10
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
2118
  Base* w;
2119
20
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2120
2121

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2122
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
2123
2124
10
    const unsigned char* p = sbuf.data();
2125
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
2126
2127
    // Setup next session and move hello to the BIO buffer
2128
10
    w->next_sess_.reset(sess);
2129
  }
2130
}
2131
2132
2133
template <class Base>
2134
199
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2135
  Base* w;
2136
398
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2137
199
  bool yes = SSL_session_reused(w->ssl_.get());
2138
597
  args.GetReturnValue().Set(yes);
2139
}
2140
2141
2142
template <class Base>
2143
19
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2144
  Base* w;
2145
38
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2146
19
  w->hello_parser_.End();
2147
}
2148
2149
2150
template <class Base>
2151
91
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2152
  Base* w;
2153
182
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2154
2155
  ClearErrorOnReturn clear_error_on_return;
2156
2157
  // XXX(sam) Return/throw an error, don't discard the SSL error reason.
2158
91
  bool yes = SSL_renegotiate(w->ssl_.get()) == 1;
2159
273
  args.GetReturnValue().Set(yes);
2160
}
2161
2162
2163
template <class Base>
2164
9
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2165
  Base* w;
2166
9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2167
9
  Environment* env = w->ssl_env();
2168
2169
9
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2170
9
  if (sess == nullptr)
2171
    return;
2172
2173
  const unsigned char* ticket;
2174
  size_t length;
2175
9
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2176
2177
9
  if (ticket == nullptr)
2178
    return;
2179
2180
  Local<Object> buff = Buffer::Copy(
2181
18
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2182
2183
18
  args.GetReturnValue().Set(buff);
2184
}
2185
2186
2187
template <class Base>
2188
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2189
  Base* w;
2190
16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2191
8
  w->awaiting_new_session_ = false;
2192
8
  w->NewSessionDoneCb();
2193
}
2194
2195
2196
template <class Base>
2197
2
void SSLWrap<Base>::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
2198
  Base* w;
2199
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2200
2
  Environment* env = w->env();
2201
2202
2
  if (args.Length() < 1)
2203
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
2204
2205
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
2206
2207
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
2208
}
2209
2210
2211
template <class Base>
2212
4
void SSLWrap<Base>::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
2213
  Base* w;
2214
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2215
2216
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
2217
}
2218
2219
2220
template <class Base>
2221
607
void SSLWrap<Base>::GetEphemeralKeyInfo(
2222
    const FunctionCallbackInfo<Value>& args) {
2223
  Base* w;
2224
607
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2225
607
  Environment* env = Environment::GetCurrent(args);
2226
607
  Local<Context> context = env->context();
2227
2228
607
  CHECK(w->ssl_);
2229
2230
  // tmp key is available on only client
2231
607
  if (w->is_server())
2232
12
    return args.GetReturnValue().SetNull();
2233
2234
601
  Local<Object> info = Object::New(env->isolate());
2235
2236
  EVP_PKEY* key;
2237
2238
601
  if (SSL_get_server_tmp_key(w->ssl_.get(), &key)) {
2239
498
    int kid = EVP_PKEY_id(key);
2240
498
    switch (kid) {
2241
      case EVP_PKEY_DH:
2242
        info->Set(context, env->type_string(),
2243
24
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH")).FromJust();
2244
        info->Set(context, env->size_string(),
2245
24
                  Integer::New(env->isolate(), EVP_PKEY_bits(key))).FromJust();
2246
6
        break;
2247
      case EVP_PKEY_EC:
2248
      // TODO(shigeki) Change this to EVP_PKEY_X25519 and add EVP_PKEY_X448
2249
      // after upgrading to 1.1.1.
2250
      case NID_X25519:
2251
        {
2252
          const char* curve_name;
2253
492
          if (kid == EVP_PKEY_EC) {
2254
7
            EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
2255
7
            int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2256
7
            curve_name = OBJ_nid2sn(nid);
2257
7
            EC_KEY_free(ec);
2258
          } else {
2259
485
            curve_name = OBJ_nid2sn(kid);
2260
          }
2261
          info->Set(context, env->type_string(),
2262
1968
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")).FromJust();
2263
          info->Set(context, env->name_string(),
2264
                    OneByteString(args.GetIsolate(),
2265
1968
                                  curve_name)).FromJust();
2266
          info->Set(context, env->size_string(),
2267
                    Integer::New(env->isolate(),
2268
1968
                                 EVP_PKEY_bits(key))).FromJust();
2269
        }
2270
492
        break;
2271
    }
2272
498
    EVP_PKEY_free(key);
2273
  }
2274
2275
1202
  return args.GetReturnValue().Set(info);
2276
}
2277
2278
2279
#ifdef SSL_set_max_send_fragment
2280
template <class Base>
2281
3
void SSLWrap<Base>::SetMaxSendFragment(
2282
    const FunctionCallbackInfo<Value>& args) {
2283


12
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2284
2285
  Base* w;
2286
6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2287
2288
12
  int rv = SSL_set_max_send_fragment(
2289
      w->ssl_.get(),
2290
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2291
6
  args.GetReturnValue().Set(rv);
2292
}
2293
#endif  // SSL_set_max_send_fragment
2294
2295
2296
template <class Base>
2297
672
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2298
  Base* w;
2299
891
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2300
2301
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2302
  // peer certificate is questionable but it's compatible with what was
2303
  // here before.
2304
  long x509_verify_error =  // NOLINT(runtime/int)
2305
672
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2306
672
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_.get())) {
2307
671
    X509_free(peer_cert);
2308
671
    x509_verify_error = SSL_get_verify_result(w->ssl_.get());
2309
  }
2310
2311
672
  if (x509_verify_error == X509_V_OK)
2312
438
    return args.GetReturnValue().SetNull();
2313
2314
453
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2315
453
  const char* code = reason;
2316
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2317







453
  switch (x509_verify_error) {
2318
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2319
1
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2320
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2321
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2322
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2323
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2324
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2325
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2326
35
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2327
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2328
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2329
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2330
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2331
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2332
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2333
    CASE_X509_ERR(OUT_OF_MEM)
2334
255
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2335
12
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2336
4
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2337
143
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2338
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2339
1
    CASE_X509_ERR(CERT_REVOKED)
2340
    CASE_X509_ERR(INVALID_CA)
2341
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2342
1
    CASE_X509_ERR(INVALID_PURPOSE)
2343
    CASE_X509_ERR(CERT_UNTRUSTED)
2344
    CASE_X509_ERR(CERT_REJECTED)
2345
  }
2346
#undef CASE_X509_ERR
2347
2348
453
  Isolate* isolate = args.GetIsolate();
2349
453
  Local<String> reason_string = OneByteString(isolate, reason);
2350
453
  Local<Value> exception_value = Exception::Error(reason_string);
2351
  Local<Object> exception_object =
2352
1359
    exception_value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2353
2265
  exception_object->Set(w->env()->context(), w->env()->code_string(),
2354
                        OneByteString(isolate, code)).FromJust();
2355
906
  args.GetReturnValue().Set(exception_object);
2356
}
2357
2358
2359
template <class Base>
2360
29
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
2361
  Base* w;
2362
29
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2363
29
  Environment* env = w->ssl_env();
2364
29
  Local<Context> context = env->context();
2365
2366
29
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get());
2367
29
  if (c == nullptr)
2368
    return;
2369
2370
29
  Local<Object> info = Object::New(env->isolate());
2371
29
  const char* cipher_name = SSL_CIPHER_get_name(c);
2372
  info->Set(context, env->name_string(),
2373
116
            OneByteString(args.GetIsolate(), cipher_name)).FromJust();
2374
  info->Set(context, env->version_string(),
2375
116
            OneByteString(args.GetIsolate(), "TLSv1/SSLv3")).FromJust();
2376
58
  args.GetReturnValue().Set(info);
2377
}
2378
2379
2380
template <class Base>
2381
166
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2382
  Base* w;
2383
332
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2384
2385
166
  const char* tls_version = SSL_get_version(w->ssl_.get());
2386
498
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2387
}
2388
2389
2390
template <class Base>
2391
23
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2392
                                      const unsigned char** out,
2393
                                      unsigned char* outlen,
2394
                                      const unsigned char* in,
2395
                                      unsigned int inlen,
2396
                                      void* arg) {
2397
23
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2398
23
  Environment* env = w->env();
2399
23
  HandleScope handle_scope(env->isolate());
2400
23
  Context::Scope context_scope(env->context());
2401
2402
  Local<Value> alpn_buffer =
2403
23
      w->object()->GetPrivate(
2404
          env->context(),
2405
92
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2406
23
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
2407
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2408
23
                                     alpn_protos.data(), alpn_protos.length(),
2409
23
                                     in, inlen);
2410
  // According to 3.2. Protocol Selection of RFC7301, fatal
2411
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2412
  // support it yet. See
2413
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2414
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2415
46
                                          : SSL_TLSEXT_ERR_NOACK;
2416
}
2417
2418
2419
template <class Base>
2420
1254
void SSLWrap<Base>::GetALPNNegotiatedProto(
2421
    const FunctionCallbackInfo<Value>& args) {
2422
  Base* w;
2423
2466
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2424
2425
  const unsigned char* alpn_proto;
2426
  unsigned int alpn_proto_len;
2427
2428
1254
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2429
2430
1254
  if (!alpn_proto)
2431
2424
    return args.GetReturnValue().Set(false);
2432
2433
  args.GetReturnValue().Set(
2434
168
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2435
}
2436
2437
2438
template <class Base>
2439
193
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2440
  Base* w;
2441
193
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2442
193
  Environment* env = w->env();
2443

386
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2444
    return env->ThrowTypeError("Must give a Buffer as first argument");
2445
2446
193
  if (w->is_client()) {
2447
28
    ArrayBufferViewContents<unsigned char> alpn_protos(args[0]);
2448
    int r = SSL_set_alpn_protos(
2449
28
        w->ssl_.get(), alpn_protos.data(), alpn_protos.length());
2450
28
    CHECK_EQ(r, 0);
2451
  } else {
2452
495
    CHECK(
2453
        w->object()->SetPrivate(
2454
            env->context(),
2455
            env->alpn_buffer_private_symbol(),
2456
            args[0]).FromJust());
2457
    // Server should select ALPN protocol from list of advertised by client
2458
330
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2459
                               SelectALPNCallback,
2460
165
                               nullptr);
2461
  }
2462
}
2463
2464
2465
template <class Base>
2466
8
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2467
8
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2468
8
  Environment* env = w->env();
2469
8
  HandleScope handle_scope(env->isolate());
2470
2471
8
  if (w->is_client()) {
2472
    // Incoming response
2473
    const unsigned char* resp;
2474
4
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2475
    Local<Value> arg;
2476
4
    if (resp == nullptr) {
2477
4
      arg = Null(env->isolate());
2478
    } else {
2479
4
      arg =
2480
2
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2481
          .ToLocalChecked();
2482
    }
2483
2484
4
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2485
2486
    // Somehow, client is expecting different return value here
2487
4
    return 1;
2488
  } else {
2489
    // Outgoing response
2490
8
    if (w->ocsp_response_.IsEmpty())
2491
2
      return SSL_TLSEXT_ERR_NOACK;
2492
2493
    Local<ArrayBufferView> obj = PersistentToLocal::Default(env->isolate(),
2494
2
                                                            w->ocsp_response_);
2495
2
    size_t len = obj->ByteLength();
2496
2497
    // OpenSSL takes control of the pointer after accepting it
2498
2
    unsigned char* data = MallocOpenSSL<unsigned char>(len);
2499
2
    obj->CopyContents(data, len);
2500
2501
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2502
      OPENSSL_free(data);
2503
2
    w->ocsp_response_.Reset();
2504
2505
2
    return SSL_TLSEXT_ERR_OK;
2506
8
  }
2507
}
2508
2509
2510
template <class Base>
2511
20
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2512
20
  cert_cb_ = cb;
2513
20
  cert_cb_arg_ = arg;
2514
20
}
2515
2516
2517
template <class Base>
2518
689
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2519
689
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2520
2521
689
  if (!w->is_server())
2522
41
    return 1;
2523
2524
648
  if (!w->is_waiting_cert_cb())
2525
628
    return 1;
2526
2527
20
  if (w->cert_cb_running_)
2528
    return -1;
2529
2530
20
  Environment* env = w->env();
2531
20
  Local<Context> context = env->context();
2532
20
  HandleScope handle_scope(env->isolate());
2533
  Context::Scope context_scope(context);
2534
20
  w->cert_cb_running_ = true;
2535
2536
20
  Local<Object> info = Object::New(env->isolate());
2537
2538
20
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2539
20
  if (servername == nullptr) {
2540
    info->Set(context,
2541
              env->servername_string(),
2542
16
              String::Empty(env->isolate())).FromJust();
2543
  } else {
2544
    Local<String> str = OneByteString(env->isolate(), servername,
2545
16
                                      strlen(servername));
2546
48
    info->Set(context, env->servername_string(), str).FromJust();
2547
  }
2548
2549
20
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
2550
  info->Set(context, env->ocsp_request_string(),
2551
80
            Boolean::New(env->isolate(), ocsp)).FromJust();
2552
2553
40
  Local<Value> argv[] = { info };
2554
20
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2555
2556
20
  if (!w->cert_cb_running_)
2557
9
    return 1;
2558
2559
  // Performing async action, wait...
2560
31
  return -1;
2561
}
2562
2563
2564
template <class Base>
2565
18
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2566
  Base* w;
2567
20
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2568
18
  Environment* env = w->env();
2569
2570

18
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2571
2572
18
  Local<Object> object = w->object();
2573
  Local<Value> ctx = object->Get(env->context(),
2574
72
                                 env->sni_context_string()).ToLocalChecked();
2575
18
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2576
2577
  // Not an object, probably undefined or null
2578
18
  if (!ctx->IsObject())
2579
8
    goto fire_cb;
2580
2581
10
  if (cons->HasInstance(ctx)) {
2582
    SecureContext* sc;
2583
10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2584
9
    w->sni_context_.Reset(env->isolate(), ctx);
2585
2586
    int rv;
2587
2588
    // NOTE: reference count is not increased by this API methods
2589
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_.get());
2590
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_.get());
2591
    STACK_OF(X509)* chain;
2592
2593
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_.get(), &chain);
2594
9
    if (rv)
2595
9
      rv = SSL_use_certificate(w->ssl_.get(), x509);
2596
9
    if (rv)
2597
8
      rv = SSL_use_PrivateKey(w->ssl_.get(), pkey);
2598

9
    if (rv && chain != nullptr)
2599
1
      rv = SSL_set1_chain(w->ssl_.get(), chain);
2600
9
    if (rv)
2601
8
      rv = w->SetCACerts(sc);
2602
9
    if (!rv) {
2603
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2604
1
      if (!err)
2605
        return env->ThrowError("CertCbDone");
2606
1
      return ThrowCryptoError(env, err);
2607
    }
2608
  } else {
2609
    // Failure: incorrect SNI context object
2610
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2611
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2612
1
    return;
2613
  }
2614
2615
 fire_cb:
2616
  CertCb cb;
2617
  void* arg;
2618
2619
16
  cb = w->cert_cb_;
2620
16
  arg = w->cert_cb_arg_;
2621
2622
16
  w->cert_cb_running_ = false;
2623
16
  w->cert_cb_ = nullptr;
2624
16
  w->cert_cb_arg_ = nullptr;
2625
2626
16
  cb(arg);
2627
}
2628
2629
2630
template <class Base>
2631
23217
void SSLWrap<Base>::DestroySSL() {
2632
23217
  if (!ssl_)
2633
34742
    return;
2634
2635
11692
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2636
11692
  ssl_.reset();
2637
}
2638
2639
2640
template <class Base>
2641
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2642
  ConfigureSecureContext(sc);
2643
  CHECK_EQ(SSL_set_SSL_CTX(ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
2644
2645
  SetCACerts(sc);
2646
}
2647
2648
2649
template <class Base>
2650
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2651
8
  int err = SSL_set1_verify_cert_store(ssl_.get(),
2652
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
2653
8
  if (err != 1)
2654
    return err;
2655
2656
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2657
8
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
2658
2659
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2660
8
  SSL_set_client_CA_list(ssl_.get(), list);
2661
8
  return 1;
2662
}
2663
2664
1406
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2665
  // From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
2666
  //
2667
  //   If VerifyCallback returns 1, the verification process is continued. If
2668
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
2669
  //   terminated with respect to verification failures and the connection will
2670
  //   be established. The calling process can however retrieve the error code
2671
  //   of the last verification error using SSL_get_verify_result(3) or by
2672
  //   maintaining its own error storage managed by VerifyCallback.
2673
  //
2674
  // Since we cannot perform I/O quickly enough with X509_STORE_CTX_ APIs in
2675
  // this callback, we ignore all preverify_ok errors and let the handshake
2676
  // continue. It is imperative that the user use Connection::VerifyError after
2677
  // the 'secure' callback has been made.
2678
1406
  return 1;
2679
}
2680
2681
3369
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
2682
3369
  const int mode = EVP_CIPHER_mode(cipher);
2683
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
2684
  // but its mode is 0 which doesn't indicate
2685
6696
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
2686
6113
         mode == EVP_CIPH_CCM_MODE ||
2687

7494
         mode == EVP_CIPH_GCM_MODE ||
2688
4708
         IS_OCB_MODE(mode);
2689
}
2690
2691
1468
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
2692
1468
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
2693
1468
  return IsSupportedAuthenticatedMode(cipher);
2694
}
2695
2696
enum class ParsePublicKeyResult {
2697
  kParsePublicOk,
2698
  kParsePublicNotRecognized,
2699
  kParsePublicFailed
2700
};
2701
2702
702
static ParsePublicKeyResult TryParsePublicKey(
2703
    EVPKeyPointer* pkey,
2704
    const BIOPointer& bp,
2705
    const char* name,
2706
    // NOLINTNEXTLINE(runtime/int)
2707
    const std::function<EVP_PKEY*(const unsigned char** p, long l)>& parse) {
2708
  unsigned char* der_data;
2709
  long der_len;  // NOLINT(runtime/int)
2710
2711
  // This skips surrounding data and decodes PEM to DER.
2712
  {
2713
702
    MarkPopErrorOnReturn mark_pop_error_on_return;
2714
702
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
2715
702
                           bp.get(), nullptr, nullptr) != 1)
2716
491
      return ParsePublicKeyResult::kParsePublicNotRecognized;
2717
  }
2718
2719
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
2720
211
  const unsigned char* p = der_data;
2721
211
  pkey->reset(parse(&p, der_len));
2722
211
  OPENSSL_clear_free(der_data, der_len);
2723
2724
  return *pkey ? ParsePublicKeyResult::kParsePublicOk :
2725
211
                 ParsePublicKeyResult::kParsePublicFailed;
2726
}
2727
2728
257
static ParsePublicKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
2729
                                              const char* key_pem,
2730
                                              int key_pem_len) {
2731
257
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
2732
257
  if (!bp)
2733
    return ParsePublicKeyResult::kParsePublicFailed;
2734
2735
  ParsePublicKeyResult ret;
2736
2737
  // Try parsing as a SubjectPublicKeyInfo first.
2738
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
2739
30
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2740
        return d2i_PUBKEY(nullptr, p, l);
2741
287
      });
2742
257
  if (ret != ParsePublicKeyResult::kParsePublicNotRecognized)
2743
30
    return ret;
2744
2745
  // Maybe it is PKCS#1.
2746
227
  CHECK(BIO_reset(bp.get()));
2747
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
2748
9
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2749
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
2750
236
      });
2751
227
  if (ret != ParsePublicKeyResult::kParsePublicNotRecognized)
2752
9
    return ret;
2753
2754
  // X.509 fallback.
2755
218
  CHECK(BIO_reset(bp.get()));
2756
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
2757
172
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2758
172
        X509Pointer x509(d2i_X509(nullptr, p, l));
2759
344
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
2760
390
      });
2761
}
2762
2763
9
static bool ParsePublicKey(EVPKeyPointer* pkey,
2764
                           const PublicKeyEncodingConfig& config,
2765
                           const char* key,
2766
                           size_t key_len) {
2767
9
  if (config.format_ == kKeyFormatPEM) {
2768
    ParsePublicKeyResult r =
2769
        ParsePublicKeyPEM(pkey, key, key_len);
2770
    return r == ParsePublicKeyResult::kParsePublicOk;
2771
  } else {
2772
9
    CHECK_EQ(config.format_, kKeyFormatDER);
2773
9
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2774
18
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2775
9
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2776
9
      return pkey;
2777
    } else {
2778
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2779
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
2780
      return pkey;
2781
    }
2782
  }
2783
}
2784
2785
28
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
2786
                                               BIO* bio,
2787
                                               PKFormatType format) {
2788
  BUF_MEM* bptr;
2789
28
  BIO_get_mem_ptr(bio, &bptr);
2790
28
  if (format == kKeyFormatPEM) {
2791
    // PEM is an ASCII format, so we will return it as a string.
2792
    return String::NewFromUtf8(env->isolate(), bptr->data,
2793
                               NewStringType::kNormal,
2794
38
                               bptr->length).ToLocalChecked();
2795
  } else {
2796
9
    CHECK_EQ(format, kKeyFormatDER);
2797
    // DER is binary, return it as a buffer.
2798
18
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
2799
  }
2800
}
2801
2802
14
static bool WritePublicKeyInner(EVP_PKEY* pkey,
2803
                                const BIOPointer& bio,
2804
                                const PublicKeyEncodingConfig& config) {
2805
28
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2806
    // PKCS#1 is only valid for RSA keys.
2807
8
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
2808
8
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
2809
8
    if (config.format_ == kKeyFormatPEM) {
2810
      // Encode PKCS#1 as PEM.
2811
3
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
2812
    } else {
2813
      // Encode PKCS#1 as DER.
2814
5
      CHECK_EQ(config.format_, kKeyFormatDER);
2815
5
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
2816
8
    }
2817
  } else {
2818
12
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2819
6
    if (config.format_ == kKeyFormatPEM) {
2820
      // Encode SPKI as PEM.
2821
6
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
2822
    } else {
2823
      // Encode SPKI as DER.
2824
      CHECK_EQ(config.format_, kKeyFormatDER);
2825
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
2826
    }
2827
  }
2828
}
2829
2830
14
static MaybeLocal<Value> WritePublicKey(Environment* env,
2831
                                        EVP_PKEY* pkey,
2832
                                        const PublicKeyEncodingConfig& config) {
2833
14
  BIOPointer bio(BIO_new(BIO_s_mem()));
2834
14
  CHECK(bio);
2835
2836
14
  if (!WritePublicKeyInner(pkey, bio, config)) {
2837
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
2838
    return MaybeLocal<Value>();
2839
  }
2840
28
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
2841
}
2842
2843
28
static bool IsASN1Sequence(const unsigned char* data, size_t size,
2844
                           size_t* data_offset, size_t* data_size) {
2845

28
  if (size < 2 || data[0] != 0x30)
2846
    return false;
2847
2848
28
  if (data[1] & 0x80) {
2849
    // Long form.
2850
20
    size_t n_bytes = data[1] & ~0x80;
2851

20
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
2852
      return false;
2853
20
    size_t length = 0;
2854
59
    for (size_t i = 0; i < n_bytes; i++)
2855
39
      length = (length << 8) | data[i + 2];
2856
20
    *data_offset = 2 + n_bytes;
2857
20
    *data_size = std::min(size - 2 - n_bytes, length);
2858
  } else {
2859
    // Short form.
2860
8
    *data_offset = 2;
2861
8
    *data_size = std::min<size_t>(size - 2, data[1]);
2862
  }
2863
2864
28
  return true;
2865
}
2866
2867
14
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
2868
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
2869
  size_t offset, len;
2870
14
  if (!IsASN1Sequence(data, size, &offset, &len))
2871
    return false;
2872
2873
  // An RSAPrivateKey sequence always starts with a single-byte integer whose
2874
  // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
2875
  // (which is the product of two primes and therefore at least 4), so we can
2876
  // decide the type of the structure based on the first three bytes of the
2877
  // sequence.
2878
28
  return len >= 3 &&
2879
28
         data[offset] == 2 &&
2880

33
         data[offset + 1] == 1 &&
2881
19
         !(data[offset + 2] & 0xfe);
2882
}
2883
2884
14
static bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
2885
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
2886
  size_t offset, len;
2887
14
  if (!IsASN1Sequence(data, size, &offset, &len))
2888
    return false;
2889
2890
  // A PrivateKeyInfo sequence always starts with an integer whereas an
2891
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
2892

28
  return len >= 1 &&
2893
28
         data[offset] != 2;
2894
}
2895
2896
123
static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,
2897
                                     const char* key,
2898
                                     size_t key_len) {
2899
123
  EVPKeyPointer pkey;
2900
2901
123
  if (config.format_ == kKeyFormatPEM) {
2902
104
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
2903
104
    if (!bio)
2904
1
      return pkey;
2905
2906
103
    char* pass = const_cast<char*>(config.passphrase_.get());
2907
    pkey.reset(PEM_read_bio_PrivateKey(bio.get(),
2908
                                       nullptr,
2909
                                       PasswordCallback,
2910
103
                                       pass));
2911
  } else {
2912
19
    CHECK_EQ(config.format_, kKeyFormatDER);
2913
2914
38
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2915
5
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2916
5
      pkey.reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2917
28
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
2918
14
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
2919
14
      if (!bio)
2920
        return pkey;
2921
2922
14
      if (IsEncryptedPrivateKeyInfo(
2923
              reinterpret_cast<const unsigned char*>(key), key_len)) {
2924
9
        char* pass = const_cast<char*>(config.passphrase_.get());
2925
        pkey.reset(d2i_PKCS8PrivateKey_bio(bio.get(),
2926
                                           nullptr,
2927
                                           PasswordCallback,
2928
9
                                           pass));
2929
      } else {
2930
5
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
2931
5
        if (p8inf)
2932
5
          pkey.reset(EVP_PKCS82PKEY(p8inf.get()));
2933
14
      }
2934
    } else {
2935
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
2936
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2937
      pkey.reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
2938
    }
2939
  }
2940
2941
  // OpenSSL can fail to parse the key but still return a non-null pointer.
2942
122
  if (ERR_peek_error() != 0)
2943
11
    pkey.reset();
2944
2945
122
  return pkey;
2946
}
2947
2948
654
ByteSource::ByteSource(ByteSource&& other)
2949
      : data_(other.data_),
2950
        allocated_data_(other.allocated_data_),
2951
654
        size_(other.size_) {
2952
654
  other.allocated_data_ = nullptr;
2953
654
}
2954
2955
2719
ByteSource::~ByteSource() {
2956
2719
  OPENSSL_clear_free(allocated_data_, size_);
2957
2719
}
2958
2959
39
ByteSource& ByteSource::operator=(ByteSource&& other) {
2960
39
  if (&other != this) {
2961
39
    OPENSSL_clear_free(allocated_data_, size_);
2962
39
    data_ = other.data_;
2963
39
    allocated_data_ = other.allocated_data_;
2964
39
    other.allocated_data_ = nullptr;
2965
39
    size_ = other.size_;
2966
  }
2967
39
  return *this;
2968
}
2969
2970
1850
const char* ByteSource::get() const {
2971
1850
  return data_;
2972
}
2973
2974
1738
size_t ByteSource::size() const {
2975
1738
  return size_;
2976
}
2977
2978
1651
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
2979
                                          Local<Value> value) {
2980
1651
  return Buffer::HasInstance(value) ? FromBuffer(value)
2981
2048
                                    : FromString(env, value.As<String>());
2982
}
2983
2984
432
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
2985
                                  bool ntc) {
2986
864
  CHECK(str->IsString());
2987
864
  size_t size = str->Utf8Length(env->isolate());
2988
432
  size_t alloc_size = ntc ? size + 1 : size;
2989
432
  char* data = MallocOpenSSL<char>(alloc_size);
2990
432
  int opts = String::NO_OPTIONS;
2991
432
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
2992
864
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
2993
432
  return Allocated(data, size);
2994
}
2995
2996
1258
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
2997
1258
  CHECK(buffer->IsArrayBufferView());
2998
1258
  Local<ArrayBufferView> abv = buffer.As<ArrayBufferView>();
2999
1258
  size_t size = abv->ByteLength();
3000
1258
  if (ntc) {
3001
4
    char* data = MallocOpenSSL<char>(size + 1);
3002
4
    abv->CopyContents(data, size);
3003
4
    data[size] = 0;
3004
4
    return Allocated(data, size);
3005
  }
3006
1254
  return Foreign(Buffer::Data(buffer), size);
3007
}
3008
3009
39
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
3010
                                          Local<Value> value) {
3011
39
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
3012
74
                                    : FromString(env, value.As<String>(), true);
3013
}
3014
3015
14
ByteSource ByteSource::FromSymmetricKeyObject(Local<Value> handle) {
3016
14
  CHECK(handle->IsObject());
3017
14
  KeyObject* key = Unwrap<KeyObject>(handle.As<Object>());
3018
14
  CHECK(key);
3019
14
  return Foreign(key->GetSymmetricKey(), key->GetSymmetricKeySize());
3020
}
3021
3022
1704
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
3023
      : data_(data),
3024
        allocated_data_(allocated_data),
3025
1704
        size_(size) {}
3026
3027
436
ByteSource ByteSource::Allocated(char* data, size_t size) {
3028
436
  return ByteSource(data, data, size);
3029
}
3030
3031
1268
ByteSource ByteSource::Foreign(const char* data, size_t size) {
3032
1268
  return ByteSource(data, nullptr, size);
3033
}
3034
3035
enum KeyEncodingContext {
3036
  kKeyContextInput,
3037
  kKeyContextExport,
3038
  kKeyContextGenerate
3039
};
3040
3041
377
static void GetKeyFormatAndTypeFromJs(
3042
    AsymmetricKeyEncodingConfig* config,
3043
    const FunctionCallbackInfo<Value>& args,
3044
    unsigned int* offset,
3045
    KeyEncodingContext context) {
3046
  // During key pair generation, it is possible not to specify a key encoding,
3047
  // which will lead to a key object being returned.
3048
1508
  if (args[*offset]->IsUndefined()) {
3049
4
    CHECK_EQ(context, kKeyContextGenerate);
3050
16
    CHECK(args[*offset + 1]->IsUndefined());
3051
4
    config->output_key_object_ = true;
3052
  } else {
3053
373
    config->output_key_object_ = false;
3054
3055
1119
    CHECK(args[*offset]->IsInt32());
3056
    config->format_ = static_cast<PKFormatType>(
3057
1492
        args[*offset].As<Int32>()->Value());
3058
3059
1119
    if (args[*offset + 1]->IsInt32()) {
3060
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
3061
232
          args[*offset + 1].As<Int32>()->Value()));
3062
    } else {
3063

315
      CHECK(context == kKeyContextInput && config->format_ == kKeyFormatPEM);
3064
1260
      CHECK(args[*offset + 1]->IsNullOrUndefined());
3065
315
      config->type_ = Nothing<PKEncodingType>();
3066
    }
3067
  }
3068
3069
377
  *offset += 2;
3070
377
}
3071
3072
17
static PublicKeyEncodingConfig GetPublicKeyEncodingFromJs(
3073
    const FunctionCallbackInfo<Value>& args,
3074
    unsigned int* offset,
3075
    KeyEncodingContext context) {
3076
17
  PublicKeyEncodingConfig result;
3077
17
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3078
17
  return result;
3079
}
3080
3081
360
static NonCopyableMaybe<PrivateKeyEncodingConfig> GetPrivateKeyEncodingFromJs(
3082
    const FunctionCallbackInfo<Value>& args,
3083
    unsigned int* offset,
3084
    KeyEncodingContext context) {
3085
360
  Environment* env = Environment::GetCurrent(args);
3086
3087
360
  PrivateKeyEncodingConfig result;
3088
360
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3089
3090
360
  if (result.output_key_object_) {
3091
2
    if (context != kKeyContextInput)
3092
2
      (*offset)++;
3093
  } else {
3094
358
    bool needs_passphrase = false;
3095
358
    if (context != kKeyContextInput) {
3096
60
      if (args[*offset]->IsString()) {
3097
        String::Utf8Value cipher_name(env->isolate(),
3098
18
                                      args[*offset].As<String>());
3099
6
        result.cipher_ = EVP_get_cipherbyname(*cipher_name);
3100
6
        if (result.cipher_ == nullptr) {
3101
1
          env->ThrowError("Unknown cipher");
3102
1
          return NonCopyableMaybe<PrivateKeyEncodingConfig>();
3103
        }
3104
5
        needs_passphrase = true;
3105
      } else {
3106
36
        CHECK(args[*offset]->IsNullOrUndefined());
3107
9
        result.cipher_ = nullptr;
3108
      }
3109
14
      (*offset)++;
3110
    }
3111
3112


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

39
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
3114
3115
78
      result.passphrase_ = ByteSource::NullTerminatedCopy(env, args[*offset]);
3116
    } else {
3117


1272
      CHECK(args[*offset]->IsNullOrUndefined() && !needs_passphrase);
3118
    }
3119
  }
3120
3121
359
  (*offset)++;
3122
359
  return NonCopyableMaybe<PrivateKeyEncodingConfig>(std::move(result));
3123
}
3124
3125
64
static ManagedEVPPKey GetPrivateKeyFromJs(
3126
    const FunctionCallbackInfo<Value>& args,
3127
    unsigned int* offset,
3128
    bool allow_key_object) {
3129


268
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3130
63
    Environment* env = Environment::GetCurrent(args);
3131
126
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3132
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3133
126
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3134
63
    if (config.IsEmpty())
3135
      return ManagedEVPPKey();
3136
    EVPKeyPointer pkey =
3137
126
        ParsePrivateKey(config.Release(), key.get(), key.size());
3138
63
    if (!pkey)
3139
9
      ThrowCryptoError(env, ERR_get_error(), "Failed to read private key");
3140
126
    return ManagedEVPPKey(pkey.release());
3141
  } else {
3142


3
    CHECK(args[*offset]->IsObject() && allow_key_object);
3143
    KeyObject* key;
3144
3
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
3145
1
    CHECK_EQ(key->GetKeyType(), kKeyTypePrivate);
3146
1
    (*offset) += 4;
3147
1
    return key->GetAsymmetricKey();
3148
  }
3149
}
3150
3151
292
static ManagedEVPPKey GetPublicOrPrivateKeyFromJs(
3152
    const FunctionCallbackInfo<Value>& args,
3153
    unsigned int* offset,
3154
    bool allow_key_object) {
3155


1210
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3156
280
    Environment* env = Environment::GetCurrent(args);
3157
560
    ByteSource data = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3158
    NonCopyableMaybe<PrivateKeyEncodingConfig> config_ =
3159
560
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3160
280
    if (config_.IsEmpty())
3161
      return ManagedEVPPKey();
3162
560
    PrivateKeyEncodingConfig config = config_.Release();
3163
560
    EVPKeyPointer pkey;
3164
280
    if (config.format_ == kKeyFormatPEM) {
3165
      // For PEM, we can easily determine whether it is a public or private key
3166
      // by looking for the respective PEM tags.
3167
      ParsePublicKeyResult ret = ParsePublicKeyPEM(&pkey, data.get(),
3168
257
                                                   data.size());
3169
257
      if (ret == ParsePublicKeyResult::kParsePublicNotRecognized) {
3170
46
        pkey = ParsePrivateKey(config, data.get(), data.size());
3171
      }
3172
    } else {
3173
      // For DER, the type determines how to parse it. SPKI, PKCS#8 and SEC1 are
3174
      // easy, but PKCS#1 can be a public key or a private key.
3175
      bool is_public;
3176

23
      switch (config.type_.ToChecked()) {
3177
        case kKeyEncodingPKCS1:
3178
          is_public = !IsRSAPrivateKey(
3179
14
              reinterpret_cast<const unsigned char*>(data.get()), data.size());
3180
14
          break;
3181
        case kKeyEncodingSPKI:
3182
          is_public = true;
3183
          break;
3184
        case kKeyEncodingPKCS8:
3185
        case kKeyEncodingSEC1:
3186
9
          is_public = false;
3187
9
          break;
3188
        default:
3189
          CHECK(!"Invalid key encoding type");
3190
      }
3191
3192
23
      if (is_public) {
3193
9
        ParsePublicKey(&pkey, config, data.get(), data.size());
3194
      } else {
3195
14
        pkey = ParsePrivateKey(config, data.get(), data.size());
3196
      }
3197
    }
3198
280
    if (!pkey)
3199
3
      ThrowCryptoError(env, ERR_get_error(), "Failed to read asymmetric key");
3200
560
    return ManagedEVPPKey(pkey.release());
3201
  } else {
3202


36
    CHECK(args[*offset]->IsObject() && allow_key_object);
3203
36
    KeyObject* key = Unwrap<KeyObject>(args[*offset].As<Object>());
3204
12
    CHECK(key);
3205
12
    CHECK_NE(key->GetKeyType(), kKeyTypeSecret);
3206
12
    (*offset) += 4;
3207
12
    return key->GetAsymmetricKey();
3208
  }
3209
}
3210
3211
14
static MaybeLocal<Value> WritePrivateKey(
3212
    Environment* env,
3213
    EVP_PKEY* pkey,
3214
    const PrivateKeyEncodingConfig& config) {
3215
14
  BIOPointer bio(BIO_new(BIO_s_mem()));
3216
14
  CHECK(bio);
3217
3218
  bool err;
3219
3220
28
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3221
    // PKCS#1 is only permitted for RSA keys.
3222
5
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
3223
3224
5
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
3225
5
    if (config.format_ == kKeyFormatPEM) {
3226
      // Encode PKCS#1 as PEM.
3227
4
      const char* pass = config.passphrase_.get();
3228
      err = PEM_write_bio_RSAPrivateKey(
3229
                bio.get(), rsa.get(),
3230
                config.cipher_,
3231
                reinterpret_cast<unsigned char*>(const_cast<char*>(pass)),
3232
4
                config.passphrase_.size(),
3233
4
                nullptr, nullptr) != 1;
3234
    } else {
3235
      // Encode PKCS#1 as DER. This does not permit encryption.
3236
1
      CHECK_EQ(config.format_, kKeyFormatDER);
3237
1
      CHECK_NULL(config.cipher_);
3238
1
      err = i2d_RSAPrivateKey_bio(bio.get(), rsa.get()) != 1;
3239
5
    }
3240
18
  } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
3241
7
    if (config.format_ == kKeyFormatPEM) {
3242
      // Encode PKCS#8 as PEM.
3243
      err = PEM_write_bio_PKCS8PrivateKey(
3244
                bio.get(), pkey,
3245
                config.cipher_,
3246
4
                const_cast<char*>(config.passphrase_.get()),
3247
4
                config.passphrase_.size(),
3248
8
                nullptr, nullptr) != 1;
3249
    } else {
3250
      // Encode PKCS#8 as DER.
3251
3
      CHECK_EQ(config.format_, kKeyFormatDER);
3252
      err = i2d_PKCS8PrivateKey_bio(
3253
                bio.get(), pkey,
3254
                config.cipher_,
3255
3
                const_cast<char*>(config.passphrase_.get()),
3256
3
                config.passphrase_.size(),
3257
6
                nullptr, nullptr) != 1;
3258
    }
3259
  } else {
3260
4
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
3261
3262
    // SEC1 is only permitted for EC keys.
3263
2
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_EC);
3264
3265
2
    ECKeyPointer ec_key(EVP_PKEY_get1_EC_KEY(pkey));
3266
2
    if (config.format_ == kKeyFormatPEM) {
3267
      // Encode SEC1 as PEM.
3268
2
      const char* pass = config.passphrase_.get();
3269
      err = PEM_write_bio_ECPrivateKey(
3270
                bio.get(), ec_key.get(),
3271
                config.cipher_,
3272
                reinterpret_cast<unsigned char*>(const_cast<char*>(pass)),
3273
2
                config.passphrase_.size(),
3274
2
                nullptr, nullptr) != 1;
3275
    } else {
3276
      // Encode SEC1 as DER. This does not permit encryption.
3277
      CHECK_EQ(config.format_, kKeyFormatDER);
3278
      CHECK_NULL(config.cipher_);
3279
      err = i2d_ECPrivateKey_bio(bio.get(), ec_key.get()) != 1;
3280
2
    }
3281
  }
3282
3283
14
  if (err) {
3284
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode private key");
3285
    return MaybeLocal<Value>();
3286
  }
3287
28
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
3288
}
3289
3290
38
ManagedEVPPKey::ManagedEVPPKey() : pkey_(nullptr) {}
3291
3292
373
ManagedEVPPKey::ManagedEVPPKey(EVP_PKEY* pkey) : pkey_(pkey) {}
3293
3294
13
ManagedEVPPKey::ManagedEVPPKey(const ManagedEVPPKey& key) : pkey_(nullptr) {
3295
13
  *this = key;
3296
13
}
3297
3298
ManagedEVPPKey::ManagedEVPPKey(ManagedEVPPKey&& key) {
3299
  *this = key;
3300
}
3301
3302
424
ManagedEVPPKey::~ManagedEVPPKey() {
3303
424
  EVP_PKEY_free(pkey_);
3304
424
}
3305
3306
20
ManagedEVPPKey& ManagedEVPPKey::operator=(const ManagedEVPPKey& key) {
3307
20
  EVP_PKEY_free(pkey_);
3308
20
  pkey_ = key.pkey_;
3309
20
  EVP_PKEY_up_ref(pkey_);
3310
20
  return *this;
3311
}
3312
3313
19
ManagedEVPPKey& ManagedEVPPKey::operator=(ManagedEVPPKey&& key) {
3314
19
  EVP_PKEY_free(pkey_);
3315
19
  pkey_ = key.pkey_;
3316
19
  key.pkey_ = nullptr;
3317
19
  return *this;
3318
}
3319
3320
378
ManagedEVPPKey::operator bool() const {
3321
378
  return pkey_ != nullptr;
3322
}
3323
3324
721
EVP_PKEY* ManagedEVPPKey::get() const {
3325
721
  return pkey_;
3326
}
3327
3328
578
Local<Function> KeyObject::Initialize(Environment* env, Local<Object> target) {
3329
578
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3330
1156
  t->InstanceTemplate()->SetInternalFieldCount(1);
3331
3332
578
  env->SetProtoMethod(t, "init", Init);
3333
  env->SetProtoMethodNoSideEffect(t, "getSymmetricKeySize",
3334
578
                                  GetSymmetricKeySize);
3335
  env->SetProtoMethodNoSideEffect(t, "getAsymmetricKeyType",
3336
578
                                  GetAsymmetricKeyType);
3337
578
  env->SetProtoMethod(t, "export", Export);
3338
3339
1734
  auto function = t->GetFunction(env->context()).ToLocalChecked();
3340
  target->Set(env->context(),
3341
              FIXED_ONE_BYTE_STRING(env->isolate(), "KeyObject"),
3342
2312
              function).FromJust();
3343
3344
578
  return function;
3345
}
3346
3347
4
MaybeLocal<Object> KeyObject::Create(Environment* env,
3348
                                     KeyType key_type,
3349
                                     const ManagedEVPPKey& pkey) {
3350
4
  CHECK_NE(key_type, kKeyTypeSecret);
3351
4
  Local<Value> type = Integer::New(env->isolate(), key_type);
3352
  Local<Object> obj;
3353
8
  if (!env->crypto_key_object_constructor()
3354
12
           ->NewInstance(env->context(), 1, &type)
3355
12
           .ToLocal(&obj)) {
3356
    return MaybeLocal<Object>();
3357
  }
3358
3359
4
  KeyObject* key = Unwrap<KeyObject>(obj);
3360
4
  CHECK(key);
3361
4
  if (key_type == kKeyTypePublic)
3362
2
    key->InitPublic(pkey);
3363
  else
3364
2
    key->InitPrivate(pkey);
3365
4
  return obj;
3366
}
3367
3368
13
ManagedEVPPKey KeyObject::GetAsymmetricKey() const {
3369
13
  CHECK_NE(key_type_, kKeyTypeSecret);
3370
13
  return this->asymmetric_key_;
3371
}
3372
3373
14
const char* KeyObject::GetSymmetricKey() const {
3374
14
  CHECK_EQ(key_type_, kKeyTypeSecret);
3375
14
  return this->symmetric_key_.get();
3376
}
3377
3378
15
size_t KeyObject::GetSymmetricKeySize() const {
3379
15
  CHECK_EQ(key_type_, kKeyTypeSecret);
3380
15
  return this->symmetric_key_len_;
3381
}
3382
3383
21
void KeyObject::New(const FunctionCallbackInfo<Value>& args) {
3384
21
  CHECK(args.IsConstructCall());
3385
42
  CHECK(args[0]->IsInt32());
3386
63
  KeyType key_type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
3387
21
  Environment* env = Environment::GetCurrent(args);
3388
21
  new KeyObject(env, args.This(), key_type);
3389
21
}
3390
3391
13
KeyType KeyObject::GetKeyType() const {
3392
13
  return this->key_type_;
3393
}
3394
3395
17
void KeyObject::Init(const FunctionCallbackInfo<Value>& args) {
3396
  KeyObject* key;
3397
18
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3398
3399
  unsigned int offset;
3400
17
  ManagedEVPPKey pkey;
3401
3402

17
  switch (key->key_type_) {
3403
  case kKeyTypeSecret:
3404
13
    CHECK_EQ(args.Length(), 1);
3405
26
    CHECK(args[0]->IsArrayBufferView());
3406
26
    key->InitSecret(args[0].As<ArrayBufferView>());
3407
13
    break;
3408
  case kKeyTypePublic:
3409
2
    CHECK_EQ(args.Length(), 3);
3410
3411
2
    offset = 0;
3412
2
    pkey = GetPublicOrPrivateKeyFromJs(args, &offset, false);
3413
2
    if (!pkey)
3414
      return;
3415
2
    key->InitPublic(pkey);
3416
2
    break;
3417
  case kKeyTypePrivate:
3418
2
    CHECK_EQ(args.Length(), 4);
3419
3420
2
    offset = 0;
3421
2
    pkey = GetPrivateKeyFromJs(args, &offset, false);
3422
2
    if (!pkey)
3423
1
      return;
3424
1
    key->InitPrivate(pkey);
3425
1
    break;
3426
  default:
3427
    CHECK(false);
3428
16
  }
3429
}
3430
3431
13
void KeyObject::InitSecret(v8::Local<v8::ArrayBufferView> abv) {
3432
13
  CHECK_EQ(this->key_type_, kKeyTypeSecret);
3433
3434
13
  size_t key_len = abv->ByteLength();
3435
13
  char* mem = MallocOpenSSL<char>(key_len);
3436
13
  abv->CopyContents(mem, key_len);
3437
26
  this->symmetric_key_ = std::unique_ptr<char, std::function<void(char*)>>(mem,
3438
13
      [key_len](char* p) {
3439
13
        OPENSSL_clear_free(p, key_len);
3440
26
      });
3441
13
  this->symmetric_key_len_ = key_len;
3442
13
}
3443
3444
4
void KeyObject::InitPublic(const ManagedEVPPKey& pkey) {
3445
4
  CHECK_EQ(this->key_type_, kKeyTypePublic);
3446
4
  CHECK(pkey);
3447
4
  this->asymmetric_key_ = pkey;
3448
4
}
3449
3450
3
void KeyObject::InitPrivate(const ManagedEVPPKey& pkey) {
3451