GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/node_crypto.cc Lines: 2936 3234 90.8 %
Date: 2019-01-07 12:15:22 Branches: 1473 2283 64.5 %

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.h"
23
#include "node_buffer.h"
24
#include "node_errors.h"
25
#include "node_constants.h"
26
#include "node_crypto.h"
27
#include "node_crypto_bio.h"
28
#include "node_crypto_groups.h"
29
#include "node_crypto_clienthello-inl.h"
30
#include "node_mutex.h"
31
#include "node_internals.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
34
v8::MaybeLocal<v8::Object> New(Environment* env, unsigned char* udata,
58
                               size_t length) {
59
34
  char* data = reinterpret_cast<char*>(udata);
60
34
  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
692
  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
15
  void operator()(STACK_OF(ASN1_OBJECT)* p) const {
114
15
    sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
115
15
  }
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
513
  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
38
static int PasswordCallback(char* buf, int size, int rwflag, void* u) {
165
38
  if (u) {
166
31
    size_t buflen = static_cast<size_t>(size);
167
31
    size_t len = strlen(static_cast<const char*>(u));
168
31
    len = len > buflen ? buflen : len;
169
31
    memcpy(buf, u, len);
170
31
    return len;
171
  }
172
173
7
  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
342
struct CryptoErrorVector : public std::vector<std::string> {
223
56
  inline void Capture() {
224
56
    clear();
225
111
    while (auto err = ERR_get_error()) {
226
      char buf[256];
227
55
      ERR_error_string_n(err, buf, sizeof(buf));
228
55
      push_back(buf);
229
    }
230
55
    std::reverse(begin(), end());
231
56
  }
232
233
60
  inline Local<Value> ToException(
234
      Environment* env,
235
      Local<String> exception_string = Local<String>()) const {
236
60
    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
52
    Local<Value> exception_v = Exception::Error(exception_string);
250
52
    CHECK(!exception_v.IsEmpty());
251
252
52
    if (!empty()) {
253
18
      CHECK(exception_v->IsObject());
254
18
      Local<Object> exception = exception_v.As<Object>();
255
      exception->Set(env->context(),
256
                     env->openssl_error_stack(),
257
90
                     ToV8Value(env->context(), *this).ToLocalChecked())
258
36
          .FromJust();
259
    }
260
261
52
    return exception_v;
262
  }
263
};
264
265
266
44
void ThrowCryptoError(Environment* env,
267
                      unsigned long err,  // NOLINT(runtime/int)
268
                      const char* message = nullptr) {
269
44
  char message_buffer[128] = {0};
270

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

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

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


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

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

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

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

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

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

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

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

4
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
885
2
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
886
2
    return 0;
887
  }
888
889
3
  return err;
890
}
891
892
893
3
void UseExtraCaCerts(const std::string& file) {
894
  ClearErrorOnReturn clear_error_on_return;
895
896
3
  if (root_cert_store == nullptr) {
897
3
    root_cert_store = NewRootCertStore();
898
899
3
    if (!file.empty()) {
900
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
901
                                           root_cert_store,
902
3
                                           file.c_str());
903
3
      if (err) {
904
        fprintf(stderr,
905
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
906
                file.c_str(),
907
1
                ERR_error_string(err, nullptr));
908
      } else {
909
2
        extra_root_certs_loaded = true;
910
      }
911
    }
912
3
  }
913
3
}
914
915
916
static void IsExtraRootCertsFileLoaded(
917
    const FunctionCallbackInfo<Value>& args) {
918
  return args.GetReturnValue().Set(extra_root_certs_loaded);
919
}
920
921
922
1294
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
923
  SecureContext* sc;
924
2588
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
925
  ClearErrorOnReturn clear_error_on_return;
926
927
1294
  if (root_cert_store == nullptr) {
928
205
    root_cert_store = NewRootCertStore();
929
  }
930
931
  // Increment reference count so global store is not deleted along with CTX.
932
1294
  X509_STORE_up_ref(root_cert_store);
933
1294
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
934
}
935
936
937
1507
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
938
  SecureContext* sc;
939
1513
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
940
1507
  Environment* env = sc->env();
941
  ClearErrorOnReturn clear_error_on_return;
942
943
1507
  if (args.Length() != 1) {
944
    return THROW_ERR_MISSING_ARGS(env, "Ciphers argument is mandatory");
945
  }
946
947
4521
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Ciphers");
948
949
3006
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
950
1505
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
951
4
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
952
4
    if (!err) {
953
      return env->ThrowError("Failed to set ciphers");
954
    }
955
4
    return ThrowCryptoError(env, err);
956
1501
  }
957
}
958
959
960
1500
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
961
  SecureContext* sc;
962
2991
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
963
1500
  Environment* env = sc->env();
964
965
1500
  if (args.Length() != 1)
966
    return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory");
967
968
4500
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name");
969
970
1499
  node::Utf8Value curve(env->isolate(), args[0]);
971
972
1499
  if (strcmp(*curve, "auto") == 0)
973
1487
    return;
974
975
12
  if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve))
976
3
    return env->ThrowError("Failed to set ECDH curve");
977
}
978
979
980
10
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
981
  SecureContext* sc;
982
13
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
983
10
  Environment* env = sc->env();
984
  ClearErrorOnReturn clear_error_on_return;
985
986
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
987
  // to be specified explicitly
988
10
  if (args.Length() != 1)
989
    return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory");
990
991
17
  DHPointer dh;
992
  {
993
10
    BIOPointer bio(LoadBIO(env, args[0]));
994
10
    if (!bio)
995
      return;
996
997
10
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
998
  }
999
1000
  // Invalid dhparam is silently discarded and DHE is no longer used.
1001
10
  if (!dh)
1002
1
    return;
1003
1004
  const BIGNUM* p;
1005
9
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
1006
9
  const int size = BN_num_bits(p);
1007
9
  if (size < 1024) {
1008
    return THROW_ERR_INVALID_ARG_VALUE(
1009
2
        env, "DH parameter is less than 1024 bits");
1010
7
  } else if (size < 2048) {
1011
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1012
9
        env->isolate(), "DH parameter is less than 2048 bits"));
1013
  }
1014
1015
7
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
1016
7
  int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get());
1017
1018
7
  if (!r)
1019
7
    return env->ThrowTypeError("Error setting temp DH parameter");
1020
}
1021
1022
1023
499
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1024
  SecureContext* sc;
1025
499
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1026
  int64_t val;
1027
1028

2495
  if (args.Length() != 1 ||
1029

2994
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1030
    return THROW_ERR_INVALID_ARG_TYPE(
1031
        sc->env(), "Options must be an integer value");
1032
  }
1033
1034
  SSL_CTX_set_options(sc->ctx_.get(),
1035
499
                      static_cast<long>(val));  // NOLINT(runtime/int)
1036
}
1037
1038
1039
431
void SecureContext::SetSessionIdContext(
1040
    const FunctionCallbackInfo<Value>& args) {
1041
  SecureContext* sc;
1042
862
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1043
431
  Environment* env = sc->env();
1044
1045
431
  if (args.Length() != 1) {
1046
    return THROW_ERR_MISSING_ARGS(
1047
        env, "Session ID context argument is mandatory");
1048
  }
1049
1050
1293
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1051
1052
431
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1053
  const unsigned char* sid_ctx =
1054
431
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1055
431
  unsigned int sid_ctx_len = sessionIdContext.length();
1056
1057
431
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1058
431
  if (r == 1)
1059
431
    return;
1060
1061
  BUF_MEM* mem;
1062
  Local<String> message;
1063
1064
  BIOPointer bio(BIO_new(BIO_s_mem()));
1065
  if (!bio) {
1066
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1067
                                    "SSL_CTX_set_session_id_context error");
1068
  } else {
1069
    ERR_print_errors(bio.get());
1070
    BIO_get_mem_ptr(bio.get(), &mem);
1071
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1072
  }
1073
1074
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1075
}
1076
1077
1078
1
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1079
  SecureContext* sc;
1080
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1081
1082


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

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

4
    if (Buffer::Length(name_val) != kTicketPartSize ||
1330
2
        Buffer::Length(iv_val) != kTicketPartSize) {
1331
      return -1;
1332
    }
1333
1334
2
    memcpy(name, Buffer::Data(name_val), kTicketPartSize);
1335
2
    memcpy(iv, Buffer::Data(iv_val), kTicketPartSize);
1336
  }
1337
1338
  HMAC_Init_ex(hctx,
1339
3
               Buffer::Data(hmac),
1340
3
               Buffer::Length(hmac),
1341
               EVP_sha256(),
1342
9
               nullptr);
1343
1344
  const unsigned char* aes_key =
1345
3
      reinterpret_cast<unsigned char*>(Buffer::Data(aes));
1346
3
  if (enc) {
1347
    EVP_EncryptInit_ex(ectx,
1348
                       EVP_aes_128_cbc(),
1349
                       nullptr,
1350
                       aes_key,
1351
2
                       iv);
1352
  } else {
1353
    EVP_DecryptInit_ex(ectx,
1354
                       EVP_aes_128_cbc(),
1355
                       nullptr,
1356
                       aes_key,
1357
1
                       iv);
1358
  }
1359
1360
6
  return r;
1361
}
1362
1363
1364
486
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1365
                                               unsigned char* name,
1366
                                               unsigned char* iv,
1367
                                               EVP_CIPHER_CTX* ectx,
1368
                                               HMAC_CTX* hctx,
