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: 297 3155 9.4 %
Date: 2019-02-01 22:03:38 Branches: 32 2275 1.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.h"
24
#include "node_buffer.h"
25
#include "node_constants.h"
26
#include "node_crypto_bio.h"
27
#include "node_crypto_clienthello-inl.h"
28
#include "node_crypto_groups.h"
29
#include "node_errors.h"
30
#include "node_mutex.h"
31
#include "node_process.h"
32
#include "tls_wrap.h"  // TLSWrap
33
34
#include "async_wrap-inl.h"
35
#include "env-inl.h"
36
#include "string_bytes.h"
37
#include "util-inl.h"
38
#include "v8.h"
39
40
#include <errno.h>
41
#include <limits.h>  // INT_MAX
42
#include <string.h>
43
44
#include <algorithm>
45
#include <memory>
46
#include <utility>
47
#include <vector>
48
49
static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
50
                                 | ASN1_STRFLGS_UTF8_CONVERT
51
                                 | XN_FLAG_SEP_MULTILINE
52
                                 | XN_FLAG_FN_SN;
53
54
namespace node {
55
namespace Buffer {
56
// OpenSSL uses `unsigned char*` for raw data, make this easier for us.
57
v8::MaybeLocal<v8::Object> New(Environment* env, unsigned char* udata,
58
                               size_t length) {
59
  char* data = reinterpret_cast<char*>(udata);
60
  return Buffer::New(env, data, length);
61
}
62
}  // namespace Buffer
63
64
namespace crypto {
65
66
using node::THROW_ERR_TLS_INVALID_PROTOCOL_METHOD;
67
68
using v8::Array;
69
using v8::Boolean;
70
using v8::ConstructorBehavior;
71
using v8::Context;
72
using v8::DontDelete;
73
using v8::EscapableHandleScope;
74
using v8::Exception;
75
using v8::External;
76
using v8::Function;
77
using v8::FunctionCallback;
78
using v8::FunctionCallbackInfo;
79
using v8::FunctionTemplate;
80
using v8::HandleScope;
81
using v8::Int32;
82
using v8::Integer;
83
using v8::Isolate;
84
using v8::Just;
85
using v8::Local;
86
using v8::Maybe;
87
using v8::MaybeLocal;
88
using v8::NewStringType;
89
using v8::Nothing;
90
using v8::Null;
91
using v8::Object;
92
using v8::PropertyAttribute;
93
using v8::ReadOnly;
94
using v8::SideEffectType;
95
using v8::Signature;
96
using v8::String;
97
using v8::Uint32;
98
using v8::Undefined;
99
using v8::Value;
100
101
#ifdef OPENSSL_NO_OCB
102
# define IS_OCB_MODE(mode) false
103
#else
104
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
105
#endif
106
107
struct StackOfX509Deleter {
108
  void operator()(STACK_OF(X509)* p) const { sk_X509_pop_free(p, X509_free); }
109
};
110
using StackOfX509 = std::unique_ptr<STACK_OF(X509), StackOfX509Deleter>;
111
112
struct StackOfXASN1Deleter {
113
  void operator()(STACK_OF(ASN1_OBJECT)* p) const {
114
    sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
115
  }
116
};
117
using StackOfASN1 = std::unique_ptr<STACK_OF(ASN1_OBJECT), StackOfXASN1Deleter>;
118
119
// OPENSSL_free is a macro, so we need a wrapper function.
120
struct OpenSSLBufferDeleter {
121
  void operator()(char* pointer) const { OPENSSL_free(pointer); }
122
};
123
using OpenSSLBuffer = std::unique_ptr<char[], OpenSSLBufferDeleter>;
124
125
static const char* const root_certs[] = {
126
#include "node_root_certs.h"  // NOLINT(build/include_order)
127
};
128
129
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
130
131
static X509_STORE* root_cert_store;
132
133
static bool extra_root_certs_loaded = false;
134
135
// Just to generate static methods
136
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
137
                                           Local<FunctionTemplate> t);
138
template void SSLWrap<TLSWrap>::ConfigureSecureContext(SecureContext* sc);
139
template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc);
140
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
141
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
142
    SSL* s,
143
    const unsigned char* key,
144
    int len,
145
    int* copy);
146
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
147
                                                  SSL_SESSION* sess);
148
template void SSLWrap<TLSWrap>::OnClientHello(
149
    void* arg,
150
    const ClientHelloParser::ClientHello& hello);
151
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
152
template void SSLWrap<TLSWrap>::DestroySSL();
153
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
154
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
155
template int SSLWrap<TLSWrap>::SelectALPNCallback(
156
    SSL* s,
157
    const unsigned char** out,
158
    unsigned char* outlen,
159
    const unsigned char* in,
160
    unsigned int inlen,
161
    void* arg);
162
163
164
static int PasswordCallback(char* buf, int size, int rwflag, void* u) {
165
  if (u) {
166
    size_t buflen = static_cast<size_t>(size);
167
    size_t len = strlen(static_cast<const char*>(u));
168
    len = len > buflen ? buflen : len;
169
    memcpy(buf, u, len);
170
    return len;
171
  }
172
173
  return 0;
174
}
175
176
// Loads OpenSSL engine by engine id and returns it. The loaded engine
177
// gets a reference so remember the corresponding call to ENGINE_free.
178
// In case of error the appropriate js exception is scheduled
179
// and nullptr is returned.
180
#ifndef OPENSSL_NO_ENGINE
181
static ENGINE* LoadEngineById(const char* engine_id, char (*errmsg)[1024]) {
182
  MarkPopErrorOnReturn mark_pop_error_on_return;
183
184
  ENGINE* engine = ENGINE_by_id(engine_id);
185
186
  if (engine == nullptr) {
187
    // Engine not found, try loading dynamically.
188
    engine = ENGINE_by_id("dynamic");
189
    if (engine != nullptr) {
190
      if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", engine_id, 0) ||
191
          !ENGINE_ctrl_cmd_string(engine, "LOAD", nullptr, 0)) {
192
        ENGINE_free(engine);
193
        engine = nullptr;
194
      }
195
    }
196
  }
197
198
  if (engine == nullptr) {
199
    int err = ERR_get_error();
200
    if (err != 0) {
201
      ERR_error_string_n(err, *errmsg, sizeof(*errmsg));
202
    } else {
203
      snprintf(*errmsg, sizeof(*errmsg),
204
               "Engine \"%s\" was not found", engine_id);
205
    }
206
  }
207
208
  return engine;
209
}
210
#endif  // !OPENSSL_NO_ENGINE
211
212
// This callback is used to avoid the default passphrase callback in OpenSSL
213
// which will typically prompt for the passphrase. The prompting is designed
214
// for the OpenSSL CLI, but works poorly for Node.js because it involves
215
// synchronous interaction with the controlling terminal, something we never
216
// want, and use this function to avoid it.
217
static int NoPasswordCallback(char* buf, int size, int rwflag, void* u) {
218
  return 0;
219
}
220
221
222
8
struct CryptoErrorVector : public std::vector<std::string> {
223
  inline void Capture() {
224
    clear();
225
    while (auto err = ERR_get_error()) {
226
      char buf[256];
227
      ERR_error_string_n(err, buf, sizeof(buf));
228
      push_back(buf);
229
    }
230
    std::reverse(begin(), end());
231
  }
232
233
  inline Local<Value> ToException(
234
      Environment* env,
235
      Local<String> exception_string = Local<String>()) const {
236
    if (exception_string.IsEmpty()) {
237
      CryptoErrorVector copy(*this);
238
      if (copy.empty()) copy.push_back("no error");  // But possibly a bug...
239
      // Use last element as the error message, everything else goes
240
      // into the .opensslErrorStack property on the exception object.
241
      auto exception_string =
242
          String::NewFromUtf8(env->isolate(), copy.back().data(),
243
                              NewStringType::kNormal, copy.back().size())
244
          .ToLocalChecked();
245
      copy.pop_back();
246
      return copy.ToException(env, exception_string);
247
    }
248
249
    Local<Value> exception_v = Exception::Error(exception_string);
250
    CHECK(!exception_v.IsEmpty());
251
252
    if (!empty()) {
253
      CHECK(exception_v->IsObject());
254
      Local<Object> exception = exception_v.As<Object>();
255
      exception->Set(env->context(),
256
                     env->openssl_error_stack(),
257
                     ToV8Value(env->context(), *this).ToLocalChecked())
258
          .FromJust();
259
    }
260
261
    return exception_v;
262
  }
263
};
264
265
266
void ThrowCryptoError(Environment* env,
267
                      unsigned long err,  // NOLINT(runtime/int)
268
                      const char* message = nullptr) {
269
  char message_buffer[128] = {0};
270
  if (err != 0 || message == nullptr) {
271
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
272
    message = message_buffer;
273
  }
274
  HandleScope scope(env->isolate());
275
  auto exception_string =
276
      String::NewFromUtf8(env->isolate(), message, NewStringType::kNormal)
277
      .ToLocalChecked();
278
  CryptoErrorVector errors;
279
  errors.Capture();
280
  auto exception = errors.ToException(env, exception_string);
281
  env->isolate()->ThrowException(exception);
282
}
283
284
285
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
286
// The entropy pool starts out empty and needs to fill up before the PRNG
287
// can be used securely.  Once the pool is filled, it never dries up again;
288
// its contents is stirred and reused when necessary.
289
//
290
// OpenSSL normally fills the pool automatically but not when someone starts
291
// generating random numbers before the pool is full: in that case OpenSSL
292
// keeps lowering the entropy estimate to thwart attackers trying to guess
293
// the initial state of the PRNG.
294
//
295
// When that happens, we will have to wait until enough entropy is available.
296
// That should normally never take longer than a few milliseconds.
297
//
298
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
299
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
300
// block under normal circumstances.
301
//
302
// The only time when /dev/urandom may conceivably block is right after boot,
303
// when the whole system is still low on entropy.  That's not something we can
304
// do anything about.
305
332
inline void CheckEntropy() {
306
  for (;;) {
307
332
    int status = RAND_status();
308
332
    CHECK_GE(status, 0);  // Cannot fail.
309
332
    if (status != 0)
310
664
      break;
311
312
    // Give up, RAND_poll() not supported.
313
    if (RAND_poll() == 0)
314
      break;
315
  }
316
332
}
317
318
319
328
bool EntropySource(unsigned char* buffer, size_t length) {
320
  // Ensure that OpenSSL's PRNG is properly seeded.
321
328
  CheckEntropy();
322
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
323
  // random. That's okay, it's still better than V8's stock source of entropy,
324
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
325
328
  return RAND_bytes(buffer, length) != -1;
326
}
327
328
329
template <typename T>
330
static T* MallocOpenSSL(size_t count) {
331
  void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
332
  CHECK_IMPLIES(mem == nullptr, count == 0);
333
  return static_cast<T*>(mem);
334
}
335
336
337
9
void SecureContext::Initialize(Environment* env, Local<Object> target) {
338
9
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
339
18
  t->InstanceTemplate()->SetInternalFieldCount(1);
340
  Local<String> secureContextString =
341
9
      FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext");
342
9
  t->SetClassName(secureContextString);
343
344
9
  env->SetProtoMethod(t, "init", Init);
345
9
  env->SetProtoMethod(t, "setKey", SetKey);
346
9
  env->SetProtoMethod(t, "setCert", SetCert);
347
9
  env->SetProtoMethod(t, "addCACert", AddCACert);
348
9
  env->SetProtoMethod(t, "addCRL", AddCRL);
349
9
  env->SetProtoMethod(t, "addRootCerts", AddRootCerts);
350
9
  env->SetProtoMethod(t, "setCiphers", SetCiphers);
351
9
  env->SetProtoMethod(t, "setECDHCurve", SetECDHCurve);
352
9
  env->SetProtoMethod(t, "setDHParam", SetDHParam);
353
9
  env->SetProtoMethod(t, "setOptions", SetOptions);
354
9
  env->SetProtoMethod(t, "setSessionIdContext", SetSessionIdContext);
355
9
  env->SetProtoMethod(t, "setSessionTimeout", SetSessionTimeout);
356
9
  env->SetProtoMethod(t, "close", Close);
357
9
  env->SetProtoMethod(t, "loadPKCS12", LoadPKCS12);
358
#ifndef OPENSSL_NO_ENGINE
359
9
  env->SetProtoMethod(t, "setClientCertEngine", SetClientCertEngine);
360
#endif  // !OPENSSL_NO_ENGINE
361
9
  env->SetProtoMethodNoSideEffect(t, "getTicketKeys", GetTicketKeys);
362
9
  env->SetProtoMethod(t, "setTicketKeys", SetTicketKeys);
363
9
  env->SetProtoMethod(t, "setFreeListLength", SetFreeListLength);
364
9
  env->SetProtoMethod(t, "enableTicketKeyCallback", EnableTicketKeyCallback);
365
9
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate<true>);
366
9
  env->SetProtoMethodNoSideEffect(t, "getIssuer", GetCertificate<false>);
367
368
#define SET_INTEGER_CONSTANTS(name, value)                                     \
369
    t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), name),                        \
370
           Integer::NewFromUnsigned(env->isolate(), value));
371
27
  SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex);
372
27
  SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex);
373
27
  SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex);
374
27
  SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex);
375
27
  SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex);
376
377
#undef SET_INTEGER_CONSTANTS
378
379
  Local<FunctionTemplate> ctx_getter_templ =
380
      FunctionTemplate::New(env->isolate(),
381
                            CtxGetter,
382
                            env->as_external(),
383
18
                            Signature::New(env->isolate(), t));
384
385
386
27
  t->PrototypeTemplate()->SetAccessorProperty(
387
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
388
      ctx_getter_templ,
389
      Local<FunctionTemplate>(),
390
27
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
391
392
  target->Set(env->context(), secureContextString,
393
45
              t->GetFunction(env->context()).ToLocalChecked()).FromJust();
394
9
  env->set_secure_context_constructor_template(t);
395
9
}
396
397
398
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
399
  Environment* env = Environment::GetCurrent(args);
400
  new SecureContext(env, args.This());
401
}
402
403
404
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
405
  SecureContext* sc;
406
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
407
  Environment* env = sc->env();
408
409
  CHECK_EQ(args.Length(), 3);
410
  CHECK(args[1]->IsInt32());
411
  CHECK(args[2]->IsInt32());
412
413
  int min_version = args[1].As<Int32>()->Value();
414
  int max_version = args[2].As<Int32>()->Value();
415
  const SSL_METHOD* method = TLS_method();
416
417
  if (args[0]->IsString()) {
418
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
419
420
    // Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends
421
    // are still accepted.  They are OpenSSL's way of saying that all known
422
    // protocols are supported unless explicitly disabled (which we do below
423
    // for SSLv2 and SSLv3.)
424
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
425
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
426
      return;
427
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
428
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
429
      return;
430
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
431
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
432
      return;
433
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
434
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
435
      return;
436
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
437
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
438
      return;
439
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
440
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
441
      return;
442
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
443
      // noop
444
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
445
      method = TLS_server_method();
446
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
447
      method = TLS_client_method();
448
    } else if (strcmp(*sslmethod, "TLS_method") == 0) {
449
      min_version = 0;
450
      max_version = 0;
451
    } else if (strcmp(*sslmethod, "TLS_server_method") == 0) {
452
      min_version = 0;
453
      max_version = 0;
454
      method = TLS_server_method();
455
    } else if (strcmp(*sslmethod, "TLS_client_method") == 0) {
456
      min_version = 0;
457
      max_version = 0;
458
      method = TLS_client_method();
459
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
460
      min_version = TLS1_VERSION;
461
      max_version = TLS1_VERSION;
462
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
463
      min_version = TLS1_VERSION;
464
      max_version = TLS1_VERSION;
465
      method = TLS_server_method();
466
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
467
      min_version = TLS1_VERSION;
468
      max_version = TLS1_VERSION;
469
      method = TLS_client_method();
470
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
471
      min_version = TLS1_1_VERSION;
472
      max_version = TLS1_1_VERSION;
473
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
474
      min_version = TLS1_1_VERSION;
475
      max_version = TLS1_1_VERSION;
476
      method = TLS_server_method();
477
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
478
      min_version = TLS1_1_VERSION;
479
      max_version = TLS1_1_VERSION;
480
      method = TLS_client_method();
481
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
482
      min_version = TLS1_2_VERSION;
483
      max_version = TLS1_2_VERSION;
484
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
485
      min_version = TLS1_2_VERSION;
486
      max_version = TLS1_2_VERSION;
487
      method = TLS_server_method();
488
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
489
      min_version = TLS1_2_VERSION;
490
      max_version = TLS1_2_VERSION;
491
      method = TLS_client_method();
492
    } else {
493
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "Unknown method");
494
      return;
