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: 3495 3859 90.6 %
Date: 2020-02-19 22:14:06 Branches: 1817 2777 65.4 %

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
1227
  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
8
  void operator()(STACK_OF(ASN1_OBJECT)* p) const {
120
8
    sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
121
8
  }
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
1135
  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 int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
146
template void SSLWrap<TLSWrap>::MemoryInfo(MemoryTracker* tracker) const;
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
4
  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
4
  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
65
Maybe<bool> Decorate(Environment* env, Local<Object> obj,
234
              unsigned long err) {  // NOLINT(runtime/int)
235
65
  if (err == 0) return Just(true);  // No decoration necessary.
236
237
54
  const char* ls = ERR_lib_error_string(err);
238
54
  const char* fs = ERR_func_error_string(err);
239
54
  const char* rs = ERR_reason_error_string(err);
240
241
54
  Isolate* isolate = env->isolate();
242
54
  Local<Context> context = isolate->GetCurrentContext();
243
244
54
  if (ls != nullptr) {
245
162
    if (obj->Set(context, env->library_string(),
246
216
                 OneByteString(isolate, ls)).IsNothing()) {
247
1
      return Nothing<bool>();
248
    }
249
  }
250
53
  if (fs != nullptr) {
251
159
    if (obj->Set(context, env->function_string(),
252
212
                 OneByteString(isolate, fs)).IsNothing()) {
253
      return Nothing<bool>();
254
    }
255
  }
256
53
  if (rs != nullptr) {
257
159
    if (obj->Set(context, env->reason_string(),
258
212
                 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
106
    std::string reason(rs);
266
267
1000
    for (auto& c : reason) {
268
947
      if (c == ' ')
269
109
        c = '_';
270
      else
271
838
        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
53
    const char* lib = "";
315
53
    const char* prefix = "OSSL_";
316









53
    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

53
    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
53
    snprintf(code, sizeof(code), "ERR_%s%s%s", prefix, lib, reason.c_str());
328
329
159
    if (obj->Set(env->isolate()->GetCurrentContext(),
330
             env->code_string(),
331
265
             OneByteString(env->isolate(), code)).IsNothing())
332
      return Nothing<bool>();
333
  }
334
335
53
  return Just(true);
336
}
337
}  // namespace error
338
339
340
632
struct CryptoErrorVector : public std::vector<std::string> {
341
78
  inline void Capture() {
342
78
    clear();
343
112
    while (auto err = ERR_get_error()) {
344
      char buf[256];
345
34
      ERR_error_string_n(err, buf, sizeof(buf));
346
34
      push_back(buf);
347
34
    }
348
78
    std::reverse(begin(), end());
349
78
  }
350
351
82
  inline MaybeLocal<Value> ToException(
352
      Environment* env,
353
      Local<String> exception_string = Local<String>()) const {
354
82
    if (exception_string.IsEmpty()) {
355
16
      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
24
          String::NewFromUtf8(env->isolate(), copy.back().data(),
361
16
                              NewStringType::kNormal, copy.back().size())
362
8
          .ToLocalChecked();
363
8
      copy.pop_back();
364
8
      return copy.ToException(env, exception_string);
365
    }
366
367
74
    Local<Value> exception_v = Exception::Error(exception_string);
368
74
    CHECK(!exception_v.IsEmpty());
369
370
74
    if (!empty()) {
371
18
      CHECK(exception_v->IsObject());
372
18
      Local<Object> exception = exception_v.As<Object>();
373
      Maybe<bool> ok = exception->Set(env->context(),
374
                     env->openssl_error_stack(),
375
72
                     ToV8Value(env->context(), *this).ToLocalChecked());
376
18
      if (ok.IsNothing())
377
1
        return MaybeLocal<Value>();
378
    }
379
380
73
    return exception_v;
381
  }
382
};
383
384
385
66
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
66
  char message_buffer[128] = {0};
391

66
  if (err != 0 || message == nullptr) {
392
55
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
393
55
    message = message_buffer;
394
  }
395
130
  HandleScope scope(env->isolate());
396
  Local<String> exception_string =
397
132
      String::NewFromUtf8(env->isolate(), message, NewStringType::kNormal)
398
66
      .ToLocalChecked();
399
130
  CryptoErrorVector errors;
400
66
  errors.Capture();
401
  Local<Value> exception;
402
132
  if (!errors.ToException(env, exception_string).ToLocal(&exception))
403
1
    return;
404
  Local<Object> obj;
405
195
  if (!exception->ToObject(env->context()).ToLocal(&obj))
406
    return;
407
130
  if (error::Decorate(env, obj, err).IsNothing())
408
1
    return;
409
64
  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
8758
inline void CheckEntropy() {
434
  for (;;) {
435
8758
    int status = RAND_status();
436
8758
    CHECK_GE(status, 0);  // Cannot fail.
437
8758
    if (status != 0)
438
17516
      break;
439
440
    // Give up, RAND_poll() not supported.
441
    if (RAND_poll() == 0)
442
      break;
443
  }
444
8758
}
445
446
447
8556
bool EntropySource(unsigned char* buffer, size_t length) {
448
  // Ensure that OpenSSL's PRNG is properly seeded.
449
8556
  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
8556
  return RAND_bytes(buffer, length) != -1;
454
}
455
456
457
template <typename T>
458
316347
static T* MallocOpenSSL(size_t count) {
459
316347
  void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
460


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

6693
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
673

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

2535
    if (args[1]->IsUndefined() || args[1]->IsNull())
717
793
      len = 1;
718
    else
719
78
      THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase");
720
  }
721
722
1626
  BIOPointer bio(LoadBIO(env, args[0]));
723
817
  if (!bio)
724
    return;
725
726
1626
  node::Utf8Value passphrase(env->isolate(), args[1]);
727
728
  EVPKeyPointer key(
729
      PEM_read_bio_PrivateKey(bio.get(),
730
                              nullptr,
731
                              PasswordCallback,
732
1626
                              *passphrase));
733
734
817
  if (!key) {
735
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
736
7
    return ThrowCryptoError(env, err, "PEM_read_bio_PrivateKey");
737
  }
738
739
810
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
740
741
810
  if (!rv) {
742
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
743
1
    return ThrowCryptoError(env, err, "SSL_CTX_use_PrivateKey");
744
  }
745
}
746
747
8
void SecureContext::SetSigalgs(const FunctionCallbackInfo<Value>& args) {
748
  SecureContext* sc;
749
8
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
750
8
  Environment* env = sc->env();
751
8
  ClearErrorOnReturn clear_error_on_return;
752
753
8
  CHECK_EQ(args.Length(), 1);
754
24
  CHECK(args[0]->IsString());
755
756
16
  const node::Utf8Value sigalgs(env->isolate(), args[0]);
757
758
8
  int rv = SSL_CTX_set1_sigalgs_list(sc->ctx_.get(), *sigalgs);
759
760
8
  if (rv == 0) {
761
    return ThrowCryptoError(env, ERR_get_error());
762
  }
763
}
764
765
#ifndef OPENSSL_NO_ENGINE
766
// Helpers for the smart pointer.
767
void ENGINE_free_fn(ENGINE* engine) { ENGINE_free(engine); }
768
769
void ENGINE_finish_and_free_fn(ENGINE* engine) {
770
  ENGINE_finish(engine);
771
  ENGINE_free(engine);
772
}
773
774
void SecureContext::SetEngineKey(const FunctionCallbackInfo<Value>& args) {
775
  Environment* env = Environment::GetCurrent(args);
776
777
  SecureContext* sc;
778
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
779
780
  CHECK_EQ(args.Length(), 2);
781
782
  char errmsg[1024];
783
  const node::Utf8Value engine_id(env->isolate(), args[1]);
784
  std::unique_ptr<ENGINE, std::function<void(ENGINE*)>> e =
785
                         { LoadEngineById(*engine_id, &errmsg),
786
                           ENGINE_free_fn };
787
  if (e.get() == nullptr) {
788
    return env->ThrowError(errmsg);
789
  }
790
791
  if (!ENGINE_init(e.get())) {
792
    return env->ThrowError("ENGINE_init");
793
  }
794
795
  e.get_deleter() = ENGINE_finish_and_free_fn;
796
797
  const node::Utf8Value key_name(env->isolate(), args[0]);
798
  EVPKeyPointer key(ENGINE_load_private_key(e.get(), *key_name,
799
                                            nullptr, nullptr));
800
801
  if (!key) {
802
    return ThrowCryptoError(env, ERR_get_error(), "ENGINE_load_private_key");
803
  }
804
805
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
806
807
  if (rv == 0) {
808
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_use_PrivateKey");
809
  }
810
811
  sc->private_key_engine_ = std::move(e);
812
}
813
#endif  // !OPENSSL_NO_ENGINE
814
815
793
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
816
793
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
817
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
818
1586
      X509_STORE_CTX_new());
819
1586
  return store_ctx.get() != nullptr &&
820

1586
         X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
821
2379
         X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1;
822
}
823
824
825
847
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
826
                                  X509Pointer&& x,
827
                                  STACK_OF(X509)* extra_certs,
828
                                  X509Pointer* cert,
829
                                  X509Pointer* issuer_) {
830
847
  CHECK(!*issuer_);
831
847
  CHECK(!*cert);
832
847
  X509* issuer = nullptr;
833
834
847
  int ret = SSL_CTX_use_certificate(ctx, x.get());
835
836
847
  if (ret) {
837
    // If we could set up our certificate, now proceed to
838
    // the CA certificates.
839
847
    SSL_CTX_clear_extra_chain_certs(ctx);
840
841
1263
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
842
416
      X509* ca = sk_X509_value(extra_certs, i);
843
844
      // NOTE: Increments reference count on `ca`
845
416
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
846
        ret = 0;
847
        issuer = nullptr;
848
        break;
849
      }
850
      // Note that we must not free r if it was successfully
851
      // added to the chain (while we must free the main
852
      // certificate, since its reference count is increased
853
      // by SSL_CTX_use_certificate).
854
855
      // Find issuer
856

416
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
857
4
        continue;
858
859
412
      issuer = ca;
860
    }
861
  }
862
863
  // Try getting issuer from a cert store
864
847
  if (ret) {
865
847
    if (issuer == nullptr) {
866
435
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
867
435
      ret = ret < 0 ? 0 : 1;
868
      // NOTE: get_cert_store doesn't increment reference count,
869
      // no need to free `store`
870
    } else {
871
      // Increment issuer reference count
872
412
      issuer = X509_dup(issuer);
873
412
      if (issuer == nullptr) {
874
        ret = 0;
875
      }
876
    }
877
  }
878
879
847
  issuer_->reset(issuer);
880
881

847
  if (ret && x != nullptr) {
882
847
    cert->reset(X509_dup(x.get()));
883
847
    if (!*cert)
884
      ret = 0;
885
  }
886
847
  return ret;
887
}
888
889
890
// Read a file that contains our certificate in "PEM" format,
891
// possibly followed by a sequence of CA certificates that should be
892
// sent to the peer in the Certificate message.
893
//
894
// Taken from OpenSSL - edited for style.
895
835
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
896
                                  BIOPointer&& in,
897
                                  X509Pointer* cert,
898
                                  X509Pointer* issuer) {
899
  // Just to ensure that `ERR_peek_last_error` below will return only errors
900
  // that we are interested in
901
835
  ERR_clear_error();
902
903
  X509Pointer x(
904
1670
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
905
906
835
  if (!x)
907
    return 0;
908
909
835
  unsigned long err = 0;  // NOLINT(runtime/int)
910
911
1670
  StackOfX509 extra_certs(sk_X509_new_null());
912
835
  if (!extra_certs)
913
    return 0;
914
915
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
916
                                    nullptr,
917
                                    NoPasswordCallback,
918
1242
                                    nullptr)}) {
919
407
    if (sk_X509_push(extra_certs.get(), extra.get())) {
920
407
      extra.release();
921
407
      continue;
922
    }
923
924
    return 0;
925
407
  }