1369
                                               int enc) {
1370
  SecureContext* sc = static_cast<SecureContext*>(
1371
486
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1372
1373
486
  if (enc) {
1374
443
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1375

1329
    if (RAND_bytes(iv, 16) <= 0 ||
1376
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1377

886
                           sc->ticket_key_aes_, iv) <= 0 ||
1378
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1379
443
                     EVP_sha256(), nullptr) <= 0) {
1380
      return -1;
1381
    }
1382
443
    return 1;
1383
  }
1384
1385
43
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1386
    // The ticket key name does not match. Discard the ticket.
1387
9
    return 0;
1388
  }
1389
1390
34
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1391

68
                         iv) <= 0 ||
1392
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1393
34
                   EVP_sha256(), nullptr) <= 0) {
1394
    return -1;
1395
  }
1396
34
  return 1;
1397
}
1398
1399
1400
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1401
  SecureContext* sc;
1402
4
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1403
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1404
4
  info.GetReturnValue().Set(ext);
1405
}
1406
1407
1408
template <bool primary>
1409
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1410
  SecureContext* wrap;
1411

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1412
6
  Environment* env = wrap->env();
1413
  X509* cert;
1414
1415
  if (primary)
1416
3
    cert = wrap->cert_.get();
1417
  else
1418
3
    cert = wrap->issuer_.get();
1419

6
  if (cert == nullptr)
1420
    return args.GetReturnValue().SetNull();
1421
1422
6
  int size = i2d_X509(cert, nullptr);
1423
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1424
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1425
6
      Buffer::Data(buff));
1426
6
  i2d_X509(cert, &serialized);
1427
1428
12
  args.GetReturnValue().Set(buff);
1429
}
1430
1431
1432
template <class Base>
1433
420
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1434
420
  HandleScope scope(env->isolate());
1435
1436
420
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
1437
420
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
1438
420
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
1439
420
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
1440
420
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
1441
420
  env->SetProtoMethod(t, "setSession", SetSession);
1442
420
  env->SetProtoMethod(t, "loadSession", LoadSession);
1443
420
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
1444
420
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
1445
420
  env->SetProtoMethodNoSideEffect(t, "getCurrentCipher", GetCurrentCipher);
1446
420
  env->SetProtoMethod(t, "endParser", EndParser);
1447
420
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1448
420
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1449
420
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
1450
420
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1451
420
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1452
420
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1453
420
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
1454
                                  GetEphemeralKeyInfo);
1455
420
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
1456
1457
#ifdef SSL_set_max_send_fragment
1458
420
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1459
#endif  // SSL_set_max_send_fragment
1460
1461
420
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
1462
                                  GetALPNNegotiatedProto);
1463
420
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1464
420
}
1465
1466
1467
template <class Base>
1468
11545
void SSLWrap<Base>::ConfigureSecureContext(SecureContext* sc) {
1469
  // OCSP stapling
1470
11545
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
1471
11545
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
1472
11545
}
1473
1474
1475
template <class Base>
1476
11
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1477
                                               const unsigned char* key,
1478
                                               int len,
1479
                                               int* copy) {
1480
11
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1481
1482
11
  *copy = 0;
1483
11
  return w->next_sess_.release();
1484
}
1485
1486
1487
template <class Base>
1488
12
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1489
12
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1490
12
  Environment* env = w->ssl_env();
1491
12
  HandleScope handle_scope(env->isolate());
1492
12
  Context::Scope context_scope(env->context());
1493
1494
12
  if (!w->session_callbacks_)
1495
4
    return 0;
1496
1497
  // Check if session is small enough to be stored
1498
8
  int size = i2d_SSL_SESSION(sess, nullptr);
1499
8
  if (size > SecureContext::kMaxSessionSize)
1500
    return 0;
1501
1502
  // Serialize session
1503
16
  Local<Object> session = Buffer::New(env, size).ToLocalChecked();
1504
  unsigned char* session_data = reinterpret_cast<unsigned char*>(
1505
8
      Buffer::Data(session));
1506
8
  memset(session_data, 0, size);
1507
8
  i2d_SSL_SESSION(sess, &session_data);
1508
1509
  unsigned int session_id_length;
1510
  const unsigned char* session_id_data = SSL_SESSION_get_id(sess,
1511
8
                                                            &session_id_length);
1512
  Local<Object> session_id = Buffer::Copy(
1513
      env,
1514
      reinterpret_cast<const char*>(session_id_data),
1515
16
      session_id_length).ToLocalChecked();
1516
24
  Local<Value> argv[] = { session_id, session };
1517
8
  w->new_session_wait_ = true;
1518
8
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1519
1520
20
  return 0;
1521
}
1522
1523
1524
template <class Base>
1525
20
void SSLWrap<Base>::OnClientHello(void* arg,
1526
                                  const ClientHelloParser::ClientHello& hello) {
1527
20
  Base* w = static_cast<Base*>(arg);
1528
20
  Environment* env = w->ssl_env();
1529
20
  HandleScope handle_scope(env->isolate());
1530
20
  Local<Context> context = env->context();
1531
  Context::Scope context_scope(context);
1532
1533
20
  Local<Object> hello_obj = Object::New(env->isolate());
1534
  Local<Object> buff = Buffer::Copy(
1535
      env,
1536
20
      reinterpret_cast<const char*>(hello.session_id()),
1537
60
      hello.session_size()).ToLocalChecked();
1538
60
  hello_obj->Set(context, env->session_id_string(), buff).FromJust();
1539
20
  if (hello.servername() == nullptr) {
1540
    hello_obj->Set(context,
1541
                   env->servername_string(),
1542
8
                   String::Empty(env->isolate())).FromJust();
1543
  } else {
1544
    Local<String> servername = OneByteString(env->isolate(),
1545
                                             hello.servername(),
1546
18
                                             hello.servername_size());
1547
54
    hello_obj->Set(context, env->servername_string(), servername).FromJust();
1548
  }
1549
  hello_obj->Set(context,
1550
                 env->tls_ticket_string(),
1551
80
                 Boolean::New(env->isolate(), hello.has_ticket())).FromJust();
1552
1553
40
  Local<Value> argv[] = { hello_obj };
1554
40
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1555
20
}
1556
1557
1558
82
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1559
82
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1560
1561
82
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1562
72
    return false;
1563
1564
10
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
1565
10
  if (names == nullptr)
1566
    return false;
1567
1568
39
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1569
29
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1570
1571
29
    if (i != 0)
1572
19
      BIO_write(out, ", ", 2);
1573
1574
29
    if (gen->type == GEN_DNS) {
1575
26
      ASN1_IA5STRING* name = gen->d.dNSName;
1576
1577
26
      BIO_write(out, "DNS:", 4);
1578
26
      BIO_write(out, name->data, name->length);
1579
    } else {
1580
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1581
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
1582
3
      if (nval == nullptr)
1583
        return false;
1584
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1585
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1586
    }
1587
  }
1588
10
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1589
1590
10
  return true;
1591
}
1592
1593
1594
1022
static void AddFingerprintDigest(const unsigned char* md,
1595
                                 unsigned int md_size,
1596
                                 char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) {
1597
  unsigned int i;
1598
1022
  const char hex[] = "0123456789ABCDEF";
1599
1600
27594
  for (i = 0; i < md_size; i++) {
1601
26572
    (*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4];
1602
26572
    (*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)];
1603
26572
    (*fingerprint)[(3*i)+2] = ':';
1604
  }
1605
1606
1022
  if (md_size > 0) {
1607
1022
    (*fingerprint)[(3*(md_size-1))+2] = '\0';
1608
  } else {
1609
    (*fingerprint)[0] = '\0';
1610
  }
1611
1022
}
1612
1613
511
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1614
511
  EscapableHandleScope scope(env->isolate());
1615
511
  Local<Context> context = env->context();
1616
511
  Local<Object> info = Object::New(env->isolate());
1617
1618
1022
  BIOPointer bio(BIO_new(BIO_s_mem()));
1619
  BUF_MEM* mem;
1620
511
  if (X509_NAME_print_ex(bio.get(),
1621
511
                         X509_get_subject_name(cert),
1622
                         0,
1623
511
                         X509_NAME_FLAGS) > 0) {
1624
511
    BIO_get_mem_ptr(bio.get(), &mem);
1625
    info->Set(context, env->subject_string(),
1626
              String::NewFromUtf8(env->isolate(), mem->data,
1627
                                  NewStringType::kNormal,
1628
2044
                                  mem->length).ToLocalChecked()).FromJust();
1629
  }
1630
511
  USE(BIO_reset(bio.get()));
1631
1632
511
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1633
511
  if (X509_NAME_print_ex(bio.get(), issuer_name, 0, X509_NAME_FLAGS) > 0) {
1634
511
    BIO_get_mem_ptr(bio.get(), &mem);
1635
    info->Set(context, env->issuer_string(),
1636
              String::NewFromUtf8(env->isolate(), mem->data,
1637
                                  NewStringType::kNormal,
1638
2044
                                  mem->length).ToLocalChecked()).FromJust();
1639
  }
1640
511
  USE(BIO_reset(bio.get()));
1641
1642
511
  int nids[] = { NID_subject_alt_name, NID_info_access };
1643
  Local<String> keys[] = { env->subjectaltname_string(),
1644
511
                           env->infoaccess_string() };
1645
511
  CHECK_EQ(arraysize(nids), arraysize(keys));