495
    }
496
  }
497
498
  sc->ctx_.reset(SSL_CTX_new(method));
499
  SSL_CTX_set_app_data(sc->ctx_.get(), sc);
500
501
  // Disable SSLv2 in the case when method == TLS_method() and the
502
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
503
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
504
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
505
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv2);
506
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv3);
507
508
  // Enable automatic cert chaining. This is enabled by default in OpenSSL, but
509
  // disabled by default in BoringSSL. Enable it explicitly to make the
510
  // behavior match when Node is built with BoringSSL.
511
  SSL_CTX_clear_mode(sc->ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
512
513
  // SSL session cache configuration
514
  SSL_CTX_set_session_cache_mode(sc->ctx_.get(),
515
                                 SSL_SESS_CACHE_CLIENT |
516
                                 SSL_SESS_CACHE_SERVER |
517
                                 SSL_SESS_CACHE_NO_INTERNAL |
518
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
519
520
  SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version);
521
522
  if (max_version == 0) {
523
    // Selecting some secureProtocol methods allows the TLS version to be "any
524
    // supported", but we don't support TLSv1.3, even if OpenSSL does.
525
    max_version = TLS1_2_VERSION;
526
  }
527
  SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version);
528
529
  // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was
530
  // exposed in the public API. To retain compatibility, install a callback
531
  // which restores the old algorithm.
532
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
533
      RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 ||
534
      RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) {
535
    return env->ThrowError("Error generating ticket keys");
536
  }
537
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
538
}
539
540
541
// Takes a string or buffer and loads it into a BIO.
542
// Caller responsible for BIO_free_all-ing the returned object.
543
static BIOPointer LoadBIO(Environment* env, Local<Value> v) {
544
  HandleScope scope(env->isolate());
545
546
  if (v->IsString()) {
547
    const node::Utf8Value s(env->isolate(), v);
548
    return NodeBIO::NewFixed(*s, s.length());
549
  }
550
551
  if (Buffer::HasInstance(v)) {
552
    return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
553
  }
554
555
  return nullptr;
556
}
557
558
559
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
560
  Environment* env = Environment::GetCurrent(args);
561
562
  SecureContext* sc;
563
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
564
565
  unsigned int len = args.Length();
566
  if (len < 1) {
567
    return THROW_ERR_MISSING_ARGS(env, "Private key argument is mandatory");
568
  }
569
570
  if (len > 2) {
571
    return env->ThrowError("Only private key and pass phrase are expected");
572
  }
573
574
  if (len == 2) {
575
    if (args[1]->IsUndefined() || args[1]->IsNull())
576
      len = 1;
577
    else
578
      THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase");
579
  }
580
581
  BIOPointer bio(LoadBIO(env, args[0]));
582
  if (!bio)
583
    return;
584
585
  node::Utf8Value passphrase(env->isolate(), args[1]);
586
587
  EVPKeyPointer key(
588
      PEM_read_bio_PrivateKey(bio.get(),
589
                              nullptr,
590
                              PasswordCallback,
591
                              len == 1 ? nullptr : *passphrase));
592
593
  if (!key) {
594
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
595
    if (!err) {
596
      return env->ThrowError("PEM_read_bio_PrivateKey");
597
    }
598
    return ThrowCryptoError(env, err);
599
  }
600
601
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
602
603
  if (!rv) {
604
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
605
    if (!err)
606
      return env->ThrowError("SSL_CTX_use_PrivateKey");
607
    return ThrowCryptoError(env, err);
608
  }
609
}
610
611
612
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
613
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
614
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
615
      X509_STORE_CTX_new());
616
  return store_ctx.get() != nullptr &&
617
         X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
618
         X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1;
619
}
620
621
622
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
623
                                  X509Pointer&& x,
624
                                  STACK_OF(X509)* extra_certs,
625
                                  X509Pointer* cert,
626
                                  X509Pointer* issuer_) {
627
  CHECK(!*issuer_);
628
  CHECK(!*cert);
629
  X509* issuer = nullptr;
630
631
  int ret = SSL_CTX_use_certificate(ctx, x.get());
632
633
  if (ret) {
634
    // If we could set up our certificate, now proceed to
635
    // the CA certificates.
636
    SSL_CTX_clear_extra_chain_certs(ctx);
637
638
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
639
      X509* ca = sk_X509_value(extra_certs, i);
640
641
      // NOTE: Increments reference count on `ca`
642
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
643
        ret = 0;
644
        issuer = nullptr;
645
        break;
646
      }
647
      // Note that we must not free r if it was successfully
648
      // added to the chain (while we must free the main
649
      // certificate, since its reference count is increased
650
      // by SSL_CTX_use_certificate).
651
652
      // Find issuer
653
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
654
        continue;
655
656
      issuer = ca;
657
    }
658
  }
659
660
  // Try getting issuer from a cert store
661
  if (ret) {
662
    if (issuer == nullptr) {
663
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
664
      ret = ret < 0 ? 0 : 1;
665
      // NOTE: get_cert_store doesn't increment reference count,
666
      // no need to free `store`
667
    } else {
668
      // Increment issuer reference count
669
      issuer = X509_dup(issuer);
670
      if (issuer == nullptr) {
671
        ret = 0;
672
      }
673
    }
674
  }
675
676
  issuer_->reset(issuer);
677
678
  if (ret && x != nullptr) {
679
    cert->reset(X509_dup(x.get()));
680
    if (!*cert)
681
      ret = 0;
682
  }
683
  return ret;
684
}
685
686
687
// Read a file that contains our certificate in "PEM" format,
688
// possibly followed by a sequence of CA certificates that should be
689
// sent to the peer in the Certificate message.
690
//
691
// Taken from OpenSSL - edited for style.
692
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
693
                                  BIOPointer&& in,
694
                                  X509Pointer* cert,
695
                                  X509Pointer* issuer) {
696
  // Just to ensure that `ERR_peek_last_error` below will return only errors
697
  // that we are interested in
698
  ERR_clear_error();
699
700
  X509Pointer x(
701
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
702
703
  if (!x)
704
    return 0;
705
706
  unsigned long err = 0;  // NOLINT(runtime/int)
707
708
  StackOfX509 extra_certs(sk_X509_new_null());
709
  if (!extra_certs)
710
    return 0;
711
712
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
713
                                    nullptr,
714
                                    NoPasswordCallback,
715
                                    nullptr)}) {
716
    if (sk_X509_push(extra_certs.get(), extra.get())) {
717
      extra.release();
718
      continue;
719
    }
720
721
    return 0;
722
  }
723
724
  // When the while loop ends, it's usually just EOF.
725
  err = ERR_peek_last_error();
726
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
727
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
728
    ERR_clear_error();
729
  } else {
730
    // some real error
731
    return 0;
732
  }
733
734
  return SSL_CTX_use_certificate_chain(ctx,
735
                                       std::move(x),
736
                                       extra_certs.get(),
737
                                       cert,
738
                                       issuer);
739
}
740
741
742
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
743
  Environment* env = Environment::GetCurrent(args);
744
745
  SecureContext* sc;
746
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
747
748
  if (args.Length() != 1) {
749
    return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory");
750
  }
751
752
  BIOPointer bio(LoadBIO(env, args[0]));
753
  if (!bio)
754
    return;
755
756
  sc->cert_.reset();
757
  sc->issuer_.reset();
758
759
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(),
760
                                         std::move(bio),
761
                                         &sc->cert_,
762
                                         &sc->issuer_);
763
764
  if (!rv) {
765
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
766
    if (!err) {
767
      return env->ThrowError("SSL_CTX_use_certificate_chain");
768
    }
769
    return ThrowCryptoError(env, err);
770
  }
771
}
772
773
774
static X509_STORE* NewRootCertStore() {
775
  static std::vector<X509*> root_certs_vector;
776
  static Mutex root_certs_vector_mutex;
777
  Mutex::ScopedLock lock(root_certs_vector_mutex);
778
779
  if (root_certs_vector.empty()) {
780
    for (size_t i = 0; i < arraysize(root_certs); i++) {
781
      X509* x509 =
782
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
783
                                              strlen(root_certs[i])).get(),
784
                            nullptr,   // no re-use of X509 structure
785
                            NoPasswordCallback,
786
                            nullptr);  // no callback data
787
788
      // Parse errors from the built-in roots are fatal.
789
      CHECK_NOT_NULL(x509);
790
791
      root_certs_vector.push_back(x509);
792
    }
793
  }
794
795
  X509_STORE* store = X509_STORE_new();
796
  if (*system_cert_path != '\0') {
797
    X509_STORE_load_locations(store, system_cert_path, nullptr);
798
  }
799
  if (per_process::cli_options->ssl_openssl_cert_store) {
800
    X509_STORE_set_default_paths(store);
801
  } else {
802
    for (X509* cert : root_certs_vector) {
803
      X509_up_ref(cert);
804
      X509_STORE_add_cert(store, cert);
805
    }
806
  }
807
808
  return store;
809
}
810
811
812
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
813
  Environment* env = Environment::GetCurrent(args);
814
815
  SecureContext* sc;
816
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
817
  ClearErrorOnReturn clear_error_on_return;
818
819
  if (args.Length() != 1) {
820
    return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory");
821
  }
822
823
  BIOPointer bio(LoadBIO(env, args[0]));
824
  if (!bio)
825
    return;
826
827
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
828
  while (X509* x509 = PEM_read_bio_X509_AUX(
829
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
830
    if (cert_store == root_cert_store) {
831
      cert_store = NewRootCertStore();
832
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
833
    }
834
    X509_STORE_add_cert(cert_store, x509);
835
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
836
    X509_free(x509);
837
  }
838
}
839
840
841
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
842
  Environment* env = Environment::GetCurrent(args);
843
844
  SecureContext* sc;
845
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
846
847
  if (args.Length() != 1) {
848
    return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory");
849
  }
850
851
  ClearErrorOnReturn clear_error_on_return;
852
853
  BIOPointer bio(LoadBIO(env, args[0]));
854
  if (!bio)
855
    return;
856
857
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
858
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
859
860
  if (!crl)
861
    return env->ThrowError("Failed to parse CRL");
862
863
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
864
  if (cert_store == root_cert_store) {
865
    cert_store = NewRootCertStore();
866
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
867
  }
868
869
  X509_STORE_add_crl(cert_store, crl.get());
870
  X509_STORE_set_flags(cert_store,
871
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
872
}
873
874
875
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
876
    X509_STORE* store,
877
    const char* file) {
878
  ERR_clear_error();
879
  MarkPopErrorOnReturn mark_pop_error_on_return;
880
881
  BIOPointer bio(BIO_new_file(file, "r"));
882
  if (!bio)
883
    return ERR_get_error();
884
885
  while (X509* x509 =
886
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
887
    X509_STORE_add_cert(store, x509);
888
    X509_free(x509);
889
  }
890
891
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
892
  // Ignore error if its EOF/no start line found.
893
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
894
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
895
    return 0;
896
  }
897
898
  return err;
899
}
900
901
902
void UseExtraCaCerts(const std::string& file) {
903
  ClearErrorOnReturn clear_error_on_return;
904
905
  if (root_cert_store == nullptr) {
906
    root_cert_store = NewRootCertStore();
907
908
    if (!file.empty()) {
909
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
910
                                           root_cert_store,
911
                                           file.c_str());
912
      if (err) {
913
        fprintf(stderr,
914
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
915
                file.c_str(),
916
                ERR_error_string(err, nullptr));
917
      } else {
918
        extra_root_certs_loaded = true;
919
      }
920
    }
921
  }
922
}
923
924
925
static void IsExtraRootCertsFileLoaded(
926
    const FunctionCallbackInfo<Value>& args) {
927
  return args.GetReturnValue().Set(extra_root_certs_loaded);
928
}
929
930
931
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
932
  SecureContext* sc;
933
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
934
  ClearErrorOnReturn clear_error_on_return;
935
936
  if (root_cert_store == nullptr) {
937
    root_cert_store = NewRootCertStore();
938
  }
939
940
  // Increment reference count so global store is not deleted along with CTX.
941
  X509_STORE_up_ref(root_cert_store);
942
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
943
}
944
945
946
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
947
  SecureContext* sc;
948
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
949
  Environment* env = sc->env();
950
  ClearErrorOnReturn clear_error_on_return;
951
952
  if (args.Length() != 1) {
953
    return THROW_ERR_MISSING_ARGS(env, "Ciphers argument is mandatory");
954
  }
955
956
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Ciphers");
957
958
  // Note: set_ciphersuites() is for TLSv1.3 and was introduced in openssl
959
  // 1.1.1, set_cipher_list() is for TLSv1.2 and earlier.
960
  //
961
  // In openssl 1.1.0, set_cipher_list() would error if it resulted in no
962
  // TLSv1.2 (and earlier) cipher suites, and there is no TLSv1.3 support.
963
  //
964
  // In openssl 1.1.1, set_cipher_list() will not error if it results in no
965
  // TLSv1.2 cipher suites if there are any TLSv1.3 cipher suites, which there
966
  // are by default. There will be an error later, during the handshake, but
967
  // that results in an async error event, rather than a sync error thrown,
968
  // which is a semver-major change for the tls API.
969
  //
970
  // Since we don't currently support TLSv1.3, work around this by removing the
971
  // TLSv1.3 cipher suites, so we get backwards compatible synchronous errors.
972
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
973
  if (
974
#ifdef TLS1_3_VERSION
975
      !SSL_CTX_set_ciphersuites(sc->ctx_.get(), "") ||
976
#endif
977
      !SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
978
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
979
    if (!err) {
980
      return env->ThrowError("Failed to set ciphers");
981
    }
982
    return ThrowCryptoError(env, err);
983
  }
984
}
985
986
987
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
988
  SecureContext* sc;
989
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
990
  Environment* env = sc->env();
991
992
  if (args.Length() != 1)
993
    return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory");
994
995
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name");
996
997
  node::Utf8Value curve(env->isolate(), args[0]);
998
999
  if (strcmp(*curve, "auto") == 0)
1000
    return;
1001
1002
  if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve))
1003
    return env->ThrowError("Failed to set ECDH curve");
1004
}
1005
1006
1007
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
1008
  SecureContext* sc;
1009
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
1010
  Environment* env = sc->env();
1011
  ClearErrorOnReturn clear_error_on_return;
1012
1013
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
1014
  // to be specified explicitly
1015
  if (args.Length() != 1)
1016
    return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory");
1017
1018
  DHPointer dh;
1019
  {
1020
    BIOPointer bio(LoadBIO(env, args[0]));
1021
    if (!bio)
1022
      return;
1023
1024
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
1025
  }
1026
1027
  // Invalid dhparam is silently discarded and DHE is no longer used.
1028
  if (!dh)
