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: 3574 3937 90.8 %
Date: 2020-02-27 22:14:15 Branches: 1836 2803 65.5 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_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
1228
  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
8790
inline void CheckEntropy() {
434
  for (;;) {
435
8790
    int status = RAND_status();
436
8790
    CHECK_GE(status, 0);  // Cannot fail.
437
8790
    if (status != 0)
438
17580
      break;
439
440
    // Give up, RAND_poll() not supported.
441
    if (RAND_poll() == 0)
442
      break;
443
  }
444
8790
}
445
446
447
8588
bool EntropySource(unsigned char* buffer, size_t length) {
448
  // Ensure that OpenSSL's PRNG is properly seeded.
449
8588
  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
8588
  return RAND_bytes(buffer, length) != -1;
454
}
455
456
457
template <typename T>
458
316864
static T* MallocOpenSSL(size_t count) {
459
316864
  void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
460


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

6702
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
691

4468
      RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 ||
692
2234
      RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) {
693
    return env->ThrowError("Error generating ticket keys");
694
  }
695
2234
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
696
}
697
698
699
// Takes a string or buffer and loads it into a BIO.
700
// Caller responsible for BIO_free_all-ing the returned object.
701
2235
static BIOPointer LoadBIO(Environment* env, Local<Value> v) {
702
4470
  HandleScope scope(env->isolate());
703
704
4470
  if (v->IsString()) {
705
2630
    const node::Utf8Value s(env->isolate(), v);
706
1315
    return NodeBIO::NewFixed(*s, s.length());
707
  }
708
709
920
  if (v->IsArrayBufferView()) {
710
920
    ArrayBufferViewContents<char> buf(v.As<ArrayBufferView>());
711
920
    return NodeBIO::NewFixed(buf.data(), buf.length());
712
  }
713
714
  return nullptr;
715
}
716
717
718
820
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
719
820
  Environment* env = Environment::GetCurrent(args);
720
721
  SecureContext* sc;
722
830
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
723
724
820
  unsigned int len = args.Length();
725
820
  if (len < 1) {
726
    return THROW_ERR_MISSING_ARGS(env, "Private key argument is mandatory");
727
  }
728
729
820
  if (len > 2) {
730
    return env->ThrowError("Only private key and pass phrase are expected");
731
  }
732
733
820
  if (len == 2) {
734

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

1588
         X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
839
2382
         X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1;
840
}
841
842
843
848
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
844
                                  X509Pointer&& x,
845
                                  STACK_OF(X509)* extra_certs,
846
                                  X509Pointer* cert,
847
                                  X509Pointer* issuer_) {
848
848
  CHECK(!*issuer_);
849
848
  CHECK(!*cert);
850
848
  X509* issuer = nullptr;
851
852
848
  int ret = SSL_CTX_use_certificate(ctx, x.get());
853
854
848
  if (ret) {
855
    // If we could set up our certificate, now proceed to
856
    // the CA certificates.
857
848
    SSL_CTX_clear_extra_chain_certs(ctx);
858
859
1264
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
860
416
      X509* ca = sk_X509_value(extra_certs, i);
861
862
      // NOTE: Increments reference count on `ca`
863
416
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
864
        ret = 0;
865
        issuer = nullptr;
866
        break;
867
      }
868
      // Note that we must not free r if it was successfully
869
      // added to the chain (while we must free the main
870
      // certificate, since its reference count is increased
871
      // by SSL_CTX_use_certificate).
872
873
      // Find issuer
874

416
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
875
4
        continue;
876
877
412
      issuer = ca;
878
    }
879
  }
880
881
  // Try getting issuer from a cert store
882
848
  if (ret) {
883
848
    if (issuer == nullptr) {
884
436
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
885
436
      ret = ret < 0 ? 0 : 1;
886
      // NOTE: get_cert_store doesn't increment reference count,
887
      // no need to free `store`
888
    } else {
889
      // Increment issuer reference count
890
412
      issuer = X509_dup(issuer);
891
412
      if (issuer == nullptr) {
892
        ret = 0;
893
      }
894
    }
895
  }
896
897
848
  issuer_->reset(issuer);
898
899

848
  if (ret && x != nullptr) {
900
848
    cert->reset(X509_dup(x.get()));
901
848
    if (!*cert)
902
      ret = 0;
903
  }
904
848
  return ret;
905
}
906
907
908
// Read a file that contains our certificate in "PEM" format,
909
// possibly followed by a sequence of CA certificates that should be
910
// sent to the peer in the Certificate message.
911
//
912
// Taken from OpenSSL - edited for style.
913
836
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
914
                                  BIOPointer&& in,
915
                                  X509Pointer* cert,
916
                                  X509Pointer* issuer) {
917
  // Just to ensure that `ERR_peek_last_error` below will return only errors
918
  // that we are interested in
919
836
  ERR_clear_error();
920
921
  X509Pointer x(
922
1672
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
923
924
836
  if (!x)
925
    return 0;
926
927
836
  unsigned long err = 0;  // NOLINT(runtime/int)
928
929
1672
  StackOfX509 extra_certs(sk_X509_new_null());
930
836
  if (!extra_certs)
931
    return 0;
932
933
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
934
                                    nullptr,
935
                                    NoPasswordCallback,
936
1243
                                    nullptr)}) {
937
407
    if (sk_X509_push(extra_certs.get(), extra.get())) {
938
407
      extra.release();
939
407
      continue;
940
    }
941
942
    return 0;
943
407
  }
