GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/out/../src/node_crypto.cc Lines: 2542 2783 91.3 %
Date: 2016-12-16 Branches: 1159 2140 54.2 %

Line Branch Exec Source
1
#include "node.h"
2
#include "node_buffer.h"
3
#include "node_crypto.h"
4
#include "node_crypto_bio.h"
5
#include "node_crypto_groups.h"
6
#include "tls_wrap.h"  // TLSWrap
7
8
#include "async-wrap.h"
9
#include "async-wrap-inl.h"
10
#include "env.h"
11
#include "env-inl.h"
12
#include "string_bytes.h"
13
#include "util.h"
14
#include "util-inl.h"
15
#include "v8.h"
16
// CNNIC Hash WhiteList is taken from
17
// https://hg.mozilla.org/mozilla-central/raw-file/98820360ab66/security/
18
// certverifier/CNNICHashWhitelist.inc
19
#include "CNNICHashWhitelist.inc"
20
21
#include <errno.h>
22
#include <limits.h>  // INT_MAX
23
#include <math.h>
24
#include <stdlib.h>
25
#include <string.h>
26
27
#define THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(val, prefix)                  \
28
  do {                                                                         \
29
    if (!Buffer::HasInstance(val) && !val->IsString()) {                       \
30
      return env->ThrowTypeError(prefix " must be a string or a buffer");      \
31
    }                                                                          \
32
  } while (0)
33
34
#define THROW_AND_RETURN_IF_NOT_BUFFER(val, prefix)           \
35
  do {                                                        \
36
    if (!Buffer::HasInstance(val)) {                          \
37
      return env->ThrowTypeError(prefix " must be a buffer"); \
38
    }                                                         \
39
  } while (0)
40
41
#define THROW_AND_RETURN_IF_NOT_STRING(val, prefix)           \
42
  do {                                                        \
43
    if (!val->IsString()) {                                   \
44
      return env->ThrowTypeError(prefix " must be a string"); \
45
    }                                                         \
46
  } while (0)
47
48
static const char PUBLIC_KEY_PFX[] =  "-----BEGIN PUBLIC KEY-----";
49
static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
50
static const char PUBRSA_KEY_PFX[] =  "-----BEGIN RSA PUBLIC KEY-----";
51
static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
52
static const char CERTIFICATE_PFX[] =  "-----BEGIN CERTIFICATE-----";
53
static const int CERTIFICATE_PFX_LEN = sizeof(CERTIFICATE_PFX) - 1;
54
55
static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
56
                                 | ASN1_STRFLGS_UTF8_CONVERT
57
                                 | XN_FLAG_SEP_MULTILINE
58
                                 | XN_FLAG_FN_SN;
59
60
namespace node {
61
namespace crypto {
62
63
using v8::AccessorSignature;
64
using v8::Array;
65
using v8::Boolean;
66
using v8::Context;
67
using v8::DEFAULT;
68
using v8::DontDelete;
69
using v8::EscapableHandleScope;
70
using v8::Exception;
71
using v8::External;
72
using v8::False;
73
using v8::FunctionCallbackInfo;
74
using v8::FunctionTemplate;
75
using v8::HandleScope;
76
using v8::Integer;
77
using v8::Isolate;
78
using v8::Local;
79
using v8::Null;
80
using v8::Object;
81
using v8::Persistent;
82
using v8::PropertyAttribute;
83
using v8::PropertyCallbackInfo;
84
using v8::ReadOnly;
85
using v8::String;
86
using v8::Value;
87
88
89
// Subject DER of CNNIC ROOT CA and CNNIC EV ROOT CA are taken from
90
// https://hg.mozilla.org/mozilla-central/file/98820360ab66/security/
91
// certverifier/NSSCertDBTrustDomain.cpp#l672
92
// C = CN, O = CNNIC, CN = CNNIC ROOT
93
static const uint8_t CNNIC_ROOT_CA_SUBJECT_DATA[] =
94
    "\x30\x32\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x43\x4E\x31\x0E\x30"
95
    "\x0C\x06\x03\x55\x04\x0A\x13\x05\x43\x4E\x4E\x49\x43\x31\x13\x30\x11\x06"
96
    "\x03\x55\x04\x03\x13\x0A\x43\x4E\x4E\x49\x43\x20\x52\x4F\x4F\x54";
97
static const uint8_t* cnnic_p = CNNIC_ROOT_CA_SUBJECT_DATA;
98
1729
static X509_NAME* cnnic_name =
99
1729
    d2i_X509_NAME(nullptr, &cnnic_p, sizeof(CNNIC_ROOT_CA_SUBJECT_DATA)-1);
100
101
// C = CN, O = China Internet Network Information Center, CN = China
102
// Internet Network Information Center EV Certificates Root
103
static const uint8_t CNNIC_EV_ROOT_CA_SUBJECT_DATA[] =
104
    "\x30\x81\x8A\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x43\x4E\x31\x32"
105
    "\x30\x30\x06\x03\x55\x04\x0A\x0C\x29\x43\x68\x69\x6E\x61\x20\x49\x6E\x74"
106
    "\x65\x72\x6E\x65\x74\x20\x4E\x65\x74\x77\x6F\x72\x6B\x20\x49\x6E\x66\x6F"
107
    "\x72\x6D\x61\x74\x69\x6F\x6E\x20\x43\x65\x6E\x74\x65\x72\x31\x47\x30\x45"
108
    "\x06\x03\x55\x04\x03\x0C\x3E\x43\x68\x69\x6E\x61\x20\x49\x6E\x74\x65\x72"
109
    "\x6E\x65\x74\x20\x4E\x65\x74\x77\x6F\x72\x6B\x20\x49\x6E\x66\x6F\x72\x6D"
110
    "\x61\x74\x69\x6F\x6E\x20\x43\x65\x6E\x74\x65\x72\x20\x45\x56\x20\x43\x65"
111
    "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x73\x20\x52\x6F\x6F\x74";
112
static const uint8_t* cnnic_ev_p = CNNIC_EV_ROOT_CA_SUBJECT_DATA;
113
1729
static X509_NAME *cnnic_ev_name =
114
1729
    d2i_X509_NAME(nullptr, &cnnic_ev_p,
115
                  sizeof(CNNIC_EV_ROOT_CA_SUBJECT_DATA)-1);
116
117
static Mutex* mutexes;
118
119
const char* const root_certs[] = {
120
#include "node_root_certs.h"  // NOLINT(build/include_order)
121
};
122
123
1729
std::string extra_root_certs_file;  // NOLINT(runtime/string)
124
125
X509_STORE* root_cert_store;
126
std::vector<X509*>* root_certs_vector;
127
128
// Just to generate static methods
129
template class SSLWrap<TLSWrap>;
130
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
131
                                           Local<FunctionTemplate> t);
132
template void SSLWrap<TLSWrap>::InitNPN(SecureContext* sc);
133
template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc);
134
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
135
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
136
    SSL* s,
137
    unsigned char* key,
138
    int len,
139
    int* copy);
140
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
141
                                                  SSL_SESSION* sess);
142
template void SSLWrap<TLSWrap>::OnClientHello(
143
    void* arg,
144
    const ClientHelloParser::ClientHello& hello);
145
146
#ifdef OPENSSL_NPN_NEGOTIATED
147
template int SSLWrap<TLSWrap>::AdvertiseNextProtoCallback(
148
    SSL* s,
149
    const unsigned char** data,
150
    unsigned int* len,
151
    void* arg);
152
template int SSLWrap<TLSWrap>::SelectNextProtoCallback(
153
    SSL* s,
154
    unsigned char** out,
155
    unsigned char* outlen,
156
    const unsigned char* in,
157
    unsigned int inlen,
158
    void* arg);
159
#endif
160
161
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
162
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
163
#endif
164
165
template void SSLWrap<TLSWrap>::DestroySSL();
166
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
167
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
168
169
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
170
template int SSLWrap<TLSWrap>::SelectALPNCallback(
171
    SSL* s,
172
    const unsigned char** out,
173
    unsigned char* outlen,
174
    const unsigned char* in,
175
    unsigned int inlen,
176
    void* arg);
177
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
178
179
34069
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
180
  static_assert(sizeof(uv_thread_t) <= sizeof(void*),
181
                "uv_thread_t does not fit in a pointer");
182
34069
  CRYPTO_THREADID_set_pointer(tid, reinterpret_cast<void*>(uv_thread_self()));
183
34069
}
184
185
186
193
static void crypto_lock_init(void) {
187

193
  mutexes = new Mutex[CRYPTO_num_locks()];
188
193
}
189
190
191
911988
static void crypto_lock_cb(int mode, int n, const char* file, int line) {
192
911988
  CHECK(!(mode & CRYPTO_LOCK) ^ !(mode & CRYPTO_UNLOCK));
193
911988
  CHECK(!(mode & CRYPTO_READ) ^ !(mode & CRYPTO_WRITE));
194
195
911988
  auto mutex = &mutexes[n];
196
911988
  if (mode & CRYPTO_LOCK)
197
    mutex->Lock();
198
  else
199
    mutex->Unlock();
200
911988
}
201
202
203
19
static int CryptoPemCallback(char *buf, int size, int rwflag, void *u) {
204
19
  if (u) {
205
19
    size_t buflen = static_cast<size_t>(size);
206
19
    size_t len = strlen(static_cast<const char*>(u));
207
19
    len = len > buflen ? buflen : len;
208
19
    memcpy(buf, u, len);
209
19
    return len;
210
  }
211
212
  return 0;
213
}
214
215
216
24
void ThrowCryptoError(Environment* env,
217
                      unsigned long err,  // NOLINT(runtime/int)
218
                      const char* default_message = nullptr) {
219
48
  HandleScope scope(env->isolate());
220
24
  if (err != 0 || default_message == nullptr) {
221
16
    char errmsg[128] = { 0 };
222
16
    ERR_error_string_n(err, errmsg, sizeof(errmsg));
223
16
    env->ThrowError(errmsg);
224
  } else {
225
    env->ThrowError(default_message);
226
  }
227
24
}
228
229
230
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
231
// The entropy pool starts out empty and needs to fill up before the PRNG
232
// can be used securely.  Once the pool is filled, it never dries up again;
233
// its contents is stirred and reused when necessary.
234
//
235
// OpenSSL normally fills the pool automatically but not when someone starts
236
// generating random numbers before the pool is full: in that case OpenSSL
237
// keeps lowering the entropy estimate to thwart attackers trying to guess
238
// the initial state of the PRNG.
239
//
240
// When that happens, we will have to wait until enough entropy is available.
241
// That should normally never take longer than a few milliseconds.
242
//
243
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
244
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
245
// block under normal circumstances.
246
//
247
// The only time when /dev/urandom may conceivably block is right after boot,
248
// when the whole system is still low on entropy.  That's not something we can
249
// do anything about.
250
3488
inline void CheckEntropy() {
251
  for (;;) {
252
3488
    int status = RAND_status();
253
3488
    CHECK_GE(status, 0);  // Cannot fail.
254
3488
    if (status != 0)
255
      break;
256
257
    // Give up, RAND_poll() not supported.
258
    if (RAND_poll() == 0)
259
      break;
260
  }
261
3488
}
262
263
264
3445
bool EntropySource(unsigned char* buffer, size_t length) {
265
  // Ensure that OpenSSL's PRNG is properly seeded.
266
3445
  CheckEntropy();
267
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
268
  // random. That's okay, it's still better than V8's stock source of entropy,
269
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
270
3445
  return RAND_bytes(buffer, length) != -1;
271
}
272
273
274
193
void SecureContext::Initialize(Environment* env, Local<Object> target) {
275
386
  Local<FunctionTemplate> t = env->NewFunctionTemplate(SecureContext::New);
276
386
  t->InstanceTemplate()->SetInternalFieldCount(1);
277
193
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"));
278
279
193
  env->SetProtoMethod(t, "init", SecureContext::Init);
280
193
  env->SetProtoMethod(t, "setKey", SecureContext::SetKey);
281
193
  env->SetProtoMethod(t, "setCert", SecureContext::SetCert);
282
193
  env->SetProtoMethod(t, "addCACert", SecureContext::AddCACert);
283
193
  env->SetProtoMethod(t, "addCRL", SecureContext::AddCRL);
284
193
  env->SetProtoMethod(t, "addRootCerts", SecureContext::AddRootCerts);
285
193
  env->SetProtoMethod(t, "setCiphers", SecureContext::SetCiphers);
286
193
  env->SetProtoMethod(t, "setECDHCurve", SecureContext::SetECDHCurve);
287
193
  env->SetProtoMethod(t, "setDHParam", SecureContext::SetDHParam);
288
193
  env->SetProtoMethod(t, "setOptions", SecureContext::SetOptions);
289
  env->SetProtoMethod(t, "setSessionIdContext",
290
193
                      SecureContext::SetSessionIdContext);
291
  env->SetProtoMethod(t, "setSessionTimeout",
292
193
                      SecureContext::SetSessionTimeout);
293
193
  env->SetProtoMethod(t, "close", SecureContext::Close);
294
193
  env->SetProtoMethod(t, "loadPKCS12", SecureContext::LoadPKCS12);
295
193
  env->SetProtoMethod(t, "getTicketKeys", SecureContext::GetTicketKeys);
296
193
  env->SetProtoMethod(t, "setTicketKeys", SecureContext::SetTicketKeys);
297
193
  env->SetProtoMethod(t, "setFreeListLength", SecureContext::SetFreeListLength);
298
  env->SetProtoMethod(t,
299
                      "enableTicketKeyCallback",
300
193
                      SecureContext::EnableTicketKeyCallback);
301
193
  env->SetProtoMethod(t, "getCertificate", SecureContext::GetCertificate<true>);
302
193
  env->SetProtoMethod(t, "getIssuer", SecureContext::GetCertificate<false>);
303
304
772
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyReturnIndex"),
305
193
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyReturnIndex));
306
772
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyHMACIndex"),
307
193
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyHMACIndex));
308
772
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyAESIndex"),
309
193
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyAESIndex));
310
772
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyNameIndex"),
311
193
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyNameIndex));
312
772
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyIVIndex"),
313
193
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyIVIndex));
314
315
965
  t->PrototypeTemplate()->SetAccessor(
316
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
317
      CtxGetter,
318
      nullptr,
319
      env->as_external(),
320
      DEFAULT,
321
      static_cast<PropertyAttribute>(ReadOnly | DontDelete),
322
193
      AccessorSignature::New(env->isolate(), t));
323
324
965
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"),
325
193
              t->GetFunction());
326
193
  env->set_secure_context_constructor_template(t);
327
193
}
328
329
330
533
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
331
533
  Environment* env = Environment::GetCurrent(args);
332
533
  new SecureContext(env, args.This());
333
533
}
334
335
336
533
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
337
  SecureContext* sc;
338
533
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
339
533
  Environment* env = sc->env();
340
341
533
  const SSL_METHOD* method = SSLv23_method();
342
343