1029
    return;
1030
1031
  const BIGNUM* p;
1032
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
1033
  const int size = BN_num_bits(p);
1034
  if (size < 1024) {
1035
    return THROW_ERR_INVALID_ARG_VALUE(
1036
        env, "DH parameter is less than 1024 bits");
1037
  } else if (size < 2048) {
1038
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1039
        env->isolate(), "DH parameter is less than 2048 bits"));
1040
  }
1041
1042
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
1043
  int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get());
1044
1045
  if (!r)
1046
    return env->ThrowTypeError("Error setting temp DH parameter");
1047
}
1048
1049
1050
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1051
  SecureContext* sc;
1052
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1053
  int64_t val;
1054
1055
  if (args.Length() != 1 ||
1056
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1057
    return THROW_ERR_INVALID_ARG_TYPE(
1058
        sc->env(), "Options must be an integer value");
1059
  }
1060
1061
  SSL_CTX_set_options(sc->ctx_.get(),
1062
                      static_cast<long>(val));  // NOLINT(runtime/int)
1063
}
1064
1065
1066
void SecureContext::SetSessionIdContext(
1067
    const FunctionCallbackInfo<Value>& args) {
1068
  SecureContext* sc;
1069
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1070
  Environment* env = sc->env();
1071
1072
  if (args.Length() != 1) {
1073
    return THROW_ERR_MISSING_ARGS(
1074
        env, "Session ID context argument is mandatory");
1075
  }
1076
1077
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1078
1079
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1080
  const unsigned char* sid_ctx =
1081
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1082
  unsigned int sid_ctx_len = sessionIdContext.length();
1083
1084
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1085
  if (r == 1)
1086
    return;
1087
1088
  BUF_MEM* mem;
1089
  Local<String> message;
1090
1091
  BIOPointer bio(BIO_new(BIO_s_mem()));
1092
  if (!bio) {
1093
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1094
                                    "SSL_CTX_set_session_id_context error");
1095
  } else {
1096
    ERR_print_errors(bio.get());
1097
    BIO_get_mem_ptr(bio.get(), &mem);
1098
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1099
  }
1100
1101
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1102
}
1103
1104
1105
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1106
  SecureContext* sc;
1107
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1108
1109
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1110
    return THROW_ERR_INVALID_ARG_TYPE(
1111
        sc->env(), "Session timeout must be a 32-bit integer");
1112
  }
1113
1114
  int32_t sessionTimeout = args[0].As<Int32>()->Value();
1115
  SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
1116
}
1117
1118
1119
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1120
  SecureContext* sc;
1121
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1122
  sc->Reset();
1123
}
1124
1125
1126
// Takes .pfx or .p12 and password in string or buffer format
1127
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1128
  Environment* env = Environment::GetCurrent(args);
1129
1130
  std::vector<char> pass;
1131
  bool ret = false;
1132
1133
  SecureContext* sc;
1134
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1135
  ClearErrorOnReturn clear_error_on_return;
1136
1137
  if (args.Length() < 1) {
1138
    return THROW_ERR_MISSING_ARGS(env, "PFX certificate argument is mandatory");
1139
  }
1140
1141
  BIOPointer in(LoadBIO(env, args[0]));
1142
  if (!in)
1143
    return env->ThrowError("Unable to load BIO");
1144
1145
  if (args.Length() >= 2) {
1146
    THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase");
1147
    size_t passlen = Buffer::Length(args[1]);
1148
    pass.resize(passlen + 1);
1149
    memcpy(pass.data(), Buffer::Data(args[1]), passlen);
1150
    pass[passlen] = '\0';
1151
  }
1152
1153
  // Free previous certs
1154
  sc->issuer_.reset();
1155
  sc->cert_.reset();
1156
1157
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1158
1159
  DeleteFnPtr<PKCS12, PKCS12_free> p12;
1160
  EVPKeyPointer pkey;
1161
  X509Pointer cert;
1162
  StackOfX509 extra_certs;
1163
1164
  PKCS12* p12_ptr = nullptr;
1165
  EVP_PKEY* pkey_ptr = nullptr;
1166
  X509* cert_ptr = nullptr;
1167
  STACK_OF(X509)* extra_certs_ptr = nullptr;
1168
  if (d2i_PKCS12_bio(in.get(), &p12_ptr) &&
1169
      (p12.reset(p12_ptr), true) &&  // Move ownership to the smart pointer.
1170
      PKCS12_parse(p12.get(), pass.data(),
1171
                   &pkey_ptr,
1172
                   &cert_ptr,
1173
                   &extra_certs_ptr) &&
1174
      (pkey.reset(pkey_ptr), cert.reset(cert_ptr),
1175
       extra_certs.reset(extra_certs_ptr), true) &&  // Move ownership.
1176
      SSL_CTX_use_certificate_chain(sc->ctx_.get(),
1177
                                    std::move(cert),
1178
                                    extra_certs.get(),
1179
                                    &sc->cert_,
1180
                                    &sc->issuer_) &&
1181
      SSL_CTX_use_PrivateKey(sc->ctx_.get(), pkey.get())) {
1182
    // Add CA certs too
1183
    for (int i = 0; i < sk_X509_num(extra_certs.get()); i++) {
1184
      X509* ca = sk_X509_value(extra_certs.get(), i);
1185
1186
      if (cert_store == root_cert_store) {
1187
        cert_store = NewRootCertStore();
1188
        SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1189
      }
1190
      X509_STORE_add_cert(cert_store, ca);
1191
      SSL_CTX_add_client_CA(sc->ctx_.get(), ca);
1192
    }
1193
    ret = true;
1194
  }
1195
1196
  if (!ret) {
1197
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1198
    const char* str = ERR_reason_error_string(err);
1199
    return env->ThrowError(str);
1200
  }
1201
}
1202
1203
1204
#ifndef OPENSSL_NO_ENGINE
1205
// Helper for the smart pointer.
1206
void ENGINE_free_fn(ENGINE* engine) { ENGINE_free(engine); }
1207
1208
void SecureContext::SetClientCertEngine(
1209
    const FunctionCallbackInfo<Value>& args) {
1210
  Environment* env = Environment::GetCurrent(args);
1211
  CHECK_EQ(args.Length(), 1);
1212
  CHECK(args[0]->IsString());
1213
1214
  SecureContext* sc;
1215
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1216
1217
  MarkPopErrorOnReturn mark_pop_error_on_return;
1218
1219
  // SSL_CTX_set_client_cert_engine does not itself support multiple
1220
  // calls by cleaning up before overwriting the client_cert_engine
1221
  // internal context variable.
1222
  // Instead of trying to fix up this problem we in turn also do not
1223
  // support multiple calls to SetClientCertEngine.
1224
  if (sc->client_cert_engine_provided_) {
1225
    return env->ThrowError(
1226
        "Multiple calls to SetClientCertEngine are not allowed");
1227
  }
1228
1229
  const node::Utf8Value engine_id(env->isolate(), args[0]);
1230
  char errmsg[1024];
1231
  DeleteFnPtr<ENGINE, ENGINE_free_fn> engine(
1232
      LoadEngineById(*engine_id, &errmsg));
1233
1234
  if (!engine)
1235
    return env->ThrowError(errmsg);
1236
1237
  // Note that this takes another reference to `engine`.
1238
  int r = SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get());
1239
  if (r == 0)
1240
    return ThrowCryptoError(env, ERR_get_error());
1241
  sc->client_cert_engine_provided_ = true;
1242
}
1243
#endif  // !OPENSSL_NO_ENGINE
1244
1245
1246
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1247
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1248
1249
  SecureContext* wrap;
1250
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1251
1252
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1253
  memcpy(Buffer::Data(buff), wrap->ticket_key_name_, 16);
1254
  memcpy(Buffer::Data(buff) + 16, wrap->ticket_key_hmac_, 16);
1255
  memcpy(Buffer::Data(buff) + 32, wrap->ticket_key_aes_, 16);
1256
1257
  args.GetReturnValue().Set(buff);
1258
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1259
}
1260
1261
1262
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1263
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1264
  SecureContext* wrap;
1265
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1266
  Environment* env = wrap->env();
1267
1268
  if (args.Length() < 1) {
1269
    return THROW_ERR_MISSING_ARGS(env, "Ticket keys argument is mandatory");
1270
  }
1271
1272
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Ticket keys");
1273
1274
  if (Buffer::Length(args[0]) != 48) {
1275
    return THROW_ERR_INVALID_ARG_VALUE(
1276
        env, "Ticket keys length must be 48 bytes");
1277
  }
1278
1279
  memcpy(wrap->ticket_key_name_, Buffer::Data(args[0]), 16);
1280
  memcpy(wrap->ticket_key_hmac_, Buffer::Data(args[0]) + 16, 16);
1281
  memcpy(wrap->ticket_key_aes_, Buffer::Data(args[0]) + 32, 16);
1282
1283
  args.GetReturnValue().Set(true);
1284
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1285
}
1286
1287
1288
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1289
}
1290
1291
1292
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1293
// the regression test in test/parallel/test-https-resume-after-renew.js.
1294
void SecureContext::EnableTicketKeyCallback(
1295
    const FunctionCallbackInfo<Value>& args) {
1296
  SecureContext* wrap;
1297
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1298
1299
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback);
1300
}
1301
1302
1303
int SecureContext::TicketKeyCallback(SSL* ssl,
1304
                                     unsigned char* name,
1305
                                     unsigned char* iv,
1306
                                     EVP_CIPHER_CTX* ectx,
1307
                                     HMAC_CTX* hctx,
1308
                                     int enc) {
1309
  static const int kTicketPartSize = 16;
1310
1311
  SecureContext* sc = static_cast<SecureContext*>(
1312
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1313
1314
  Environment* env = sc->env();
1315
  HandleScope handle_scope(env->isolate());
1316
  Context::Scope context_scope(env->context());
1317
1318
  Local<Value> argv[] = {
1319
    Buffer::Copy(env,
1320
                 reinterpret_cast<char*>(name),
1321
                 kTicketPartSize).ToLocalChecked(),
1322
    Buffer::Copy(env,
1323
                 reinterpret_cast<char*>(iv),
1324
                 kTicketPartSize).ToLocalChecked(),
1325
    Boolean::New(env->isolate(), enc != 0)
1326
  };
1327
1328
  Local<Value> ret = node::MakeCallback(env->isolate(),
1329
                                        sc->object(),
1330
                                        env->ticketkeycallback_string(),
1331
                                        arraysize(argv),
1332
                                        argv,
1333
                                        {0, 0}).ToLocalChecked();
1334
  Local<Array> arr = ret.As<Array>();
1335
1336
  int r =
1337
      arr->Get(env->context(),
1338
               kTicketKeyReturnIndex).ToLocalChecked()
1339
               ->Int32Value(env->context()).FromJust();
1340
  if (r < 0)
1341
    return r;
1342
1343
  Local<Value> hmac = arr->Get(env->context(),
1344
                               kTicketKeyHMACIndex).ToLocalChecked();
1345
  Local<Value> aes = arr->Get(env->context(),
1346
                              kTicketKeyAESIndex).ToLocalChecked();
1347
  if (Buffer::Length(aes) != kTicketPartSize)
1348
    return -1;
1349
1350
  if (enc) {
1351
    Local<Value> name_val = arr->Get(env->context(),
1352
                                     kTicketKeyNameIndex).ToLocalChecked();
1353
    Local<Value> iv_val = arr->Get(env->context(),
1354
                                   kTicketKeyIVIndex).ToLocalChecked();
1355
1356
    if (Buffer::Length(name_val) != kTicketPartSize ||
1357
        Buffer::Length(iv_val) != kTicketPartSize) {
1358
      return -1;
1359
    }
1360
1361
    memcpy(name, Buffer::Data(name_val), kTicketPartSize);
1362
    memcpy(iv, Buffer::Data(iv_val), kTicketPartSize);
1363
  }
1364
1365
  HMAC_Init_ex(hctx,
1366
               Buffer::Data(hmac),
1367
               Buffer::Length(hmac),
1368
               EVP_sha256(),
1369
               nullptr);
1370
1371
  const unsigned char* aes_key =
1372
      reinterpret_cast<unsigned char*>(Buffer::Data(aes));
1373
  if (enc) {
1374
    EVP_EncryptInit_ex(ectx,
1375
                       EVP_aes_128_cbc(),
1376
                       nullptr,
1377
                       aes_key,
1378
                       iv);
1379
  } else {
1380
    EVP_DecryptInit_ex(ectx,
1381
                       EVP_aes_128_cbc(),
1382
                       nullptr,
1383
                       aes_key,
1384
                       iv);
1385
  }
1386
1387
  return r;
1388
}
1389
1390
1391
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1392
                                               unsigned char* name,
1393
                                               unsigned char* iv,
1394
                                               EVP_CIPHER_CTX* ectx,
1395
                                               HMAC_CTX* hctx,
1396
                                               int enc) {
1397
  SecureContext* sc = static_cast<SecureContext*>(
1398
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1399
1400
  if (enc) {
1401
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1402
    if (RAND_bytes(iv, 16) <= 0 ||
1403
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1404
                           sc->ticket_key_aes_, iv) <= 0 ||
1405
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1406
                     EVP_sha256(), nullptr) <= 0) {
1407
      return -1;
1408
    }
1409
    return 1;
1410
  }
1411
1412
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1413
    // The ticket key name does not match. Discard the ticket.
1414
    return 0;
1415
  }
1416
1417
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1418
                         iv) <= 0 ||
1419
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1420
                   EVP_sha256(), nullptr) <= 0) {
1421
    return -1;
1422
  }
1423
  return 1;
1424
}
1425
1426
1427
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1428
  SecureContext* sc;
1429
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1430
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1431
  info.GetReturnValue().Set(ext);
1432
}
1433
1434
1435
template <bool primary>
1436
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1437
  SecureContext* wrap;
1438
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1439
  Environment* env = wrap->env();
1440
  X509* cert;
1441
1442
  if (primary)
1443
    cert = wrap->cert_.get();
1444
  else
1445
    cert = wrap->issuer_.get();
1446
  if (cert == nullptr)
1447
    return args.GetReturnValue().SetNull();
1448
1449
  int size = i2d_X509(cert, nullptr);
1450
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1451
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1452
      Buffer::Data(buff));
1453
  i2d_X509(cert, &serialized);
1454
1455
  args.GetReturnValue().Set(buff);
1456
}
1457
1458
1459
template <class Base>
1460
1
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1461
1
  HandleScope scope(env->isolate());
1462
1463
1
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
1464
1
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
1465
1
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
1466
1
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
1467
1
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
1468
1
  env->SetProtoMethod(t, "setSession", SetSession);
1469
1
  env->SetProtoMethod(t, "loadSession", LoadSession);
1470
1
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
1471
1
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
1472
1
  env->SetProtoMethodNoSideEffect(t, "getCurrentCipher", GetCurrentCipher);
1473
1
  env->SetProtoMethod(t, "endParser", EndParser);
1474
1
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1475
1
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1476
1
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
1477
1
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1478
1
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1479
1
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1480
1
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
1481
                                  GetEphemeralKeyInfo);
1482
1
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
1483
1484
#ifdef SSL_set_max_send_fragment
1485
1
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1486
#endif  // SSL_set_max_send_fragment
1487
1488
1
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
1489
                                  GetALPNNegotiatedProto);
1490
1
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1491
1
}
1492
1493
1494
template <class Base>
1495
void SSLWrap<Base>::ConfigureSecureContext(SecureContext* sc) {
1496
  // OCSP stapling
1497
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
1498
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
1499
}
1500
1501
1502
template <class Base>
1503
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1504
                                               const unsigned char* key,
1505
                                               int len,
