GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_crypto.cc Lines: 3183 3478 91.5 %
Date: 2019-05-05 22:32:45 Branches: 1688 2574 65.6 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_crypto.h"
23
#include "node_buffer.h"
24
#include "node_crypto_bio.h"
25
#include "node_crypto_clienthello-inl.h"
26
#include "node_crypto_groups.h"
27
#include "node_errors.h"
28
#include "node_mutex.h"
29
#include "node_process.h"
30
#include "tls_wrap.h"  // TLSWrap
31
32
#include "async_wrap-inl.h"
33
#include "base_object-inl.h"
34
#include "env-inl.h"
35
#include "string_bytes.h"
36
#include "util-inl.h"
37
#include "v8.h"
38
39
#include <openssl/ec.h>
40
#include <openssl/ecdh.h>
41
#ifndef OPENSSL_NO_ENGINE
42
# include <openssl/engine.h>
43
#endif  // !OPENSSL_NO_ENGINE
44
#include <openssl/evp.h>
45
#include <openssl/pem.h>
46
#include <openssl/x509v3.h>
47
#include <openssl/hmac.h>
48
#include <openssl/rand.h>
49
#include <openssl/pkcs12.h>
50
51
#include <cerrno>
52
#include <climits>  // INT_MAX
53
#include <cstring>
54
55
#include <algorithm>
56
#include <memory>
57
#include <utility>
58
#include <vector>
59
60
static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
61
                                 | ASN1_STRFLGS_UTF8_CONVERT
62
                                 | XN_FLAG_SEP_MULTILINE
63
                                 | XN_FLAG_FN_SN;
64
65
namespace node {
66
namespace crypto {
67
68
using node::THROW_ERR_TLS_INVALID_PROTOCOL_METHOD;
69
70
using v8::Array;
71
using v8::ArrayBufferView;
72
using v8::Boolean;
73
using v8::ConstructorBehavior;
74
using v8::Context;
75
using v8::DontDelete;
76
using v8::EscapableHandleScope;
77
using v8::Exception;
78
using v8::External;
79
using v8::False;
80
using v8::Function;
81
using v8::FunctionCallback;
82
using v8::FunctionCallbackInfo;
83
using v8::FunctionTemplate;
84
using v8::HandleScope;
85
using v8::Int32;
86
using v8::Integer;
87
using v8::Isolate;
88
using v8::Just;
89
using v8::Local;
90
using v8::Maybe;
91
using v8::MaybeLocal;
92
using v8::NewStringType;
93
using v8::Nothing;
94
using v8::Null;
95
using v8::Object;
96
using v8::PropertyAttribute;
97
using v8::ReadOnly;
98
using v8::SideEffectType;
99
using v8::Signature;
100
using v8::String;
101
using v8::Uint32;
102
using v8::Undefined;
103
using v8::Value;
104
105
#ifdef OPENSSL_NO_OCB
106
# define IS_OCB_MODE(mode) false
107
#else
108
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
109
#endif
110
111
struct StackOfX509Deleter {
112
1211
  void operator()(STACK_OF(X509)* p) const { sk_X509_pop_free(p, X509_free); }
113
};
114
using StackOfX509 = std::unique_ptr<STACK_OF(X509), StackOfX509Deleter>;
115
116
struct StackOfXASN1Deleter {
117
20
  void operator()(STACK_OF(ASN1_OBJECT)* p) const {
118
20
    sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
119
20
  }
120
};
121
using StackOfASN1 = std::unique_ptr<STACK_OF(ASN1_OBJECT), StackOfXASN1Deleter>;
122
123
// OPENSSL_free is a macro, so we need a wrapper function.
124
struct OpenSSLBufferDeleter {
125
1145
  void operator()(char* pointer) const { OPENSSL_free(pointer); }
126
};
127
using OpenSSLBuffer = std::unique_ptr<char[], OpenSSLBufferDeleter>;
128
129
static const char* const root_certs[] = {
130
#include "node_root_certs.h"  // NOLINT(build/include_order)
131
};
132
133
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
134
135
static X509_STORE* root_cert_store;
136
137
static bool extra_root_certs_loaded = false;
138
139
// Just to generate static methods
140
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
141
                                           Local<FunctionTemplate> t);
142
template void SSLWrap<TLSWrap>::ConfigureSecureContext(SecureContext* sc);
143
template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc);
144
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
145
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
146
    SSL* s,
147
    const unsigned char* key,
148
    int len,
149
    int* copy);
150
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
151
                                                  SSL_SESSION* sess);
152
template void SSLWrap<TLSWrap>::OnClientHello(
153
    void* arg,
154
    const ClientHelloParser::ClientHello& hello);
155
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
156
template void SSLWrap<TLSWrap>::DestroySSL();
157
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
158
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
159
template int SSLWrap<TLSWrap>::SelectALPNCallback(
160
    SSL* s,
161
    const unsigned char** out,
162
    unsigned char* outlen,
163
    const unsigned char* in,
164
    unsigned int inlen,
165
    void* arg);
166
167
79
static int PasswordCallback(char* buf, int size, int rwflag, void* u) {
168
79
  const char* passphrase = static_cast<char*>(u);
169
79
  if (passphrase != nullptr) {
170
73
    size_t buflen = static_cast<size_t>(size);
171
73
    size_t len = strlen(passphrase);
172
73
    if (buflen < len)
173
1
      return -1;
174
72
    memcpy(buf, passphrase, len);
175
72
    return len;
176
  }
177
178
6
  return -1;
179
}
180
181
// Loads OpenSSL engine by engine id and returns it. The loaded engine
182
// gets a reference so remember the corresponding call to ENGINE_free.
183
// In case of error the appropriate js exception is scheduled
184
// and nullptr is returned.
185
#ifndef OPENSSL_NO_ENGINE
186
2
static ENGINE* LoadEngineById(const char* engine_id, char (*errmsg)[1024]) {
187
2
  MarkPopErrorOnReturn mark_pop_error_on_return;
188
189
2
  ENGINE* engine = ENGINE_by_id(engine_id);
190
191
2
  if (engine == nullptr) {
192
    // Engine not found, try loading dynamically.
193
2
    engine = ENGINE_by_id("dynamic");
194
2
    if (engine != nullptr) {
195

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









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

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

62
  if (err != 0 || message == nullptr) {
388
52
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
389
52
    message = message_buffer;
390
  }
391
62
  HandleScope scope(env->isolate());
392
  Local<String> exception_string =
393
62
      String::NewFromUtf8(env->isolate(), message, NewStringType::kNormal)
394
124
      .ToLocalChecked();
395
122
  CryptoErrorVector errors;
396
62
  errors.Capture();
397
  Local<Value> exception;
398
124
  if (!errors.ToException(env, exception_string).ToLocal(&exception))
399
1
    return;
400
  Local<Object> obj;
401
183
  if (!exception->ToObject(env->context()).ToLocal(&obj))
402
    return;
403
122
  if (error::Decorate(env, obj, err).IsNothing())
404
1
    return;
405
120
  env->isolate()->ThrowException(exception);
406
}
407
408
409
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
410
// The entropy pool starts out empty and needs to fill up before the PRNG
411
// can be used securely.  Once the pool is filled, it never dries up again;
412
// its contents is stirred and reused when necessary.
413
//
414
// OpenSSL normally fills the pool automatically but not when someone starts
415
// generating random numbers before the pool is full: in that case OpenSSL
416
// keeps lowering the entropy estimate to thwart attackers trying to guess
417
// the initial state of the PRNG.
418
//
419
// When that happens, we will have to wait until enough entropy is available.
420
// That should normally never take longer than a few milliseconds.
421
//
422
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
423
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
424
// block under normal circumstances.
425
//
426
// The only time when /dev/urandom may conceivably block is right after boot,
427
// when the whole system is still low on entropy.  That's not something we can
428
// do anything about.
429
9411
inline void CheckEntropy() {
430
  for (;;) {
431
9411
    int status = RAND_status();
432
9411
    CHECK_GE(status, 0);  // Cannot fail.
433
9411
    if (status != 0)
434
18822
      break;
435
436
    // Give up, RAND_poll() not supported.
437
    if (RAND_poll() == 0)
438
      break;
439
  }
440
9411
}
441
442
443
9199
bool EntropySource(unsigned char* buffer, size_t length) {
444
  // Ensure that OpenSSL's PRNG is properly seeded.
445
9199
  CheckEntropy();
446
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
447
  // random. That's okay, it's still better than V8's stock source of entropy,
448
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
449
9199
  return RAND_bytes(buffer, length) != -1;
450
}
451
452
453
template <typename T>
454
1119
static T* MallocOpenSSL(size_t count) {
455
1119
  void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
456



1119
  CHECK_IMPLIES(mem == nullptr, count == 0);
457
1119
  return static_cast<T*>(mem);
458
}
459
460
461
600
void SecureContext::Initialize(Environment* env, Local<Object> target) {
462
600
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
463
1200
  t->InstanceTemplate()->SetInternalFieldCount(1);
464
  Local<String> secureContextString =
465
600
      FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext");
466
600
  t->SetClassName(secureContextString);
467
468
600
  env->SetProtoMethod(t, "init", Init);
469
600
  env->SetProtoMethod(t, "setKey", SetKey);
470
600
  env->SetProtoMethod(t, "setCert", SetCert);
471
600
  env->SetProtoMethod(t, "addCACert", AddCACert);
472
600
  env->SetProtoMethod(t, "addCRL", AddCRL);
473
600
  env->SetProtoMethod(t, "addRootCerts", AddRootCerts);
474
600
  env->SetProtoMethod(t, "setCipherSuites", SetCipherSuites);
475
600
  env->SetProtoMethod(t, "setCiphers", SetCiphers);
476
600
  env->SetProtoMethod(t, "setECDHCurve", SetECDHCurve);
477
600
  env->SetProtoMethod(t, "setDHParam", SetDHParam);
478
600
  env->SetProtoMethod(t, "setMaxProto", SetMaxProto);
479
600
  env->SetProtoMethod(t, "setMinProto", SetMinProto);
480
600
  env->SetProtoMethod(t, "getMaxProto", GetMaxProto);
481
600
  env->SetProtoMethod(t, "getMinProto", GetMinProto);
482
600
  env->SetProtoMethod(t, "setOptions", SetOptions);
483
600
  env->SetProtoMethod(t, "setSessionIdContext", SetSessionIdContext);
484
600
  env->SetProtoMethod(t, "setSessionTimeout", SetSessionTimeout);
485
600
  env->SetProtoMethod(t, "close", Close);
486
600
  env->SetProtoMethod(t, "loadPKCS12", LoadPKCS12);
487
#ifndef OPENSSL_NO_ENGINE
488
600
  env->SetProtoMethod(t, "setClientCertEngine", SetClientCertEngine);
489
#endif  // !OPENSSL_NO_ENGINE
490
600
  env->SetProtoMethodNoSideEffect(t, "getTicketKeys", GetTicketKeys);
491
600
  env->SetProtoMethod(t, "setTicketKeys", SetTicketKeys);
492
600
  env->SetProtoMethod(t, "setFreeListLength", SetFreeListLength);
493
600
  env->SetProtoMethod(t, "enableTicketKeyCallback", EnableTicketKeyCallback);
494
600
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate<true>);
495
600
  env->SetProtoMethodNoSideEffect(t, "getIssuer", GetCertificate<false>);
496
497
#define SET_INTEGER_CONSTANTS(name, value)                                     \
498
    t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), name),                        \
499
           Integer::NewFromUnsigned(env->isolate(), value));
500
1800
  SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex);
501
1800
  SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex);
502
1800
  SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex);
503
1800
  SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex);
504
1800
  SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex);
505
506
#undef SET_INTEGER_CONSTANTS
507
508
  Local<FunctionTemplate> ctx_getter_templ =
509
      FunctionTemplate::New(env->isolate(),
510
                            CtxGetter,
511
                            env->as_callback_data(),
512
1200
                            Signature::New(env->isolate(), t));
513
514
515
1800
  t->PrototypeTemplate()->SetAccessorProperty(
516
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
517
      ctx_getter_templ,
518
      Local<FunctionTemplate>(),
519
1800
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
520
521
  target->Set(env->context(), secureContextString,
522
3000
              t->GetFunction(env->context()).ToLocalChecked()).Check();
523
600
  env->set_secure_context_constructor_template(t);
524
600
}
525
526
527
2273
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
528
2273
  Environment* env = Environment::GetCurrent(args);
529
2273
  new SecureContext(env, args.This());
530
2273
}
531
532
// A maxVersion of 0 means "any", but OpenSSL may support TLS versions that
533
// Node.js doesn't, so pin the max to what we do support.
534
const int MAX_SUPPORTED_VERSION = TLS1_3_VERSION;
535
536
2273
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
537
  SecureContext* sc;
538
2322
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
539
2273
  Environment* env = sc->env();
540
541
2273
  CHECK_EQ(args.Length(), 3);
542
4546
  CHECK(args[1]->IsInt32());
543
4546
  CHECK(args[2]->IsInt32());
544
545
6819
  int min_version = args[1].As<Int32>()->Value();
546
6819
  int max_version = args[2].As<Int32>()->Value();
547
2273
  const SSL_METHOD* method = TLS_method();
548
549
2273
  if (max_version == 0)
550
    max_version = MAX_SUPPORTED_VERSION;