926
927
  // When the while loop ends, it's usually just EOF.
928
835
  err = ERR_peek_last_error();
929

1670
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
930
835
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
931
835
    ERR_clear_error();
932
  } else {
933
    // some real error
934
    return 0;
935
  }
936
937
835
  return SSL_CTX_use_certificate_chain(ctx,
938
835
                                       std::move(x),
939
                                       extra_certs.get(),
940
                                       cert,
941
835
                                       issuer);
942
}
943
944
945
835
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
946
835
  Environment* env = Environment::GetCurrent(args);
947
948
  SecureContext* sc;
949
835
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
950
951
835
  if (args.Length() != 1) {
952
    return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory");
953
  }
954
955
1670
  BIOPointer bio(LoadBIO(env, args[0]));
956
835
  if (!bio)
957
    return;
958
959
835
  sc->cert_.reset();
960
835
  sc->issuer_.reset();
961
962
2505
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(),
963
835
                                         std::move(bio),
964
835
                                         &sc->cert_,
965
1670
                                         &sc->issuer_);
966
967
835
  if (!rv) {
968
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
969
    return ThrowCryptoError(env, err, "SSL_CTX_use_certificate_chain");
970
  }
971
}
972
973
974
247
static X509_STORE* NewRootCertStore() {
975

247
  static std::vector<X509*> root_certs_vector;
976

247
  static Mutex root_certs_vector_mutex;
977
494
  Mutex::ScopedLock lock(root_certs_vector_mutex);
978
979
247
  if (root_certs_vector.empty()) {
980
33120
    for (size_t i = 0; i < arraysize(root_certs); i++) {
981
      X509* x509 =
982
65760
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
983
32880
                                              strlen(root_certs[i])).get(),
984
                            nullptr,   // no re-use of X509 structure
985
                            NoPasswordCallback,
986
32880
                            nullptr);  // no callback data
987
988
      // Parse errors from the built-in roots are fatal.
989
32880
      CHECK_NOT_NULL(x509);
990
991
32880
      root_certs_vector.push_back(x509);
992
    }
993
  }
994
995
247
  X509_STORE* store = X509_STORE_new();
996
247
  if (*system_cert_path != '\0') {
997
    X509_STORE_load_locations(store, system_cert_path, nullptr);
998
  }
999
247
  if (per_process::cli_options->ssl_openssl_cert_store) {
1000
    X509_STORE_set_default_paths(store);
1001
  } else {
1002
34086
    for (X509* cert : root_certs_vector) {
1003
33839
      X509_up_ref(cert);
1004
33839
      X509_STORE_add_cert(store, cert);
1005
    }
1006
  }
1007
1008
494
  return store;
1009
}
1010
1011
1012
201
void GetRootCertificates(const FunctionCallbackInfo<Value>& args) {
1013
201
  Environment* env = Environment::GetCurrent(args);
1014
27738
  Local<Value> result[arraysize(root_certs)];
1015
1016
27738
  for (size_t i = 0; i < arraysize(root_certs); i++) {
1017
55074
    if (!String::NewFromOneByte(
1018
            env->isolate(),
1019
27537
            reinterpret_cast<const uint8_t*>(root_certs[i]),
1020
82611
            NewStringType::kNormal).ToLocal(&result[i])) {
1021
      return;
1022
    }
1023
  }
1024
1025
603
  args.GetReturnValue().Set(
1026
      Array::New(env->isolate(), result, arraysize(root_certs)));
1027
}
1028
1029
1030
551
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
1031
551
  Environment* env = Environment::GetCurrent(args);
1032
1033
  SecureContext* sc;
1034
551
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1035
551
  ClearErrorOnReturn clear_error_on_return;
1036
1037
551
  if (args.Length() != 1) {
1038
    return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory");
1039
  }
1040
1041
1102
  BIOPointer bio(LoadBIO(env, args[0]));
1042
551
  if (!bio)
1043
    return;
1044
1045
551
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1046
1442
  while (X509* x509 = PEM_read_bio_X509_AUX(
1047
1442
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1048
891
    if (cert_store == root_cert_store) {
1049
1
      cert_store = NewRootCertStore();
1050
1
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1051
    }
1052
891
    X509_STORE_add_cert(cert_store, x509);
1053
891
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
1054
891
    X509_free(x509);
1055
891
  }
1056
}
1057
1058
1059
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
1060
2
  Environment* env = Environment::GetCurrent(args);
1061
1062
  SecureContext* sc;
1063
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1064
1065
2
  if (args.Length() != 1) {
1066
    return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory");
1067
  }
1068
1069
1
  ClearErrorOnReturn clear_error_on_return;
1070
1071
3
  BIOPointer bio(LoadBIO(env, args[0]));
1072
2
  if (!bio)
1073
    return;
1074
1075
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
1076
3
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
1077
1078
2
  if (!crl)
1079
1
    return env->ThrowError("Failed to parse CRL");
1080
1081
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1082
1
  if (cert_store == root_cert_store) {
1083
    cert_store = NewRootCertStore();
1084
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1085
  }
1086
1087
1
  X509_STORE_add_crl(cert_store, crl.get());
1088
  X509_STORE_set_flags(cert_store,
1089
1
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1090
}
1091
1092
1093
3
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1094
    X509_STORE* store,
1095
    const char* file) {
1096
3
  ERR_clear_error();
1097
6
  MarkPopErrorOnReturn mark_pop_error_on_return;
1098
1099
6
  BIOPointer bio(BIO_new_file(file, "r"));
1100
3
  if (!bio)
1101
1
    return ERR_get_error();
1102
1103
  while (X509* x509 =
1104
4
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1105
2
    X509_STORE_add_cert(store, x509);
1106
2
    X509_free(x509);
1107
2
  }
1108
1109
2
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1110
  // Ignore error if its EOF/no start line found.
1111

4
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1112
2
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1113
2
    return 0;
1114
  }
1115
1116
  return err;
1117
}
1118
1119
1120
3
void UseExtraCaCerts(const std::string& file) {
1121
3
  ClearErrorOnReturn clear_error_on_return;
1122
1123
3
  if (root_cert_store == nullptr) {
1124
3
    root_cert_store = NewRootCertStore();
1125
1126
3
    if (!file.empty()) {
1127
3
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1128
                                           root_cert_store,
1129
3
                                           file.c_str());
1130
3
      if (err) {
1131
1
        fprintf(stderr,
1132
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
1133
                file.c_str(),
1134
1
                ERR_error_string(err, nullptr));
1135
      } else {
1136
2
        extra_root_certs_loaded = true;
1137
      }
1138
    }
1139
  }
1140
3
}
1141
1142
1143
static void IsExtraRootCertsFileLoaded(
1144
    const FunctionCallbackInfo<Value>& args) {
1145
  return args.GetReturnValue().Set(extra_root_certs_loaded);
1146
}
1147
1148
1149
1700
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
1150
  SecureContext* sc;
1151
1700
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1152
1700
  ClearErrorOnReturn clear_error_on_return;
1153
1154
1700
  if (root_cert_store == nullptr) {
1155
237
    root_cert_store = NewRootCertStore();
1156
  }
1157
1158
  // Increment reference count so global store is not deleted along with CTX.
1159
1700
  X509_STORE_up_ref(root_cert_store);
1160
1700
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
1161
}
1162
1163
1164
2155
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
1165
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
1166
#ifndef OPENSSL_IS_BORINGSSL
1167
  SecureContext* sc;
1168
2156
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1169
2155
  Environment* env = sc->env();
1170
2154
  ClearErrorOnReturn clear_error_on_return;
1171
1172
2155
  CHECK_EQ(args.Length(), 1);
1173
6465
  CHECK(args[0]->IsString());
1174
1175
4309
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1176
2155
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers)) {
1177
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1178
1
    return ThrowCryptoError(env, err, "Failed to set ciphers");
1179
  }
1180
#endif
1181
}
1182
1183
1184
2157
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
1185
  SecureContext* sc;
1186
2172
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1187
2157
  Environment* env = sc->env();
1188
2142
  ClearErrorOnReturn clear_error_on_return;
1189
1190
2157
  CHECK_EQ(args.Length(), 1);
1191
6471
  CHECK(args[0]->IsString());
1192
1193
4299
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1194
2157
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
1195
15
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1196
1197

15
    if (strlen(*ciphers) == 0 && ERR_GET_REASON(err) == SSL_R_NO_CIPHER_MATCH) {
1198
      // TLS1.2 ciphers were deliberately cleared, so don't consider
1199
      // SSL_R_NO_CIPHER_MATCH to be an error (this is how _set_cipher_suites()
1200
      // works). If the user actually sets a value (like "no-such-cipher"), then
1201
      // that's actually an error.
1202
11
      return;
1203
    }
1204
4
    return ThrowCryptoError(env, err, "Failed to set ciphers");
1205
  }
1206
}
1207
1208
1209
2150
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
1210
  SecureContext* sc;
1211
4293
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1212
2150
  Environment* env = sc->env();
1213
1214
2150
  if (args.Length() != 1)
1215
    return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory");
1216
1217
6450
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name");
1218
1219
2156
  node::Utf8Value curve(env->isolate(), args[0]);
1220
1221
2149
  if (strcmp(*curve, "auto") == 0)
1222
2139
    return;
1223
1224
10
  if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve))
1225
3
    return env->ThrowError("Failed to set ECDH curve");
1226
}
1227
1228
1229
10
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
1230
  SecureContext* sc;
1231
13
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
1232
10
  Environment* env = sc->env();
1233
7
  ClearErrorOnReturn clear_error_on_return;
1234
1235
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
1236
  // to be specified explicitly
1237
10
  if (args.Length() != 1)
1238
    return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory");
1239
1240
17
  DHPointer dh;
1241
  {
1242
20
    BIOPointer bio(LoadBIO(env, args[0]));
1243
10
    if (!bio)
1244
      return;
1245
1246
10
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
1247
  }
1248
1249
  // Invalid dhparam is silently discarded and DHE is no longer used.
1250
10
  if (!dh)
1251
1
    return;
1252
1253
  const BIGNUM* p;
1254
9
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
1255
9
  const int size = BN_num_bits(p);
1256
9
  if (size < 1024) {
1257
    return THROW_ERR_INVALID_ARG_VALUE(
1258
2
        env, "DH parameter is less than 1024 bits");
1259
7
  } else if (size < 2048) {
1260
9
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1261
        env->isolate(), "DH parameter is less than 2048 bits"));
1262
  }
1263
1264
7
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
1265
7
  int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get());
1266
1267
7
  if (!r)
1268
    return env->ThrowTypeError("Error setting temp DH parameter");