1646
1533
  for (size_t i = 0; i < arraysize(nids); i++) {
1647
1022
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1648
1022
    if (index < 0)
1649
940
      continue;
1650
1651
82
    X509_EXTENSION* ext = X509_get_ext(cert, index);
1652
82
    CHECK_NOT_NULL(ext);
1653
1654
82
    if (!SafeX509ExtPrint(bio.get(), ext)) {
1655
72
      CHECK_EQ(1, X509V3_EXT_print(bio.get(), ext, 0, 0));
1656
    }
1657
1658
82
    BIO_get_mem_ptr(bio.get(), &mem);
1659
    info->Set(context, keys[i],
1660
              String::NewFromUtf8(env->isolate(), mem->data,
1661
                                  NewStringType::kNormal,
1662
246
                                  mem->length).ToLocalChecked()).FromJust();
1663
1664
82
    USE(BIO_reset(bio.get()));
1665
  }
1666
1667
1022
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1668
1022
  RSAPointer rsa;
1669
1022
  ECPointer ec;
1670
511
  if (pkey) {
1671
511
    switch (EVP_PKEY_id(pkey.get())) {
1672
      case EVP_PKEY_RSA:
1673
477
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1674
477
        break;
1675
      case EVP_PKEY_EC:
1676
34
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1677
34
        break;
1678
    }
1679
  }
1680
1681
511
  if (rsa) {
1682
    const BIGNUM* n;
1683
    const BIGNUM* e;
1684
477
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1685
477
    BN_print(bio.get(), n);
1686
477
    BIO_get_mem_ptr(bio.get(), &mem);
1687
    info->Set(context, env->modulus_string(),
1688
              String::NewFromUtf8(env->isolate(), mem->data,
1689
                                  NewStringType::kNormal,
1690
1908
                                  mem->length).ToLocalChecked()).FromJust();
1691
477
    USE(BIO_reset(bio.get()));
1692
1693
477
    int bits = BN_num_bits(n);
1694
    info->Set(context, env->bits_string(),
1695
1908
              Integer::New(env->isolate(), bits)).FromJust();
1696
1697
477
    uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
1698
477
    uint32_t lo = static_cast<uint32_t>(exponent_word);
1699
477
    uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
1700
477
    if (hi == 0) {
1701
477
      BIO_printf(bio.get(), "0x%x", lo);
1702
    } else {
1703
      BIO_printf(bio.get(), "0x%x%08x", hi, lo);
1704
    }
1705
477
    BIO_get_mem_ptr(bio.get(), &mem);
1706
    info->Set(context, env->exponent_string(),
1707
              String::NewFromUtf8(env->isolate(), mem->data,
1708
                                  NewStringType::kNormal,
1709
1908
                                  mem->length).ToLocalChecked()).FromJust();
1710
477
    USE(BIO_reset(bio.get()));
1711
1712
477
    int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
1713
477
    CHECK_GE(size, 0);
1714
954
    Local<Object> pubbuff = Buffer::New(env, size).ToLocalChecked();
1715
    unsigned char* pubserialized =
1716
477
        reinterpret_cast<unsigned char*>(Buffer::Data(pubbuff));
1717
477
    i2d_RSA_PUBKEY(rsa.get(), &pubserialized);
1718
1908
    info->Set(env->context(), env->pubkey_string(), pubbuff).FromJust();
1719
34
  } else if (ec) {
1720
34
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1721
34
    if (group != nullptr) {
1722
34
      int bits = EC_GROUP_order_bits(group);
1723
34
      if (bits > 0) {
1724
        info->Set(context, env->bits_string(),
1725
136
                  Integer::New(env->isolate(), bits)).FromJust();
1726
      }
1727
    }
1728
1729
34
    unsigned char* pub = nullptr;
1730
68
    size_t publen = EC_KEY_key2buf(ec.get(), EC_KEY_get_conv_form(ec.get()),
1731
68
                                   &pub, nullptr);
1732
34
    if (publen > 0) {
1733
68
      Local<Object> buf = Buffer::New(env, pub, publen).ToLocalChecked();
1734
      // Ownership of pub pointer accepted by Buffer.
1735
34
      pub = nullptr;
1736
102
      info->Set(context, env->pubkey_string(), buf).FromJust();
1737
    } else {
1738
      CHECK_NULL(pub);
1739
    }
1740
1741
34
    if (EC_GROUP_get_asn1_flag(group) != 0) {
1742
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1743
1744
34
      int nid = EC_GROUP_get_curve_name(group);
1745
34
      if (nid != 0) {
1746
34
        if (const char* sn = OBJ_nid2sn(nid)) {
1747
          info->Set(context, env->asn1curve_string(),
1748
136
                    OneByteString(env->isolate(), sn)).FromJust();
1749
        }
1750
      }
1751
34
      if (nid != 0) {
1752
34
        if (const char* nist = EC_curve_nid2nist(nid)) {
1753
          info->Set(context, env->nistcurve_string(),
1754
136
                    OneByteString(env->isolate(), nist)).FromJust();
1755
        }
1756
      }
1757
    } else {
1758
      // Unnamed curves can be described by their mathematical properties,
1759
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
1760
    }
1761
  }
1762
1763
511
  pkey.reset();
1764
511
  rsa.reset();
1765
511
  ec.reset();
1766
1767
511
  ASN1_TIME_print(bio.get(), X509_get_notBefore(cert));
1768
511
  BIO_get_mem_ptr(bio.get(), &mem);
1769
  info->Set(context, env->valid_from_string(),
1770
            String::NewFromUtf8(env->isolate(), mem->data,
1771
                                NewStringType::kNormal,
1772
2044
                                mem->length).ToLocalChecked()).FromJust();
1773
511
  USE(BIO_reset(bio.get()));
1774
1775
511
  ASN1_TIME_print(bio.get(), X509_get_notAfter(cert));
1776
511
  BIO_get_mem_ptr(bio.get(), &mem);
1777
  info->Set(context, env->valid_to_string(),
1778
            String::NewFromUtf8(env->isolate(), mem->data,
1779
                                NewStringType::kNormal,
1780
2044
                                mem->length).ToLocalChecked()).FromJust();
1781
511
  bio.reset();
1782
1783
  unsigned char md[EVP_MAX_MD_SIZE];
1784
  unsigned int md_size;
1785
  char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
1786
511
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1787
511
      AddFingerprintDigest(md, md_size, &fingerprint);
1788
      info->Set(context, env->fingerprint_string(),
1789
2044
                OneByteString(env->isolate(), fingerprint)).FromJust();
1790
  }
1791
511
  if (X509_digest(cert, EVP_sha256(), md, &md_size)) {
1792
511
      AddFingerprintDigest(md, md_size, &fingerprint);
1793
      info->Set(context, env->fingerprint256_string(),
1794
2044
                OneByteString(env->isolate(), fingerprint)).FromJust();
1795
  }
1796
1797
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
1798
511
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
1799
511
  if (eku) {
1800
15
    Local<Array> ext_key_usage = Array::New(env->isolate());
1801
    char buf[256];
1802
1803
15
    int j = 0;
1804
44
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku.get()); i++) {
1805
29
      if (OBJ_obj2txt(buf,
1806
                      sizeof(buf),
1807
29
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
1808
29
        ext_key_usage->Set(context,
1809
                           j++,
1810
116
                           OneByteString(env->isolate(), buf)).FromJust();
1811
      }
1812
    }
1813
1814
15
    eku.reset();
1815
45
    info->Set(context, env->ext_key_usage_string(), ext_key_usage).FromJust();
1816
  }
1817
1818
511
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1819
511
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
1820
511
    if (bn) {
1821
511
      OpenSSLBuffer buf(BN_bn2hex(bn.get()));
1822
511
      if (buf) {
1823
        info->Set(context, env->serial_number_string(),
1824
2044
                  OneByteString(env->isolate(), buf.get())).FromJust();
1825
511
      }
1826
511
    }
1827
  }
1828
1829
  // Raw DER certificate
1830
511
  int size = i2d_X509(cert, nullptr);
1831
1022
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1832
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1833
511
      Buffer::Data(buff));
1834
511
  i2d_X509(cert, &serialized);
1835
1533
  info->Set(context, env->raw_string(), buff).FromJust();
1836
1837
1022
  return scope.Escape(info);
1838
}
1839
1840
1841
178
static Local<Object> AddIssuerChainToObject(X509Pointer* cert,
1842
                                            Local<Object> object,
1843
                                            StackOfX509&& peer_certs,
1844
                                            Environment* const env) {
1845
178
  Local<Context> context = env->isolate()->GetCurrentContext();
1846
178
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
1847
  for (;;) {
1848
    int i;
1849
380
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
1850
140
      X509* ca = sk_X509_value(peer_certs.get(), i);
1851
140
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
1852
2
        continue;
1853
1854
138
      Local<Object> ca_info = X509ToObject(env, ca);
1855
414
      object->Set(context, env->issuercert_string(), ca_info).FromJust();
1856
138
      object = ca_info;
1857
1858
      // NOTE: Intentionally freeing cert that is not used anymore.
1859
      // Delete cert and continue aggregating issuers.
1860
138
      cert->reset(sk_X509_delete(peer_certs.get(), i));
1861
138
      break;
1862
    }
1863
1864
    // Issuer not found, break out of the loop.
1865
188
    if (i == sk_X509_num(peer_certs.get()))
1866
178
      break;
1867
10
  }
1868
178
  return object;
1869
}
1870
1871
1872
178
static StackOfX509 CloneSSLCerts(X509Pointer&& cert,
1873
                                 const STACK_OF(X509)* const ssl_certs) {
1874
178
  StackOfX509 peer_certs(sk_X509_new(nullptr));
1875
178
  if (cert)
1876
    sk_X509_push(peer_certs.get(), cert.release());
1877
496
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
1878
318
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
1879

318
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
1880
      return StackOfX509();
1881
    // `cert` is now managed by the stack.
1882
318
    cert.release();
1883
318
  }
