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: 3266 3596 90.8 %
Date: 2019-09-26 22:31:05 Branches: 1769 2728 64.8 %

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

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









48
    switch (ERR_GET_LIB(err)) { OSSL_ERROR_CODES_MAP(V) }
317
#undef V
318
#undef OSSL_ERROR_CODES_MAP
319
    // Don't generate codes like "ERR_OSSL_SSL_".
320

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

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



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

6864
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
670

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


3366
    if (args[1]->IsUndefined() || args[1]->IsNull())
714
796
      len = 1;
715
    else
716
78
      THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase");
717
  }
718
719
820
  BIOPointer bio(LoadBIO(env, args[0]));
720
820
  if (!bio)
721
    return;
722
723
1632
  node::Utf8Value passphrase(env->isolate(), args[1]);
724
725
  EVPKeyPointer key(
726
      PEM_read_bio_PrivateKey(bio.get(),
727
                              nullptr,
728
                              PasswordCallback,
729
1632
                              *passphrase));
730
731
820
  if (!key) {
732
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
733
7
    if (!err) {
734
      return env->ThrowError("PEM_read_bio_PrivateKey");
735
    }
736
7
    return ThrowCryptoError(env, err);
737
  }
738
739
813
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
740
741
813
  if (!rv) {
742
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
743
1
    if (!err)
744
      return env->ThrowError("SSL_CTX_use_PrivateKey");
745
1
    return ThrowCryptoError(env, err);
746
812
  }
747
}
748
749
8
void SecureContext::SetSigalgs(const FunctionCallbackInfo<Value>& args) {
750
  SecureContext* sc;
751
8
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
752
8
  Environment* env = sc->env();
753
  ClearErrorOnReturn clear_error_on_return;
754
755
8
  CHECK_EQ(args.Length(), 1);
756
24
  CHECK(args[0]->IsString());
757
758
16
  const node::Utf8Value sigalgs(env->isolate(), args[0]);
759
760
8
  int rv = SSL_CTX_set1_sigalgs_list(sc->ctx_.get(), *sigalgs);
761
762
8
  if (rv == 0) {
763
    return ThrowCryptoError(env, ERR_get_error());
764
8
  }
765
}
766
767
856
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
768
856
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
769
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
770
856
      X509_STORE_CTX_new());
771
1712
  return store_ctx.get() != nullptr &&
772

1712
         X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
773
1712
         X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1;
774
}
775
776
777
850
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
778
                                  X509Pointer&& x,
779
                                  STACK_OF(X509)* extra_certs,
780
                                  X509Pointer* cert,
781
                                  X509Pointer* issuer_) {
782
850
  CHECK(!*issuer_);
783
850
  CHECK(!*cert);
784
850
  X509* issuer = nullptr;
785
786
850
  int ret = SSL_CTX_use_certificate(ctx, x.get());
787
788
850
  if (ret) {
789
    // If we could set up our certificate, now proceed to
790
    // the CA certificates.
791
850
    SSL_CTX_clear_extra_chain_certs(ctx);
792
793
1265
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
794
415
      X509* ca = sk_X509_value(extra_certs, i);
795
796
      // NOTE: Increments reference count on `ca`
797
415
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
798
        ret = 0;
799
        issuer = nullptr;
800
        break;
801
      }
802
      // Note that we must not free r if it was successfully
803
      // added to the chain (while we must free the main
804
      // certificate, since its reference count is increased
805
      // by SSL_CTX_use_certificate).
806
807
      // Find issuer
808

415
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
809
4
        continue;
810
811
411
      issuer = ca;
812
    }
813
  }
814
815
  // Try getting issuer from a cert store
816
850
  if (ret) {
817
850
    if (issuer == nullptr) {
818
439
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
819
439
      ret = ret < 0 ? 0 : 1;
820
      // NOTE: get_cert_store doesn't increment reference count,
821
      // no need to free `store`
822
    } else {
823
      // Increment issuer reference count
824
411
      issuer = X509_dup(issuer);
825
411
      if (issuer == nullptr) {
826
        ret = 0;
827
      }
828
    }
829
  }
830
831
850
  issuer_->reset(issuer);
832
833

850
  if (ret && x != nullptr) {
834
850
    cert->reset(X509_dup(x.get()));
835
850
    if (!*cert)
836
      ret = 0;
837
  }
838
850
  return ret;
839
}
840
841
842
// Read a file that contains our certificate in "PEM" format,
843
// possibly followed by a sequence of CA certificates that should be
844
// sent to the peer in the Certificate message.
845
//
846
// Taken from OpenSSL - edited for style.
847
838
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
848
                                  BIOPointer&& in,
849
                                  X509Pointer* cert,
850
                                  X509Pointer* issuer) {
851
  // Just to ensure that `ERR_peek_last_error` below will return only errors
852
  // that we are interested in
853
838
  ERR_clear_error();
854
855
  X509Pointer x(
856
838
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
857
858
838
  if (!x)
859
    return 0;
860
861
838
  unsigned long err = 0;  // NOLINT(runtime/int)
862
863
1676
  StackOfX509 extra_certs(sk_X509_new_null());
864
838
  if (!extra_certs)
865
    return 0;
866
867
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
868
                                    nullptr,
869
                                    NoPasswordCallback,
870
1244
                                    nullptr)}) {
871
406
    if (sk_X509_push(extra_certs.get(), extra.get())) {
872
406
      extra.release();
873
406
      continue;
874
    }
875
876
    return 0;
877
  }
878
879
  // When the while loop ends, it's usually just EOF.
880
838
  err = ERR_peek_last_error();
881

1676
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
882
838
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
883
838
    ERR_clear_error();
884
  } else {
885
    // some real error
886
    return 0;
887
  }
888
889
  return SSL_CTX_use_certificate_chain(ctx,
890
838
                                       std::move(x),
891
                                       extra_certs.get(),
892
                                       cert,
893
2514
                                       issuer);
894
}
895
896
897
838
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
898
838
  Environment* env = Environment::GetCurrent(args);
899
900
  SecureContext* sc;
901
838
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
902
903
838
  if (args.Length() != 1) {
904
    return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory");
905
  }
906
907
838
  BIOPointer bio(LoadBIO(env, args[0]));
908
838
  if (!bio)
909
    return;
910
911
838
  sc->cert_.reset();
912
838
  sc->issuer_.reset();
913
914
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(),
915
838
                                         std::move(bio),
916
                                         &sc->cert_,
917
1676
                                         &sc->issuer_);
918
919
838
  if (!rv) {
920
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
921
    if (!err) {
922
      return env->ThrowError("SSL_CTX_use_certificate_chain");
923
    }
924
    return ThrowCryptoError(env, err);
925
838
  }
926
}
927
928
929
305
static X509_STORE* NewRootCertStore() {
930

305
  static std::vector<X509*> root_certs_vector;
931

305
  static Mutex root_certs_vector_mutex;
932
305
  Mutex::ScopedLock lock(root_certs_vector_mutex);
933
934
305
  if (root_certs_vector.empty()) {
935
41580
    for (size_t i = 0; i < arraysize(root_certs); i++) {
936
      X509* x509 =
937
41283
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
938
41283
                                              strlen(root_certs[i])).get(),
939
                            nullptr,   // no re-use of X509 structure
940
                            NoPasswordCallback,
941
82566
                            nullptr);  // no callback data
942
943
      // Parse errors from the built-in roots are fatal.
944
41283
      CHECK_NOT_NULL(x509);
945
946
41283
      root_certs_vector.push_back(x509);
947
    }
948
  }
949
950
305
  X509_STORE* store = X509_STORE_new();
951
305
  if (*system_cert_path != '\0') {
952
    X509_STORE_load_locations(store, system_cert_path, nullptr);
953
  }
954
305
  if (per_process::cli_options->ssl_openssl_cert_store) {
955
    X509_STORE_set_default_paths(store);
956
  } else {
957
42700
    for (X509* cert : root_certs_vector) {
958
42395
      X509_up_ref(cert);
959
42395
      X509_STORE_add_cert(store, cert);
960
    }
961
  }
962
963
305
  return store;
964
}
965
966
967
1
void GetRootCertificates(const FunctionCallbackInfo<Value>& args) {
968
1
  Environment* env = Environment::GetCurrent(args);
969
1
  Local<Array> result = Array::New(env->isolate(), arraysize(root_certs));
970
971
140
  for (size_t i = 0; i < arraysize(root_certs); i++) {
972
    Local<Value> value;
973
278
    if (!String::NewFromOneByte(env->isolate(),
974
139
                                reinterpret_cast<const uint8_t*>(root_certs[i]),
975

1112
                                NewStringType::kNormal).ToLocal(&value) ||
976

695
        !result->Set(env->context(), i, value).FromMaybe(false)) {
977
1
      return;
978
    }
979
  }
980
981
2
  args.GetReturnValue().Set(result);
982
}
983
984
985
555
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
986
555
  Environment* env = Environment::GetCurrent(args);
987
988
  SecureContext* sc;
989
555
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
990
  ClearErrorOnReturn clear_error_on_return;
991
992
555
  if (args.Length() != 1) {
993
    return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory");
994
  }