1138
  if (args.Length() == 1 && args[0]->IsString()) {
344
65
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
345
346
    // Note that SSLv2 and SSLv3 are disallowed but SSLv2_method and friends
347
    // are still accepted.  They are OpenSSL's way of saying that all known
348
    // protocols are supported unless explicitly disabled (which we do below
349
    // for SSLv2 and SSLv3.)
350
36
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
351
7
      return env->ThrowError("SSLv2 methods disabled");
352
35
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
353
      return env->ThrowError("SSLv2 methods disabled");
354
34
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
355
      return env->ThrowError("SSLv2 methods disabled");
356
33
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
357
      return env->ThrowError("SSLv3 methods disabled");
358
32
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
359
      return env->ThrowError("SSLv3 methods disabled");
360
31
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
361
      return env->ThrowError("SSLv3 methods disabled");
362
30
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
363
1
      method = SSLv23_method();
364
29
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
365
1
      method = SSLv23_server_method();
366
28
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
367
1
      method = SSLv23_client_method();
368
27
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
369
3
      method = TLSv1_method();
370
24
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
371
1
      method = TLSv1_server_method();
372
23
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
373
1
      method = TLSv1_client_method();
374
22
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
375
2
      method = TLSv1_1_method();
376
20
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
377
1
      method = TLSv1_1_server_method();
378
19
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
379
1
      method = TLSv1_1_client_method();
380
18
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
381
14
      method = TLSv1_2_method();
382
4
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
383
2
      method = TLSv1_2_server_method();
384
2
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
385
1
      method = TLSv1_2_client_method();
386
    } else {
387
      return env->ThrowError("Unknown method");
388
    }
389
  }
390
391
526
  sc->ctx_ = SSL_CTX_new(method);
392
526
  SSL_CTX_set_app_data(sc->ctx_, sc);
393
394
  // Disable SSLv2 in the case when method == SSLv23_method() and the
395
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
396
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
397
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
398
526
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv2);
399
526
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv3);
400
401
  // SSL session cache configuration
402
526
  SSL_CTX_set_session_cache_mode(sc->ctx_,
403
                                 SSL_SESS_CACHE_SERVER |
404
                                 SSL_SESS_CACHE_NO_INTERNAL |
405
526
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
406
526
  SSL_CTX_sess_set_get_cb(sc->ctx_, SSLWrap<Connection>::GetSessionCallback);
407
526
  SSL_CTX_sess_set_new_cb(sc->ctx_, SSLWrap<Connection>::NewSessionCallback);
408
}
409
410
411
// Takes a string or buffer and loads it into a BIO.
412
// Caller responsible for BIO_free_all-ing the returned object.
413
561
static BIO* LoadBIO(Environment* env, Local<Value> v) {
414
1122
  HandleScope scope(env->isolate());
415
416
1122
  if (v->IsString()) {
417
86
    const node::Utf8Value s(env->isolate(), v);
418
43
    return NodeBIO::NewFixed(*s, s.length());
419
  }
420
421
518
  if (Buffer::HasInstance(v)) {
422
518
    return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
423
  }
424
425
  return nullptr;
426
}
427
428
429
222
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
430
222
  Environment* env = Environment::GetCurrent(args);
431
432
  SecureContext* sc;
433
226
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
434
435
222
  unsigned int len = args.Length();
436
222
  if (len < 1) {
437
    return env->ThrowError("Private key argument is mandatory");
438
  }
439
440
222
  if (len > 2) {
441
    return env->ThrowError("Only private key and pass phrase are expected");
442
  }
443
444
222
  if (len == 2) {
445
24
    THROW_AND_RETURN_IF_NOT_STRING(args[1], "Pass phrase");
446
  }
447
448
220
  BIO *bio = LoadBIO(env, args[0]);
449
220
  if (!bio)
450
    return;
451
452
438
  node::Utf8Value passphrase(env->isolate(), args[1]);
453
454
220
  EVP_PKEY* key = PEM_read_bio_PrivateKey(bio,
455
                                          nullptr,
456
                                          CryptoPemCallback,
457
220
                                          len == 1 ? nullptr : *passphrase);
458
459
220
  if (!key) {
460
1
    BIO_free_all(bio);
461
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
462
1
    if (!err) {
463
      return env->ThrowError("PEM_read_bio_PrivateKey");
464
    }
465
1
    return ThrowCryptoError(env, err);
466
  }
467
468
219
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_, key);
469
219
  EVP_PKEY_free(key);
470
219
  BIO_free_all(bio);
471
472
219
  if (!rv) {
473
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
474
1
    if (!err)
475
      return env->ThrowError("SSL_CTX_use_PrivateKey");
476
1
    return ThrowCryptoError(env, err);
477
  }
478
}
479
480
481
222
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
482
  int ret;
483
484
222
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
485
  X509_STORE_CTX store_ctx;
486
487
222
  ret = X509_STORE_CTX_init(&store_ctx, store, nullptr, nullptr);
488
222
  if (!ret)
489
    goto end;
490
491
222
  ret = X509_STORE_CTX_get1_issuer(issuer, &store_ctx, cert);
492
222
  X509_STORE_CTX_cleanup(&store_ctx);
493
494
 end:
495
222
  return ret;
496
}
497
498
499
227
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
500
                                  X509* x,
501
                                  STACK_OF(X509)* extra_certs,
502
                                  X509** cert,
503
                                  X509** issuer) {
504
227
  CHECK_EQ(*issuer, nullptr);
505
227
  CHECK_EQ(*cert, nullptr);
506
507
227
  int ret = SSL_CTX_use_certificate(ctx, x);
508
509
227
  if (ret) {
510
    // If we could set up our certificate, now proceed to
511
    // the CA certificates.
512
    int r;
513
514
227
    SSL_CTX_clear_extra_chain_certs(ctx);
515
516
232
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
517
5
      X509* ca = sk_X509_value(extra_certs, i);
518
519
      // NOTE: Increments reference count on `ca`
520
5
      r = SSL_CTX_add1_chain_cert(ctx, ca);
521
522
5
      if (!r) {
523
        ret = 0;
524
        *issuer = nullptr;
525
        goto end;
526
      }
527
      // Note that we must not free r if it was successfully
528
      // added to the chain (while we must free the main
529
      // certificate, since its reference count is increased
530
      // by SSL_CTX_use_certificate).
531
532
      // Find issuer
533

5
      if (*issuer != nullptr || X509_check_issued(ca, x) != X509_V_OK)
534
        continue;
535
536
5
      *issuer = ca;
537
    }
538
  }
539
540
  // Try getting issuer from a cert store
541
227
  if (ret) {
542
227
    if (*issuer == nullptr) {
543
222
      ret = SSL_CTX_get_issuer(ctx, x, issuer);
544
222
      ret = ret < 0 ? 0 : 1;
545
      // NOTE: get_cert_store doesn't increment reference count,
546
      // no need to free `store`
547
    } else {
548
      // Increment issuer reference count
549
5
      *issuer = X509_dup(*issuer);
550
5
      if (*issuer == nullptr) {
551
        ret = 0;
552
        goto end;
553
      }
554
    }
555
  }
556
557
 end:
558
227
  if (ret && x != nullptr) {
559
227
    *cert = X509_dup(x);
560
227
    if (*cert == nullptr)
561
      ret = 0;
562
  }
563
227
  return ret;
564
}
565
566
567
// Read a file that contains our certificate in "PEM" format,
568
// possibly followed by a sequence of CA certificates that should be
569
// sent to the peer in the Certificate message.
570
//
571
// Taken from OpenSSL - edited for style.
572
220
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
573
                                  BIO* in,
574
                                  X509** cert,
575
                                  X509** issuer) {
576
220
  X509* x = nullptr;
577
578
  // Just to ensure that `ERR_peek_last_error` below will return only errors
579
  // that we are interested in
580
220
  ERR_clear_error();
581
582
220
  x = PEM_read_bio_X509_AUX(in, nullptr, CryptoPemCallback, nullptr);
583
584
220
  if (x == nullptr) {
585
    SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
586
    return 0;
587
  }
588
589
220
  X509* extra = nullptr;
590
220
  int ret = 0;
591
220
  unsigned long err = 0;  // NOLINT(runtime/int)
592
593
  // Read extra certs
594
220
  STACK_OF(X509)* extra_certs = sk_X509_new_null();
595
220
  if (extra_certs == nullptr) {
596
    SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_MALLOC_FAILURE);
597
    goto done;
598
  }
599
600
222
  while ((extra = PEM_read_bio_X509(in, nullptr, CryptoPemCallback, nullptr))) {
601
2
    if (sk_X509_push(extra_certs, extra))
602
      continue;
603
604
    // Failure, free all certs
605
    goto done;
606
  }
607
220
  extra = nullptr;
608
609
  // When the while loop ends, it's usually just EOF.
610
220
  err = ERR_peek_last_error();
611

440
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
612
220
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
613
220
    ERR_clear_error();
614
  } else  {
615
    // some real error
616
    goto done;
617
  }
618
619
220
  ret = SSL_CTX_use_certificate_chain(ctx, x, extra_certs, cert, issuer);
620
  if (!ret)
621
    goto done;
622
623
 done:
624
220
  if (extra_certs != nullptr)
625
220
    sk_X509_pop_free(extra_certs, X509_free);
626
220
  if (extra != nullptr)
627
    X509_free(extra);
628
220
  if (x != nullptr)
629
220
    X509_free(x);
630
631
  return ret;
632
}
633
634
635
220
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
636
220
  Environment* env = Environment::GetCurrent(args);
637
638
  SecureContext* sc;
639
220
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
640
641
220
  if (args.Length() != 1) {
642
    return env->ThrowTypeError("Certificate argument is mandatory");
643
  }
644
645
220
  BIO* bio = LoadBIO(env, args[0]);
646
220
  if (!bio)
647
    return;
648
649
  // Free previous certs
650
220
  if (sc->issuer_ != nullptr) {
651
    X509_free(sc->issuer_);
652
    sc->issuer_ = nullptr;
653
  }
654
220
  if (sc->cert_ != nullptr) {
655
1
    X509_free(sc->cert_);
656
1
    sc->cert_ = nullptr;
657
  }
658
659
220
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_,
660
                                         bio,
661
                                         &sc->cert_,
662
220
                                         &sc->issuer_);
663
664
220
  BIO_free_all(bio);
665
666
220
  if (!rv) {
667
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
668
    if (!err) {
669
      return env->ThrowError("SSL_CTX_use_certificate_chain");
670
    }
671
    return ThrowCryptoError(env, err);
672
  }
673
}
674
675
676
#if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(OPENSSL_IS_BORINGSSL)
677
// This section contains OpenSSL 1.1.0 functions reimplemented for OpenSSL
678
// 1.0.2 so that the following code can be written without lots of #if lines.
679
680
static int X509_STORE_up_ref(X509_STORE* store) {
681
446
  CRYPTO_add(&store->references, 1, CRYPTO_LOCK_X509_STORE);
682
  return 1;
683
}
684
685
static int X509_up_ref(X509* cert) {
686
20850
  CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
687
  return 1;
688
}
689
#endif  // OPENSSL_VERSION_NUMBER < 0x10100000L && !OPENSSL_IS_BORINGSSL
690
691
692
139
static X509_STORE* NewRootCertStore() {
693
139
  if (!root_certs_vector) {
694
262
    root_certs_vector = new std::vector<X509*>;
695
696
19781
    for (size_t i = 0; i < arraysize(root_certs); i++) {
697
19650
      BIO* bp = NodeBIO::NewFixed(root_certs[i], strlen(root_certs[i]));
698
19650
      X509 *x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr);
699
19650
      BIO_free(bp);
700
701
19650
      if (x509 == nullptr) {
702
        // Parse errors from the built-in roots are fatal.
703
        ABORT();
704
        return nullptr;
705
      }
706
707
19650
      root_certs_vector->push_back(x509);
708
    }
709
  }
710
711
139
  X509_STORE* store = X509_STORE_new();
712
21406
  for (auto& cert : *root_certs_vector) {
713
41700
    X509_up_ref(cert);
714
20850
    X509_STORE_add_cert(store, cert);
715
  }
716
717
  return store;
718
}
719
720
721
92
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
722
92
  Environment* env = Environment::GetCurrent(args);
723
724
  SecureContext* sc;
725
92
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
726
  ClearErrorOnReturn clear_error_on_return;
727
  (void) &clear_error_on_return;  // Silence compiler warning.
728
729
92
  if (args.Length() != 1) {
730
    return env->ThrowTypeError("CA certificate argument is mandatory");
731
  }
732
733
92
  BIO* bio = LoadBIO(env, args[0]);
734
92
  if (!bio) {
735
    return;
736
  }
737
738
92
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
739
94
  while (X509* x509 =
740
186
             PEM_read_bio_X509(bio, nullptr, CryptoPemCallback, nullptr)) {
741
94
    if (cert_store == root_cert_store) {
742
1
      cert_store = NewRootCertStore();
743
1
      SSL_CTX_set_cert_store(sc->ctx_, cert_store);
744
    }
745
94
    X509_STORE_add_cert(cert_store, x509);
746
94
    SSL_CTX_add_client_CA(sc->ctx_, x509);
747
94
    X509_free(x509);
748
  }
749
750
92
  BIO_free_all(bio);
751
}
752
753
754
7
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
755
7
  Environment* env = Environment::GetCurrent(args);
756
757
  SecureContext* sc;
758
7
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
759
760
7
  if (args.Length() != 1) {
761
    return env->ThrowTypeError("CRL argument is mandatory");
762
  }
763
764
  ClearErrorOnReturn clear_error_on_return;
765
  (void) &clear_error_on_return;  // Silence compiler warning.
766
767
7
  BIO *bio = LoadBIO(env, args[0]);
768
7
  if (!bio)
769
    return;
770
771
  X509_CRL* crl =
772
7
      PEM_read_bio_X509_CRL(bio, nullptr, CryptoPemCallback, nullptr);
773
774
7
  if (crl == nullptr) {
775
1
    BIO_free_all(bio);
776
    return env->ThrowError("Failed to parse CRL");
777
  }
778
779
6
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
780
6
  if (cert_store == root_cert_store) {
781
5
    cert_store = NewRootCertStore();
782
5
    SSL_CTX_set_cert_store(sc->ctx_, cert_store);
783
  }
784
785
6
  X509_STORE_add_crl(cert_store, crl);
786
  X509_STORE_set_flags(cert_store,
787
6
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
788
789
6
  BIO_free_all(bio);
790
6
  X509_CRL_free(crl);
791
}
792
793
794
2
void UseExtraCaCerts(const std::string& file) {
795
2
  extra_root_certs_file = file;
796
2
}
797
798
799
2
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
800
    X509_STORE* store,
801
    const char* file) {
802
2
  ERR_clear_error();
803
  MarkPopErrorOnReturn mark_pop_error_on_return;
804
805
2
  BIO* bio = BIO_new_file(file, "r");
806
2
  if (!bio) {
807
1
    return ERR_get_error();
808
  }
809
810
1
  while (X509* x509 =
811
2
      PEM_read_bio_X509(bio, nullptr, CryptoPemCallback, nullptr)) {
812
1
    X509_STORE_add_cert(store, x509);
813
1
    X509_free(x509);
814
  }
815
1
  BIO_free_all(bio);
816
817
1
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
818
  // Ignore error if its EOF/no start line found.
819

2
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
820
1
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
821
    return 0;
822
  }
823
824
  return err;
825
}
826
827
446
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
828
  SecureContext* sc;
829
446
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
830
  ClearErrorOnReturn clear_error_on_return;
831
  (void) &clear_error_on_return;  // Silence compiler warning.
832
833
446
  if (!root_cert_store) {
834
131
    root_cert_store = NewRootCertStore();
835
836
131
    if (!extra_root_certs_file.empty()) {
837
2
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
838
                                           root_cert_store,
839
2
                                           extra_root_certs_file.c_str());
840
2
      if (err) {
841
2
        ProcessEmitWarning(sc->env(),
842
                           "Ignoring extra certs from `%s`, load failed: %s\n",
843
                           extra_root_certs_file.c_str(),
844
1
                           ERR_error_string(err, nullptr));
845
      }
846
    }
847
  }