944
945
  // When the while loop ends, it's usually just EOF.
946
836
  err = ERR_peek_last_error();
947

1672
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
948
836
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
949
836
    ERR_clear_error();
950
  } else {
951
    // some real error
952
    return 0;
953
  }
954
955
836
  return SSL_CTX_use_certificate_chain(ctx,
956
836
                                       std::move(x),
957
                                       extra_certs.get(),
958
                                       cert,
959
836
                                       issuer);
960
}
961
962
963
836
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
964
836
  Environment* env = Environment::GetCurrent(args);
965
966
  SecureContext* sc;
967
836
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
968
969
836
  if (args.Length() != 1) {
970
    return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory");
971
  }
972
973
1672
  BIOPointer bio(LoadBIO(env, args[0]));
974
836
  if (!bio)
975
    return;
976
977
836
  sc->cert_.reset();
978
836
  sc->issuer_.reset();
979
980
2508
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(),
981
836
                                         std::move(bio),
982
836
                                         &sc->cert_,
983
1672
                                         &sc->issuer_);
984
985
836
  if (!rv) {
986
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
987
    return ThrowCryptoError(env, err, "SSL_CTX_use_certificate_chain");
988
  }
989
}
990
991
992
248
static X509_STORE* NewRootCertStore() {
993

248
  static std::vector<X509*> root_certs_vector;
994

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

4
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1130
2
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1131
2
    return 0;
1132
  }
1133
1134
  return err;
1135
}
1136
1137
1138
3
void UseExtraCaCerts(const std::string& file) {
1139
3
  ClearErrorOnReturn clear_error_on_return;
1140
1141
3
  if (root_cert_store == nullptr) {
1142
3
    root_cert_store = NewRootCertStore();
1143
1144
3
    if (!file.empty()) {
1145
3
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1146
                                           root_cert_store,
1147
3
                                           file.c_str());
1148
3
      if (err) {
1149
1
        fprintf(stderr,
1150
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
1151
                file.c_str(),
1152
1
                ERR_error_string(err, nullptr));
1153
      } else {
1154
2
        extra_root_certs_loaded = true;
1155
      }
1156
    }
1157
  }
1158
3
}
1159
1160
1161
static void IsExtraRootCertsFileLoaded(
1162
    const FunctionCallbackInfo<Value>& args) {
1163
  return args.GetReturnValue().Set(extra_root_certs_loaded);
1164
}
1165
1166
1167
1703
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
1168
  SecureContext* sc;
1169
1703
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1170
1703
  ClearErrorOnReturn clear_error_on_return;
1171
1172
1703
  if (root_cert_store == nullptr) {
1173
238
    root_cert_store = NewRootCertStore();
1174
  }
1175
1176
  // Increment reference count so global store is not deleted along with CTX.
1177
1703
  X509_STORE_up_ref(root_cert_store);
1178
1703
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
1179
}
1180
1181
1182
2158
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
1183
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
1184
#ifndef OPENSSL_IS_BORINGSSL
1185
  SecureContext* sc;
1186
2159
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1187
2158
  Environment* env = sc->env();
1188
2157
  ClearErrorOnReturn clear_error_on_return;
1189
1190
2158
  CHECK_EQ(args.Length(), 1);
1191
6474
  CHECK(args[0]->IsString());
1192
1193
4315
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1194
2158
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers)) {
1195
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1196
1
    return ThrowCryptoError(env, err, "Failed to set ciphers");
1197
  }
1198
#endif
1199
}
1200
1201
1202
2160
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
1203
  SecureContext* sc;
1204
2175
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1205
2160
  Environment* env = sc->env();
1206
2145
  ClearErrorOnReturn clear_error_on_return;
1207
1208
2160
  CHECK_EQ(args.Length(), 1);
1209
6480
  CHECK(args[0]->IsString());
1210
1211
4305
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1212
2160
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
1213
15
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1214
1215

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

2463
  if (args.Length() != 1 ||
1346
4105
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1347
    return THROW_ERR_INVALID_ARG_TYPE(
1348
        sc->env(), "Options must be an integer value");
1349
  }
1350
1351
821
  SSL_CTX_set_options(sc->ctx_.get(),
1352
821
                      static_cast<long>(val));  // NOLINT(runtime/int)
1353
}
1354
1355
1356
750
void SecureContext::SetSessionIdContext(
1357
    const FunctionCallbackInfo<Value>& args) {
1358
  SecureContext* sc;
1359
1500
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1360
750
  Environment* env = sc->env();
1361
1362
750
  if (args.Length() != 1) {
1363
    return THROW_ERR_MISSING_ARGS(
1364
        env, "Session ID context argument is mandatory");
1365
  }
1366
1367
2250
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1368
1369
750
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1370
  const unsigned char* sid_ctx =
1371
750
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1372
750
  unsigned int sid_ctx_len = sessionIdContext.length();
1373
1374
750
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1375
750
  if (r == 1)
1376
750
    return;
1377
1378
  BUF_MEM* mem;
1379
  Local<String> message;
1380
1381
  BIOPointer bio(BIO_new(BIO_s_mem()));
1382
  if (!bio) {
1383
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1384
                                    "SSL_CTX_set_session_id_context error");
1385
  } else {
1386
    ERR_print_errors(bio.get());
1387
    BIO_get_mem_ptr(bio.get(), &mem);
1388
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1389
  }