1884
178
  return peer_certs;
1885
}
1886
1887
1888
178
static Local<Object> GetLastIssuedCert(X509Pointer* cert,
1889
                                       const SSLPointer& ssl,
1890
                                       Local<Object> issuer_chain,
1891
                                       Environment* const env) {
1892
178
  Local<Context> context = env->isolate()->GetCurrentContext();
1893
510
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
1894
    X509* ca;
1895
154
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
1896
      break;
1897
1898
154
    Local<Object> ca_info = X509ToObject(env, ca);
1899
462
    issuer_chain->Set(context, env->issuercert_string(), ca_info).FromJust();
1900
154
    issuer_chain = ca_info;
1901
1902
    // Delete previous cert and continue aggregating issuers.
1903
154
    cert->reset(ca);
1904
  }
1905
178
  return issuer_chain;
1906
}
1907
1908
1909
template <class Base>
1910
220
void SSLWrap<Base>::GetPeerCertificate(
1911
    const FunctionCallbackInfo<Value>& args) {
1912
  Base* w;
1913
440
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1914
220
  Environment* env = w->ssl_env();
1915
1916
  ClearErrorOnReturn clear_error_on_return;
1917
1918
  Local<Object> result;
1919
  // Used to build the issuer certificate chain.
1920
  Local<Object> issuer_chain;
1921
1922
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1923
  // contains the `peer_certificate`, but on server it doesn't.
1924
  X509Pointer cert(
1925
440
      w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) : nullptr);
1926
220
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_.get());
1927


220
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
1928
3
    goto done;
1929
1930
  // Short result requested.
1931


868
  if (args.Length() < 1 || !args[0]->IsTrue()) {
1932
39
    result = X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
1933
39
    goto done;
1934
  }
1935
1936
356
  if (auto peer_certs = CloneSSLCerts(std::move(cert), ssl_certs)) {
1937
    // First and main certificate.
1938
178
    X509Pointer cert(sk_X509_value(peer_certs.get(), 0));
1939
178
    CHECK(cert);
1940
178
    result = X509ToObject(env, cert.release());
1941
1942
178
    issuer_chain =
1943
178
        AddIssuerChainToObject(&cert, result, std::move(peer_certs), env);
1944
178
    issuer_chain = GetLastIssuedCert(&cert, w->ssl_, issuer_chain, env);
1945
    // Last certificate should be self-signed.
1946
178
    if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK)
1947
      issuer_chain->Set(env->context(),
1948
                        env->issuercert_string(),
1949
712
                        issuer_chain).FromJust();
1950
  }
1951
1952
 done:
1953
660
  args.GetReturnValue().Set(result);
1954
}
1955
1956
1957
template <class Base>
1958
3
void SSLWrap<Base>::GetCertificate(
1959
    const FunctionCallbackInfo<Value>& args) {
1960
  Base* w;
1961
6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1962
3
  Environment* env = w->ssl_env();
1963
1964
  ClearErrorOnReturn clear_error_on_return;
1965
1966
  Local<Object> result;
1967
1968
6
  X509Pointer cert(SSL_get_certificate(w->ssl_.get()));
1969
1970
3
  if (cert)
1971
2
    result = X509ToObject(env, cert.get());
1972
1973
9
  args.GetReturnValue().Set(result);
1974
}
1975
1976
1977
template <class Base>
1978
3
void SSLWrap<Base>::GetFinished(const FunctionCallbackInfo<Value>& args) {
1979
3
  Environment* env = Environment::GetCurrent(args);
1980
1981
  Base* w;
1982
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1983
1984
  // We cannot just pass nullptr to SSL_get_finished()
1985
  // because it would further be propagated to memcpy(),
1986
  // where the standard requirements as described in ISO/IEC 9899:2011
1987
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1988
  // Thus, we use a dummy byte.
1989
  char dummy[1];
1990
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
1991
3
  if (len == 0)
1992
1
    return;
1993
1994
2
  char* buf = Malloc(len);
1995
2
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf, len));
1996
6
  args.GetReturnValue().Set(Buffer::New(env, buf, len).ToLocalChecked());
1997
}
1998
1999
2000
template <class Base>
2001
3
void SSLWrap<Base>::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
2002
3
  Environment* env = Environment::GetCurrent(args);
2003
2004
  Base* w;
2005
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2006
2007
  // We cannot just pass nullptr to SSL_get_peer_finished()
2008
  // because it would further be propagated to memcpy(),
2009
  // where the standard requirements as described in ISO/IEC 9899:2011
2010
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2011
  // Thus, we use a dummy byte.
2012
  char dummy[1];
2013
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
2014
3
  if (len == 0)
2015
1
    return;
2016
2017
2
  char* buf = Malloc(len);
2018
2
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf, len));
2019
6
  args.GetReturnValue().Set(Buffer::New(env, buf, len).ToLocalChecked());
2020
}
2021
2022
2023
template <class Base>
2024
139
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
2025
139
  Environment* env = Environment::GetCurrent(args);
2026
2027
  Base* w;
2028
139
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2029
2030
139
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2031
139
  if (sess == nullptr)
2032
    return;
2033
2034
139
  int slen = i2d_SSL_SESSION(sess, nullptr);
2035
139
  CHECK_GT(slen, 0);
2036
2037
139
  char* sbuf = Malloc(slen);
2038
139
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
2039
139
  i2d_SSL_SESSION(sess, &p);
2040
417
  args.GetReturnValue().Set(Buffer::New(env, sbuf, slen).ToLocalChecked());
2041
}
2042
2043
2044
template <class Base>
2045
80
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
2046
80
  Environment* env = Environment::GetCurrent(args);
2047
2048
  Base* w;
2049
80
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2050
2051
80
  if (args.Length() < 1) {
2052
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
2053
  }
2054
2055
80
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
2056
80
  size_t slen = Buffer::Length(args[0]);
2057
80
  std::vector<char> sbuf(slen);
2058
80
  if (char* p = Buffer::Data(args[0]))
2059
80
    sbuf.assign(p, p + slen);
2060
2061
80
  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf.data());
2062
160
  SSLSessionPointer sess(d2i_SSL_SESSION(nullptr, &p, slen));
2063
2064
80
  if (sess == nullptr)
2065
    return;
2066
2067
80
  int r = SSL_set_session(w->ssl_.get(), sess.get());
2068
2069
80
  if (!r)
2070
80
    return env->ThrowError("SSL_set_session error");
2071
}
2072
2073
2074
template <class Base>
2075
10
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
2076
  Base* w;
2077
20
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2078
2079

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2080
10
    ssize_t slen = Buffer::Length(args[0]);
2081
10
    char* sbuf = Buffer::Data(args[0]);
2082
2083
10
    const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
2084
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
2085
2086
    // Setup next session and move hello to the BIO buffer
2087
10
    w->next_sess_.reset(sess);
2088
  }
2089
}
2090
2091
2092
template <class Base>
2093
198
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2094
  Base* w;
2095
396
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2096
198
  bool yes = SSL_session_reused(w->ssl_.get());
2097
594
  args.GetReturnValue().Set(yes);
2098
}
2099
2100
2101
template <class Base>
2102
19
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2103
  Base* w;
2104
38
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2105
19
  w->hello_parser_.End();
2106
}
2107
2108
2109
template <class Base>
2110
3
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2111
  Base* w;
2112
6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2113
2114
  ClearErrorOnReturn clear_error_on_return;
2115
2116
3
  bool yes = SSL_renegotiate(w->ssl_.get()) == 1;
2117
9
  args.GetReturnValue().Set(yes);
2118
}
2119
2120
2121
template <class Base>
2122
9
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2123
  Base* w;
2124
9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2125
9
  Environment* env = w->ssl_env();
2126
2127
9
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2128
9
  if (sess == nullptr)
2129
    return;
2130
2131
  const unsigned char* ticket;
2132
  size_t length;
2133
9
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2134
2135
9
  if (ticket == nullptr)
2136
    return;
2137
2138
  Local<Object> buff = Buffer::Copy(
2139
18
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2140
2141
18
  args.GetReturnValue().Set(buff);
2142
}
2143
2144
2145
template <class Base>
2146
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2147
  Base* w;
2148
16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2149
8
  w->new_session_wait_ = false;
2150
8
  w->NewSessionDoneCb();
2151
}
2152
2153
2154
template <class Base>
2155
2
void SSLWrap<Base>::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
2156
  Base* w;
2157
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2158
2
  Environment* env = w->env();
2159
2160
2
  if (args.Length() < 1)
2161
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
2162
2163
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
2164
2165
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
2166
}
2167
2168
2169
template <class Base>
2170
4
void SSLWrap<Base>::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
2171
  Base* w;