848
849
  // Increment reference count so global store is not deleted along with CTX.
850
892
  X509_STORE_up_ref(root_cert_store);
851
446
  SSL_CTX_set_cert_store(sc->ctx_, root_cert_store);
852
}
853
854
855
523
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
856
  SecureContext* sc;
857
525
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
858
523
  Environment* env = sc->env();
859
  ClearErrorOnReturn clear_error_on_return;
860
  (void) &clear_error_on_return;  // Silence compiler warning.
861
862
523
  if (args.Length() != 1) {
863
    return env->ThrowTypeError("Ciphers argument is mandatory");
864
  }
865
866
1046
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Ciphers");
867
868
1563
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
869
521
  SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
870
}
871
872
873
519
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
874
  SecureContext* sc;
875
520
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
876
519
  Environment* env = sc->env();
877
878
519
  if (args.Length() != 1)
879
    return env->ThrowTypeError("ECDH curve name argument is mandatory");
880
881
1038
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "ECDH curve name");
882
883
1036
  node::Utf8Value curve(env->isolate(), args[0]);
884
885
518
  int nid = OBJ_sn2nid(*curve);
886
887
518
  if (nid == NID_undef)
888
    return env->ThrowTypeError("First argument should be a valid curve name");
889
890
518
  EC_KEY* ecdh = EC_KEY_new_by_curve_name(nid);
891
892
518
  if (ecdh == nullptr)
893
    return env->ThrowTypeError("First argument should be a valid curve name");
894
895
518
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_ECDH_USE);
896
518
  SSL_CTX_set_tmp_ecdh(sc->ctx_, ecdh);
897
898
518
  EC_KEY_free(ecdh);
899
}
900
901
902
9
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
903
  SecureContext* sc;
904
9
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
905
9
  Environment* env = sc->env();
906
  ClearErrorOnReturn clear_error_on_return;
907
  (void) &clear_error_on_return;  // Silence compiler warning.
908
909
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
910
  // to be specifed explicitly
911
9
  if (args.Length() != 1)
912
    return env->ThrowTypeError("DH argument is mandatory");
913
914
  // Invalid dhparam is silently discarded and DHE is no longer used.
915
9
  BIO* bio = LoadBIO(env, args[0]);
916
9
  if (!bio)
917
    return;
918
919
9
  DH* dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
920
9
  BIO_free_all(bio);
921
922
9
  if (dh == nullptr)
923
    return;
924
925
8
  const int size = BN_num_bits(dh->p);
926
8
  if (size < 1024) {
927
    return env->ThrowError("DH parameter is less than 1024 bits");
928
6
  } else if (size < 2048) {
929
6
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
930
        env->isolate(), "WARNING: DH parameter is less than 2048 bits"));
931
  }
932
933
6
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE);
934
6
  int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh);
935
6
  DH_free(dh);
936
937
6
  if (!r)
938
    return env->ThrowTypeError("Error setting temp DH parameter");
939
}
940
941
942
186
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
943
  SecureContext* sc;
944
186
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
945
946

558
  if (args.Length() != 1 || !args[0]->IntegerValue()) {
947
    return sc->env()->ThrowTypeError("Options must be an integer value");
948
  }
949
950
186
  SSL_CTX_set_options(
951
      sc->ctx_,
952
186
      static_cast<long>(args[0]->IntegerValue()));  // NOLINT(runtime/int)
953
}
954
955
956
181
void SecureContext::SetSessionIdContext(
957
    const FunctionCallbackInfo<Value>& args) {
958
  SecureContext* sc;
959
362
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
960
181
  Environment* env = sc->env();
961
962
181
  if (args.Length() != 1) {
963
    return env->ThrowTypeError("Session ID context argument is mandatory");
964
  }
965
966
362
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Session ID context");
967
968
362
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
969
  const unsigned char* sid_ctx =
970
181
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
971
181
  unsigned int sid_ctx_len = sessionIdContext.length();
972
973
181
  int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
974
181
  if (r == 1)
975
    return;
976
977
  BIO* bio;
978
  BUF_MEM* mem;
979
  Local<String> message;
980
981
  bio = BIO_new(BIO_s_mem());
982
  if (bio == nullptr) {
983
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
984
                                    "SSL_CTX_set_session_id_context error");
985
  } else {
986
    ERR_print_errors(bio);
987
    BIO_get_mem_ptr(bio, &mem);
988
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
989
    BIO_free_all(bio);
990
  }
991
992
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
993
}
994
995
996
1
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
997
  SecureContext* sc;
998
1
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
999
1000

3
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1001
1
    return sc->env()->ThrowTypeError(
1002
        "Session timeout must be a 32-bit integer");
1003
  }
1004
1005
  int32_t sessionTimeout = args[0]->Int32Value();
1006
  SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
1007
}
1008
1009
1010
285
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1011
  SecureContext* sc;
1012
285
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1013
285
  sc->FreeCTXMem();
1014
}
1015
1016
1017
// Takes .pfx or .p12 and password in string or buffer format
1018
13
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1019
13
  Environment* env = Environment::GetCurrent(args);
1020
1021
13
  BIO* in = nullptr;
1022
13
  PKCS12* p12 = nullptr;
1023
13
  EVP_PKEY* pkey = nullptr;
1024
13
  X509* cert = nullptr;
1025
13
  STACK_OF(X509)* extra_certs = nullptr;
1026
13
  char* pass = nullptr;
1027
13
  bool ret = false;
1028
1029
  SecureContext* sc;
1030
19
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1031
  ClearErrorOnReturn clear_error_on_return;
1032
  (void) &clear_error_on_return;  // Silence compiler warning.
1033
1034
13
  if (args.Length() < 1) {
1035
    return env->ThrowTypeError("PFX certificate argument is mandatory");
1036
  }
1037
1038
13
  in = LoadBIO(env, args[0]);
1039
13
  if (in == nullptr) {
1040
    return env->ThrowError("Unable to load BIO");
1041
  }
1042
1043
13
  if (args.Length() >= 2) {
1044
11
    THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Pass phrase");
1045
11
    size_t passlen = Buffer::Length(args[1]);
1046
11
    pass = new char[passlen + 1];
1047
22
    memcpy(pass, Buffer::Data(args[1]), passlen);
1048
11
    pass[passlen] = '\0';
1049
  }
1050
1051
  // Free previous certs
1052
13
  if (sc->issuer_ != nullptr) {
1053
    X509_free(sc->issuer_);
1054
    sc->issuer_ = nullptr;
1055
  }
1056
13
  if (sc->cert_ != nullptr) {
1057
    X509_free(sc->cert_);
1058
    sc->cert_ = nullptr;
1059
  }
1060
1061
13
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
1062
1063

37
  if (d2i_PKCS12_bio(in, &p12) &&
1064
18
      PKCS12_parse(p12, pass, &pkey, &cert, &extra_certs) &&
1065
7
      SSL_CTX_use_certificate_chain(sc->ctx_,
1066
                                    cert,
1067
                                    extra_certs,
1068
                                    &sc->cert_,
1069

20
                                    &sc->issuer_) &&
1070
7
      SSL_CTX_use_PrivateKey(sc->ctx_, pkey)) {
1071
    // Add CA certs too
1072
13
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
1073
3
      X509* ca = sk_X509_value(extra_certs, i);
1074
1075
3
      if (cert_store == root_cert_store) {
1076
2
        cert_store = NewRootCertStore();
1077
2
        SSL_CTX_set_cert_store(sc->ctx_, cert_store);
1078
      }
1079
3
      X509_STORE_add_cert(cert_store, ca);
1080
3
      SSL_CTX_add_client_CA(sc->ctx_, ca);
1081
    }
1082
    ret = true;
1083
  }
1084
1085
13
  if (pkey != nullptr)
1086
7
    EVP_PKEY_free(pkey);
1087
13
  if (cert != nullptr)
1088
7
    X509_free(cert);
1089
13
  if (extra_certs != nullptr)
1090
3
    sk_X509_pop_free(extra_certs, X509_free);
1091
1092
13
  PKCS12_free(p12);
1093
13
  BIO_free_all(in);
1094
13
  delete[] pass;
1095
1096
13
  if (!ret) {
1097
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1098
6
    const char* str = ERR_reason_error_string(err);
1099
    return env->ThrowError(str);
1100
  }
1101
}
1102
1103
1104
7
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1105
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1106
1107
  SecureContext* wrap;
1108
7
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1109
1110
14
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1111
7
  if (SSL_CTX_get_tlsext_ticket_keys(wrap->ctx_,
1112
                                     Buffer::Data(buff),
1113
                                     Buffer::Length(buff)) != 1) {
1114
    return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
1115
  }
1116
1117
7
  args.GetReturnValue().Set(buff);
1118
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1119
}
1120
1121
1122
16
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1123
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1124
  SecureContext* wrap;
1125
16
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1126
16
  Environment* env = wrap->env();
1127
1128
16
  if (args.Length() < 1) {
1129
    return env->ThrowTypeError("Ticket keys argument is mandatory");
1130
  }
1131
1132
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Ticket keys");
1133
1134
15
  if (Buffer::Length(args[0]) != 48) {
1135
    return env->ThrowTypeError("Ticket keys length must be 48 bytes");
1136
  }
1137
1138
28
  if (SSL_CTX_set_tlsext_ticket_keys(wrap->ctx_,
1139
                                     Buffer::Data(args[0]),
1140
                                     Buffer::Length(args[0])) != 1) {
1141
    return env->ThrowError("Failed to fetch tls ticket keys");
1142
  }
1143
1144
28
  args.GetReturnValue().Set(true);
1145
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1146
}
1147
1148
1149
290
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1150
  SecureContext* wrap;
1151
290
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1152
1153
580
  wrap->ctx_->freelist_max_len = args[0]->Int32Value();
1154
}
1155
1156
1157
1
void SecureContext::EnableTicketKeyCallback(
1158
    const FunctionCallbackInfo<Value>& args) {
1159
  SecureContext* wrap;
1160
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1161
1162
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_, TicketKeyCallback);
1163
}
1164
1165
1166
3
int SecureContext::TicketKeyCallback(SSL* ssl,
1167
                                     unsigned char* name,
1168
                                     unsigned char* iv,
1169
                                     EVP_CIPHER_CTX* ectx,
1170
                                     HMAC_CTX* hctx,
1171
                                     int enc) {
1172
  static const int kTicketPartSize = 16;
1173
1174
  SecureContext* sc = static_cast<SecureContext*>(
1175
3
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1176
1177
3
  Environment* env = sc->env();
1178
6
  HandleScope handle_scope(env->isolate());
1179
9
  Context::Scope context_scope(env->context());
1180
1181
  Local<Value> argv[] = {
1182
3
    Buffer::Copy(env,
1183
                 reinterpret_cast<char*>(name),
1184
                 kTicketPartSize).ToLocalChecked(),
1185
3
    Buffer::Copy(env,
1186
                 reinterpret_cast<char*>(iv),
1187
                 kTicketPartSize).ToLocalChecked(),
1188
    Boolean::New(env->isolate(), enc != 0)
1189
18
  };
1190
  Local<Value> ret = node::MakeCallback(env,
1191
                                        sc->object(),
1192
                                        env->ticketkeycallback_string(),
1193
3
                                        arraysize(argv),
1194
9
                                        argv);
1195
3
  Local<Array> arr = ret.As<Array>();
1196
1197
6
  int r = arr->Get(kTicketKeyReturnIndex)->Int32Value();
1198
3
  if (r < 0)
1199
    return r;
1200
1201
3
  Local<Value> hmac = arr->Get(kTicketKeyHMACIndex);
1202
3
  Local<Value> aes = arr->Get(kTicketKeyAESIndex);
1203
3
  if (Buffer::Length(aes) != kTicketPartSize)
1204
    return -1;
1205
1206
3
  if (enc) {
1207
2
    Local<Value> name_val = arr->Get(kTicketKeyNameIndex);
1208
2
    Local<Value> iv_val = arr->Get(kTicketKeyIVIndex);
1209
1210

4
    if (Buffer::Length(name_val) != kTicketPartSize ||
1211
2
        Buffer::Length(iv_val) != kTicketPartSize) {
1212
      return -1;
1213
    }
1214
1215
4
    memcpy(name, Buffer::Data(name_val), kTicketPartSize);
1216
4
    memcpy(iv, Buffer::Data(iv_val), kTicketPartSize);
1217
  }
1218
1219
6
  HMAC_Init_ex(hctx,
1220
3
               Buffer::Data(hmac),
1221
3
               Buffer::Length(hmac),
1222
               EVP_sha256(),
1223
3
               nullptr);
1224
1225
  const unsigned char* aes_key =
1226
3
      reinterpret_cast<unsigned char*>(Buffer::Data(aes));
1227
3
  if (enc) {
1228
2
    EVP_EncryptInit_ex(ectx,
1229
                       EVP_aes_128_cbc(),
1230
                       nullptr,
1231
                       aes_key,
1232
2
                       iv);
1233
  } else {
1234
1
    EVP_DecryptInit_ex(ectx,
1235
                       EVP_aes_128_cbc(),
1236
                       nullptr,
1237
                       aes_key,
1238
1
                       iv);
1239
  }
1240
1241
  return r;
1242
}
1243
1244
1245
1246
1247
2
void SecureContext::CtxGetter(Local<String> property,
1248
                              const PropertyCallbackInfo<Value>& info) {
1249
  SecureContext* sc;
1250
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1251
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_);
1252
4
  info.GetReturnValue().Set(ext);
1253
}
1254
1255
1256
template <bool primary>
1257
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1258
  SecureContext* wrap;
1259

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1260
6
  Environment* env = wrap->env();
1261
  X509* cert;
1262
1263
  if (primary)
1264
3
    cert = wrap->cert_;
1265
  else
1266
3
    cert = wrap->issuer_;
1267

6
  if (cert == nullptr)
1268
    return args.GetReturnValue().Set(Null(env->isolate()));
1269
1270
6
  int size = i2d_X509(cert, nullptr);
1271
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1272
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1273
6
      Buffer::Data(buff));
1274
6
  i2d_X509(cert, &serialized);
1275
1276
12
  args.GetReturnValue().Set(buff);
1277
}
1278
1279
1280
template <class Base>
1281
341
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1282
682
  HandleScope scope(env->isolate());
1283
1284
341
  env->SetProtoMethod(t, "getPeerCertificate", GetPeerCertificate);
1285
341
  env->SetProtoMethod(t, "getSession", GetSession);
1286
341
  env->SetProtoMethod(t, "setSession", SetSession);
1287
341
  env->SetProtoMethod(t, "loadSession", LoadSession);
1288
341
  env->SetProtoMethod(t, "isSessionReused", IsSessionReused);
1289
341
  env->SetProtoMethod(t, "isInitFinished", IsInitFinished);
1290
341
  env->SetProtoMethod(t, "verifyError", VerifyError);
1291
341
  env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
1292
341
  env->SetProtoMethod(t, "endParser", EndParser);
1293
341
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1294
341
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1295
341
  env->SetProtoMethod(t, "shutdownSSL", Shutdown);
1296
341
  env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket);