551
552
6819
  if (args[0]->IsString()) {
553
362
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
554
555
    // Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends
556
    // are still accepted.  They are OpenSSL's way of saying that all known
557
    // protocols below TLS 1.3 are supported unless explicitly disabled (which
558
    // we do below for SSLv2 and SSLv3.)
559
362
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
560
15
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
561
15
      return;
562
347
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
563
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
564
1
      return;
565
346
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
566
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
567
1
      return;
568
345
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
569
15
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
570
15
      return;
571
330
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
572
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
573
1
      return;
574
329
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
575
1
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
576
1
      return;
577
328
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
578
36
      max_version = TLS1_2_VERSION;
579
292
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
580
1
      max_version = TLS1_2_VERSION;
581
1
      method = TLS_server_method();
582
291
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
583
1
      max_version = TLS1_2_VERSION;
584
1
      method = TLS_client_method();
585
290
    } else if (strcmp(*sslmethod, "TLS_method") == 0) {
586
53
      min_version = 0;
587
53
      max_version = MAX_SUPPORTED_VERSION;
588
237
    } else if (strcmp(*sslmethod, "TLS_server_method") == 0) {
589
      min_version = 0;
590
      max_version = MAX_SUPPORTED_VERSION;
591
      method = TLS_server_method();
592
237
    } else if (strcmp(*sslmethod, "TLS_client_method") == 0) {
593
      min_version = 0;
594
      max_version = MAX_SUPPORTED_VERSION;
595
      method = TLS_client_method();
596
237
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
597
71
      min_version = TLS1_VERSION;
598
71
      max_version = TLS1_VERSION;
599
166
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
600
1
      min_version = TLS1_VERSION;
601
1
      max_version = TLS1_VERSION;
602
1
      method = TLS_server_method();
603
165
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
604
1
      min_version = TLS1_VERSION;
605
1
      max_version = TLS1_VERSION;
606
1
      method = TLS_client_method();
607
164
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
608
71
      min_version = TLS1_1_VERSION;
609
71
      max_version = TLS1_1_VERSION;
610
93
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
611
1
      min_version = TLS1_1_VERSION;
612
1
      max_version = TLS1_1_VERSION;
613
1
      method = TLS_server_method();
614
92
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
615
1
      min_version = TLS1_1_VERSION;
616
1
      max_version = TLS1_1_VERSION;
617
1
      method = TLS_client_method();
618
91
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
619
73
      min_version = TLS1_2_VERSION;
620
73
      max_version = TLS1_2_VERSION;
621
18
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
622
2
      min_version = TLS1_2_VERSION;
623
2
      max_version = TLS1_2_VERSION;
624
2
      method = TLS_server_method();
625
16
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
626
1
      min_version = TLS1_2_VERSION;
627
1
      max_version = TLS1_2_VERSION;
628
1
      method = TLS_client_method();
629
    } else {
630
15
      const std::string msg("Unknown method: ");
631
15
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, (msg + * sslmethod).c_str());
632
15
      return;
633
313
    }
634
  }
635
636
2224
  sc->ctx_.reset(SSL_CTX_new(method));
637
2224
  SSL_CTX_set_app_data(sc->ctx_.get(), sc);
638
639
  // Disable SSLv2 in the case when method == TLS_method() and the
640
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
641
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
642
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
643
2224
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv2);
644
2224
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv3);
645
646
  // Enable automatic cert chaining. This is enabled by default in OpenSSL, but
647
  // disabled by default in BoringSSL. Enable it explicitly to make the
648
  // behavior match when Node is built with BoringSSL.
649
2224
  SSL_CTX_clear_mode(sc->ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
650
651
  // SSL session cache configuration
652
2224
  SSL_CTX_set_session_cache_mode(sc->ctx_.get(),
653
                                 SSL_SESS_CACHE_CLIENT |
654
                                 SSL_SESS_CACHE_SERVER |
655
                                 SSL_SESS_CACHE_NO_INTERNAL |
656
2224
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
657
658
2224
  SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version);
659
2224
  SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version);
660
661
  // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was
662
  // exposed in the public API. To retain compatibility, install a callback
663
  // which restores the old algorithm.
664

6672
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
665

4448
      RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 ||
666
2224
      RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) {
667
    return env->ThrowError("Error generating ticket keys");
668
  }
669
2224
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
670
}
671
672
673
// Takes a string or buffer and loads it into a BIO.
674
// Caller responsible for BIO_free_all-ing the returned object.
675
2190
static BIOPointer LoadBIO(Environment* env, Local<Value> v) {
676
2190
  HandleScope scope(env->isolate());
677
678
4380
  if (v->IsString()) {
679
1275
    const node::Utf8Value s(env->isolate(), v);
680
1275
    return NodeBIO::NewFixed(*s, s.length());
681
  }
682
683
915
  if (v->IsArrayBufferView()) {
684
915
    ArrayBufferViewContents<char> buf(v.As<ArrayBufferView>());
685
915
    return NodeBIO::NewFixed(buf.data(), buf.length());
686
  }
687
688
  return nullptr;
689
}
690
691
692
802
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
693
802
  Environment* env = Environment::GetCurrent(args);
694
695
  SecureContext* sc;
696
812
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
697
698
802
  unsigned int len = args.Length();
699
802
  if (len < 1) {
700
    return THROW_ERR_MISSING_ARGS(env, "Private key argument is mandatory");
701
  }
702
703
802
  if (len > 2) {
704
    return env->ThrowError("Only private key and pass phrase are expected");
705
  }
706
707
802
  if (len == 2) {
708


3286
    if (args[1]->IsUndefined() || args[1]->IsNull())
709
776
      len = 1;
710
    else
711
78
      THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase");
712
  }
713
714
800
  BIOPointer bio(LoadBIO(env, args[0]));
715
800
  if (!bio)
716
    return;
717
718
1592
  node::Utf8Value passphrase(env->isolate(), args[1]);
719
720
  EVPKeyPointer key(
721
      PEM_read_bio_PrivateKey(bio.get(),
722
                              nullptr,
723
                              PasswordCallback,
724
1592
                              *passphrase));
725
726
800
  if (!key) {
727
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
728
7
    if (!err) {
729
      return env->ThrowError("PEM_read_bio_PrivateKey");
730
    }
731
7
    return ThrowCryptoError(env, err);
732
  }
733
734
793
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
735
736
793
  if (!rv) {
737
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
738
1
    if (!err)
739
      return env->ThrowError("SSL_CTX_use_PrivateKey");
740
1
    return ThrowCryptoError(env, err);
741
792
  }
742
}
743
744
745
788
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
746
788
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
747
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
748
788
      X509_STORE_CTX_new());
749
1576
  return store_ctx.get() != nullptr &&
750

1576
         X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
751
1576
         X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1;
752
}
753
754
755
830
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
756
                                  X509Pointer&& x,
757
                                  STACK_OF(X509)* extra_certs,
758
                                  X509Pointer* cert,
759
                                  X509Pointer* issuer_) {
760
830
  CHECK(!*issuer_);
761
830
  CHECK(!*cert);
762
830
  X509* issuer = nullptr;
763
764
830
  int ret = SSL_CTX_use_certificate(ctx, x.get());
765
766
830
  if (ret) {
767
    // If we could set up our certificate, now proceed to
768
    // the CA certificates.
769
830
    SSL_CTX_clear_extra_chain_certs(ctx);
770
771
1235
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
772
405
      X509* ca = sk_X509_value(extra_certs, i);
773
774
      // NOTE: Increments reference count on `ca`
775
405
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
776
        ret = 0;
777
        issuer = nullptr;
778
        break;
779
      }
780
      // Note that we must not free r if it was successfully
781
      // added to the chain (while we must free the main
782
      // certificate, since its reference count is increased
783
      // by SSL_CTX_use_certificate).
784
785
      // Find issuer
786

405
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
787
4
        continue;
788
789
401
      issuer = ca;
790
    }
791
  }
792
793
  // Try getting issuer from a cert store
794
830
  if (ret) {
795
830
    if (issuer == nullptr) {
796
429
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
797
429
      ret = ret < 0 ? 0 : 1;
798
      // NOTE: get_cert_store doesn't increment reference count,
799
      // no need to free `store`
800
    } else {
801
      // Increment issuer reference count
802
401
      issuer = X509_dup(issuer);
803
401
      if (issuer == nullptr) {
804
        ret = 0;
805
      }
806
    }
807
  }
808
809
830
  issuer_->reset(issuer);
810
811

830
  if (ret && x != nullptr) {
812
830
    cert->reset(X509_dup(x.get()));
813
830
    if (!*cert)
814
      ret = 0;
815
  }
816
830
  return ret;
817
}
818
819
820
// Read a file that contains our certificate in "PEM" format,
821
// possibly followed by a sequence of CA certificates that should be
822
// sent to the peer in the Certificate message.
823
//
824
// Taken from OpenSSL - edited for style.
825
818
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
826
                                  BIOPointer&& in,
827
                                  X509Pointer* cert,
828
                                  X509Pointer* issuer) {
829
  // Just to ensure that `ERR_peek_last_error` below will return only errors
830
  // that we are interested in
831
818
  ERR_clear_error();
832
833
  X509Pointer x(
834
818
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
835
836
818
  if (!x)
837
    return 0;
838
839
818
  unsigned long err = 0;  // NOLINT(runtime/int)
840
841
1636
  StackOfX509 extra_certs(sk_X509_new_null());
842
818
  if (!extra_certs)
843
    return 0;
844
845
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
846
                                    nullptr,
847
                                    NoPasswordCallback,
848
1214
                                    nullptr)}) {
849
396
    if (sk_X509_push(extra_certs.get(), extra.get())) {
850
396
      extra.release();
851
396
      continue;
852
    }
853
854
    return 0;
855
  }
856
857
  // When the while loop ends, it's usually just EOF.
858
818
  err = ERR_peek_last_error();
859

1636
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
860
818
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
861
818
    ERR_clear_error();
862
  } else {
863
    // some real error
864
    return 0;
865
  }
866
867
  return SSL_CTX_use_certificate_chain(ctx,
868
818
                                       std::move(x),
869
                                       extra_certs.get(),
870
                                       cert,
871
2454
                                       issuer);
872
}
873
874
875
818
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
876
818
  Environment* env = Environment::GetCurrent(args);
877
878
  SecureContext* sc;
879
818
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
880
881
818
  if (args.Length() != 1) {
882
    return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory");
883
  }
884
885
818
  BIOPointer bio(LoadBIO(env, args[0]));
886
818
  if (!bio)
887
    return;
888
889
818
  sc->cert_.reset();
890
818
  sc->issuer_.reset();
891
892
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(),
893
818
                                         std::move(bio),
894
                                         &sc->cert_,
895
1636
                                         &sc->issuer_);
896
897
818
  if (!rv) {
898
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
899
    if (!err) {
900
      return env->ThrowError("SSL_CTX_use_certificate_chain");
901
    }
902
    return ThrowCryptoError(env, err);
903
818
  }
904
}
905
906
907
244
static X509_STORE* NewRootCertStore() {
908

244
  static std::vector<X509*> root_certs_vector;
909

244
  static Mutex root_certs_vector_mutex;
910
244
  Mutex::ScopedLock lock(root_certs_vector_mutex);
911
912
244
  if (root_certs_vector.empty()) {
913
33276
    for (size_t i = 0; i < arraysize(root_certs); i++) {
914
      X509* x509 =
915
33040
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
916
33040
                                              strlen(root_certs[i])).get(),
917
                            nullptr,   // no re-use of X509 structure
918
                            NoPasswordCallback,
919
66080
                            nullptr);  // no callback data
920
921
      // Parse errors from the built-in roots are fatal.
922
33040
      CHECK_NOT_NULL(x509);
923
924
33040
      root_certs_vector.push_back(x509);
925
    }
926
  }
927
928
244
  X509_STORE* store = X509_STORE_new();
929
244
  if (*system_cert_path != '\0') {
930
    X509_STORE_load_locations(store, system_cert_path, nullptr);
931
  }
932
244
  if (per_process::cli_options->ssl_openssl_cert_store) {
933
    X509_STORE_set_default_paths(store);
934
  } else {
935
34404
    for (X509* cert : root_certs_vector) {
936
34160
      X509_up_ref(cert);
937
34160
      X509_STORE_add_cert(store, cert);
938
    }
939
  }
940
941
244
  return store;
942
}
943
944
945
542
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
946
542
  Environment* env = Environment::GetCurrent(args);
947
948
  SecureContext* sc;
949
542
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
950
  ClearErrorOnReturn clear_error_on_return;
951
952
542
  if (args.Length() != 1) {
953
    return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory");
954
  }
955
956
1084
  BIOPointer bio(LoadBIO(env, args[0]));
957
542
  if (!bio)
958
    return;
959
960
542
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
961
  while (X509* x509 = PEM_read_bio_X509_AUX(
962
1415
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
963
873
    if (cert_store == root_cert_store) {
964
2
      cert_store = NewRootCertStore();
965
2
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
966
    }
967
873
    X509_STORE_add_cert(cert_store, x509);
968
873
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
969
873
    X509_free(x509);
970
542
  }
971
}
972
973
974
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
975
2
  Environment* env = Environment::GetCurrent(args);
976
977
  SecureContext* sc;
978
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
979
980
2
  if (args.Length() != 1) {
981
    return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory");
982
  }
983
984
  ClearErrorOnReturn clear_error_on_return;
985
986
3
  BIOPointer bio(LoadBIO(env, args[0]));
987
2
  if (!bio)
988
    return;
989
990
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
991
3
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
992
993
2
  if (!crl)
994
1
    return env->ThrowError("Failed to parse CRL");
995
996
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
997
1
  if (cert_store == root_cert_store) {
998
    cert_store = NewRootCertStore();
999
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1000
  }
1001
1002
1
  X509_STORE_add_crl(cert_store, crl.get());
1003
  X509_STORE_set_flags(cert_store,
1004
2
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1005
}
1006
1007
1008
3
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1009
    X509_STORE* store,
1010
    const char* file) {
1011
3
  ERR_clear_error();
1012
3
  MarkPopErrorOnReturn mark_pop_error_on_return;
1013
1014
6
  BIOPointer bio(BIO_new_file(file, "r"));
1015
3
  if (!bio)
1016
1
    return ERR_get_error();
1017
1018
  while (X509* x509 =
1019
4
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1020
2
    X509_STORE_add_cert(store, x509);
1021
2
    X509_free(x509);
1022
  }
1023
1024
2
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1025
  // Ignore error if its EOF/no start line found.
1026

4
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1027
2
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1028
2
    return 0;
1029
  }
1030
1031
3
  return err;