2172
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2173
2174
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
2175
}
2176
2177
2178
template <class Base>
2179
456
void SSLWrap<Base>::GetEphemeralKeyInfo(
2180
    const FunctionCallbackInfo<Value>& args) {
2181
  Base* w;
2182
456
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2183
456
  Environment* env = Environment::GetCurrent(args);
2184
456
  Local<Context> context = env->context();
2185
2186
456
  CHECK(w->ssl_);
2187
2188
  // tmp key is available on only client
2189
456
  if (w->is_server())
2190
12
    return args.GetReturnValue().SetNull();
2191
2192
450
  Local<Object> info = Object::New(env->isolate());
2193
2194
  EVP_PKEY* key;
2195
2196
450
  if (SSL_get_server_tmp_key(w->ssl_.get(), &key)) {
2197
404
    int kid = EVP_PKEY_id(key);
2198
404
    switch (kid) {
2199
      case EVP_PKEY_DH:
2200
        info->Set(context, env->type_string(),
2201
24
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH")).FromJust();
2202
        info->Set(context, env->size_string(),
2203
24
                  Integer::New(env->isolate(), EVP_PKEY_bits(key))).FromJust();
2204
6
        break;
2205
      case EVP_PKEY_EC:
2206
      // TODO(shigeki) Change this to EVP_PKEY_X25519 and add EVP_PKEY_X448
2207
      // after upgrading to 1.1.1.
2208
      case NID_X25519:
2209
        {
2210
          const char* curve_name;
2211
398
          if (kid == EVP_PKEY_EC) {
2212
7
            EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
2213
7
            int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2214
7
            curve_name = OBJ_nid2sn(nid);
2215
7
            EC_KEY_free(ec);
2216
          } else {
2217
391
            curve_name = OBJ_nid2sn(kid);
2218
          }
2219
          info->Set(context, env->type_string(),
2220
1592
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")).FromJust();
2221
          info->Set(context, env->name_string(),
2222
                    OneByteString(args.GetIsolate(),
2223
1592
                                  curve_name)).FromJust();
2224
          info->Set(context, env->size_string(),
2225
                    Integer::New(env->isolate(),
2226
1592
                                 EVP_PKEY_bits(key))).FromJust();
2227
        }
2228
398
        break;
2229
    }
2230
404
    EVP_PKEY_free(key);
2231
  }
2232
2233
900
  return args.GetReturnValue().Set(info);
2234
}
2235
2236
2237
#ifdef SSL_set_max_send_fragment
2238
template <class Base>
2239
3
void SSLWrap<Base>::SetMaxSendFragment(
2240
    const FunctionCallbackInfo<Value>& args) {
2241


12
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2242
2243
  Base* w;
2244
6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2245
2246
12
  int rv = SSL_set_max_send_fragment(
2247
      w->ssl_.get(),
2248
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2249
6
  args.GetReturnValue().Set(rv);
2250
}
2251
#endif  // SSL_set_max_send_fragment
2252
2253
2254
template <class Base>
2255
521
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2256
  Base* w;
2257
739
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2258
2259
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2260
  // peer certificate is questionable but it's compatible with what was
2261
  // here before.
2262
  long x509_verify_error =  // NOLINT(runtime/int)
2263
521
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2264
521
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_.get())) {
2265
520
    X509_free(peer_cert);
2266
520
    x509_verify_error = SSL_get_verify_result(w->ssl_.get());
2267
  }
2268
2269
521
  if (x509_verify_error == X509_V_OK)
2270
436
    return args.GetReturnValue().SetNull();
2271
2272
303
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2273
303
  const char* code = reason;
2274
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2275







303
  switch (x509_verify_error) {
2276
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2277
1
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2278
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2279
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2280
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2281
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2282
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2283
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2284
35
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2285
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2286
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2287
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2288
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2289
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2290
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2291
    CASE_X509_ERR(OUT_OF_MEM)
2292
109
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2293
12
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2294
4
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2295
139
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2296
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2297
1
    CASE_X509_ERR(CERT_REVOKED)
2298
    CASE_X509_ERR(INVALID_CA)
2299
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2300
1
    CASE_X509_ERR(INVALID_PURPOSE)
2301
    CASE_X509_ERR(CERT_UNTRUSTED)
2302
    CASE_X509_ERR(CERT_REJECTED)
2303
  }
2304
#undef CASE_X509_ERR
2305
2306
303
  Isolate* isolate = args.GetIsolate();
2307
303
  Local<String> reason_string = OneByteString(isolate, reason);
2308
303
  Local<Value> exception_value = Exception::Error(reason_string);
2309
  Local<Object> exception_object =
2310
909
    exception_value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2311
1515
  exception_object->Set(w->env()->context(), w->env()->code_string(),
2312
                        OneByteString(isolate, code)).FromJust();
2313
606
  args.GetReturnValue().Set(exception_object);
2314
}
2315
2316
2317
template <class Base>
2318
27
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
2319
  Base* w;
2320
27
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2321
27
  Environment* env = w->ssl_env();
2322
27
  Local<Context> context = env->context();
2323
2324
27
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get());
2325
27
  if (c == nullptr)
2326
    return;
2327
2328
27
  Local<Object> info = Object::New(env->isolate());
2329
27
  const char* cipher_name = SSL_CIPHER_get_name(c);
2330
  info->Set(context, env->name_string(),
2331
108
            OneByteString(args.GetIsolate(), cipher_name)).FromJust();
2332
  info->Set(context, env->version_string(),
2333
108
            OneByteString(args.GetIsolate(), "TLSv1/SSLv3")).FromJust();
2334
54
  args.GetReturnValue().Set(info);
2335
}
2336
2337
2338
template <class Base>
2339
165
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2340
  Base* w;
2341
330
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2342
2343
165
  const char* tls_version = SSL_get_version(w->ssl_.get());
2344
495
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2345
}
2346
2347
2348
template <class Base>
2349
23
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2350
                                      const unsigned char** out,
2351
                                      unsigned char* outlen,
2352
                                      const unsigned char* in,
2353
                                      unsigned int inlen,
2354
                                      void* arg) {
2355
23
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2356
23
  Environment* env = w->env();
2357
23
  HandleScope handle_scope(env->isolate());
2358
23
  Context::Scope context_scope(env->context());
2359
2360
  Local<Value> alpn_buffer =
2361
23
      w->object()->GetPrivate(
2362
          env->context(),
2363
92
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2364
23
  CHECK(Buffer::HasInstance(alpn_buffer));
2365
  const unsigned char* alpn_protos =
2366
23
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2367
23
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2368
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2369
23
                                     alpn_protos, alpn_protos_len, in, inlen);
2370
  // According to 3.2. Protocol Selection of RFC7301, fatal
2371
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2372
  // support it yet. See
2373
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2374
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2375
46
                                          : SSL_TLSEXT_ERR_NOACK;
2376
}
2377
2378
2379
template <class Base>
2380
946
void SSLWrap<Base>::GetALPNNegotiatedProto(
2381
    const FunctionCallbackInfo<Value>& args) {
2382
  Base* w;
2383
1850
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2384
2385
  const unsigned char* alpn_proto;
2386
  unsigned int alpn_proto_len;
2387
2388
946
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2389
2390
946
  if (!alpn_proto)
2391
1808
    return args.GetReturnValue().Set(false);
2392
2393
  args.GetReturnValue().Set(
2394
168
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2395
}
2396
2397
2398
template <class Base>
2399
181
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2400
  Base* w;
2401
181
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2402
181
  Environment* env = w->env();
2403

362
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2404
    return env->ThrowTypeError("Must give a Buffer as first argument");
2405
2406
181
  if (w->is_client()) {
2407
    const unsigned char* alpn_protos =
2408
28
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2409
28
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2410
28
    int r = SSL_set_alpn_protos(w->ssl_.get(), alpn_protos, alpn_protos_len);
2411
28
    CHECK_EQ(r, 0);
2412
  } else {
2413
459
    CHECK(
2414
        w->object()->SetPrivate(
2415
            env->context(),
2416
            env->alpn_buffer_private_symbol(),
2417
            args[0]).FromJust());
2418
    // Server should select ALPN protocol from list of advertised by client
2419
306
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2420
                               SelectALPNCallback,
2421
153
                               nullptr);
2422
  }
2423
}
2424
2425
2426
template <class Base>
2427
8
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2428
8
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2429
8
  Environment* env = w->env();
2430
8
  HandleScope handle_scope(env->isolate());
2431
2432
8
  if (w->is_client()) {
2433
    // Incoming response
2434
    const unsigned char* resp;
2435
4
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2436
    Local<Value> arg;
2437
4
    if (resp == nullptr) {
2438
4
      arg = Null(env->isolate());
2439
    } else {
2440
4
      arg =
2441
2
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2442
          .ToLocalChecked();
2443
    }
2444
2445
4
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2446
2447
    // Somehow, client is expecting different return value here
2448
4
    return 1;
2449
  } else {
2450
    // Outgoing response
2451
8
    if (w->ocsp_response_.IsEmpty())
2452
2
      return SSL_TLSEXT_ERR_NOACK;
2453
2454
    Local<Object> obj = PersistentToLocal::Default(env->isolate(),
2455
2
                                                   w->ocsp_response_);
2456
2
    char* resp = Buffer::Data(obj);
2457
2
    size_t len = Buffer::Length(obj);
2458
2459
    // OpenSSL takes control of the pointer after accepting it
2460
2
    char* data = node::Malloc(len);
2461
2
    memcpy(data, resp, len);
2462
2463
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2464
      free(data);
2465
2
    w->ocsp_response_.Reset();
2466
2467
2
    return SSL_TLSEXT_ERR_OK;
2468
8
  }
2469
}
2470
2471
2472
template <class Base>
2473
20
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2474
20
  cert_cb_ = cb;
2475
20
  cert_cb_arg_ = arg;
2476
20
}
2477
2478
2479
template <class Base>
2480
520
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2481
520
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2482
2483
520
  if (!w->is_server())
2484
40
    return 1;
2485
2486
480
  if (!w->is_waiting_cert_cb())
2487
460
    return 1;