1269
}
1270
1271
1272
11
void SecureContext::SetMinProto(const FunctionCallbackInfo<Value>& args) {
1273
  SecureContext* sc;
1274
11
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1275
1276
11
  CHECK_EQ(args.Length(), 1);
1277
22
  CHECK(args[0]->IsInt32());
1278
1279
33
  int version = args[0].As<Int32>()->Value();
1280
1281
11
  CHECK(SSL_CTX_set_min_proto_version(sc->ctx_.get(), version));
1282
}
1283
1284
1285
46
void SecureContext::SetMaxProto(const FunctionCallbackInfo<Value>& args) {
1286
  SecureContext* sc;
1287
46
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1288
1289
46
  CHECK_EQ(args.Length(), 1);
1290
92
  CHECK(args[0]->IsInt32());
1291
1292
138
  int version = args[0].As<Int32>()->Value();
1293
1294
46
  CHECK(SSL_CTX_set_max_proto_version(sc->ctx_.get(), version));
1295
}
1296
1297
1298
57
void SecureContext::GetMinProto(const FunctionCallbackInfo<Value>& args) {
1299
  SecureContext* sc;
1300
57
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1301
1302
57
  CHECK_EQ(args.Length(), 0);
1303
1304
  long version =  // NOLINT(runtime/int)
1305
57
    SSL_CTX_get_min_proto_version(sc->ctx_.get());
1306
171
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1307
}
1308
1309
1310
76
void SecureContext::GetMaxProto(const FunctionCallbackInfo<Value>& args) {
1311
  SecureContext* sc;
1312
76
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1313
1314
76
  CHECK_EQ(args.Length(), 0);
1315
1316
  long version =  // NOLINT(runtime/int)
1317
76
    SSL_CTX_get_max_proto_version(sc->ctx_.get());
1318
228
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1319
}
1320
1321
1322
821
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1323
  SecureContext* sc;
1324
821
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1325
  int64_t val;
1326
1327

2463
  if (args.Length() != 1 ||
1328
4105
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1329
    return THROW_ERR_INVALID_ARG_TYPE(
1330
        sc->env(), "Options must be an integer value");
1331
  }
1332
1333
821
  SSL_CTX_set_options(sc->ctx_.get(),
1334
821
                      static_cast<long>(val));  // NOLINT(runtime/int)
1335
}
1336
1337
1338
750
void SecureContext::SetSessionIdContext(
1339
    const FunctionCallbackInfo<Value>& args) {
1340
  SecureContext* sc;
1341
1500
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1342
750
  Environment* env = sc->env();
1343
1344
750
  if (args.Length() != 1) {
1345
    return THROW_ERR_MISSING_ARGS(
1346
        env, "Session ID context argument is mandatory");
1347
  }
1348
1349
2250
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1350
1351
750
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1352
  const unsigned char* sid_ctx =
1353
750
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1354
750
  unsigned int sid_ctx_len = sessionIdContext.length();
1355
1356
750
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1357
750
  if (r == 1)
1358
750
    return;
1359
1360
  BUF_MEM* mem;
1361
  Local<String> message;
1362
1363
  BIOPointer bio(BIO_new(BIO_s_mem()));
1364
  if (!bio) {
1365
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1366
                                    "SSL_CTX_set_session_id_context error");
1367
  } else {
1368
    ERR_print_errors(bio.get());
1369
    BIO_get_mem_ptr(bio.get(), &mem);
1370
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1371
  }
1372
1373
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1374
}
1375
1376
1377
2
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1378
  SecureContext* sc;
1379
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1380
1381

6
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1382
1
    return THROW_ERR_INVALID_ARG_TYPE(
1383
1
        sc->env(), "Session timeout must be a 32-bit integer");
1384
  }
1385
1386
3
  int32_t sessionTimeout = args[0].As<Int32>()->Value();
1387
1
  SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
1388
}
1389
1390
1391
1251
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1392
  SecureContext* sc;
1393
1251
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1394
1251
  sc->Reset();
1395
}
1396
1397
1398
// Takes .pfx or .p12 and password in string or buffer format
1399
18
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1400
18
  Environment* env = Environment::GetCurrent(args);
1401
1402
30
  std::vector<char> pass;
1403
18
  bool ret = false;
1404
1405
  SecureContext* sc;
1406
18
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1407
12
  ClearErrorOnReturn clear_error_on_return;
1408
1409
18
  if (args.Length() < 1) {
1410
    return THROW_ERR_MISSING_ARGS(env, "PFX certificate argument is mandatory");
1411
  }
1412
1413
30
  BIOPointer in(LoadBIO(env, args[0]));
1414
18
  if (!in)
1415
    return env->ThrowError("Unable to load BIO");
1416
1417
18
  if (args.Length() >= 2) {
1418
15
    THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase");
1419
30
    Local<ArrayBufferView> abv = args[1].As<ArrayBufferView>();
1420
15
    size_t passlen = abv->ByteLength();
1421
15
    pass.resize(passlen + 1);
1422
30
    abv->CopyContents(pass.data(), passlen);
1423
15
    pass[passlen] = '\0';
1424
  }
1425
1426
  // Free previous certs
1427
18
  sc->issuer_.reset();
1428
18
  sc->cert_.reset();
1429
1430
18
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1431
1432
30
  DeleteFnPtr<PKCS12, PKCS12_free> p12;
1433
30
  EVPKeyPointer pkey;
1434
30
  X509Pointer cert;
1435
30
  StackOfX509 extra_certs;
1436
1437
18
  PKCS12* p12_ptr = nullptr;
1438
18
  EVP_PKEY* pkey_ptr = nullptr;
1439
18
  X509* cert_ptr = nullptr;
1440
18
  STACK_OF(X509)* extra_certs_ptr = nullptr;
1441
36
  if (d2i_PKCS12_bio(in.get(), &p12_ptr) &&
1442
32
      (p12.reset(p12_ptr), true) &&  // Move ownership to the smart pointer.
1443
16
      PKCS12_parse(p12.get(), pass.data(),
1444
                   &pkey_ptr,
1445
                   &cert_ptr,
1446
                   &extra_certs_ptr) &&
1447
12
      (pkey.reset(pkey_ptr), cert.reset(cert_ptr),
1448
24
       extra_certs.reset(extra_certs_ptr), true) &&  // Move ownership.
1449
36
      SSL_CTX_use_certificate_chain(sc->ctx_.get(),
1450
12
                                    std::move(cert),
1451
                                    extra_certs.get(),
1452
12
                                    &sc->cert_,
1453

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

6
    if (Buffer::Length(name_val) != kTicketPartSize ||
1629
3
        Buffer::Length(iv_val) != kTicketPartSize) {
1630
      return -1;
1631
    }
1632
1633
6
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1634
6
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1635
  }
1636
1637
4
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1638
8
  HMAC_Init_ex(hctx,
1639
4
               hmac_buf.data(),
1640
4
               hmac_buf.length(),
1641
               EVP_sha256(),
1642
4
               nullptr);
1643
1644
4
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1645
4
  if (enc) {
1646
3
    EVP_EncryptInit_ex(ectx,
1647
                       EVP_aes_128_cbc(),
1648
                       nullptr,
1649
                       aes_key.data(),
1650
3
                       iv);
1651
  } else {
1652
1
    EVP_DecryptInit_ex(ectx,
1653
                       EVP_aes_128_cbc(),
1654
                       nullptr,
1655
                       aes_key.data(),
1656
1
                       iv);
1657
  }
1658
1659
4
  return r;
1660
}
1661
1662
1663
1143
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1664
                                               unsigned char* name,
1665
                                               unsigned char* iv,
1666
                                               EVP_CIPHER_CTX* ectx,
1667
                                               HMAC_CTX* hctx,
1668
                                               int enc) {
1669
  SecureContext* sc = static_cast<SecureContext*>(
1670
1143
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1671
1672
1143
  if (enc) {
1673
1089
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1674

3267
    if (RAND_bytes(iv, 16) <= 0 ||
1675
1089
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1676

2178
                           sc->ticket_key_aes_, iv) <= 0 ||
1677
1089
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1678
                     EVP_sha256(), nullptr) <= 0) {
1679
      return -1;
1680
    }
1681
1089
    return 1;
1682
  }
1683
1684
54
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1685
    // The ticket key name does not match. Discard the ticket.
1686
12
    return 0;
1687
  }
1688
1689
84
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1690

84
                         iv) <= 0 ||
1691
42
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1692
                   EVP_sha256(), nullptr) <= 0) {
1693
    return -1;
1694
  }
1695
42
  return 1;
1696
}
1697
1698
1699
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1700
  SecureContext* sc;
1701
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1702
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1703
4
  info.GetReturnValue().Set(ext);
1704
}
1705
1706
1707
template <bool primary>
1708
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1709
  SecureContext* wrap;
1710

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1711
6
  Environment* env = wrap->env();
1712
  X509* cert;
1713
1714
  if (primary)
1715
3
    cert = wrap->cert_.get();
1716
  else
1717
3
    cert = wrap->issuer_.get();
1718

6
  if (cert == nullptr)
1719
    return args.GetReturnValue().SetNull();
1720
1721
6
  int size = i2d_X509(cert, nullptr);
1722
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1723
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1724
6
      Buffer::Data(buff));
1725
6
  i2d_X509(cert, &serialized);
1726
1727
12
  args.GetReturnValue().Set(buff);
1728
}
1729
1730
1731
template <class Base>
1732
476
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1733
952
  HandleScope scope(env->isolate());
1734
1735
476
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
1736
476
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
1737
476
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
1738
476
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
1739
476
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
1740
476
  env->SetProtoMethod(t, "setSession", SetSession);
1741
476
  env->SetProtoMethod(t, "loadSession", LoadSession);
1742
476
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
1743
476
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
1744
476
  env->SetProtoMethodNoSideEffect(t, "getCipher", GetCipher);
1745
476
  env->SetProtoMethodNoSideEffect(t, "getSharedSigalgs", GetSharedSigalgs);
1746
476
  env->SetProtoMethod(t, "endParser", EndParser);
1747
476
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1748
476
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1749
476
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
1750
476
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1751
476
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1752
476
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1753
476
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
1754
                                  GetEphemeralKeyInfo);
1755
476
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
1756
1757
#ifdef SSL_set_max_send_fragment
1758
476
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1759
#endif  // SSL_set_max_send_fragment
1760
1761
476
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
1762
                                  GetALPNNegotiatedProto);
1763
476
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1764
476
}
1765
1766
1767
template <class Base>
1768
12166
void SSLWrap<Base>::ConfigureSecureContext(SecureContext* sc) {
1769
  // OCSP stapling
1770
12166
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
1771
12166
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
1772
12166
}
1773
1774
1775
template <class Base>
1776
93
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1777
                                               const unsigned char* key,
1778
                                               int len,
1779
                                               int* copy) {
1780
93
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1781
1782
93
  *copy = 0;
1783
93
  return w->next_sess_.release();
1784
}
1785
1786
1787
template <class Base>
1788
1584
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1789
1584
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1790
1584
  Environment* env = w->ssl_env();
1791
3168
  HandleScope handle_scope(env->isolate());
1792
1584
  Context::Scope context_scope(env->context());
1793
1794
1584
  if (!w->session_callbacks_)
1795
1302
    return 0;
1796
1797
  // Check if session is small enough to be stored
1798
282
  int size = i2d_SSL_SESSION(sess, nullptr);
1799
282
  if (size > SecureContext::kMaxSessionSize)
1800
    return 0;
1801
1802
  // Serialize session
1803
564
  Local<Object> session = Buffer::New(env, size).ToLocalChecked();
1804
  unsigned char* session_data = reinterpret_cast<unsigned char*>(
1805
282
      Buffer::Data(session));
1806
282
  memset(session_data, 0, size);
1807
282
  i2d_SSL_SESSION(sess, &session_data);
1808
1809
  unsigned int session_id_length;
1810
  const unsigned char* session_id_data = SSL_SESSION_get_id(sess,
1811
282
                                                            &session_id_length);
1812
564
  Local<Object> session_id = Buffer::Copy(
1813
      env,
1814
      reinterpret_cast<const char*>(session_id_data),
1815
282
      session_id_length).ToLocalChecked();