1297
341
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1298
341
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1299
341
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1300
341
  env->SetProtoMethod(t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
1301
341
  env->SetProtoMethod(t, "getProtocol", GetProtocol);
1302
1303
#ifdef SSL_set_max_send_fragment
1304
341
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1305
#endif  // SSL_set_max_send_fragment
1306
1307
#ifdef OPENSSL_NPN_NEGOTIATED
1308
341
  env->SetProtoMethod(t, "getNegotiatedProtocol", GetNegotiatedProto);
1309
#endif  // OPENSSL_NPN_NEGOTIATED
1310
1311
#ifdef OPENSSL_NPN_NEGOTIATED
1312
341
  env->SetProtoMethod(t, "setNPNProtocols", SetNPNProtocols);
1313
#endif
1314
1315
341
  env->SetProtoMethod(t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
1316
341
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1317
1318
1705
  t->PrototypeTemplate()->SetAccessor(
1319
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
1320
      SSLGetter,
1321
      nullptr,
1322
      env->as_external(),
1323
      DEFAULT,
1324
      static_cast<PropertyAttribute>(ReadOnly | DontDelete),
1325
      AccessorSignature::New(env->isolate(), t));
1326
341
}
1327
1328
1329
template <class Base>
1330
636
void SSLWrap<Base>::InitNPN(SecureContext* sc) {
1331
#ifdef OPENSSL_NPN_NEGOTIATED
1332
  // Server should advertise NPN protocols
1333
636
  SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
1334
                                        AdvertiseNextProtoCallback,
1335
                                        nullptr);
1336
  // Client should select protocol from list of advertised
1337
  // If server supports NPN
1338
636
  SSL_CTX_set_next_proto_select_cb(sc->ctx_, SelectNextProtoCallback, nullptr);
1339
#endif  // OPENSSL_NPN_NEGOTIATED
1340
1341
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1342
  // OCSP stapling
1343
636
  SSL_CTX_set_tlsext_status_cb(sc->ctx_, TLSExtStatusCallback);
1344
636
  SSL_CTX_set_tlsext_status_arg(sc->ctx_, nullptr);
1345
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1346
636
}
1347
1348
1349
template <class Base>
1350
6
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1351
                                               unsigned char* key,
1352
                                               int len,
1353
                                               int* copy) {
1354
6
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1355
1356
6
  *copy = 0;
1357
6
  SSL_SESSION* sess = w->next_sess_;
1358
6
  w->next_sess_ = nullptr;
1359
1360
6
  return sess;
1361
}
1362
1363
1364
template <class Base>
1365
5
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1366
5
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1367
10
  Environment* env = w->ssl_env();
1368
10
  HandleScope handle_scope(env->isolate());
1369
15
  Context::Scope context_scope(env->context());
1370
1371

5
  if (!w->session_callbacks_)
1372
    return 0;
1373
1374
  // Check if session is small enough to be stored
1375
2
  int size = i2d_SSL_SESSION(sess, nullptr);
1376

2
  if (size > SecureContext::kMaxSessionSize)
1377
    return 0;
1378
1379
  // Serialize session
1380
4
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1381
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1382
2
      Buffer::Data(buff));
1383
4
  memset(serialized, 0, size);
1384
2
  i2d_SSL_SESSION(sess, &serialized);
1385
1386
2
  Local<Object> session = Buffer::Copy(
1387
      env,
1388
      reinterpret_cast<char*>(sess->session_id),
1389
4
      sess->session_id_length).ToLocalChecked();
1390
6
  Local<Value> argv[] = { session, buff };
1391
2
  w->new_session_wait_ = true;
1392
4
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1393
1394
2
  return 0;
1395
}
1396
1397
1398
template <class Base>
1399
17
void SSLWrap<Base>::OnClientHello(void* arg,
1400
                                  const ClientHelloParser::ClientHello& hello) {
1401
17
  Base* w = static_cast<Base*>(arg);
1402
31
  Environment* env = w->ssl_env();
1403
34
  HandleScope handle_scope(env->isolate());
1404
51
  Context::Scope context_scope(env->context());
1405
1406
17
  Local<Object> hello_obj = Object::New(env->isolate());
1407
17
  Local<Object> buff = Buffer::Copy(
1408
      env,
1409
17
      reinterpret_cast<const char*>(hello.session_id()),
1410
51
      hello.session_size()).ToLocalChecked();
1411
51
  hello_obj->Set(env->session_id_string(), buff);
1412

17
  if (hello.servername() == nullptr) {
1413
15
    hello_obj->Set(env->servername_string(), String::Empty(env->isolate()));
1414
  } else {
1415
14
    Local<String> servername = OneByteString(env->isolate(),
1416
                                             hello.servername(),
1417
28
                                             hello.servername_size());
1418
42
    hello_obj->Set(env->servername_string(), servername);
1419
  }
1420
85
  hello_obj->Set(env->tls_ticket_string(),
1421
17
                 Boolean::New(env->isolate(), hello.has_ticket()));
1422
85
  hello_obj->Set(env->ocsp_request_string(),
1423
17
                 Boolean::New(env->isolate(), hello.ocsp_request()));
1424
1425
34
  Local<Value> argv[] = { hello_obj };
1426
34
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1427
17
}
1428
1429
1430
28
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1431
28
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1432
1433
28
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1434
    return false;
1435
1436
2
  const unsigned char* p = ext->value->data;
1437
2
  GENERAL_NAMES* names = reinterpret_cast<GENERAL_NAMES*>(ASN1_item_d2i(
1438
      NULL,
1439
      &p,
1440
2
      ext->value->length,
1441
4
      ASN1_ITEM_ptr(method->it)));
1442
2
  if (names == NULL)
1443
    return false;
1444
1445
14
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1446
6
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1447
1448
6
    if (i != 0)
1449
4
      BIO_write(out, ", ", 2);
1450
1451
6
    if (gen->type == GEN_DNS) {
1452
3
      ASN1_IA5STRING* name = gen->d.dNSName;
1453
1454
3
      BIO_write(out, "DNS:", 4);
1455
3
      BIO_write(out, name->data, name->length);
1456
    } else {
1457
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1458
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, NULL);
1459
3
      if (nval == NULL)
1460
        return false;
1461
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1462
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1463
    }
1464
  }
1465
2
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1466
1467
2
  return true;
1468
}
1469
1470
1471
49
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1472
98
  EscapableHandleScope scope(env->isolate());
1473
1474
49
  Local<Object> info = Object::New(env->isolate());
1475
1476
49
  BIO* bio = BIO_new(BIO_s_mem());
1477
  BUF_MEM* mem;
1478
49
  if (X509_NAME_print_ex(bio,
1479
                         X509_get_subject_name(cert),
1480
                         0,
1481
                         X509_NAME_FLAGS) > 0) {
1482
49
    BIO_get_mem_ptr(bio, &mem);
1483
294
    info->Set(env->subject_string(),
1484
49
              String::NewFromUtf8(env->isolate(), mem->data,
1485
98
                                  String::kNormalString, mem->length));
1486
  }
1487
49
  (void) BIO_reset(bio);
1488
1489
49
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1490
49
  if (X509_NAME_print_ex(bio, issuer_name, 0, X509_NAME_FLAGS) > 0) {
1491
49
    BIO_get_mem_ptr(bio, &mem);
1492
294
    info->Set(env->issuer_string(),
1493
49
              String::NewFromUtf8(env->isolate(), mem->data,
1494
98
                                  String::kNormalString, mem->length));
1495
  }
1496
49
  (void) BIO_reset(bio);
1497
1498
49
  int nids[] = { NID_subject_alt_name, NID_info_access };
1499
  Local<String> keys[] = { env->subjectaltname_string(),
1500
147
                           env->infoaccess_string() };
1501
49
  CHECK_EQ(arraysize(nids), arraysize(keys));
1502
147
  for (size_t i = 0; i < arraysize(nids); i++) {
1503
98
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1504
98
    if (index < 0)
1505
      continue;
1506
1507
    X509_EXTENSION* ext;
1508
    int rv;
1509
1510
28
    ext = X509_get_ext(cert, index);
1511
28
    CHECK_NE(ext, nullptr);
1512
1513
28
    if (!SafeX509ExtPrint(bio, ext)) {
1514
26
      rv = X509V3_EXT_print(bio, ext, 0, 0);
1515
26
      CHECK_EQ(rv, 1);
1516
    }
1517
1518
28
    BIO_get_mem_ptr(bio, &mem);
1519
140
    info->Set(keys[i],
1520
28
              String::NewFromUtf8(env->isolate(), mem->data,
1521
56
                                  String::kNormalString, mem->length));
1522
1523
28
    (void) BIO_reset(bio);
1524
  }
1525
1526
49
  EVP_PKEY* pkey = X509_get_pubkey(cert);
1527
49
  RSA* rsa = nullptr;
1528
49
  if (pkey != nullptr)
1529
49
    rsa = EVP_PKEY_get1_RSA(pkey);
1530
1531
49
  if (rsa != nullptr) {
1532
48
      BN_print(bio, rsa->n);
1533
48
      BIO_get_mem_ptr(bio, &mem);
1534
288
      info->Set(env->modulus_string(),
1535
48
                String::NewFromUtf8(env->isolate(), mem->data,
1536
96
                                    String::kNormalString, mem->length));
1537
48
      (void) BIO_reset(bio);
1538
1539
48
      BN_ULONG exponent_word = BN_get_word(rsa->e);
1540
48
      BIO_printf(bio, "0x%lx", exponent_word);
1541
1542
48
      BIO_get_mem_ptr(bio, &mem);
1543
288
      info->Set(env->exponent_string(),
1544
48
                String::NewFromUtf8(env->isolate(), mem->data,
1545
96
                                    String::kNormalString, mem->length));
1546
48
      (void) BIO_reset(bio);
1547
  }
1548
1549
49
  if (pkey != nullptr) {
1550
49
    EVP_PKEY_free(pkey);
1551
49
    pkey = nullptr;
1552
  }
1553
49
  if (rsa != nullptr) {
1554
48
    RSA_free(rsa);
1555
48
    rsa = nullptr;
1556
  }
1557
1558
49
  ASN1_TIME_print(bio, X509_get_notBefore(cert));
1559
49
  BIO_get_mem_ptr(bio, &mem);
1560
294
  info->Set(env->valid_from_string(),
1561
49
            String::NewFromUtf8(env->isolate(), mem->data,
1562
98
                                String::kNormalString, mem->length));
1563
49
  (void) BIO_reset(bio);
1564
1565
49
  ASN1_TIME_print(bio, X509_get_notAfter(cert));
1566
49
  BIO_get_mem_ptr(bio, &mem);
1567
294
  info->Set(env->valid_to_string(),
1568
49
            String::NewFromUtf8(env->isolate(), mem->data,
1569
98
                                String::kNormalString, mem->length));
1570
49
  BIO_free_all(bio);
1571
1572
  unsigned int md_size, i;
1573
  unsigned char md[EVP_MAX_MD_SIZE];
1574
49
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1575
49
    const char hex[] = "0123456789ABCDEF";
1576
    char fingerprint[EVP_MAX_MD_SIZE * 3];
1577
1578
    // TODO(indutny): Unify it with buffer's code
1579
1029
    for (i = 0; i < md_size; i++) {
1580
980
      fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1581
980
      fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1582
980
      fingerprint[(3*i)+2] = ':';
1583
    }
1584
1585
49
    if (md_size > 0) {
1586
49
      fingerprint[(3*(md_size-1))+2] = '\0';
1587
    } else {
1588
      fingerprint[0] = '\0';
1589
    }
1590
1591
245
    info->Set(env->fingerprint_string(),
1592
49
              OneByteString(env->isolate(), fingerprint));
1593
  }
1594
1595
  STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
1596
49
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr));
1597
49
  if (eku != nullptr) {
1598
1
    Local<Array> ext_key_usage = Array::New(env->isolate());
1599
    char buf[256];
1600
1601
1
    int j = 0;
1602
2
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1603
1
      if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku, i), 1) >= 0)
1604
3
        ext_key_usage->Set(j++, OneByteString(env->isolate(), buf));
1605
    }
1606
1607
1
    sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1608
3
    info->Set(env->ext_key_usage_string(), ext_key_usage);
1609
  }
1610
1611
49
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1612
49
    if (BIGNUM* bn = ASN1_INTEGER_to_BN(serial_number, nullptr)) {
1613
49
      if (char* buf = BN_bn2hex(bn)) {
1614
245
        info->Set(env->serial_number_string(),
1615
49
                  OneByteString(env->isolate(), buf));
1616
49
        OPENSSL_free(buf);
1617
      }
1618
49
      BN_free(bn);
1619
    }
1620
  }
1621
1622
  // Raw DER certificate
1623
49
  int size = i2d_X509(cert, nullptr);
1624
98
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1625
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1626
49
      Buffer::Data(buff));
1627
49
  i2d_X509(cert, &serialized);
1628
147
  info->Set(env->raw_string(), buff);
1629
1630
98
  return scope.Escape(info);
1631
}
1632
1633
1634
// TODO(indutny): Split it into multiple smaller functions
1635
template <class Base>
1636
49
void SSLWrap<Base>::GetPeerCertificate(
1637
    const FunctionCallbackInfo<Value>& args) {
1638
  Base* w;
1639

49
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1640
97
  Environment* env = w->ssl_env();
1641
1642
  ClearErrorOnReturn clear_error_on_return;
1643
  (void) &clear_error_on_return;  // Silence unused variable warning.
1644
1645
49
  Local<Object> result;
1646
49
  Local<Object> info;
1647
1648
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1649
  // contains the `peer_certificate`, but on server it doesn't
1650

97
  X509* cert = w->is_server() ? SSL_get_peer_certificate(w->ssl_) : nullptr;
1651
49
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_);
1652
49
  STACK_OF(X509)* peer_certs = nullptr;
1653

49
  if (cert == nullptr && ssl_certs == nullptr)
1654
    goto done;
1655
1656



48
  if (cert == nullptr && sk_X509_num(ssl_certs) == 0)
1657
    goto done;
1658
1659
  // Short result requested
1660



144
  if (args.Length() < 1 || !args[0]->IsTrue()) {
1661

47
    result = X509ToObject(env,
1662
                          cert == nullptr ? sk_X509_value(ssl_certs, 0) : cert);
1663
47
    goto done;
1664
  }
1665
1666
  // Clone `ssl_certs`, because we are going to destruct it
1667
1
  peer_certs = sk_X509_new(nullptr);
1668

1
  if (cert != nullptr)
1669
    sk_X509_push(peer_certs, cert);
1670

5
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
1671
2
    cert = X509_dup(sk_X509_value(ssl_certs, i));
1672

2
    if (cert == nullptr)
1673
      goto done;
1674

2
    if (!sk_X509_push(peer_certs, cert))
1675
      goto done;
1676
  }
1677
1678
  // First and main certificate
1679
1
  cert = sk_X509_value(peer_certs, 0);
1680
1
  result = X509ToObject(env, cert);
1681
1
  info = result;
1682
1683
  // Put issuer inside the object
1684
1
  cert = sk_X509_delete(peer_certs, 0);
1685

1
  while (sk_X509_num(peer_certs) > 0) {
1686
    int i;
1687

1
    for (i = 0; i < sk_X509_num(peer_certs); i++) {
1688
1
      X509* ca = sk_X509_value(peer_certs, i);
1689

1
      if (X509_check_issued(ca, cert) != X509_V_OK)
1690
        continue;
1691
1692
1
      Local<Object> ca_info = X509ToObject(env, ca);
1693
3
      info->Set(env->issuercert_string(), ca_info);
1694
1
      info = ca_info;
1695
1696
      // NOTE: Intentionally freeing cert that is not used anymore
1697
1
      X509_free(cert);
1698
1699
      // Delete cert and continue aggregating issuers
1700
1
      cert = sk_X509_delete(peer_certs, i);
1701
1
      break;
1702
    }
1703
1704
    // Issuer not found, break out of the loop
1705

1
    if (i == sk_X509_num(peer_certs))
1706
      break;
1707
  }