2488
2489
20
  if (w->cert_cb_running_)
2490
    return -1;
2491
2492
20
  Environment* env = w->env();
2493
20
  Local<Context> context = env->context();
2494
20
  HandleScope handle_scope(env->isolate());
2495
  Context::Scope context_scope(context);
2496
20
  w->cert_cb_running_ = true;
2497
2498
20
  Local<Object> info = Object::New(env->isolate());
2499
2500
20
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2501
20
  if (servername == nullptr) {
2502
    info->Set(context,
2503
              env->servername_string(),
2504
16
              String::Empty(env->isolate())).FromJust();
2505
  } else {
2506
    Local<String> str = OneByteString(env->isolate(), servername,
2507
16
                                      strlen(servername));
2508
48
    info->Set(context, env->servername_string(), str).FromJust();
2509
  }
2510
2511
20
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
2512
  info->Set(context, env->ocsp_request_string(),
2513
80
            Boolean::New(env->isolate(), ocsp)).FromJust();
2514
2515
40
  Local<Value> argv[] = { info };
2516
20
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2517
2518
20
  if (!w->cert_cb_running_)
2519
9
    return 1;
2520
2521
  // Performing async action, wait...
2522
31
  return -1;
2523
}
2524
2525
2526
template <class Base>
2527
18
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2528
  Base* w;
2529
20
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2530
18
  Environment* env = w->env();
2531
2532

18
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2533
2534
18
  Local<Object> object = w->object();
2535
  Local<Value> ctx = object->Get(env->context(),
2536
72
                                 env->sni_context_string()).ToLocalChecked();
2537
18
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2538
2539
  // Not an object, probably undefined or null
2540
18
  if (!ctx->IsObject())
2541
8
    goto fire_cb;
2542
2543
10
  if (cons->HasInstance(ctx)) {
2544
    SecureContext* sc;
2545
10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2546
9
    w->sni_context_.Reset(env->isolate(), ctx);
2547
2548
    int rv;
2549
2550
    // NOTE: reference count is not increased by this API methods
2551
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_.get());
2552
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_.get());
2553
    STACK_OF(X509)* chain;
2554
2555
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_.get(), &chain);
2556
9
    if (rv)
2557
9
      rv = SSL_use_certificate(w->ssl_.get(), x509);
2558
9
    if (rv)
2559
8
      rv = SSL_use_PrivateKey(w->ssl_.get(), pkey);
2560

9
    if (rv && chain != nullptr)
2561
1
      rv = SSL_set1_chain(w->ssl_.get(), chain);
2562
9
    if (rv)
2563
8
      rv = w->SetCACerts(sc);
2564
9
    if (!rv) {
2565
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2566
1
      if (!err)
2567
        return env->ThrowError("CertCbDone");
2568
1
      return ThrowCryptoError(env, err);
2569
    }
2570
  } else {
2571
    // Failure: incorrect SNI context object
2572
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2573
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2574
1
    return;
2575
  }
2576
2577
 fire_cb:
2578
  CertCb cb;
2579
  void* arg;
2580
2581
16
  cb = w->cert_cb_;
2582
16
  arg = w->cert_cb_arg_;
2583
2584
16
  w->cert_cb_running_ = false;
2585
16
  w->cert_cb_ = nullptr;
2586
16
  w->cert_cb_arg_ = nullptr;
2587
2588
16
  cb(arg);
2589
}
2590
2591
2592
template <class Base>
2593
23016
void SSLWrap<Base>::DestroySSL() {
2594
23016
  if (!ssl_)
2595
34497
    return;
2596
2597
11535
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2598
11535
  ssl_.reset();
2599
}
2600
2601
2602
template <class Base>
2603
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2604
  ConfigureSecureContext(sc);
2605
  CHECK_EQ(SSL_set_SSL_CTX(ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
2606
2607
  SetCACerts(sc);
2608
}
2609
2610
2611
template <class Base>
2612
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2613
8
  int err = SSL_set1_verify_cert_store(ssl_.get(),
2614
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
2615
8
  if (err != 1)
2616
    return err;
2617
2618
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2619
8
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
2620
2621
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2622
8
  SSL_set_client_CA_list(ssl_.get(), list);
2623
8
  return 1;
2624
}
2625
2626
1098
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2627
  // Quoting SSL_set_verify(3ssl):
2628
  //
2629
  //   The VerifyCallback function is used to control the behaviour when
2630
  //   the SSL_VERIFY_PEER flag is set. It must be supplied by the
2631
  //   application and receives two arguments: preverify_ok indicates,
2632
  //   whether the verification of the certificate in question was passed
2633
  //   (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to
2634
  //   the complete context used for the certificate chain verification.
2635
  //
2636
  //   The certificate chain is checked starting with the deepest nesting
2637
  //   level (the root CA certificate) and worked upward to the peer's
2638
  //   certificate.  At each level signatures and issuer attributes are
2639
  //   checked.  Whenever a verification error is found, the error number is
2640
  //   stored in x509_ctx and VerifyCallback is called with preverify_ok=0.
2641
  //   By applying X509_CTX_store_* functions VerifyCallback can locate the
2642
  //   certificate in question and perform additional steps (see EXAMPLES).
2643
  //   If no error is found for a certificate, VerifyCallback is called
2644
  //   with preverify_ok=1 before advancing to the next level.
2645
  //
2646
  //   The return value of VerifyCallback controls the strategy of the
2647
  //   further verification process. If VerifyCallback returns 0, the
2648
  //   verification process is immediately stopped with "verification
2649
  //   failed" state. If SSL_VERIFY_PEER is set, a verification failure
2650
  //   alert is sent to the peer and the TLS/SSL handshake is terminated. If
2651
  //   VerifyCallback returns 1, the verification process is continued. If
2652
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
2653
  //   terminated with respect to verification failures and the connection
2654
  //   will be established. The calling process can however retrieve the
2655
  //   error code of the last verification error using
2656
  //   SSL_get_verify_result(3) or by maintaining its own error storage
2657
  //   managed by VerifyCallback.
2658
  //
2659
  //   If no VerifyCallback is specified, the default callback will be
2660
  //   used.  Its return value is identical to preverify_ok, so that any
2661
  //   verification failure will lead to a termination of the TLS/SSL
2662
  //   handshake with an alert message, if SSL_VERIFY_PEER is set.
2663
  //
2664
  // Since we cannot perform I/O quickly enough in this callback, we ignore
2665
  // all preverify_ok errors and let the handshake continue. It is
2666
  // imperative that the user use Connection::VerifyError after the
2667
  // 'secure' callback has been made.
2668
1098
  return 1;
2669
}
2670
2671
3346
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
2672
3346
  const int mode = EVP_CIPHER_mode(cipher);
2673
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
2674
  // but its mode is 0 which doesn't indicate
2675
6650
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
2676
6067
         mode == EVP_CIPH_CCM_MODE ||
2677

7439
         mode == EVP_CIPH_GCM_MODE ||
2678
4676
         IS_OCB_MODE(mode);
2679
}
2680
2681
1453
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
2682
1453
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
2683
1453
  return IsSupportedAuthenticatedMode(cipher);
2684
}
2685
2686
template <typename T>
2687
412
static T* MallocOpenSSL(size_t count) {
2688
412
  void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
2689

412
  CHECK_IMPLIES(mem == nullptr, count == 0);
2690
412
  return static_cast<T*>(mem);
2691
}
2692
2693
enum class ParsePublicKeyResult {
2694
  kParsePublicOk,
2695
  kParsePublicNotRecognized,
2696
  kParsePublicFailed
2697
};
2698
2699
643
static ParsePublicKeyResult TryParsePublicKey(
2700
    EVPKeyPointer* pkey,
2701
    const BIOPointer& bp,
2702
    const char* name,
2703
    // NOLINTNEXTLINE(runtime/int)
2704
    std::function<EVP_PKEY*(const unsigned char** p, long l)> parse) {
2705
  unsigned char* der_data;
2706
  long der_len;  // NOLINT(runtime/int)
2707
2708
  // This skips surrounding data and decodes PEM to DER.
2709
  {
2710
643
    MarkPopErrorOnReturn mark_pop_error_on_return;
2711
643
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
2712
643
                           bp.get(), nullptr, nullptr) != 1)
2713
434
      return ParsePublicKeyResult::kParsePublicNotRecognized;
2714
  }
2715
2716
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
2717
209
  const unsigned char* p = der_data;
2718
209
  pkey->reset(parse(&p, der_len));
2719
209
  OPENSSL_clear_free(der_data, der_len);
2720
2721
  return *pkey ? ParsePublicKeyResult::kParsePublicOk :
2722
209
                 ParsePublicKeyResult::kParsePublicFailed;
2723
}
2724
2725
236
static ParsePublicKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
2726
                                              const char* key_pem,
2727
                                              int key_pem_len) {
2728
236
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
2729
236
  if (!bp)
2730
    return ParsePublicKeyResult::kParsePublicFailed;
2731
2732
  ParsePublicKeyResult ret;
2733
2734
  // Try PKCS#8 first.
2735
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
2736
28
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2737
        return d2i_PUBKEY(nullptr, p, l);
2738
264
      });
2739
236
  if (ret != ParsePublicKeyResult::kParsePublicNotRecognized)
2740
28
    return ret;
2741
2742
  // Maybe it is PKCS#1.
2743
208
  CHECK(BIO_reset(bp.get()));
2744
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
2745
9
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2746
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
2747
217
      });
2748
208
  if (ret != ParsePublicKeyResult::kParsePublicNotRecognized)