995
996
1110
  BIOPointer bio(LoadBIO(env, args[0]));
997
555
  if (!bio)
998
    return;
999
1000
555
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1001
  while (X509* x509 = PEM_read_bio_X509_AUX(
1002
1449
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1003
894
    if (cert_store == root_cert_store) {
1004
2
      cert_store = NewRootCertStore();
1005
2
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1006
    }
1007
894
    X509_STORE_add_cert(cert_store, x509);
1008
894
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
1009
894
    X509_free(x509);
1010
555
  }
1011
}
1012
1013
1014
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
1015
2
  Environment* env = Environment::GetCurrent(args);
1016
1017
  SecureContext* sc;
1018
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1019
1020
2
  if (args.Length() != 1) {
1021
    return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory");
1022
  }
1023
1024
  ClearErrorOnReturn clear_error_on_return;
1025
1026
3
  BIOPointer bio(LoadBIO(env, args[0]));
1027
2
  if (!bio)
1028
    return;
1029
1030
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
1031
3
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
1032
1033
2
  if (!crl)
1034
1
    return env->ThrowError("Failed to parse CRL");
1035
1036
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1037
1
  if (cert_store == root_cert_store) {
1038
    cert_store = NewRootCertStore();
1039
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1040
  }
1041
1042
1
  X509_STORE_add_crl(cert_store, crl.get());
1043
  X509_STORE_set_flags(cert_store,
1044
2
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1045
}
1046
1047
1048
3
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1049
    X509_STORE* store,
1050
    const char* file) {
1051
3
  ERR_clear_error();
1052
3
  MarkPopErrorOnReturn mark_pop_error_on_return;
1053
1054
6
  BIOPointer bio(BIO_new_file(file, "r"));
1055
3
  if (!bio)
1056
1
    return ERR_get_error();
1057
1058
  while (X509* x509 =
1059
4
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1060
2
    X509_STORE_add_cert(store, x509);
1061
2
    X509_free(x509);
1062
  }
1063
1064
2
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1065
  // Ignore error if its EOF/no start line found.
1066

4
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1067
2
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1068
2
    return 0;
1069
  }
1070
1071
3
  return err;
1072
}
1073
1074
1075
3
void UseExtraCaCerts(const std::string& file) {
1076
  ClearErrorOnReturn clear_error_on_return;
1077
1078
3
  if (root_cert_store == nullptr) {
1079
3
    root_cert_store = NewRootCertStore();
1080
1081
3
    if (!file.empty()) {
1082
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1083
                                           root_cert_store,
1084
3
                                           file.c_str());
1085
3
      if (err) {
1086
        fprintf(stderr,
1087
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
1088
                file.c_str(),
1089
1
                ERR_error_string(err, nullptr));
1090
      } else {
1091
2
        extra_root_certs_loaded = true;
1092
      }
1093
    }
1094
3
  }
1095
3
}
1096
1097
1098
static void IsExtraRootCertsFileLoaded(
1099
    const FunctionCallbackInfo<Value>& args) {
1100
  return args.GetReturnValue().Set(extra_root_certs_loaded);
1101
}
1102
1103
1104
1754
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
1105
  SecureContext* sc;
1106
3508
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1107
  ClearErrorOnReturn clear_error_on_return;
1108
1109
1754
  if (root_cert_store == nullptr) {
1110
294
    root_cert_store = NewRootCertStore();
1111
  }
1112
1113
  // Increment reference count so global store is not deleted along with CTX.
1114
1754
  X509_STORE_up_ref(root_cert_store);
1115
1754
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
1116
}
1117
1118
1119
2215
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
1120
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
1121
#ifndef OPENSSL_IS_BORINGSSL
1122
  SecureContext* sc;
1123
2216
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1124
2215
  Environment* env = sc->env();
1125
  ClearErrorOnReturn clear_error_on_return;
1126
1127
2215
  CHECK_EQ(args.Length(), 1);
1128
6645
  CHECK(args[0]->IsString());
1129
1130
4429
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1131
2215
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers)) {
1132
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1133
1
    if (!err) {
1134
      // This would be an OpenSSL bug if it happened.
1135
      return env->ThrowError("Failed to set ciphers");
1136
    }
1137
1
    return ThrowCryptoError(env, err);
1138
2214
  }
1139
#endif
1140
}
1141
1142
1143
2217
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
1144
  SecureContext* sc;
1145
2232
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1146
2217
  Environment* env = sc->env();
1147
  ClearErrorOnReturn clear_error_on_return;
1148
1149
2217
  CHECK_EQ(args.Length(), 1);
1150
6651
  CHECK(args[0]->IsString());
1151
1152
4419
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1153
2217
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
1154
15
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1155
15
    if (!err) {
1156
      // This would be an OpenSSL bug if it happened.
1157
      return env->ThrowError("Failed to set ciphers");
1158
    }
1159
1160

15
    if (strlen(*ciphers) == 0 && ERR_GET_REASON(err) == SSL_R_NO_CIPHER_MATCH) {
1161
      // TLS1.2 ciphers were deliberately cleared, so don't consider
1162
      // SSL_R_NO_CIPHER_MATCH to be an error (this is how _set_cipher_suites()
1163
      // works). If the user actually sets a value (like "no-such-cipher"), then
1164
      // that's actually an error.
1165
11
      return;
1166
    }
1167
4
    return ThrowCryptoError(env, err);
1168
2202
  }
1169
}
1170
1171
1172
2210
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
1173
  SecureContext* sc;
1174
4413
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1175
2210
  Environment* env = sc->env();
1176
1177
2210
  if (args.Length() != 1)
1178
    return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory");
1179
1180
6630
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name");
1181
1182
2209
  node::Utf8Value curve(env->isolate(), args[0]);
1183
1184
2209
  if (strcmp(*curve, "auto") == 0)
1185
2199
    return;
1186
1187
10
  if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve))
1188
3
    return env->ThrowError("Failed to set ECDH curve");
1189
}
1190
1191
1192
10
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
1193
  SecureContext* sc;
1194
13
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
1195
10
  Environment* env = sc->env();
1196
  ClearErrorOnReturn clear_error_on_return;
1197
1198
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
1199
  // to be specified explicitly
1200
10
  if (args.Length() != 1)
1201
    return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory");
1202
1203
17
  DHPointer dh;
1204
  {
1205
10
    BIOPointer bio(LoadBIO(env, args[0]));
1206
10
    if (!bio)
1207
      return;
1208
1209
10
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
1210
  }
1211
1212
  // Invalid dhparam is silently discarded and DHE is no longer used.
1213
10
  if (!dh)
1214
1
    return;
1215
1216
  const BIGNUM* p;
1217
9
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
1218
9
  const int size = BN_num_bits(p);
1219
9
  if (size < 1024) {
1220
    return THROW_ERR_INVALID_ARG_VALUE(
1221
2
        env, "DH parameter is less than 1024 bits");
1222
7
  } else if (size < 2048) {
1223
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1224
9
        env->isolate(), "DH parameter is less than 2048 bits"));
1225
  }
1226
1227
7
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
1228
7
  int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get());
1229
1230
7
  if (!r)
1231
7
    return env->ThrowTypeError("Error setting temp DH parameter");
1232
}
1233
1234
1235
11
void SecureContext::SetMinProto(const FunctionCallbackInfo<Value>& args) {
1236
  SecureContext* sc;
1237
22
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1238
1239
11
  CHECK_EQ(args.Length(), 1);
1240
22
  CHECK(args[0]->IsInt32());
1241
1242
33
  int version = args[0].As<Int32>()->Value();
1243
1244
11
  CHECK(SSL_CTX_set_min_proto_version(sc->ctx_.get(), version));
1245
}
1246
1247
1248
45
void SecureContext::SetMaxProto(const FunctionCallbackInfo<Value>& args) {
1249
  SecureContext* sc;
1250
90
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1251
1252
45
  CHECK_EQ(args.Length(), 1);
1253
90
  CHECK(args[0]->IsInt32());
1254
1255
135
  int version = args[0].As<Int32>()->Value();
1256
1257
45
  CHECK(SSL_CTX_set_max_proto_version(sc->ctx_.get(), version));
1258
}
1259
1260
1261
56
void SecureContext::GetMinProto(const FunctionCallbackInfo<Value>& args) {
1262
  SecureContext* sc;
1263
112
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1264
1265
56
  CHECK_EQ(args.Length(), 0);
1266
1267
  long version =  // NOLINT(runtime/int)
1268
56
    SSL_CTX_get_min_proto_version(sc->ctx_.get());
1269
168
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1270
}
1271
1272
1273
75
void SecureContext::GetMaxProto(const FunctionCallbackInfo<Value>& args) {
1274
  SecureContext* sc;
1275
150
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1276
1277
75
  CHECK_EQ(args.Length(), 0);
1278
1279
  long version =  // NOLINT(runtime/int)
1280
75
    SSL_CTX_get_max_proto_version(sc->ctx_.get());
1281
225
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1282
}
1283
1284
1285
812
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1286
  SecureContext* sc;
1287
812
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1288
  int64_t val;
1289
1290