1390
1391
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1392
}
1393
1394
1395
2
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1396
  SecureContext* sc;
1397
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1398
1399

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

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

6
    if (Buffer::Length(name_val) != kTicketPartSize ||
1647
3
        Buffer::Length(iv_val) != kTicketPartSize) {
1648
      return -1;
1649
    }
1650
1651
6
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1652
6
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1653
  }
1654
1655
4
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1656
8
  HMAC_Init_ex(hctx,
1657
4
               hmac_buf.data(),
1658
4
               hmac_buf.length(),
1659
               EVP_sha256(),
1660
4
               nullptr);
1661
1662
4
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1663
4
  if (enc) {
1664
3
    EVP_EncryptInit_ex(ectx,
1665
                       EVP_aes_128_cbc(),
1666
                       nullptr,
1667
                       aes_key.data(),
1668
3
                       iv);
1669
  } else {
1670
1
    EVP_DecryptInit_ex(ectx,
1671
                       EVP_aes_128_cbc(),
1672
                       nullptr,
1673
                       aes_key.data(),
1674
1
                       iv);
1675
  }
1676
1677
4
  return r;
1678
}
1679
1680
1681
1145
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1682
                                               unsigned char* name,
1683
                                               unsigned char* iv,
1684
                                               EVP_CIPHER_CTX* ectx,
1685
                                               HMAC_CTX* hctx,
1686
                                               int enc) {
1687
  SecureContext* sc = static_cast<SecureContext*>(
1688
1145
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1689
1690
1145
  if (enc) {
1691
1091
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1692

3273
    if (RAND_bytes(iv, 16) <= 0 ||
1693
1091
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1694

2182
                           sc->ticket_key_aes_, iv) <= 0 ||
1695
1091
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1696
                     EVP_sha256(), nullptr) <= 0) {
1697
      return -1;
1698
    }
1699
1091
    return 1;
1700
  }
1701
1702
54
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1703
    // The ticket key name does not match. Discard the ticket.
1704
12
    return 0;
1705
  }
1706
1707
84
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1708

84
                         iv) <= 0 ||
1709
42
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1710
                   EVP_sha256(), nullptr) <= 0) {
1711
    return -1;
1712
  }
1713
42
  return 1;
1714
}
1715
1716
1717
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1718
  SecureContext* sc;
1719
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1720
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1721
4
  info.GetReturnValue().Set(ext);
1722
}
1723
1724
1725
template <bool primary>
1726
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1727
  SecureContext* wrap;
1728

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1729
6
  Environment* env = wrap->env();
1730
  X509* cert;
1731
1732
  if (primary)
1733
3
    cert = wrap->cert_.get();
1734
  else
1735
3
    cert = wrap->issuer_.get();
1736

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

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

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

722
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
2241
      return StackOfX509();
2242
    // `cert` is now managed by the stack.
2243
722
    cert.release();
2244
  }
2245
385
  return peer_certs;
2246
}
2247
2248
2249
385
static Local<Object> GetLastIssuedCert(X509Pointer* cert,
2250
                                       const SSLPointer& ssl,
2251
                                       Local<Object> issuer_chain,
2252
                                       Environment* const env) {
2253
385
  Local<Context> context = env->isolate()->GetCurrentContext();
2254
1101
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
2255
    X509* ca;
2256
358
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
2257
      break;
2258
2259
358
    Local<Object> ca_info = X509ToObject(env, ca);
2260
1074
    issuer_chain->Set(context, env->issuercert_string(), ca_info).Check();
2261
358
    issuer_chain = ca_info;
2262
2263
    // Delete previous cert and continue aggregating issuers.
2264
358
    cert->reset(ca);
2265
  }
2266
385
  return issuer_chain;
2267
}
2268
2269
2270
template <class Base>
2271
434
void SSLWrap<Base>::GetPeerCertificate(
2272
    const FunctionCallbackInfo<Value>& args) {
2273
  Base* w;
2274
434
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2275
434
  Environment* env = w->ssl_env();
2276
2277
434
  ClearErrorOnReturn clear_error_on_return;
2278
2279
  Local<Object> result;
2280
  // Used to build the issuer certificate chain.
2281
  Local<Object> issuer_chain;
2282
2283
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
2284
  // contains the `peer_certificate`, but on server it doesn't.
2285
  X509Pointer cert(
2286
868
      w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) : nullptr);
2287
434
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_.get());
2288


434
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
2289
5
    goto done;
2290
2291
  // Short result requested.
2292

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

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

9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2605
2606
  Base* w;
2607
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2608
2609
12
  int rv = SSL_set_max_send_fragment(
2610
      w->ssl_.get(),
2611
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2612
6
  args.GetReturnValue().Set(rv);
2613
}
2614
#endif  // SSL_set_max_send_fragment
2615
2616
2617
template <class Base>
2618
871
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2619
  Base* w;