1816
846
  Local<Value> argv[] = { session_id, session };
1817
  // On servers, we pause the handshake until callback of 'newSession', which
1818
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
1819
282
  if (w->is_server())
1820
8
    w->awaiting_new_session_ = true;
1821
282
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1822
1823
282
  return 0;
1824
}
1825
1826
1827
template <class Base>
1828
35
void SSLWrap<Base>::KeylogCallback(const SSL* s, const char* line) {
1829
35
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1830
35
  Environment* env = w->ssl_env();
1831
70
  HandleScope handle_scope(env->isolate());
1832
35
  Context::Scope context_scope(env->context());
1833
1834
35
  const size_t size = strlen(line);
1835
70
  Local<Value> line_bf = Buffer::Copy(env, line, 1 + size).ToLocalChecked();
1836
35
  char* data = Buffer::Data(line_bf);
1837
35
  data[size] = '\n';
1838
35
  w->MakeCallback(env->onkeylog_string(), 1, &line_bf);
1839
35
}
1840
1841
1842
template <class Base>
1843
20
void SSLWrap<Base>::OnClientHello(void* arg,
1844
                                  const ClientHelloParser::ClientHello& hello) {
1845
20
  Base* w = static_cast<Base*>(arg);
1846
20
  Environment* env = w->ssl_env();
1847
40
  HandleScope handle_scope(env->isolate());
1848
20
  Local<Context> context = env->context();
1849
  Context::Scope context_scope(context);
1850
1851
20
  Local<Object> hello_obj = Object::New(env->isolate());
1852
60
  Local<Object> buff = Buffer::Copy(
1853
      env,
1854
20
      reinterpret_cast<const char*>(hello.session_id()),
1855
40
      hello.session_size()).ToLocalChecked();
1856
60
  hello_obj->Set(context, env->session_id_string(), buff).Check();
1857
20
  if (hello.servername() == nullptr) {
1858
8
    hello_obj->Set(context,
1859
                   env->servername_string(),
1860
                   String::Empty(env->isolate())).Check();
1861
  } else {
1862
18
    Local<String> servername = OneByteString(env->isolate(),
1863
                                             hello.servername(),
1864
36
                                             hello.servername_size());
1865
54
    hello_obj->Set(context, env->servername_string(), servername).Check();
1866
  }
1867
80
  hello_obj->Set(context,
1868
                 env->tls_ticket_string(),
1869
20
                 Boolean::New(env->isolate(), hello.has_ticket())).Check();
1870
1871
40
  Local<Value> argv[] = { hello_obj };
1872
20
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1873
20
}
1874
1875
1876
70
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1877
70
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1878
1879
70
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1880
65
    return false;
1881
1882
5
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
1883
5
  if (names == nullptr)
1884
1
    return false;
1885
1886
16
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1887
12
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1888
1889
12
    if (i != 0)
1890
8
      BIO_write(out, ", ", 2);
1891
1892
12
    if (gen->type == GEN_DNS) {
1893
9
      ASN1_IA5STRING* name = gen->d.dNSName;
1894
1895
9
      BIO_write(out, "DNS:", 4);
1896
9
      BIO_write(out, name->data, name->length);
1897
    } else {
1898
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1899
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
1900
3
      if (nval == nullptr)
1901
        return false;
1902
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1903
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1904
    }
1905
  }
1906
4
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1907
1908
4
  return true;
1909
}
1910
1911
1912
2266
static void AddFingerprintDigest(const unsigned char* md,
1913
                                 unsigned int md_size,
1914
                                 char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) {
1915
  unsigned int i;
1916
2266
  const char hex[] = "0123456789ABCDEF";
1917
1918
61182
  for (i = 0; i < md_size; i++) {
1919
58916
    (*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4];
1920
58916
    (*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)];
1921
58916
    (*fingerprint)[(3*i)+2] = ':';
1922
  }
1923
1924
2266
  if (md_size > 0) {
1925
2266
    (*fingerprint)[(3*(md_size-1))+2] = '\0';
1926
  } else {
1927
    (*fingerprint)[0] = '\0';
1928
  }
1929
2266
}
1930
1931
1932
63
static MaybeLocal<Object> ECPointToBuffer(Environment* env,
1933
                                          const EC_GROUP* group,
1934
                                          const EC_POINT* point,
1935
                                          point_conversion_form_t form,
1936
                                          const char** error) {
1937
63
  size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, nullptr);
1938
63
  if (len == 0) {
1939
    if (error != nullptr) *error = "Failed to get public key length";
1940
    return MaybeLocal<Object>();
1941
  }
1942
126
  AllocatedBuffer buf = env->AllocateManaged(len);
1943
63
  len = EC_POINT_point2oct(group,
1944
                           point,
1945
                           form,
1946
63
                           reinterpret_cast<unsigned char*>(buf.data()),
1947
                           buf.size(),
1948
63
                           nullptr);
1949
63
  if (len == 0) {
1950
    if (error != nullptr) *error = "Failed to get public key";
1951
    return MaybeLocal<Object>();
1952
  }
1953
63
  return buf.ToBuffer();
1954
}
1955
1956
1957
1133
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1958
1133
  EscapableHandleScope scope(env->isolate());
1959
1133
  Local<Context> context = env->context();
1960
1133
  Local<Object> info = Object::New(env->isolate());
1961
1962
2266
  BIOPointer bio(BIO_new(BIO_s_mem()));
1963
  BUF_MEM* mem;
1964
1133
  if (X509_NAME_print_ex(bio.get(),
1965
1133
                         X509_get_subject_name(cert),
1966
                         0,
1967
                         X509_NAME_FLAGS) > 0) {
1968
1133
    BIO_get_mem_ptr(bio.get(), &mem);
1969
2266
    info->Set(context, env->subject_string(),
1970
3399
              String::NewFromUtf8(env->isolate(), mem->data,
1971
                                  NewStringType::kNormal,
1972
5665
                                  mem->length).ToLocalChecked()).Check();
1973
  }
1974
1133
  USE(BIO_reset(bio.get()));
1975
1976
1133
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1977
1133
  if (X509_NAME_print_ex(bio.get(), issuer_name, 0, X509_NAME_FLAGS) > 0) {
1978
1133
    BIO_get_mem_ptr(bio.get(), &mem);
1979
2266
    info->Set(context, env->issuer_string(),
1980
3399
              String::NewFromUtf8(env->isolate(), mem->data,
1981
                                  NewStringType::kNormal,
1982
5665
                                  mem->length).ToLocalChecked()).Check();
1983
  }
1984
1133
  USE(BIO_reset(bio.get()));
1985
1986
1133
  int nids[] = { NID_subject_alt_name, NID_info_access };
1987
  Local<String> keys[] = { env->subjectaltname_string(),
1988
1133
                           env->infoaccess_string() };
1989
1133
  CHECK_EQ(arraysize(nids), arraysize(keys));
1990
3399
  for (size_t i = 0; i < arraysize(nids); i++) {
1991
2266
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1992
2266
    if (index < 0)
1993
4393
      continue;
1994
1995
70
    X509_EXTENSION* ext = X509_get_ext(cert, index);
1996
70
    CHECK_NOT_NULL(ext);
1997
1998

136
    if (!SafeX509ExtPrint(bio.get(), ext) &&
1999
66
        X509V3_EXT_print(bio.get(), ext, 0, 0) != 1) {
2000
3
      info->Set(context, keys[i], Null(env->isolate())).Check();
2001
1
      USE(BIO_reset(bio.get()));
2002
1
      continue;
2003
    }
2004
2005
69
    BIO_get_mem_ptr(bio.get(), &mem);
2006
138
    info->Set(context, keys[i],
2007
207
              String::NewFromUtf8(env->isolate(), mem->data,
2008
                                  NewStringType::kNormal,
2009
276
                                  mem->length).ToLocalChecked()).Check();
2010
2011
69
    USE(BIO_reset(bio.get()));
2012
  }
2013
2014
2266
  EVPKeyPointer pkey(X509_get_pubkey(cert));
2015
2266
  RSAPointer rsa;
2016
2266
  ECPointer ec;
2017
1133
  if (pkey) {
2018
1133
    switch (EVP_PKEY_id(pkey.get())) {
2019
      case EVP_PKEY_RSA:
2020
1096
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
2021
1096
        break;
2022
      case EVP_PKEY_EC:
2023
37
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
2024
37
        break;
2025
    }
2026
  }
2027
2028
1133
  if (rsa) {
2029
    const BIGNUM* n;
2030
    const BIGNUM* e;
2031
1096
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
2032
1096
    BN_print(bio.get(), n);
2033
1096
    BIO_get_mem_ptr(bio.get(), &mem);
2034
2192
    info->Set(context, env->modulus_string(),
2035
3288
              String::NewFromUtf8(env->isolate(), mem->data,
2036
                                  NewStringType::kNormal,
2037
5480
                                  mem->length).ToLocalChecked()).Check();
2038
1096
    USE(BIO_reset(bio.get()));
2039
2040
1096
    int bits = BN_num_bits(n);
2041
2192
    info->Set(context, env->bits_string(),
2042
4384
              Integer::New(env->isolate(), bits)).Check();
2043
2044
1096
    uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
2045
1096
    uint32_t lo = static_cast<uint32_t>(exponent_word);
2046
1096
    uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
2047
1096
    if (hi == 0) {
2048
1096
      BIO_printf(bio.get(), "0x%x", lo);
2049
    } else {
2050
      BIO_printf(bio.get(), "0x%x%08x", hi, lo);
2051
    }
2052
1096
    BIO_get_mem_ptr(bio.get(), &mem);
2053
2192
    info->Set(context, env->exponent_string(),
2054
3288
              String::NewFromUtf8(env->isolate(), mem->data,
2055
                                  NewStringType::kNormal,
2056
5480
                                  mem->length).ToLocalChecked()).Check();
2057
1096
    USE(BIO_reset(bio.get()));
2058
2059
1096
    int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
2060
1096
    CHECK_GE(size, 0);
2061
2192
    Local<Object> pubbuff = Buffer::New(env, size).ToLocalChecked();
2062
    unsigned char* pubserialized =
2063
1096
        reinterpret_cast<unsigned char*>(Buffer::Data(pubbuff));
2064
1096
    i2d_RSA_PUBKEY(rsa.get(), &pubserialized);
2065
4384
    info->Set(env->context(), env->pubkey_string(), pubbuff).Check();
2066
37
  } else if (ec) {
2067
37
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
2068
37
    if (group != nullptr) {
2069
37
      int bits = EC_GROUP_order_bits(group);
2070
37
      if (bits > 0) {
2071
74
        info->Set(context, env->bits_string(),
2072
148
                  Integer::New(env->isolate(), bits)).Check();
2073
      }
2074
    }
2075
2076
37
    const EC_POINT* pubkey = EC_KEY_get0_public_key(ec.get());
2077
    Local<Object> buf;
2078

111
    if (pubkey != nullptr &&
2079
74
        ECPointToBuffer(
2080
37
            env, group, pubkey, EC_KEY_get_conv_form(ec.get()), nullptr)
2081
37
            .ToLocal(&buf)) {
2082
111
      info->Set(context, env->pubkey_string(), buf).Check();
2083
    }
2084
2085
37
    const int nid = EC_GROUP_get_curve_name(group);
2086
37
    if (nid != 0) {
2087
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
2088
2089
37
      if (const char* sn = OBJ_nid2sn(nid)) {
2090
74
        info->Set(context, env->asn1curve_string(),
2091
148
                  OneByteString(env->isolate(), sn)).Check();
2092
      }
2093
2094
37
      if (const char* nist = EC_curve_nid2nist(nid)) {
2095
74
        info->Set(context, env->nistcurve_string(),
2096
148
                  OneByteString(env->isolate(), nist)).Check();
2097
      }
2098
    } else {
2099
      // Unnamed curves can be described by their mathematical properties,
2100
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
2101
    }
2102
  }
