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

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

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



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

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

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


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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

1785
    if (RAND_bytes(iv, 16) <= 0 ||
1394
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1395

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

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

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1430
6
  Environment* env = wrap->env();
1431
  X509* cert;
1432
1433
  if (primary)
1434
3
    cert = wrap->cert_.get();
1435
  else
1436
3
    cert = wrap->issuer_.get();
1437

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

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

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


225
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
1969
3
    goto done;
1970
1971
  // Short result requested.
1972


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

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2121
10
    ssize_t slen = Buffer::Length(args[0]);
2122
10
    char* sbuf = Buffer::Data(args[0]);
2123
2124
10
    const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
2125
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
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<Object>());
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
  CHECK(Buffer::HasInstance(alpn_buffer));
2407
  const unsigned char* alpn_protos =
2408
23
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2409
23
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2410
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2411
23
                                     alpn_protos, alpn_protos_len, in, inlen);
2412
  // According to 3.2. Protocol Selection of RFC7301, fatal
2413
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2414
  // support it yet. See
2415
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2416
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2417
46
                                          : SSL_TLSEXT_ERR_NOACK;
2418
}
2419
2420
2421
template <class Base>
2422
1253
void SSLWrap<Base>::GetALPNNegotiatedProto(
2423
    const FunctionCallbackInfo<Value>& args) {
2424
  Base* w;
2425
2464
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2426
2427
  const unsigned char* alpn_proto;
2428
  unsigned int alpn_proto_len;
2429
2430
1253
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2431
2432
1253
  if (!alpn_proto)
2433
2422
    return args.GetReturnValue().Set(false);
2434
2435
  args.GetReturnValue().Set(
2436
168
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2437
}
2438
2439
2440
template <class Base>
2441
192
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2442
  Base* w;
2443
192
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2444
192
  Environment* env = w->env();
2445

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

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

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

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

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

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

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

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

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


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

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


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


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


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


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

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


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

17
  switch (key->key_type_) {
3405
  case kKeyTypeSecret:
3406
13
    CHECK_EQ(args.Length(), 1);
3407
26
    key->InitSecret(Buffer::Data(args[0]), Buffer::Length(args[0]));
3408
13
    break;
3409
  case kKeyTypePublic:
3410
2
    CHECK_EQ(args.Length(), 3);
3411
3412
2
    offset = 0;
3413
2
    pkey = GetPublicOrPrivateKeyFromJs(args, &offset, false);
3414
2
    if (!pkey)
3415
      return;
3416
2
    key->InitPublic(pkey);
3417
2
    break;
3418
  case kKeyTypePrivate:
3419
2
    CHECK_EQ(args.Length(), 4);
3420
3421
2
    offset = 0;
3422
2
    pkey = GetPrivateKeyFromJs(args, &offset, false);
3423
2
    if (!pkey)
3424
1
      return;
3425
1
    key->InitPrivate(pkey);
3426
1
    break;
3427
  default:
3428
    CHECK(false);
3429
16
  }
3430
}
3431
3432
13
void KeyObject::InitSecret(const char* key, size_t key_len) {
3433
13
  CHECK_EQ(this->key_type_, kKeyTypeSecret);
3434
3435
13
  char* mem = MallocOpenSSL<char>(key_len);
3436
13
  memcpy(mem, key, 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