1032
}
1033
1034
1035
3
void UseExtraCaCerts(const std::string& file) {
1036
  ClearErrorOnReturn clear_error_on_return;
1037
1038
3
  if (root_cert_store == nullptr) {
1039
3
    root_cert_store = NewRootCertStore();
1040
1041
3
    if (!file.empty()) {
1042
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1043
                                           root_cert_store,
1044
3
                                           file.c_str());
1045
3
      if (err) {
1046
        fprintf(stderr,
1047
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
1048
                file.c_str(),
1049
1
                ERR_error_string(err, nullptr));
1050
      } else {
1051
2
        extra_root_certs_loaded = true;
1052
      }
1053
    }
1054
3
  }
1055
3
}
1056
1057
1058
static void IsExtraRootCertsFileLoaded(
1059
    const FunctionCallbackInfo<Value>& args) {
1060
  return args.GetReturnValue().Set(extra_root_certs_loaded);
1061
}
1062
1063
1064
1703
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
1065
  SecureContext* sc;
1066
3406
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1067
  ClearErrorOnReturn clear_error_on_return;
1068
1069
1703
  if (root_cert_store == nullptr) {
1070
233
    root_cert_store = NewRootCertStore();
1071
  }
1072
1073
  // Increment reference count so global store is not deleted along with CTX.
1074
1703
  X509_STORE_up_ref(root_cert_store);
1075
1703
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
1076
}
1077
1078
1079
2155
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
1080
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
1081
#ifndef OPENSSL_IS_BORINGSSL
1082
  SecureContext* sc;
1083
2156
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1084
2155
  Environment* env = sc->env();
1085
  ClearErrorOnReturn clear_error_on_return;
1086
1087
2155
  CHECK_EQ(args.Length(), 1);
1088
6465
  CHECK(args[0]->IsString());
1089
1090
4309
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1091
2155
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers)) {
1092
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1093
1
    if (!err) {
1094
      // This would be an OpenSSL bug if it happened.
1095
      return env->ThrowError("Failed to set ciphers");
1096
    }
1097
1
    return ThrowCryptoError(env, err);
1098
2154
  }
1099
#endif
1100
}
1101
1102
1103
2157
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
1104
  SecureContext* sc;
1105
2170
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1106
2157
  Environment* env = sc->env();
1107
  ClearErrorOnReturn clear_error_on_return;
1108
1109
2157
  CHECK_EQ(args.Length(), 1);
1110
6471
  CHECK(args[0]->IsString());
1111
1112
4301
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1113
2157
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
1114
13
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1115
13
    if (!err) {
1116
      // This would be an OpenSSL bug if it happened.
1117
      return env->ThrowError("Failed to set ciphers");
1118
    }
1119
1120

13
    if (strlen(*ciphers) == 0 && ERR_GET_REASON(err) == SSL_R_NO_CIPHER_MATCH) {
1121
      // TLS1.2 ciphers were deliberately cleared, so don't consider
1122
      // SSL_R_NO_CIPHER_MATCH to be an error (this is how _set_cipher_suites()
1123
      // works). If the user actually sets a value (like "no-such-cipher"), then
1124
      // that's actually an error.
1125
9
      return;
1126
    }
1127
4
    return ThrowCryptoError(env, err);
1128
2144
  }
1129
}
1130
1131
1132
2150
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
1133
  SecureContext* sc;
1134
4293
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1135
2150
  Environment* env = sc->env();
1136
1137
2150
  if (args.Length() != 1)
1138
    return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory");
1139
1140
6450
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name");
1141
1142
2149
  node::Utf8Value curve(env->isolate(), args[0]);
1143
1144
2149
  if (strcmp(*curve, "auto") == 0)
1145
2139
    return;
1146
1147
10
  if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve))
1148
3
    return env->ThrowError("Failed to set ECDH curve");
1149
}
1150
1151
1152
10
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
1153
  SecureContext* sc;
1154
13
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
1155
10
  Environment* env = sc->env();
1156
  ClearErrorOnReturn clear_error_on_return;
1157
1158
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
1159
  // to be specified explicitly
1160
10
  if (args.Length() != 1)
1161
    return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory");
1162
1163
17
  DHPointer dh;
1164
  {
1165
10
    BIOPointer bio(LoadBIO(env, args[0]));
1166
10
    if (!bio)
1167
      return;
1168
1169
10
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
1170
  }
1171
1172
  // Invalid dhparam is silently discarded and DHE is no longer used.
1173
10
  if (!dh)
1174
1
    return;
1175
1176
  const BIGNUM* p;
1177
9
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
1178
9
  const int size = BN_num_bits(p);
1179
9
  if (size < 1024) {
1180
    return THROW_ERR_INVALID_ARG_VALUE(
1181
2
        env, "DH parameter is less than 1024 bits");
1182
7
  } else if (size < 2048) {
1183
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1184
9
        env->isolate(), "DH parameter is less than 2048 bits"));
1185
  }
1186
1187
7
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
1188
7
  int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get());
1189
1190
7
  if (!r)
1191
7
    return env->ThrowTypeError("Error setting temp DH parameter");
1192
}
1193
1194
1195
9
void SecureContext::SetMinProto(const FunctionCallbackInfo<Value>& args) {
1196
  SecureContext* sc;
1197
18
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1198
1199
9
  CHECK_EQ(args.Length(), 1);
1200
18
  CHECK(args[0]->IsInt32());
1201
1202
27
  int version = args[0].As<Int32>()->Value();
1203
1204
9
  CHECK(SSL_CTX_set_min_proto_version(sc->ctx_.get(), version));
1205
}
1206
1207
1208
43
void SecureContext::SetMaxProto(const FunctionCallbackInfo<Value>& args) {
1209
  SecureContext* sc;
1210
86
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1211
1212
43
  CHECK_EQ(args.Length(), 1);
1213
86
  CHECK(args[0]->IsInt32());
1214
1215
129
  int version = args[0].As<Int32>()->Value();
1216
1217
43
  CHECK(SSL_CTX_set_max_proto_version(sc->ctx_.get(), version));
1218
}
1219
1220
1221
52
void SecureContext::GetMinProto(const FunctionCallbackInfo<Value>& args) {
1222
  SecureContext* sc;
1223
104
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1224
1225
52
  CHECK_EQ(args.Length(), 0);
1226
1227
  long version =  // NOLINT(runtime/int)
1228
52
    SSL_CTX_get_min_proto_version(sc->ctx_.get());
1229
156
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1230
}
1231
1232
1233
71
void SecureContext::GetMaxProto(const FunctionCallbackInfo<Value>& args) {
1234
  SecureContext* sc;
1235
142
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1236
1237
71
  CHECK_EQ(args.Length(), 0);
1238
1239
  long version =  // NOLINT(runtime/int)
1240
71
    SSL_CTX_get_max_proto_version(sc->ctx_.get());
1241
213
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1242
}
1243
1244
1245
794
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1246
  SecureContext* sc;
1247
794
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1248
  int64_t val;
1249
1250

3970
  if (args.Length() != 1 ||
1251

4764
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1252
    return THROW_ERR_INVALID_ARG_TYPE(
1253
        sc->env(), "Options must be an integer value");
1254
  }
1255
1256
  SSL_CTX_set_options(sc->ctx_.get(),
1257
794
                      static_cast<long>(val));  // NOLINT(runtime/int)
1258
}
1259
1260
1261
725
void SecureContext::SetSessionIdContext(
1262
    const FunctionCallbackInfo<Value>& args) {
1263
  SecureContext* sc;
1264
1450
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1265
725
  Environment* env = sc->env();
1266
1267
725
  if (args.Length() != 1) {
1268
    return THROW_ERR_MISSING_ARGS(
1269
        env, "Session ID context argument is mandatory");
1270
  }
1271
1272
2175
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1273
1274
725
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1275
  const unsigned char* sid_ctx =
1276
725
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1277
725
  unsigned int sid_ctx_len = sessionIdContext.length();
1278
1279
725
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1280
725
  if (r == 1)
1281
725
    return;
1282
1283
  BUF_MEM* mem;
1284
  Local<String> message;
1285
1286
  BIOPointer bio(BIO_new(BIO_s_mem()));
1287
  if (!bio) {
1288
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1289
                                    "SSL_CTX_set_session_id_context error");
1290
  } else {
1291
    ERR_print_errors(bio.get());
1292
    BIO_get_mem_ptr(bio.get(), &mem);
1293
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1294
  }
1295
1296
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1297
}
1298
1299
1300
2
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1301
  SecureContext* sc;
1302
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1303
1304


8
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1305
    return THROW_ERR_INVALID_ARG_TYPE(
1306
1
        sc->env(), "Session timeout must be a 32-bit integer");
1307
  }
1308
1309
3
  int32_t sessionTimeout = args[0].As<Int32>()->Value();
1310
1
  SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
1311
}
1312
1313
1314
1284
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1315
  SecureContext* sc;
1316
2568
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1317
1284
  sc->Reset();
1318
}
1319
1320
1321
// Takes .pfx or .p12 and password in string or buffer format
1322
18
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1323
18
  Environment* env = Environment::GetCurrent(args);
1324
1325
18
  std::vector<char> pass;
1326
18
  bool ret = false;
1327
1328
  SecureContext* sc;
1329
18
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1330
12
  ClearErrorOnReturn clear_error_on_return;
1331
1332
18
  if (args.Length() < 1) {
1333
    return THROW_ERR_MISSING_ARGS(env, "PFX certificate argument is mandatory");
1334
  }
1335
1336
30
  BIOPointer in(LoadBIO(env, args[0]));
1337
18
  if (!in)
1338
    return env->ThrowError("Unable to load BIO");
1339
1340
18
  if (args.Length() >= 2) {
1341
15
    THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase");
1342
30
    Local<ArrayBufferView> abv = args[1].As<ArrayBufferView>();
1343
15
    size_t passlen = abv->ByteLength();
1344
15
    pass.resize(passlen + 1);
1345
30
    abv->CopyContents(pass.data(), passlen);
1346
15
    pass[passlen] = '\0';
1347
  }
1348
1349
  // Free previous certs
1350
18
  sc->issuer_.reset();
1351
18
  sc->cert_.reset();
1352
1353
18
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1354
1355
30
  DeleteFnPtr<PKCS12, PKCS12_free> p12;
1356
30
  EVPKeyPointer pkey;
1357
30
  X509Pointer cert;
1358
30
  StackOfX509 extra_certs;
1359
1360
18
  PKCS12* p12_ptr = nullptr;
1361
18
  EVP_PKEY* pkey_ptr = nullptr;
1362
18
  X509* cert_ptr = nullptr;
1363
18
  STACK_OF(X509)* extra_certs_ptr = nullptr;
1364
36
  if (d2i_PKCS12_bio(in.get(), &p12_ptr) &&
1365
32
      (p12.reset(p12_ptr), true) &&  // Move ownership to the smart pointer.
1366
16
      PKCS12_parse(p12.get(), pass.data(),
1367
                   &pkey_ptr,
1368
                   &cert_ptr,
1369
16
                   &extra_certs_ptr) &&
1370
12
      (pkey.reset(pkey_ptr), cert.reset(cert_ptr),
1371
24
       extra_certs.reset(extra_certs_ptr), true) &&  // Move ownership.
1372
      SSL_CTX_use_certificate_chain(sc->ctx_.get(),
1373
12
                                    std::move(cert),
1374
                                    extra_certs.get(),
1375
                                    &sc->cert_,
1376

54
                                    &sc->issuer_) &&
1377
12
      SSL_CTX_use_PrivateKey(sc->ctx_.get(), pkey.get())) {
1378
    // Add CA certs too
1379
21
    for (int i = 0; i < sk_X509_num(extra_certs.get()); i++) {
1380
9
      X509* ca = sk_X509_value(extra_certs.get(), i);
1381
1382
9
      if (cert_store == root_cert_store) {
1383
6
        cert_store = NewRootCertStore();
1384
6
        SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1385
      }
1386
9
      X509_STORE_add_cert(cert_store, ca);
1387
9
      SSL_CTX_add_client_CA(sc->ctx_.get(), ca);
1388
    }
1389
12
    ret = true;
1390
  }
1391
1392
18
  if (!ret) {
1393
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1394
6
    const char* str = ERR_reason_error_string(err);
1395
6
    return env->ThrowError(str);
1396
12
  }
1397
}
1398
1399
1400
#ifndef OPENSSL_NO_ENGINE
1401
// Helper for the smart pointer.
1402
void ENGINE_free_fn(ENGINE* engine) { ENGINE_free(engine); }
1403
1404
void SecureContext::SetClientCertEngine(
1405
    const FunctionCallbackInfo<Value>& args) {
1406
  Environment* env = Environment::GetCurrent(args);
1407
  CHECK_EQ(args.Length(), 1);
1408
  CHECK(args[0]->IsString());
1409
1410
  SecureContext* sc;
1411
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1412
1413
  MarkPopErrorOnReturn mark_pop_error_on_return;
1414
1415
  // SSL_CTX_set_client_cert_engine does not itself support multiple
1416
  // calls by cleaning up before overwriting the client_cert_engine
1417
  // internal context variable.
1418
  // Instead of trying to fix up this problem we in turn also do not
1419
  // support multiple calls to SetClientCertEngine.
1420
  if (sc->client_cert_engine_provided_) {
1421
    return env->ThrowError(
1422
        "Multiple calls to SetClientCertEngine are not allowed");
1423
  }
1424
1425
  const node::Utf8Value engine_id(env->isolate(), args[0]);
1426
  char errmsg[1024];
1427
  DeleteFnPtr<ENGINE, ENGINE_free_fn> engine(
1428
      LoadEngineById(*engine_id, &errmsg));
1429
1430
  if (!engine)
1431
    return env->ThrowError(errmsg);
1432
1433
  // Note that this takes another reference to `engine`.
1434
  int r = SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get());
1435
  if (r == 0)
1436
    return ThrowCryptoError(env, ERR_get_error());
1437
  sc->client_cert_engine_provided_ = true;