1708
1709
  // Last certificate should be self-signed
1710

1
  while (X509_check_issued(cert, cert) != X509_V_OK) {
1711
    X509* ca;
1712
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(w->ssl_), cert, &ca) <= 0)
1713
      break;
1714
1715
    Local<Object> ca_info = X509ToObject(env, ca);
1716
    info->Set(env->issuercert_string(), ca_info);
1717
    info = ca_info;
1718
1719
    // NOTE: Intentionally freeing cert that is not used anymore
1720
    X509_free(cert);
1721
1722
    // Delete cert and continue aggregating issuers
1723
    cert = ca;
1724
  }
1725
1726
  // Self-issued certificate
1727

1
  if (X509_check_issued(cert, cert) == X509_V_OK)
1728
3
    info->Set(env->issuercert_string(), info);
1729
1730

1
  CHECK_NE(cert, nullptr);
1731
1732
 done:
1733

49
  if (cert != nullptr)
1734
8
    X509_free(cert);
1735

49
  if (peer_certs != nullptr)
1736
1
    sk_X509_pop_free(peer_certs, X509_free);
1737

49
  if (result.IsEmpty())
1738
1
    result = Object::New(env->isolate());
1739
98
  args.GetReturnValue().Set(result);
1740
}
1741
1742
1743
template <class Base>
1744
107
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1745
107
  Environment* env = Environment::GetCurrent(args);
1746
1747
  Base* w;
1748

107
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1749
1750
107
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1751

107
  if (sess == nullptr)
1752
    return;
1753
1754
107
  int slen = i2d_SSL_SESSION(sess, nullptr);
1755

107
  CHECK_GT(slen, 0);
1756
1757
107
  char* sbuf = new char[slen];
1758
107
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1759
107
  i2d_SSL_SESSION(sess, &p);
1760
321
  args.GetReturnValue().Set(Encode(env->isolate(), sbuf, slen, BUFFER));
1761

107
  delete[] sbuf;
1762
}
1763
1764
1765
template <class Base>
1766
62
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1767
62
  Environment* env = Environment::GetCurrent(args);
1768
1769
  Base* w;
1770

62
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1771
1772

62
  if (args.Length() < 1) {
1773
    return env->ThrowError("Session argument is mandatory");
1774
  }
1775
1776

62
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Session");
1777
62
  size_t slen = Buffer::Length(args[0]);
1778
62
  char* sbuf = new char[slen];
1779
124
  memcpy(sbuf, Buffer::Data(args[0]), slen);
1780
1781
62
  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1782
62
  SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1783
1784

62
  delete[] sbuf;
1785
1786

62
  if (sess == nullptr)
1787
    return;
1788
1789
62
  int r = SSL_set_session(w->ssl_, sess);
1790
62
  SSL_SESSION_free(sess);
1791
1792

62
  if (!r)
1793
    return env->ThrowError("SSL_set_session error");
1794
}
1795
1796
1797
template <class Base>
1798
8
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1799
  Base* w;
1800

8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1801
13
  Environment* env = w->ssl_env();
1802
1803



16
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1804
5
    ssize_t slen = Buffer::Length(args[0]);
1805
5
    char* sbuf = Buffer::Data(args[0]);
1806
1807
5
    const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1808
5
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1809
1810
    // Setup next session and move hello to the BIO buffer
1811

5
    if (w->next_sess_ != nullptr)
1812
      SSL_SESSION_free(w->next_sess_);
1813
5
    w->next_sess_ = sess;
1814
1815
5
    Local<Object> info = Object::New(env->isolate());
1816
#ifndef OPENSSL_NO_TLSEXT
1817

5
    if (sess->tlsext_hostname == nullptr) {
1818
      info->Set(env->servername_string(), False(args.GetIsolate()));
1819
    } else {
1820
20
      info->Set(env->servername_string(),
1821
5
                OneByteString(args.GetIsolate(), sess->tlsext_hostname));
1822
    }
1823
#endif
1824
10
    args.GetReturnValue().Set(info);
1825
  }
1826
}
1827
1828
1829
template <class Base>
1830
59
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1831
  Base* w;
1832

59
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1833
59
  bool yes = SSL_session_reused(w->ssl_);
1834
177
  args.GetReturnValue().Set(yes);
1835
}
1836
1837
1838
template <class Base>
1839
16
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
1840
  Base* w;
1841

16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1842
16
  w->hello_parser_.End();
1843
}
1844
1845
1846
template <class Base>
1847
1
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1848
  Base* w;
1849

1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1850
1851
  ClearErrorOnReturn clear_error_on_return;
1852
  (void) &clear_error_on_return;  // Silence unused variable warning.
1853
1854
1
  bool yes = SSL_renegotiate(w->ssl_) == 1;
1855
3
  args.GetReturnValue().Set(yes);
1856
}
1857
1858
1859
template <class Base>
1860
2
void SSLWrap<Base>::Shutdown(const FunctionCallbackInfo<Value>& args) {
1861
  Base* w;
1862

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1863
1864
2
  int rv = SSL_shutdown(w->ssl_);
1865
4
  args.GetReturnValue().Set(rv);
1866
}
1867
1868
1869
template <class Base>
1870
9
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1871
  Base* w;
1872

9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1873
18
  Environment* env = w->ssl_env();
1874
1875
9
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1876


9
  if (sess == nullptr || sess->tlsext_tick == nullptr)
1877
    return;
1878
1879
9
  Local<Object> buff = Buffer::Copy(
1880
      env,
1881
      reinterpret_cast<char*>(sess->tlsext_tick),
1882
18
      sess->tlsext_ticklen).ToLocalChecked();
1883
1884
9
  args.GetReturnValue().Set(buff);
1885
}
1886
1887
1888
template <class Base>
1889
2
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1890
  Base* w;
1891

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1892
2
  w->new_session_wait_ = false;
1893
2
  w->NewSessionDoneCb();
1894
}
1895
1896
1897
template <class Base>
1898
2
void SSLWrap<Base>::SetOCSPResponse(
1899
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1900
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1901
  Base* w;
1902

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1903
2
  Environment* env = w->env();
1904
1905

2
  if (args.Length() < 1)
1906
    return env->ThrowTypeError("OCSP response argument is mandatory");
1907
1908

2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "OCSP response");
1909
1910
6
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
1911
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1912
}
1913
1914
1915
template <class Base>
1916
3
void SSLWrap<Base>::RequestOCSP(
1917
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1918
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1919
  Base* w;
1920

3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1921
1922
3
  SSL_set_tlsext_status_type(w->ssl_, TLSEXT_STATUSTYPE_ocsp);
1923
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1924
}
1925
1926
1927
template <class Base>
1928
281
void SSLWrap<Base>::GetEphemeralKeyInfo(
1929
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1930
  Base* w;
1931

281
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1932
281
  Environment* env = Environment::GetCurrent(args);
1933
1934

281
  CHECK_NE(w->ssl_, nullptr);
1935
1936
  // tmp key is available on only client
1937

562
  if (w->is_server())
1938
10
    return args.GetReturnValue().SetNull();
1939
1940
276
  Local<Object> info = Object::New(env->isolate());
1941
1942
  EVP_PKEY* key;
1943
1944

276
  if (SSL_get_server_tmp_key(w->ssl_, &key)) {
1945

241
    switch (EVP_PKEY_id(key)) {
1946
      case EVP_PKEY_DH:
1947
24
        info->Set(env->type_string(),
1948
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH"));
1949
24
        info->Set(env->size_string(),
1950
                  Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1951
6
        break;
1952
      case EVP_PKEY_EC:
1953
        {
1954
235
          EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
1955
235
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
1956
235
          EC_KEY_free(ec);
1957
940
          info->Set(env->type_string(),
1958
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"));
1959
1175
          info->Set(env->name_string(),
1960
                    OneByteString(args.GetIsolate(), OBJ_nid2sn(nid)));
1961
940
          info->Set(env->size_string(),
1962
                    Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1963
        }
1964
    }
1965
241
    EVP_PKEY_free(key);
1966
  }
1967
1968
276
  return args.GetReturnValue().Set(info);
1969
}
1970
1971
1972
#ifdef SSL_set_max_send_fragment
1973
template <class Base>
1974
3
void SSLWrap<Base>::SetMaxSendFragment(
1975
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1976



9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
1977
1978
  Base* w;
1979

3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1980
1981
3
  int rv = SSL_set_max_send_fragment(w->ssl_, args[0]->Int32Value());
1982
6
  args.GetReturnValue().Set(rv);
1983
}
1984
#endif  // SSL_set_max_send_fragment
1985
1986
1987
template <class Base>
1988
23
void SSLWrap<Base>::IsInitFinished(const FunctionCallbackInfo<Value>& args) {
1989
  Base* w;
1990

23
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1991
23
  bool yes = SSL_is_init_finished(w->ssl_);
1992
69
  args.GetReturnValue().Set(yes);
1993
}
1994
1995
1996
template <class Base>
1997
318
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
1998
  Base* w;
1999

378
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2000
2001
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2002
  // peer certificate is questionable but it's compatible with what was
2003
  // here before.
2004
  long x509_verify_error =  // NOLINT(runtime/int)
2005
318
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2006

318
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
2007
315
    X509_free(peer_cert);
2008
315
    x509_verify_error = SSL_get_verify_result(w->ssl_);
2009
  }
2010
2011

318
  if (x509_verify_error == X509_V_OK)
2012
120
    return args.GetReturnValue().SetNull();
2013
2014
  // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
2015
  // in the presence of invalid error codes.  Probably academical but something
2016
  // to keep in mind if/when node ever grows multi-isolate capabilities.
2017
258
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2018
258
  const char* code = reason;
2019
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2020














258
  switch (x509_verify_error) {
2021
3
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2022
5
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2023
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2024
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2025
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2026
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2027
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2028
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2029
29
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2030
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2031
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2032
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2033
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2034
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2035
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2036
    CASE_X509_ERR(OUT_OF_MEM)
2037
120
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2038
4
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2039
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2040
93
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2041
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2042
2
    CASE_X509_ERR(CERT_REVOKED)
2043
    CASE_X509_ERR(INVALID_CA)
2044
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2045
1
    CASE_X509_ERR(INVALID_PURPOSE)
2046
    CASE_X509_ERR(CERT_UNTRUSTED)
2047
    CASE_X509_ERR(CERT_REJECTED)
2048
  }
2049
#undef CASE_X509_ERR
2050
2051
258
  Isolate* isolate = args.GetIsolate();
2052
258
  Local<String> reason_string = OneByteString(isolate, reason);
2053
258
  Local<Value> exception_value = Exception::Error(reason_string);
2054
258
  Local<Object> exception_object = exception_value->ToObject(isolate);
2055
1032
  exception_object->Set(FIXED_ONE_BYTE_STRING(isolate, "code"),
2056
                        OneByteString(isolate, code));
2057
516
  args.GetReturnValue().Set(exception_object);
2058
}
2059
2060
2061
template <class Base>
2062
10
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
2063
  Base* w;
2064

10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2065
19
  Environment* env = w->ssl_env();
2066
2067
10
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
2068

10
  if (c == nullptr)
2069
    return;
2070
2071
10
  Local<Object> info = Object::New(env->isolate());
2072
10
  const char* cipher_name = SSL_CIPHER_get_name(c);
2073
40
  info->Set(env->name_string(), OneByteString(args.GetIsolate(), cipher_name));
2074
10
  const char* cipher_version = SSL_CIPHER_get_version(c);
2075
40
  info->Set(env->version_string(),
2076
            OneByteString(args.GetIsolate(), cipher_version));
2077
10
  args.GetReturnValue().Set(info);
2078
}
2079
2080
2081
template <class Base>
2082
3
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2083
  Base* w;
2084

3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2085
2086
3
  const char* tls_version = SSL_get_version(w->ssl_);
2087
6
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2088
}
2089
2090
2091
#ifdef OPENSSL_NPN_NEGOTIATED
2092
template <class Base>
2093
269
int SSLWrap<Base>::AdvertiseNextProtoCallback(SSL* s,
2094
                                              const unsigned char** data,
2095
                                              unsigned int* len,
2096
                                              void* arg) {
2097
269
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2098
269
  Environment* env = w->env();
2099
538
  HandleScope handle_scope(env->isolate());
2100
807
  Context::Scope context_scope(env->context());
2101
2102
  auto npn_buffer =
2103
269
      w->object()->GetPrivate(
2104
          env->context(),
2105
1076
          env->npn_buffer_private_symbol()).ToLocalChecked();
2106
2107

538
  if (npn_buffer->IsUndefined()) {
2108
    // No initialization - no NPN protocols
2109
159
    *data = reinterpret_cast<const unsigned char*>("");
2110
159
    *len = 0;
2111
  } else {
2112

110
    CHECK(Buffer::HasInstance(npn_buffer));
2113
110
    *data = reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2114
110
    *len = Buffer::Length(npn_buffer);
2115
  }
2116
2117
538
  return SSL_TLSEXT_ERR_OK;
2118
}
2119
2120
2121
template <class Base>
2122
268
int SSLWrap<Base>::SelectNextProtoCallback(SSL* s,
2123
                                           unsigned char** out,
2124
                                           unsigned char* outlen,
2125
                                           const unsigned char* in,
2126
                                           unsigned int inlen,
2127
                                           void* arg) {
2128
268
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2129
268
  Environment* env = w->env();
2130
536
  HandleScope handle_scope(env->isolate());
2131
804
  Context::Scope context_scope(env->context());
2132
2133
  auto npn_buffer =
2134
268
      w->object()->GetPrivate(
2135
          env->context(),
2136
1072
          env->npn_buffer_private_symbol()).ToLocalChecked();
2137
2138

536
  if (npn_buffer->IsUndefined()) {
2139
    // We should at least select one protocol
2140
    // If server is using NPN
2141
247
    *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
2142
247
    *outlen = 8;
2143
2144
    // set status: unsupported
2145

1729
    CHECK(
2146
        w->object()->SetPrivate(
2147
            env->context(),
2148
            env->selected_npn_buffer_private_symbol(),
2149
            False(env->isolate())).FromJust());
2150
2151
    return SSL_TLSEXT_ERR_OK;
2152
  }
2153
2154

21
  CHECK(Buffer::HasInstance(npn_buffer));
2155
  const unsigned char* npn_protos =
2156
21
      reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2157
21
  size_t len = Buffer::Length(npn_buffer);
2158
2159
21
  int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
2160
21
  Local<Value> result;
2161


21
  switch (status) {
2162
    case OPENSSL_NPN_UNSUPPORTED:
2163
      result = Null(env->isolate());
2164
      break;
2165
    case OPENSSL_NPN_NEGOTIATED:
2166
14
      result = OneByteString(env->isolate(), *out, *outlen);
2167
7
      break;
2168
    case OPENSSL_NPN_NO_OVERLAP:
2169
42
      result = False(env->isolate());
2170
14
      break;
2171
    default:
2172
      break;
2173
  }
2174
2175

84
  CHECK(
2176
      w->object()->SetPrivate(
2177
          env->context(),
2178
          env->selected_npn_buffer_private_symbol(),
2179
          result).FromJust());
2180
2181
  return SSL_TLSEXT_ERR_OK;
2182
}
2183
2184
2185
template <class Base>
2186
588
void SSLWrap<Base>::GetNegotiatedProto(
2187
    const FunctionCallbackInfo<Value>& args) {
2188
  Base* w;
2189

912
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2190
588
  Environment* env = w->env();
2191
2192

1175
  if (w->is_client()) {
2193
    auto selected_npn_buffer =
2194
273
        w->object()->GetPrivate(
2195
            env->context(),
2196
1092
            env->selected_npn_buffer_private_symbol()).ToLocalChecked();
2197
273
    args.GetReturnValue().Set(selected_npn_buffer);
2198
    return;
2199
  }
2200
2201
  const unsigned char* npn_proto;
2202
  unsigned int npn_proto_len;
2203
2204
315
  SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
2205
2206

315
  if (!npn_proto)
2207
102
    return args.GetReturnValue().Set(false);
2208
2209
1056
  args.GetReturnValue().Set(
2210
      OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
2211
}
2212
2213
2214
template <class Base>
2215
143
void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
2216
  Base* w;
2217

143
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2218
143
  Environment* env = w->env();
2219
2220

143
  if (args.Length() < 1)
2221
    return env->ThrowTypeError("NPN protocols argument is mandatory");
2222
2223

143
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "NPN protocols");
2224
2225