2620
1336
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2621
2622
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2623
  // peer certificate is questionable but it's compatible with what was
2624
  // here before.
2625
  long x509_verify_error =  // NOLINT(runtime/int)
2626
871
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2627
871
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_.get())) {
2628
863
    X509_free(peer_cert);
2629
863
    x509_verify_error = SSL_get_verify_result(w->ssl_.get());
2630
  } else {
2631
8
    const SSL_CIPHER* curr_cipher = SSL_get_current_cipher(w->ssl_.get());
2632
8
    const SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2633
    // Allow no-cert for PSK authentication in TLS1.2 and lower.
2634
    // In TLS1.3 check that session was reused because TLS1.3 PSK
2635
    // looks like session resumption. Is there a better way?
2636

21
    if (SSL_CIPHER_get_auth_nid(curr_cipher) == NID_auth_psk ||
2637
12
        (SSL_SESSION_get_protocol_version(sess) == TLS1_3_VERSION &&
2638
6
         SSL_session_reused(w->ssl_.get())))
2639
14
      return args.GetReturnValue().SetNull();
2640
  }
2641
2642
864
  if (x509_verify_error == X509_V_OK)
2643
916
    return args.GetReturnValue().SetNull();
2644
2645
406
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2646
406
  const char* code = reason;
2647
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2648







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

3
    switch (sign_nid) {
2735
      case EVP_PKEY_RSA:
2736
        sig_with_md = "RSA+";
2737
        break;
2738
2739
      case EVP_PKEY_RSA_PSS:
2740
2
        sig_with_md = "RSA-PSS+";
2741
2
        break;
2742
2743
      case EVP_PKEY_DSA:
2744
        sig_with_md = "DSA+";
2745
        break;
2746
2747
      case EVP_PKEY_EC:
2748
1
        sig_with_md = "ECDSA+";
2749
1
        break;
2750
2751
      case NID_ED25519:
2752
        sig_with_md = "Ed25519+";
2753
        break;
2754
2755
      case NID_ED448:
2756
        sig_with_md = "Ed448+";
2757
        break;
2758
#ifndef OPENSSL_NO_GOST
2759
      case NID_id_GostR3410_2001:
2760
        sig_with_md = "gost2001+";
2761
        break;
2762
2763
      case NID_id_GostR3410_2012_256:
2764
        sig_with_md = "gost2012_256+";
2765
        break;
2766
2767
      case NID_id_GostR3410_2012_512:
2768
        sig_with_md = "gost2012_512+";
2769
        break;
2770
#endif  // !OPENSSL_NO_GOST
2771
      default:
2772
        const char* sn = OBJ_nid2sn(sign_nid);
2773
2774
        if (sn != nullptr) {
2775
          sig_with_md = std::string(sn) + "+";
2776
        } else {
2777
          sig_with_md = "UNDEF+";
2778
        }
2779
        break;
2780
    }
2781
2782
3
    const char* sn_hash = OBJ_nid2sn(hash_nid);
2783
3
    if (sn_hash != nullptr) {
2784
3
      sig_with_md += std::string(sn_hash);
2785
    } else {
2786
      sig_with_md += "UNDEF";
2787
    }
2788
6
    ret_arr[i] = OneByteString(env->isolate(), sig_with_md.c_str());
2789
  }
2790
2791
6
  args.GetReturnValue().Set(
2792
                 Array::New(env->isolate(), ret_arr.out(), ret_arr.length()));
2793
}
2794
2795
template <class Base>
2796
3
void SSLWrap<Base>::ExportKeyingMaterial(
2797
    const FunctionCallbackInfo<Value>& args) {
2798
6
  CHECK(args[0]->IsInt32());
2799
9
  CHECK(args[1]->IsString());
2800
2801
  Base* w;
2802
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2803
3
  Environment* env = w->ssl_env();
2804
2805
9
  uint32_t olen = args[0].As<Uint32>()->Value();
2806
6
  node::Utf8Value label(env->isolate(), args[1]);
2807
2808
6
  AllocatedBuffer out = env->AllocateManaged(olen);
2809
2810
6
  ByteSource key;
2811
2812
3
  int useContext = 0;
2813

12
  if (!args[2]->IsNull() && Buffer::HasInstance(args[2])) {
2814
2
    key = ByteSource::FromBuffer(args[2]);
2815
2816
2
    useContext = 1;
2817
  }
2818
2819
12
  if (SSL_export_keying_material(w->ssl_.get(),
2820
3
                                 reinterpret_cast<unsigned char*>(out.data()),
2821
                                 olen,
2822
3
                                 *label,
2823
                                 label.length(),
2824
                                 reinterpret_cast<const unsigned char*>(
2825
3
                                   key.get()),
2826
                                 key.size(),
2827
                                 useContext) != 1) {
2828
    return ThrowCryptoError(env, ERR_get_error(), "SSL_export_keying_material");
2829
  }
2830
2831
9
  args.GetReturnValue().Set(out.ToBuffer().ToLocalChecked());
2832
}
2833
2834
template <class Base>
2835
547
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2836
  Base* w;
2837
547
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2838
2839
547
  const char* tls_version = SSL_get_version(w->ssl_.get());
2840
1641
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2841
}
2842
2843
2844
template <class Base>
2845
26
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2846
                                      const unsigned char** out,