1438
}
1439
#endif  // !OPENSSL_NO_ENGINE
1440
1441
1442
10
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1443
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1444
1445
  SecureContext* wrap;
1446
20
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1447
1448
20
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1449
10
  memcpy(Buffer::Data(buff), wrap->ticket_key_name_, 16);
1450
10
  memcpy(Buffer::Data(buff) + 16, wrap->ticket_key_hmac_, 16);
1451
10
  memcpy(Buffer::Data(buff) + 32, wrap->ticket_key_aes_, 16);
1452
1453
20
  args.GetReturnValue().Set(buff);
1454
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1455
}
1456
1457
1458
25
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1459
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1460
  SecureContext* wrap;
1461
27
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1462
25
  Environment* env = wrap->env();
1463
1464
  // TODO(@sam-github) Move type and len check to js, and CHECK() in C++.
1465
25
  if (args.Length() < 1) {
1466
    return THROW_ERR_MISSING_ARGS(env, "Ticket keys argument is mandatory");
1467
  }
1468
1469
25
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Ticket keys");
1470
48
  ArrayBufferViewContents<char> buf(args[0].As<ArrayBufferView>());
1471
1472
24
  if (buf.length() != 48) {
1473
    return THROW_ERR_INVALID_ARG_VALUE(
1474
1
        env, "Ticket keys length must be 48 bytes");
1475
  }
1476
1477
23
  memcpy(wrap->ticket_key_name_, buf.data(), 16);
1478
23
  memcpy(wrap->ticket_key_hmac_, buf.data() + 16, 16);
1479
23
  memcpy(wrap->ticket_key_aes_, buf.data() + 32, 16);
1480
1481
46
  args.GetReturnValue().Set(true);
1482
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1483
}
1484
1485
1486
1310
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1487
1310
}
1488
1489
1490
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1491
// the regression test in test/parallel/test-https-resume-after-renew.js.
1492
1
void SecureContext::EnableTicketKeyCallback(
1493
    const FunctionCallbackInfo<Value>& args) {
1494
  SecureContext* wrap;
1495
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1496
1497
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback);
1498
}
1499
1500
1501
4
int SecureContext::TicketKeyCallback(SSL* ssl,
1502
                                     unsigned char* name,
1503
                                     unsigned char* iv,
1504
                                     EVP_CIPHER_CTX* ectx,
1505
                                     HMAC_CTX* hctx,
1506
                                     int enc) {
1507
  static const int kTicketPartSize = 16;
1508
1509
  SecureContext* sc = static_cast<SecureContext*>(
1510
4
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1511
1512
4
  Environment* env = sc->env();
1513
4
  HandleScope handle_scope(env->isolate());
1514
4
  Context::Scope context_scope(env->context());
1515
1516
  Local<Value> argv[] = {
1517
    Buffer::Copy(env,
1518
                 reinterpret_cast<char*>(name),
1519
                 kTicketPartSize).ToLocalChecked(),
1520
    Buffer::Copy(env,
1521
                 reinterpret_cast<char*>(iv),
1522
                 kTicketPartSize).ToLocalChecked(),
1523
    Boolean::New(env->isolate(), enc != 0)
1524
16
  };
1525
1526
  Local<Value> ret = node::MakeCallback(env->isolate(),
1527
                                        sc->object(),
1528
                                        env->ticketkeycallback_string(),
1529
4
                                        arraysize(argv),
1530
                                        argv,
1531
12
                                        {0, 0}).ToLocalChecked();
1532
4
  Local<Array> arr = ret.As<Array>();
1533
1534
  int r =
1535
4
      arr->Get(env->context(),
1536
12
               kTicketKeyReturnIndex).ToLocalChecked()
1537
16
               ->Int32Value(env->context()).FromJust();
1538
4
  if (r < 0)
1539
    return r;
1540
1541
4
  Local<Value> hmac = arr->Get(env->context(),
1542
12
                               kTicketKeyHMACIndex).ToLocalChecked();
1543
4
  Local<Value> aes = arr->Get(env->context(),
1544
12
                              kTicketKeyAESIndex).ToLocalChecked();
1545
4
  if (Buffer::Length(aes) != kTicketPartSize)
1546
    return -1;
1547
1548
4
  if (enc) {
1549
3
    Local<Value> name_val = arr->Get(env->context(),
1550
9
                                     kTicketKeyNameIndex).ToLocalChecked();
1551
3
    Local<Value> iv_val = arr->Get(env->context(),
1552
9
                                   kTicketKeyIVIndex).ToLocalChecked();
1553
1554

6
    if (Buffer::Length(name_val) != kTicketPartSize ||
1555
3
        Buffer::Length(iv_val) != kTicketPartSize) {
1556
      return -1;
1557
    }
1558
1559
6
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1560
6
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1561
  }
1562
1563
4
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1564
  HMAC_Init_ex(hctx,
1565
4
               hmac_buf.data(),
1566
4
               hmac_buf.length(),
1567
               EVP_sha256(),
1568
12
               nullptr);
1569
1570
4
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1571
4
  if (enc) {
1572
    EVP_EncryptInit_ex(ectx,
1573
                       EVP_aes_128_cbc(),
1574
                       nullptr,
1575
                       aes_key.data(),
1576
3
                       iv);
1577
  } else {
1578
    EVP_DecryptInit_ex(ectx,
1579
                       EVP_aes_128_cbc(),
1580
                       nullptr,
1581
                       aes_key.data(),
1582
1
                       iv);
1583
  }
1584
1585
8
  return r;
1586
}
1587
1588
1589
1167
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1590
                                               unsigned char* name,
1591
                                               unsigned char* iv,
1592
                                               EVP_CIPHER_CTX* ectx,
1593
                                               HMAC_CTX* hctx,
1594
                                               int enc) {
1595
  SecureContext* sc = static_cast<SecureContext*>(
1596
1167
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1597
1598
1167
  if (enc) {
1599
1114
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1600

3342
    if (RAND_bytes(iv, 16) <= 0 ||
1601
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1602

2228
                           sc->ticket_key_aes_, iv) <= 0 ||
1603
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1604
1114
                     EVP_sha256(), nullptr) <= 0) {
1605
      return -1;
1606
    }
1607
1114
    return 1;
1608
  }
1609
1610
53
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1611
    // The ticket key name does not match. Discard the ticket.
1612
12
    return 0;
1613
  }
1614
1615
41
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1616

82
                         iv) <= 0 ||
1617
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1618
41
                   EVP_sha256(), nullptr) <= 0) {
1619
    return -1;
1620
  }
1621
41
  return 1;
1622
}
1623
1624
1625
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1626
  SecureContext* sc;
1627
4
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1628
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1629
4
  info.GetReturnValue().Set(ext);
1630
}
1631
1632
1633
template <bool primary>
1634
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1635
  SecureContext* wrap;
1636

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1637
6
  Environment* env = wrap->env();
1638
  X509* cert;
1639
1640
  if (primary)
1641
3
    cert = wrap->cert_.get();
1642
  else
1643
3
    cert = wrap->issuer_.get();
1644

6
  if (cert == nullptr)
1645
    return args.GetReturnValue().SetNull();
1646
1647
6
  int size = i2d_X509(cert, nullptr);
1648
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1649
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1650
6
      Buffer::Data(buff));
1651
6
  i2d_X509(cert, &serialized);
1652
1653
12
  args.GetReturnValue().Set(buff);
1654
}
1655
1656
1657
template <class Base>
1658
478
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1659
478
  HandleScope scope(env->isolate());
1660
1661
478
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
1662
478
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
1663
478
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
1664
478
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
1665
478
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
1666
478
  env->SetProtoMethod(t, "setSession", SetSession);
1667
478
  env->SetProtoMethod(t, "loadSession", LoadSession);
1668
478
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
1669
478
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
1670
478
  env->SetProtoMethodNoSideEffect(t, "getCipher", GetCipher);
1671
478
  env->SetProtoMethod(t, "endParser", EndParser);
1672
478
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1673
478
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1674
478
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
1675
478
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1676
478
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1677
478
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1678
478
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
1679
                                  GetEphemeralKeyInfo);
1680
478
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
1681
1682
#ifdef SSL_set_max_send_fragment
1683
478
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1684
#endif  // SSL_set_max_send_fragment
1685
1686
478
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
1687
                                  GetALPNNegotiatedProto);
1688
478
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1689
478
}
1690
1691
1692
template <class Base>
1693
12217
void SSLWrap<Base>::ConfigureSecureContext(SecureContext* sc) {
1694
  // OCSP stapling
1695
12217
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
1696
12217
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
1697
12217
}
1698
1699
1700
template <class Base>
1701
144
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1702
                                               const unsigned char* key,
1703
                                               int len,
1704
                                               int* copy) {
1705
144
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1706
1707
144
  *copy = 0;
1708
144
  return w->next_sess_.release();
1709
}
1710
1711
1712
template <class Base>
1713
1607
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1714
1607
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1715
1607
  Environment* env = w->ssl_env();
1716
1607
  HandleScope handle_scope(env->isolate());
1717
1607
  Context::Scope context_scope(env->context());
1718
1719
1607
  if (!w->session_callbacks_)
1720
1315
    return 0;
1721
1722
  // Check if session is small enough to be stored
1723
292
  int size = i2d_SSL_SESSION(sess, nullptr);
1724
292
  if (size > SecureContext::kMaxSessionSize)
1725
    return 0;
1726
1727
  // Serialize session
1728
584
  Local<Object> session = Buffer::New(env, size).ToLocalChecked();
1729
  unsigned char* session_data = reinterpret_cast<unsigned char*>(
1730
292
      Buffer::Data(session));
1731
292
  memset(session_data, 0, size);
1732
292
  i2d_SSL_SESSION(sess, &session_data);
1733
1734
  unsigned int session_id_length;
1735
  const unsigned char* session_id_data = SSL_SESSION_get_id(sess,
1736
292
                                                            &session_id_length);
1737
  Local<Object> session_id = Buffer::Copy(
1738
      env,
1739
      reinterpret_cast<const char*>(session_id_data),
1740
584
      session_id_length).ToLocalChecked();
1741
876
  Local<Value> argv[] = { session_id, session };
1742
  // On servers, we pause the handshake until callback of 'newSession', which
1743
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
1744
292
  if (w->is_server())
1745
8
    w->awaiting_new_session_ = true;
1746
292
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1747
1748
1899
  return 0;
1749
}
1750
1751
1752
template <class Base>
1753
20
void SSLWrap<Base>::OnClientHello(void* arg,
1754
                                  const ClientHelloParser::ClientHello& hello) {
1755
20
  Base* w = static_cast<Base*>(arg);
1756
20
  Environment* env = w->ssl_env();
1757
20
  HandleScope handle_scope(env->isolate());
1758
20
  Local<Context> context = env->context();
1759
  Context::Scope context_scope(context);
1760
1761
20
  Local<Object> hello_obj = Object::New(env->isolate());
1762
  Local<Object> buff = Buffer::Copy(
1763
      env,
1764
20
      reinterpret_cast<const char*>(hello.session_id()),
1765
60
      hello.session_size()).ToLocalChecked();
1766
60
  hello_obj->Set(context, env->session_id_string(), buff).Check();
1767
20
  if (hello.servername() == nullptr) {
1768
    hello_obj->Set(context,
1769
                   env->servername_string(),
1770
8
                   String::Empty(env->isolate())).Check();
1771
  } else {
1772
    Local<String> servername = OneByteString(env->isolate(),
1773
                                             hello.servername(),
1774
18
                                             hello.servername_size());
1775
54
    hello_obj->Set(context, env->servername_string(), servername).Check();
1776
  }
1777
  hello_obj->Set(context,
1778
                 env->tls_ticket_string(),
1779
80
                 Boolean::New(env->isolate(), hello.has_ticket())).Check();
1780
1781
40
  Local<Value> argv[] = { hello_obj };
1782
40
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1783
20
}
1784
1785
1786
96
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1787
96
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1788
1789
96
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1790
85
    return false;
1791
1792
11
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
1793
11
  if (names == nullptr)
1794
    return false;
1795
1796
43
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1797
32
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1798
1799
32
    if (i != 0)
1800
21
      BIO_write(out, ", ", 2);
1801
1802
32
    if (gen->type == GEN_DNS) {
1803
29
      ASN1_IA5STRING* name = gen->d.dNSName;
1804
1805
29
      BIO_write(out, "DNS:", 4);
1806
29
      BIO_write(out, name->data, name->length);
1807
    } else {
1808
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1809
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
1810
3
      if (nval == nullptr)
1811
        return false;
1812
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1813
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1814
    }
1815
  }
1816
11
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1817
1818
11
  return true;
1819
}
1820
1821
1822
2286
static void AddFingerprintDigest(const unsigned char* md,
1823
                                 unsigned int md_size,
1824
                                 char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) {
1825
  unsigned int i;
1826
2286
  const char hex[] = "0123456789ABCDEF";
1827
1828
61722
  for (i = 0; i < md_size; i++) {
1829
59436
    (*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4];
1830
59436
    (*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)];
1831
59436
    (*fingerprint)[(3*i)+2] = ':';
1832
  }
1833
1834
2286
  if (md_size > 0) {
1835
2286
    (*fingerprint)[(3*(md_size-1))+2] = '\0';
1836
  } else {
1837
    (*fingerprint)[0] = '\0';
1838
  }
1839
2286
}
1840
1841
1842
63
static MaybeLocal<Object> ECPointToBuffer(Environment* env,
1843
                                          const EC_GROUP* group,
1844
                                          const EC_POINT* point,
1845
                                          point_conversion_form_t form,
1846
                                          const char** error) {
1847
63
  size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, nullptr);
1848
63
  if (len == 0) {
1849
    if (error != nullptr) *error = "Failed to get public key length";
1850
    return MaybeLocal<Object>();
1851
  }
1852
63
  AllocatedBuffer buf = env->AllocateManaged(len);
1853
  len = EC_POINT_point2oct(group,
1854
                           point,
1855
                           form,
1856
63
                           reinterpret_cast<unsigned char*>(buf.data()),
1857
                           buf.size(),
1858
126
                           nullptr);
