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: 2941 3234 90.9 %
Date: 2019-02-23 22:23:05 Branches: 1494 2299 65.0 %

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

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

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



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

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

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


2150
    if (args[1]->IsUndefined() || args[1]->IsNull())
576
492
      len = 1;
577
    else
578
78
      THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase");
579
  }
580
581
516
  BIOPointer bio(LoadBIO(env, args[0]));
582
516
  if (!bio)
583
    return;
584
585
1024
  node::Utf8Value passphrase(env->isolate(), args[1]);
586
587
  EVPKeyPointer key(
588
      PEM_read_bio_PrivateKey(bio.get(),
589
                              nullptr,
590
                              PasswordCallback,
591

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1439
6
  Environment* env = wrap->env();
1440
  X509* cert;
1441
1442
  if (primary)
1443
3
    cert = wrap->cert_.get();
1444
  else
1445
3
    cert = wrap->issuer_.get();
1446

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

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

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


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


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

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


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







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

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

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

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

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

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

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

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

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

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


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

39
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
3120
3121
78
      result.passphrase_ = ByteSource::NullTerminatedCopy(env, args[*offset]);
3122
    } else {
3123


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


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


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


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

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


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

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