4060
  if (args.Length() != 1 ||
1291

4872
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1292
    return THROW_ERR_INVALID_ARG_TYPE(
1293
        sc->env(), "Options must be an integer value");
1294
  }
1295
1296
  SSL_CTX_set_options(sc->ctx_.get(),
1297
812
                      static_cast<long>(val));  // NOLINT(runtime/int)
1298
}
1299
1300
1301
741
void SecureContext::SetSessionIdContext(
1302
    const FunctionCallbackInfo<Value>& args) {
1303
  SecureContext* sc;
1304
1482
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1305
741
  Environment* env = sc->env();
1306
1307
741
  if (args.Length() != 1) {
1308
    return THROW_ERR_MISSING_ARGS(
1309
        env, "Session ID context argument is mandatory");
1310
  }
1311
1312
2223
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1313
1314
741
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1315
  const unsigned char* sid_ctx =
1316
741
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1317
741
  unsigned int sid_ctx_len = sessionIdContext.length();
1318
1319
741
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1320
741
  if (r == 1)
1321
741
    return;
1322
1323
  BUF_MEM* mem;
1324
  Local<String> message;
1325
1326
  BIOPointer bio(BIO_new(BIO_s_mem()));
1327
  if (!bio) {
1328
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1329
                                    "SSL_CTX_set_session_id_context error");
1330
  } else {
1331
    ERR_print_errors(bio.get());
1332
    BIO_get_mem_ptr(bio.get(), &mem);
1333
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1334
  }
1335
1336
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1337
}
1338
1339
1340
2
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1341
  SecureContext* sc;
1342
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1343
1344


8
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1345
    return THROW_ERR_INVALID_ARG_TYPE(
1346
1
        sc->env(), "Session timeout must be a 32-bit integer");
1347
  }
1348
1349
3
  int32_t sessionTimeout = args[0].As<Int32>()->Value();
1350
1
  SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
1351
}
1352
1353
1354
1317
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1355
  SecureContext* sc;
1356
2634
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1357
1317
  sc->Reset();
1358
}
1359
1360
1361
// Takes .pfx or .p12 and password in string or buffer format
1362
18
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1363
18
  Environment* env = Environment::GetCurrent(args);
1364
1365
18
  std::vector<char> pass;
1366
18
  bool ret = false;
1367
1368
  SecureContext* sc;
1369
18
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1370
12
  ClearErrorOnReturn clear_error_on_return;
1371
1372
18
  if (args.Length() < 1) {
1373
    return THROW_ERR_MISSING_ARGS(env, "PFX certificate argument is mandatory");
1374
  }
1375
1376
30
  BIOPointer in(LoadBIO(env, args[0]));
1377
18
  if (!in)
1378
    return env->ThrowError("Unable to load BIO");
1379
1380
18
  if (args.Length() >= 2) {
1381
15
    THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase");
1382
30
    Local<ArrayBufferView> abv = args[1].As<ArrayBufferView>();
1383
15
    size_t passlen = abv->ByteLength();
1384
15
    pass.resize(passlen + 1);
1385
30
    abv->CopyContents(pass.data(), passlen);
1386
15
    pass[passlen] = '\0';
1387
  }
1388
1389
  // Free previous certs
1390
18
  sc->issuer_.reset();
1391
18
  sc->cert_.reset();
1392
1393
18
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1394
1395
30
  DeleteFnPtr<PKCS12, PKCS12_free> p12;
1396
30
  EVPKeyPointer pkey;
1397
30
  X509Pointer cert;
1398
30
  StackOfX509 extra_certs;
1399
1400
18
  PKCS12* p12_ptr = nullptr;
1401
18
  EVP_PKEY* pkey_ptr = nullptr;
1402
18
  X509* cert_ptr = nullptr;
1403
18
  STACK_OF(X509)* extra_certs_ptr = nullptr;
1404
36
  if (d2i_PKCS12_bio(in.get(), &p12_ptr) &&
1405
32
      (p12.reset(p12_ptr), true) &&  // Move ownership to the smart pointer.
1406
16
      PKCS12_parse(p12.get(), pass.data(),
1407
                   &pkey_ptr,
1408
                   &cert_ptr,
1409
16
                   &extra_certs_ptr) &&
1410
12
      (pkey.reset(pkey_ptr), cert.reset(cert_ptr),
1411
24
       extra_certs.reset(extra_certs_ptr), true) &&  // Move ownership.
1412
      SSL_CTX_use_certificate_chain(sc->ctx_.get(),
1413
12
                                    std::move(cert),
1414
                                    extra_certs.get(),
1415
                                    &sc->cert_,
1416

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

6
    if (Buffer::Length(name_val) != kTicketPartSize ||
1595
3
        Buffer::Length(iv_val) != kTicketPartSize) {
1596
      return -1;
1597
    }
1598
1599
6
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1600
6
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1601
  }
1602
1603
4
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1604
  HMAC_Init_ex(hctx,
1605
4
               hmac_buf.data(),
1606
4
               hmac_buf.length(),
1607
               EVP_sha256(),
1608
12
               nullptr);
1609
1610
4
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1611
4
  if (enc) {
1612
    EVP_EncryptInit_ex(ectx,
1613
                       EVP_aes_128_cbc(),
1614
                       nullptr,
1615
                       aes_key.data(),
1616
3
                       iv);
1617
  } else {
1618
    EVP_DecryptInit_ex(ectx,
1619
                       EVP_aes_128_cbc(),
1620
                       nullptr,
1621
                       aes_key.data(),
1622
1
                       iv);
1623
  }
1624
1625
8
  return r;
1626
}
1627
1628
1629
1155
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1630
                                               unsigned char* name,
1631
                                               unsigned char* iv,
1632
                                               EVP_CIPHER_CTX* ectx,
1633
                                               HMAC_CTX* hctx,
1634
                                               int enc) {
1635
  SecureContext* sc = static_cast<SecureContext*>(
1636
1155
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1637
1638
1155
  if (enc) {
1639
1102
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1640

3306
    if (RAND_bytes(iv, 16) <= 0 ||
1641
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1642

2204
                           sc->ticket_key_aes_, iv) <= 0 ||
1643
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1644
1102
                     EVP_sha256(), nullptr) <= 0) {
1645
      return -1;
1646
    }
1647
1102
    return 1;
1648
  }
1649
1650
53
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1651
    // The ticket key name does not match. Discard the ticket.
1652
12
    return 0;
1653
  }
1654
1655
41
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1656

82
                         iv) <= 0 ||
1657
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1658
41
                   EVP_sha256(), nullptr) <= 0) {
1659
    return -1;
1660
  }
1661
41
  return 1;
1662
}
1663
1664
1665
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1666
  SecureContext* sc;
1667
4
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1668
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1669
4
  info.GetReturnValue().Set(ext);
1670
}
1671
1672
1673
template <bool primary>
1674
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1675
  SecureContext* wrap;
1676

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1677
6
  Environment* env = wrap->env();
1678
  X509* cert;
1679
1680
  if (primary)
1681
3
    cert = wrap->cert_.get();
1682
  else
1683
3
    cert = wrap->issuer_.get();
1684

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

148
    if (pubkey != nullptr &&
2042
        ECPointToBuffer(
2043
37
            env, group, pubkey, EC_KEY_get_conv_form(ec.get()), nullptr)
2044
148
            .ToLocal(&buf)) {
2045
111
      info->Set(context, env->pubkey_string(), buf).Check();
2046
    }
2047
2048
37
    const int nid = EC_GROUP_get_curve_name(group);
2049
37
    if (nid != 0) {
2050
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
2051
2052
37
      if (const char* sn = OBJ_nid2sn(nid)) {
2053
        info->Set(context, env->asn1curve_string(),
2054
148
                  OneByteString(env->isolate(), sn)).Check();
2055
      }
2056
2057
37
      if (const char* nist = EC_curve_nid2nist(nid)) {
2058
        info->Set(context, env->nistcurve_string(),
2059
148
                  OneByteString(env->isolate(), nist)).Check();
2060
      }
2061
    } else {
2062
      // Unnamed curves can be described by their mathematical properties,
2063
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
2064
    }
2065
  }
2066
2067
1318
  pkey.reset();
2068
1318
  rsa.reset();
2069
1318
  ec.reset();
2070
2071
1318
  ASN1_TIME_print(bio.get(), X509_get_notBefore(cert));
2072
1318
  BIO_get_mem_ptr(bio.get(), &mem);
2073
  info->Set(context, env->valid_from_string(),
2074
            String::NewFromUtf8(env->isolate(), mem->data,
2075
                                NewStringType::kNormal,
2076
5272
                                mem->length).ToLocalChecked()).Check();
2077
1318
  USE(BIO_reset(bio.get()));
2078
2079
1318
  ASN1_TIME_print(bio.get(), X509_get_notAfter(cert));
2080
1318
  BIO_get_mem_ptr(bio.get(), &mem);
2081
  info->Set(context, env->valid_to_string(),
2082
            String::NewFromUtf8(env->isolate(), mem->data,
2083
                                NewStringType::kNormal,
2084
5272
                                mem->length).ToLocalChecked()).Check();
2085
1318
  bio.reset();
2086
2087
  unsigned char md[EVP_MAX_MD_SIZE];