1506
                                               int* copy) {
1507
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1508
1509
  *copy = 0;
1510
  return w->next_sess_.release();
1511
}
1512
1513
1514
template <class Base>
1515
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1516
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1517
  Environment* env = w->ssl_env();
1518
  HandleScope handle_scope(env->isolate());
1519
  Context::Scope context_scope(env->context());
1520
1521
  if (!w->session_callbacks_)
1522
    return 0;
1523
1524
  // Check if session is small enough to be stored
1525
  int size = i2d_SSL_SESSION(sess, nullptr);
1526
  if (size > SecureContext::kMaxSessionSize)
1527
    return 0;
1528
1529
  // Serialize session
1530
  Local<Object> session = Buffer::New(env, size).ToLocalChecked();
1531
  unsigned char* session_data = reinterpret_cast<unsigned char*>(
1532
      Buffer::Data(session));
1533
  memset(session_data, 0, size);
1534
  i2d_SSL_SESSION(sess, &session_data);
1535
1536
  unsigned int session_id_length;
1537
  const unsigned char* session_id_data = SSL_SESSION_get_id(sess,
1538
                                                            &session_id_length);
1539
  Local<Object> session_id = Buffer::Copy(
1540
      env,
1541
      reinterpret_cast<const char*>(session_id_data),
1542
      session_id_length).ToLocalChecked();
1543
  Local<Value> argv[] = { session_id, session };
1544
  // On servers, we pause the handshake until callback of 'newSession', which
1545
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
1546
  if (w->is_server())
1547
    w->awaiting_new_session_ = true;
1548
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1549
1550
  return 0;
1551
}
1552
1553
1554
template <class Base>
1555
void SSLWrap<Base>::OnClientHello(void* arg,
1556
                                  const ClientHelloParser::ClientHello& hello) {
1557
  Base* w = static_cast<Base*>(arg);
1558
  Environment* env = w->ssl_env();
1559
  HandleScope handle_scope(env->isolate());
1560
  Local<Context> context = env->context();
1561
  Context::Scope context_scope(context);
1562
1563
  Local<Object> hello_obj = Object::New(env->isolate());
1564
  Local<Object> buff = Buffer::Copy(
1565
      env,
1566
      reinterpret_cast<const char*>(hello.session_id()),
1567
      hello.session_size()).ToLocalChecked();
1568
  hello_obj->Set(context, env->session_id_string(), buff).FromJust();
1569
  if (hello.servername() == nullptr) {
1570
    hello_obj->Set(context,
1571
                   env->servername_string(),
1572
                   String::Empty(env->isolate())).FromJust();
1573
  } else {
1574
    Local<String> servername = OneByteString(env->isolate(),
1575
                                             hello.servername(),
1576
                                             hello.servername_size());
1577
    hello_obj->Set(context, env->servername_string(), servername).FromJust();
1578
  }
1579
  hello_obj->Set(context,
1580
                 env->tls_ticket_string(),
1581
                 Boolean::New(env->isolate(), hello.has_ticket())).FromJust();
1582
1583
  Local<Value> argv[] = { hello_obj };
1584
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1585
}
1586
1587
1588
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1589
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1590
1591
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1592
    return false;
1593
1594
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
1595
  if (names == nullptr)
1596
    return false;
1597
1598
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1599
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1600
1601
    if (i != 0)
1602
      BIO_write(out, ", ", 2);
1603
1604
    if (gen->type == GEN_DNS) {
1605
      ASN1_IA5STRING* name = gen->d.dNSName;
1606
1607
      BIO_write(out, "DNS:", 4);
1608
      BIO_write(out, name->data, name->length);
1609
    } else {
1610
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1611
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
1612
      if (nval == nullptr)
1613
        return false;
1614
      X509V3_EXT_val_prn(out, nval, 0, 0);
1615
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1616
    }
1617
  }
1618
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1619
1620
  return true;
1621
}
1622
1623
1624
static void AddFingerprintDigest(const unsigned char* md,
1625
                                 unsigned int md_size,
1626
                                 char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) {
1627
  unsigned int i;
1628
  const char hex[] = "0123456789ABCDEF";
1629
1630
  for (i = 0; i < md_size; i++) {
1631
    (*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4];
1632
    (*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)];
1633
    (*fingerprint)[(3*i)+2] = ':';
1634
  }
1635
1636
  if (md_size > 0) {
1637
    (*fingerprint)[(3*(md_size-1))+2] = '\0';
1638
  } else {
1639
    (*fingerprint)[0] = '\0';
1640
  }
1641
}
1642
1643
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1644
  EscapableHandleScope scope(env->isolate());
1645
  Local<Context> context = env->context();
1646
  Local<Object> info = Object::New(env->isolate());
1647
1648
  BIOPointer bio(BIO_new(BIO_s_mem()));
1649
  BUF_MEM* mem;
1650
  if (X509_NAME_print_ex(bio.get(),
1651
                         X509_get_subject_name(cert),
1652
                         0,
1653
                         X509_NAME_FLAGS) > 0) {
1654
    BIO_get_mem_ptr(bio.get(), &mem);
1655
    info->Set(context, env->subject_string(),
1656
              String::NewFromUtf8(env->isolate(), mem->data,
1657
                                  NewStringType::kNormal,
1658
                                  mem->length).ToLocalChecked()).FromJust();
1659
  }
1660
  USE(BIO_reset(bio.get()));
1661
1662
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1663
  if (X509_NAME_print_ex(bio.get(), issuer_name, 0, X509_NAME_FLAGS) > 0) {
1664
    BIO_get_mem_ptr(bio.get(), &mem);
1665
    info->Set(context, env->issuer_string(),
1666
              String::NewFromUtf8(env->isolate(), mem->data,
1667
                                  NewStringType::kNormal,
1668
                                  mem->length).ToLocalChecked()).FromJust();
1669
  }
1670
  USE(BIO_reset(bio.get()));
1671
1672
  int nids[] = { NID_subject_alt_name, NID_info_access };
1673
  Local<String> keys[] = { env->subjectaltname_string(),
1674
                           env->infoaccess_string() };
1675
  CHECK_EQ(arraysize(nids), arraysize(keys));
1676
  for (size_t i = 0; i < arraysize(nids); i++) {
1677
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1678
    if (index < 0)
1679
      continue;
1680
1681
    X509_EXTENSION* ext = X509_get_ext(cert, index);
1682
    CHECK_NOT_NULL(ext);
1683
1684
    if (!SafeX509ExtPrint(bio.get(), ext)) {
1685
      CHECK_EQ(1, X509V3_EXT_print(bio.get(), ext, 0, 0));
1686
    }
1687
1688
    BIO_get_mem_ptr(bio.get(), &mem);
1689
    info->Set(context, keys[i],
1690
              String::NewFromUtf8(env->isolate(), mem->data,
1691
                                  NewStringType::kNormal,
1692
                                  mem->length).ToLocalChecked()).FromJust();
1693
1694
    USE(BIO_reset(bio.get()));
1695
  }
1696
1697
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1698
  RSAPointer rsa;
1699
  ECPointer ec;
1700
  if (pkey) {
1701
    switch (EVP_PKEY_id(pkey.get())) {
1702
      case EVP_PKEY_RSA:
1703
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1704
        break;
1705
      case EVP_PKEY_EC:
1706
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1707
        break;
1708
    }
1709
  }
1710
1711
  if (rsa) {
1712
    const BIGNUM* n;
1713
    const BIGNUM* e;
1714
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1715
    BN_print(bio.get(), n);
1716
    BIO_get_mem_ptr(bio.get(), &mem);
1717
    info->Set(context, env->modulus_string(),
1718
              String::NewFromUtf8(env->isolate(), mem->data,
1719
                                  NewStringType::kNormal,
1720
                                  mem->length).ToLocalChecked()).FromJust();
1721
    USE(BIO_reset(bio.get()));
1722
1723
    int bits = BN_num_bits(n);
1724
    info->Set(context, env->bits_string(),
1725
              Integer::New(env->isolate(), bits)).FromJust();
1726
1727
    uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
1728
    uint32_t lo = static_cast<uint32_t>(exponent_word);
1729
    uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
1730
    if (hi == 0) {
1731
      BIO_printf(bio.get(), "0x%x", lo);
1732
    } else {
1733
      BIO_printf(bio.get(), "0x%x%08x", hi, lo);
1734
    }
1735
    BIO_get_mem_ptr(bio.get(), &mem);
1736
    info->Set(context, env->exponent_string(),
1737
              String::NewFromUtf8(env->isolate(), mem->data,
1738
                                  NewStringType::kNormal,
1739
                                  mem->length).ToLocalChecked()).FromJust();
1740
    USE(BIO_reset(bio.get()));
1741
1742
    int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
1743
    CHECK_GE(size, 0);
1744
    Local<Object> pubbuff = Buffer::New(env, size).ToLocalChecked();
1745
    unsigned char* pubserialized =
1746
        reinterpret_cast<unsigned char*>(Buffer::Data(pubbuff));
1747
    i2d_RSA_PUBKEY(rsa.get(), &pubserialized);
1748
    info->Set(env->context(), env->pubkey_string(), pubbuff).FromJust();
1749
  } else if (ec) {
1750
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1751
    if (group != nullptr) {
1752
      int bits = EC_GROUP_order_bits(group);
1753
      if (bits > 0) {
1754
        info->Set(context, env->bits_string(),
1755
                  Integer::New(env->isolate(), bits)).FromJust();
1756
      }
1757
    }
1758
1759
    unsigned char* pub = nullptr;
1760
    size_t publen = EC_KEY_key2buf(ec.get(), EC_KEY_get_conv_form(ec.get()),
1761
                                   &pub, nullptr);
1762
    if (publen > 0) {
1763
      Local<Object> buf = Buffer::New(env, pub, publen).ToLocalChecked();
1764
      // Ownership of pub pointer accepted by Buffer.
1765
      pub = nullptr;
1766
      info->Set(context, env->pubkey_string(), buf).FromJust();
1767
    } else {
1768
      CHECK_NULL(pub);
1769
    }
1770
1771
    const int nid = EC_GROUP_get_curve_name(group);
1772
    if (nid != 0) {
1773
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1774
1775
      if (const char* sn = OBJ_nid2sn(nid)) {
1776
        info->Set(context, env->asn1curve_string(),
1777
                  OneByteString(env->isolate(), sn)).FromJust();
1778
      }
1779
1780
      if (const char* nist = EC_curve_nid2nist(nid)) {
1781
        info->Set(context, env->nistcurve_string(),
1782
                  OneByteString(env->isolate(), nist)).FromJust();
1783
      }
1784
    } else {
1785
      // Unnamed curves can be described by their mathematical properties,
1786
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
1787
    }
1788
  }
1789
1790
  pkey.reset();
1791
  rsa.reset();
1792
  ec.reset();
1793
1794
  ASN1_TIME_print(bio.get(), X509_get_notBefore(cert));
1795
  BIO_get_mem_ptr(bio.get(), &mem);
1796
  info->Set(context, env->valid_from_string(),
1797
            String::NewFromUtf8(env->isolate(), mem->data,
1798
                                NewStringType::kNormal,
1799
                                mem->length).ToLocalChecked()).FromJust();
1800
  USE(BIO_reset(bio.get()));
1801
1802
  ASN1_TIME_print(bio.get(), X509_get_notAfter(cert));
1803
  BIO_get_mem_ptr(bio.get(), &mem);
1804
  info->Set(context, env->valid_to_string(),
1805
            String::NewFromUtf8(env->isolate(), mem->data,
1806
                                NewStringType::kNormal,
1807
                                mem->length).ToLocalChecked()).FromJust();
1808
  bio.reset();
1809
1810
  unsigned char md[EVP_MAX_MD_SIZE];
1811
  unsigned int md_size;
1812
  char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
1813
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1814
      AddFingerprintDigest(md, md_size, &fingerprint);
1815
      info->Set(context, env->fingerprint_string(),
1816
                OneByteString(env->isolate(), fingerprint)).FromJust();
1817
  }
1818
  if (X509_digest(cert, EVP_sha256(), md, &md_size)) {
1819
      AddFingerprintDigest(md, md_size, &fingerprint);
1820
      info->Set(context, env->fingerprint256_string(),
1821
                OneByteString(env->isolate(), fingerprint)).FromJust();
1822
  }
1823
1824
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
1825
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
1826
  if (eku) {
1827
    Local<Array> ext_key_usage = Array::New(env->isolate());
1828
    char buf[256];
1829
1830
    int j = 0;
1831
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku.get()); i++) {
1832
      if (OBJ_obj2txt(buf,
1833
                      sizeof(buf),
1834
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
1835
        ext_key_usage->Set(context,
1836
                           j++,
1837
                           OneByteString(env->isolate(), buf)).FromJust();
1838
      }
1839
    }
1840
1841
    eku.reset();
1842
    info->Set(context, env->ext_key_usage_string(), ext_key_usage).FromJust();
1843
  }
1844
1845
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1846
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
1847
    if (bn) {
1848
      OpenSSLBuffer buf(BN_bn2hex(bn.get()));
1849
      if (buf) {
1850
        info->Set(context, env->serial_number_string(),
1851
                  OneByteString(env->isolate(), buf.get())).FromJust();
1852
      }
1853
    }
1854
  }
1855
1856
  // Raw DER certificate
1857
  int size = i2d_X509(cert, nullptr);
1858
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1859
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1860
      Buffer::Data(buff));
1861
  i2d_X509(cert, &serialized);
1862
  info->Set(context, env->raw_string(), buff).FromJust();
1863
1864
  return scope.Escape(info);
1865
}
1866
1867
1868
static Local<Object> AddIssuerChainToObject(X509Pointer* cert,
1869
                                            Local<Object> object,
1870
                                            StackOfX509&& peer_certs,
1871
                                            Environment* const env) {
1872
  Local<Context> context = env->isolate()->GetCurrentContext();
1873
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
1874
  for (;;) {
1875
    int i;
1876
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
1877
      X509* ca = sk_X509_value(peer_certs.get(), i);
1878
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
1879
        continue;
1880
1881
      Local<Object> ca_info = X509ToObject(env, ca);
1882
      object->Set(context, env->issuercert_string(), ca_info).FromJust();
1883
      object = ca_info;
1884
1885
      // NOTE: Intentionally freeing cert that is not used anymore.
1886
      // Delete cert and continue aggregating issuers.
1887
      cert->reset(sk_X509_delete(peer_certs.get(), i));
1888
      break;
1889
    }
1890
1891
    // Issuer not found, break out of the loop.
1892
    if (i == sk_X509_num(peer_certs.get()))
1893
      break;
1894
  }
1895
  return object;
1896
}
1897
1898
1899
static StackOfX509 CloneSSLCerts(X509Pointer&& cert,
1900
                                 const STACK_OF(X509)* const ssl_certs) {
1901
  StackOfX509 peer_certs(sk_X509_new(nullptr));
1902
  if (cert)
1903
    sk_X509_push(peer_certs.get(), cert.release());
1904
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
1905
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
1906
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
1907
      return StackOfX509();
1908
    // `cert` is now managed by the stack.
1909
    cert.release();
1910
  }
1911
  return peer_certs;
1912
}
1913
1914
1915
static Local<Object> GetLastIssuedCert(X509Pointer* cert,
1916
                                       const SSLPointer& ssl,
1917
                                       Local<Object> issuer_chain,
1918
                                       Environment* const env) {
1919
  Local<Context> context = env->isolate()->GetCurrentContext();
1920
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
1921
    X509* ca;
1922
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
1923
      break;
1924
1925
    Local<Object> ca_info = X509ToObject(env, ca);
1926
    issuer_chain->Set(context, env->issuercert_string(), ca_info).FromJust();
1927
    issuer_chain = ca_info;
1928
1929
    // Delete previous cert and continue aggregating issuers.
1930
    cert->reset(ca);
1931
  }