2847
                                      unsigned char* outlen,
2848
                                      const unsigned char* in,
2849
                                      unsigned int inlen,
2850
                                      void* arg) {
2851
26
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2852
26
  Environment* env = w->env();
2853
52
  HandleScope handle_scope(env->isolate());
2854
26
  Context::Scope context_scope(env->context());
2855
2856
  Local<Value> alpn_buffer =
2857
52
      w->object()->GetPrivate(
2858
          env->context(),
2859
78
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2860
26
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
2861
26
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2862
26
                                     alpn_protos.data(), alpn_protos.length(),
2863
26
                                     in, inlen);
2864
  // According to 3.2. Protocol Selection of RFC7301, fatal
2865
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2866
  // support it yet. See
2867
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2868
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2869
52
                                          : SSL_TLSEXT_ERR_NOACK;
2870
}
2871
2872
2873
template <class Base>
2874
1612
void SSLWrap<Base>::GetALPNNegotiatedProto(
2875
    const FunctionCallbackInfo<Value>& args) {
2876
  Base* w;
2877
1612
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2878
2879
  const unsigned char* alpn_proto;
2880
  unsigned int alpn_proto_len;
2881
2882
1612
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2883
2884
  Local<Value> result;
2885
1612
  if (alpn_proto_len == 0) {
2886
3128
    result = False(args.GetIsolate());
2887

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

8
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
2891
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
2892
4
    result = w->env()->http_1_1_string();
2893
  } else {
2894
12
    result = OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len);
2895
  }
2896
2897
3224
  args.GetReturnValue().Set(result);
2898
}
2899
2900
2901
template <class Base>
2902
200
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2903
  Base* w;
2904
200
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2905
200
  Environment* env = w->env();
2906

400
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2907
    return env->ThrowTypeError("Must give a Buffer as first argument");
2908
2909
200
  if (w->is_client()) {
2910
31
    ArrayBufferViewContents<unsigned char> alpn_protos(args[0]);
2911
62
    int r = SSL_set_alpn_protos(
2912
93
        w->ssl_.get(), alpn_protos.data(), alpn_protos.length());
2913
31
    CHECK_EQ(r, 0);
2914
  } else {
2915
507
    CHECK(
2916
        w->object()->SetPrivate(
2917
            env->context(),
2918
            env->alpn_buffer_private_symbol(),
2919
            args[0]).FromJust());
2920
    // Server should select ALPN protocol from list of advertised by client
2921
169
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2922
                               SelectALPNCallback,
2923
                               nullptr);
2924
  }
2925
}
2926
2927
2928
template <class Base>
2929
8
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2930
8
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2931
8
  Environment* env = w->env();
2932
16
  HandleScope handle_scope(env->isolate());
2933
2934
8
  if (w->is_client()) {
2935
    // Incoming response
2936
    const unsigned char* resp;
2937
4
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2938
    Local<Value> arg;
2939
4
    if (resp == nullptr) {
2940
4
      arg = Null(env->isolate());
2941
    } else {
2942
2
      arg =
2943
4
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2944
          .ToLocalChecked();
2945
    }
2946
2947
4
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2948
2949
    // No async acceptance is possible, so always return 1 to accept the
2950
    // response.  The listener for 'OCSPResponse' event has no control over
2951
    // return value, but it can .destroy() the connection if the response is not
2952
    // acceptable.
2953
4
    return 1;
2954
  } else {
2955
    // Outgoing response
2956
8
    if (w->ocsp_response_.IsEmpty())
2957
2
      return SSL_TLSEXT_ERR_NOACK;
2958
2959
2
    Local<ArrayBufferView> obj = PersistentToLocal::Default(env->isolate(),
2960
2
                                                            w->ocsp_response_);
2961
2
    size_t len = obj->ByteLength();
2962
2963
    // OpenSSL takes control of the pointer after accepting it
2964
2
    unsigned char* data = MallocOpenSSL<unsigned char>(len);
2965
2
    obj->CopyContents(data, len);
2966
2967
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2968
      OPENSSL_free(data);
2969
2
    w->ocsp_response_.Reset();
2970
2971
2
    return SSL_TLSEXT_ERR_OK;
2972
  }
2973
}
2974
2975
2976
template <class Base>
2977
22
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2978
22
  cert_cb_ = cb;
2979
22
  cert_cb_arg_ = arg;
2980
22
}
2981
2982
2983
template <class Base>
2984
870
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2985
870
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2986
2987
870
  if (!w->is_server())
2988
41
    return 1;
2989
2990
829
  if (!w->is_waiting_cert_cb())
2991
807
    return 1;
2992
2993
22
  if (w->cert_cb_running_)
2994
    // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
2995
    // handshake will continue after certcb is done.
2996
    return -1;
2997
2998
22
  Environment* env = w->env();
2999
22
  Local<Context> context = env->context();
3000
44
  HandleScope handle_scope(env->isolate());
3001
  Context::Scope context_scope(context);
3002
22
  w->cert_cb_running_ = true;
3003
3004
22
  Local<Object> info = Object::New(env->isolate());