2088
  unsigned int md_size;
2089
  char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
2090
1318
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
2091
1318
      AddFingerprintDigest(md, md_size, &fingerprint);
2092
      info->Set(context, env->fingerprint_string(),
2093
5272
                OneByteString(env->isolate(), fingerprint)).Check();
2094
  }
2095
1318
  if (X509_digest(cert, EVP_sha256(), md, &md_size)) {
2096
1318
      AddFingerprintDigest(md, md_size, &fingerprint);
2097
      info->Set(context, env->fingerprint256_string(),
2098
5272
                OneByteString(env->isolate(), fingerprint)).Check();
2099
  }
2100
2101
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
2102
1318
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
2103
1318
  if (eku) {
2104
128
    Local<Array> ext_key_usage = Array::New(env->isolate());
2105
    char buf[256];
2106
2107
128
    int j = 0;
2108
380
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku.get()); i++) {
2109
252
      if (OBJ_obj2txt(buf,
2110
                      sizeof(buf),
2111
252
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
2112
252
        ext_key_usage->Set(context,
2113
                           j++,
2114
1008
                           OneByteString(env->isolate(), buf)).Check();
2115
      }
2116
    }
2117
2118
128
    eku.reset();
2119
384
    info->Set(context, env->ext_key_usage_string(), ext_key_usage).Check();
2120
  }
2121
2122
1318
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
2123
1318
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
2124
1318
    if (bn) {
2125
1318
      OpenSSLBuffer buf(BN_bn2hex(bn.get()));
2126
1318
      if (buf) {
2127
        info->Set(context, env->serial_number_string(),
2128
5272
                  OneByteString(env->isolate(), buf.get())).Check();
2129
1318
      }
2130
1318
    }
2131
  }
2132
2133
  // Raw DER certificate
2134
1318
  int size = i2d_X509(cert, nullptr);
2135
2636
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
2136
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
2137
1318
      Buffer::Data(buff));
2138
1318
  i2d_X509(cert, &serialized);
2139
3954
  info->Set(context, env->raw_string(), buff).Check();
2140
2141
2636
  return scope.Escape(info);
2142
}
2143
2144
2145
445
static Local<Object> AddIssuerChainToObject(X509Pointer* cert,
2146
                                            Local<Object> object,
2147
                                            StackOfX509&& peer_certs,
2148
                                            Environment* const env) {
2149
445
  Local<Context> context = env->isolate()->GetCurrentContext();
2150
445
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
2151
  for (;;) {
2152
    int i;
2153
916
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
2154
404
      X509* ca = sk_X509_value(peer_certs.get(), i);
2155
404
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
2156
2
        continue;
2157
2158
402
      Local<Object> ca_info = X509ToObject(env, ca);
2159
1206
      object->Set(context, env->issuercert_string(), ca_info).Check();
2160
402
      object = ca_info;
2161
2162
      // NOTE: Intentionally freeing cert that is not used anymore.
2163
      // Delete cert and continue aggregating issuers.
2164
402
      cert->reset(sk_X509_delete(peer_certs.get(), i));
2165
402
      break;
2166
    }
2167
2168
    // Issuer not found, break out of the loop.
2169
456
    if (i == sk_X509_num(peer_certs.get()))
2170
445
      break;
2171
11
  }
2172
445
  return object;
2173
}
2174
2175
2176
445
static StackOfX509 CloneSSLCerts(X509Pointer&& cert,
2177
                                 const STACK_OF(X509)* const ssl_certs) {
2178
445
  StackOfX509 peer_certs(sk_X509_new(nullptr));
2179
445
  if (cert)
2180
    sk_X509_push(peer_certs.get(), cert.release());
2181
1294
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
2182
849
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
2183

849
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
2184
      return StackOfX509();
2185
    // `cert` is now managed by the stack.
2186
849
    cert.release();
2187
849
  }
2188
445
  return peer_certs;
2189
}
2190
2191
2192
445
static Local<Object> GetLastIssuedCert(X509Pointer* cert,
2193
                                       const SSLPointer& ssl,
2194
                                       Local<Object> issuer_chain,
2195
                                       Environment* const env) {
2196
445
  Local<Context> context = env->isolate()->GetCurrentContext();
2197
1307
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
2198
    X509* ca;
2199
417
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
2200
      break;
2201
2202
417
    Local<Object> ca_info = X509ToObject(env, ca);
2203
1251
    issuer_chain->Set(context, env->issuercert_string(), ca_info).Check();
2204
417
    issuer_chain = ca_info;
2205
2206
    // Delete previous cert and continue aggregating issuers.
2207
417
    cert->reset(ca);
2208
  }
2209
445
  return issuer_chain;
2210
}
2211
2212
2213
template <class Base>
2214
491
void SSLWrap<Base>::GetPeerCertificate(
2215
    const FunctionCallbackInfo<Value>& args) {
2216
  Base* w;
2217
982
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2218
491
  Environment* env = w->ssl_env();
2219
2220
  ClearErrorOnReturn clear_error_on_return;
2221
2222
  Local<Object> result;
2223
  // Used to build the issuer certificate chain.
2224
  Local<Object> issuer_chain;
2225
2226
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
2227
  // contains the `peer_certificate`, but on server it doesn't.
2228
  X509Pointer cert(
2229
982
      w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) : nullptr);
2230
491
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_.get());
2231


491
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
2232
3
    goto done;
2233
2234
  // Short result requested.
2235


1952
  if (args.Length() < 1 || !args[0]->IsTrue()) {
2236
43
    result = X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
2237
43
    goto done;
2238
  }
2239
2240
890
  if (auto peer_certs = CloneSSLCerts(std::move(cert), ssl_certs)) {
2241
    // First and main certificate.
2242
445
    X509Pointer cert(sk_X509_value(peer_certs.get(), 0));
2243
445
    CHECK(cert);
2244
445
    result = X509ToObject(env, cert.release());
2245
2246
445
    issuer_chain =
2247
445
        AddIssuerChainToObject(&cert, result, std::move(peer_certs), env);
2248
445
    issuer_chain = GetLastIssuedCert(&cert, w->ssl_, issuer_chain, env);
2249
    // Last certificate should be self-signed.
2250
445
    if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK)
2251
      issuer_chain->Set(env->context(),
2252
                        env->issuercert_string(),
2253
1780
                        issuer_chain).Check();
2254
  }
2255
2256
 done:
2257
1473
  args.GetReturnValue().Set(result);
2258
}
2259
2260
2261
template <class Base>
2262
12
void SSLWrap<Base>::GetCertificate(
2263
    const FunctionCallbackInfo<Value>& args) {
2264
  Base* w;
2265
24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2266
12
  Environment* env = w->ssl_env();
2267
2268
  ClearErrorOnReturn clear_error_on_return;
2269
2270
  Local<Object> result;
2271
2272
12
  X509* cert = SSL_get_certificate(w->ssl_.get());
2273
2274
12
  if (cert != nullptr)
2275
11
    result = X509ToObject(env, cert);
2276
2277
24
  args.GetReturnValue().Set(result);
2278
}
2279
2280
2281
template <class Base>
2282
3
void SSLWrap<Base>::GetFinished(const FunctionCallbackInfo<Value>& args) {
2283
3
  Environment* env = Environment::GetCurrent(args);
2284
2285
  Base* w;
2286
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2287
2288
  // We cannot just pass nullptr to SSL_get_finished()
2289
  // because it would further be propagated to memcpy(),
2290
  // where the standard requirements as described in ISO/IEC 9899:2011
2291
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2292
  // Thus, we use a dummy byte.
2293
  char dummy[1];
2294
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
2295
3
  if (len == 0)
2296
1
    return;
2297
2298
2
  AllocatedBuffer buf = env->AllocateManaged(len);
2299
2
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf.data(), len));
2300
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
2301
}
2302
2303
2304
template <class Base>
2305
3
void SSLWrap<Base>::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
2306
3
  Environment* env = Environment::GetCurrent(args);
2307
2308
  Base* w;
2309
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2310
2311
  // We cannot just pass nullptr to SSL_get_peer_finished()
2312
  // because it would further be propagated to memcpy(),
2313
  // where the standard requirements as described in ISO/IEC 9899:2011
2314
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2315
  // Thus, we use a dummy byte.
2316
  char dummy[1];
2317
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
2318
3
  if (len == 0)
2319
1
    return;
2320
2321
2
  AllocatedBuffer buf = env->AllocateManaged(len);
2322
2
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf.data(), len));
2323
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
2324
}
2325
2326
2327
template <class Base>
2328
19
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
2329
19
  Environment* env = Environment::GetCurrent(args);
2330
2331
  Base* w;
2332
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2333
2334
19
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2335
19
  if (sess == nullptr)
2336
    return;
2337
2338
19
  int slen = i2d_SSL_SESSION(sess, nullptr);
2339
19
  if (slen <= 0)
2340
    return;  // Invalid or malformed session.
2341
2342
19
  AllocatedBuffer sbuf = env->AllocateManaged(slen);
2343
19
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf.data());
2344
19
  CHECK_LT(0, i2d_SSL_SESSION(sess, &p));