2103
2104
1133
  pkey.reset();
2105
1133
  rsa.reset();
2106
1133
  ec.reset();
2107
2108
1133
  ASN1_TIME_print(bio.get(), X509_get0_notBefore(cert));
2109
1133
  BIO_get_mem_ptr(bio.get(), &mem);
2110
2266
  info->Set(context, env->valid_from_string(),
2111
3399
            String::NewFromUtf8(env->isolate(), mem->data,
2112
                                NewStringType::kNormal,
2113
5665
                                mem->length).ToLocalChecked()).Check();
2114
1133
  USE(BIO_reset(bio.get()));
2115
2116
1133
  ASN1_TIME_print(bio.get(), X509_get0_notAfter(cert));
2117
1133
  BIO_get_mem_ptr(bio.get(), &mem);
2118
2266
  info->Set(context, env->valid_to_string(),
2119
3399
            String::NewFromUtf8(env->isolate(), mem->data,
2120
                                NewStringType::kNormal,
2121
5665
                                mem->length).ToLocalChecked()).Check();
2122
1133
  bio.reset();
2123
2124
  unsigned char md[EVP_MAX_MD_SIZE];
2125
  unsigned int md_size;
2126
  char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
2127
1133
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
2128
1133
      AddFingerprintDigest(md, md_size, &fingerprint);
2129
2266
      info->Set(context, env->fingerprint_string(),
2130
4532
                OneByteString(env->isolate(), fingerprint)).Check();
2131
  }
2132
1133
  if (X509_digest(cert, EVP_sha256(), md, &md_size)) {
2133
1133
      AddFingerprintDigest(md, md_size, &fingerprint);
2134
2266
      info->Set(context, env->fingerprint256_string(),
2135
4532
                OneByteString(env->isolate(), fingerprint)).Check();
2136
  }
2137
2138
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
2139
2266
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
2140
1133
  if (eku) {
2141
8
    const int count = sk_ASN1_OBJECT_num(eku.get());
2142
16
    MaybeStackBuffer<Local<Value>, 16> ext_key_usage(count);
2143
    char buf[256];
2144
2145
8
    int j = 0;
2146
20
    for (int i = 0; i < count; i++) {
2147
12
      if (OBJ_obj2txt(buf,
2148
                      sizeof(buf),
2149
12
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
2150
24
        ext_key_usage[j++] = OneByteString(env->isolate(), buf);
2151
      }
2152
    }
2153
2154
8
    eku.reset();
2155
16
    info->Set(context, env->ext_key_usage_string(),
2156
32
              Array::New(env->isolate(), ext_key_usage.out(), count)).Check();
2157
  }
2158
2159
1133
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
2160
2266
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
2161
1133
    if (bn) {
2162
2266
      OpenSSLBuffer buf(BN_bn2hex(bn.get()));
2163
1133
      if (buf) {
2164
2266
        info->Set(context, env->serial_number_string(),
2165
4532
                  OneByteString(env->isolate(), buf.get())).Check();
2166
      }
2167
    }
2168
  }
2169
2170
  // Raw DER certificate
2171
1133
  int size = i2d_X509(cert, nullptr);
2172
2266
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
2173
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
2174
1133
      Buffer::Data(buff));
2175
1133
  i2d_X509(cert, &serialized);
2176
3399
  info->Set(context, env->raw_string(), buff).Check();
2177
2178
1133
  return scope.Escape(info);
2179
}
2180
2181
2182
385
static Local<Object> AddIssuerChainToObject(X509Pointer* cert,
2183
                                            Local<Object> object,
2184
                                            StackOfX509&& peer_certs,
2185
                                            Environment* const env) {
2186
385
  Local<Context> context = env->isolate()->GetCurrentContext();
2187
385
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
2188
  for (;;) {
2189
    int i;
2190
391
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
2191
337
      X509* ca = sk_X509_value(peer_certs.get(), i);
2192
337
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
2193
2
        continue;
2194
2195
335
      Local<Object> ca_info = X509ToObject(env, ca);
2196
1005
      object->Set(context, env->issuercert_string(), ca_info).Check();
2197
335
      object = ca_info;
2198
2199
      // NOTE: Intentionally freeing cert that is not used anymore.
2200
      // Delete cert and continue aggregating issuers.
2201
335
      cert->reset(sk_X509_delete(peer_certs.get(), i));
2202
335
      break;
2203
    }
2204
2205
    // Issuer not found, break out of the loop.
2206
389
    if (i == sk_X509_num(peer_certs.get()))
2207
385
      break;
2208
4
  }
2209
385
  return object;
2210
}
2211
2212
2213
385
static StackOfX509 CloneSSLCerts(X509Pointer&& cert,
2214
                                 const STACK_OF(X509)* const ssl_certs) {
2215
770
  StackOfX509 peer_certs(sk_X509_new(nullptr));
2216
385
  if (cert)
2217
    sk_X509_push(peer_certs.get(), cert.release());
2218
1107
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
2219
1444
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
2220

722
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
2221
      return StackOfX509();
2222
    // `cert` is now managed by the stack.
2223
722
    cert.release();
2224
  }
2225
385
  return peer_certs;
2226
}
2227
2228
2229
385
static Local<Object> GetLastIssuedCert(X509Pointer* cert,
2230
                                       const SSLPointer& ssl,
2231
                                       Local<Object> issuer_chain,
2232
                                       Environment* const env) {
2233
385
  Local<Context> context = env->isolate()->GetCurrentContext();
2234
1101
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
2235
    X509* ca;
2236
358
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
2237
      break;
2238
2239
358
    Local<Object> ca_info = X509ToObject(env, ca);
2240
1074
    issuer_chain->Set(context, env->issuercert_string(), ca_info).Check();
2241
358
    issuer_chain = ca_info;
2242
2243
    // Delete previous cert and continue aggregating issuers.
2244
358
    cert->reset(ca);
2245
  }
2246
385
  return issuer_chain;
2247
}
2248
2249
2250
template <class Base>
2251
434
void SSLWrap<Base>::GetPeerCertificate(
2252
    const FunctionCallbackInfo<Value>& args) {
2253
  Base* w;
2254
434
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2255
434
  Environment* env = w->ssl_env();
2256
2257
434
  ClearErrorOnReturn clear_error_on_return;
2258
2259
  Local<Object> result;
2260
  // Used to build the issuer certificate chain.
2261
  Local<Object> issuer_chain;
2262
2263
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
2264
  // contains the `peer_certificate`, but on server it doesn't.
2265
  X509Pointer cert(
2266
868
      w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) : nullptr);
2267
434
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_.get());
2268


434
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
2269
5
    goto done;
2270
2271
  // Short result requested.
2272

1287
  if (args.Length() < 1 || !args[0]->IsTrue()) {
2273
44
    result = X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
2274
44
    goto done;
2275
  }
2276
2277
770
  if (auto peer_certs = CloneSSLCerts(std::move(cert), ssl_certs)) {
2278
    // First and main certificate.
2279
770
    X509Pointer cert(sk_X509_value(peer_certs.get(), 0));
2280
385
    CHECK(cert);
2281
385
    result = X509ToObject(env, cert.release());
2282
2283
385
    issuer_chain =
2284
385
        AddIssuerChainToObject(&cert, result, std::move(peer_certs), env);
2285
385
    issuer_chain = GetLastIssuedCert(&cert, w->ssl_, issuer_chain, env);
2286
    // Last certificate should be self-signed.
2287
385
    if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK)
2288
1540
      issuer_chain->Set(env->context(),
2289
                        env->issuercert_string(),
2290
                        issuer_chain).Check();
2291
  }
2292
2293
 done:
2294
868
  args.GetReturnValue().Set(result);
2295
}
2296
2297
2298
template <class Base>
2299
12
void SSLWrap<Base>::GetCertificate(
2300
    const FunctionCallbackInfo<Value>& args) {
2301
  Base* w;
2302
12
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2303
12
  Environment* env = w->ssl_env();
2304
2305
12
  ClearErrorOnReturn clear_error_on_return;
2306
2307
  Local<Object> result;
2308
2309
12
  X509* cert = SSL_get_certificate(w->ssl_.get());
2310
2311
12
  if (cert != nullptr)
2312
11
    result = X509ToObject(env, cert);
2313
2314
24
  args.GetReturnValue().Set(result);
2315
}
2316
2317
2318
template <class Base>
2319
3
void SSLWrap<Base>::GetFinished(const FunctionCallbackInfo<Value>& args) {
2320
3
  Environment* env = Environment::GetCurrent(args);
2321
2322
  Base* w;
2323
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2324
2325
  // We cannot just pass nullptr to SSL_get_finished()
2326
  // because it would further be propagated to memcpy(),
2327
  // where the standard requirements as described in ISO/IEC 9899:2011
2328
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2329
  // Thus, we use a dummy byte.
2330
  char dummy[1];
2331
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
2332
3
  if (len == 0)
2333
1
    return;
2334
2335
4
  AllocatedBuffer buf = env->AllocateManaged(len);
2336
2
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf.data(), len));
2337
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
2338
}
2339
2340
2341
template <class Base>
2342
3
void SSLWrap<Base>::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
2343
3
  Environment* env = Environment::GetCurrent(args);
2344
2345
  Base* w;
2346
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2347
2348
  // We cannot just pass nullptr to SSL_get_peer_finished()
2349
  // because it would further be propagated to memcpy(),
2350
  // where the standard requirements as described in ISO/IEC 9899:2011
2351
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2352
  // Thus, we use a dummy byte.
2353
  char dummy[1];
2354
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
2355
3
  if (len == 0)
2356
1
    return;
2357
2358
4
  AllocatedBuffer buf = env->AllocateManaged(len);
2359
2
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf.data(), len));
2360
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
2361
}
2362
2363
2364
template <class Base>
2365
19
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
2366
19
  Environment* env = Environment::GetCurrent(args);
2367
2368
  Base* w;
2369
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2370
2371
19
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2372
19
  if (sess == nullptr)
2373
    return;
2374
2375
19
  int slen = i2d_SSL_SESSION(sess, nullptr);
2376
19
  if (slen <= 0)
2377
    return;  // Invalid or malformed session.
2378
2379
38
  AllocatedBuffer sbuf = env->AllocateManaged(slen);
2380
19
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf.data());
2381
19
  CHECK_LT(0, i2d_SSL_SESSION(sess, &p));
2382
57
  args.GetReturnValue().Set(sbuf.ToBuffer().ToLocalChecked());
2383
}
2384
2385
2386
template <class Base>
2387
128
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
2388
128
  Environment* env = Environment::GetCurrent(args);
2389
2390
  Base* w;
2391
128
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2392
2393
128
  if (args.Length() < 1) {
2394
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
2395
  }
2396
2397
128
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
2398
256
  ArrayBufferViewContents<unsigned char> sbuf(args[0].As<ArrayBufferView>());
2399
2400
128
  const unsigned char* p = sbuf.data();
2401
256
  SSLSessionPointer sess(d2i_SSL_SESSION(nullptr, &p, sbuf.length()));
2402
2403
128
  if (sess == nullptr)
2404
    return;
2405
2406
128
  int r = SSL_set_session(w->ssl_.get(), sess.get());
2407
2408
128
  if (!r)
2409
    return env->ThrowError("SSL_set_session error");
2410
}
2411
2412
2413
template <class Base>
2414
10
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
2415
  Base* w;