1859
63
  if (len == 0) {
1860
    if (error != nullptr) *error = "Failed to get public key";
1861
    return MaybeLocal<Object>();
1862
  }
1863
63
  return buf.ToBuffer();
1864
}
1865
1866
1867
1143
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1868
1143
  EscapableHandleScope scope(env->isolate());
1869
1143
  Local<Context> context = env->context();
1870
1143
  Local<Object> info = Object::New(env->isolate());
1871
1872
2286
  BIOPointer bio(BIO_new(BIO_s_mem()));
1873
  BUF_MEM* mem;
1874
1143
  if (X509_NAME_print_ex(bio.get(),
1875
1143
                         X509_get_subject_name(cert),
1876
                         0,
1877
1143
                         X509_NAME_FLAGS) > 0) {
1878
1143
    BIO_get_mem_ptr(bio.get(), &mem);
1879
    info->Set(context, env->subject_string(),
1880
              String::NewFromUtf8(env->isolate(), mem->data,
1881
                                  NewStringType::kNormal,
1882
4572
                                  mem->length).ToLocalChecked()).Check();
1883
  }
1884
1143
  USE(BIO_reset(bio.get()));
1885
1886
1143
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1887
1143
  if (X509_NAME_print_ex(bio.get(), issuer_name, 0, X509_NAME_FLAGS) > 0) {
1888
1143
    BIO_get_mem_ptr(bio.get(), &mem);
1889
    info->Set(context, env->issuer_string(),
1890
              String::NewFromUtf8(env->isolate(), mem->data,
1891
                                  NewStringType::kNormal,
1892
4572
                                  mem->length).ToLocalChecked()).Check();
1893
  }
1894
1143
  USE(BIO_reset(bio.get()));
1895
1896
1143
  int nids[] = { NID_subject_alt_name, NID_info_access };
1897
  Local<String> keys[] = { env->subjectaltname_string(),
1898
1143
                           env->infoaccess_string() };
1899
1143
  CHECK_EQ(arraysize(nids), arraysize(keys));
1900
3429
  for (size_t i = 0; i < arraysize(nids); i++) {
1901
2286
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1902
2286
    if (index < 0)
1903
2190
      continue;
1904
1905
96
    X509_EXTENSION* ext = X509_get_ext(cert, index);
1906
96
    CHECK_NOT_NULL(ext);
1907
1908
96
    if (!SafeX509ExtPrint(bio.get(), ext)) {
1909
85
      CHECK_EQ(1, X509V3_EXT_print(bio.get(), ext, 0, 0));
1910
    }
1911
1912
96
    BIO_get_mem_ptr(bio.get(), &mem);
1913
    info->Set(context, keys[i],
1914
              String::NewFromUtf8(env->isolate(), mem->data,
1915
                                  NewStringType::kNormal,
1916
288
                                  mem->length).ToLocalChecked()).Check();
1917
1918
96
    USE(BIO_reset(bio.get()));
1919
  }
1920
1921
2286
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1922
2286
  RSAPointer rsa;
1923
2286
  ECPointer ec;
1924
1143
  if (pkey) {
1925
1143
    switch (EVP_PKEY_id(pkey.get())) {
1926
      case EVP_PKEY_RSA:
1927
1106
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1928
1106
        break;
1929
      case EVP_PKEY_EC:
1930
37
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1931
37
        break;
1932
    }
1933
  }
1934
1935
1143
  if (rsa) {
1936
    const BIGNUM* n;
1937
    const BIGNUM* e;
1938
1106
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1939
1106
    BN_print(bio.get(), n);
1940
1106
    BIO_get_mem_ptr(bio.get(), &mem);
1941
    info->Set(context, env->modulus_string(),
1942
              String::NewFromUtf8(env->isolate(), mem->data,
1943
                                  NewStringType::kNormal,
1944
4424
                                  mem->length).ToLocalChecked()).Check();
1945
1106
    USE(BIO_reset(bio.get()));
1946
1947
1106
    int bits = BN_num_bits(n);
1948
    info->Set(context, env->bits_string(),
1949
4424
              Integer::New(env->isolate(), bits)).Check();
1950
1951
1106
    uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
1952
1106
    uint32_t lo = static_cast<uint32_t>(exponent_word);
1953
1106
    uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
1954
1106
    if (hi == 0) {
1955
1106
      BIO_printf(bio.get(), "0x%x", lo);
1956
    } else {
1957
      BIO_printf(bio.get(), "0x%x%08x", hi, lo);
1958
    }
1959
1106
    BIO_get_mem_ptr(bio.get(), &mem);
1960
    info->Set(context, env->exponent_string(),
1961
              String::NewFromUtf8(env->isolate(), mem->data,
1962
                                  NewStringType::kNormal,
1963
4424
                                  mem->length).ToLocalChecked()).Check();
1964
1106
    USE(BIO_reset(bio.get()));
1965
1966
1106
    int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
1967
1106
    CHECK_GE(size, 0);
1968
2212
    Local<Object> pubbuff = Buffer::New(env, size).ToLocalChecked();
1969
    unsigned char* pubserialized =
1970
1106
        reinterpret_cast<unsigned char*>(Buffer::Data(pubbuff));
1971
1106
    i2d_RSA_PUBKEY(rsa.get(), &pubserialized);
1972
4424
    info->Set(env->context(), env->pubkey_string(), pubbuff).Check();
1973
37
  } else if (ec) {
1974
37
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1975
37
    if (group != nullptr) {
1976
37
      int bits = EC_GROUP_order_bits(group);
1977
37
      if (bits > 0) {
1978
        info->Set(context, env->bits_string(),
1979
148
                  Integer::New(env->isolate(), bits)).Check();
1980
      }
1981
    }
1982
1983
37
    const EC_POINT* pubkey = EC_KEY_get0_public_key(ec.get());
1984
    Local<Object> buf;
1985

148
    if (pubkey != nullptr &&
1986
        ECPointToBuffer(
1987
37
            env, group, pubkey, EC_KEY_get_conv_form(ec.get()), nullptr)
1988
148
            .ToLocal(&buf)) {
1989
111
      info->Set(context, env->pubkey_string(), buf).Check();
1990
    }
1991
1992
37
    const int nid = EC_GROUP_get_curve_name(group);
1993
37
    if (nid != 0) {
1994
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1995
1996
37
      if (const char* sn = OBJ_nid2sn(nid)) {
1997
        info->Set(context, env->asn1curve_string(),
1998
148
                  OneByteString(env->isolate(), sn)).Check();
1999
      }
2000
2001
37
      if (const char* nist = EC_curve_nid2nist(nid)) {
2002
        info->Set(context, env->nistcurve_string(),
2003
148
                  OneByteString(env->isolate(), nist)).Check();
2004
      }
2005
    } else {
2006
      // Unnamed curves can be described by their mathematical properties,
2007
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
2008
    }
2009
  }
2010
2011
1143
  pkey.reset();
2012
1143
  rsa.reset();
2013
1143
  ec.reset();
2014
2015
1143
  ASN1_TIME_print(bio.get(), X509_get_notBefore(cert));
2016
1143
  BIO_get_mem_ptr(bio.get(), &mem);
2017
  info->Set(context, env->valid_from_string(),
2018
            String::NewFromUtf8(env->isolate(), mem->data,
2019
                                NewStringType::kNormal,
2020
4572
                                mem->length).ToLocalChecked()).Check();
2021
1143
  USE(BIO_reset(bio.get()));
2022
2023
1143
  ASN1_TIME_print(bio.get(), X509_get_notAfter(cert));
2024
1143
  BIO_get_mem_ptr(bio.get(), &mem);
2025
  info->Set(context, env->valid_to_string(),
2026
            String::NewFromUtf8(env->isolate(), mem->data,
2027
                                NewStringType::kNormal,
2028
4572
                                mem->length).ToLocalChecked()).Check();
2029
1143
  bio.reset();
2030
2031
  unsigned char md[EVP_MAX_MD_SIZE];
2032
  unsigned int md_size;
2033
  char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
2034
1143
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
2035
1143
      AddFingerprintDigest(md, md_size, &fingerprint);
2036
      info->Set(context, env->fingerprint_string(),
2037
4572
                OneByteString(env->isolate(), fingerprint)).Check();
2038
  }
2039
1143
  if (X509_digest(cert, EVP_sha256(), md, &md_size)) {
2040
1143
      AddFingerprintDigest(md, md_size, &fingerprint);
2041
      info->Set(context, env->fingerprint256_string(),
2042
4572
                OneByteString(env->isolate(), fingerprint)).Check();
2043
  }
2044
2045
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
2046
1143
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
2047
1143
  if (eku) {
2048
20
    Local<Array> ext_key_usage = Array::New(env->isolate());
2049
    char buf[256];
2050
2051
20
    int j = 0;
2052
56
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku.get()); i++) {
2053
36
      if (OBJ_obj2txt(buf,
2054
                      sizeof(buf),
2055
36
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
2056
36
        ext_key_usage->Set(context,
2057
                           j++,
2058
144
                           OneByteString(env->isolate(), buf)).Check();
2059
      }
2060
    }
2061
2062
20
    eku.reset();
2063
60
    info->Set(context, env->ext_key_usage_string(), ext_key_usage).Check();
2064
  }
2065
2066
1143
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
2067
1143
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
2068
1143
    if (bn) {
2069
1143
      OpenSSLBuffer buf(BN_bn2hex(bn.get()));
2070
1143
      if (buf) {
2071
        info->Set(context, env->serial_number_string(),
2072
4572
                  OneByteString(env->isolate(), buf.get())).Check();
2073
1143
      }
2074
1143
    }
2075
  }
2076
2077
  // Raw DER certificate
2078
1143
  int size = i2d_X509(cert, nullptr);
2079
2286
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
2080
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
2081
1143
      Buffer::Data(buff));
2082
1143
  i2d_X509(cert, &serialized);
2083
3429
  info->Set(context, env->raw_string(), buff).Check();
2084
2085
2286
  return scope.Escape(info);
2086
}
2087
2088
2089
386
static Local<Object> AddIssuerChainToObject(X509Pointer* cert,
2090
                                            Local<Object> object,
2091
                                            StackOfX509&& peer_certs,
2092
                                            Environment* const env) {
2093
386
  Local<Context> context = env->isolate()->GetCurrentContext();
2094
386
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
2095
  for (;;) {
2096
    int i;
2097
798
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
2098
346
      X509* ca = sk_X509_value(peer_certs.get(), i);
2099
346
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
2100
2
        continue;
2101
2102
344
      Local<Object> ca_info = X509ToObject(env, ca);
2103
1032
      object->Set(context, env->issuercert_string(), ca_info).Check();
2104
344
      object = ca_info;
2105
2106
      // NOTE: Intentionally freeing cert that is not used anymore.
2107
      // Delete cert and continue aggregating issuers.
2108
344
      cert->reset(sk_X509_delete(peer_certs.get(), i));
2109
344
      break;
2110
    }
2111
2112
    // Issuer not found, break out of the loop.
2113
397
    if (i == sk_X509_num(peer_certs.get()))
2114
386
      break;
2115
11
  }
2116
386
  return object;
2117
}
2118
2119
2120
386
static StackOfX509 CloneSSLCerts(X509Pointer&& cert,
2121
                                 const STACK_OF(X509)* const ssl_certs) {
2122
386
  StackOfX509 peer_certs(sk_X509_new(nullptr));
2123
386
  if (cert)
2124
    sk_X509_push(peer_certs.get(), cert.release());
2125
1118
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
2126
732
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
2127

732
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
2128
      return StackOfX509();
2129
    // `cert` is now managed by the stack.
2130
732
    cert.release();
2131
732
  }
2132
386
  return peer_certs;
2133
}
2134
2135
2136
386
static Local<Object> GetLastIssuedCert(X509Pointer* cert,
2137
                                       const SSLPointer& ssl,
2138
                                       Local<Object> issuer_chain,
2139
                                       Environment* const env) {
2140
386
  Local<Context> context = env->isolate()->GetCurrentContext();
2141
1131
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
2142
    X509* ca;
2143
359
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
2144
      break;
2145
2146
359
    Local<Object> ca_info = X509ToObject(env, ca);
2147
1077
    issuer_chain->Set(context, env->issuercert_string(), ca_info).Check();
2148
359
    issuer_chain = ca_info;
2149
2150
    // Delete previous cert and continue aggregating issuers.
2151
359
    cert->reset(ca);
2152
  }
2153
386
  return issuer_chain;
2154
}
2155
2156
2157
template <class Base>
2158
432
void SSLWrap<Base>::GetPeerCertificate(
2159
    const FunctionCallbackInfo<Value>& args) {
2160
  Base* w;
2161
864
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2162
432
  Environment* env = w->ssl_env();
2163
2164
  ClearErrorOnReturn clear_error_on_return;
2165
2166
  Local<Object> result;
2167
  // Used to build the issuer certificate chain.
2168
  Local<Object> issuer_chain;
2169
2170
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
2171
  // contains the `peer_certificate`, but on server it doesn't.
2172
  X509Pointer cert(
2173
864
      w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) : nullptr);
2174
432
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_.get());
2175


432
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
2176
3
    goto done;
2177
2178
  // Short result requested.
2179


1716
  if (args.Length() < 1 || !args[0]->IsTrue()) {
2180
43
    result = X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
2181
43
    goto done;
2182
  }
2183
2184
772
  if (auto peer_certs = CloneSSLCerts(std::move(cert), ssl_certs)) {
2185
    // First and main certificate.
2186
386
    X509Pointer cert(sk_X509_value(peer_certs.get(), 0));
2187
386
    CHECK(cert);
2188
386
    result = X509ToObject(env, cert.release());
2189
2190
386
    issuer_chain =
2191
386
        AddIssuerChainToObject(&cert, result, std::move(peer_certs), env);
2192
386
    issuer_chain = GetLastIssuedCert(&cert, w->ssl_, issuer_chain, env);
2193
    // Last certificate should be self-signed.
2194
386
    if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK)