2749
9
    return ret;
2750
2751
  // X.509 fallback.
2752
199
  CHECK(BIO_reset(bp.get()));
2753
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
2754
172
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2755
172
        X509Pointer x509(d2i_X509(nullptr, p, l));
2756
344
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
2757
371
      });
2758
}
2759
2760
205
static bool ParsePublicKey(EVPKeyPointer* pkey,
2761
                           const PublicKeyEncodingConfig& config,
2762
                           const char* key,
2763
                           size_t key_len) {
2764
205
  if (config.format_ == kKeyFormatPEM) {
2765
    ParsePublicKeyResult r =
2766
200
        ParsePublicKeyPEM(pkey, key, key_len);
2767
200
    return r == ParsePublicKeyResult::kParsePublicOk;
2768
  } else {
2769
5
    CHECK_EQ(config.format_, kKeyFormatDER);
2770
5
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2771
10
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2772
5
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2773
5
      return pkey;
2774
    } else {
2775
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2776
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
2777
      return pkey;
2778
    }
2779
  }
2780
}
2781
2782
24
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
2783
                                               BIO* bio,
2784
                                               PKFormatType format) {
2785
  BUF_MEM* bptr;
2786
24
  BIO_get_mem_ptr(bio, &bptr);
2787
24
  if (format == kKeyFormatPEM) {
2788
    // PEM is an ASCII format, so we will return it as a string.
2789
    return String::NewFromUtf8(env->isolate(), bptr->data,
2790
                               NewStringType::kNormal,
2791
38
                               bptr->length).ToLocalChecked();
2792
  } else {
2793
5
    CHECK_EQ(format, kKeyFormatDER);
2794
    // DER is binary, return it as a buffer.
2795
10
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
2796
  }
2797
}
2798
2799
12
static bool WritePublicKeyInner(EVP_PKEY* pkey,
2800
                                const BIOPointer& bio,
2801
                                const PublicKeyEncodingConfig& config) {
2802
24
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2803
    // PKCS#1 is only valid for RSA keys.
2804
6
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
2805
6
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
2806
6
    if (config.format_ == kKeyFormatPEM) {
2807
      // Encode PKCS#1 as PEM.
2808
3
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
2809
    } else {
2810
      // Encode PKCS#1 as DER.
2811
3
      CHECK_EQ(config.format_, kKeyFormatDER);
2812
3
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
2813
6
    }
2814
  } else {
2815
12
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2816
6
    if (config.format_ == kKeyFormatPEM) {
2817
      // Encode SPKI as PEM.
2818
6
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
2819
    } else {
2820
      // Encode SPKI as DER.
2821
      CHECK_EQ(config.format_, kKeyFormatDER);
2822
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
2823
    }
2824
  }
2825
}
2826
2827
12
static MaybeLocal<Value> WritePublicKey(Environment* env,
2828
                                        EVP_PKEY* pkey,
2829
                                        const PublicKeyEncodingConfig& config) {
2830
12
  BIOPointer bio(BIO_new(BIO_s_mem()));
2831
12
  CHECK(bio);
2832
2833
12
  if (!WritePublicKeyInner(pkey, bio, config)) {
2834
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
2835
    return MaybeLocal<Value>();
2836
  }
2837
24
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
2838
}
2839
2840
90
static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,
2841
                                     const char* key,
2842
                                     size_t key_len) {
2843
90
  EVPKeyPointer pkey;
2844
2845
90
  if (config.format_ == kKeyFormatPEM) {
2846
83
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
2847
83
    if (!bio)
2848
1
      return pkey;
2849
2850
82
    char* pass = const_cast<char*>(config.passphrase_.get());
2851
    pkey.reset(PEM_read_bio_PrivateKey(bio.get(),
2852
                                       nullptr,
2853
                                       PasswordCallback,
2854
82
                                       pass));
2855
  } else {
2856
7
    CHECK_EQ(config.format_, kKeyFormatDER);
2857
2858
14
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2859
5
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2860
5
      pkey.reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2861
4
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
2862
2
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
2863
2
      if (!bio)
2864
        return pkey;
2865
2
      char* pass = const_cast<char*>(config.passphrase_.get());
2866
      pkey.reset(d2i_PKCS8PrivateKey_bio(bio.get(),
2867
                                         nullptr,
2868
                                         PasswordCallback,
2869
2
                                         pass));
2870
    } else {
2871
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
2872
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2873
      pkey.reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
2874
    }
2875
  }
2876
2877
  // OpenSSL can fail to parse the key but still return a non-null pointer.
2878
89
  if (ERR_peek_error() != 0)
2879
10
    pkey.reset();
2880
2881
89
  return pkey;
2882
}
2883
2884
173
ByteSource::ByteSource(ByteSource&& other)
2885
      : data_(other.data_),
2886
        allocated_data_(other.allocated_data_),
2887
173
        size_(other.size_) {
2888
173
  other.allocated_data_ = nullptr;
2889
173
}
2890
2891
1934
ByteSource::~ByteSource() {
2892
1934
  OPENSSL_clear_free(allocated_data_, size_);
2893
1934
}
2894
2895
22
ByteSource& ByteSource::operator=(ByteSource&& other) {
2896
22
  if (&other != this) {
2897
22
    OPENSSL_clear_free(allocated_data_, size_);
2898
22
    data_ = other.data_;
2899
22
    allocated_data_ = other.allocated_data_;
2900
22
    other.allocated_data_ = nullptr;
2901
22
    size_ = other.size_;
2902
  }
2903
22
  return *this;
2904
}
2905
2906
1751
const char* ByteSource::get() const {
2907
1751
  return data_;
2908
}
2909
2910
1667
size_t ByteSource::size() const {
2911
1667
  return size_;
2912
}
2913
2914
1607
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
2915
                                          Local<Value> value) {
2916
1607
  return Buffer::HasInstance(value) ? FromBuffer(value)
2917
1984
                                    : FromString(env, value.As<String>());
2918
}
2919
2920
395
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
2921
                                  bool ntc) {
2922
790
  CHECK(str->IsString());
2923
790
  size_t size = str->Utf8Length(env->isolate());
2924
395
  size_t alloc_size = ntc ? size + 1 : size;
2925
395
  char* data = MallocOpenSSL<char>(alloc_size);
2926
395
  int opts = String::NO_OPTIONS;
2927
395
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
2928
790
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
2929
395
  return Allocated(data, size);
2930
}
2931
2932
1234
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
2933
1234
  size_t size = Buffer::Length(buffer);
2934
1234
  if (ntc) {
2935
4
    char* data = MallocOpenSSL<char>(size + 1);
2936
4
    memcpy(data, Buffer::Data(buffer), size);
2937
4
    data[size] = 0;
2938
4
    return Allocated(data, size);
2939
  }
2940
1230
  return Foreign(Buffer::Data(buffer), size);
2941
}
2942
2943
22
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
2944
                                          Local<Value> value) {
2945
22
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
2946
40
                                    : FromString(env, value.As<String>(), true);
2947
}
2948
2949
14
ByteSource ByteSource::FromSymmetricKeyObject(Local<Value> handle) {
2950
14
  CHECK(handle->IsObject());
2951
14
  KeyObject* key = Unwrap<KeyObject>(handle.As<Object>());
2952
14
  CHECK(key);
2953
14
  return Foreign(key->GetSymmetricKey(), key->GetSymmetricKeySize());
2954
}
2955
2956
1643
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
2957
      : data_(data),
2958
        allocated_data_(allocated_data),
2959
1643
        size_(size) {}
2960
2961
399
ByteSource ByteSource::Allocated(char* data, size_t size) {
2962
399
  return ByteSource(data, data, size);
2963
}
2964
2965
1244
ByteSource ByteSource::Foreign(const char* data, size_t size) {
2966
1244
  return ByteSource(data, nullptr, size);
2967
}
2968
2969
enum KeyEncodingContext {
2970
  kKeyContextInput,
2971
  kKeyContextExport,
2972
  kKeyContextGenerate
2973
};
2974
2975
334
static void GetKeyFormatAndTypeFromJs(
2976
    AsymmetricKeyEncodingConfig* config,
2977
    const FunctionCallbackInfo<Value>& args,
2978
    unsigned int* offset,
2979
    KeyEncodingContext context) {
2980
  // During key pair generation, it is possible not to specify a key encoding,
2981
  // which will lead to a key object being returned.
2982
1336
  if (args[*offset]->IsUndefined()) {
2983
4
    CHECK_EQ(context, kKeyContextGenerate);
2984
16
    CHECK(args[*offset + 1]->IsUndefined());
2985
4
    config->output_key_object_ = true;
2986
  } else {
2987
330
    config->output_key_object_ = false;
2988
2989
990
    CHECK(args[*offset]->IsInt32());
2990
    config->format_ = static_cast<PKFormatType>(
2991
1320
        args[*offset].As<Int32>()->Value());
2992
2993
990
    if (args[*offset + 1]->IsInt32()) {
2994
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
2995
152
          args[*offset + 1].As<Int32>()->Value()));
2996
    } else {
2997

292
      CHECK(context == kKeyContextInput && config->format_ == kKeyFormatPEM);
2998
1168
      CHECK(args[*offset + 1]->IsNullOrUndefined());
2999
292
      config->type_ = Nothing<PKEncodingType>();
3000
    }
3001
  }
3002
3003
334
  *offset += 2;