2345
57
  args.GetReturnValue().Set(sbuf.ToBuffer().ToLocalChecked());
2346
}
2347
2348
2349
template <class Base>
2350
120
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
2351
120
  Environment* env = Environment::GetCurrent(args);
2352
2353
  Base* w;
2354
120
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2355
2356
120
  if (args.Length() < 1) {
2357
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
2358
  }
2359
2360
120
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
2361
240
  ArrayBufferViewContents<unsigned char> sbuf(args[0].As<ArrayBufferView>());
2362
2363
120
  const unsigned char* p = sbuf.data();
2364
120
  SSLSessionPointer sess(d2i_SSL_SESSION(nullptr, &p, sbuf.length()));
2365
2366
120
  if (sess == nullptr)
2367
    return;
2368
2369
120
  int r = SSL_set_session(w->ssl_.get(), sess.get());
2370
2371
120
  if (!r)
2372
    return env->ThrowError("SSL_set_session error");
2373
}
2374
2375
2376
template <class Base>
2377
10
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
2378
  Base* w;
2379
20
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2380
2381
  // TODO(@sam-github) check arg length and types in js, and CHECK in c++
2382

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2383
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
2384
2385
10
    const unsigned char* p = sbuf.data();
2386
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
2387
2388
    // Setup next session and move hello to the BIO buffer
2389
10
    w->next_sess_.reset(sess);
2390
  }
2391
}
2392
2393
2394
template <class Base>
2395
524
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2396
  Base* w;
2397
1048
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2398
524
  bool yes = SSL_session_reused(w->ssl_.get());
2399
1572
  args.GetReturnValue().Set(yes);
2400
}
2401
2402
2403
template <class Base>
2404
19
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2405
  Base* w;
2406
38
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2407
19
  w->hello_parser_.End();
2408
}
2409
2410
2411
template <class Base>
2412
92
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2413
  Base* w;
2414
93
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2415
2416
  ClearErrorOnReturn clear_error_on_return;
2417
2418
92
  if (SSL_renegotiate(w->ssl_.get()) != 1) {
2419
1
    return ThrowCryptoError(w->ssl_env(), ERR_get_error());
2420
91
  }
2421
}
2422
2423
2424
template <class Base>
2425
18
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2426
  Base* w;
2427
18
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2428
18
  Environment* env = w->ssl_env();
2429
2430
18
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2431
18
  if (sess == nullptr)
2432
    return;
2433
2434
  const unsigned char* ticket;
2435
  size_t length;
2436
18
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2437
2438
18
  if (ticket == nullptr)
2439
    return;
2440
2441
  Local<Object> buff = Buffer::Copy(
2442
36
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2443
2444
36
  args.GetReturnValue().Set(buff);
2445
}
2446
2447
2448
template <class Base>
2449
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2450
  Base* w;
2451
16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2452
8
  w->awaiting_new_session_ = false;
2453
8
  w->NewSessionDoneCb();
2454
}
2455
2456
2457
template <class Base>
2458
2
void SSLWrap<Base>::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
2459
  Base* w;
2460
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2461
2
  Environment* env = w->env();
2462
2463
2
  if (args.Length() < 1)
2464
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
2465
2466
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
2467
2468
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
2469
}
2470
2471
2472
template <class Base>
2473
4
void SSLWrap<Base>::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
2474
  Base* w;
2475
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2476
2477
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
2478
}
2479
2480
2481
template <class Base>
2482
876
void SSLWrap<Base>::GetEphemeralKeyInfo(
2483
    const FunctionCallbackInfo<Value>& args) {
2484
  Base* w;
2485
876
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2486
876
  Environment* env = Environment::GetCurrent(args);
2487
876
  Local<Context> context = env->context();
2488
2489
876
  CHECK(w->ssl_);
2490
2491
  // tmp key is available on only client
2492
876
  if (w->is_server())
2493
14
    return args.GetReturnValue().SetNull();
2494
2495
869
  Local<Object> info = Object::New(env->isolate());
2496
2497
  EVP_PKEY* raw_key;
2498
869
  if (SSL_get_server_tmp_key(w->ssl_.get(), &raw_key)) {
2499
814
    EVPKeyPointer key(raw_key);
2500
814
    int kid = EVP_PKEY_id(key.get());
2501
814
    switch (kid) {
2502
      case EVP_PKEY_DH:
2503
        info->Set(context, env->type_string(),
2504
24
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH")).Check();
2505
        info->Set(context, env->size_string(),
2506
24
                  Integer::New(env->isolate(), EVP_PKEY_bits(key.get())))
2507
12
            .Check();
2508
6
        break;
2509
      case EVP_PKEY_EC:
2510
      case EVP_PKEY_X25519:
2511
      case EVP_PKEY_X448:
2512
        {
2513
          const char* curve_name;
2514
808
          if (kid == EVP_PKEY_EC) {
2515
7
            EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key.get());
2516
7
            int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2517
7
            curve_name = OBJ_nid2sn(nid);
2518
7
            EC_KEY_free(ec);
2519
          } else {
2520
801
            curve_name = OBJ_nid2sn(kid);
2521
          }
2522
          info->Set(context, env->type_string(),
2523
3232
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")).Check();
2524
          info->Set(context, env->name_string(),
2525
                    OneByteString(args.GetIsolate(),
2526
3232
                                  curve_name)).Check();
2527
          info->Set(context, env->size_string(),
2528
                    Integer::New(env->isolate(),
2529
3232
                                 EVP_PKEY_bits(key.get()))).Check();
2530
        }
2531
808
        break;
2532
      default:
2533
        break;
2534
814
    }
2535
  }
2536
  // TODO(@sam-github) semver-major: else return ThrowCryptoError(env,
2537
  // ERR_get_error())
2538
2539
1738
  return args.GetReturnValue().Set(info);
2540
}
2541
2542
2543
#ifdef SSL_set_max_send_fragment
2544
template <class Base>
2545
3
void SSLWrap<Base>::SetMaxSendFragment(
2546
    const FunctionCallbackInfo<Value>& args) {
2547


12
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2548
2549
  Base* w;
2550
6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2551
2552
12
  int rv = SSL_set_max_send_fragment(
2553
      w->ssl_.get(),
2554
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2555
6
  args.GetReturnValue().Set(rv);
2556
}
2557
#endif  // SSL_set_max_send_fragment
2558
2559
2560
template <class Base>
2561
939
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2562
  Base* w;
2563
1453
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2564
2565
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2566
  // peer certificate is questionable but it's compatible with what was
2567
  // here before.
2568
  long x509_verify_error =  // NOLINT(runtime/int)
2569
939
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2570
939
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_.get())) {
2571
938
    X509_free(peer_cert);
2572
938
    x509_verify_error = SSL_get_verify_result(w->ssl_.get());
2573
  }
2574
2575
939
  if (x509_verify_error == X509_V_OK)
2576
1028
    return args.GetReturnValue().SetNull();
2577
2578
425
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2579
425
  const char* code = reason;
2580
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2581







425
  switch (x509_verify_error) {
2582
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2583
1
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2584
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2585
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2586
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2587
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2588
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2589
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2590
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2591
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2592
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2593
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2594
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2595
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2596
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2597
    CASE_X509_ERR(OUT_OF_MEM)
2598
248
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2599
13
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2600
4
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2601
156
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2602
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2603
1
    CASE_X509_ERR(CERT_REVOKED)
2604
    CASE_X509_ERR(INVALID_CA)
2605
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2606
1
    CASE_X509_ERR(INVALID_PURPOSE)
2607
    CASE_X509_ERR(CERT_UNTRUSTED)
2608
    CASE_X509_ERR(CERT_REJECTED)
2609
  }
2610
#undef CASE_X509_ERR
2611
2612
425
  Isolate* isolate = args.GetIsolate();
2613
425
  Local<String> reason_string = OneByteString(isolate, reason);
2614
425
  Local<Value> exception_value = Exception::Error(reason_string);
2615
  Local<Object> exception_object =
2616
1275
    exception_value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2617
2125
  exception_object->Set(w->env()->context(), w->env()->code_string(),
2618
                        OneByteString(isolate, code)).Check();
2619
850
  args.GetReturnValue().Set(exception_object);
2620
}
2621
2622
2623
template <class Base>
2624
49
void SSLWrap<Base>::GetCipher(const FunctionCallbackInfo<Value>& args) {
2625
  Base* w;
2626
49
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2627
49
  Environment* env = w->ssl_env();
2628
49
  Local<Context> context = env->context();
2629
2630
49
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get());
2631
49
  if (c == nullptr)
2632
    return;
2633
2634
49
  Local<Object> info = Object::New(env->isolate());
2635
49
  const char* cipher_name = SSL_CIPHER_get_name(c);
2636
  info->Set(context, env->name_string(),
2637
196
            OneByteString(args.GetIsolate(), cipher_name)).Check();
2638
49
  const char* cipher_version = SSL_CIPHER_get_version(c);
2639
  info->Set(context, env->version_string(),
2640
196
            OneByteString(args.GetIsolate(), cipher_version)).Check();
2641
98
  args.GetReturnValue().Set(info);
2642
}
2643
2644
2645
template <class Base>
2646
2
void SSLWrap<Base>::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
2647
  Base* w;