2195
      issuer_chain->Set(env->context(),
2196
                        env->issuercert_string(),
2197
1544
                        issuer_chain).Check();
2198
  }
2199
2200
 done:
2201
1296
  args.GetReturnValue().Set(result);
2202
}
2203
2204
2205
template <class Base>
2206
12
void SSLWrap<Base>::GetCertificate(
2207
    const FunctionCallbackInfo<Value>& args) {
2208
  Base* w;
2209
24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2210
12
  Environment* env = w->ssl_env();
2211
2212
  ClearErrorOnReturn clear_error_on_return;
2213
2214
  Local<Object> result;
2215
2216
12
  X509* cert = SSL_get_certificate(w->ssl_.get());
2217
2218
12
  if (cert != nullptr)
2219
11
    result = X509ToObject(env, cert);
2220
2221
24
  args.GetReturnValue().Set(result);
2222
}
2223
2224
2225
template <class Base>
2226
3
void SSLWrap<Base>::GetFinished(const FunctionCallbackInfo<Value>& args) {
2227
3
  Environment* env = Environment::GetCurrent(args);
2228
2229
  Base* w;
2230
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2231
2232
  // We cannot just pass nullptr to SSL_get_finished()
2233
  // because it would further be propagated to memcpy(),
2234
  // where the standard requirements as described in ISO/IEC 9899:2011
2235
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2236
  // Thus, we use a dummy byte.
2237
  char dummy[1];
2238
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
2239
3
  if (len == 0)
2240
1
    return;
2241
2242
2
  AllocatedBuffer buf = env->AllocateManaged(len);
2243
2
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf.data(), len));
2244
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
2245
}
2246
2247
2248
template <class Base>
2249
3
void SSLWrap<Base>::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
2250
3
  Environment* env = Environment::GetCurrent(args);
2251
2252
  Base* w;
2253
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2254
2255
  // We cannot just pass nullptr to SSL_get_peer_finished()
2256
  // because it would further be propagated to memcpy(),
2257
  // where the standard requirements as described in ISO/IEC 9899:2011
2258
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2259
  // Thus, we use a dummy byte.
2260
  char dummy[1];
2261
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
2262
3
  if (len == 0)
2263
1
    return;
2264
2265
2
  AllocatedBuffer buf = env->AllocateManaged(len);
2266
2
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf.data(), len));
2267
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
2268
}
2269
2270
2271
template <class Base>
2272
19
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
2273
19
  Environment* env = Environment::GetCurrent(args);
2274
2275
  Base* w;
2276
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2277
2278
19
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2279
19
  if (sess == nullptr)
2280
    return;
2281
2282
19
  int slen = i2d_SSL_SESSION(sess, nullptr);
2283
19
  CHECK_GT(slen, 0);
2284
2285
19
  AllocatedBuffer sbuf = env->AllocateManaged(slen);
2286
19
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf.data());
2287
19
  i2d_SSL_SESSION(sess, &p);
2288
57
  args.GetReturnValue().Set(sbuf.ToBuffer().ToLocalChecked());
2289
}
2290
2291
2292
template <class Base>
2293
118
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
2294
118
  Environment* env = Environment::GetCurrent(args);
2295
2296
  Base* w;
2297
118
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2298
2299
118
  if (args.Length() < 1) {
2300
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
2301
  }
2302
2303
118
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
2304
236
  ArrayBufferViewContents<unsigned char> sbuf(args[0].As<ArrayBufferView>());
2305
2306
118
  const unsigned char* p = sbuf.data();
2307
118
  SSLSessionPointer sess(d2i_SSL_SESSION(nullptr, &p, sbuf.length()));
2308
2309
118
  if (sess == nullptr)
2310
    return;
2311
2312
118
  int r = SSL_set_session(w->ssl_.get(), sess.get());
2313
2314
118
  if (!r)
2315
    return env->ThrowError("SSL_set_session error");
2316
}
2317
2318
2319
template <class Base>
2320
10
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
2321
  Base* w;
2322
20
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2323
2324
  // TODO(@sam-github) check arg length and types in js, and CHECK in c++
2325

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2326
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
2327
2328
10
    const unsigned char* p = sbuf.data();
2329
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
2330
2331
    // Setup next session and move hello to the BIO buffer
2332
10
    w->next_sess_.reset(sess);
2333
  }
2334
}
2335
2336
2337
template <class Base>
2338
464
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2339
  Base* w;
2340
928
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2341
464
  bool yes = SSL_session_reused(w->ssl_.get());
2342
1392
  args.GetReturnValue().Set(yes);
2343
}
2344
2345
2346
template <class Base>
2347
19
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2348
  Base* w;
2349
38
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2350
19
  w->hello_parser_.End();
2351
}
2352
2353
2354
template <class Base>
2355
92
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2356
  Base* w;
2357
93
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2358
2359
  ClearErrorOnReturn clear_error_on_return;
2360
2361
92
  if (SSL_renegotiate(w->ssl_.get()) != 1) {
2362
1
    return ThrowCryptoError(w->ssl_env(), ERR_get_error());
2363
91
  }
2364
}
2365
2366
2367
template <class Base>
2368
18
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2369
  Base* w;
2370
18
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2371
18
  Environment* env = w->ssl_env();
2372
2373
18
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2374
18
  if (sess == nullptr)
2375
    return;
2376
2377
  const unsigned char* ticket;
2378
  size_t length;
2379
18
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2380
2381
18
  if (ticket == nullptr)
2382
    return;
2383
2384
  Local<Object> buff = Buffer::Copy(
2385
36
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2386
2387
36
  args.GetReturnValue().Set(buff);
2388
}
2389
2390
2391
template <class Base>
2392
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2393
  Base* w;
2394
16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2395
8
  w->awaiting_new_session_ = false;
2396
8
  w->NewSessionDoneCb();
2397
}
2398
2399
2400
template <class Base>
2401
2
void SSLWrap<Base>::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
2402
  Base* w;
2403
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2404
2
  Environment* env = w->env();
2405
2406
2
  if (args.Length() < 1)
2407
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
2408
2409
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
2410
2411
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
2412
}
2413
2414
2415
template <class Base>
2416
4
void SSLWrap<Base>::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
2417
  Base* w;
2418
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2419
2420
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
2421
}
2422
2423
2424
template <class Base>
2425
843
void SSLWrap<Base>::GetEphemeralKeyInfo(
2426
    const FunctionCallbackInfo<Value>& args) {
2427
  Base* w;
2428
843
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2429
843
  Environment* env = Environment::GetCurrent(args);
2430
843
  Local<Context> context = env->context();
2431
2432
843
  CHECK(w->ssl_);
2433
2434
  // tmp key is available on only client
2435
843
  if (w->is_server())
2436
14
    return args.GetReturnValue().SetNull();
2437
2438
836
  Local<Object> info = Object::New(env->isolate());
2439
2440
  EVP_PKEY* raw_key;
2441
836
  if (SSL_get_server_tmp_key(w->ssl_.get(), &raw_key)) {
2442
750
    EVPKeyPointer key(raw_key);
2443
750
    int kid = EVP_PKEY_id(key.get());
2444
750
    switch (kid) {
2445
      case EVP_PKEY_DH:
2446
        info->Set(context, env->type_string(),
2447
24
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH")).Check();
2448
        info->Set(context, env->size_string(),
2449
24
                  Integer::New(env->isolate(), EVP_PKEY_bits(key.get())))
2450
12
            .Check();
2451
6
        break;
2452
      case EVP_PKEY_EC:
2453
      case EVP_PKEY_X25519:
2454
      case EVP_PKEY_X448:
2455
        {
2456
          const char* curve_name;
2457
744
          if (kid == EVP_PKEY_EC) {
2458
7
            EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key.get());
2459
7
            int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2460
7
            curve_name = OBJ_nid2sn(nid);
2461
7
            EC_KEY_free(ec);
2462
          } else {
2463
737
            curve_name = OBJ_nid2sn(kid);
2464
          }
2465
          info->Set(context, env->type_string(),
2466
2976
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")).Check();
2467
          info->Set(context, env->name_string(),
2468
                    OneByteString(args.GetIsolate(),
2469
2976
                                  curve_name)).Check();
2470
          info->Set(context, env->size_string(),
2471
                    Integer::New(env->isolate(),
2472
2976
                                 EVP_PKEY_bits(key.get()))).Check();
2473
        }
2474
744
        break;
2475
      default:
2476
        break;
2477
750
    }
2478
  }
2479
  // TODO(@sam-github) semver-major: else return ThrowCryptoError(env,
2480
  // ERR_get_error())
2481
2482
1672
  return args.GetReturnValue().Set(info);
2483
}
2484
2485
2486
#ifdef SSL_set_max_send_fragment
2487
template <class Base>
2488
3
void SSLWrap<Base>::SetMaxSendFragment(
2489
    const FunctionCallbackInfo<Value>& args) {
2490


12
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2491
2492
  Base* w;
2493
6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2494
2495
12
  int rv = SSL_set_max_send_fragment(
2496
      w->ssl_.get(),
2497
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2498
6
  args.GetReturnValue().Set(rv);
2499
}
2500
#endif  // SSL_set_max_send_fragment
2501
2502
2503
template <class Base>
2504
906
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2505
  Base* w;
2506
1342
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2507
2508
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2509
  // peer certificate is questionable but it's compatible with what was
2510
  // here before.
2511
  long x509_verify_error =  // NOLINT(runtime/int)
2512
906
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2513
906
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_.get())) {
2514
905
    X509_free(peer_cert);
2515
905
    x509_verify_error = SSL_get_verify_result(w->ssl_.get());
2516
  }
2517
2518
906
  if (x509_verify_error == X509_V_OK)
2519
872
    return args.GetReturnValue().SetNull();
2520
2521
470
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2522
470
  const char* code = reason;
2523
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2524







470
  switch (x509_verify_error) {
2525
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2526
1
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2527
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2528
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2529
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2530
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2531
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2532
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2533
35
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2534
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2535
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2536
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2537
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2538
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2539
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2540
    CASE_X509_ERR(OUT_OF_MEM)
2541
260
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2542
13
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2543
4
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2544
154
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2545
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2546
1
    CASE_X509_ERR(CERT_REVOKED)
2547
    CASE_X509_ERR(INVALID_CA)
2548
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2549
1
    CASE_X509_ERR(INVALID_PURPOSE)
2550
    CASE_X509_ERR(CERT_UNTRUSTED)
2551
    CASE_X509_ERR(CERT_REJECTED)
2552
  }
2553
#undef CASE_X509_ERR
2554
2555
470
  Isolate* isolate = args.GetIsolate();
2556
470
  Local<String> reason_string = OneByteString(isolate, reason);
2557
470
  Local<Value> exception_value = Exception::Error(reason_string);
2558
  Local<Object> exception_object =
2559
1410
    exception_value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2560
2350
  exception_object->Set(w->env()->context(), w->env()->code_string(),
2561
                        OneByteString(isolate, code)).Check();
2562
940
  args.GetReturnValue().Set(exception_object);
2563
}
2564
2565
2566
template <class Base>
2567
45
void SSLWrap<Base>::GetCipher(const FunctionCallbackInfo<Value>& args) {
2568
  Base* w;
2569
45
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2570
45
  Environment* env = w->ssl_env();
2571
45
  Local<Context> context = env->context();
2572
2573
45
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get());
2574
45
  if (c == nullptr)
2575
    return;
2576
2577
45
  Local<Object> info = Object::New(env->isolate());
2578
45
  const char* cipher_name = SSL_CIPHER_get_name(c);
2579
  info->Set(context, env->name_string(),
2580
180
            OneByteString(args.GetIsolate(), cipher_name)).Check();
2581
45
  const char* cipher_version = SSL_CIPHER_get_version(c);
2582
  info->Set(context, env->version_string(),
2583
180
            OneByteString(args.GetIsolate(), cipher_version)).Check();
2584
90
  args.GetReturnValue().Set(info);
2585
}
2586
2587
2588
template <class Base>
2589
547
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2590
  Base* w;
2591
1094
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2592
2593
547
  const char* tls_version = SSL_get_version(w->ssl_.get());
2594
1641
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2595
}
2596
2597
2598
template <class Base>
2599
23
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2600
                                      const unsigned char** out,
2601
                                      unsigned char* outlen,
2602
                                      const unsigned char* in,
2603
                                      unsigned int inlen,
2604
                                      void* arg) {
2605
23
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2606
23
  Environment* env = w->env();
2607
23
  HandleScope handle_scope(env->isolate());
2608
23
  Context::Scope context_scope(env->context());
2609
2610
  Local<Value> alpn_buffer =
2611
23
      w->object()->GetPrivate(
2612
          env->context(),
2613
92
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2614
23
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
2615
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2616
23
                                     alpn_protos.data(), alpn_protos.length(),
2617
23
                                     in, inlen);
2618
  // According to 3.2. Protocol Selection of RFC7301, fatal
2619
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2620
  // support it yet. See
2621
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2622
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2623
46
                                          : SSL_TLSEXT_ERR_NOACK;
2624
}
2625
2626
2627
template <class Base>
2628
1680
void SSLWrap<Base>::GetALPNNegotiatedProto(
2629
    const FunctionCallbackInfo<Value>& args) {
2630
  Base* w;
2631
3360
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2632
2633
  const unsigned char* alpn_proto;
2634
  unsigned int alpn_proto_len;
2635
2636
1680
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2637
2638
  Local<Value> result;
2639
1680
  if (alpn_proto_len == 0) {
2640
3276
    result = False(args.GetIsolate());
2641

78
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
2642
36
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
2643
72
    result = w->env()->h2_string();
2644

8
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
2645
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
2646
4
    result = w->env()->http_1_1_string();
2647
  } else {
2648
12
    result = OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len);
2649
  }
2650
2651
3360
  args.GetReturnValue().Set(result);
2652
}
2653
2654
2655
template <class Base>
2656
194
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2657
  Base* w;
2658
194
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2659
194
  Environment* env = w->env();