1932
  return issuer_chain;
1933
}
1934
1935
1936
template <class Base>
1937
void SSLWrap<Base>::GetPeerCertificate(
1938
    const FunctionCallbackInfo<Value>& args) {
1939
  Base* w;
1940
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1941
  Environment* env = w->ssl_env();
1942
1943
  ClearErrorOnReturn clear_error_on_return;
1944
1945
  Local<Object> result;
1946
  // Used to build the issuer certificate chain.
1947
  Local<Object> issuer_chain;
1948
1949
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1950
  // contains the `peer_certificate`, but on server it doesn't.
1951
  X509Pointer cert(
1952
      w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) : nullptr);
1953
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_.get());
1954
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
1955
    goto done;
1956
1957
  // Short result requested.
1958
  if (args.Length() < 1 || !args[0]->IsTrue()) {
1959
    result = X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
1960
    goto done;
1961
  }
1962
1963
  if (auto peer_certs = CloneSSLCerts(std::move(cert), ssl_certs)) {
1964
    // First and main certificate.
1965
    X509Pointer cert(sk_X509_value(peer_certs.get(), 0));
1966
    CHECK(cert);
1967
    result = X509ToObject(env, cert.release());
1968
1969
    issuer_chain =
1970
        AddIssuerChainToObject(&cert, result, std::move(peer_certs), env);
1971
    issuer_chain = GetLastIssuedCert(&cert, w->ssl_, issuer_chain, env);
1972
    // Last certificate should be self-signed.
1973
    if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK)
1974
      issuer_chain->Set(env->context(),
1975
                        env->issuercert_string(),
1976
                        issuer_chain).FromJust();
1977
  }
1978
1979
 done:
1980
  args.GetReturnValue().Set(result);
1981
}
1982
1983
1984
template <class Base>
1985
void SSLWrap<Base>::GetCertificate(
1986
    const FunctionCallbackInfo<Value>& args) {
1987
  Base* w;
1988
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1989
  Environment* env = w->ssl_env();
1990
1991
  ClearErrorOnReturn clear_error_on_return;
1992
1993
  Local<Object> result;
1994
1995
  X509* cert = SSL_get_certificate(w->ssl_.get());
1996
1997
  if (cert != nullptr)
1998
    result = X509ToObject(env, cert);
1999
2000
  args.GetReturnValue().Set(result);
2001
}
2002
2003
2004
template <class Base>
2005
void SSLWrap<Base>::GetFinished(const FunctionCallbackInfo<Value>& args) {
2006
  Environment* env = Environment::GetCurrent(args);
2007
2008
  Base* w;
2009
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2010
2011
  // We cannot just pass nullptr to SSL_get_finished()
2012
  // because it would further be propagated to memcpy(),
2013
  // where the standard requirements as described in ISO/IEC 9899:2011
2014
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2015
  // Thus, we use a dummy byte.
2016
  char dummy[1];
2017
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
2018
  if (len == 0)
2019
    return;
2020
2021
  char* buf = Malloc(len);
2022
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf, len));
2023
  args.GetReturnValue().Set(Buffer::New(env, buf, len).ToLocalChecked());
2024
}
2025
2026
2027
template <class Base>
2028
void SSLWrap<Base>::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
2029
  Environment* env = Environment::GetCurrent(args);
2030
2031
  Base* w;
2032
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2033
2034
  // We cannot just pass nullptr to SSL_get_peer_finished()
2035
  // because it would further be propagated to memcpy(),
2036
  // where the standard requirements as described in ISO/IEC 9899:2011
2037
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
2038
  // Thus, we use a dummy byte.
2039
  char dummy[1];
2040
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
2041
  if (len == 0)
2042
    return;
2043
2044
  char* buf = Malloc(len);
2045
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf, len));
2046
  args.GetReturnValue().Set(Buffer::New(env, buf, len).ToLocalChecked());
2047
}
2048
2049
2050
template <class Base>
2051
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
2052
  Environment* env = Environment::GetCurrent(args);
2053
2054
  Base* w;
2055
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2056
2057
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2058
  if (sess == nullptr)
2059
    return;
2060
2061
  int slen = i2d_SSL_SESSION(sess, nullptr);
2062
  CHECK_GT(slen, 0);
2063
2064
  char* sbuf = Malloc(slen);
2065
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
2066
  i2d_SSL_SESSION(sess, &p);
2067
  args.GetReturnValue().Set(Buffer::New(env, sbuf, slen).ToLocalChecked());
2068
}
2069
2070
2071
template <class Base>
2072
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
2073
  Environment* env = Environment::GetCurrent(args);
2074
2075
  Base* w;
2076
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2077
2078
  if (args.Length() < 1) {
2079
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
2080
  }
2081
2082
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
2083
  size_t slen = Buffer::Length(args[0]);
2084
  std::vector<char> sbuf(slen);
2085
  if (char* p = Buffer::Data(args[0]))
2086
    sbuf.assign(p, p + slen);
2087
2088
  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf.data());
2089
  SSLSessionPointer sess(d2i_SSL_SESSION(nullptr, &p, slen));
2090
2091
  if (sess == nullptr)
2092
    return;
2093
2094
  int r = SSL_set_session(w->ssl_.get(), sess.get());
2095
2096
  if (!r)
2097
    return env->ThrowError("SSL_set_session error");
2098
}
2099
2100
2101
template <class Base>
2102
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
2103
  Base* w;
2104
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2105
2106
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2107
    ssize_t slen = Buffer::Length(args[0]);
2108
    char* sbuf = Buffer::Data(args[0]);
2109
2110
    const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
2111
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
2112
2113
    // Setup next session and move hello to the BIO buffer
2114
    w->next_sess_.reset(sess);
2115
  }
2116
}
2117
2118
2119
template <class Base>
2120
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2121
  Base* w;
2122
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2123
  bool yes = SSL_session_reused(w->ssl_.get());
2124
  args.GetReturnValue().Set(yes);
2125
}
2126
2127
2128
template <class Base>
2129
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2130
  Base* w;
2131
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2132
  w->hello_parser_.End();
2133
}
2134
2135
2136
template <class Base>
2137
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2138
  Base* w;
2139
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2140
2141
  ClearErrorOnReturn clear_error_on_return;
2142
2143
  // XXX(sam) Return/throw an error, don't discard the SSL error reason.
2144
  bool yes = SSL_renegotiate(w->ssl_.get()) == 1;
2145
  args.GetReturnValue().Set(yes);
2146
}
2147
2148
2149
template <class Base>
2150
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2151
  Base* w;
2152
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2153
  Environment* env = w->ssl_env();
2154
2155
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2156
  if (sess == nullptr)
2157
    return;
2158
2159
  const unsigned char* ticket;
2160
  size_t length;
2161
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2162
2163
  if (ticket == nullptr)
2164
    return;
2165
2166
  Local<Object> buff = Buffer::Copy(
2167
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2168
2169
  args.GetReturnValue().Set(buff);
2170
}
2171
2172
2173
template <class Base>
2174
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2175
  Base* w;
2176
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2177
  w->awaiting_new_session_ = false;
2178
  w->NewSessionDoneCb();
2179
}
2180
2181
2182
template <class Base>
2183
void SSLWrap<Base>::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
2184
  Base* w;
2185
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2186
  Environment* env = w->env();
2187
2188
  if (args.Length() < 1)
2189
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
2190
2191
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
2192
2193
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
2194
}
2195
2196
2197
template <class Base>
2198
void SSLWrap<Base>::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
2199
  Base* w;
2200
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2201
2202
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
2203
}
2204
2205
2206
template <class Base>
2207
void SSLWrap<Base>::GetEphemeralKeyInfo(
2208
    const FunctionCallbackInfo<Value>& args) {
2209
  Base* w;
2210
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2211
  Environment* env = Environment::GetCurrent(args);
2212
  Local<Context> context = env->context();
2213
2214
  CHECK(w->ssl_);
2215
2216
  // tmp key is available on only client
2217
  if (w->is_server())
2218
    return args.GetReturnValue().SetNull();
2219
2220
  Local<Object> info = Object::New(env->isolate());
2221
2222
  EVP_PKEY* key;
2223
2224
  if (SSL_get_server_tmp_key(w->ssl_.get(), &key)) {
2225
    int kid = EVP_PKEY_id(key);
2226
    switch (kid) {
2227
      case EVP_PKEY_DH:
2228
        info->Set(context, env->type_string(),
2229
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH")).FromJust();
2230
        info->Set(context, env->size_string(),
2231
                  Integer::New(env->isolate(), EVP_PKEY_bits(key))).FromJust();
2232
        break;
2233
      case EVP_PKEY_EC:
2234
      // TODO(shigeki) Change this to EVP_PKEY_X25519 and add EVP_PKEY_X448
2235
      // after upgrading to 1.1.1.
2236
      case NID_X25519:
2237
        {
2238
          const char* curve_name;
2239
          if (kid == EVP_PKEY_EC) {
2240
            EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
2241
            int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2242
            curve_name = OBJ_nid2sn(nid);
2243
            EC_KEY_free(ec);
2244
          } else {
2245
            curve_name = OBJ_nid2sn(kid);
2246
          }
2247
          info->Set(context, env->type_string(),
2248
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")).FromJust();
2249
          info->Set(context, env->name_string(),
2250
                    OneByteString(args.GetIsolate(),
2251
                                  curve_name)).FromJust();
2252
          info->Set(context, env->size_string(),
2253
                    Integer::New(env->isolate(),
2254
                                 EVP_PKEY_bits(key))).FromJust();
2255
        }
2256
        break;
2257
    }
2258
    EVP_PKEY_free(key);
2259
  }
2260
2261
  return args.GetReturnValue().Set(info);
2262
}
2263
2264
2265
#ifdef SSL_set_max_send_fragment
2266
template <class Base>
2267
void SSLWrap<Base>::SetMaxSendFragment(
2268
    const FunctionCallbackInfo<Value>& args) {
2269
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2270
2271
  Base* w;
2272
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2273
2274
  int rv = SSL_set_max_send_fragment(
2275
      w->ssl_.get(),
2276
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2277
  args.GetReturnValue().Set(rv);
2278
}
2279
#endif  // SSL_set_max_send_fragment
2280
2281
2282
template <class Base>
2283
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2284
  Base* w;
2285
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2286
2287
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2288
  // peer certificate is questionable but it's compatible with what was
2289
  // here before.
2290
  long x509_verify_error =  // NOLINT(runtime/int)
2291
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2292
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_.get())) {
2293
    X509_free(peer_cert);
2294
    x509_verify_error = SSL_get_verify_result(w->ssl_.get());
2295
  }
2296
2297
  if (x509_verify_error == X509_V_OK)
2298
    return args.GetReturnValue().SetNull();
2299
2300
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2301
  const char* code = reason;
2302
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2303
  switch (x509_verify_error) {
2304
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2305
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2306
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2307
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2308
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2309
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2310
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2311
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2312
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2313
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2314
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2315
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2316
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2317
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2318
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2319
    CASE_X509_ERR(OUT_OF_MEM)
2320
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2321
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2322
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2323
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2324
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2325
    CASE_X509_ERR(CERT_REVOKED)
2326
    CASE_X509_ERR(INVALID_CA)
2327
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2328
    CASE_X509_ERR(INVALID_PURPOSE)
2329
    CASE_X509_ERR(CERT_UNTRUSTED)
2330
    CASE_X509_ERR(CERT_REJECTED)
2331
  }
2332
#undef CASE_X509_ERR
2333
2334
  Isolate* isolate = args.GetIsolate();
2335
  Local<String> reason_string = OneByteString(isolate, reason);
2336
  Local<Value> exception_value = Exception::Error(reason_string);
2337
  Local<Object> exception_object =
2338
    exception_value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2339
  exception_object->Set(w->env()->context(), w->env()->code_string(),
2340
                        OneByteString(isolate, code)).FromJust();
2341
  args.GetReturnValue().Set(exception_object);
2342
}
2343
2344
2345
template <class Base>
2346
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
2347
  Base* w;
2348
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2349
  Environment* env = w->ssl_env();
2350
  Local<Context> context = env->context();
2351
2352
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get());
2353
  if (c == nullptr)
2354
    return;
2355
2356
  Local<Object> info = Object::New(env->isolate());
2357
  const char* cipher_name = SSL_CIPHER_get_name(c);
2358
  info->Set(context, env->name_string(),
2359
            OneByteString(args.GetIsolate(), cipher_name)).FromJust();
2360
  info->Set(context, env->version_string(),
2361
            OneByteString(args.GetIsolate(), "TLSv1/SSLv3")).FromJust();
2362
  args.GetReturnValue().Set(info);
2363
}
2364
2365
2366
template <class Base>
2367
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2368
  Base* w;
2369
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2370
2371
  const char* tls_version = SSL_get_version(w->ssl_.get());
2372
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2373
}
2374
2375
2376
template <class Base>
2377
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2378
                                      const unsigned char** out,
2379
                                      unsigned char* outlen,
2380
                                      const unsigned char* in,
2381
                                      unsigned int inlen,
2382
                                      void* arg) {
2383
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2384
  Environment* env = w->env();
2385
  HandleScope handle_scope(env->isolate());
2386
  Context::Scope context_scope(env->context());
2387
2388
  Local<Value> alpn_buffer =
2389
      w->object()->GetPrivate(
2390
          env->context(),
2391
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2392
  CHECK(Buffer::HasInstance(alpn_buffer));
2393
  const unsigned char* alpn_protos =
2394
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2395
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2396
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2397
                                     alpn_protos, alpn_protos_len, in, inlen);
2398
  // According to 3.2. Protocol Selection of RFC7301, fatal
2399
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2400
  // support it yet. See
2401
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2402
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2403
                                          : SSL_TLSEXT_ERR_NOACK;
2404
}
2405
2406
2407
template <class Base>
2408
void SSLWrap<Base>::GetALPNNegotiatedProto(
2409
    const FunctionCallbackInfo<Value>& args) {
2410
  Base* w;
2411
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2412
2413
  const unsigned char* alpn_proto;
2414
  unsigned int alpn_proto_len;
2415
2416
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2417
2418
  if (!alpn_proto)
2419
    return args.GetReturnValue().Set(false);
2420
2421
  args.GetReturnValue().Set(
2422
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2423
}
2424
2425
2426
template <class Base>
2427
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2428
  Base* w;
2429
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2430
  Environment* env = w->env();
2431
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2432
    return env->ThrowTypeError("Must give a Buffer as first argument");
2433
2434
  if (w->is_client()) {
2435
    const unsigned char* alpn_protos =
2436
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2437
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2438
    int r = SSL_set_alpn_protos(w->ssl_.get(), alpn_protos, alpn_protos_len);
2439
    CHECK_EQ(r, 0);
2440
  } else {
2441
    CHECK(
2442
        w->object()->SetPrivate(
2443
            env->context(),
2444
            env->alpn_buffer_private_symbol(),
2445
            args[0]).FromJust());
2446
    // Server should select ALPN protocol from list of advertised by client
2447
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2448
                               SelectALPNCallback,
2449
                               nullptr);
2450
  }
2451
}
2452
2453
2454
template <class Base>
2455
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2456
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2457
  Environment* env = w->env();
2458
  HandleScope handle_scope(env->isolate());