3005
3006
22
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3007
22
  if (servername == nullptr) {
3008
16
    info->Set(context,
3009
              env->servername_string(),
3010
              String::Empty(env->isolate())).Check();
3011
  } else {
3012
18
    Local<String> str = OneByteString(env->isolate(), servername,
3013
36
                                      strlen(servername));
3014
54
    info->Set(context, env->servername_string(), str).Check();
3015
  }
3016
3017
22
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
3018
88
  info->Set(context, env->ocsp_request_string(),
3019
            Boolean::New(env->isolate(), ocsp)).Check();
3020
3021
44
  Local<Value> argv[] = { info };
3022
22
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
3023
3024
22
  if (!w->cert_cb_running_)
3025
9
    return 1;
3026
3027
  // Performing async action, wait...
3028
13
  return -1;
3029
}
3030
3031
3032
template <class Base>
3033
19
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
3034
  Base* w;
3035
22
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
3036
19
  Environment* env = w->env();
3037
3038

19
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
3039
3040
19
  Local<Object> object = w->object();
3041
76
  Local<Value> ctx = object->Get(env->context(),
3042
19
                                 env->sni_context_string()).ToLocalChecked();
3043
19
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
3044
3045
  // Not an object, probably undefined or null
3046
19
  if (!ctx->IsObject())
3047
8
    goto fire_cb;
3048
3049
11
  if (cons->HasInstance(ctx)) {
3050
9
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
3051
9
    CHECK_NOT_NULL(sc);
3052
    // Store the SNI context for later use.
3053
9
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
3054
3055
    int rv;
3056
3057
    // NOTE: reference count is not increased by this API methods
3058
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_.get());
3059
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_.get());
3060
    STACK_OF(X509)* chain;
3061
3062
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_.get(), &chain);
3063
9
    if (rv)
3064
9
      rv = SSL_use_certificate(w->ssl_.get(), x509);
3065
9
    if (rv)
3066
8
      rv = SSL_use_PrivateKey(w->ssl_.get(), pkey);
3067

9
    if (rv && chain != nullptr)
3068
1
      rv = SSL_set1_chain(w->ssl_.get(), chain);
3069
9
    if (rv)
3070
8
      rv = w->SetCACerts(sc);
3071
9
    if (!rv) {
3072
      // Not clear why sometimes we throw error, and sometimes we call
3073
      // onerror(). Both cause .destroy(), but onerror does a bit more.
3074
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
3075
1
      return ThrowCryptoError(env, err, "CertCbDone");
3076
    }
3077
  } else {
3078
    // Failure: incorrect SNI context object
3079
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
3080
2
    w->MakeCallback(env->onerror_string(), 1, &err);
3081
2
    return;
3082
  }
3083
3084
 fire_cb:
3085
  CertCb cb;
3086
  void* arg;
3087
3088
16
  cb = w->cert_cb_;
3089
16
  arg = w->cert_cb_arg_;
3090
3091
16
  w->cert_cb_running_ = false;
3092
16
  w->cert_cb_ = nullptr;
3093
16
  w->cert_cb_arg_ = nullptr;
3094
3095
16
  cb(arg);
3096
}
3097
3098
3099
template <class Base>
3100
24248
void SSLWrap<Base>::DestroySSL() {
3101
24248
  if (!ssl_)
3102
12089
    return;
3103
3104
12159
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
3105
12159
  ssl_.reset();
3106
}
3107
3108
3109
template <class Base>
3110
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
3111
8
  int err = SSL_set1_verify_cert_store(ssl_.get(),
3112
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
3113
8
  if (err != 1)
3114
    return err;
3115
3116
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
3117
8
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
3118
3119
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
3120
8
  SSL_set_client_CA_list(ssl_.get(), list);
3121
8
  return 1;
3122
}
3123
3124
template <class Base>
3125
void SSLWrap<Base>::MemoryInfo(MemoryTracker* tracker) const {
3126
  tracker->TrackField("ocsp_response", ocsp_response_);
3127
  tracker->TrackField("sni_context", sni_context_);
3128
}
3129
3130
1921
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
3131
  // From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
3132
  //
3133
  //   If VerifyCallback returns 1, the verification process is continued. If
3134
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
3135
  //   terminated with respect to verification failures and the connection will
3136
  //   be established. The calling process can however retrieve the error code
3137
  //   of the last verification error using SSL_get_verify_result(3) or by
3138
  //   maintaining its own error storage managed by VerifyCallback.
3139
  //
3140
  // Since we cannot perform I/O quickly enough with X509_STORE_CTX_ APIs in
3141
  // this callback, we ignore all preverify_ok errors and let the handshake
3142
  // continue. It is imperative that the user use Connection::VerifyError after
3143
  // the 'secure' callback has been made.
3144
1921
  return 1;
3145
}
3146
3147
3356
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
3148
3356
  const int mode = EVP_CIPHER_mode(cipher);
3149
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
3150
  // but its mode is 0 which doesn't indicate
3151
6665
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
3152
6074
         mode == EVP_CIPH_CCM_MODE ||
3153

7453
         mode == EVP_CIPH_GCM_MODE ||
3154
4688
         IS_OCB_MODE(mode);
3155
}
3156
3157
1456
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
3158
1456
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
3159
1456
  return IsSupportedAuthenticatedMode(cipher);