3004
334
}
3005
3006
217
static PublicKeyEncodingConfig GetPublicKeyEncodingFromJs(
3007
    const FunctionCallbackInfo<Value>& args,
3008
    unsigned int* offset,
3009
    KeyEncodingContext context) {
3010
217
  PublicKeyEncodingConfig result;
3011
217
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3012
217
  return result;
3013
}
3014
3015
203
static ManagedEVPPKey GetPublicKeyFromJs(
3016
    const FunctionCallbackInfo<Value>& args,
3017
    unsigned int* offset,
3018
    bool allow_key_object) {
3019


819
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3020
202
    Environment* env = Environment::GetCurrent(args);
3021
404
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3022
    PublicKeyEncodingConfig config =
3023
202
        GetPublicKeyEncodingFromJs(args, offset, kKeyContextInput);
3024
404
    EVPKeyPointer pkey;
3025
202
    ParsePublicKey(&pkey, config, key.get(), key.size());
3026
202
    if (!pkey)
3027
      ThrowCryptoError(env, ERR_get_error(), "Failed to read public key");
3028
404
    return ManagedEVPPKey(pkey.release());
3029
  } else {
3030


3
    CHECK(args[*offset]->IsObject() && allow_key_object);
3031
    KeyObject* key;
3032
3
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
3033
1
    CHECK_EQ(key->GetKeyType(), kKeyTypePublic);
3034
1
    (*offset) += 3;
3035
1
    return key->GetAsymmetricKey();
3036
  }
3037
}
3038
3039
117
static NonCopyableMaybe<PrivateKeyEncodingConfig> GetPrivateKeyEncodingFromJs(
3040
    const FunctionCallbackInfo<Value>& args,
3041
    unsigned int* offset,
3042
    KeyEncodingContext context) {
3043
117
  Environment* env = Environment::GetCurrent(args);
3044
3045
117
  PrivateKeyEncodingConfig result;
3046
117
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3047
3048
117
  if (result.output_key_object_) {
3049
2
    if (context != kKeyContextInput)
3050
2
      (*offset)++;
3051
  } else {
3052
115
    bool needs_passphrase = false;
3053
115
    if (context != kKeyContextInput) {
3054
52
      if (args[*offset]->IsString()) {
3055
        String::Utf8Value cipher_name(env->isolate(),
3056
15
                                      args[*offset].As<String>());
3057
5
        result.cipher_ = EVP_get_cipherbyname(*cipher_name);
3058
5
        if (result.cipher_ == nullptr) {
3059
1
          env->ThrowError("Unknown cipher");
3060
1
          return NonCopyableMaybe<PrivateKeyEncodingConfig>();
3061
        }
3062
4
        needs_passphrase = true;
3063
      } else {
3064
32
        CHECK(args[*offset]->IsNullOrUndefined());
3065
8
        result.cipher_ = nullptr;
3066
      }
3067
12
      (*offset)++;
3068
    }
3069
3070


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

22
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
3072
3073
44
      result.passphrase_ = ByteSource::NullTerminatedCopy(env, args[*offset]);
3074
    } else {
3075


368
      CHECK(args[*offset]->IsNullOrUndefined() && !needs_passphrase);
3076
    }
3077
  }
3078
3079
116
  (*offset)++;
3080
116
  return NonCopyableMaybe<PrivateKeyEncodingConfig>(std::move(result));
3081
}
3082
3083
59
static ManagedEVPPKey GetPrivateKeyFromJs(
3084
    const FunctionCallbackInfo<Value>& args,
3085
    unsigned int* offset,
3086
    bool allow_key_object) {
3087


244
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3088
58
    Environment* env = Environment::GetCurrent(args);
3089
116
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3090
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3091
116
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3092
58
    if (config.IsEmpty())
3093
      return ManagedEVPPKey();
3094
    EVPKeyPointer pkey =
3095
116
        ParsePrivateKey(config.Release(), key.get(), key.size());
3096
58
    if (!pkey)
3097
8
      ThrowCryptoError(env, ERR_get_error(), "Failed to read private key");
3098
116
    return ManagedEVPPKey(pkey.release());
3099
  } else {
3100


3
    CHECK(args[*offset]->IsObject() && allow_key_object);
3101
    KeyObject* key;
3102
3
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
3103
1
    CHECK_EQ(key->GetKeyType(), kKeyTypePrivate);
3104
1
    (*offset) += 4;
3105
1
    return key->GetAsymmetricKey();
3106
  }
3107
}
3108
3109
8
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
3110
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
3111

8
  if (size >= 2 && data[0] == 0x30) {
3112
    size_t offset;
3113
8
    if (data[1] & 0x80) {
3114
      // Long form.
3115
6
      size_t n_bytes = data[1] & ~0x80;
3116

6
      if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
3117
        return false;
3118
6
      size_t i, length = 0;
3119
17
      for (i = 0; i < n_bytes; i++)
3120
11
        length = (length << 8) | data[i + 2];
3121
6
      offset = 2 + n_bytes;
3122
6
      size = std::min(size, length + 2);
3123
    } else {
3124
      // Short form.
3125
2
      offset = 2;
3126
2
      size = std::min<size_t>(size, data[1] + 2);
3127
    }
3128
3129
    // An RSAPrivateKey sequence always starts with a single-byte integer whose
3130
    // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
3131
    // (which is the product of two primes and therefore at least 4), so we can
3132
    // decide the type of the structure based on the first three bytes of the
3133
    // sequence.
3134
16
    return size - offset >= 3 &&
3135
16
           data[offset] == 2 &&
3136

21
           data[offset + 1] == 1 &&
3137
13
           !(data[offset + 2] & 0xfe);
3138
  }
3139
3140
  return false;
3141
}
3142
3143
52
static ManagedEVPPKey GetPublicOrPrivateKeyFromJs(
3144
    const FunctionCallbackInfo<Value>& args,
3145
    unsigned int* offset,
3146
    bool allow_key_object) {
3147


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

8
      switch (config.type_.ToChecked()) {
3169
        case kKeyEncodingPKCS1:
3170
          is_public = !IsRSAPrivateKey(
3171
8
              reinterpret_cast<const unsigned char*>(data.get()), data.size());
3172
8
          break;
3173
        case kKeyEncodingSPKI:
3174
          is_public = true;
3175
          break;
3176
        case kKeyEncodingPKCS8:
3177
        case kKeyEncodingSEC1:
3178
          is_public = false;
3179
          break;
3180
        default:
3181
          CHECK(!"Invalid key encoding type");
3182
      }
3183
3184
8
      if (is_public) {
3185
3
        ParsePublicKey(&pkey, config, data.get(), data.size());
3186
      } else {
3187
5
        pkey = ParsePrivateKey(config, data.get(), data.size());
3188
      }
3189
    }
3190
44
    if (!pkey)
3191
3
      ThrowCryptoError(env, ERR_get_error(), "Failed to read asymmetric key");
3192
88
    return ManagedEVPPKey(pkey.release());
3193
  } else {
3194


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

16
  switch (key->key_type_) {
3392
  case kKeyTypeSecret:
3393
13
    CHECK_EQ(args.Length(), 1);
3394
26
    key->InitSecret(Buffer::Data(args[0]), Buffer::Length(args[0]));
3395
13
    break;
3396
  case kKeyTypePublic:
3397
1
    CHECK_EQ(args.Length(), 3);
3398
3399
1
    offset = 0;
3400
1
    pkey = GetPublicKeyFromJs(args, &offset, false);
3401
1
    if (!pkey)
3402
      return;
3403
1
    key->InitPublic(pkey);
3404
1
    break;
3405
  case kKeyTypePrivate:
3406
2
    CHECK_EQ(args.Length(), 4);
3407
3408
2
    offset = 0;
3409
2
    pkey = GetPrivateKeyFromJs(args, &offset, false);
3410
2
    if (!pkey)
3411
1
      return;
3412
1
    key->InitPrivate(pkey);
3413
1
    break;
3414
  default:
3415
    CHECK(false);
3416
15
  }
3417
}
3418
3419
13
void KeyObject::InitSecret(const char* key, size_t key_len) {
3420
13
  CHECK_EQ(this->key_type_, kKeyTypeSecret);
3421
3422
13
  char* mem = MallocOpenSSL<char>(key_len);
3423
13
  memcpy(mem, key, key_len);
3424
26
  this->symmetric_key_ = std::unique_ptr<char, std::function<void(char*)>>(mem,
3425
13
      [key_len](char* p) {
3426
13
        OPENSSL_clear_free(p, key_len);
3427
26
      });
3428
13
  this->symmetric_key_len_ = key_len;
3429
13
}
3430
3431
3
void KeyObject::InitPublic(const ManagedEVPPKey& pkey) {
3432
3
  CHECK_EQ(this->key_type_, kKeyTypePublic);
3433
3
  CHECK(pkey);
3434
3
  this->asymmetric_key_ = pkey;
3435
3
}
3436
3437
3
void KeyObject::InitPrivate(const ManagedEVPPKey& pkey) {
3438
3
  CHECK_EQ(this->key_type_, kKeyTypePrivate);
3439
3
  CHECK(pkey);
3440
3
  this->asymmetric_key_ = pkey;
3441
3
}
3442
3443
6
Local<String> KeyObject::GetAsymmetricKeyType() const {
3444
6
  CHECK_NE(this->key_type_, kKeyTypeSecret);
3445

6
  switch (EVP_PKEY_id(this->asymmetric_key_.get())) {
3446
  case EVP_PKEY_RSA:
3447
6
    return env()->crypto_rsa_string();
3448
  case EVP_PKEY_DSA:
3449
    return env()->crypto_dsa_string();
3450
<