2648
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2649
2
  Environment* env = w->ssl_env();
2650
2
  std::vector<Local<Value>> ret_arr;
2651
2652
2
  SSL* ssl = w->ssl_.get();
2653
  int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
2654
2
                                    nullptr);
2655
2656
5
  for (int i = 0; i < nsig; i++) {
2657
    int hash_nid;
2658
    int sign_nid;
2659
3
    std::string sig_with_md;
2660
2661
3
    SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
2662
                           nullptr);
2663
2664


3
    switch (sign_nid) {
2665
      case EVP_PKEY_RSA:
2666
        sig_with_md = "RSA+";
2667
        break;
2668
2669
      case EVP_PKEY_RSA_PSS:
2670
2
        sig_with_md = "RSA-PSS+";
2671
2
        break;
2672
2673
      case EVP_PKEY_DSA:
2674
        sig_with_md = "DSA+";
2675
        break;
2676
2677
      case EVP_PKEY_EC:
2678
1
        sig_with_md = "ECDSA+";
2679
1
        break;
2680
2681
      case NID_ED25519:
2682
        sig_with_md = "Ed25519+";
2683
        break;
2684
2685
      case NID_ED448:
2686
        sig_with_md = "Ed448+";
2687
        break;
2688
2689
      case NID_id_GostR3410_2001:
2690
        sig_with_md = "gost2001+";
2691
        break;
2692
2693
      case NID_id_GostR3410_2012_256:
2694
        sig_with_md = "gost2012_256+";
2695
        break;
2696
2697
      case NID_id_GostR3410_2012_512:
2698
        sig_with_md = "gost2012_512+";
2699
        break;
2700
2701
      default:
2702
        const char* sn = OBJ_nid2sn(sign_nid);
2703
2704
        if (sn != nullptr) {
2705
          sig_with_md = std::string(sn) + "+";
2706
        } else {
2707
          sig_with_md = "UNDEF+";
2708
        }
2709
        break;
2710
    }
2711
2712
3
    const char* sn_hash = OBJ_nid2sn(hash_nid);
2713
3
    if (sn_hash != nullptr) {
2714
3
      sig_with_md += std::string(sn_hash);
2715
    } else {
2716
      sig_with_md += "UNDEF";
2717
    }
2718
2719
6
    ret_arr.push_back(OneByteString(env->isolate(), sig_with_md.c_str()));
2720
  }
2721
2722
  args.GetReturnValue().Set(
2723
6
                 Array::New(env->isolate(), ret_arr.data(), ret_arr.size()));
2724
}
2725
2726
2727
template <class Base>
2728
547
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2729
  Base* w;
2730
1094
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2731
2732
547
  const char* tls_version = SSL_get_version(w->ssl_.get());
2733
1641
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2734
}
2735
2736
2737
template <class Base>
2738
25
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2739
                                      const unsigned char** out,
2740
                                      unsigned char* outlen,
2741
                                      const unsigned char* in,
2742
                                      unsigned int inlen,
2743
                                      void* arg) {
2744
25
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2745
25
  Environment* env = w->env();
2746
25
  HandleScope handle_scope(env->isolate());
2747
25
  Context::Scope context_scope(env->context());
2748
2749
  Local<Value> alpn_buffer =
2750
25
      w->object()->GetPrivate(
2751
          env->context(),
2752
100
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2753
25
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
2754
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2755
25
                                     alpn_protos.data(), alpn_protos.length(),
2756
25
                                     in, inlen);
2757
  // According to 3.2. Protocol Selection of RFC7301, fatal
2758
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2759
  // support it yet. See
2760
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2761
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2762
50
                                          : SSL_TLSEXT_ERR_NOACK;
2763
}
2764
2765
2766
template <class Base>
2767
1691
void SSLWrap<Base>::GetALPNNegotiatedProto(
2768
    const FunctionCallbackInfo<Value>& args) {
2769
  Base* w;
2770
3382
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2771
2772
  const unsigned char* alpn_proto;
2773
  unsigned int alpn_proto_len;
2774
2775
1691
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2776
2777
  Local<Value> result;
2778
1691
  if (alpn_proto_len == 0) {
2779
3290
    result = False(args.GetIsolate());
2780

86
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
2781
40
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
2782
80
    result = w->env()->h2_string();
2783

8
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
2784
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
2785
4
    result = w->env()->http_1_1_string();
2786
  } else {
2787
12
    result = OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len);
2788
  }
2789
2790
3382
  args.GetReturnValue().Set(result);
2791
}
2792
2793
2794
template <class Base>
2795
198
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2796
  Base* w;
2797
198
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2798
198
  Environment* env = w->env();
2799

396
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2800
    return env->ThrowTypeError("Must give a Buffer as first argument");
2801
2802
198
  if (w->is_client()) {
2803
30
    ArrayBufferViewContents<unsigned char> alpn_protos(args[0]);
2804
    int r = SSL_set_alpn_protos(
2805
30
        w->ssl_.get(), alpn_protos.data(), alpn_protos.length());
2806
30
    CHECK_EQ(r, 0);
2807
  } else {
2808
504
    CHECK(
2809
        w->object()->SetPrivate(
2810
            env->context(),
2811
            env->alpn_buffer_private_symbol(),
2812
            args[0]).FromJust());
2813
    // Server should select ALPN protocol from list of advertised by client
2814
336
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2815
                               SelectALPNCallback,
2816
168
                               nullptr);
2817
  }
2818
}
2819
2820
2821
template <class Base>
2822
8
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2823
8
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2824
8
  Environment* env = w->env();
2825
8
  HandleScope handle_scope(env->isolate());
2826
2827
8
  if (w->is_client()) {
2828
    // Incoming response
2829
    const unsigned char* resp;
2830
4
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2831
    Local<Value> arg;
2832
4
    if (resp == nullptr) {
2833
4
      arg = Null(env->isolate());
2834
    } else {
2835
4
      arg =
2836
2
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2837
          .ToLocalChecked();
2838
    }
2839
2840
4
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2841
2842
    // No async acceptance is possible, so always return 1 to accept the
2843
    // response.  The listener for 'OCSPResponse' event has no control over
2844
    // return value, but it can .destroy() the connection if the response is not
2845
    // acceptable.
2846
4
    return 1;
2847
  } else {
2848
    // Outgoing response
2849
8
    if (w->ocsp_response_.IsEmpty())
2850
2
      return SSL_TLSEXT_ERR_NOACK;
2851
2852
    Local<ArrayBufferView> obj = PersistentToLocal::Default(env->isolate(),
2853
2
                                                            w->ocsp_response_);
2854
2
    size_t len = obj->ByteLength();
2855
2856
    // OpenSSL takes control of the pointer after accepting it
2857
2
    unsigned char* data = MallocOpenSSL<unsigned char>(len);
2858
2
    obj->CopyContents(data, len);
2859
2860
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2861
      OPENSSL_free(data);
2862
2
    w->ocsp_response_.Reset();
2863
2864
2
    return SSL_TLSEXT_ERR_OK;
2865
8
  }
2866
}
2867
2868
2869
template <class Base>
2870
22
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2871
22
  cert_cb_ = cb;
2872
22
  cert_cb_arg_ = arg;
2873
22
}
2874
2875
2876
template <class Base>
2877
888
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2878
888
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2879
2880
888
  if (!w->is_server())
2881
42
    return 1;
2882
2883
846
  if (!w->is_waiting_cert_cb())
2884
824
    return 1;
2885
2886
22
  if (w->cert_cb_running_)
2887
    // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
2888
    // handshake will continue after certcb is done.
2889
    return -1;
2890
2891
22
  Environment* env = w->env();
2892
22
  Local<Context> context = env->context();
2893
22
  HandleScope handle_scope(env->isolate());
2894
  Context::Scope context_scope(context);
2895
22
  w->cert_cb_running_ = true;
2896
2897
22
  Local<Object> info = Object::New(env->isolate());
2898
2899
22
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2900
22
  if (servername == nullptr) {
2901
    info->Set(context,
2902
              env->servername_string(),
2903
16
              String::Empty(env->isolate())).Check();
2904
  } else {
2905
    Local<String> str = OneByteString(env->isolate(), servername,
2906
18
                                      strlen(servername));
2907
54
    info->Set(context, env->servername_string(), str).Check();
2908
  }
2909
2910
22
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
2911
  info->Set(context, env->ocsp_request_string(),
2912
88
            Boolean::New(env->isolate(), ocsp)).Check();
2913
2914
44
  Local<Value> argv[] = { info };
2915
22
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2916
2917
22
  if (!w->cert_cb_running_)
2918
9
    return 1;
2919
2920
  // Performing async action, wait...
2921
35
  return -1;
2922
}
2923
2924
2925
template <class Base>
2926
19
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2927
  Base* w;
2928
22
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2929
19
  Environment* env = w->env();
2930
2931

19
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2932
2933
19
  Local<Object> object = w->object();
2934
  Local<Value> ctx = object->Get(env->context(),
2935
76
                                 env->sni_context_string()).ToLocalChecked();
2936
19
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2937
2938
  // Not an object, probably undefined or null
2939
19
  if (!ctx->IsObject())