2416
10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2417
2418
  // TODO(@sam-github) check arg length and types in js, and CHECK in c++
2419

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2420
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
2421
2422
10
    const unsigned char* p = sbuf.data();
2423
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
2424
2425
    // Setup next session and move hello to the BIO buffer
2426
10
    w->next_sess_.reset(sess);
2427
  }
2428
}
2429
2430
2431
template <class Base>
2432
474
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2433
  Base* w;
2434
474
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2435
474
  bool yes = SSL_session_reused(w->ssl_.get());
2436
1422
  args.GetReturnValue().Set(yes);
2437
}
2438
2439
2440
template <class Base>
2441
19
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2442
  Base* w;
2443
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2444
19
  w->hello_parser_.End();
2445
}
2446
2447
2448
template <class Base>
2449
92
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2450
  Base* w;
2451
93
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2452
2453
91
  ClearErrorOnReturn clear_error_on_return;
2454
2455
92
  if (SSL_renegotiate(w->ssl_.get()) != 1) {
2456
1
    return ThrowCryptoError(w->ssl_env(), ERR_get_error());
2457
  }
2458
}
2459
2460
2461
template <class Base>
2462
18
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2463
  Base* w;
2464
18
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2465
18
  Environment* env = w->ssl_env();
2466
2467
18
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2468
18
  if (sess == nullptr)
2469
    return;
2470
2471
  const unsigned char* ticket;
2472
  size_t length;
2473
18
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2474
2475
18
  if (ticket == nullptr)
2476
    return;
2477
2478
36
  Local<Object> buff = Buffer::Copy(
2479
18
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2480
2481
36
  args.GetReturnValue().Set(buff);
2482
}
2483
2484
2485
template <class Base>
2486
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2487
  Base* w;
2488
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2489
8
  w->awaiting_new_session_ = false;
2490
8
  w->NewSessionDoneCb();
2491
}
2492
2493
2494
template <class Base>
2495
2
void SSLWrap<Base>::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
2496
  Base* w;
2497
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2498
2
  Environment* env = w->env();
2499
2500
2
  if (args.Length() < 1)
2501
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
2502
2503
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
2504
2505
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
2506
}
2507
2508
2509
template <class Base>
2510
4
void SSLWrap<Base>::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
2511
  Base* w;
2512
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2513
2514
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
2515
}
2516
2517
2518
template <class Base>
2519
806
void SSLWrap<Base>::GetEphemeralKeyInfo(
2520
    const FunctionCallbackInfo<Value>& args) {
2521
  Base* w;
2522
806
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2523
806
  Environment* env = Environment::GetCurrent(args);
2524
806
  Local<Context> context = env->context();
2525
2526
806
  CHECK(w->ssl_);
2527
2528
  // tmp key is available on only client
2529
806
  if (w->is_server())
2530
14
    return args.GetReturnValue().SetNull();
2531
2532
799
  Local<Object> info = Object::New(env->isolate());
2533
2534
  EVP_PKEY* raw_key;
2535
799
  if (SSL_get_server_tmp_key(w->ssl_.get(), &raw_key)) {
2536
1520
    EVPKeyPointer key(raw_key);
2537
760
    int kid = EVP_PKEY_id(key.get());
2538
760
    switch (kid) {
2539
      case EVP_PKEY_DH:
2540
28
        info->Set(context, env->type_string(),
2541
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH")).Check();
2542
28
        info->Set(context, env->size_string(),
2543
7
                  Integer::New(env->isolate(), EVP_PKEY_bits(key.get())))
2544
            .Check();
2545
7
        break;
2546
      case EVP_PKEY_EC:
2547
      case EVP_PKEY_X25519:
2548
      case EVP_PKEY_X448:
2549
        {
2550
          const char* curve_name;
2551
753
          if (kid == EVP_PKEY_EC) {
2552
5
            EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key.get());
2553
5
            int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2554
5
            curve_name = OBJ_nid2sn(nid);
2555
5
            EC_KEY_free(ec);
2556
          } else {
2557
748
            curve_name = OBJ_nid2sn(kid);
2558
          }
2559
3012
          info->Set(context, env->type_string(),
2560
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")).Check();
2561
3012
          info->Set(context, env->name_string(),
2562
                    OneByteString(args.GetIsolate(),
2563
                                  curve_name)).Check();
2564
3012
          info->Set(context, env->size_string(),
2565
                    Integer::New(env->isolate(),
2566
753
                                 EVP_PKEY_bits(key.get()))).Check();
2567
        }
2568
753
        break;
2569
      default:
2570
        break;
2571
    }
2572
  }
2573
  // TODO(@sam-github) semver-major: else return ThrowCryptoError(env,
2574
  // ERR_get_error())
2575
2576
1598
  return args.GetReturnValue().Set(info);
2577
}
2578
2579
2580
#ifdef SSL_set_max_send_fragment
2581
template <class Base>
2582
3
void SSLWrap<Base>::SetMaxSendFragment(
2583
    const FunctionCallbackInfo<Value>& args) {
2584

9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2585
2586
  Base* w;
2587
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2588
2589
12
  int rv = SSL_set_max_send_fragment(
2590
      w->ssl_.get(),
2591
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2592
6
  args.GetReturnValue().Set(rv);
2593
}
2594
#endif  // SSL_set_max_send_fragment
2595
2596
2597
template <class Base>
2598
869
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2599
  Base* w;
2600
1333
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2601
2602
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2603
  // peer certificate is questionable but it's compatible with what was
2604
  // here before.
2605
  long x509_verify_error =  // NOLINT(runtime/int)
2606
869
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2607
869
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_.get())) {
2608
861
    X509_free(peer_cert);
2609
861
    x509_verify_error = SSL_get_verify_result(w->ssl_.get());
2610
  } else {
2611
8
    const SSL_CIPHER* curr_cipher = SSL_get_current_cipher(w->ssl_.get());
2612
8
    const SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2613
    // Allow no-cert for PSK authentication in TLS1.2 and lower.
2614
    // In TLS1.3 check that session was reused because TLS1.3 PSK
2615
    // looks like session resumption. Is there a better way?
2616

21
    if (SSL_CIPHER_get_auth_nid(curr_cipher) == NID_auth_psk ||
2617
12
        (SSL_SESSION_get_protocol_version(sess) == TLS1_3_VERSION &&
2618
6
         SSL_session_reused(w->ssl_.get())))
2619
14
      return args.GetReturnValue().SetNull();
2620
  }
2621
2622
862
  if (x509_verify_error == X509_V_OK)
2623
914
    return args.GetReturnValue().SetNull();
2624
2625
405
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2626
405
  const char* code = reason;
2627
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2628







405
  switch (x509_verify_error) {
2629
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2630
1
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2631
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2632
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2633
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2634
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2635
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2636
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2637
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2638
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2639
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2640
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2641
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2642
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2643
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2644
    CASE_X509_ERR(OUT_OF_MEM)
2645
231
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2646
13
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2647
3
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2648
154
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2649
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2650
1
    CASE_X509_ERR(CERT_REVOKED)
2651
    CASE_X509_ERR(INVALID_CA)
2652
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2653
1
    CASE_X509_ERR(INVALID_PURPOSE)
2654
    CASE_X509_ERR(CERT_UNTRUSTED)
2655
    CASE_X509_ERR(CERT_REJECTED)
2656
  }
2657
#undef CASE_X509_ERR
2658
2659
405
  Isolate* isolate = args.GetIsolate();
2660
405
  Local<String> reason_string = OneByteString(isolate, reason);
2661
405
  Local<Value> exception_value = Exception::Error(reason_string);
2662
  Local<Object> exception_object =
2663
1215
    exception_value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2664
  exception_object->Set(w->env()->context(), w->env()->code_string(),
2665
2025
                        OneByteString(isolate, code)).Check();
2666
810
  args.GetReturnValue().Set(exception_object);
2667
}
2668
2669
2670
template <class Base>
2671
49
void SSLWrap<Base>::GetCipher(const FunctionCallbackInfo<Value>& args) {
2672
  Base* w;
2673
49
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2674
49
  Environment* env = w->ssl_env();
2675
49
  Local<Context> context = env->context();
2676
2677
49
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get());
2678
49
  if (c == nullptr)
2679
    return;
2680
2681
49
  Local<Object> info = Object::New(env->isolate());
2682
49
  const char* cipher_name = SSL_CIPHER_get_name(c);
2683
196
  info->Set(context, env->name_string(),
2684
            OneByteString(args.GetIsolate(), cipher_name)).Check();
2685
49
  const char* cipher_standard_name = SSL_CIPHER_standard_name(c);
2686
196
  info->Set(context, env->standard_name_string(),
2687
            OneByteString(args.GetIsolate(), cipher_standard_name)).Check();
2688
49
  const char* cipher_version = SSL_CIPHER_get_version(c);
2689
196
  info->Set(context, env->version_string(),
2690
            OneByteString(args.GetIsolate(), cipher_version)).Check();
2691
98
  args.GetReturnValue().Set(info);
2692
}
2693
2694
2695
template <class Base>
2696
2
void SSLWrap<Base>::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
2697
  Base* w;
2698
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2699
2
  Environment* env = w->ssl_env();
2700
2701
2
  SSL* ssl = w->ssl_.get();
2702
  int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
2703
2
                                    nullptr);
2704
4
  MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
2705
2706
5
  for (int i = 0; i < nsig; i++) {
2707
    int hash_nid;
2708
    int sign_nid;
2709
6
    std::string sig_with_md;
2710
2711
3
    SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
2712
                           nullptr);
2713
2714

3
    switch (sign_nid) {
2715
      case EVP_PKEY_RSA:
2716
        sig_with_md = "RSA+";
2717
        break;
2718
2719
      case EVP_PKEY_RSA_PSS:
2720
2
        sig_with_md = "RSA-PSS+";
2721
2
        break;
2722
2723
      case EVP_PKEY_DSA:
2724
        sig_with_md = "DSA+";
2725
        break;
2726
2727
      case EVP_PKEY_EC:
2728
1
        sig_with_md = "ECDSA+";
2729
1
        break;
2730
2731
      case NID_ED25519:
2732
        sig_with_md = "Ed25519+";
2733
        break;
2734
2735
      case NID_ED448:
2736
        sig_with_md = "Ed448+";
2737
        break;
2738
#ifndef OPENSSL_NO_GOST
2739
      case NID_id_GostR3410_2001:
2740
        sig_with_md = "gost2001+";
2741
        break;
2742
2743
      case NID_id_GostR3410_2012_256:
2744
        sig_with_md = "gost2012_256+";
2745
        break;
2746
2747
      case NID_id_GostR3410_2012_512:
2748
        sig_with_md = "gost2012_512+";
2749
        break;
2750
#endif  // !OPENSSL_NO_GOST
2751
      default:
2752
        const char* sn = OBJ_nid2sn(sign_nid);
2753
2754
        if (sn != nullptr) {
2755
          sig_with_md = std::string(sn) + "+";
2756
        } else {
2757
          sig_with_md = "UNDEF+";
2758
        }
2759
        break;
2760
    }
2761
2762
3
    const char* sn_hash = OBJ_nid2sn(hash_nid);
2763
3
    if (sn_hash != nullptr) {
2764
3
      sig_with_md += std::string(sn_hash);
2765
    } else {
2766
      sig_with_md += "UNDEF";
2767
    }
2768
6
    ret_arr[i] = OneByteString(env->isolate(), sig_with_md.c_str());
2769
  }
2770
2771
6
  args.GetReturnValue().Set(
2772
                 Array::New(env->isolate(), ret_arr.out(), ret_arr.length()));