715
  CHECK(
2226
      w->object()->SetPrivate(
2227
          env->context(),
2228
          env->npn_buffer_private_symbol(),
2229
          args[0]).FromJust());
2230
}
2231
#endif  // OPENSSL_NPN_NEGOTIATED
2232
2233
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2234
template <class Base>
2235
13
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2236
                                      const unsigned char** out,
2237
                                      unsigned char* outlen,
2238
                                      const unsigned char* in,
2239
                                      unsigned int inlen,
2240
                                      void* arg) {
2241
13
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2242
13
  Environment* env = w->env();
2243
26
  HandleScope handle_scope(env->isolate());
2244
39
  Context::Scope context_scope(env->context());
2245
2246
  Local<Value> alpn_buffer =
2247
13
      w->object()->GetPrivate(
2248
          env->context(),
2249
52
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2250

13
  CHECK(Buffer::HasInstance(alpn_buffer));
2251
  const unsigned char* alpn_protos =
2252
13
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2253
13
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2254
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2255
13
                                     alpn_protos, alpn_protos_len, in, inlen);
2256
2257

13
  switch (status) {
2258
    case OPENSSL_NPN_NO_OVERLAP:
2259
      // According to 3.2. Protocol Selection of RFC7301,
2260
      // fatal no_application_protocol alert shall be sent
2261
      // but current openssl does not support it yet. See
2262
      // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2263
      // Instead, we send a warning alert for now.
2264
      return SSL_TLSEXT_ERR_ALERT_WARNING;
2265
    case OPENSSL_NPN_NEGOTIATED:
2266
9
      return SSL_TLSEXT_ERR_OK;
2267
    default:
2268
      return SSL_TLSEXT_ERR_ALERT_FATAL;
2269
  }
2270
}
2271
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2272
2273
2274
template <class Base>
2275
588
void SSLWrap<Base>::GetALPNNegotiatedProto(
2276
    const FunctionCallbackInfo<v8::Value>& args) {
2277
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2278
  Base* w;
2279

1158
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2280
2281
  const unsigned char* alpn_proto;
2282
  unsigned int alpn_proto_len;
2283
2284
588
  SSL_get0_alpn_selected(w->ssl_, &alpn_proto, &alpn_proto_len);
2285
2286

588
  if (!alpn_proto)
2287
1140
    return args.GetReturnValue().Set(false);
2288
2289
72
  args.GetReturnValue().Set(
2290
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2291
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2292
}
2293
2294
2295
template <class Base>
2296
135
void SSLWrap<Base>::SetALPNProtocols(
2297
    const FunctionCallbackInfo<v8::Value>& args) {
2298
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2299
  Base* w;
2300

135
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2301
135
  Environment* env = w->env();
2302



270
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2303
    return env->ThrowTypeError("Must give a Buffer as first argument");
2304
2305

270
  if (w->is_client()) {
2306
    const unsigned char* alpn_protos =
2307
22
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2308
22
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2309
22
    int r = SSL_set_alpn_protos(w->ssl_, alpn_protos, alpn_protos_len);
2310

22
    CHECK_EQ(r, 0);
2311
  } else {
2312

565
    CHECK(
2313
        w->object()->SetPrivate(
2314
          env->context(),
2315
          env->alpn_buffer_private_symbol(),
2316
          args[0]).FromJust());
2317
    // Server should select ALPN protocol from list of advertised by client
2318
113
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_), SelectALPNCallback,
2319
                               nullptr);
2320
  }
2321
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2322
}
2323
2324
2325
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2326
template <class Base>
2327
7
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2328
7
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2329
7
  Environment* env = w->env();
2330
14
  HandleScope handle_scope(env->isolate());
2331
2332

13
  if (w->is_client()) {
2333
    // Incoming response
2334
    const unsigned char* resp;
2335
3
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2336
3
    Local<Value> arg;
2337

3
    if (resp == nullptr) {
2338
3
      arg = Null(env->isolate());
2339
    } else {
2340
6
      arg = Buffer::Copy(
2341
          env,
2342
          reinterpret_cast<char*>(const_cast<unsigned char*>(resp)),
2343
          len).ToLocalChecked();
2344
    }
2345
2346
3
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2347
2348
    // Somehow, client is expecting different return value here
2349
    return 1;
2350
  } else {
2351
    // Outgoing response
2352

8
    if (w->ocsp_response_.IsEmpty())
2353
      return SSL_TLSEXT_ERR_NOACK;
2354
2355
2
    Local<Object> obj = PersistentToLocal(env->isolate(), w->ocsp_response_);
2356
2
    char* resp = Buffer::Data(obj);
2357
2
    size_t len = Buffer::Length(obj);
2358
2359
    // OpenSSL takes control of the pointer after accepting it
2360
2
    char* data = node::Malloc(len);
2361
2
    memcpy(data, resp, len);
2362
2363

2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2364
      free(data);
2365
2
    w->ocsp_response_.Reset();
2366
2367
    return SSL_TLSEXT_ERR_OK;
2368
  }
2369
}
2370
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2371
2372
2373
template <class Base>
2374
21
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2375
21
  cert_cb_ = cb;
2376
21
  cert_cb_arg_ = arg;
2377
21
}
2378
2379
2380
template <class Base>
2381
320
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2382
320
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2383
2384

637
  if (!w->is_server())
2385
    return 1;
2386
2387

597
  if (!w->is_waiting_cert_cb())
2388
    return 1;
2389
2390

21
  if (w->cert_cb_running_)
2391
    return -1;
2392
2393
21
  Environment* env = w->env();
2394
42
  HandleScope handle_scope(env->isolate());
2395
63
  Context::Scope context_scope(env->context());
2396
21
  w->cert_cb_running_ = true;
2397
2398
21
  Local<Object> info = Object::New(env->isolate());
2399
2400
21
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2401

21
  if (servername == nullptr) {
2402
40
    info->Set(env->servername_string(), String::Empty(env->isolate()));
2403
  } else {
2404
13
    Local<String> str = OneByteString(env->isolate(), servername,
2405
26
                                      strlen(servername));
2406
39
    info->Set(env->servername_string(), str);
2407
  }
2408
2409
21
  bool ocsp = false;
2410
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2411
21
  ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp;
2412
#endif
2413
2414
105
  info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp));
2415
2416
42
  Local<Value> argv[] = { info };
2417
42
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2418
2419

21
  if (!w->cert_cb_running_)
2420
    return 1;
2421
2422
  // Performing async action, wait...
2423
9
  return -1;
2424
}
2425
2426
2427
template <class Base>
2428
21
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2429
  Base* w;
2430

21
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2431
21
  Environment* env = w->env();
2432
2433



42
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2434
2435
42
  Local<Object> object = w->object();
2436
42
  Local<Value> ctx = object->Get(env->sni_context_string());
2437
21
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2438
2439
  // Not an object, probably undefined or null
2440

21
  if (!ctx->IsObject())
2441
    goto fire_cb;
2442
2443

10
  if (cons->HasInstance(ctx)) {
2444
    SecureContext* sc;
2445

10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2446
18
    w->sni_context_.Reset();
2447
18
    w->sni_context_.Reset(env->isolate(), ctx);
2448
2449
    int rv;
2450
2451
    // NOTE: reference count is not increased by this API methods
2452
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_);
2453
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_);
2454
    STACK_OF(X509)* chain;
2455
2456
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain);
2457

9
    if (rv)
2458
9
      rv = SSL_use_certificate(w->ssl_, x509);
2459

9
    if (rv)
2460
8
      rv = SSL_use_PrivateKey(w->ssl_, pkey);
2461


9
    if (rv && chain != nullptr)
2462
1
      rv = SSL_set1_chain(w->ssl_, chain);
2463

9
    if (rv)
2464
8
      rv = w->SetCACerts(sc);
2465

9
    if (!rv) {
2466
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2467

1
      if (!err)
2468
        return env->ThrowError("CertCbDone");
2469
1
      return ThrowCryptoError(env, err);
2470
    }
2471
  } else {
2472
    // Failure: incorrect SNI context object
2473
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2474
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2475
    return;
2476
  }
2477
2478
 fire_cb:
2479
  CertCb cb;
2480
  void* arg;
2481
2482
19
  cb = w->cert_cb_;
2483
19
  arg = w->cert_cb_arg_;
2484
2485
19
  w->cert_cb_running_ = false;
2486
19
  w->cert_cb_ = nullptr;
2487
19
  w->cert_cb_arg_ = nullptr;
2488
2489
19
  cb(arg);
2490
}
2491
2492
2493
template <class Base>
2494
2
void SSLWrap<Base>::SSLGetter(Local<String> property,
2495
                              const PropertyCallbackInfo<Value>& info) {
2496
  Base* base;
2497

4
  ASSIGN_OR_RETURN_UNWRAP(&base, info.This());
2498
  SSL* ssl = base->ssl_;
2499
  Local<External> ext = External::New(info.GetIsolate(), ssl);
2500
  info.GetReturnValue().Set(ext);
2501
}
2502
2503
2504
template <class Base>
2505
680
void SSLWrap<Base>::DestroySSL() {
2506

680
  if (ssl_ == nullptr)
2507
    return;
2508
2509
620
  SSL_free(ssl_);
2510
1240
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2511
620
  ssl_ = nullptr;
2512
}
2513
2514
2515
template <class Base>
2516
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2517
  InitNPN(sc);
2518
  CHECK_EQ(SSL_set_SSL_CTX(ssl_, sc->ctx_), sc->ctx_);
2519
2520
  SetCACerts(sc);
2521
}
2522
2523
2524
template <class Base>
2525
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2526
8
  int err = SSL_set1_verify_cert_store(ssl_, SSL_CTX_get_cert_store(sc->ctx_));
2527

8
  if (err != 1)
2528
    return err;
2529
2530
8
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2531
16
      SSL_CTX_get_client_CA_list(sc->ctx_));
2532
2533
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2534
8
  SSL_set_client_CA_list(ssl_, list);
2535
8
  return 1;
2536
}
2537
2538
2539
3
void Connection::OnClientHelloParseEnd(void* arg) {
2540
3
  Connection* conn = static_cast<Connection*>(arg);
2541
2542
  // Write all accumulated data
2543
3
  int r = BIO_write(conn->bio_read_,
2544
                    reinterpret_cast<char*>(conn->hello_data_),
2545
6
                    conn->hello_offset_);
2546
3
  conn->HandleBIOError(conn->bio_read_, "BIO_write", r);
2547
3
  conn->SetShutdownFlags();
2548
3
}
2549
2550
2551
#ifdef SSL_PRINT_DEBUG
2552
# define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
2553
#else
2554
# define DEBUG_PRINT(...)
2555
#endif
2556
2557
2558
27
int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
2559
27
  if (rv >= 0)
2560
    return rv;
2561
2562
17
  int retry = BIO_should_retry(bio);
2563
  (void) retry;  // unused if !defined(SSL_PRINT_DEBUG)
2564
2565
17
  if (BIO_should_write(bio)) {
2566
    DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n",
2567
                ssl_,
2568
                func,
2569
                retry);
2570
    return 0;
2571
2572
17
  } else if (BIO_should_read(bio)) {
2573
    DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
2574
    return 0;
2575
2576
  } else {
2577
    char ssl_error_buf[512];
2578
    ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
2579
2580
    HandleScope scope(ssl_env()->isolate());
2581
    Local<Value> exception =
2582
        Exception::Error(OneByteString(ssl_env()->isolate(), ssl_error_buf));
2583
    object()->Set(ssl_env()->error_string(), exception);
2584
2585
    DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n",
2586
                ssl_,
2587
                func,
2588
                rv,
2589
                ssl_error_buf);
2590
2591
    return rv;
2592
  }
2593
2594
  return 0;
2595
}
2596
2597
2598
25
int Connection::HandleSSLError(const char* func,
2599
                               int rv,
2600
                               ZeroStatus zs,
2601
                               SyscallStatus ss) {
2602
  ClearErrorOnReturn clear_error_on_return;
2603
  (void) &clear_error_on_return;  // Silence unused variable warning.
2604
2605
25
  if (rv > 0)
2606
    return rv;
2607
21
  if (rv == 0 && zs == kZeroIsNotAnError)
2608
    return rv;
2609
2610
20
  int err = SSL_get_error(ssl_, rv);
2611
2612
20
  if (err == SSL_ERROR_NONE) {
2613
    return 0;
2614
2615
20
  } else if (err == SSL_ERROR_WANT_WRITE) {
2616
    DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
2617
    return 0;
2618
2619
20
  } else if (err == SSL_ERROR_WANT_READ) {
2620
    DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
2621
    return 0;
2622
2623
1
  } else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2624
    DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2625
    return 0;
2626
2627
1
  } else if (err == SSL_ERROR_ZERO_RETURN) {
2628
    HandleScope scope(ssl_env()->isolate());
2629
2630
    Local<Value> exception =
2631
        Exception::Error(ssl_env()->zero_return_string());
2632
    object()->Set(ssl_env()->error_string(), exception);
2633
    return rv;
2634
2635
1
  } else if (err == SSL_ERROR_SYSCALL && ss == kIgnoreSyscall) {
2636
    return 0;
2637
2638
  } else {
2639
2
    HandleScope scope(ssl_env()->isolate());
2640
    BUF_MEM* mem;
2641
    BIO *bio;
2642
2643
1
    CHECK(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
2644
2645
    // XXX We need to drain the error queue for this thread or else OpenSSL
2646
    // has the possibility of blocking connections? This problem is not well
2647
    // understood. And we should be somehow propagating these errors up
2648
    // into JavaScript. There is no test which demonstrates this problem.
2649
    // https://github.com/joyent/node/issues/1719
2650
1
    bio = BIO_new(BIO_s_mem());
2651
1
    if (bio != nullptr) {
2652
1
      ERR_print_errors(bio);
2653
1
      BIO_get_mem_ptr(bio, &mem);
2654
      Local<Value> exception = Exception::Error(
2655
          OneByteString(ssl_env()->isolate(),
2656
1
            mem->data,
2657
2
            mem->length));
2658
4
      object()->Set(ssl_env()->error_string(), exception);
2659
1
      BIO_free_all(bio);
2660
    }
2661
2662
    return rv;
2663
  }
2664
2665
  return 0;
2666
}
2667
2668
2669
void Connection::ClearError() {
2670
#ifndef NDEBUG
2671
  HandleScope scope(ssl_env()->isolate());
2672
2673
  // We should clear the error in JS-land
2674
  Local<String> error_key = ssl_env()->error_string();
2675
  Local<Value> error = object()->Get(error_key);
2676
  CHECK_EQ(error->BooleanValue(), false);
2677
#endif  // NDEBUG
2678
}
2679
2680
2681
36
void Connection::SetShutdownFlags() {
2682
72
  HandleScope scope(ssl_env()->isolate());
2683
2684
36
  int flags = SSL_get_shutdown(ssl_);
2685
2686
36
  if (flags & SSL_SENT_SHUTDOWN) {
2687
    Local<String> sent_shutdown_key = ssl_env()->sent_shutdown_string();
2688
    object()->Set(sent_shutdown_key, True(ssl_env()->isolate()));
2689
  }
2690
2691
36
  if (flags & SSL_RECEIVED_SHUTDOWN) {
2692
2
    Local<String> received_shutdown_key = ssl_env()->received_shutdown_string();
2693
5
    object()->Set(received_shutdown_key, True(ssl_env()->isolate()));
2694
  }
2695
36
}
2696
2697
2698
void Connection::NewSessionDoneCb() {
2699
  HandleScope scope(env()->isolate());
2700
2701
  MakeCallback(env()->onnewsessiondone_string(), 0, nullptr);
2702
}
2703
2704
2705
193
void Connection::Initialize(Environment* env, Local<Object> target) {
2706
386
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Connection::New);
2707
386
  t->InstanceTemplate()->SetInternalFieldCount(1);