3160
}
3161
3162
enum class ParseKeyResult {
3163
  kParseKeyOk,
3164
  kParseKeyNotRecognized,
3165
  kParseKeyNeedPassphrase,
3166
  kParseKeyFailed
3167
};
3168
3169
2918
static ParseKeyResult TryParsePublicKey(
3170
    EVPKeyPointer* pkey,
3171
    const BIOPointer& bp,
3172
    const char* name,
3173
    // NOLINTNEXTLINE(runtime/int)
3174
    const std::function<EVP_PKEY*(const unsigned char** p, long l)>& parse) {
3175
  unsigned char* der_data;
3176
  long der_len;  // NOLINT(runtime/int)
3177
3178
  // This skips surrounding data and decodes PEM to DER.
3179
  {
3180
3790
    MarkPopErrorOnReturn mark_pop_error_on_return;
3181
2918
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
3182
                           bp.get(), nullptr, nullptr) != 1)
3183
2046
      return ParseKeyResult::kParseKeyNotRecognized;
3184
  }
3185
3186
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
3187
872
  const unsigned char* p = der_data;
3188
872
  pkey->reset(parse(&p, der_len));
3189
872
  OPENSSL_clear_free(der_data, der_len);
3190
3191
872
  return *pkey ? ParseKeyResult::kParseKeyOk :
3192
1744
                 ParseKeyResult::kParseKeyFailed;
3193
}
3194
3195
1059
static ParseKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
3196
                                        const char* key_pem,
3197
                                        int key_pem_len) {
3198
2118
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
3199
1059
  if (!bp)
3200
    return ParseKeyResult::kParseKeyFailed;
3201
3202
  ParseKeyResult ret;
3203
3204
  // Try parsing as a SubjectPublicKeyInfo first.
3205
2118
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
3206
122
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3207
        return d2i_PUBKEY(nullptr, p, l);
3208
1181
      });
3209
1059
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
3210
122
    return ret;
3211
3212
  // Maybe it is PKCS#1.
3213
937
  CHECK(BIO_reset(bp.get()));
3214
1874
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
3215
15
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3216
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
3217
952
      });
3218
937
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
3219
15
    return ret;
3220
3221
  // X.509 fallback.
3222
922
  CHECK(BIO_reset(bp.get()));
3223
1844
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
3224
735
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
3225
1470
        X509Pointer x509(d2i_X509(nullptr, p, l));
3226
1470
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
3227
922
      });
3228
}
3229
3230
22
static ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
3231
                                     const PublicKeyEncodingConfig& config,
3232
                                     const char* key,
3233
                                     size_t key_len) {
3234
22
  if (config.format_ == kKeyFormatPEM) {
3235
    return ParsePublicKeyPEM(pkey, key, key_len);
3236
  } else {
3237
22
    CHECK_EQ(config.format_, kKeyFormatDER);
3238
3239
22
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3240
44
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3241
22
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
3242
    } else {
3243
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
3244
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
3245
    }
3246
3247
22
    return *pkey ? ParseKeyResult::kParseKeyOk :
3248
44
                   ParseKeyResult::kParseKeyFailed;
3249
  }
3250
}
3251
3252
47
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
3253
                                               BIO* bio,
3254
                                               PKFormatType format) {
3255
  BUF_MEM* bptr;
3256
47
  BIO_get_mem_ptr(bio, &bptr);
3257
47
  if (format == kKeyFormatPEM) {
3258
    // PEM is an ASCII format, so we will return it as a string.
3259
111
    return String::NewFromUtf8(env->isolate(), bptr->data,
3260
                               NewStringType::kNormal,
3261
111
                               bptr->length).ToLocalChecked();
3262
  } else {
3263
10
    CHECK_EQ(format, kKeyFormatDER);
3264
    // DER is binary, return it as a buffer.
3265
20
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
3266
  }
3267
}
3268
3269
26
static bool WritePublicKeyInner(EVP_PKEY* pkey,
3270
                                const BIOPointer& bio,
3271
                                const PublicKeyEncodingConfig& config) {
3272
52
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3273
    // PKCS#1 is only valid for RSA keys.
3274
9
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
3275
18
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
3276
9
    if (config.format_ == kKeyFormatPEM) {
3277
      // Encode PKCS#1 as PEM.
3278
3
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
3279
    } else {
3280
      // Encode PKCS#1 as DER.
3281
6
      CHECK_EQ(config.format_, kKeyFormatDER);
3282
6
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
3283
    }
3284
  } else {
3285
34
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
3286
17
    if (config.format_ == kKeyFormatPEM) {
3287
      // Encode SPKI as PEM.
3288
17
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
3289
    } else {
3290
      // Encode SPKI as DER.
3291
      CHECK_EQ(config.format_, kKeyFormatDER);
3292
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
3293
    }
3294
  }