2940
8
    goto fire_cb;
2941
2942
11
  if (cons->HasInstance(ctx)) {
2943
    SecureContext* sc;
2944
10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2945
9
    w->sni_context_.Reset(env->isolate(), ctx);
2946
2947
    int rv;
2948
2949
    // NOTE: reference count is not increased by this API methods
2950
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_.get());
2951
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_.get());
2952
    STACK_OF(X509)* chain;
2953
2954
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_.get(), &chain);
2955
9
    if (rv)
2956
9
      rv = SSL_use_certificate(w->ssl_.get(), x509);
2957
9
    if (rv)
2958
8
      rv = SSL_use_PrivateKey(w->ssl_.get(), pkey);
2959

9
    if (rv && chain != nullptr)
2960
1
      rv = SSL_set1_chain(w->ssl_.get(), chain);
2961
9
    if (rv)
2962
8
      rv = w->SetCACerts(sc);
2963
9
    if (!rv) {
2964
      // Not clear why sometimes we throw error, and sometimes we call
2965
      // onerror(). Both cause .destroy(), but onerror does a bit more.
2966
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2967
1
      if (!err)
2968
        return env->ThrowError("CertCbDone");
2969
1
      return ThrowCryptoError(env, err);
2970
    }
2971
  } else {
2972
    // Failure: incorrect SNI context object
2973
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2974
2
    w->MakeCallback(env->onerror_string(), 1, &err);
2975
2
    return;
2976
  }
2977
2978
 fire_cb:
2979
  CertCb cb;
2980
  void* arg;
2981
2982
16
  cb = w->cert_cb_;
2983
16
  arg = w->cert_cb_arg_;
2984
2985
16
  w->cert_cb_running_ = false;
2986
16
  w->cert_cb_ = nullptr;
2987
16
  w->cert_cb_arg_ = nullptr;
2988
2989
16
  cb(arg);
2990
}
2991
2992
2993
template <class Base>
2994
24347
void SSLWrap<Base>::DestroySSL() {
2995
24347
  if (!ssl_)
2996
36467
    return;
2997
2998
12227
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2999
12227
  ssl_.reset();
3000
}
3001
3002
3003
template <class Base>
3004
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
3005
  ConfigureSecureContext(sc);
3006
  CHECK_EQ(SSL_set_SSL_CTX(ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
3007
3008
  SetCACerts(sc);
3009
}
3010
3011
3012
template <class Base>
3013
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
3014
8
  int err = SSL_set1_verify_cert_store(ssl_.get(),
3015
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
3016
8
  if (err != 1)
3017
    return err;
3018
3019
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
3020
8
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
3021
3022
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
3023
8
  SSL_set_client_CA_list(ssl_.get(), list);
3024
8
  return 1;
3025
}
3026
3027
2143
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
3028
  // From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
3029
  //
3030
  //   If VerifyCallback returns 1, the verification process is continued. If
3031
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
3032
  //   terminated with respect to verification failures and the connection will
3033
  //   be established. The calling process can however retrieve the error code
3034
  //   of the last verification error using SSL_get_verify_result(3) or by
3035
  //   maintaining its own error storage managed by VerifyCallback.
3036
  //
3037
  // Since we cannot perform I/O quickly enough with X509_STORE_CTX_ APIs in
3038
  // this callback, we ignore all preverify_ok errors and let the handshake
3039
  // continue. It is imperative that the user use Connection::VerifyError after
3040
  // the 'secure' callback has been made.
3041
2143
  return 1;
3042
}
3043
3044
3377
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
3045
3377
  const int mode = EVP_CIPHER_mode(cipher);
3046
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
3047
  // but its mode is 0 which doesn't indicate
3048
6707
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
3049
6116
         mode == EVP_CIPH_CCM_MODE ||
3050

7502
         mode == EVP_CIPH_GCM_MODE ||
3051
4716
         IS_OCB_MODE(mode);
3052
}
3053
3054
1471
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
3055
1471
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
3056
1471
  return IsSupportedAuthenticatedMode(cipher);
3057
}
3058
3059
enum class ParseKeyResult {
3060
  kParseKeyOk,
3061
  kParseKeyNotRecognized,
3062
  kParseKeyNeedPassphrase,
3063
  kParseKeyFailed
3064
};
3065
3066
2821
static ParseKeyResult TryParsePublicKey(
3067
    EVPKeyPointer* pkey,
3068
    const BIOPointer& bp,
3069
    const char* name,
3070
    // NOLINTNEXTLINE(runtime/int)
3071
    const std::function<EVP_PKEY*(const unsigned char** p, long l)>& parse) {
3072
  unsigned char* der_data;
3073
  long der_len;  // NOLINT(runtime/int)
3074
3075
  // This skips surrounding data and decodes PEM to DER.
3076
  {
3077
2821
    MarkPopErrorOnReturn mark_pop_error_on_return;
3078
2821
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
3079
2821
                           bp.get(), nullptr, nullptr) != 1)
3080
1956
      return ParseKeyResult::kParseKeyNotRecognized;
3081
  }
3082
3083
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
3084
865
  const unsigned char* p = der_data;
3085
865
  pkey->reset(parse(&p, der_len));
3086
865
  OPENSSL_clear_free(der_data, der_len);
3087
3088
  return *pkey ? ParseKeyResult::kParseKeyOk :
3089
865
                 ParseKeyResult::kParseKeyFailed;
3090
}
3091
3092
1024
static ParseKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
3093
                                        const char* key_pem,
3094
                                        int key_pem_len) {
3095
1024
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
3096
1024
  if (!bp)
3097
    return ParseKeyResult::kParseKeyFailed;
3098
3099
  ParseKeyResult ret;
3100
3101
  // Try parsing as a SubjectPublicKeyInfo first.
3102
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
3103
118
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3104
        return d2i_PUBKEY(nullptr, p, l);
3105
1142
      });
3106
1024
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
3107
118
    return ret;
3108
3109
  // Maybe it is PKCS#1.
3110
906
  CHECK(BIO_reset(bp.get()));
3111
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
3112
15
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3113
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
3114
921
      });
3115
906
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
3116
15
    return ret;
3117
3118
  // X.509 fallback.
3119
891
  CHECK(BIO_reset(bp.get()));
3120
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
3121
732
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3122
732
        X509Pointer x509(d2i_X509(nullptr, p, l));
3123
1464
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
3124
1623
      });
3125
}
3126
3127
21
static ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
3128
                                     const PublicKeyEncodingConfig& config,
3129
                                     const char* key,
3130
                                     size_t key_len) {
3131
21
  if (config.format_ == kKeyFormatPEM) {
3132
    return ParsePublicKeyPEM(pkey, key, key_len);
3133
  } else {
3134
21
    CHECK_EQ(config.format_, kKeyFormatDER);
3135
3136
21
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3137
42
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3138
21
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
3139
    } else {
3140
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
3141
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
3142
    }
3143
3144
    return *pkey ? ParseKeyResult::kParseKeyOk :
3145
21
                   ParseKeyResult::kParseKeyFailed;
3146
  }
3147
}
3148
3149
46
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
3150
                                               BIO* bio,
3151
                                               PKFormatType format) {
3152
  BUF_MEM* bptr;
3153
46
  BIO_get_mem_ptr(bio, &bptr);
3154
46
  if (format == kKeyFormatPEM) {
3155
    // PEM is an ASCII format, so we will return it as a string.
3156
    return String::NewFromUtf8(env->isolate(), bptr->data,
3157
                               NewStringType::kNormal,
3158
74
                               bptr->length).ToLocalChecked();
3159
  } else {
3160
9
    CHECK_EQ(format, kKeyFormatDER);
3161
    // DER is binary, return it as a buffer.
3162
18
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
3163
  }
3164
}
3165
3166
25
static bool WritePublicKeyInner(EVP_PKEY* pkey,
3167
                                const BIOPointer& bio,
3168
                                const PublicKeyEncodingConfig& config) {
3169
50
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3170
    // PKCS#1 is only valid for RSA keys.
3171
8
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
3172
8
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
3173
8
    if (config.format_ == kKeyFormatPEM) {
3174
      // Encode PKCS#1 as PEM.
3175
3
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
3176
    } else {
3177
      // Encode PKCS#1 as DER.
3178
5
      CHECK_EQ(config.format_, kKeyFormatDER);
3179
5
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
3180
8
    }
3181
  } else {
3182
34
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
3183
17
    if (config.format_ == kKeyFormatPEM) {
3184
      // Encode SPKI as PEM.
3185
17
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
3186
    } else {
3187
      // Encode SPKI as DER.
3188
      CHECK_EQ(config.format_, kKeyFormatDER);
3189
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
3190
    }
3191
  }