2459
2460
  if (w->is_client()) {
2461
    // Incoming response
2462
    const unsigned char* resp;
2463
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2464
    Local<Value> arg;
2465
    if (resp == nullptr) {
2466
      arg = Null(env->isolate());
2467
    } else {
2468
      arg =
2469
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2470
          .ToLocalChecked();
2471
    }
2472
2473
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2474
2475
    // Somehow, client is expecting different return value here
2476
    return 1;
2477
  } else {
2478
    // Outgoing response
2479
    if (w->ocsp_response_.IsEmpty())
2480
      return SSL_TLSEXT_ERR_NOACK;
2481
2482
    Local<Object> obj = PersistentToLocal::Default(env->isolate(),
2483
                                                   w->ocsp_response_);
2484
    char* resp = Buffer::Data(obj);
2485
    size_t len = Buffer::Length(obj);
2486
2487
    // OpenSSL takes control of the pointer after accepting it
2488
    unsigned char* data = MallocOpenSSL<unsigned char>(len);
2489
    memcpy(data, resp, len);
2490
2491
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2492
      OPENSSL_free(data);
2493
    w->ocsp_response_.Reset();
2494
2495
    return SSL_TLSEXT_ERR_OK;
2496
  }
2497
}
2498
2499
2500
template <class Base>
2501
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2502
  cert_cb_ = cb;
2503
  cert_cb_arg_ = arg;
2504
}
2505
2506
2507
template <class Base>
2508
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2509
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2510
2511
  if (!w->is_server())
2512
    return 1;
2513
2514
  if (!w->is_waiting_cert_cb())
2515
    return 1;
2516
2517
  if (w->cert_cb_running_)
2518
    return -1;
2519
2520
  Environment* env = w->env();
2521
  Local<Context> context = env->context();
2522
  HandleScope handle_scope(env->isolate());
2523
  Context::Scope context_scope(context);
2524
  w->cert_cb_running_ = true;
2525
2526
  Local<Object> info = Object::New(env->isolate());
2527
2528
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2529
  if (servername == nullptr) {
2530
    info->Set(context,
2531
              env->servername_string(),
2532
              String::Empty(env->isolate())).FromJust();
2533
  } else {
2534
    Local<String> str = OneByteString(env->isolate(), servername,
2535
                                      strlen(servername));
2536
    info->Set(context, env->servername_string(), str).FromJust();
2537
  }
2538
2539
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
2540
  info->Set(context, env->ocsp_request_string(),
2541
            Boolean::New(env->isolate(), ocsp)).FromJust();
2542
2543
  Local<Value> argv[] = { info };
2544
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2545
2546
  if (!w->cert_cb_running_)
2547
    return 1;
2548
2549
  // Performing async action, wait...
2550
  return -1;
2551
}
2552
2553
2554
template <class Base>
2555
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2556
  Base* w;
2557
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2558
  Environment* env = w->env();
2559
2560
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2561
2562
  Local<Object> object = w->object();
2563
  Local<Value> ctx = object->Get(env->context(),
2564
                                 env->sni_context_string()).ToLocalChecked();
2565
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2566
2567
  // Not an object, probably undefined or null
2568
  if (!ctx->IsObject())
2569
    goto fire_cb;
2570
2571
  if (cons->HasInstance(ctx)) {
2572
    SecureContext* sc;
2573
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2574
    w->sni_context_.Reset(env->isolate(), ctx);
2575
2576
    int rv;
2577
2578
    // NOTE: reference count is not increased by this API methods
2579
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_.get());
2580
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_.get());
2581
    STACK_OF(X509)* chain;
2582
2583
    rv = SSL_CTX_get0_chain_certs(sc->ctx_.get(), &chain);
2584
    if (rv)
2585
      rv = SSL_use_certificate(w->ssl_.get(), x509);
2586
    if (rv)
2587
      rv = SSL_use_PrivateKey(w->ssl_.get(), pkey);
2588
    if (rv && chain != nullptr)
2589
      rv = SSL_set1_chain(w->ssl_.get(), chain);
2590
    if (rv)
2591
      rv = w->SetCACerts(sc);
2592
    if (!rv) {
2593
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2594
      if (!err)
2595
        return env->ThrowError("CertCbDone");
2596
      return ThrowCryptoError(env, err);
2597
    }
2598
  } else {
2599
    // Failure: incorrect SNI context object
2600
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2601
    w->MakeCallback(env->onerror_string(), 1, &err);
2602
    return;
2603
  }
2604
2605
 fire_cb:
2606
  CertCb cb;
2607
  void* arg;
2608
2609
  cb = w->cert_cb_;
2610
  arg = w->cert_cb_arg_;
2611
2612
  w->cert_cb_running_ = false;
2613
  w->cert_cb_ = nullptr;
2614
  w->cert_cb_arg_ = nullptr;
2615
2616
  cb(arg);
2617
}
2618
2619
2620
template <class Base>
2621
void SSLWrap<Base>::DestroySSL() {
2622
  if (!ssl_)
2623
    return;
2624
2625
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2626
  ssl_.reset();
2627
}
2628
2629
2630
template <class Base>
2631
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2632
  ConfigureSecureContext(sc);
2633
  CHECK_EQ(SSL_set_SSL_CTX(ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
2634
2635
  SetCACerts(sc);
2636
}
2637
2638
2639
template <class Base>
2640
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2641
  int err = SSL_set1_verify_cert_store(ssl_.get(),
2642
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
2643
  if (err != 1)
2644
    return err;
2645
2646
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2647
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
2648
2649
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2650
  SSL_set_client_CA_list(ssl_.get(), list);
2651
  return 1;
2652
}
2653
2654
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2655
  // Quoting SSL_set_verify(3ssl):
2656
  //
2657
  //   The VerifyCallback function is used to control the behaviour when
2658
  //   the SSL_VERIFY_PEER flag is set. It must be supplied by the
2659
  //   application and receives two arguments: preverify_ok indicates,
2660
  //   whether the verification of the certificate in question was passed
2661
  //   (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to
2662
  //   the complete context used for the certificate chain verification.
2663
  //
2664
  //   The certificate chain is checked starting with the deepest nesting
2665
  //   level (the root CA certificate) and worked upward to the peer's
2666
  //   certificate.  At each level signatures and issuer attributes are
2667
  //   checked.  Whenever a verification error is found, the error number is
2668
  //   stored in x509_ctx and VerifyCallback is called with preverify_ok=0.
2669
  //   By applying X509_CTX_store_* functions VerifyCallback can locate the
2670
  //   certificate in question and perform additional steps (see EXAMPLES).
2671
  //   If no error is found for a certificate, VerifyCallback is called
2672
  //   with preverify_ok=1 before advancing to the next level.
2673
  //
2674
  //   The return value of VerifyCallback controls the strategy of the
2675
  //   further verification process. If VerifyCallback returns 0, the
2676
  //   verification process is immediately stopped with "verification
2677
  //   failed" state. If SSL_VERIFY_PEER is set, a verification failure
2678
  //   alert is sent to the peer and the TLS/SSL handshake is terminated. If
2679
  //   VerifyCallback returns 1, the verification process is continued. If
2680
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
2681
  //   terminated with respect to verification failures and the connection
2682
  //   will be established. The calling process can however retrieve the
2683
  //   error code of the last verification error using
2684
  //   SSL_get_verify_result(3) or by maintaining its own error storage
2685
  //   managed by VerifyCallback.
2686
  //
2687
  //   If no VerifyCallback is specified, the default callback will be
2688
  //   used.  Its return value is identical to preverify_ok, so that any
2689
  //   verification failure will lead to a termination of the TLS/SSL
2690
  //   handshake with an alert message, if SSL_VERIFY_PEER is set.
2691
  //
2692
  // Since we cannot perform I/O quickly enough in this callback, we ignore
2693
  // all preverify_ok errors and let the handshake continue. It is
2694
  // imperative that the user use Connection::VerifyError after the
2695
  // 'secure' callback has been made.
2696
  return 1;
2697
}
2698
2699
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
2700
  const int mode = EVP_CIPHER_mode(cipher);
2701
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
2702
  // but its mode is 0 which doesn't indicate
2703
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
2704
         mode == EVP_CIPH_CCM_MODE ||
2705
         mode == EVP_CIPH_GCM_MODE ||
2706
         IS_OCB_MODE(mode);
2707
}
2708
2709
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
2710
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
2711
  return IsSupportedAuthenticatedMode(cipher);
2712
}
2713
2714
enum class ParsePublicKeyResult {
2715
  kParsePublicOk,
2716
  kParsePublicNotRecognized,
2717
  kParsePublicFailed
2718
};
2719
2720
static ParsePublicKeyResult TryParsePublicKey(
2721
    EVPKeyPointer* pkey,
2722
    const BIOPointer& bp,
2723
    const char* name,
2724
    // NOLINTNEXTLINE(runtime/int)
2725
    std::function<EVP_PKEY*(const unsigned char** p, long l)> parse) {
2726
  unsigned char* der_data;
2727
  long der_len;  // NOLINT(runtime/int)
2728
2729
  // This skips surrounding data and decodes PEM to DER.
2730
  {
2731
    MarkPopErrorOnReturn mark_pop_error_on_return;
2732
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
2733
                           bp.get(), nullptr, nullptr) != 1)
2734
      return ParsePublicKeyResult::kParsePublicNotRecognized;
2735
  }
2736
2737
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
2738
  const unsigned char* p = der_data;
2739
  pkey->reset(parse(&p, der_len));
2740
  OPENSSL_clear_free(der_data, der_len);
2741
2742
  return *pkey ? ParsePublicKeyResult::kParsePublicOk :
2743
                 ParsePublicKeyResult::kParsePublicFailed;
2744
}
2745
2746
static ParsePublicKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
2747
                                              const char* key_pem,
2748
                                              int key_pem_len) {
2749
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
2750
  if (!bp)
2751
    return ParsePublicKeyResult::kParsePublicFailed;
2752
2753
  ParsePublicKeyResult ret;
2754
2755
  // Try parsing as a SubjectPublicKeyInfo first.
2756
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
2757
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2758
        return d2i_PUBKEY(nullptr, p, l);
2759
      });
2760
  if (ret != ParsePublicKeyResult::kParsePublicNotRecognized)
2761
    return ret;
2762
2763
  // Maybe it is PKCS#1.
2764
  CHECK(BIO_reset(bp.get()));
2765
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
2766
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2767
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
2768
      });
2769
  if (ret != ParsePublicKeyResult::kParsePublicNotRecognized)
2770
    return ret;
2771
2772
  // X.509 fallback.
2773
  CHECK(BIO_reset(bp.get()));
2774
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
2775
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2776
        X509Pointer x509(d2i_X509(nullptr, p, l));
2777
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
2778
      });
2779
}
2780
2781
static bool ParsePublicKey(EVPKeyPointer* pkey,
2782
                           const PublicKeyEncodingConfig& config,
2783
                           const char* key,
2784
                           size_t key_len) {
2785
  if (config.format_ == kKeyFormatPEM) {
2786
    ParsePublicKeyResult r =
2787
        ParsePublicKeyPEM(pkey, key, key_len);
2788
    return r == ParsePublicKeyResult::kParsePublicOk;
2789
  } else {
2790
    CHECK_EQ(config.format_, kKeyFormatDER);
2791
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2792
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2793
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2794
      return pkey;
2795
    } else {
2796
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2797
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
2798
      return pkey;
2799
    }
2800
  }
2801
}
2802
2803
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
2804
                                               BIO* bio,
2805
                                               PKFormatType format) {
2806
  BUF_MEM* bptr;
2807
  BIO_get_mem_ptr(bio, &bptr);
2808
  if (format == kKeyFormatPEM) {
2809
    // PEM is an ASCII format, so we will return it as a string.
2810
    return String::NewFromUtf8(env->isolate(), bptr->data,
2811
                               NewStringType::kNormal,
2812
                               bptr->length).ToLocalChecked();
2813
  } else {
2814
    CHECK_EQ(format, kKeyFormatDER);
2815
    // DER is binary, return it as a buffer.
2816
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
2817
  }
2818
}
2819
2820
static bool WritePublicKeyInner(EVP_PKEY* pkey,
2821
                                const BIOPointer& bio,
2822
                                const PublicKeyEncodingConfig& config) {
2823
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2824
    // PKCS#1 is only valid for RSA keys.
2825
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
2826
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
2827
    if (config.format_ == kKeyFormatPEM) {
2828
      // Encode PKCS#1 as PEM.
2829
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
2830
    } else {
2831
      // Encode PKCS#1 as DER.
2832
      CHECK_EQ(config.format_, kKeyFormatDER);
2833
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
2834
    }
2835
  } else {
2836
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2837
    if (config.format_ == kKeyFormatPEM) {
2838
      // Encode SPKI as PEM.
2839
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
2840
    } else {
2841
      // Encode SPKI as DER.
2842
      CHECK_EQ(config.format_, kKeyFormatDER);
2843
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
2844
    }
2845
  }
2846
}
2847
2848
static MaybeLocal<Value> WritePublicKey(Environment* env,
2849
                                        EVP_PKEY* pkey,
2850
                                        const PublicKeyEncodingConfig& config) {
2851
  BIOPointer bio(BIO_new(BIO_s_mem()));
2852
  CHECK(bio);
2853
2854
  if (!WritePublicKeyInner(pkey, bio, config)) {
2855
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
2856
    return MaybeLocal<Value>();
2857
  }
2858
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
2859
}
2860
2861
static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,
2862
                                     const char* key,
2863
                                     size_t key_len) {
2864
  EVPKeyPointer pkey;
2865
2866
  if (config.format_ == kKeyFormatPEM) {
2867
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
2868
    if (!bio)
2869
      return pkey;
2870
2871
    char* pass = const_cast<char*>(config.passphrase_.get());
2872
    pkey.reset(PEM_read_bio_PrivateKey(bio.get(),
2873
                                       nullptr,
2874
                                       PasswordCallback,
2875
                                       pass));
2876
  } else {
2877
    CHECK_EQ(config.format_, kKeyFormatDER);
2878
2879
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2880
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2881
      pkey.reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2882
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
2883
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
2884
      if (!bio)
2885
        return pkey;
2886
      char* pass = const_cast<char*>(config.passphrase_.get());
2887
      pkey.reset(d2i_PKCS8PrivateKey_bio(bio.get(),
2888
                                         nullptr,
2889
                                         PasswordCallback,
2890
                                         pass));
2891
    } else {
2892
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
2893
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2894
      pkey.reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
2895
    }
2896
  }
2897
2898
  // OpenSSL can fail to parse the key but still return a non-null pointer.
2899
  if (ERR_peek_error() != 0)
2900
    pkey.reset();
2901
2902
  return pkey;
2903
}
2904
2905
ByteSource::ByteSource(ByteSource&& other)
2906
      : data_(other.data_),
2907
        allocated_data_(other.allocated_data_),
2908
        size_(other.size_) {
2909
  other.allocated_data_ = nullptr;
2910
}
2911
2912
ByteSource::~ByteSource() {
2913
  OPENSSL_clear_free(allocated_data_, size_);
2914
}
2915
2916
ByteSource& ByteSource::operator=(ByteSource&& other) {
2917
  if (&other != this) {
2918
    OPENSSL_clear_free(allocated_data_, size_);
2919
    data_ = other.data_;
2920
    allocated_data_ = other.allocated_data_;
2921
    other.allocated_data_ = nullptr;
2922
    size_ = other.size_;
2923
  }
2924
  return *this;
2925
}
2926
2927
const char* ByteSource::get() const {
2928
  return data_;
2929
}
2930
2931
size_t ByteSource::size() const {
2932
  return size_;
2933
}
2934
2935
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
2936
                                          Local<Value> value) {
2937
  return Buffer::HasInstance(value) ? FromBuffer(value)
2938
                                    : FromString(env, value.As<String>());
2939
}
2940
2941
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
2942
                                  bool ntc) {
2943
  CHECK(str->IsString());
2944
  size_t size = str->Utf8Length(env->isolate());
2945
  size_t alloc_size = ntc ? size + 1 : size;
2946
  char* data = MallocOpenSSL<char>(alloc_size);
2947
  int opts = String::NO_OPTIONS;
2948
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
2949
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
2950
  return Allocated(data, size);
2951
}
2952
2953
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
2954
  size_t size = Buffer::Length(buffer);