3295
}
3296
3297
26
static MaybeLocal<Value> WritePublicKey(Environment* env,
3298
                                        EVP_PKEY* pkey,
3299
                                        const PublicKeyEncodingConfig& config) {
3300
52
  BIOPointer bio(BIO_new(BIO_s_mem()));
3301
26
  CHECK(bio);
3302
3303
26
  if (!WritePublicKeyInner(pkey, bio, config)) {
3304
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
3305
    return MaybeLocal<Value>();
3306
  }
3307
52
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
3308
}
3309
3310
58
static bool IsASN1Sequence(const unsigned char* data, size_t size,
3311
                           size_t* data_offset, size_t* data_size) {
3312

58
  if (size < 2 || data[0] != 0x30)
3313
    return false;
3314
3315
58
  if (data[1] & 0x80) {
3316
    // Long form.
3317
38
    size_t n_bytes = data[1] & ~0x80;
3318

38
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
3319
      return false;
3320
38
    size_t length = 0;
3321
114
    for (size_t i = 0; i < n_bytes; i++)
3322
76
      length = (length << 8) | data[i + 2];
3323
38
    *data_offset = 2 + n_bytes;
3324
38
    *data_size = std::min(size - 2 - n_bytes, length);
3325
  } else {
3326
    // Short form.
3327
20
    *data_offset = 2;
3328
20
    *data_size = std::min<size_t>(size - 2, data[1]);
3329
  }
3330
3331
58
  return true;
3332
}
3333
3334
32
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
3335
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
3336
  size_t offset, len;
3337
32
  if (!IsASN1Sequence(data, size, &offset, &len))
3338
    return false;
3339
3340
  // An RSAPrivateKey sequence always starts with a single-byte integer whose
3341
  // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
3342
  // (which is the product of two primes and therefore at least 4), so we can
3343
  // decide the type of the structure based on the first three bytes of the
3344
  // sequence.
3345
64
  return len >= 3 &&
3346
64
         data[offset] == 2 &&
3347

74
         data[offset + 1] == 1 &&
3348
42
         !(data[offset + 2] & 0xfe);
3349
}
3350
3351
26
static bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
3352
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
3353
  size_t offset, len;
3354
26
  if (!IsASN1Sequence(data, size, &offset, &len))
3355
    return false;
3356
3357
  // A PrivateKeyInfo sequence always starts with an integer whereas an
3358
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
3359

52
  return len >= 1 &&
3360
52
         data[offset] != 2;
3361
}
3362
3363
394
static ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
3364
                                      const PrivateKeyEncodingConfig& config,
3365
                                      const char* key,
3366
                                      size_t key_len) {
3367
  // OpenSSL needs a non-const pointer, that's why the const_cast is required.
3368
394
  char* const passphrase = const_cast<char*>(config.passphrase_.get());
3369
3370
394
  if (config.format_ == kKeyFormatPEM) {
3371
713
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
3372
357
    if (!bio)
3373
1
      return ParseKeyResult::kParseKeyFailed;
3374
3375
356
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
3376
                                        nullptr,
3377
                                        PasswordCallback,
3378
356
                                        passphrase));
3379
  } else {
3380
37
    CHECK_EQ(config.format_, kKeyFormatDER);
3381
3382
74
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3383
11
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3384
11
      pkey->reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
3385
52
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
3386
52
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
3387
26
      if (!bio)
3388
        return ParseKeyResult::kParseKeyFailed;
3389
3390
26
      if (IsEncryptedPrivateKeyInfo(
3391
              reinterpret_cast<const unsigned char*>(key), key_len)) {
3392
17
        pkey->reset(d2i_PKCS8PrivateKey_bio(bio.get(),
3393
                                            nullptr,
3394
                                            PasswordCallback,
3395
17
                                            passphrase));
3396
      } else {
3397
18
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
3398
9
        if (p8inf)
3399
9
          pkey->reset(EVP_PKCS82PKEY(p8inf.get()));
3400
      }
3401
    } else {
3402
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
3403
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
3404
      pkey->reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
3405
    }
3406
  }
3407
3408
  // OpenSSL can fail to parse the key but still return a non-null pointer.
3409
393
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
3410
393
  if (err != 0)
3411
18
    pkey->reset();
3412
3413
393
  if (*pkey)
3414
375
    return ParseKeyResult::kParseKeyOk;
3415

28
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
3416
10
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
3417
9
    if (config.passphrase_.get() == nullptr)
3418
8
      return ParseKeyResult::kParseKeyNeedPassphrase;
3419
  }
3420
10
  return ParseKeyResult::kParseKeyFailed;
3421
}
3422
3423
2490
ByteSource::ByteSource(ByteSource&& other)
3424
2490
      : data_(other.data_),
3425
2490
        allocated_data_(other.allocated_data_),
3426
4980
        size_(other.size_) {
3427
2490
  other.allocated_data_ = nullptr;
3428
2490
}
3429
3430
15232
ByteSource::~ByteSource() {
3431
7616
  OPENSSL_clear_free(allocated_data_, size_);
3432
7616
}
3433
3434
108
ByteSource& ByteSource::operator=(ByteSource&& other) {
3435
108
  if (&other != this) {
3436
108
    OPENSSL_clear_free(allocated_data_, size_);
3437
108
    data_ = other.data_;
3438
108
    allocated_data_ = other.allocated_data_;
3439
108
    other.allocated_data_ = nullptr;
3440
108
    size_ = other.size_;
3441
  }
3442
108
  return *this;
3443
}
3444
3445
4313
const char* ByteSource::get() const {
3446
4313
  return data_;
3447
}
3448
3449
3906
size_t ByteSource::size() const {
3450
3906
  return size_;
3451
}
3452
3453