3192
}
3193
3194
25
static MaybeLocal<Value> WritePublicKey(Environment* env,
3195
                                        EVP_PKEY* pkey,
3196
                                        const PublicKeyEncodingConfig& config) {
3197
25
  BIOPointer bio(BIO_new(BIO_s_mem()));
3198
25
  CHECK(bio);
3199
3200
25
  if (!WritePublicKeyInner(pkey, bio, config)) {
3201
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
3202
    return MaybeLocal<Value>();
3203
  }
3204
50
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
3205
}
3206
3207
56
static bool IsASN1Sequence(const unsigned char* data, size_t size,
3208
                           size_t* data_offset, size_t* data_size) {
3209

56
  if (size < 2 || data[0] != 0x30)
3210
    return false;
3211
3212
56
  if (data[1] & 0x80) {
3213
    // Long form.
3214
36
    size_t n_bytes = data[1] & ~0x80;
3215

36
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
3216
      return false;
3217
36
    size_t length = 0;
3218
108
    for (size_t i = 0; i < n_bytes; i++)
3219
72
      length = (length << 8) | data[i + 2];
3220
36
    *data_offset = 2 + n_bytes;
3221
36
    *data_size = std::min(size - 2 - n_bytes, length);
3222
  } else {
3223
    // Short form.
3224
20
    *data_offset = 2;
3225
20
    *data_size = std::min<size_t>(size - 2, data[1]);
3226
  }
3227
3228
56
  return true;
3229
}
3230
3231
30
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
3232
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
3233
  size_t offset, len;
3234
30
  if (!IsASN1Sequence(data, size, &offset, &len))
3235
    return false;
3236
3237
  // An RSAPrivateKey sequence always starts with a single-byte integer whose
3238
  // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
3239
  // (which is the product of two primes and therefore at least 4), so we can
3240
  // decide the type of the structure based on the first three bytes of the
3241
  // sequence.
3242
60
  return len >= 3 &&
3243
60
         data[offset] == 2 &&
3244

69
         data[offset + 1] == 1 &&
3245
39
         !(data[offset + 2] & 0xfe);
3246
}
3247
3248
26
static bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
3249
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
3250
  size_t offset, len;
3251
26
  if (!IsASN1Sequence(data, size, &offset, &len))
3252
    return false;
3253
3254
  // A PrivateKeyInfo sequence always starts with an integer whereas an
3255
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
3256

52
  return len >= 1 &&
3257
52
         data[offset] != 2;
3258
}
3259
3260
355
static ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
3261
                                      const PrivateKeyEncodingConfig& config,
3262
                                      const char* key,
3263
                                      size_t key_len) {
3264
  // OpenSSL needs a non-const pointer, that's why the const_cast is required.
3265
355
  char* const passphrase = const_cast<char*>(config.passphrase_.get());
3266
3267
355
  if (config.format_ == kKeyFormatPEM) {
3268
320
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
3269
320
    if (!bio)
3270
1
      return ParseKeyResult::kParseKeyFailed;
3271
3272
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
3273
                                        nullptr,
3274
                                        PasswordCallback,
3275
319
                                        passphrase));
3276
  } else {
3277
35
    CHECK_EQ(config.format_, kKeyFormatDER);
3278
3279
70
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3280
9
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3281
9
      pkey->reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
3282
52
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
3283
26
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
3284
26
      if (!bio)
3285
        return ParseKeyResult::kParseKeyFailed;
3286
3287
26
      if (IsEncryptedPrivateKeyInfo(
3288
              reinterpret_cast<const unsigned char*>(key), key_len)) {
3289
        pkey->reset(d2i_PKCS8PrivateKey_bio(bio.get(),
3290
                                            nullptr,
3291
                                            PasswordCallback,
3292
17
                                            passphrase));
3293
      } else {
3294
9
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
3295
9
        if (p8inf)
3296
9
          pkey->reset(EVP_PKCS82PKEY(p8inf.get()));
3297
26
      }
3298
    } else {
3299
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
3300
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3301
      pkey->reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
3302
    }
3303
  }
3304
3305
  // OpenSSL can fail to parse the key but still return a non-null pointer.
3306
354
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
3307
354
  if (err != 0)
3308
17
    pkey->reset();
3309
3310
354
  if (*pkey)
3311
337
    return ParseKeyResult::kParseKeyOk;
3312

27
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
3313
10
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
3314
9
    if (config.passphrase_.get() == nullptr)
3315
8
      return ParseKeyResult::kParseKeyNeedPassphrase;
3316
  }
3317
9
  return ParseKeyResult::kParseKeyFailed;
3318
}
3319
3320
2364
ByteSource::ByteSource(ByteSource&& other)
3321
      : data_(other.data_),
3322
        allocated_data_(other.allocated_data_),
3323
2364
        size_(other.size_) {
3324
2364
  other.allocated_data_ = nullptr;
3325
2364
}
3326
3327
6289
ByteSource::~ByteSource() {
3328
6289
  OPENSSL_clear_free(allocated_data_, size_);
3329
6289
}
3330
3331
85
ByteSource& ByteSource::operator=(ByteSource&& other) {
3332
85
  if (&other != this) {
3333
85
    OPENSSL_clear_free(allocated_data_, size_);
3334
85
    data_ = other.data_;
3335
85
    allocated_data_ = other.allocated_data_;
3336
85
    other.allocated_data_ = nullptr;
3337
85
    size_ = other.size_;
3338
  }
3339
85
  return *this;
3340
}
3341
3342
3142
const char* ByteSource::get() const {
3343
3142
  return data_;
3344
}
3345
3346
2778
size_t ByteSource::size() const {
3347
2778
  return size_;
3348
}
3349
3350
2555
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
3351
                                          Local<Value> value) {
3352
2555
  return Buffer::HasInstance(value) ? FromBuffer(value)
3353
2929
                                    : FromString(env, value.As<String>());
3354
}
3355
3356
448
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
3357
                                  bool ntc) {
3358
896
  CHECK(str->IsString());
3359
896
  size_t size = str->Utf8Length(env->isolate());
3360
448
  size_t alloc_size = ntc ? size + 1 : size;
3361
448
  char* data = MallocOpenSSL<char>(alloc_size);
3362
448
  int opts = String::NO_OPTIONS;
3363
448
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
3364
896
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
3365
448
  return Allocated(data, size);
3366
}
3367
3368
2192
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
3369
2192
  CHECK(buffer->IsArrayBufferView());
3370
2192
  Local<ArrayBufferView> abv = buffer.As<ArrayBufferView>();
3371
2192
  size_t size = abv->ByteLength();
3372
2192
  if (ntc) {
3373
11
    char* data = MallocOpenSSL<char>(size + 1);
3374
11
    abv->CopyContents(data, size);
3375
11
    data[size] = 0;
3376
11
    return Allocated(data, size);
3377
  }
3378
2181
  return Foreign(Buffer::Data(buffer), size);
3379
}
3380
3381
85
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
3382
                                          Local<Value> value) {
3383
85
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
3384
159
                                    : FromString(env, value.As<String>(), true);
3385
}
3386
3387
14
ByteSource ByteSource::FromSymmetricKeyObject(Local<Value> handle) {
3388
14
  CHECK(handle->IsObject());
3389
14
  KeyObject* key = Unwrap<KeyObject>(handle.As<Object>());
3390
14
  CHECK(key);
3391
14
  return Foreign(key->GetSymmetricKey(), key->GetSymmetricKeySize());
3392
}
3393
3394
2654
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
3395
      : data_(data),
3396
        allocated_data_(allocated_data),
3397
2654
        size_(size) {}
3398
3399
459
ByteSource ByteSource::Allocated(char* data, size_t size) {
3400
459
  return ByteSource(data, data, size);
3401
}
3402
3403
2195
ByteSource ByteSource::Foreign(const char* data, size_t size) {
3404
2195
  return ByteSource(data, nullptr, size);
3405
}
3406
3407
enum KeyEncodingContext {
3408
  kKeyContextInput,
3409
  kKeyContextExport,
3410
  kKeyContextGenerate
3411
};
3412
3413
1303
static void GetKeyFormatAndTypeFromJs(
3414
    AsymmetricKeyEncodingConfig* config,
3415
    const FunctionCallbackInfo<Value>& args,
3416
    unsigned int* offset,
3417
    KeyEncodingContext context) {
3418
  // During key pair generation, it is possible not to specify a key encoding,
3419
  // which will lead to a key object being returned.
3420
5212
  if (args[*offset]->IsUndefined()) {
3421
14
    CHECK_EQ(context, kKeyContextGenerate);
3422
56
    CHECK(args[*offset + 1]->IsUndefined());
3423
14
    config->output_key_object_ = true;
3424
  } else {
3425
1289
    config->output_key_object_ = false;
3426
3427
3867
    CHECK(args[*offset]->IsInt32());
3428
    config->format_ = static_cast<PKFormatType>(
3429
5156
        args[*offset].As<Int32>()->Value());
3430
3431
3867
    if (args[*offset + 1]->IsInt32()) {
3432
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
3433
416
          args[*offset + 1].As<Int32>()->Value()));
3434
    } else {
3435

1185
      CHECK(context == kKeyContextInput && config->format_ == kKeyFormatPEM);
3436
4740
      CHECK(args[*offset + 1]->IsNullOrUndefined());
3437
1185
      config->type_ = Nothing<PKEncodingType>();
3438
    }
3439
  }
3440
3441
1303
  *offset += 2;
3442
1303
}
3443
3444
33
static PublicKeyEncodingConfig GetPublicKeyEncodingFromJs(
3445
    const FunctionCallbackInfo<Value>& args,
34