2955
  if (ntc) {
2956
    char* data = MallocOpenSSL<char>(size + 1);
2957
    memcpy(data, Buffer::Data(buffer), size);
2958
    data[size] = 0;
2959
    return Allocated(data, size);
2960
  }
2961
  return Foreign(Buffer::Data(buffer), size);
2962
}
2963
2964
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
2965
                                          Local<Value> value) {
2966
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
2967
                                    : FromString(env, value.As<String>(), true);
2968
}
2969
2970
ByteSource ByteSource::FromSymmetricKeyObject(Local<Value> handle) {
2971
  CHECK(handle->IsObject());
2972
  KeyObject* key = Unwrap<KeyObject>(handle.As<Object>());
2973
  CHECK(key);
2974
  return Foreign(key->GetSymmetricKey(), key->GetSymmetricKeySize());
2975
}
2976
2977
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
2978
      : data_(data),
2979
        allocated_data_(allocated_data),
2980
        size_(size) {}
2981
2982
ByteSource ByteSource::Allocated(char* data, size_t size) {
2983
  return ByteSource(data, data, size);
2984
}
2985
2986
ByteSource ByteSource::Foreign(const char* data, size_t size) {
2987
  return ByteSource(data, nullptr, size);
2988
}
2989
2990
enum KeyEncodingContext {
2991
  kKeyContextInput,
2992
  kKeyContextExport,
2993
  kKeyContextGenerate
2994
};
2995
2996
static void GetKeyFormatAndTypeFromJs(
2997
    AsymmetricKeyEncodingConfig* config,
2998
    const FunctionCallbackInfo<Value>& args,
2999
    unsigned int* offset,
3000
    KeyEncodingContext context) {
3001
  // During key pair generation, it is possible not to specify a key encoding,
3002
  // which will lead to a key object being returned.
3003
  if (args[*offset]->IsUndefined()) {
3004
    CHECK_EQ(context, kKeyContextGenerate);
3005
    CHECK(args[*offset + 1]->IsUndefined());
3006
    config->output_key_object_ = true;
3007
  } else {
3008
    config->output_key_object_ = false;
3009
3010
    CHECK(args[*offset]->IsInt32());
3011
    config->format_ = static_cast<PKFormatType>(
3012
        args[*offset].As<Int32>()->Value());
3013
3014
    if (args[*offset + 1]->IsInt32()) {
3015
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
3016
          args[*offset + 1].As<Int32>()->Value()));
3017
    } else {
3018
      CHECK(context == kKeyContextInput && config->format_ == kKeyFormatPEM);
3019
      CHECK(args[*offset + 1]->IsNullOrUndefined());
3020
      config->type_ = Nothing<PKEncodingType>();
3021
    }
3022
  }
3023
3024
  *offset += 2;
3025
}
3026
3027
static PublicKeyEncodingConfig GetPublicKeyEncodingFromJs(
3028
    const FunctionCallbackInfo<Value>& args,
3029
    unsigned int* offset,
3030
    KeyEncodingContext context) {
3031
  PublicKeyEncodingConfig result;
3032
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3033
  return result;
3034
}
3035
3036
static NonCopyableMaybe<PrivateKeyEncodingConfig> GetPrivateKeyEncodingFromJs(
3037
    const FunctionCallbackInfo<Value>& args,
3038
    unsigned int* offset,
3039
    KeyEncodingContext context) {
3040
  Environment* env = Environment::GetCurrent(args);
3041
3042
  PrivateKeyEncodingConfig result;
3043
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3044
3045
  if (result.output_key_object_) {
3046
    if (context != kKeyContextInput)
3047
      (*offset)++;
3048
  } else {
3049
    bool needs_passphrase = false;
3050
    if (context != kKeyContextInput) {
3051
      if (args[*offset]->IsString()) {
3052
        String::Utf8Value cipher_name(env->isolate(),
3053
                                      args[*offset].As<String>());
3054
        result.cipher_ = EVP_get_cipherbyname(*cipher_name);
3055
        if (result.cipher_ == nullptr) {
3056
          env->ThrowError("Unknown cipher");
3057
          return NonCopyableMaybe<PrivateKeyEncodingConfig>();
3058
        }
3059
        needs_passphrase = true;
3060
      } else {
3061
        CHECK(args[*offset]->IsNullOrUndefined());
3062
        result.cipher_ = nullptr;
3063
      }
3064
      (*offset)++;
3065
    }
3066
3067
    if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3068
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
3069
3070
      result.passphrase_ = ByteSource::NullTerminatedCopy(env, args[*offset]);
3071
    } else {
3072
      CHECK(args[*offset]->IsNullOrUndefined() && !needs_passphrase);
3073
    }
3074
  }
3075
3076
  (*offset)++;
3077
  return NonCopyableMaybe<PrivateKeyEncodingConfig>(std::move(result));
3078
}
3079
3080
static ManagedEVPPKey GetPrivateKeyFromJs(
3081
    const FunctionCallbackInfo<Value>& args,
3082
    unsigned int* offset,
3083
    bool allow_key_object) {
3084
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3085
    Environment* env = Environment::GetCurrent(args);
3086
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3087
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3088
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3089
    if (config.IsEmpty())
3090
      return ManagedEVPPKey();
3091
    EVPKeyPointer pkey =
3092
        ParsePrivateKey(config.Release(), key.get(), key.size());
3093
    if (!pkey)
3094
      ThrowCryptoError(env, ERR_get_error(), "Failed to read private key");
3095
    return ManagedEVPPKey(pkey.release());
3096
  } else {
3097
    CHECK(args[*offset]->IsObject() && allow_key_object);
3098
    KeyObject* key;
3099
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
3100
    CHECK_EQ(key->GetKeyType(), kKeyTypePrivate);
3101
    (*offset) += 4;
3102
    return key->GetAsymmetricKey();
3103
  }
3104
}
3105
3106
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
3107
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
3108
  if (size >= 2 && data[0] == 0x30) {
3109
    size_t offset;
3110
    if (data[1] & 0x80) {
3111
      // Long form.
3112
      size_t n_bytes = data[1] & ~0x80;
3113
      if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
3114
        return false;
3115
      size_t i, length = 0;
3116
      for (i = 0; i < n_bytes; i++)
3117
        length = (length << 8) | data[i + 2];
3118
      offset = 2 + n_bytes;
3119
      size = std::min(size, length + 2);
3120
    } else {
3121
      // Short form.
3122
      offset = 2;
3123
      size = std::min<size_t>(size, data[1] + 2);
3124
    }
3125
3126
    // An RSAPrivateKey sequence always starts with a single-byte integer whose
3127
    // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
3128
    // (which is the product of two primes and therefore at least 4), so we can
3129
    // decide the type of the structure based on the first three bytes of the
3130
    // sequence.
3131
    return size - offset >= 3 &&
3132
           data[offset] == 2 &&
3133
           data[offset + 1] == 1 &&
3134
           !(data[offset + 2] & 0xfe);
3135
  }
3136
3137
  return false;
3138
}
3139
3140
static ManagedEVPPKey GetPublicOrPrivateKeyFromJs(
3141
    const FunctionCallbackInfo<Value>& args,
3142
    unsigned int* offset,
3143
    bool allow_key_object) {
3144
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3145
    Environment* env = Environment::GetCurrent(args);
3146
    ByteSource data = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3147
    NonCopyableMaybe<PrivateKeyEncodingConfig> config_ =
3148
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3149
    if (config_.IsEmpty())
3150
      return ManagedEVPPKey();
3151
    PrivateKeyEncodingConfig config = config_.Release();
3152
    EVPKeyPointer pkey;
3153
    if (config.format_ == kKeyFormatPEM) {
3154
      // For PEM, we can easily determine whether it is a public or private key
3155
      // by looking for the respective PEM tags.
3156
      ParsePublicKeyResult ret = ParsePublicKeyPEM(&pkey, data.get(),
3157
                                                   data.size());
3158
      if (ret == ParsePublicKeyResult::kParsePublicNotRecognized) {
3159
        pkey = ParsePrivateKey(config, data.get(), data.size());
3160
      }
3161
    } else {
3162
      // For DER, the type determines how to parse it. SPKI, PKCS#8 and SEC1 are
3163
      // easy, but PKCS#1 can be a public key or a private key.
3164
      bool is_public;
3165
      switch (config.type_.ToChecked()) {
3166
        case kKeyEncodingPKCS1:
3167
          is_public = !IsRSAPrivateKey(
3168
              reinterpret_cast<const unsigned char*>(data.get()), data.size());
3169
          break;
3170
        case kKeyEncodingSPKI:
3171
          is_public = true;
3172
          break;
3173
        case kKeyEncodingPKCS8:
3174
        case kKeyEncodingSEC1:
3175
          is_public = false;
3176
          break;
3177
        default:
3178
          CHECK(!"Invalid key encoding type");
3179
      }
3180
3181
      if (is_public) {
3182
        ParsePublicKey(&pkey, config, data.get(), data.size());
3183
      } else {
3184
        pkey = ParsePrivateKey(config, data.get(), data.size());
3185
      }
3186
    }
3187
    if (!pkey)
3188
      ThrowCryptoError(env, ERR_get_error(), "Failed to read asymmetric key");
3189
    return ManagedEVPPKey(pkey.release());
3190
  } else {
3191
    CHECK(args[*offset]->IsObject() && allow_key_object);
3192
    KeyObject* key = Unwrap<KeyObject>(args[*offset].As<Object>());
3193
    CHECK(key);
3194
    CHECK_NE(key->GetKeyType(), kKeyTypeSecret);
3195
    (*offset) += 4;
3196
    return key->GetAsymmetricKey();
3197
  }
3198
}
3199
3200
static MaybeLocal<Value> WritePrivateKey(
3201
    Environment* env,
3202
    EVP_PKEY* pkey,
3203
    const PrivateKeyEncodingConfig& config) {
3204
  BIOPointer bio(BIO_new(BIO_s_mem()));
3205
  CHECK(bio);
3206
3207
  bool err;
3208
3209
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
3210
    // PKCS#1 is only permitted for RSA keys.
3211
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
3212
3213
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
3214
    if (config.format_ == kKeyFormatPEM) {
3215
      // Encode PKCS#1 as PEM.
3216
      const char* pass = config.passphrase_.get();
3217
      err = PEM_write_bio_RSAPrivateKey(
3218
                bio.get(), rsa.get(),
3219
                config.cipher_,
3220
                reinterpret_cast<unsigned char*>(const_cast<char*>(pass)),
3221
                config.passphrase_.size(),
3222
                nullptr, nullptr) != 1;
3223
    } else {
3224
      // Encode PKCS#1 as DER. This does not permit encryption.
3225
      CHECK_EQ(config.format_, kKeyFormatDER);
3226
      CHECK_NULL(config.cipher_);
3227
      err = i2d_RSAPrivateKey_bio(bio.get(), rsa.get()) != 1;
3228
    }
3229
  } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
3230
    if (config.format_ == kKeyFormatPEM) {
3231
      // Encode PKCS#8 as PEM.
3232
      err = PEM_write_bio_PKCS8PrivateKey(
3233
                bio.get(), pkey,
3234
                config.cipher_,
3235
                const_cast<char*>(config.passphrase_.get()),
3236
                config.passphrase_.size(),
3237
                nullptr, nullptr) != 1;
3238
    } else {
3239
      // Encode PKCS#8 as DER.
3240
      CHECK_EQ(config.format_, kKeyFormatDER);
3241
      err = i2d_PKCS8PrivateKey_bio(
3242
                bio.get(), pkey,
3243
                config.cipher_,
3244
                const_cast<char*>(config.passphrase_.get()),
3245
                config.passphrase_.size(),
3246
                nullptr, nullptr) != 1;
3247
    }
3248
  } else {
3249
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
3250
3251
    // SEC1 is only permitted for EC keys.
3252
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_EC);
3253
3254
    ECKeyPointer ec_key(EVP_PKEY_get1_EC_KEY(pkey));
3255
    if (config.format_ == kKeyFormatPEM) {
3256
      // Encode SEC1 as PEM.
3257
      const char* pass = config.passphrase_.get();
3258
      err = PEM_write_bio_ECPrivateKey(
3259
                bio.get(), ec_key.get(),
3260
                config.cipher_,
3261
                reinterpret_cast<unsigned char*>(const_cast<char*>(pass)),
3262
                config.passphrase_.size(),
3263
                nullptr, nullptr) != 1;
3264
    } else {
3265
      // Encode SEC1 as DER. This does not permit encryption.
3266
      CHECK_EQ(config.format_, kKeyFormatDER);
3267
      CHECK_NULL(config.cipher_);
3268
      err = i2d_ECPrivateKey_bio(bio.get(), ec_key.get()) != 1;
3269
    }
3270
  }
3271
3272
  if (err) {
3273
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode private key");
3274
    return MaybeLocal<Value>();
3275
  }