2773
}
2774
2775
2776
template <class Base>
2777
547
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2778
  Base* w;
2779
547
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2780
2781
547
  const char* tls_version = SSL_get_version(w->ssl_.get());
2782
1641
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2783
}
2784
2785
2786
template <class Base>
2787
26
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2788
                                      const unsigned char** out,
2789
                                      unsigned char* outlen,
2790
                                      const unsigned char* in,
2791
                                      unsigned int inlen,
2792
                                      void* arg) {
2793
26
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2794
26
  Environment* env = w->env();
2795
52
  HandleScope handle_scope(env->isolate());
2796
26
  Context::Scope context_scope(env->context());
2797
2798
  Local<Value> alpn_buffer =
2799
52
      w->object()->GetPrivate(
2800
          env->context(),
2801
78
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2802
26
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
2803
26
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2804
26
                                     alpn_protos.data(), alpn_protos.length(),
2805
26
                                     in, inlen);
2806
  // According to 3.2. Protocol Selection of RFC7301, fatal
2807
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2808
  // support it yet. See
2809
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2810
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2811
52
                                          : SSL_TLSEXT_ERR_NOACK;
2812
}
2813
2814
2815
template <class Base>
2816
1609
void SSLWrap<Base>::GetALPNNegotiatedProto(
2817
    const FunctionCallbackInfo<Value>& args) {
2818
  Base* w;
2819
1609
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2820
2821
  const unsigned char* alpn_proto;
2822
  unsigned int alpn_proto_len;
2823
2824
1609
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2825
2826
  Local<Value> result;
2827
1609
  if (alpn_proto_len == 0) {
2828
3122
    result = False(args.GetIsolate());
2829

90
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
2830
42
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
2831
84
    result = w->env()->h2_string();
2832

8
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
2833
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
2834
4
    result = w->env()->http_1_1_string();
2835
  } else {
2836
12
    result = OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len);
2837
  }
2838
2839
3218
  args.GetReturnValue().Set(result);
2840
}
2841
2842
2843
template <class Base>
2844
200
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2845
  Base* w;
2846
200
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2847
200
  Environment* env = w->env();
2848

400
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2849
    return env->ThrowTypeError("Must give a Buffer as first argument");
2850
2851
200
  if (w->is_client()) {
2852
31
    ArrayBufferViewContents<unsigned char> alpn_protos(args[0]);
2853
62
    int r = SSL_set_alpn_protos(
2854
93
        w->ssl_.get(), alpn_protos.data(), alpn_protos.length());
2855
31
    CHECK_EQ(r, 0);
2856
  } else {
2857
507
    CHECK(
2858
        w->object()->SetPrivate(
2859
            env->context(),
2860
            env->alpn_buffer_private_symbol(),
2861
            args[0]).FromJust());
2862
    // Server should select ALPN protocol from list of advertised by client
2863
169
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2864
                               SelectALPNCallback,
2865
                               nullptr);
2866
  }
2867
}
2868
2869
2870
template <class Base>
2871
8
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2872
8
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2873
8
  Environment* env = w->env();
2874
16
  HandleScope handle_scope(env->isolate());
2875
2876
8
  if (w->is_client()) {
2877
    // Incoming response
2878
    const unsigned char* resp;
2879
4
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2880
    Local<Value> arg;
2881
4
    if (resp == nullptr) {
2882
4
      arg = Null(env->isolate());
2883
    } else {
2884
2
      arg =
2885
4
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2886
          .ToLocalChecked();
2887
    }
2888
2889
4
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2890
2891
    // No async acceptance is possible, so always return 1 to accept the
2892
    // response.  The listener for 'OCSPResponse' event has no control over
2893
    // return value, but it can .destroy() the connection if the response is not
2894
    // acceptable.
2895
4
    return 1;
2896
  } else {
2897
    // Outgoing response
2898
8
    if (w->ocsp_response_.IsEmpty())
2899
2
      return SSL_TLSEXT_ERR_NOACK;
2900
2901
2
    Local<ArrayBufferView> obj = PersistentToLocal::Default(env->isolate(),
2902
2
                                                            w->ocsp_response_);
2903
2
    size_t len = obj->ByteLength();
2904
2905
    // OpenSSL takes control of the pointer after accepting it
2906
2
    unsigned char* data = MallocOpenSSL<unsigned char>(len);
2907
2
    obj->CopyContents(data, len);
2908
2909
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2910
      OPENSSL_free(data);
2911
2
    w->ocsp_response_.Reset();
2912
2913
2
    return SSL_TLSEXT_ERR_OK;
2914
  }
2915
}
2916
2917
2918
template <class Base>
2919
22
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2920
22
  cert_cb_ = cb;
2921
22
  cert_cb_arg_ = arg;
2922
22
}
2923
2924
2925
template <class Base>
2926
869
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2927
869
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2928
2929
869
  if (!w->is_server())
2930
41
    return 1;
2931
2932
828
  if (!w->is_waiting_cert_cb())
2933
806
    return 1;
2934
2935
22
  if (w->cert_cb_running_)
2936
    // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
2937
    // handshake will continue after certcb is done.
2938
    return -1;
2939
2940
22
  Environment* env = w->env();
2941
22
  Local<Context> context = env->context();
2942
44
  HandleScope handle_scope(env->isolate());
2943
  Context::Scope context_scope(context);
2944
22
  w->cert_cb_running_ = true;
2945
2946
22
  Local<Object> info = Object::New(env->isolate());
2947
2948
22
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2949
22
  if (servername == nullptr) {
2950
16
    info->Set(context,
2951
              env->servername_string(),
2952
              String::Empty(env->isolate())).Check();
2953
  } else {
2954
18
    Local<String> str = OneByteString(env->isolate(), servername,
2955
36
                                      strlen(servername));
2956
54
    info->Set(context, env->servername_string(), str).Check();
2957
  }
2958
2959
22
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
2960
88
  info->Set(context, env->ocsp_request_string(),
2961
            Boolean::New(env->isolate(), ocsp)).Check();
2962
2963
44
  Local<Value> argv[] = { info };
2964
22
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2965
2966
22
  if (!w->cert_cb_running_)
2967
9
    return 1;
2968
2969
  // Performing async action, wait...
2970
13
  return -1;
2971
}
2972
2973
2974
template <class Base>
2975
19
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2976
  Base* w;
2977
22
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2978
19
  Environment* env = w->env();
2979
2980

19
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2981
2982
19
  Local<Object> object = w->object();
2983
76
  Local<Value> ctx = object->Get(env->context(),
2984
19
                                 env->sni_context_string()).ToLocalChecked();
2985
19
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2986
2987
  // Not an object, probably undefined or null
2988
19
  if (!ctx->IsObject())
2989
8
    goto fire_cb;
2990
2991
11
  if (cons->HasInstance(ctx)) {
2992
9
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
2993
9
    CHECK_NOT_NULL(sc);
2994
    // Store the SNI context for later use.
2995
9
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
2996
2997
    int rv;
2998
2999
    // NOTE: reference count is not increased by this API methods
3000
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_.get());
3001
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_.get());
3002
    STACK_OF(X509)* chain;
3003
3004
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_.get(), &chain);
3005
9
    if (rv)
3006
9
      rv = SSL_use_certificate(w->ssl_.get(), x509);
3007
9
    if (rv)
3008
8
      rv = SSL_use_PrivateKey(w->ssl_.get(), pkey);
3009

9
    if (rv && chain != nullptr)
3010
1
      rv = SSL_set1_chain(w->ssl_.get(), chain);
3011
9
    if (rv)
3012
8
      rv = w->SetCACerts(sc);
3013
9
    if (!rv) {
3014
      // Not clear why sometimes we throw error, and sometimes we call
3015
      // onerror(). Both cause .destroy(), but onerror does a bit more.
3016
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
3017
1
      return ThrowCryptoError(env, err, "CertCbDone");
3018
    }
3019
  } else {
3020
    // Failure: incorrect SNI context object
3021
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
3022
2
    w->MakeCallback(env->onerror_string(), 1, &err);
3023
2
    return;
3024
  }
3025
3026
 fire_cb:
3027
  CertCb cb;
3028
  void* arg;
3029
3030
16
  cb = w->cert_cb_;
3031
16
  arg = w->cert_cb_arg_;
3032
3033
16
  w->cert_cb_running_ = false;
3034
16
  w->cert_cb_ = nullptr;
3035
16
  w->cert_cb_arg_ = nullptr;
3036
3037
16
  cb(arg);
3038
}
3039
3040
3041
template <class Base>
3042
24240
void SSLWrap<Base>::DestroySSL() {
3043
24240
  if (!ssl_)
3044
12085
    return;
3045
3046
12155
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
3047
12155
  ssl_.reset();
3048
}
3049
3050
3051
template <class Base>
3052
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
3053
8
  int err = SSL_set1_verify_cert_store(ssl_.get(),
3054
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
3055
8
  if (err != 1)
3056
    return err;
3057
3058
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
3059
8
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
3060
3061
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
3062
8
  SSL_set_client_CA_list(ssl_.get(), list);
3063
8
  return 1;
3064
}
3065
3066
template <class Base>
3067
void SSLWrap<Base>::MemoryInfo(MemoryTracker* tracker) const {
3068
  tracker->TrackField("ocsp_response", ocsp_response_);
3069
  tracker->TrackField("sni_context", sni_context_);
3070
}
3071
3072
1919
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
3073
  // From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
3074
  //
3075
  //   If VerifyCallback returns 1, the verification process is continued. If
3076
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
3077
  //   terminated with respect to verification failures and the connection will
3078
  //   be established. The calling process can however retrieve the error code
3079
  //   of the last verification error using SSL_get_verify_result(3) or by
3080
  //   maintaining its own error storage managed by VerifyCallback.
3081
  //
3082
  // Since we cannot perform I/O quickly enough with X509_STORE_CTX_ APIs in
3083
  // this callback, we ignore all preverify_ok errors and let the handshake
3084
  // continue. It is imperative that the user use Connection::VerifyError after
3085
  // the 'secure' callback has been made.
3086
1919
  return 1;
3087
}
3088
3089
3356
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
3090
3356
  const int mode = EVP_CIPHER_mode(cipher);
3091
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
3092
  // but its mode is 0 which doesn't indicate
3093
6665
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
3094
6074
         mode == EVP_CIPH_CCM_MODE ||
3095

7453
         mode == EVP_CIPH_GCM_MODE ||
3096
4688
         IS_OCB_MODE(mode);
3097
}
3098
3099
1456
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
3100
1456
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
3101
1456
  return IsSupportedAuthenticatedMode(cipher);
3102
}
3103
3104
enum class ParseKeyResult {
3105
  kParseKeyOk,
3106
  kParseKeyNotRecognized,
3107
  kParseKeyNeedPassphrase,
3108
  kParseKeyFailed
3109
};
3110
3111
2906
static ParseKeyResult TryParsePublicKey(
3112
    EVPKeyPointer* pkey,
3113
    const BIOPointer& bp,
3114
    const char* name,
3115
    // NOLINTNEXTLINE(runtime/int)
3116
    const std::function<EVP_PKEY*(const unsigned char** p, long l)>& parse) {
3117
  unsigned char* der_data;
3118
  long der_len;  // NOLINT(runtime/int)
3119
3120
  // This skips surrounding data and decodes PEM to DER.
3121
  {
3122
3778
    MarkPopErrorOnReturn mark_pop_error_on_return;
3123
2906
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
3124
                           bp.get(), nullptr, nullptr) != 1)
3125
2034
      return ParseKeyResult::kParseKeyNotRecognized;
3126
  }