2708
193
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"));
2709
2710
193
  env->SetProtoMethod(t, "encIn", Connection::EncIn);
2711
193
  env->SetProtoMethod(t, "clearOut", Connection::ClearOut);
2712
193
  env->SetProtoMethod(t, "clearIn", Connection::ClearIn);
2713
193
  env->SetProtoMethod(t, "encOut", Connection::EncOut);
2714
193
  env->SetProtoMethod(t, "clearPending", Connection::ClearPending);
2715
193
  env->SetProtoMethod(t, "encPending", Connection::EncPending);
2716
193
  env->SetProtoMethod(t, "start", Connection::Start);
2717
193
  env->SetProtoMethod(t, "close", Connection::Close);
2718
2719
193
  SSLWrap<Connection>::AddMethods(env, t);
2720
2721
2722
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2723
193
  env->SetProtoMethod(t, "getServername", Connection::GetServername);
2724
193
  env->SetProtoMethod(t, "setSNICallback",  Connection::SetSNICallback);
2725
#endif
2726
2727
965
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"),
2728
193
              t->GetFunction());
2729
193
}
2730
2731
2732
inline int compar(const void* a, const void* b) {
2733
10
  return memcmp(a, b, CNNIC_WHITELIST_HASH_LEN);
2734
}
2735
2736
2737
71
inline int IsSelfSigned(X509* cert) {
2738
71
  return X509_NAME_cmp(X509_get_subject_name(cert),
2739
142
                       X509_get_issuer_name(cert)) == 0;
2740
}
2741
2742
2743
inline X509* FindRoot(STACK_OF(X509)* sk) {
2744
  for (int i = 0; i < sk_X509_num(sk); i++) {
2745
    X509* cert = sk_X509_value(sk, i);
2746
    if (IsSelfSigned(cert))
2747
      return cert;
2748
  }
2749
  return nullptr;
2750
}
2751
2752
2753
// Whitelist check for certs issued by CNNIC. See
2754
// https://blog.mozilla.org/security/2015/04/02
2755
// /distrusting-new-cnnic-certificates/
2756
71
inline CheckResult CheckWhitelistedServerCert(X509_STORE_CTX* ctx) {
2757
  unsigned char hash[CNNIC_WHITELIST_HASH_LEN];
2758
71
  unsigned int hashlen = CNNIC_WHITELIST_HASH_LEN;
2759
2760
71
  STACK_OF(X509)* chain = X509_STORE_CTX_get1_chain(ctx);
2761
71
  CHECK_NE(chain, nullptr);
2762
71
  CHECK_GT(sk_X509_num(chain), 0);
2763
2764
  // Take the last cert as root at the first time.
2765
71
  X509* root_cert = sk_X509_value(chain, sk_X509_num(chain)-1);
2766
71
  X509_NAME* root_name = X509_get_subject_name(root_cert);
2767
2768
71
  if (!IsSelfSigned(root_cert)) {
2769
    root_cert = FindRoot(chain);
2770
    CHECK_NE(root_cert, nullptr);
2771
    root_name = X509_get_subject_name(root_cert);
2772
  }
2773
2774
  // When the cert is issued from either CNNNIC ROOT CA or CNNNIC EV
2775
  // ROOT CA, check a hash of its leaf cert if it is in the whitelist.
2776

141
  if (X509_NAME_cmp(root_name, cnnic_name) == 0 ||
2777
70
      X509_NAME_cmp(root_name, cnnic_ev_name) == 0) {
2778
1
    X509* leaf_cert = sk_X509_value(chain, 0);
2779
1
    int ret = X509_digest(leaf_cert, EVP_sha256(), hash,
2780
1
                          &hashlen);
2781
1
    CHECK(ret);
2782
2783
    void* result = bsearch(hash, WhitelistedCNNICHashes,
2784
                           arraysize(WhitelistedCNNICHashes),
2785
1
                           CNNIC_WHITELIST_HASH_LEN, compar);
2786
1
    if (result == nullptr) {
2787
1
      sk_X509_pop_free(chain, X509_free);
2788
1
      return CHECK_CERT_REVOKED;
2789
    }
2790
  }
2791
2792
70
  sk_X509_pop_free(chain, X509_free);
2793
70
  return CHECK_OK;
2794
}
2795
2796
2797
574
inline int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2798
  // Failure on verification of the cert is handled in
2799
  // Connection::VerifyError.
2800

574
  if (preverify_ok == 0 || X509_STORE_CTX_get_error(ctx) != X509_V_OK)
2801
    return 1;
2802
2803
  // Server does not need to check the whitelist.
2804
  SSL* ssl = static_cast<SSL*>(
2805
101
      X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
2806
2807
101
  if (SSL_is_server(ssl))
2808
    return 1;
2809
2810
  // Client needs to check if the server cert is listed in the
2811
  // whitelist when it is issued by the specific rootCAs.
2812
71
  CheckResult ret = CheckWhitelistedServerCert(ctx);
2813
71
  if (ret == CHECK_CERT_REVOKED)
2814
1
    X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
2815
2816
71
  return ret;
2817
}
2818
2819
2820
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2821
3
int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
2822
3
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(s));
2823
3
  Environment* env = conn->env();
2824
6
  HandleScope scope(env->isolate());
2825
2826
3
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2827
2828
3
  if (servername) {
2829
2
    conn->servername_.Reset(env->isolate(),
2830
4
                            OneByteString(env->isolate(), servername));
2831
2832
    // Call the SNI callback and use its return value as context
2833
4
    if (!conn->sniObject_.IsEmpty()) {
2834
4
      conn->sni_context_.Reset();
2835
2836
      Local<Object> sni_obj = PersistentToLocal(env->isolate(),
2837
2
                                                conn->sniObject_);
2838
2839
4
      Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
2840
      Local<Value> ret = node::MakeCallback(env->isolate(),
2841
                                            sni_obj,
2842
                                            env->onselect_string(),
2843
                                            1,
2844
2
                                            &arg);
2845
2846
      // If ret is SecureContext
2847
      Local<FunctionTemplate> secure_context_constructor_template =
2848
2
          env->secure_context_constructor_template();
2849
2
      if (secure_context_constructor_template->HasInstance(ret)) {
2850
        conn->sni_context_.Reset(env->isolate(), ret);
2851
        SecureContext* sc;
2852
        ASSIGN_OR_RETURN_UNWRAP(&sc, ret.As<Object>(), SSL_TLSEXT_ERR_NOACK);
2853
        conn->SetSNIContext(sc);
2854
      } else {
2855
        return SSL_TLSEXT_ERR_NOACK;
2856
      }
2857
    }
2858
  }
2859
2860
  return SSL_TLSEXT_ERR_OK;
2861
}
2862
#endif
2863
2864
7
void Connection::New(const FunctionCallbackInfo<Value>& args) {
2865
7
  Environment* env = Environment::GetCurrent(args);
2866
2867

21
  if (args.Length() < 1 || !args[0]->IsObject()) {
2868
    env->ThrowError("First argument must be a tls module SecureContext");
2869
    return;
2870
  }
2871
2872
  SecureContext* sc;
2873
12
  ASSIGN_OR_RETURN_UNWRAP(&sc, args[0].As<Object>());
2874
2875
6
  bool is_server = args[1]->BooleanValue();
2876
2877
  SSLWrap<Connection>::Kind kind =
2878
6
      is_server ? SSLWrap<Connection>::kServer : SSLWrap<Connection>::kClient;
2879
6
  Connection* conn = new Connection(env, args.This(), sc, kind);
2880
6
  conn->bio_read_ = NodeBIO::New();
2881
6
  conn->bio_write_ = NodeBIO::New();
2882
2883
6
  SSL_set_app_data(conn->ssl_, conn);
2884
2885
6
  if (is_server)
2886
4
    SSL_set_info_callback(conn->ssl_, SSLInfoCallback);
2887
2888
6
  InitNPN(sc);
2889
2890
6
  SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
2891
2892
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2893
6
  if (is_server) {
2894
4
    SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
2895
4
  } else if (args[2]->IsString()) {
2896
    const node::Utf8Value servername(env->isolate(), args[2]);
2897
    SSL_set_tlsext_host_name(conn->ssl_, *servername);
2898
  }
2899
#endif
2900
2901
6
  SSL_set_bio(conn->ssl_, conn->bio_read_, conn->bio_write_);
2902
2903
#ifdef SSL_MODE_RELEASE_BUFFERS
2904
6
  long mode = SSL_get_mode(conn->ssl_);  // NOLINT(runtime/int)
2905
6
  SSL_set_mode(conn->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
2906
#endif
2907
2908
2909
  int verify_mode;
2910
6
  if (is_server) {
2911
4
    bool request_cert = args[2]->BooleanValue();
2912
4
    if (!request_cert) {
2913
      // Note reject_unauthorized ignored.
2914
      verify_mode = SSL_VERIFY_NONE;
2915
    } else {
2916
      bool reject_unauthorized = args[3]->BooleanValue();
2917
      verify_mode = SSL_VERIFY_PEER;
2918
      if (reject_unauthorized)
2919
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2920
    }
2921
  } else {
2922
    // Note request_cert and reject_unauthorized are ignored for clients.
2923
    verify_mode = SSL_VERIFY_NONE;
2924
  }
2925
2926
2927
  // Always allow a connection. We'll reject in javascript.
2928
6
  SSL_set_verify(conn->ssl_, verify_mode, VerifyCallback);
2929
2930
6
  if (is_server) {
2931
4
    SSL_set_accept_state(conn->ssl_);
2932
  } else {
2933
2
    SSL_set_connect_state(conn->ssl_);
2934
  }
2935
}
2936
2937
2938
48
void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
2939
48
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
2940
43
    return;
2941
2942
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
2943
  // a non-const SSL* in OpenSSL <= 0.9.7e.
2944
5
  SSL* ssl = const_cast<SSL*>(ssl_);
2945
5
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(ssl));
2946
5
  Environment* env = conn->env();
2947
10
  HandleScope handle_scope(env->isolate());
2948
15
  Context::Scope context_scope(env->context());
2949
2950
5
  if (where & SSL_CB_HANDSHAKE_START) {
2951
4
    conn->MakeCallback(env->onhandshakestart_string(), 0, nullptr);
2952
  }
2953
2954
5
  if (where & SSL_CB_HANDSHAKE_DONE) {
2955
1
    conn->MakeCallback(env->onhandshakedone_string(), 0, nullptr);
2956
  }
