GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_crypto.cc Lines: 3266 3618 90.3 %
Date: 2019-10-06 22:30:00 Branches: 1768 2746 64.4 %

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

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









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

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

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



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

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

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


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

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

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

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

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

307
  static std::vector<X509*> root_certs_vector;
984

307
  static Mutex root_certs_vector_mutex;
985
307
  Mutex::ScopedLock lock(root_certs_vector_mutex);
986
987
307
  if (root_certs_vector.empty()) {
988
41860
    for (size_t i = 0; i < arraysize(root_certs); i++) {
989
      X509* x509 =
990
41561
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
991
41561
                                              strlen(root_certs[i])).get(),
992
                            nullptr,   // no re-use of X509 structure
993
                            NoPasswordCallback,
994
83122
                            nullptr);  // no callback data
995
996
      // Parse errors from the built-in roots are fatal.
997
41561
      CHECK_NOT_NULL(x509);
998
999
41561
      root_certs_vector.push_back(x509);
1000
    }
1001
  }
1002
1003
307
  X509_STORE* store = X509_STORE_new();
1004
307
  if (*system_cert_path != '\0') {
1005
    X509_STORE_load_locations(store, system_cert_path, nullptr);
1006
  }
1007
307
  if (per_process::cli_options->ssl_openssl_cert_store) {
1008
    X509_STORE_set_default_paths(store);
1009
  } else {
1010
42980
    for (X509* cert : root_certs_vector) {
1011
42673
      X509_up_ref(cert);
1012
42673
      X509_STORE_add_cert(store, cert);
1013
    }
1014
  }
1015
1016
307
  return store;
1017
}
1018
1019
1020
1
void GetRootCertificates(const FunctionCallbackInfo<Value>& args) {
1021
1
  Environment* env = Environment::GetCurrent(args);
1022
1
  Local<Array> result = Array::New(env->isolate(), arraysize(root_certs));
1023
1024
140
  for (size_t i = 0; i < arraysize(root_certs); i++) {
1025
    Local<Value> value;
1026
278
    if (!String::NewFromOneByte(env->isolate(),
1027
139
                                reinterpret_cast<const uint8_t*>(root_certs[i]),
1028

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

695
        !result->Set(env->context(), i, value).FromMaybe(false)) {
1030
1
      return;
1031
    }
1032
  }
1033
1034
2
  args.GetReturnValue().Set(result);
1035
}
1036
1037
1038
555
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
1039
555
  Environment* env = Environment::GetCurrent(args);
1040
1041
  SecureContext* sc;
1042
555
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1043
  ClearErrorOnReturn clear_error_on_return;
1044
1045
555
  if (args.Length() != 1) {
1046
    return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory");
1047
  }
1048
1049
1110
  BIOPointer bio(LoadBIO(env, args[0]));
1050
555
  if (!bio)
1051
    return;
1052
1053
555
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1054
  while (X509* x509 = PEM_read_bio_X509_AUX(
1055
1449
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1056
894
    if (cert_store == root_cert_store) {
1057
2
      cert_store = NewRootCertStore();
1058
2
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1059
    }
1060
894
    X509_STORE_add_cert(cert_store, x509);
1061
894
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
1062
894
    X509_free(x509);
1063
555
  }
1064
}
1065
1066
1067
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
1068
2
  Environment* env = Environment::GetCurrent(args);
1069
1070
  SecureContext* sc;
1071
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1072
1073
2
  if (args.Length() != 1) {
1074
    return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory");
1075
  }
1076
1077
  ClearErrorOnReturn clear_error_on_return;
1078
1079
3
  BIOPointer bio(LoadBIO(env, args[0]));
1080
2
  if (!bio)
1081
    return;
1082
1083
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
1084
3
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
1085
1086
2
  if (!crl)
1087
1
    return env->ThrowError("Failed to parse CRL");
1088
1089
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1090
1
  if (cert_store == root_cert_store) {
1091
    cert_store = NewRootCertStore();
1092
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1093
  }
1094
1095
1
  X509_STORE_add_crl(cert_store, crl.get());
1096
  X509_STORE_set_flags(cert_store,
1097
2
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1098
}
1099
1100
1101
3
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1102
    X509_STORE* store,
1103
    const char* file) {
1104
3
  ERR_clear_error();
1105
3
  MarkPopErrorOnReturn mark_pop_error_on_return;
1106
1107
6
  BIOPointer bio(BIO_new_file(file, "r"));
1108
3
  if (!bio)
1109
1
    return ERR_get_error();
1110
1111
  while (X509* x509 =
1112
4
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1113
2
    X509_STORE_add_cert(store, x509);
1114
2
    X509_free(x509);
1115
  }
1116
1117
2
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1118
  // Ignore error if its EOF/no start line found.
1119

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

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

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

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


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

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

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

3309
    if (RAND_bytes(iv, 16) <= 0 ||
1691
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1692

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

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

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

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

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

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


491
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
2282
3
    goto done;
2283
2284
  // Short result requested.
2285


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

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


12
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2598
2599
  Base* w;
2600
6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2601
2602
12
  int rv = SSL_set_max_send_fragment(
2603
      w->ssl_.get(),
2604
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2605
6
  args.GetReturnValue().Set(rv);
2606
}
2607
#endif  // SSL_set_max_send_fragment
2608
2609
2610
template <class Base>
2611
939
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2612
  Base* w;
2613
1453
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2614
2615
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2616
  // peer certificate is questionable but it's compatible with what was
2617
  // here before.
2618
  long x509_verify_error =  // NOLINT(runtime/int)
2619
939
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2620
939
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_.get())) {
2621
938
    X509_free(peer_cert);
2622
938
    x509_verify_error = SSL_get_verify_result(w->ssl_.get());
2623
  }
2624
2625
939
  if (x509_verify_error == X509_V_OK)
2626
1028
    return args.GetReturnValue().SetNull();
2627
2628
425
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2629
425
  const char* code = reason;
2630
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2631







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


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

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

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

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

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

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

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

56
  if (size < 2 || data[0] != 0x30)
3260
    return false;
3261
3262
56
  if (data[1] & 0x80) {
3263
    // Long form.
3264
36
    size_t n_bytes = data[1] & ~0x80;
3265

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

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

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

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