3127
3128
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
3129
872
  const unsigned char* p = der_data;
3130
872
  pkey->reset(parse(&p, der_len));
3131
872
  OPENSSL_clear_free(der_data, der_len);
3132
3133
872
  return *pkey ? ParseKeyResult::kParseKeyOk :
3134
1744
                 ParseKeyResult::kParseKeyFailed;
3135
}
3136
3137
1055
static ParseKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
3138
                                        const char* key_pem,
3139
                                        int key_pem_len) {
3140
2110
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
3141
1055
  if (!bp)
3142
    return ParseKeyResult::kParseKeyFailed;
3143
3144
  ParseKeyResult ret;
3145
3146
  // Try parsing as a SubjectPublicKeyInfo first.
3147
2110
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
3148
122
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3149
        return d2i_PUBKEY(nullptr, p, l);
3150
1177
      });
3151
1055
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
3152
122
    return ret;
3153
3154
  // Maybe it is PKCS#1.
3155
933
  CHECK(BIO_reset(bp.get()));
3156
1866
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
3157
15
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3158
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
3159
948
      });
3160
933
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
3161
15
    return ret;
3162
3163
  // X.509 fallback.
3164
918
  CHECK(BIO_reset(bp.get()));
3165
1836
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
3166
735
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3167
1470
        X509Pointer x509(d2i_X509(nullptr, p, l));
3168
1470
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
3169
918
      });
3170
}
3171
3172
22
static ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
3173
                                     const PublicKeyEncodingConfig& config,
3174
                                     const char* key,
3175
                                     size_t key_len) {
3176
22
  if (config.format_ == kKeyFormatPEM) {
3177
    return ParsePublicKeyPEM(pkey, key, key_len);
3178
  } else {
3179
22
    CHECK_EQ(config.format_, kKeyFormatDER);
3180
3181
22
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3182
44
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3183
22
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
3184
    } else {
3185
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
3186
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
3187
    }
3188
3189
22
    return *pkey ? ParseKeyResult::kParseKeyOk :
3190
44
                   ParseKeyResult::kParseKeyFailed;
3191
  }
3192
}
3193
3194
47
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
3195
                                               BIO* bio,
3196
                                               PKFormatType format) {
3197
  BUF_MEM* bptr;
3198
47
  BIO_get_mem_ptr(bio, &bptr);
3199
47
  if (format == kKeyFormatPEM) {
3200
    // PEM is an ASCII format, so we will return it as a string.
3201
111
    return String::NewFromUtf8(env->isolate(), bptr->data,
3202
                               NewStringType::kNormal,
3203
111
                               bptr->length).ToLocalChecked();
3204
  } else {
3205
10
    CHECK_EQ(format, kKeyFormatDER);
3206
    // DER is binary, return it as a buffer.
3207
20
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
3208
  }
3209
}
3210
3211
26
static bool WritePublicKeyInner(EVP_PKEY* pkey,
3212
                                const BIOPointer& bio,
3213
                                const PublicKeyEncodingConfig& config) {
3214
52
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3215
    // PKCS#1 is only valid for RSA keys.
3216
9
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
3217
18
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
3218
9
    if (config.format_ == kKeyFormatPEM) {
3219
      // Encode PKCS#1 as PEM.
3220
3
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
3221
    } else {
3222
      // Encode PKCS#1 as DER.
3223
6
      CHECK_EQ(config.format_, kKeyFormatDER);
3224
6
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
3225
    }
3226
  } else {
3227
34
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
3228
17
    if (config.format_ == kKeyFormatPEM) {
3229
      // Encode SPKI as PEM.
3230
17
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
3231
    } else {
3232
      // Encode SPKI as DER.
3233
      CHECK_EQ(config.format_, kKeyFormatDER);
3234
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
3235
    }
3236
  }
3237
}
3238
3239
26
static MaybeLocal<Value> WritePublicKey(Environment* env,
3240
                                        EVP_PKEY* pkey,
3241
                                        const PublicKeyEncodingConfig& config) {
3242
52
  BIOPointer bio(BIO_new(BIO_s_mem()));
3243
26
  CHECK(bio);
3244
3245
26
  if (!WritePublicKeyInner(pkey, bio, config)) {
3246
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
3247
    return MaybeLocal<Value>();
3248
  }
3249
52
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
3250
}
3251
3252
58
static bool IsASN1Sequence(const unsigned char* data, size_t size,
3253
                           size_t* data_offset, size_t* data_size) {
3254

58
  if (size < 2 || data[0] != 0x30)
3255
    return false;
3256
3257
58
  if (data[1] & 0x80) {
3258
    // Long form.
3259
38
    size_t n_bytes = data[1] & ~0x80;
3260

38
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
3261
      return false;
3262
38
    size_t length = 0;
3263
114
    for (size_t i = 0; i < n_bytes; i++)
3264
76
      length = (length << 8) | data[i + 2];
3265
38
    *data_offset = 2 + n_bytes;
3266
38
    *data_size = std::min(size - 2 - n_bytes, length);
3267
  } else {
3268
    // Short form.
3269
20
    *data_offset = 2;
3270
20
    *data_size = std::min<size_t>(size - 2, data[1]);
3271
  }
3272
3273
58
  return true;
3274
}
3275
3276
32
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
3277
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
3278
  size_t offset, len;
3279
32
  if (!IsASN1Sequence(data, size, &offset, &len))
3280
    return false;
3281
3282
  // An RSAPrivateKey sequence always starts with a single-byte integer whose
3283
  // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
3284
  // (which is the product of two primes and therefore at least 4), so we can
3285
  // decide the type of the structure based on the first three bytes of the
3286
  // sequence.
3287
64
  return len >= 3 &&
3288
64
         data[offset] == 2 &&
3289

74
         data[offset + 1] == 1 &&
3290
42
         !(data[offset + 2] & 0xfe);
3291
}
3292
3293
26
static bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
3294
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
3295
  size_t offset, len;
3296
26
  if (!IsASN1Sequence(data, size, &offset, &len))
3297
    return false;
3298
3299
  // A PrivateKeyInfo sequence always starts with an integer whereas an
3300
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
3301

52
  return len >= 1 &&
3302
52
         data[offset] != 2;
3303
}
3304
3305
390
static ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
3306
                                      const PrivateKeyEncodingConfig& config,
3307
                                      const char* key,
3308
                                      size_t key_len) {
3309
  // OpenSSL needs a non-const pointer, that's why the const_cast is required.
3310
390
  char* const passphrase = const_cast<char*>(config.passphrase_.get());
3311
3312
390
  if (config.format_ == kKeyFormatPEM) {
3313
705
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
3314
353
    if (!bio)
3315
1
      return ParseKeyResult::kParseKeyFailed;
3316
3317
352
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
3318
                                        nullptr,
3319
                                        PasswordCallback,
3320
352
                                        passphrase));
3321
  } else {
3322
37
    CHECK_EQ(config.format_, kKeyFormatDER);
3323
3324
74
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3325
11
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3326
11
      pkey->reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
3327
52
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
3328
52
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
3329
26
      if (!bio)
3330
        return ParseKeyResult::kParseKeyFailed;
3331
3332
26
      if (IsEncryptedPrivateKeyInfo(
3333
              reinterpret_cast<const unsigned char*>(key), key_len)) {
3334
17
        pkey->reset(d2i_PKCS8PrivateKey_bio(bio.get(),
3335
                                            nullptr,
3336
                                            PasswordCallback,
3337
17
                                            passphrase));
3338
      } else {
3339
18
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
3340
9
        if (p8inf)
3341
9
          pkey->reset(EVP_PKCS82PKEY(p8inf.get()));
3342
      }
3343
    } else {
3344
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
3345
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3346
      pkey->reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
3347
    }
3348
  }
3349
3350
  // OpenSSL can fail to parse the key but still return a non-null pointer.
3351
389
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
3352
389
  if (err != 0)
3353
18
    pkey->reset();
3354
3355
389
  if (*pkey)
3356
371
    return ParseKeyResult::kParseKeyOk;
3357

28
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
3358
10
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
3359
9
    if (config.passphrase_.get() == nullptr)
3360
8
      return ParseKeyResult::kParseKeyNeedPassphrase;
3361
  }
3362
10
  return ParseKeyResult::kParseKeyFailed;
3363
}
3364
3365
2482
ByteSource::ByteSource(ByteSource&& other)
3366
2482
      : data_(other.data_),
3367
2482
        allocated_data_(other.allocated_data_),
3368
4964
        size_(other.size_) {
3369
2482
  other.allocated_data_ = nullptr;
3370
2482
}
3371
3372
15174
ByteSource::~ByteSource() {
3373
7587
  OPENSSL_clear_free(allocated_data_, size_);
3374
7587
}
3375
3376
102
ByteSource& ByteSource::operator=(ByteSource&& other) {
3377
102
  if (&other != this) {
3378
102
    OPENSSL_clear_free(allocated_data_, size_);
3379
102
    data_ = other.data_;
3380
102
    allocated_data_ = other.allocated_data_;
3381
102
    other.allocated_data_ = nullptr;
3382
102
    size_ = other.size_;
3383
  }
3384
102
  return *this;
3385
}
3386
3387
3712
const char* ByteSource::get() const {
3388
3712
  return data_;
3389
}
3390
3391
3313
size_t ByteSource::size() const {
3392
3313
  return size_;
3393
}
3394
3395
2597
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
3396
                                          Local<Value> value) {
3397
2597
  return Buffer::HasInstance(value) ? FromBuffer(value)
3398
2980
                                    : FromString(env, value.As<String>());
3399
}
3400
3401
457
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
3402
                                  bool ntc) {
3403
914
  CHECK(str->IsString());
3404
914
  size_t size = str->Utf8Length(env->isolate());
3405
457
  size_t alloc_size = ntc ? size + 1 : size;
3406
457
  char* data = MallocOpenSSL<char>(alloc_size);
3407
457
  int opts = String::NO_OPTIONS;
3408
457
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
3409
914
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
3410
457
  return Allocated(data, size);
3411
}
3412
3413
2225
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
3414
2225
  CHECK(buffer->IsArrayBufferView());
3415
2225
  Local<ArrayBufferView> abv = buffer.As<ArrayBufferView>();
3416
2225
  size_t size = abv->ByteLength();
3417
2225
  if (ntc) {
3418
11
    char* data = MallocOpenSSL<char>(size + 1);
3419
11
    abv->CopyContents(data, size);
3420
11
    data[size] = 0;
3421
11
    return Allocated(data, size);
3422
  }
3423
2214
  return Foreign(Buffer::Data(buffer), size);
3424
}
3425
3426
85
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
3427
                                          Local<Value> value) {
3428
85
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
3429
159
                                    : FromString(env, value.As<String>(), true);
3430
}
3431
3432
14
ByteSource ByteSource::FromSymmetricKeyObject(Local<Value> handle) {
3433
14
  CHECK(handle->IsObject());
3434
14
  KeyObject* key = Unwrap<KeyObject>(handle.As<Object>());
3435
14
  CHECK(key);
3436
14
  return Foreign(key->GetSymmetricKey(), key->GetSymmetricKeySize());
3437
}
3438
3439
3758
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
3440
      : data_(data),
3441
        allocated_data_(allocated_data),
3442
3758
        size_(size) {}
3443
3444
472
ByteSource ByteSource::Allocated(char* data, size_t size) {
3445
472
  return ByteSource(data, data, size);
3446
}
3447
3448
3286
ByteSource ByteSource::Foreign(const char* data, size_t size) {
3449
3286
  return ByteSource(data, nullptr, size);
3450
}
3451
3452
enum KeyEncodingContext {
34