2957
}
2958
2959
2960
6
void Connection::EncIn(const FunctionCallbackInfo<Value>& args) {
2961
  Connection* conn;
2962
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2963
6
  Environment* env = conn->env();
2964
2965
6
  if (args.Length() < 3) {
2966
    return env->ThrowTypeError(
2967
        "Data, offset, and length arguments are mandatory");
2968
  }
2969
2970
6
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
2971
2972
6
  char* buffer_data = Buffer::Data(args[0]);
2973
6
  size_t buffer_length = Buffer::Length(args[0]);
2974
2975
6
  size_t off = args[1]->Int32Value();
2976
6
  size_t len = args[2]->Int32Value();
2977
2978
6
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
2979
    return env->ThrowRangeError("offset + length > buffer.length");
2980
2981
  int bytes_written;
2982
6
  char* data = buffer_data + off;
2983
2984

6
  if (conn->is_server() && !conn->hello_parser_.IsEnded()) {
2985
    // Just accumulate data, everything will be pushed to BIO later
2986
3
    if (conn->hello_parser_.IsPaused()) {
2987
      bytes_written = 0;
2988
    } else {
2989
      // Copy incoming data to the internal buffer
2990
      // (which has a size of the biggest possible TLS frame)
2991
3
      size_t available = sizeof(conn->hello_data_) - conn->hello_offset_;
2992
3
      size_t copied = len < available ? len : available;
2993
6
      memcpy(conn->hello_data_ + conn->hello_offset_, data, copied);
2994
3
      conn->hello_offset_ += copied;
2995
2996
3
      conn->hello_parser_.Parse(conn->hello_data_, conn->hello_offset_);
2997
3
      bytes_written = copied;
2998
    }
2999
  } else {
3000
3
    bytes_written = BIO_write(conn->bio_read_, data, len);
3001
3
    conn->HandleBIOError(conn->bio_read_, "BIO_write", bytes_written);
3002
3
    conn->SetShutdownFlags();
3003
  }
3004
3005
12
  args.GetReturnValue().Set(bytes_written);
3006
}
3007
3008
3009
16
void Connection::ClearOut(const FunctionCallbackInfo<Value>& args) {
3010
  Connection* conn;
3011
16
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3012
16
  Environment* env = conn->env();
3013
3014
16
  if (args.Length() < 3) {
3015
    return env->ThrowTypeError(
3016
        "Data, offset, and length arguments are mandatory");
3017
  }
3018
3019
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3020
3021
16
  char* buffer_data = Buffer::Data(args[0]);
3022
16
  size_t buffer_length = Buffer::Length(args[0]);
3023
3024
16
  size_t off = args[1]->Int32Value();
3025
16
  size_t len = args[2]->Int32Value();
3026
3027
16
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3028
    return env->ThrowRangeError("offset + length > buffer.length");
3029
3030
16
  if (!SSL_is_init_finished(conn->ssl_)) {
3031
    int rv;
3032
3033
10
    if (conn->is_server()) {
3034
10
      rv = SSL_accept(conn->ssl_);
3035
      conn->HandleSSLError("SSL_accept:ClearOut",
3036
                           rv,
3037
                           kZeroIsAnError,
3038
10
                           kSyscallError);
3039
    } else {
3040
      rv = SSL_connect(conn->ssl_);
3041
      conn->HandleSSLError("SSL_connect:ClearOut",
3042
                           rv,
3043
                           kZeroIsAnError,
3044
                           kSyscallError);
3045
    }
3046
3047
10
    if (rv < 0) {
3048
18
      return args.GetReturnValue().Set(rv);
3049
    }
3050
  }
3051
3052
7
  int bytes_read = SSL_read(conn->ssl_, buffer_data + off, len);
3053
  conn->HandleSSLError("SSL_read:ClearOut",
3054
                       bytes_read,
3055
                       kZeroIsNotAnError,
3056
7
                       kSyscallError);
3057
7
  conn->SetShutdownFlags();
3058
3059
14
  args.GetReturnValue().Set(bytes_read);
3060
}
3061
3062
3063
19
void Connection::ClearPending(const FunctionCallbackInfo<Value>& args) {
3064
  Connection* conn;
3065
19
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3066
19
  int bytes_pending = BIO_pending(conn->bio_read_);
3067
38
  args.GetReturnValue().Set(bytes_pending);
3068
}
3069
3070
3071
26
void Connection::EncPending(const FunctionCallbackInfo<Value>& args) {
3072
  Connection* conn;
3073
26
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3074
26
  int bytes_pending = BIO_pending(conn->bio_write_);
3075
52
  args.GetReturnValue().Set(bytes_pending);
3076
}
3077
3078
3079
21
void Connection::EncOut(const FunctionCallbackInfo<Value>& args) {
3080
  Connection* conn;
3081
21
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3082
21
  Environment* env = conn->env();
3083
3084
21
  if (args.Length() < 3) {
3085
    return env->ThrowTypeError(
3086
        "Data, offset, and length arguments are mandatory");
3087
  }
3088
3089
21
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3090
3091
21
  char* buffer_data = Buffer::Data(args[0]);
3092
21
  size_t buffer_length = Buffer::Length(args[0]);
3093
3094
21
  size_t off = args[1]->Int32Value();
3095
21
  size_t len = args[2]->Int32Value();
3096
3097
21
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3098
    return env->ThrowRangeError("offset + length > buffer.length");
3099
3100
21
  int bytes_read = BIO_read(conn->bio_write_, buffer_data + off, len);
3101
3102
21
  conn->HandleBIOError(conn->bio_write_, "BIO_read:EncOut", bytes_read);
3103
21
  conn->SetShutdownFlags();
3104
3105
42
  args.GetReturnValue().Set(bytes_read);
3106
}
3107
3108
3109
2
void Connection::ClearIn(const FunctionCallbackInfo<Value>& args) {
3110
  Connection* conn;
3111
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3112
2
  Environment* env = conn->env();
3113
3114
2
  if (args.Length() < 3) {
3115
    return env->ThrowTypeError(
3116
        "Data, offset, and length arguments are mandatory");
3117
  }
3118
3119
2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3120
3121
2
  char* buffer_data = Buffer::Data(args[0]);
3122
2
  size_t buffer_length = Buffer::Length(args[0]);
3123
3124
2
  size_t off = args[1]->Int32Value();
3125
2
  size_t len = args[2]->Int32Value();
3126
3127
2
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3128
    return env->ThrowRangeError("offset + length > buffer.length");
3129
3130
2
  if (!SSL_is_init_finished(conn->ssl_)) {
3131
    int rv;
3132
    if (conn->is_server()) {
3133
      rv = SSL_accept(conn->ssl_);
3134
      conn->HandleSSLError("SSL_accept:ClearIn",
3135
                           rv,
3136
                           kZeroIsAnError,
3137
                           kSyscallError);
3138
    } else {
3139
      rv = SSL_connect(conn->ssl_);
3140
      conn->HandleSSLError("SSL_connect:ClearIn",
3141
                           rv,
3142
                           kZeroIsAnError,
3143
                           kSyscallError);
3144
    }
3145
3146
    if (rv < 0) {
3147
      return args.GetReturnValue().Set(rv);
3148
    }
3149
  }
3150
3151
2
  int bytes_written = SSL_write(conn->ssl_, buffer_data + off, len);
3152
3153
2
  conn->HandleSSLError("SSL_write:ClearIn",
3154
                       bytes_written,
3155
                       len == 0 ? kZeroIsNotAnError : kZeroIsAnError,
3156
2
                       kSyscallError);
3157
2
  conn->SetShutdownFlags();
3158
3159
4
  args.GetReturnValue().Set(bytes_written);
3160
}
3161
3162
3163
6
void Connection::Start(const FunctionCallbackInfo<Value>& args) {
3164
  Connection* conn;
3165
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3166
3167
6
  int rv = 0;
3168
6
  if (!SSL_is_init_finished(conn->ssl_)) {
3169
6
    if (conn->is_server()) {
3170
4
      rv = SSL_accept(conn->ssl_);
3171
      conn->HandleSSLError("SSL_accept:Start",
3172
                           rv,
3173
                           kZeroIsAnError,
3174
4
                           kSyscallError);
3175
    } else {
3176
2
      rv = SSL_connect(conn->ssl_);
3177
      conn->HandleSSLError("SSL_connect:Start",
3178
                           rv,
3179
                           kZeroIsAnError,
3180
2
                           kSyscallError);
3181
    }
3182
  }
3183
12
  args.GetReturnValue().Set(rv);
3184
}
3185
3186
3187
2
void Connection::Close(const FunctionCallbackInfo<Value>& args) {
3188
  Connection* conn;
3189
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3190
3191
2
  if (conn->ssl_ != nullptr) {
3192
2
    SSL_free(conn->ssl_);
3193
2
    conn->ssl_ = nullptr;
3194
  }
3195
}
3196
3197
3198
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3199
1
void Connection::GetServername(const FunctionCallbackInfo<Value>& args) {
3200
  Connection* conn;
3201
1
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3202
3203

2
  if (conn->is_server() && !conn->servername_.IsEmpty()) {
3204
    args.GetReturnValue().Set(conn->servername_);
3205
  } else {
3206
2
    args.GetReturnValue().Set(false);
3207
  }
3208
}
3209
3210
3211
2
void Connection::SetSNICallback(const FunctionCallbackInfo<Value>& args) {
3212
  Connection* conn;
3213
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3214
2
  Environment* env = conn->env();
3215
3216

6
  if (args.Length() < 1 || !args[0]->IsFunction()) {
3217
    return env->ThrowError("Must give a Function as first argument");
3218
  }
3219
3220
2
  Local<Object> obj = Object::New(env->isolate());
3221
6
  obj->Set(FIXED_ONE_BYTE_STRING(args.GetIsolate(), "onselect"), args[0]);
3222
2
  conn->sniObject_.Reset(args.GetIsolate(), obj);
3223
}
3224
#endif
3225
3226
3227
193
void CipherBase::Initialize(Environment* env, Local<Object> target) {
3228
386
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3229
3230
386
  t->InstanceTemplate()->SetInternalFieldCount(1);
3231
3232
193
  env->SetProtoMethod(t, "init", Init);
3233
193
  env->SetProtoMethod(t, "initiv", InitIv);
3234
193
  env->SetProtoMethod(t, "update", Update);
3235
193
  env->SetProtoMethod(t, "final", Final);
3236
193
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
3237
193
  env->SetProtoMethod(t, "getAuthTag", GetAuthTag);
3238
193
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
3239
193
  env->SetProtoMethod(t, "setAAD", SetAAD);
3240
3241
965
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
3242
193
              t->GetFunction());
3243
193
}
3244
3245
3246
1001
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
3247
1001
  CHECK_EQ(args.IsConstructCall(), true);
3248
1001
  CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher;
3249
1001
  Environment* env = Environment::GetCurrent(args);
3250
1001
  new CipherBase(env, args.This(), kind);
3251
1001
}
3252
3253
3254
36
void CipherBase::Init(const char* cipher_type,
3255
                      const char* key_buf,
3256
                      int key_buf_len) {
3257
72
  HandleScope scope(env()->isolate());
3258
3259
#ifdef NODE_FIPS_MODE
3260
  if (FIPS_mode()) {
3261
    return env()->ThrowError(
3262
        "crypto.createCipher() is not supported in FIPS mode.");
3263
  }
3264
#endif  // NODE_FIPS_MODE
3265
3266
36
  CHECK_EQ(cipher_, nullptr);
3267
36
  cipher_ = EVP_get_cipherbyname(cipher_type);
3268
36
  if (cipher_ == nullptr) {
3269
    return env()->ThrowError("Unknown cipher");
3270
  }
3271
3272
  unsigned char key[EVP_MAX_KEY_LENGTH];
3273
  unsigned char iv[EVP_MAX_IV_LENGTH];
3274
3275
36
  int key_len = EVP_BytesToKey(cipher_,
3276
                               EVP_md5(),
3277
                               nullptr,
3278
                               reinterpret_cast<const unsigned char*>(key_buf),
3279
                               key_buf_len,
3280
                               1,
3281
                               key,
3282
36
                               iv);
3283
3284
36
  EVP_CIPHER_CTX_init(&ctx_);
3285
36
  const bool encrypt = (kind_ == kCipher);
3286
36
  EVP_CipherInit_ex(&ctx_, cipher_, nullptr, nullptr, nullptr, encrypt);
3287
36
  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3288
    EVP_CIPHER_CTX_cleanup(&ctx_);
3289
    return env()->ThrowError("Invalid key length");
3290
  }
3291
3292
36
  EVP_CipherInit_ex(&ctx_,
3293
                    nullptr,
3294
                    nullptr,
3295
                    reinterpret_cast<unsigned char*>(key),
3296
                    reinterpret_cast<unsigned char*>(iv),
3297
72
                    kind_ == kCipher);
3298
36
  initialised_ = true;
3299
}
3300
3301
3302
36
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
3303
  CipherBase* cipher;
3304
36
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3305
36
  Environment* env = cipher->env();
3306
3307
36
  if (args.Length() < 2) {
3308
    return env->ThrowError("Cipher type and key arguments are mandatory");
3309
  }
3310
3311
72
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3312
36
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3313
3314
108
  const node::Utf8Value cipher_type(args.GetIsolate(), args[0]);
3315
36
  const char* key_buf = Buffer::Data(args[1]);
3316
36
  ssize_t key_buf_len = Buffer::Length(args[1]);
3317
36
  cipher->Init(*cipher_type, key_buf, key_buf_len);
3318
}
3319
3320
3321
965
void CipherBase::InitIv(const char* cipher_type,
3322
                        const char* key,
3323
                        int key_len,
3324
                        const char* iv,
3325
                        int iv_len) {
3326
1395
  HandleScope scope(env()->isolate());
3327
3328
965
  cipher_ = EVP_get_cipherbyname(cipher_type);
3329
965
  if (cipher_ == nullptr) {
3330
535
    return env()->ThrowError("Unknown cipher");
3331
  }
3332
3333
965
  const int expected_iv_len = EVP_CIPHER_iv_length(cipher_);
3334
965
  const bool is_gcm_mode = (EVP_CIPH_GCM_MODE == EVP_CIPHER_mode(cipher_));
3335
3336
965
  if (is_gcm_mode == false && iv_len != expected_iv_len) {
3337
510
    return env()->ThrowError("Invalid IV length");
3338
  }
3339
3340
455
  EVP_CIPHER_CTX_init(&ctx_);
3341
455
  const bool encrypt = (kind_ == kCipher);
3342
455
  EVP_CipherInit_ex(&ctx_, cipher_, nullptr, nullptr, nullptr, encrypt);
3343
3344

855
  if (is_gcm_mode &&
3345
400
      !EVP_CIPHER_CTX_ctrl(&ctx_, EVP_CTRL_GCM_SET_IVLEN, iv_len, nullptr)) {
3346
25
    EVP_CIPHER_CTX_cleanup(&ctx_);
3347
25
    return env()->ThrowError("Invalid IV length");
3348
  }
3349
3350
430
  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3351
    EVP_CIPHER_CTX_cleanup(&ctx_);
3352
    return env()->ThrowError("Invalid key length");
3353
  }
3354
3355
430
  EVP_CipherInit_ex(&ctx_,
3356
                    nullptr,
3357
                    nullptr,
3358
                    reinterpret_cast<const unsigned char*>(key),
3359
                    reinterpret_cast<const unsigned char*>(iv),
3360
860
                    kind_ == kCipher);
3361
430
  initialised_ = true;
3362
}
3363
3364
3365
965
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
3366
  CipherBase* cipher;
3367
965
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3368
965
  Environment* env = cipher->env();
3369
3370
965
  if (args.Length() < 3) {
3371
    return env->ThrowError("Cipher type, key, and IV arguments are mandatory");
3372
  }
3373
3374
1930
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3375
965
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3376
965
  THROW_AND_RETURN_IF_NOT_BUFFER(args[2], "IV");
3377
3378
1930
  const node::Utf8Value cipher_type(env->isolate(), args[0]);
3379
965
  ssize_t key_len = Buffer::Length(args[1]);
3380
965
  const char* key_buf = Buffer::Data(args[1]);
3381
965
  ssize_t iv_len = Buffer::Length(args[2]);
3382
965
  const char* iv_buf = Buffer::Data(args[2]);
3383
965
  cipher->InitIv(*cipher_type, key_buf, key_len, iv_buf, iv_len);
3384
}
3385
3386
3387
bool CipherBase::IsAuthenticatedMode() const {
3388
  // check if this cipher operates in an AEAD mode that we support.
3389



217
  if (!cipher_)
3390
    return false;
3391
217
  int mode = EVP_CIPHER_mode(cipher_);
3392
217
  return mode == EVP_CIPH_GCM_MODE;
3393
}
3394
3395
3396
74
bool CipherBase::GetAuthTag(char** out, unsigned int* out_len) const {
3397
  // only callable after Final and if encrypting.
3398

74
  if (initialised_ || kind_ != kCipher || !auth_tag_)
3399
    return false;
3400
25
  *out_len = auth_tag_len_;
3401
50
  *out = node::Malloc(auth_tag_len_);
3402
50
  memcpy(*out, auth_tag_, auth_tag_len_);
3403
25
  return true;
3404
}
3405
3406
3407
74
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
3408
74
  Environment* env = Environment::GetCurrent(args);
3409
  CipherBase* cipher;
3410
74
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3411
3412
74
  char* out = nullptr;
3413
74
  unsigned int out_len = 0;
3414
3415
74
  if (cipher->GetAuthTag(&out, &out_len)) {
3416
50
    Local<Object> buf = Buffer::New(env, out, out_len).ToLocalChecked();
3417
25
    args.GetReturnValue().Set(buf);
3418
  } else {
3419
    env->ThrowError("Attempting to get auth tag in unsupported state");
3420
  }
3421
}
3422
3423
3424
50
bool CipherBase::SetAuthTag(const char* data, unsigned int len) {
3425


100
  if (!initialised_ || !IsAuthenticatedMode() || kind_ != kDecipher)
3426
    return false;
3427
26
  delete[] auth_tag_;
3428
26
  auth_tag_len_ = len;
3429
26
  auth_tag_ = new char[len];
3430
52
  memcpy(auth_tag_, data, len);
3431
26
  return true;
3432
}
3433
3434
3435
50
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
3436
50
  Environment* env = Environment::GetCurrent(args);
3437
3438
100
  Local<Object> buf = args[0].As<Object>();
3439
3440

50
  if (!buf->IsObject() || !Buffer::HasInstance(buf))
3441
    return env->ThrowTypeError("Auth tag must be a Buffer");
3442
3443
  CipherBase* cipher;
3444
50
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3445
3446
50
  if (!cipher->SetAuthTag(Buffer::Data(buf), Buffer::Length(buf)))
3447
    env->ThrowError("Attempting to set auth tag in unsupported state");
3448
}
3449
3450
3451
26
bool CipherBase::SetAAD(const char* data, unsigned int len) {
3452

51
  if (!initialised_ || !IsAuthenticatedMode())
3453
    return false;
3454
  int outlen;
3455
25
  if (!EVP_CipherUpdate(&ctx_,
3456
                        nullptr,
3457
                        &outlen,
3458
                        reinterpret_cast<const unsigned char*>(data),
3459
                        len)) {
3460
    return false;
3461
  }
3462
25
  return true;
3463
}
3464
3465
3466
26
void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
3467
26
  Environment* env = Environment::GetCurrent(args);
3468
3469
26