3276
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
3277
}
3278
3279
ManagedEVPPKey::ManagedEVPPKey() : pkey_(nullptr) {}
3280
3281
ManagedEVPPKey::ManagedEVPPKey(EVP_PKEY* pkey) : pkey_(pkey) {}
3282
3283
ManagedEVPPKey::ManagedEVPPKey(const ManagedEVPPKey& key) : pkey_(nullptr) {
3284
  *this = key;
3285
}
3286
3287
ManagedEVPPKey::ManagedEVPPKey(ManagedEVPPKey&& key) {
3288
  *this = key;
3289
}
3290
3291
ManagedEVPPKey::~ManagedEVPPKey() {
3292
  EVP_PKEY_free(pkey_);
3293
}
3294
3295
ManagedEVPPKey& ManagedEVPPKey::operator=(const ManagedEVPPKey& key) {
3296
  EVP_PKEY_free(pkey_);
3297
  pkey_ = key.pkey_;
3298
  EVP_PKEY_up_ref(pkey_);
3299
  return *this;
3300
}
3301
3302
ManagedEVPPKey& ManagedEVPPKey::operator=(ManagedEVPPKey&& key) {
3303
  EVP_PKEY_free(pkey_);
3304
  pkey_ = key.pkey_;
3305
  key.pkey_ = nullptr;
3306
  return *this;
3307
}
3308
3309
ManagedEVPPKey::operator bool() const {
3310
  return pkey_ != nullptr;
3311
}
3312
3313
EVP_PKEY* ManagedEVPPKey::get() const {
3314
  return pkey_;
3315
}
3316
3317
9
Local<Function> KeyObject::Initialize(Environment* env, Local<Object> target) {
3318
9
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3319
18
  t->InstanceTemplate()->SetInternalFieldCount(1);
3320
3321
9
  env->SetProtoMethod(t, "init", Init);
3322
  env->SetProtoMethodNoSideEffect(t, "getSymmetricKeySize",
3323
9
                                  GetSymmetricKeySize);
3324
  env->SetProtoMethodNoSideEffect(t, "getAsymmetricKeyType",
3325
9
                                  GetAsymmetricKeyType);
3326
9
  env->SetProtoMethod(t, "export", Export);
3327
3328
27
  auto function = t->GetFunction(env->context()).ToLocalChecked();
3329
  target->Set(env->context(),
3330
              FIXED_ONE_BYTE_STRING(env->isolate(), "KeyObject"),
3331
36
              function).FromJust();
3332
3333
9
  return function;
3334
}
3335
3336
MaybeLocal<Object> KeyObject::Create(Environment* env,
3337
                                     KeyType key_type,
3338
                                     const ManagedEVPPKey& pkey) {
3339
  CHECK_NE(key_type, kKeyTypeSecret);
3340
  Local<Value> type = Integer::New(env->isolate(), key_type);
3341
  Local<Object> obj;
3342
  if (!env->crypto_key_object_constructor()
3343
           ->NewInstance(env->context(), 1, &type)
3344
           .ToLocal(&obj)) {
3345
    return MaybeLocal<Object>();
3346
  }
3347
3348
  KeyObject* key = Unwrap<KeyObject>(obj);
3349
  CHECK(key);
3350
  if (key_type == kKeyTypePublic)
3351
    key->InitPublic(pkey);
3352
  else
3353
    key->InitPrivate(pkey);
3354
  return obj;
3355
}
3356
3357
ManagedEVPPKey KeyObject::GetAsymmetricKey() const {
3358
  CHECK_NE(key_type_, kKeyTypeSecret);
3359
  return this->asymmetric_key_;
3360
}
3361
3362
const char* KeyObject::GetSymmetricKey() const {
3363
  CHECK_EQ(key_type_, kKeyTypeSecret);
3364
  return this->symmetric_key_.get();
3365
}
3366
3367
size_t KeyObject::GetSymmetricKeySize() const {
3368
  CHECK_EQ(key_type_, kKeyTypeSecret);
3369
  return this->symmetric_key_len_;
3370
}
3371
3372
void KeyObject::New(const FunctionCallbackInfo<Value>& args) {
3373
  CHECK(args.IsConstructCall());
3374
  CHECK(args[0]->IsInt32());
3375
  KeyType key_type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
3376
  Environment* env = Environment::GetCurrent(args);
3377
  new KeyObject(env, args.This(), key_type);
3378
}
3379
3380
KeyType KeyObject::GetKeyType() const {
3381
  return this->key_type_;
3382
}
3383
3384
void KeyObject::Init(const FunctionCallbackInfo<Value>& args) {
3385
  KeyObject* key;
3386
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3387
3388
  unsigned int offset;
3389
  ManagedEVPPKey pkey;
3390
3391
  switch (key->key_type_) {
3392
  case kKeyTypeSecret:
3393
    CHECK_EQ(args.Length(), 1);
3394
    key->InitSecret(Buffer::Data(args[0]), Buffer::Length(args[0]));
3395
    break;
3396
  case kKeyTypePublic:
3397
    CHECK_EQ(args.Length(), 3);
3398
3399
    offset = 0;
3400
    pkey = GetPublicOrPrivateKeyFromJs(args, &offset, false);
3401
    if (!pkey)
3402
      return;
3403
    key->InitPublic(pkey);
3404
    break;
3405
  case kKeyTypePrivate:
3406
    CHECK_EQ(args.Length(), 4);
3407
3408
    offset = 0;
3409
    pkey = GetPrivateKeyFromJs(args, &offset, false);
3410
    if (!pkey)
3411
      return;
3412
    key->InitPrivate(pkey);
3413
    break;
3414
  default:
3415
    CHECK(false);
3416
  }
3417
}
3418
3419
void KeyObject::InitSecret(const char* key, size_t key_len) {
3420
  CHECK_EQ(this->key_type_, kKeyTypeSecret);
3421
3422
  char* mem = MallocOpenSSL<char>(key_len);
3423
  memcpy(mem, key, key_len);
3424
  this->symmetric_key_ = std::unique_ptr<char, std::function<void(char*)>>(mem,
3425
      [key_len](char* p) {
3426
        OPENSSL_clear_free(p, key_len);
3427
      });
3428
  this->symmetric_key_len_ = key_len;
3429
}
3430
3431
void KeyObject::InitPublic(const ManagedEVPPKey& pkey) {
3432
  CHECK_EQ(this->key_type_, kKeyTypePublic);
3433
  CHECK(pkey);
3434
  this->asymmetric_key_ = pkey;
3435
}
3436
3437
void KeyObject::InitPrivate(const ManagedEVPPKey& pkey) {
3438
  CHECK_EQ(this->key_type_, kKeyTypePrivate);
3439
  CHECK(pkey);
3440
  this->asymmetric_key_ = pkey;
3441
}
3442
3443
Local<String> KeyObject::GetAsymmetricKeyType() const {
3444
  CHECK_NE(this->key_type_, kKeyTypeSecret);
3445
  switch (EVP_PKEY_id(this->asymmetric_key_.get())) {
3446
  case EVP_PKEY_RSA:
3447
    return env()->crypto_rsa_string();
3448
  case EVP_PKEY_DSA:
3449
    return env()->crypto_dsa_string();
3450
  case EVP_PKEY_EC:
3451
    return env()->crypto_ec_string();
3452
  default:
3453
    CHECK(false);
3454
  }
3455
}
3456
3457
void KeyObject::GetAsymmetricKeyType(const FunctionCallbackInfo<Value>& args) {
3458
  KeyObject* key;
3459
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3460
3461
  args.GetReturnValue().Set(key->GetAsymmetricKeyType());
3462
}
3463
3464
void KeyObject::GetSymmetricKeySize(const FunctionCallbackInfo<Value>& args) {
3465
  KeyObject* key;
3466
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3467
  args.GetReturnValue().Set(static_cast<uint32_t>(key->GetSymmetricKeySize()));
3468
}
3469
3470
void KeyObject::Export(const v8::FunctionCallbackInfo<v8::Value>& args) {
3471
  KeyObject* key;
3472
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3473
3474
  MaybeLocal<Value> result;
3475
  if (key->key_type_ == kKeyTypeSecret) {
3476
    result = key->ExportSecretKey();
3477
  } else if (key->key_type_ == kKeyTypePublic) {
3478
    unsigned int offset = 0;
3479
    PublicKeyEncodingConfig config =
3480
        GetPublicKeyEncodingFromJs(args, &offset, kKeyContextExport);
3481
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
3482
    result = key->ExportPublicKey(config);
3483
  } else {
3484
    CHECK_EQ(key->key_type_, kKeyTypePrivate);
3485
    unsigned int offset = 0;
3486
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3487
        GetPrivateKeyEncodingFromJs(args, &offset, kKeyContextExport);
3488
    if (config.IsEmpty())
3489
      return;
3490
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
3491
    result = key->ExportPrivateKey(config.Release());
3492
  }
3493
3494
  if (!result.IsEmpty())
3495
    args.GetReturnValue().Set(result.ToLocalChecked());
3496
}
3497
3498
Local<Value> KeyObject::ExportSecretKey() const {
3499
  return Buffer::Copy(env(), symmetric_key_.get(), symmetric_key_len_)
3500
      .ToLocalChecked();
3501
}
3502
3503
MaybeLocal<Value> KeyObject::ExportPublicKey(
3504
    const PublicKeyEncodingConfig& config) const {
3505
  return WritePublicKey(env(), asymmetric_key_.get(), config);
3506
}
3507
3508
MaybeLocal<Value> KeyObject::ExportPrivateKey(
3509
    const PrivateKeyEncodingConfig& config) const {
3510
  return WritePrivateKey(env(), asymmetric_key_.get(), config);
3511
}
3512
3513
3514
9
void CipherBase::Initialize(Environment* env, Local<Object> target) {
3515
9
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3516
3517
18
  t->InstanceTemplate()->SetInternalFieldCount(1);
3518
3519
9
  env->SetProtoMethod(t, "init", Init);
3520
9
  env->SetProtoMethod(t, "initiv", InitIv);
3521
9
  env->SetProtoMethod(t, "update", Update);
3522
9
  env->SetProtoMethod(t, "final", Final);
3523
9
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
3524
9
  env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag);
3525
9
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
3526
9
  env->SetProtoMethod(t, "setAAD", SetAAD);
3527
3528
  target->Set(env->context(),
3529
              FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
3530
54
              t->GetFunction(env->context()).ToLocalChecked()).FromJust();
3531
9
}
3532
3533
3534
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
3535
  CHECK(args.IsConstructCall());
3536
  CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher;
3537
  Environment* env = Environment::GetCurrent(args);
3538
  new CipherBase(env, args.This(), kind);
3539
}
3540
3541
void CipherBase::CommonInit(const char* cipher_type,
3542
                            const EVP_CIPHER* cipher,
3543
                            const unsigned char* key,
3544
                            int key_len,
3545
                            const unsigned char* iv,
3546
                            int iv_len,
3547
                            unsigned int auth_tag_len) {
3548
  CHECK(!ctx_);
3549
  ctx_.reset(EVP_CIPHER_CTX_new());
3550
3551
  const int mode = EVP_CIPHER_mode(cipher);
3552
  if (mode == EVP_CIPH_WRAP_MODE)
3553
    EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
3554
3555
  const bool encrypt = (kind_ == kCipher);
3556
  if (1 != EVP_CipherInit_ex(ctx_.get(), cipher, nullptr,
3557
                             nullptr, nullptr, encrypt)) {
3558
    return ThrowCryptoError(env(), ERR_get_error(),
3559
                            "Failed to initialize cipher");
3560
  }
3561
3562
  if (IsSupportedAuthenticatedMode(cipher)) {
3563
    CHECK_GE(iv_len, 0);
3564
    if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len))
3565
      return;
3566
  }
3567
3568
  if (!EVP_CIPHER_CTX_set_key_length(ctx_.get(), key_len)) {
3569
    ctx_.reset();
3570
    return env()->ThrowError("Invalid key length");
3571
  }
3572
3573
  if (1 != EVP_CipherInit_ex(ctx_.get(), nullptr, nullptr, key, iv, encrypt)) {
3574
    return ThrowCryptoError(env(), ERR_get_error(),
3575
                            "Failed to initialize cipher");
3576
  }
3577
}
3578
3579
void CipherBase::Init(const char* cipher_type,
3580
                      const char* key_buf,
3581
                      int key_buf_len,
3582
                      unsigned int auth_tag_len) {
3583
  HandleScope scope(env()->isolate());
3584
  MarkPopErrorOnReturn mark_pop_error_on_return;
3585
3586
#ifdef NODE_FIPS_MODE
3587
  if (FIPS_mode()) {
3588
    return env()->ThrowError(
3589
        "crypto.createCipher() is not supported in FIPS mode.");
3590
  }
3591
#endif  // NODE_FIPS_MODE
3592
3593
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
3594
  if (cipher == nullptr)
3595
    return env()->ThrowError("Unknown cipher");
3596
3597
  unsigned char key[EVP_MAX_KEY_LENGTH];
3598
  unsigned char iv[EVP_MAX_IV_LENGTH];
3599
3600
  int key_len = EVP_BytesToKey(cipher,
3601
                               EVP_md5(),
3602
                               nullptr,
3603
                               reinterpret_cast<const unsigned char*>(key_buf),
3604
                               key_buf_len,
3605
                               1,
3606
                               key,
3607
                               iv);
3608
  CHECK_NE(key_len, 0);
3609
3610
  const int mode = EVP_CIPHER_mode(cipher);
3611
  if (kind_ == kCipher && (mode == EVP_CIPH_CTR_MODE ||
3612
                           mode == EVP_CIPH_GCM_MODE ||
3613
                           mode == EVP_CIPH_CCM_MODE)) {
3614
    // Ignore the return value (i.e. possible exception) because we are
3615
    // not calling back into JS anyway.
3616
    ProcessEmitWarning(env(),
3617
                       "Use Cipheriv for counter mode of %s",
3618
                       cipher_type);
3619
  }
3620
3621
  CommonInit(cipher_type, cipher, key, key_len, iv,
3622
             EVP_CIPHER_iv_length(cipher), auth_tag_len);
3623
}
3624
3625
3626
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
3627
  CipherBase* cipher;
3628
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3629
3630
  CHECK_GE(args.Length(), 3);
3631
3632
  const node::Utf8Value cipher_type(args.GetIsolate(), args[0]);
3633
  const char* key_buf = Buffer::Data(args[1]);
3634
  ssize_t key_buf_len = Buffer::Length(args[1]);
3635
3636
  // Don't assign to cipher->auth_tag_len_ directly; the value might not
3637
  // represent a valid length at this point.
3638
  unsigned int auth_tag_len;
3639
  if (args[2]->IsUint32()) {
3640
    auth_tag_len = args[2].As<Uint32>()->Value();
3641
  } else {
3642
    CHECK(args[2]->IsInt32() && args[2].As<Int32>()->Value() == -1);
3643
    auth_tag_len = kNoAuthTagLength;
3644
  }
3645
3646
  cipher->Init(*cipher_type, key_buf, key_buf_len, auth_tag_len);
3647
}
3648
3649
void CipherBase::InitIv(const char* cipher_type,
3650
                        const unsigned char* key,
3651
                        int key_len,
3652
                        const unsigned char* iv,
3653
                        int iv_len,
3654
                        unsigned int auth_tag_len) {
3655
  HandleScope scope(env()->isolate());
3656
  MarkPopErrorOnReturn mark_pop_error_on_return;
3657
3658
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
3659
  if (cipher == nullptr) {
3660
    return env()->ThrowError("Unknown cipher");
3661
  }
3662
3663
  const int expected_iv_len = EVP_CIPHER_iv_length(cipher);
3664
  const bool is_authenticated_mode = IsSupportedAuthenticatedMode(cipher);
3665
  const bool has_iv = iv_len >= 0;
3666
3667
  // Throw if no IV was passed and the cipher requires an IV
3668
  if (!has_iv && expected_iv_len != 0) {
3669
    char msg[128];
3670
    snprintf(msg, sizeof(msg), "Missing IV for cipher %s", cipher_type);
3671
    return env()->ThrowError(msg);
3672
  }
3673
3674
  // Throw if an IV was passed which does not match the cipher's fixed IV length
3675
  if (!is_authenticated_mode && has_iv && iv_len != expected_iv_len) {
3676
    return env()->ThrowError("Invalid IV length");
3677
  }
3678
3679
  CommonInit(cipher_type, cipher, key, key_len, iv, iv_len, auth_tag_len);
3680
}
3681
3682
3683
static ByteSource GetSecretKeyBytes(Environment* env, Local<Value> value) {
3684
  // A key can be passed as a string, buffer or KeyObject with type 'secret'.
3685
  // If it is a string, we need to convert it to a buffer. We are not doing that
3686
  // in JS to avoid creating an unprotected copy on the heap.
3687
  return value->IsString() || Buffer::HasInstance(value) ?
3688
           ByteSource::FromStringOrBuffer(env, value) :
3689
           ByteSource::FromSymmetricKeyObject(value);
3690
}
3691
3692
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
3693
  CipherBase* cipher;
3694
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3695
  Environment* env = cipher->env();
3696
3697
  CHECK_GE(args.Length(), 4);
3698
3699
  const node::Utf8Value cipher_type(env->isolate(), args[0]);
3700
  const ByteSource key = GetSecretKeyBytes(env, args[1]);
3701
3702
  ssize_t iv_len;
3703
  const unsigned char* iv_buf;
3704
  if (args[2]->IsNull()) {
3705
    iv_buf = nullptr;
3706
    iv_len = -1;
3707
  } else {
3708
    iv_buf = reinterpret_cast<unsigned char*>(Buffer::Data(args[2]));
3709
    iv_len = Buffer::Length(args[2]);
3710
  }
3711
3712
  // Don't assign to cipher->auth_tag_len_ directly; the value might not
3713
  // represent a valid length at this point.
3714
  unsigned int auth_tag_len;
3715
  if (args[3]->IsUint32()) {
3716
    auth_tag_len = args[3].As<Uint32>()->Value();
3717
  } else {
3718
    CHECK(args[3]->IsInt32() && args[3].As<Int32>()->Value() == -1);
3719
    auth_tag_len = kNoAuthTagLength;
3720
  }
3721
3722
  cipher->InitIv(*cipher_type,
3723
                 reinterpret_cast<const unsigned char*>(key.get()),
3724
                 key.size(),