2660

388
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2661
    return env->ThrowTypeError("Must give a Buffer as first argument");
2662
2663
194
  if (w->is_client()) {
2664
28
    ArrayBufferViewContents<unsigned char> alpn_protos(args[0]);
2665
    int r = SSL_set_alpn_protos(
2666
28
        w->ssl_.get(), alpn_protos.data(), alpn_protos.length());
2667
28
    CHECK_EQ(r, 0);
2668
  } else {
2669
498
    CHECK(
2670
        w->object()->SetPrivate(
2671
            env->context(),
2672
            env->alpn_buffer_private_symbol(),
2673
            args[0]).FromJust());
2674
    // Server should select ALPN protocol from list of advertised by client
2675
332
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2676
                               SelectALPNCallback,
2677
166
                               nullptr);
2678
  }
2679
}
2680
2681
2682
template <class Base>
2683
8
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2684
8
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2685
8
  Environment* env = w->env();
2686
8
  HandleScope handle_scope(env->isolate());
2687
2688
8
  if (w->is_client()) {
2689
    // Incoming response
2690
    const unsigned char* resp;
2691
4
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2692
    Local<Value> arg;
2693
4
    if (resp == nullptr) {
2694
4
      arg = Null(env->isolate());
2695
    } else {
2696
4
      arg =
2697
2
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2698
          .ToLocalChecked();
2699
    }
2700
2701
4
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2702
2703
    // No async acceptance is possible, so always return 1 to accept the
2704
    // response.  The listener for 'OCSPResponse' event has no control over
2705
    // return value, but it can .destroy() the connection if the response is not
2706
    // acceptable.
2707
4
    return 1;
2708
  } else {
2709
    // Outgoing response
2710
8
    if (w->ocsp_response_.IsEmpty())
2711
2
      return SSL_TLSEXT_ERR_NOACK;
2712
2713
    Local<ArrayBufferView> obj = PersistentToLocal::Default(env->isolate(),
2714
2
                                                            w->ocsp_response_);
2715
2
    size_t len = obj->ByteLength();
2716
2717
    // OpenSSL takes control of the pointer after accepting it
2718
2
    unsigned char* data = MallocOpenSSL<unsigned char>(len);
2719
2
    obj->CopyContents(data, len);
2720
2721
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2722
      OPENSSL_free(data);
2723
2
    w->ocsp_response_.Reset();
2724
2725
2
    return SSL_TLSEXT_ERR_OK;
2726
8
  }
2727
}
2728
2729
2730
template <class Base>
2731
20
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2732
20
  cert_cb_ = cb;
2733
20
  cert_cb_arg_ = arg;
2734
20
}
2735
2736
2737
template <class Base>
2738
906
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2739
906
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2740
2741
906
  if (!w->is_server())
2742
42
    return 1;
2743
2744
864
  if (!w->is_waiting_cert_cb())
2745
844
    return 1;
2746
2747
20
  if (w->cert_cb_running_)
2748
    // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
2749
    // handshake will continue after certcb is done.
2750
    return -1;
2751
2752
20
  Environment* env = w->env();
2753
20
  Local<Context> context = env->context();
2754
20
  HandleScope handle_scope(env->isolate());
2755
  Context::Scope context_scope(context);
2756
20
  w->cert_cb_running_ = true;
2757
2758
20
  Local<Object> info = Object::New(env->isolate());
2759
2760
20
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2761
20
  if (servername == nullptr) {
2762
    info->Set(context,
2763
              env->servername_string(),
2764
16
              String::Empty(env->isolate())).Check();
2765
  } else {
2766
    Local<String> str = OneByteString(env->isolate(), servername,
2767
16
                                      strlen(servername));
2768
48
    info->Set(context, env->servername_string(), str).Check();
2769
  }
2770
2771
20
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
2772
  info->Set(context, env->ocsp_request_string(),
2773
80
            Boolean::New(env->isolate(), ocsp)).Check();
2774
2775
40
  Local<Value> argv[] = { info };
2776
20
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2777
2778
20
  if (!w->cert_cb_running_)
2779
9
    return 1;
2780
2781
  // Performing async action, wait...
2782
31
  return -1;
2783
}
2784
2785
2786
template <class Base>
2787
18
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2788
  Base* w;
2789
20
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2790
18
  Environment* env = w->env();
2791
2792

18
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2793
2794
18
  Local<Object> object = w->object();
2795
  Local<Value> ctx = object->Get(env->context(),
2796
72
                                 env->sni_context_string()).ToLocalChecked();
2797
18
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2798
2799
  // Not an object, probably undefined or null
2800
18
  if (!ctx->IsObject())
2801
8
    goto fire_cb;
2802
2803
10
  if (cons->HasInstance(ctx)) {
2804
    SecureContext* sc;
2805
10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2806
9
    w->sni_context_.Reset(env->isolate(), ctx);
2807
2808
    int rv;
2809
2810
    // NOTE: reference count is not increased by this API methods
2811
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_.get());
2812
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_.get());
2813
    STACK_OF(X509)* chain;
2814
2815
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_.get(), &chain);
2816
9
    if (rv)
2817
9
      rv = SSL_use_certificate(w->ssl_.get(), x509);
2818
9
    if (rv)
2819
8
      rv = SSL_use_PrivateKey(w->ssl_.get(), pkey);
2820

9
    if (rv && chain != nullptr)
2821
1
      rv = SSL_set1_chain(w->ssl_.get(), chain);
2822
9
    if (rv)
2823
8
      rv = w->SetCACerts(sc);
2824
9
    if (!rv) {
2825
      // Not clear why sometimes we throw error, and sometimes we call
2826
      // onerror(). Both cause .destroy(), but onerror does a bit more.
2827
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2828
1
      if (!err)
2829
        return env->ThrowError("CertCbDone");
2830
1
      return ThrowCryptoError(env, err);
2831
    }
2832
  } else {
2833
    // Failure: incorrect SNI context object
2834
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2835
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2836
1
    return;
2837
  }
2838
2839
 fire_cb:
2840
  CertCb cb;
2841
  void* arg;
2842
2843
16
  cb = w->cert_cb_;
2844
16
  arg = w->cert_cb_arg_;
2845
2846
16
  w->cert_cb_running_ = false;
2847
16
  w->cert_cb_ = nullptr;
2848
16
  w->cert_cb_arg_ = nullptr;
2849
2850
16
  cb(arg);
2851
}
2852
2853
2854
template <class Base>
2855
24239
void SSLWrap<Base>::DestroySSL() {
2856
24239
  if (!ssl_)
2857
36279
    return;
2858
2859
12199
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2860
12199
  ssl_.reset();
2861
}
2862
2863
2864
template <class Base>
2865
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2866
  ConfigureSecureContext(sc);
2867
  CHECK_EQ(SSL_set_SSL_CTX(ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
2868
2869
  SetCACerts(sc);
2870
}
2871
2872
2873
template <class Base>
2874
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2875
8
  int err = SSL_set1_verify_cert_store(ssl_.get(),
2876
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
2877
8
  if (err != 1)
2878
    return err;
2879
2880
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2881
8
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
2882
2883
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2884
8
  SSL_set_client_CA_list(ssl_.get(), list);
2885
8
  return 1;
2886
}
2887
2888
2033
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2889
  // From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
2890
  //
2891
  //   If VerifyCallback returns 1, the verification process is continued. If
2892
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
2893
  //   terminated with respect to verification failures and the connection will
2894
  //   be established. The calling process can however retrieve the error code
2895
  //   of the last verification error using SSL_get_verify_result(3) or by
2896
  //   maintaining its own error storage managed by VerifyCallback.
2897
  //
2898
  // Since we cannot perform I/O quickly enough with X509_STORE_CTX_ APIs in
2899
  // this callback, we ignore all preverify_ok errors and let the handshake
2900
  // continue. It is imperative that the user use Connection::VerifyError after
2901
  // the 'secure' callback has been made.
2902
2033
  return 1;
2903
}
2904
2905
3374
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
2906
3374
  const int mode = EVP_CIPHER_mode(cipher);
2907
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
2908
  // but its mode is 0 which doesn't indicate
2909
6701
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
2910
6113
         mode == EVP_CIPH_CCM_MODE ||
2911

7499
         mode == EVP_CIPH_GCM_MODE ||
2912
4713
         IS_OCB_MODE(mode);
2913
}
2914
2915
1468
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
2916
1468
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
2917
1468
  return IsSupportedAuthenticatedMode(cipher);
2918
}
2919
2920
enum class ParseKeyResult {
2921
  kParseKeyOk,
2922
  kParseKeyNotRecognized,
2923
  kParseKeyNeedPassphrase,
2924
  kParseKeyFailed
2925
};
2926
2927
2484
static ParseKeyResult TryParsePublicKey(
2928
    EVPKeyPointer* pkey,
2929
    const BIOPointer& bp,
2930
    const char* name,
2931
    // NOLINTNEXTLINE(runtime/int)
2932
    const std::function<EVP_PKEY*(const unsigned char** p, long l)>& parse) {
2933
  unsigned char* der_data;
2934
  long der_len;  // NOLINT(runtime/int)
2935
2936
  // This skips surrounding data and decodes PEM to DER.
2937
  {
2938
2484
    MarkPopErrorOnReturn mark_pop_error_on_return;
2939
2484
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
2940
2484
                           bp.get(), nullptr, nullptr) != 1)
2941
1718
      return ParseKeyResult::kParseKeyNotRecognized;
2942
  }
2943
2944
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
2945
766
  const unsigned char* p = der_data;
2946
766
  pkey->reset(parse(&p, der_len));
2947
766
  OPENSSL_clear_free(der_data, der_len);
2948
2949
  return *pkey ? ParseKeyResult::kParseKeyOk :
2950
766
                 ParseKeyResult::kParseKeyFailed;
2951
}
2952
2953
898
static ParseKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
2954
                                        const char* key_pem,
2955
                                        int key_pem_len) {
2956
898
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
2957
898
  if (!bp)
2958
    return ParseKeyResult::kParseKeyFailed;
2959
2960
  ParseKeyResult ret;
2961
2962
  // Try parsing as a SubjectPublicKeyInfo first.
2963
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
2964
96
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2965
        return d2i_PUBKEY(nullptr, p, l);
2966
994
      });
2967
898
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
2968
96
    return ret;
2969
2970
  // Maybe it is PKCS#1.
2971
802
  CHECK(BIO_reset(bp.get()));
2972
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
2973
18
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2974
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
2975
820
      });
2976
802
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
2977
18
    return ret;
2978
2979
  // X.509 fallback.
2980
784
  CHECK(BIO_reset(bp.get()));
2981
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
2982
652
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2983
652
        X509Pointer x509(d2i_X509(nullptr, p, l));
2984
1304
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
2985
1436
      });
2986
}
2987
2988
21
static ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
2989
                                     const PublicKeyEncodingConfig& config,
2990
                                     const char* key,
2991
                                     size_t key_len) {
2992
21
  if (config.format_ == kKeyFormatPEM) {
2993
    return ParsePublicKeyPEM(pkey, key, key_len);
2994
  } else {
2995
21
    CHECK_EQ(config.format_, kKeyFormatDER);
2996
2997
21
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2998
42
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2999
21
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
3000
    } else {
3001
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
3002
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
3003
    }
3004
3005
    return *pkey ? ParseKeyResult::kParseKeyOk :
3006
21
                   ParseKeyResult::kParseKeyFailed;
3007
  }
3008
}
3009
3010
40
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
3011
                                               BIO* bio,
3012
                                               PKFormatType format) {
3013
  BUF_MEM* bptr;
3014
40
  BIO_get_mem_ptr(bio, &bptr);
3015
40
  if (format == kKeyFormatPEM) {
3016
    // PEM is an ASCII format, so we will return it as a string.
3017
    return String::NewFromUtf8(env->isolate(), bptr->data,
3018
                               NewStringType::kNormal,
3019
62
                               bptr->length).ToLocalChecked();
3020
  } else {
3021
9
    CHECK_EQ(format, kKeyFormatDER);
3022
    // DER is binary, return it as a buffer.
3023
18
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
3024
  }
3025
}
3026
3027
22
static bool WritePublicKeyInner(EVP_PKEY* pkey,
3028
                                const BIOPointer& bio,
3029
                                const PublicKeyEncodingConfig& config) {
3030
44
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3031
    // PKCS#1 is only valid for RSA keys.
3032
8
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
3033
8
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
3034
8
    if (config.format_ == kKeyFormatPEM) {
3035
      // Encode PKCS#1 as PEM.
3036
3
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
3037
    } else {
3038
      // Encode PKCS#1 as DER.
3039
5
      CHECK_EQ(config.format_, kKeyFormatDER);
3040
5
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
3041
8
    }
3042
  } else {
3043
28
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
3044
14
    if (config.format_ == kKeyFormatPEM) {
3045
      // Encode SPKI as PEM.
3046
14
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
3047
    } else {
3048
      // Encode SPKI as DER.
3049
      CHECK_EQ(config.format_, kKeyFormatDER);
3050
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
3051
    }
3052
  }
3053
}
3054
3055
22
static MaybeLocal<Value> WritePublicKey(Environment* env,
3056
                                        EVP_PKEY* pkey,
3057
                                        const PublicKeyEncodingConfig& config) {
3058
22
  BIOPointer bio(BIO_new(BIO_s_mem()));
3059
22
  CHECK(bio);
3060
3061
22
  if (!WritePublicKeyInner(pkey, bio, config)) {
3062
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
3063
    return MaybeLocal<Value>();
3064
  }
3065
44
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
3066
}
3067
3068
56
static bool IsASN1Sequence(const unsigned char* data, size_t size,
3069
                           size_t* data_offset, size_t* data_size) {
3070

56
  if (size < 2 || data[0] != 0x30)
3071
    return false;
3072
3073
56
  if (data[1] & 0x80) {
3074
    // Long form.
3075
36
    size_t n_bytes = data[1] & ~0x80;
3076

36
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
3077
      return false;
3078
36
    size_t length = 0;
3079
107
    for (size_t i = 0; i < n_bytes; i++)
3080
71
      length = (length << 8) | data[i + 2];
3081
36
    *data_offset = 2 + n_bytes;
3082
36
    *data_size = std::min(size - 2 - n_bytes, length);
3083
  } else {
3084
    // Short form.
3085
20
    *data_offset = 2;
3086
20
    *data_size = std::min<size_t>(size - 2, data[1]);
3087
  }
3088
3089
56
  return true;
3090
}
3091
3092
30
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
3093
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
3094
  size_t offset, len;
3095
30
  if (!IsASN1Sequence(data, size, &offset, &len))
3096
    return false;
3097
3098
  // An RSAPrivateKey sequence always starts with a single-byte integer whose
3099
  // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
3100
  // (which is the product of two primes and therefore at least 4), so we can
3101
  // decide the type of the structure based on the first three bytes of the
3102
  // sequence.
3103
60
  return len >= 3 &&
3104
60
         data[offset] == 2 &&
3105

69
         data[offset + 1] == 1 &&
3106
39
         !(data[offset + 2] & 0xfe);
3107
}
3108
3109
26
static bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
3110
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
3111
  size_t offset, len;
3112
26
  if (!IsASN1Sequence(data, size, &offset, &len))
3113
    return false;
3114
3115
  // A PrivateKeyInfo sequence always starts with an integer whereas an
3116
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
3117

52
  return len >= 1 &&
3118
52
         data[offset] != 2;
3119
}
3120
3121
320
static ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
3122
                                      const PrivateKeyEncodingConfig& config,
3123
                                      const char* key,
3124
                                      size_t key_len) {
3125
  // OpenSSL needs a non-const pointer, that's why the const_cast is required.
3126
320
  char* const passphrase = const_cast<char*>(config.passphrase_.get());
3127
3128
320
  if (config.format_ == kKeyFormatPEM) {
3129
285
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
3130
285
    if (!bio)
3131
1
      return ParseKeyResult::kParseKeyFailed;
3132
3133
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
3134
                                        nullptr,
3135
                                        PasswordCallback,
3136
284
                                        passphrase));
3137
  } else {
3138
35
    CHECK_EQ(config.format_, kKeyFormatDER);
3139
3140
70
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3141
9
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3142
9
      pkey->reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
3143
52
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
3144
26
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
3145
26
      if (!bio)
3146
        return ParseKeyResult::kParseKeyFailed;
3147
3148
26
      if (IsEncryptedPrivateKeyInfo(
3149
              reinterpret_cast<const unsigned char*>(key), key_len)) {
3150
        pkey->reset(d2i_PKCS8PrivateKey_bio(bio.get(),
3151
                                            nullptr,
3152
                                            PasswordCallback,
3153
17
                                            passphrase));
3154
      } else {
3155
9
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
3156
9
        if (p8inf)
3157
9
          pkey->reset(EVP_PKCS82PKEY(p8inf.get()));
3158
26
      }
3159
    } else {
3160
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
3161
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3162
      pkey->reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
3163
    }
3164
  }
3165
3166
  // OpenSSL can fail to parse the key but still return a non-null pointer.
3167
319
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
3168
319
  if (err != 0)
3169
15
    pkey->reset();
3170
3171
319
  if (*pkey)
3172
304
    return ParseKeyResult::kParseKeyOk;
3173

23
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
3174
8
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
3175
7
    if (config.passphrase_.get() == nullptr)
3176
6
      return ParseKeyResult::kParseKeyNeedPassphrase;
3177
  }
3178
9
  return ParseKeyResult::kParseKeyFailed;
3179
}
3180
3181
2098
ByteSource::ByteSource(ByteSource&& other)
3182
      : data_(other.data_),
3183
        allocated_data_(other.allocated_data_),
3184
2098
        size_(other.size_) {
3185
2098
  other.allocated_data_ = nullptr;
3186
2098
}
3187
3188
5737
ByteSource::~ByteSource() {
3189
5737
  OPENSSL_clear_free(allocated_data_, size_);
3190
5737
}
3191
3192
71
ByteSource& ByteSource::operator=(ByteSource&& other) {
3193
71
  if (&other != this) {
3194
71
    OPENSSL_clear_free(allocated_data_, size_);
3195
71
    data_ = other.data_;
3196
71
    allocated_data_ = other.allocated_data_;
3197
71
    other.allocated_data_ = nullptr;
3198
71
    size_ = other.size_;
3199
  }
3200
71
  return *this;
3201
}
3202
3203
2940
const char* ByteSource::get() const {
3204
2940
  return data_;
3205
}
3206
3207
2613
size_t ByteSource::size() const {
3208
2613
  return size_;
3209
}
3210
3211
2420
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
3212
                                          Local<Value> value) {
3213
2420
  return Buffer::HasInstance(value) ? FromBuffer(value)
3214
3453
                                    : FromString(env, value.As<String>());
3215
}
3216
3217
1093
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
3218
                                  bool ntc) {
3219
2186
  CHECK(str->IsString());
3220
2186
  size_t size = str->Utf8Length(env->isolate());
3221
1093
  size_t alloc_size = ntc ? size + 1 : size;
3222
1093
  char* data = MallocOpenSSL<char>(alloc_size);
3223
1093
  int opts = String::NO_OPTIONS;
3224
1093
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
3225
2186
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
3226
1093
  return Allocated(data, size);
3227
}
3228
3229
1398
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
3230
1398
  CHECK(buffer->IsArrayBufferView());
3231
1398
  Local<ArrayBufferView> abv = buffer.As<ArrayBufferView>();
3232
1398
  size_t size = abv->ByteLength();
3233
1398
  if (ntc) {
3234
11
    char* data = MallocOpenSSL<char>(size + 1);
3235
11
    abv->CopyContents(data, size);
3236
11
    data[size] = 0;
3237
11
    return Allocated(data, size);
3238
  }
3239
1387
  return Foreign(Buffer::Data(buffer), size);
3240
}
3241
3242
71
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
3243
                                          Local<Value> value) {
3244
71
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
3245
131
                                    : FromString(env, value.As<String>(), true);
3246
}
3247
3248
14
ByteSource ByteSource::FromSymmetricKeyObject(Local<Value> handle) {
3249
14
  CHECK(handle->IsObject());
3250
14
  KeyObject* key = Unwrap<KeyObject>(handle.As<Object>());
3251
14
  CHECK(key);
3252
14
  return Foreign(key->GetSymmetricKey(), key->GetSymmetricKeySize());
3253
}
3254
3255
2505
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
3256
      : data_(data),
3257
        allocated_data_(allocated_data),
3258
2505
        size_(size) {}
3259
3260
1104
ByteSource ByteSource::Allocated(char* data, size_t size) {
3261
1104
  return ByteSource(data, data, size);
3262
}
3263
3264
1401
ByteSource ByteSource::Foreign(const char* data, size_t size) {
3265
1401
  return ByteSource(data, nullptr, size);
3266
}
3267
3268
enum KeyEncodingContext {
3269
  kKeyContextInput,
3270
  kKeyContextExport,
3271
  kKeyContextGenerate
3272
};
3273
3274
1163
static void GetKeyFormatAndTypeFromJs(
3275
    AsymmetricKeyEncodingConfig* config,
3276
    const FunctionCallbackInfo<Value>& args,
3277
    unsigned int* offset,
3278
    KeyEncodingContext context) {
3279
  // During key pair generation, it is possible not to specify a key encoding,
3280
  // which will lead to a key object being returned.
3281
4652
  if (args[*offset]->IsUndefined()) {
3282
14
    CHECK_EQ(context, kKeyContextGenerate);
3283
56
    CHECK(args[*offset + 1]->IsUndefined());
3284
14
    config->output_key_object_ = true;
3285
  } else {
3286
1149
    config->output_key_object_ = false;
3287
3288
3447
    CHECK(args[*offset]->IsInt32());
3289
    config->format_ = static_cast<PKFormatType>(
3290
4596
        args[*offset].As<Int32>()->Value());
3291
3292
3447
    if (args[*offset + 1]->IsInt32()) {
3293
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
3294
392
          args[*offset + 1].As<Int32>()->Value()));
3295
    } else {
3296

1051
      CHECK(context == kKeyContextInput && config->format_ == kKeyFormatPEM);
3297
4204
      CHECK(args[*offset + 1]->IsNullOrUndefined());
3298
1051
      config->type_ = Nothing<PKEncodingType>();
3299
    }
3300
  }
3301
3302
1163
  *offset += 2;
3303
1163
}
3304
3305
30
static PublicKeyEncodingConfig GetPublicKeyEncodingFromJs(
3306
    const FunctionCallbackInfo<Value>& args,
3307
    unsigned int* offset,
3308
    KeyEncodingContext context) {
3309
30
  PublicKeyEncodingConfig result;
3310
30
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3311
30
  return result;
3312
}
3313
3314
1107
static inline ManagedEVPPKey GetParsedKey(Environment* env,
3315
                                          EVPKeyPointer&& pkey,
3316
                                          ParseKeyResult ret,
3317
                                          const char* default_msg) {
3318
1107
  switch (ret) {
3319
    case ParseKeyResult::kParseKeyOk:
3320
1091
      CHECK(pkey);
3321
1091
      break;
3322
    case ParseKeyResult::kParseKeyNeedPassphrase:
3323
      THROW_ERR_MISSING_PASSPHRASE(env,
3324
6
                                   "Passphrase required for encrypted key");
3325
6
      break;
3326
    default:
3327
10
      ThrowCryptoError(env, ERR_get_error(), default_msg);
3328
  }
3329
3330
1107
  return ManagedEVPPKey(std::move(pkey));
3331
}
3332
3333
1133
static NonCopyableMaybe<PrivateKeyEncodingConfig> GetPrivateKeyEncodingFromJs(
3334
    const FunctionCallbackInfo<Value>& args,
3335
    unsigned int* offset,
3336
    KeyEncodingContext context) {
3337
1133
  Environment* env = Environment::GetCurrent(args);
3338
3339
1133
  PrivateKeyEncodingConfig result;
3340
1133
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3341
3342
1133
  if (result.output_key_object_) {
3343
7
    if (context != kKeyContextInput)
3344
7
      (*offset)++;
3345
  } else {
3346
1126
    bool needs_passphrase = false;
3347
1126
    if (context != kKeyContextInput) {
3348
76
      if (args[*offset]->IsString()) {
3349
        String::Utf8Value cipher_name(env->isolate(),
3350
18
                                      args[*offset].As<String>());
3351
6
        result.cipher_ = EVP_get_cipherbyname(*cipher_name);
3352
6
        if (result.cipher_ == nullptr) {
3353
1
          env->ThrowError("Unknown cipher");
3354
1
          return NonCopyableMaybe<PrivateKeyEncodingConfig>();
3355
        }
3356
5
        needs_passphrase = true;
3357
      } else {
3358
52
        CHECK(args[*offset]->IsNullOrUndefined());
3359
13
        result.cipher_ = nullptr;
3360
      }
3361
18
      (*offset)++;
3362
    }
3363
3364


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

71
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
3366
3367
142
      result.passphrase_ = ByteSource::NullTerminatedCopy(env, args[*offset]);
3368
    } else {
3369


4216
      CHECK(args[*offset]->IsNullOrUndefined() && !needs_passphrase);
3370
    }
3371
  }
3372
3373
1132
  (*offset)++;
3374
1132
  return NonCopyableMaybe<PrivateKeyEncodingConfig>(std::move(result));
3375
}
3376
3377
194
static ManagedEVPPKey GetPrivateKeyFromJs(
3378
    const FunctionCallbackInfo<Value>& args,
3379
    unsigned int* offset,
3380
    bool allow_key_object) {
3381


855
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3382
161
    Environment* env = Environment::GetCurrent(args);
3383
322
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3384
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3385
322
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3386
161
    if (config.IsEmpty())
3387
      return ManagedEVPPKey();
3388
3389
322
    EVPKeyPointer pkey;
3390
    ParseKeyResult ret =
3391
161
        ParsePrivateKey(&pkey, config.Release(), key.get(), key.size());
3392
161
    return GetParsedKey(env, std::move(pkey), ret,
3393
322
                        "Failed to read private key");
3394
  } else {
3395


99
    CHECK(args[*offset]->IsObject() && allow_key_object);
3396
    KeyObject* key;
3397
99
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
3398
33
    CHECK_EQ(key->GetKeyType(), kKeyTypePrivate);
3399
33
    (*offset) += 4;
3400
33
    return key->GetAsymmetricKey();
3401
  }
3402
}
3403
3404
1045
static ManagedEVPPKey GetPublicOrPrivateKeyFromJs(
3405
    const FunctionCallbackInfo<Value>& args,
3406
    unsigned int* offset) {
3407


4402
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3408
946
    Environment* env = Environment::GetCurrent(args);
3409
1892
    ByteSource data = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3410
    NonCopyableMaybe<PrivateKeyEncodingConfig> config_ =
3411
1892
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3412
946
    if (config_.IsEmpty())
3413
      return ManagedEVPPKey();
3414
3415
    ParseKeyResult ret;
3416
1892
    PrivateKeyEncodingConfig config = config_.Release();
3417
1892
    EVPKeyPointer pkey;
3418
946
    if (config.format_ == kKeyFormatPEM) {
3419
      // For PEM, we can easily determine whether it is a public or private key
3420
      // by looking for the respective PEM tags.
3421
898
      ret = ParsePublicKeyPEM(&pkey, data.get(), data.size());
3422
898
      if (ret == ParseKeyResult::kParseKeyNotRecognized) {
3423
132
        ret = ParsePrivateKey(&pkey, config, data.get(), data.size());
3424
      }
3425
    } else {
3426
      // For DER, the type determines how to parse it. SPKI, PKCS#8 and SEC1 are
3427
      // easy, but PKCS#1 can be a public key or a private key.
3428
      bool is_public;
3429

48
      switch (config.type_.ToChecked()) {
3430
        case kKeyEncodingPKCS1:
3431