GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/out/../src/node_crypto.cc Lines: 2492 2765 90.1 %
Date: 2016-09-10 Branches: 1131 2164 52.3 %

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
1637
static X509_NAME* cnnic_name =
99
1637
    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
1637
static X509_NAME *cnnic_ev_name =
114
1637
    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
X509_STORE* root_cert_store;
124
125
// Just to generate static methods
126
template class SSLWrap<TLSWrap>;
127
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
128
                                           Local<FunctionTemplate> t);
129
template void SSLWrap<TLSWrap>::InitNPN(SecureContext* sc);
130
template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc);
131
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
132
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
133
    SSL* s,
134
    unsigned char* key,
135
    int len,
136
    int* copy);
137
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
138
                                                  SSL_SESSION* sess);
139
template void SSLWrap<TLSWrap>::OnClientHello(
140
    void* arg,
141
    const ClientHelloParser::ClientHello& hello);
142
143
#ifdef OPENSSL_NPN_NEGOTIATED
144
template int SSLWrap<TLSWrap>::AdvertiseNextProtoCallback(
145
    SSL* s,
146
    const unsigned char** data,
147
    unsigned int* len,
148
    void* arg);
149
template int SSLWrap<TLSWrap>::SelectNextProtoCallback(
150
    SSL* s,
151
    unsigned char** out,
152
    unsigned char* outlen,
153
    const unsigned char* in,
154
    unsigned int inlen,
155
    void* arg);
156
#endif
157
158
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
159
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
160
#endif
161
162
template void SSLWrap<TLSWrap>::DestroySSL();
163
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
164
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
165
166
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
167
template int SSLWrap<TLSWrap>::SelectALPNCallback(
168
    SSL* s,
169
    const unsigned char** out,
170
    unsigned char* outlen,
171
    const unsigned char* in,
172
    unsigned int inlen,
173
    void* arg);
174
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
175
176
43149
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
177
  static_assert(sizeof(uv_thread_t) <= sizeof(void*),
178
                "uv_thread_t does not fit in a pointer");
179
43149
  CRYPTO_THREADID_set_pointer(tid, reinterpret_cast<void*>(uv_thread_self()));
180
43149
}
181
182
183
182
static void crypto_lock_init(void) {
184

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

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

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

408
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
611
204
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
612
204
    ERR_clear_error();
613
  } else  {
614
    // some real error
615
    goto done;
616
  }
617
618
204
  ret = SSL_CTX_use_certificate_chain(ctx, x, extra_certs, cert, issuer);
619
  if (!ret)
620
    goto done;
621
622
 done:
623
204
  if (extra_certs != nullptr)
624
204
    sk_X509_pop_free(extra_certs, X509_free);
625
204
  if (extra != nullptr)
626
    X509_free(extra);
627
204
  if (x != nullptr)
628
204
    X509_free(x);
629
630
  return ret;
631
}
632
633
634
204
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
635
204
  Environment* env = Environment::GetCurrent(args);
636
637
  SecureContext* sc;
638
204
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
639
640
204
  if (args.Length() != 1) {
641
    return env->ThrowTypeError("Certificate argument is mandatory");
642
  }
643
644
204
  BIO* bio = LoadBIO(env, args[0]);
645
204
  if (!bio)
646
    return;
647
648
  // Free previous certs
649
204
  if (sc->issuer_ != nullptr) {
650
    X509_free(sc->issuer_);
651
    sc->issuer_ = nullptr;
652
  }
653
204
  if (sc->cert_ != nullptr) {
654
1
    X509_free(sc->cert_);
655
1
    sc->cert_ = nullptr;
656
  }
657
658
204
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_,
659
                                         bio,
660
                                         &sc->cert_,
661
204
                                         &sc->issuer_);
662
663
204
  BIO_free_all(bio);
664
665
204
  if (!rv) {
666
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
667
    if (!err) {
668
      return env->ThrowError("SSL_CTX_use_certificate_chain");
669
    }
670
    return ThrowCryptoError(env, err);
671
  }
672
}
673
674
675
89
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
676
89
  bool newCAStore = false;
677
89
  Environment* env = Environment::GetCurrent(args);
678
679
  SecureContext* sc;
680
89
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
681
  ClearErrorOnReturn clear_error_on_return;
682
  (void) &clear_error_on_return;  // Silence compiler warning.
683
684
89
  if (args.Length() != 1) {
685
    return env->ThrowTypeError("CA certificate argument is mandatory");
686
  }
687
688
89
  if (!sc->ca_store_) {
689
75
    sc->ca_store_ = X509_STORE_new();
690
75
    newCAStore = true;
691
  }
692
693
89
  unsigned cert_count = 0;
694
89
  if (BIO* bio = LoadBIO(env, args[0])) {
695
91
    while (X509* x509 =
696
180
        PEM_read_bio_X509(bio, nullptr, CryptoPemCallback, nullptr)) {
697
91
      X509_STORE_add_cert(sc->ca_store_, x509);
698
91
      SSL_CTX_add_client_CA(sc->ctx_, x509);
699
91
      X509_free(x509);
700
91
      cert_count += 1;
701
    }
702
89
    BIO_free_all(bio);
703
  }
704
705
89
  if (cert_count > 0 && newCAStore) {
706
74
    SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
707
  }
708
}
709
710
711
6
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
712
6
  Environment* env = Environment::GetCurrent(args);
713
714
  SecureContext* sc;
715
6
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
716
717
6
  if (args.Length() != 1) {
718
    return env->ThrowTypeError("CRL argument is mandatory");
719
  }
720
721
  ClearErrorOnReturn clear_error_on_return;
722
  (void) &clear_error_on_return;  // Silence compiler warning.
723
724
6
  BIO *bio = LoadBIO(env, args[0]);
725
6
  if (!bio)
726
    return;
727
728
  X509_CRL *x509 =
729
6
      PEM_read_bio_X509_CRL(bio, nullptr, CryptoPemCallback, nullptr);
730
731
6
  if (x509 == nullptr) {
732
    BIO_free_all(bio);
733
    return;
734
  }
735
736
6
  X509_STORE_add_crl(sc->ca_store_, x509);
737
6
  X509_STORE_set_flags(sc->ca_store_, X509_V_FLAG_CRL_CHECK |
738
6
                                      X509_V_FLAG_CRL_CHECK_ALL);
739
6
  BIO_free_all(bio);
740
6
  X509_CRL_free(x509);
741
}
742
743
744
745
420
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
746
  SecureContext* sc;
747
420
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
748
  ClearErrorOnReturn clear_error_on_return;
749
  (void) &clear_error_on_return;  // Silence compiler warning.
750
751
420
  CHECK_EQ(sc->ca_store_, nullptr);
752
753
420
  if (!root_cert_store) {
754
124
    root_cert_store = X509_STORE_new();
755
756
18724
    for (size_t i = 0; i < arraysize(root_certs); i++) {
757
18600
      BIO* bp = NodeBIO::NewFixed(root_certs[i], strlen(root_certs[i]));
758
18600
      if (bp == nullptr) {
759
        return;
760
      }
761
762
18600
      X509 *x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr);
763
18600
      if (x509 == nullptr) {
764
        BIO_free_all(bp);
765
        return;
766
      }
767
768
18600
      X509_STORE_add_cert(root_cert_store, x509);
769
770
18600
      BIO_free_all(bp);
771
18600
      X509_free(x509);
772
    }
773
  }
774
775
420
  sc->ca_store_ = root_cert_store;
776
420
  SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
777
}
778
779
780
495
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
781
  SecureContext* sc;
782
497
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
783
495
  Environment* env = sc->env();
784
  ClearErrorOnReturn clear_error_on_return;
785
  (void) &clear_error_on_return;  // Silence compiler warning.
786
787
495
  if (args.Length() != 1) {
788
    return env->ThrowTypeError("Ciphers argument is mandatory");
789
  }
790
791
990
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Ciphers");
792
793
1479
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
794
493
  SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
795
}
796
797
798
491
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
799
  SecureContext* sc;
800
492
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
801
491
  Environment* env = sc->env();
802
803
491
  if (args.Length() != 1)
804
    return env->ThrowTypeError("ECDH curve name argument is mandatory");
805
806
982
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "ECDH curve name");
807
808
980
  node::Utf8Value curve(env->isolate(), args[0]);
809
810
490
  int nid = OBJ_sn2nid(*curve);
811
812
490
  if (nid == NID_undef)
813
    return env->ThrowTypeError("First argument should be a valid curve name");
814
815
490
  EC_KEY* ecdh = EC_KEY_new_by_curve_name(nid);
816
817
490
  if (ecdh == nullptr)
818
    return env->ThrowTypeError("First argument should be a valid curve name");
819
820
490
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_ECDH_USE);
821
490
  SSL_CTX_set_tmp_ecdh(sc->ctx_, ecdh);
822
823
490
  EC_KEY_free(ecdh);
824
}
825
826
827
9
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
828
  SecureContext* sc;
829
9
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
830
9
  Environment* env = sc->env();
831
  ClearErrorOnReturn clear_error_on_return;
832
  (void) &clear_error_on_return;  // Silence compiler warning.
833
834
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
835
  // to be specifed explicitly
836
9
  if (args.Length() != 1)
837
    return env->ThrowTypeError("DH argument is mandatory");
838
839
  // Invalid dhparam is silently discarded and DHE is no longer used.
840
9
  BIO* bio = LoadBIO(env, args[0]);
841
9
  if (!bio)
842
    return;
843
844
9
  DH* dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
845
9
  BIO_free_all(bio);
846
847
9
  if (dh == nullptr)
848
    return;
849
850
8
  const int size = BN_num_bits(dh->p);
851
8
  if (size < 1024) {
852
    return env->ThrowError("DH parameter is less than 1024 bits");
853
6
  } else if (size < 2048) {
854
6
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
855
        env->isolate(), "WARNING: DH parameter is less than 2048 bits"));
856
  }
857
858
6
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE);
859
6
  int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh);
860
6
  DH_free(dh);
861
862
6
  if (!r)
863
    return env->ThrowTypeError("Error setting temp DH parameter");
864
}
865
866
867
178
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
868
  SecureContext* sc;
869
178
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
870
871

534
  if (args.Length() != 1 || !args[0]->IntegerValue()) {
872
    return sc->env()->ThrowTypeError("Options must be an integer value");
873
  }
874
875
178
  SSL_CTX_set_options(
876
      sc->ctx_,
877
178
      static_cast<long>(args[0]->IntegerValue()));  // NOLINT(runtime/int)
878
}
879
880
881
173
void SecureContext::SetSessionIdContext(
882
    const FunctionCallbackInfo<Value>& args) {
883
  SecureContext* sc;
884
346
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
885
173
  Environment* env = sc->env();
886
887
173
  if (args.Length() != 1) {
888
    return env->ThrowTypeError("Session ID context argument is mandatory");
889
  }
890
891
346
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Session ID context");
892
893
346
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
894
  const unsigned char* sid_ctx =
895
173
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
896
173
  unsigned int sid_ctx_len = sessionIdContext.length();
897
898
173
  int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
899
173
  if (r == 1)
900
    return;
901
902
  BIO* bio;
903
  BUF_MEM* mem;
904
  Local<String> message;
905
906
  bio = BIO_new(BIO_s_mem());
907
  if (bio == nullptr) {
908
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
909
                                    "SSL_CTX_set_session_id_context error");
910
  } else {
911
    ERR_print_errors(bio);
912
    BIO_get_mem_ptr(bio, &mem);
913
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
914
    BIO_free_all(bio);
915
  }
916
917
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
918
}
919
920
921
1
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
922
  SecureContext* sc;
923
1
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
924
925

3
  if (args.Length() != 1 || !args[0]->IsInt32()) {
926
1
    return sc->env()->ThrowTypeError(
927
        "Session timeout must be a 32-bit integer");
928
  }
929
930
  int32_t sessionTimeout = args[0]->Int32Value();
931
  SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
932
}
933
934
935
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
936
  SecureContext* sc;
937
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
938
  sc->FreeCTXMem();
939
}
940
941
942
// Takes .pfx or .p12 and password in string or buffer format
943
13
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
944
13
  Environment* env = Environment::GetCurrent(args);
945
946
13
  BIO* in = nullptr;
947
13
  PKCS12* p12 = nullptr;
948
13
  EVP_PKEY* pkey = nullptr;
949
13
  X509* cert = nullptr;
950
13
  STACK_OF(X509)* extra_certs = nullptr;
951
13
  char* pass = nullptr;
952
13
  bool ret = false;
953
954
  SecureContext* sc;
955
19
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
956
  ClearErrorOnReturn clear_error_on_return;
957
  (void) &clear_error_on_return;  // Silence compiler warning.
958
959
13
  if (args.Length() < 1) {
960
    return env->ThrowTypeError("PFX certificate argument is mandatory");
961
  }
962
963
13
  in = LoadBIO(env, args[0]);
964
13
  if (in == nullptr) {
965
    return env->ThrowError("Unable to load BIO");
966
  }
967
968
13
  if (args.Length() >= 2) {
969
11
    THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Pass phrase");
970
11
    size_t passlen = Buffer::Length(args[1]);
971
11
    pass = new char[passlen + 1];
972
22
    memcpy(pass, Buffer::Data(args[1]), passlen);
973
11
    pass[passlen] = '\0';
974
  }
975
976
  // Free previous certs
977
13
  if (sc->issuer_ != nullptr) {
978
    X509_free(sc->issuer_);
979
    sc->issuer_ = nullptr;
980
  }
981
13
  if (sc->cert_ != nullptr) {
982
    X509_free(sc->cert_);
983
    sc->cert_ = nullptr;
984
  }
985
986

37
  if (d2i_PKCS12_bio(in, &p12) &&
987
18
      PKCS12_parse(p12, pass, &pkey, &cert, &extra_certs) &&
988
7
      SSL_CTX_use_certificate_chain(sc->ctx_,
989
                                    cert,
990
                                    extra_certs,
991
                                    &sc->cert_,
992

20
                                    &sc->issuer_) &&
993
7
      SSL_CTX_use_PrivateKey(sc->ctx_, pkey)) {
994
    // Add CA certs too
995
13
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
996
3
      X509* ca = sk_X509_value(extra_certs, i);
997
998
3
      if (!sc->ca_store_) {
999
        sc->ca_store_ = X509_STORE_new();
1000
        SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
1001
      }
1002
3
      X509_STORE_add_cert(sc->ca_store_, ca);
1003
3
      SSL_CTX_add_client_CA(sc->ctx_, ca);
1004
    }
1005
    ret = true;
1006
  }
1007
1008
13
  if (pkey != nullptr)
1009
7
    EVP_PKEY_free(pkey);
1010
13
  if (cert != nullptr)
1011
7
    X509_free(cert);
1012
13
  if (extra_certs != nullptr)
1013
3
    sk_X509_pop_free(extra_certs, X509_free);
1014
1015
13
  PKCS12_free(p12);
1016
13
  BIO_free_all(in);
1017
13
  delete[] pass;
1018
1019
13
  if (!ret) {
1020
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1021
6
    const char* str = ERR_reason_error_string(err);
1022
    return env->ThrowError(str);
1023
  }
1024
}
1025
1026
1027
7
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1028
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1029
1030
  SecureContext* wrap;
1031
7
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1032
1033
14
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1034
7
  if (SSL_CTX_get_tlsext_ticket_keys(wrap->ctx_,
1035
                                     Buffer::Data(buff),
1036
                                     Buffer::Length(buff)) != 1) {
1037
    return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
1038
  }
1039
1040
7
  args.GetReturnValue().Set(buff);
1041
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1042
}
1043
1044
1045
16
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1046
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1047
  SecureContext* wrap;
1048
16
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1049
16
  Environment* env = wrap->env();
1050
1051
16
  if (args.Length() < 1) {
1052
    return env->ThrowTypeError("Ticket keys argument is mandatory");
1053
  }
1054
1055
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Ticket keys");
1056
1057
15
  if (Buffer::Length(args[0]) != 48) {
1058
    return env->ThrowTypeError("Ticket keys length must be 48 bytes");
1059
  }
1060
1061
28
  if (SSL_CTX_set_tlsext_ticket_keys(wrap->ctx_,
1062
                                     Buffer::Data(args[0]),
1063
                                     Buffer::Length(args[0])) != 1) {
1064
    return env->ThrowError("Failed to fetch tls ticket keys");
1065
  }
1066
1067
28
  args.GetReturnValue().Set(true);
1068
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1069
}
1070
1071
1072
274
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1073
  SecureContext* wrap;
1074
274
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1075
1076
548
  wrap->ctx_->freelist_max_len = args[0]->Int32Value();
1077
}
1078
1079
1080
1
void SecureContext::EnableTicketKeyCallback(
1081
    const FunctionCallbackInfo<Value>& args) {
1082
  SecureContext* wrap;
1083
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1084
1085
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_, TicketKeyCallback);
1086
}
1087
1088
1089
3
int SecureContext::TicketKeyCallback(SSL* ssl,
1090
                                     unsigned char* name,
1091
                                     unsigned char* iv,
1092
                                     EVP_CIPHER_CTX* ectx,
1093
                                     HMAC_CTX* hctx,
1094
                                     int enc) {
1095
  static const int kTicketPartSize = 16;
1096
1097
  SecureContext* sc = static_cast<SecureContext*>(
1098
3
      SSL_CTX_get_app_data(ssl->ctx));
1099
1100
3
  Environment* env = sc->env();
1101
6
  HandleScope handle_scope(env->isolate());
1102
9
  Context::Scope context_scope(env->context());
1103
1104
  Local<Value> argv[] = {
1105
3
    Buffer::Copy(env,
1106
                 reinterpret_cast<char*>(name),
1107
                 kTicketPartSize).ToLocalChecked(),
1108
3
    Buffer::Copy(env,
1109
                 reinterpret_cast<char*>(iv),
1110
                 kTicketPartSize).ToLocalChecked(),
1111
    Boolean::New(env->isolate(), enc != 0)
1112
18
  };
1113
  Local<Value> ret = node::MakeCallback(env,
1114
                                        sc->object(),
1115
                                        env->ticketkeycallback_string(),
1116
3
                                        arraysize(argv),
1117
9
                                        argv);
1118
3
  Local<Array> arr = ret.As<Array>();
1119
1120
6
  int r = arr->Get(kTicketKeyReturnIndex)->Int32Value();
1121
3
  if (r < 0)
1122
    return r;
1123
1124
3
  Local<Value> hmac = arr->Get(kTicketKeyHMACIndex);
1125
3
  Local<Value> aes = arr->Get(kTicketKeyAESIndex);
1126
3
  if (Buffer::Length(aes) != kTicketPartSize)
1127
    return -1;
1128
1129
3
  if (enc) {
1130
2
    Local<Value> name_val = arr->Get(kTicketKeyNameIndex);
1131
2
    Local<Value> iv_val = arr->Get(kTicketKeyIVIndex);
1132
1133

4
    if (Buffer::Length(name_val) != kTicketPartSize ||
1134
2
        Buffer::Length(iv_val) != kTicketPartSize) {
1135
      return -1;
1136
    }
1137
1138
4
    memcpy(name, Buffer::Data(name_val), kTicketPartSize);
1139
4
    memcpy(iv, Buffer::Data(iv_val), kTicketPartSize);
1140
  }
1141
1142
6
  HMAC_Init_ex(hctx,
1143
3
               Buffer::Data(hmac),
1144
3
               Buffer::Length(hmac),
1145
               EVP_sha256(),
1146
3
               nullptr);
1147
1148
  const unsigned char* aes_key =
1149
3
      reinterpret_cast<unsigned char*>(Buffer::Data(aes));
1150
3
  if (enc) {
1151
2
    EVP_EncryptInit_ex(ectx,
1152
                       EVP_aes_128_cbc(),
1153
                       nullptr,
1154
                       aes_key,
1155
2
                       iv);
1156
  } else {
1157
1
    EVP_DecryptInit_ex(ectx,
1158
                       EVP_aes_128_cbc(),
1159
                       nullptr,
1160
                       aes_key,
1161
1
                       iv);
1162
  }
1163
1164
  return r;
1165
}
1166
1167
1168
1169
1170
2
void SecureContext::CtxGetter(Local<String> property,
1171
                              const PropertyCallbackInfo<Value>& info) {
1172
  SecureContext* sc;
1173
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1174
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_);
1175
4
  info.GetReturnValue().Set(ext);
1176
}
1177
1178
1179
template <bool primary>
1180
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1181
  SecureContext* wrap;
1182

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1183
6
  Environment* env = wrap->env();
1184
  X509* cert;
1185
1186
  if (primary)
1187
3
    cert = wrap->cert_;
1188
  else
1189
3
    cert = wrap->issuer_;
1190

6
  if (cert == nullptr)
1191
    return args.GetReturnValue().Set(Null(env->isolate()));
1192
1193
6
  int size = i2d_X509(cert, nullptr);
1194
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1195
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1196
6
      Buffer::Data(buff));
1197
6
  i2d_X509(cert, &serialized);
1198
1199
12
  args.GetReturnValue().Set(buff);
1200
}
1201
1202
1203
template <class Base>
1204
321
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1205
642
  HandleScope scope(env->isolate());
1206
1207
321
  env->SetProtoMethod(t, "getPeerCertificate", GetPeerCertificate);
1208
321
  env->SetProtoMethod(t, "getSession", GetSession);
1209
321
  env->SetProtoMethod(t, "setSession", SetSession);
1210
321
  env->SetProtoMethod(t, "loadSession", LoadSession);
1211
321
  env->SetProtoMethod(t, "isSessionReused", IsSessionReused);
1212
321
  env->SetProtoMethod(t, "isInitFinished", IsInitFinished);
1213
321
  env->SetProtoMethod(t, "verifyError", VerifyError);
1214
321
  env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
1215
321
  env->SetProtoMethod(t, "endParser", EndParser);
1216
321
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1217
321
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1218
321
  env->SetProtoMethod(t, "shutdownSSL", Shutdown);
1219
321
  env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket);
1220
321
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1221
321
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1222
321
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1223
321
  env->SetProtoMethod(t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
1224
321
  env->SetProtoMethod(t, "getProtocol", GetProtocol);
1225
1226
#ifdef SSL_set_max_send_fragment
1227
321
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1228
#endif  // SSL_set_max_send_fragment
1229
1230
#ifdef OPENSSL_NPN_NEGOTIATED
1231
321
  env->SetProtoMethod(t, "getNegotiatedProtocol", GetNegotiatedProto);
1232
#endif  // OPENSSL_NPN_NEGOTIATED
1233
1234
#ifdef OPENSSL_NPN_NEGOTIATED
1235
321
  env->SetProtoMethod(t, "setNPNProtocols", SetNPNProtocols);
1236
#endif
1237
1238
321
  env->SetProtoMethod(t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
1239
321
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1240
1241
1605
  t->PrototypeTemplate()->SetAccessor(
1242
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
1243
      SSLGetter,
1244
      nullptr,
1245
      env->as_external(),
1246
      DEFAULT,
1247
      static_cast<PropertyAttribute>(ReadOnly | DontDelete),
1248
      AccessorSignature::New(env->isolate(), t));
1249
321
}
1250
1251
1252
template <class Base>
1253
599
void SSLWrap<Base>::InitNPN(SecureContext* sc) {
1254
#ifdef OPENSSL_NPN_NEGOTIATED
1255
  // Server should advertise NPN protocols
1256
599
  SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
1257
                                        AdvertiseNextProtoCallback,
1258
                                        nullptr);
1259
  // Client should select protocol from list of advertised
1260
  // If server supports NPN
1261
599
  SSL_CTX_set_next_proto_select_cb(sc->ctx_, SelectNextProtoCallback, nullptr);
1262
#endif  // OPENSSL_NPN_NEGOTIATED
1263
1264
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1265
  // OCSP stapling
1266
599
  SSL_CTX_set_tlsext_status_cb(sc->ctx_, TLSExtStatusCallback);
1267
599
  SSL_CTX_set_tlsext_status_arg(sc->ctx_, nullptr);
1268
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1269
599
}
1270
1271
1272
template <class Base>
1273
6
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1274
                                               unsigned char* key,
1275
                                               int len,
1276
                                               int* copy) {
1277
6
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1278
1279
6
  *copy = 0;
1280
6
  SSL_SESSION* sess = w->next_sess_;
1281
6
  w->next_sess_ = nullptr;
1282
1283
6
  return sess;
1284
}
1285
1286
1287
template <class Base>
1288
5
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1289
5
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1290
10
  Environment* env = w->ssl_env();
1291
10
  HandleScope handle_scope(env->isolate());
1292
15
  Context::Scope context_scope(env->context());
1293
1294

5
  if (!w->session_callbacks_)
1295
    return 0;
1296
1297
  // Check if session is small enough to be stored
1298
2
  int size = i2d_SSL_SESSION(sess, nullptr);
1299

2
  if (size > SecureContext::kMaxSessionSize)
1300
    return 0;
1301
1302
  // Serialize session
1303
4
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1304
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1305
2
      Buffer::Data(buff));
1306
4
  memset(serialized, 0, size);
1307
2
  i2d_SSL_SESSION(sess, &serialized);
1308
1309
2
  Local<Object> session = Buffer::Copy(
1310
      env,
1311
      reinterpret_cast<char*>(sess->session_id),
1312
4
      sess->session_id_length).ToLocalChecked();
1313
6
  Local<Value> argv[] = { session, buff };
1314
2
  w->new_session_wait_ = true;
1315
4
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1316
1317
2
  return 0;
1318
}
1319
1320
1321
template <class Base>
1322
17
void SSLWrap<Base>::OnClientHello(void* arg,
1323
                                  const ClientHelloParser::ClientHello& hello) {
1324
17
  Base* w = static_cast<Base*>(arg);
1325
31
  Environment* env = w->ssl_env();
1326
34
  HandleScope handle_scope(env->isolate());
1327
51
  Context::Scope context_scope(env->context());
1328
1329
17
  Local<Object> hello_obj = Object::New(env->isolate());
1330
17
  Local<Object> buff = Buffer::Copy(
1331
      env,
1332
17
      reinterpret_cast<const char*>(hello.session_id()),
1333
51
      hello.session_size()).ToLocalChecked();
1334
51
  hello_obj->Set(env->session_id_string(), buff);
1335

17
  if (hello.servername() == nullptr) {
1336
15
    hello_obj->Set(env->servername_string(), String::Empty(env->isolate()));
1337
  } else {
1338
14
    Local<String> servername = OneByteString(env->isolate(),
1339
                                             hello.servername(),
1340
28
                                             hello.servername_size());
1341
42
    hello_obj->Set(env->servername_string(), servername);
1342
  }
1343
85
  hello_obj->Set(env->tls_ticket_string(),
1344
17
                 Boolean::New(env->isolate(), hello.has_ticket()));
1345
85
  hello_obj->Set(env->ocsp_request_string(),
1346
17
                 Boolean::New(env->isolate(), hello.ocsp_request()));
1347
1348
34
  Local<Value> argv[] = { hello_obj };
1349
34
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1350
17
}
1351
1352
1353
25
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1354
25
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1355
1356
25
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1357
    return false;
1358
1359
2
  const unsigned char* p = ext->value->data;
1360
2
  GENERAL_NAMES* names = reinterpret_cast<GENERAL_NAMES*>(ASN1_item_d2i(
1361
      NULL,
1362
      &p,
1363
2
      ext->value->length,
1364
4
      ASN1_ITEM_ptr(method->it)));
1365
2
  if (names == NULL)
1366
    return false;
1367
1368
14
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1369
6
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1370
1371
6
    if (i != 0)
1372
4
      BIO_write(out, ", ", 2);
1373
1374
6
    if (gen->type == GEN_DNS) {
1375
3
      ASN1_IA5STRING* name = gen->d.dNSName;
1376
1377
3
      BIO_write(out, "DNS:", 4);
1378
3
      BIO_write(out, name->data, name->length);
1379
    } else {
1380
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1381
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, NULL);
1382
3
      if (nval == NULL)
1383
        return false;
1384
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1385
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1386
    }
1387
  }
1388
2
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1389
1390
2
  return true;
1391
}
1392
1393
1394
46
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1395
92
  EscapableHandleScope scope(env->isolate());
1396
1397
46
  Local<Object> info = Object::New(env->isolate());
1398
1399
46
  BIO* bio = BIO_new(BIO_s_mem());
1400
  BUF_MEM* mem;
1401
46
  if (X509_NAME_print_ex(bio,
1402
                         X509_get_subject_name(cert),
1403
                         0,
1404
                         X509_NAME_FLAGS) > 0) {
1405
46
    BIO_get_mem_ptr(bio, &mem);
1406
276
    info->Set(env->subject_string(),
1407
46
              String::NewFromUtf8(env->isolate(), mem->data,
1408
92
                                  String::kNormalString, mem->length));
1409
  }
1410
46
  (void) BIO_reset(bio);
1411
1412
46
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1413
46
  if (X509_NAME_print_ex(bio, issuer_name, 0, X509_NAME_FLAGS) > 0) {
1414
46
    BIO_get_mem_ptr(bio, &mem);
1415
276
    info->Set(env->issuer_string(),
1416
46
              String::NewFromUtf8(env->isolate(), mem->data,
1417
92
                                  String::kNormalString, mem->length));
1418
  }
1419
46
  (void) BIO_reset(bio);
1420
1421
46
  int nids[] = { NID_subject_alt_name, NID_info_access };
1422
  Local<String> keys[] = { env->subjectaltname_string(),
1423
138
                           env->infoaccess_string() };
1424
46
  CHECK_EQ(arraysize(nids), arraysize(keys));
1425
138
  for (size_t i = 0; i < arraysize(nids); i++) {
1426
92
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1427
92
    if (index < 0)
1428
      continue;
1429
1430
    X509_EXTENSION* ext;
1431
    int rv;
1432
1433
25
    ext = X509_get_ext(cert, index);
1434
25
    CHECK_NE(ext, nullptr);
1435
1436
25
    if (!SafeX509ExtPrint(bio, ext)) {
1437
23
      rv = X509V3_EXT_print(bio, ext, 0, 0);
1438
23
      CHECK_EQ(rv, 1);
1439
    }
1440
1441
25
    BIO_get_mem_ptr(bio, &mem);
1442
125
    info->Set(keys[i],
1443
25
              String::NewFromUtf8(env->isolate(), mem->data,
1444
50
                                  String::kNormalString, mem->length));
1445
1446
25
    (void) BIO_reset(bio);
1447
  }
1448
1449
46
  EVP_PKEY* pkey = X509_get_pubkey(cert);
1450
46
  RSA* rsa = nullptr;
1451
46
  if (pkey != nullptr)
1452
46
    rsa = EVP_PKEY_get1_RSA(pkey);
1453
1454
46
  if (rsa != nullptr) {
1455
45
      BN_print(bio, rsa->n);
1456
45
      BIO_get_mem_ptr(bio, &mem);
1457
270
      info->Set(env->modulus_string(),
1458
45
                String::NewFromUtf8(env->isolate(), mem->data,
1459
90
                                    String::kNormalString, mem->length));
1460
45
      (void) BIO_reset(bio);
1461
1462
45
      BN_ULONG exponent_word = BN_get_word(rsa->e);
1463
45
      BIO_printf(bio, "0x%lx", exponent_word);
1464
1465
45
      BIO_get_mem_ptr(bio, &mem);
1466
270
      info->Set(env->exponent_string(),
1467
45
                String::NewFromUtf8(env->isolate(), mem->data,
1468
90
                                    String::kNormalString, mem->length));
1469
45
      (void) BIO_reset(bio);
1470
  }
1471
1472
46
  if (pkey != nullptr) {
1473
46
    EVP_PKEY_free(pkey);
1474
46
    pkey = nullptr;
1475
  }
1476
46
  if (rsa != nullptr) {
1477
45
    RSA_free(rsa);
1478
45
    rsa = nullptr;
1479
  }
1480
1481
46
  ASN1_TIME_print(bio, X509_get_notBefore(cert));
1482
46
  BIO_get_mem_ptr(bio, &mem);
1483
276
  info->Set(env->valid_from_string(),
1484
46
            String::NewFromUtf8(env->isolate(), mem->data,
1485
92
                                String::kNormalString, mem->length));
1486
46
  (void) BIO_reset(bio);
1487
1488
46
  ASN1_TIME_print(bio, X509_get_notAfter(cert));
1489
46
  BIO_get_mem_ptr(bio, &mem);
1490
276
  info->Set(env->valid_to_string(),
1491
46
            String::NewFromUtf8(env->isolate(), mem->data,
1492
92
                                String::kNormalString, mem->length));
1493
46
  BIO_free_all(bio);
1494
1495
  unsigned int md_size, i;
1496
  unsigned char md[EVP_MAX_MD_SIZE];
1497
46
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1498
46
    const char hex[] = "0123456789ABCDEF";
1499
    char fingerprint[EVP_MAX_MD_SIZE * 3];
1500
1501
    // TODO(indutny): Unify it with buffer's code
1502
966
    for (i = 0; i < md_size; i++) {
1503
920
      fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1504
920
      fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1505
920
      fingerprint[(3*i)+2] = ':';
1506
    }
1507
1508
46
    if (md_size > 0) {
1509
46
      fingerprint[(3*(md_size-1))+2] = '\0';
1510
    } else {
1511
      fingerprint[0] = '\0';
1512
    }
1513
1514
230
    info->Set(env->fingerprint_string(),
1515
46
              OneByteString(env->isolate(), fingerprint));
1516
  }
1517
1518
  STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
1519
46
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr));
1520
46
  if (eku != nullptr) {
1521
1
    Local<Array> ext_key_usage = Array::New(env->isolate());
1522
    char buf[256];
1523
1524
1
    int j = 0;
1525
2
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1526
1
      if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku, i), 1) >= 0)
1527
3
        ext_key_usage->Set(j++, OneByteString(env->isolate(), buf));
1528
    }
1529
1530
1
    sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1531
3
    info->Set(env->ext_key_usage_string(), ext_key_usage);
1532
  }
1533
1534
46
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1535
46
    if (BIGNUM* bn = ASN1_INTEGER_to_BN(serial_number, nullptr)) {
1536
46
      if (char* buf = BN_bn2hex(bn)) {
1537
230
        info->Set(env->serial_number_string(),
1538
46
                  OneByteString(env->isolate(), buf));
1539
46
        OPENSSL_free(buf);
1540
      }
1541
46
      BN_free(bn);
1542
    }
1543
  }
1544
1545
  // Raw DER certificate
1546
46
  int size = i2d_X509(cert, nullptr);
1547
92
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1548
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1549
46
      Buffer::Data(buff));
1550
46
  i2d_X509(cert, &serialized);
1551
138
  info->Set(env->raw_string(), buff);
1552
1553
92
  return scope.Escape(info);
1554
}
1555
1556
1557
// TODO(indutny): Split it into multiple smaller functions
1558
template <class Base>
1559
46
void SSLWrap<Base>::GetPeerCertificate(
1560
    const FunctionCallbackInfo<Value>& args) {
1561
  Base* w;
1562

46
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1563
91
  Environment* env = w->ssl_env();
1564
1565
  ClearErrorOnReturn clear_error_on_return;
1566
  (void) &clear_error_on_return;  // Silence unused variable warning.
1567
1568
46
  Local<Object> result;
1569
46
  Local<Object> info;
1570
1571
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1572
  // contains the `peer_certificate`, but on server it doesn't
1573

91
  X509* cert = w->is_server() ? SSL_get_peer_certificate(w->ssl_) : nullptr;
1574
46
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_);
1575
46
  STACK_OF(X509)* peer_certs = nullptr;
1576

46
  if (cert == nullptr && ssl_certs == nullptr)
1577
    goto done;
1578
1579



45
  if (cert == nullptr && sk_X509_num(ssl_certs) == 0)
1580
    goto done;
1581
1582
  // Short result requested
1583



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

44
    result = X509ToObject(env,
1585
                          cert == nullptr ? sk_X509_value(ssl_certs, 0) : cert);
1586
44
    goto done;
1587
  }
1588
1589
  // Clone `ssl_certs`, because we are going to destruct it
1590
1
  peer_certs = sk_X509_new(nullptr);
1591

1
  if (cert != nullptr)
1592
    sk_X509_push(peer_certs, cert);
1593

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

2
    if (cert == nullptr)
1596
      goto done;
1597

2
    if (!sk_X509_push(peer_certs, cert))
1598
      goto done;
1599
  }
1600
1601
  // First and main certificate
1602
1
  cert = sk_X509_value(peer_certs, 0);
1603
1
  result = X509ToObject(env, cert);
1604
1
  info = result;
1605
1606
  // Put issuer inside the object
1607
1
  cert = sk_X509_delete(peer_certs, 0);
1608

1
  while (sk_X509_num(peer_certs) > 0) {
1609
    int i;
1610

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

1
      if (X509_check_issued(ca, cert) != X509_V_OK)
1613
        continue;
1614
1615
1
      Local<Object> ca_info = X509ToObject(env, ca);
1616
3
      info->Set(env->issuercert_string(), ca_info);
1617
1
      info = ca_info;
1618
1619
      // NOTE: Intentionally freeing cert that is not used anymore
1620
1
      X509_free(cert);
1621
1622
      // Delete cert and continue aggregating issuers
1623
1
      cert = sk_X509_delete(peer_certs, i);
1624
1
      break;
1625
    }
1626
1627
    // Issuer not found, break out of the loop
1628

1
    if (i == sk_X509_num(peer_certs))
1629
      break;
1630
  }
1631
1632
  // Last certificate should be self-signed
1633

1
  while (X509_check_issued(cert, cert) != X509_V_OK) {
1634
    X509* ca;
1635
    if (SSL_CTX_get_issuer(w->ssl_->ctx, cert, &ca) <= 0)
1636
      break;
1637
1638
    Local<Object> ca_info = X509ToObject(env, ca);
1639
    info->Set(env->issuercert_string(), ca_info);
1640
    info = ca_info;
1641
1642
    // NOTE: Intentionally freeing cert that is not used anymore
1643
    X509_free(cert);
1644
1645
    // Delete cert and continue aggregating issuers
1646
    cert = ca;
1647
  }
1648
1649
  // Self-issued certificate
1650

1
  if (X509_check_issued(cert, cert) == X509_V_OK)
1651
3
    info->Set(env->issuercert_string(), info);
1652
1653

1
  CHECK_NE(cert, nullptr);
1654
1655
 done:
1656

46
  if (cert != nullptr)
1657
8
    X509_free(cert);
1658

46
  if (peer_certs != nullptr)
1659
1
    sk_X509_pop_free(peer_certs, X509_free);
1660

46
  if (result.IsEmpty())
1661
1
    result = Object::New(env->isolate());
1662
92
  args.GetReturnValue().Set(result);
1663
}
1664
1665
1666
template <class Base>
1667
105
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1668
105
  Environment* env = Environment::GetCurrent(args);
1669
1670
  Base* w;
1671

105
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1672
1673
105
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1674

105
  if (sess == nullptr)
1675
    return;
1676
1677
105
  int slen = i2d_SSL_SESSION(sess, nullptr);
1678

105
  CHECK_GT(slen, 0);
1679
1680
105
  char* sbuf = new char[slen];
1681
105
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1682
105
  i2d_SSL_SESSION(sess, &p);
1683
315
  args.GetReturnValue().Set(Encode(env->isolate(), sbuf, slen, BUFFER));
1684

105
  delete[] sbuf;
1685
}
1686
1687
1688
template <class Base>
1689
62
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1690
62
  Environment* env = Environment::GetCurrent(args);
1691
1692
  Base* w;
1693

62
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1694
1695

62
  if (args.Length() < 1) {
1696
    return env->ThrowError("Session argument is mandatory");
1697
  }
1698
1699

62
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Session");
1700
62
  size_t slen = Buffer::Length(args[0]);
1701
62
  char* sbuf = new char[slen];
1702
124
  memcpy(sbuf, Buffer::Data(args[0]), slen);
1703
1704
62
  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1705
62
  SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1706
1707

62
  delete[] sbuf;
1708
1709

62
  if (sess == nullptr)
1710
    return;
1711
1712
62
  int r = SSL_set_session(w->ssl_, sess);
1713
62
  SSL_SESSION_free(sess);
1714
1715

62
  if (!r)
1716
    return env->ThrowError("SSL_set_session error");
1717
}
1718
1719
1720
template <class Base>
1721
8
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1722
  Base* w;
1723

8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1724
13
  Environment* env = w->ssl_env();
1725
1726



16
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1727
5
    ssize_t slen = Buffer::Length(args[0]);
1728
5
    char* sbuf = Buffer::Data(args[0]);
1729
1730
5
    const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1731
5
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1732
1733
    // Setup next session and move hello to the BIO buffer
1734

5
    if (w->next_sess_ != nullptr)
1735
      SSL_SESSION_free(w->next_sess_);
1736
5
    w->next_sess_ = sess;
1737
1738
5
    Local<Object> info = Object::New(env->isolate());
1739
#ifndef OPENSSL_NO_TLSEXT
1740

5
    if (sess->tlsext_hostname == nullptr) {
1741
      info->Set(env->servername_string(), False(args.GetIsolate()));
1742
    } else {
1743
20
      info->Set(env->servername_string(),
1744
5
                OneByteString(args.GetIsolate(), sess->tlsext_hostname));
1745
    }
1746
#endif
1747
10
    args.GetReturnValue().Set(info);
1748
  }
1749
}
1750
1751
1752
template <class Base>
1753
56
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1754
  Base* w;
1755

56
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1756
56
  bool yes = SSL_session_reused(w->ssl_);
1757
168
  args.GetReturnValue().Set(yes);
1758
}
1759
1760
1761
template <class Base>
1762
16
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
1763
  Base* w;
1764

16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1765
16
  w->hello_parser_.End();
1766
}
1767
1768
1769
template <class Base>
1770
1
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1771
  Base* w;
1772

1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1773
1774
  ClearErrorOnReturn clear_error_on_return;
1775
  (void) &clear_error_on_return;  // Silence unused variable warning.
1776
1777
1
  bool yes = SSL_renegotiate(w->ssl_) == 1;
1778
3
  args.GetReturnValue().Set(yes);
1779
}
1780
1781
1782
template <class Base>
1783
2
void SSLWrap<Base>::Shutdown(const FunctionCallbackInfo<Value>& args) {
1784
  Base* w;
1785

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1786
1787
2
  int rv = SSL_shutdown(w->ssl_);
1788
4
  args.GetReturnValue().Set(rv);
1789
}
1790
1791
1792
template <class Base>
1793
9
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1794
  Base* w;
1795

9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1796
18
  Environment* env = w->ssl_env();
1797
1798
9
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1799


9
  if (sess == nullptr || sess->tlsext_tick == nullptr)
1800
    return;
1801
1802
9
  Local<Object> buff = Buffer::Copy(
1803
      env,
1804
      reinterpret_cast<char*>(sess->tlsext_tick),
1805
18
      sess->tlsext_ticklen).ToLocalChecked();
1806
1807
9
  args.GetReturnValue().Set(buff);
1808
}
1809
1810
1811
template <class Base>
1812
2
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1813
  Base* w;
1814

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1815
2
  w->new_session_wait_ = false;
1816
2
  w->NewSessionDoneCb();
1817
}
1818
1819
1820
template <class Base>
1821
2
void SSLWrap<Base>::SetOCSPResponse(
1822
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1823
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1824
  Base* w;
1825

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1826
2
  Environment* env = w->env();
1827
1828

2
  if (args.Length() < 1)
1829
    return env->ThrowTypeError("OCSP response argument is mandatory");
1830
1831

2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "OCSP response");
1832
1833
6
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
1834
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1835
}
1836
1837
1838
template <class Base>
1839
3
void SSLWrap<Base>::RequestOCSP(
1840
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1841
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1842
  Base* w;
1843

3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1844
1845
3
  SSL_set_tlsext_status_type(w->ssl_, TLSEXT_STATUSTYPE_ocsp);
1846
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1847
}
1848
1849
1850
template <class Base>
1851
263
void SSLWrap<Base>::GetEphemeralKeyInfo(
1852
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1853
  Base* w;
1854

263
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1855
263
  Environment* env = Environment::GetCurrent(args);
1856
1857

263
  CHECK_NE(w->ssl_, nullptr);
1858
1859
  // tmp key is available on only client
1860

526
  if (w->is_server())
1861
10
    return args.GetReturnValue().SetNull();
1862
1863
258
  Local<Object> info = Object::New(env->isolate());
1864
1865
  EVP_PKEY* key;
1866
1867

258
  if (SSL_get_server_tmp_key(w->ssl_, &key)) {
1868

223
    switch (EVP_PKEY_id(key)) {
1869
      case EVP_PKEY_DH:
1870
24
        info->Set(env->type_string(),
1871
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH"));
1872
24
        info->Set(env->size_string(),
1873
                  Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1874
6
        break;
1875
      case EVP_PKEY_EC:
1876
        {
1877
217
          EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
1878
217
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
1879
217
          EC_KEY_free(ec);
1880
868
          info->Set(env->type_string(),
1881
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"));
1882
1085
          info->Set(env->name_string(),
1883
                    OneByteString(args.GetIsolate(), OBJ_nid2sn(nid)));
1884
868
          info->Set(env->size_string(),
1885
                    Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1886
        }
1887
    }
1888
223
    EVP_PKEY_free(key);
1889
  }
1890
1891
258
  return args.GetReturnValue().Set(info);
1892
}
1893
1894
1895
#ifdef SSL_set_max_send_fragment
1896
template <class Base>
1897
3
void SSLWrap<Base>::SetMaxSendFragment(
1898
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1899



9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
1900
1901
  Base* w;
1902

3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1903
1904
3
  int rv = SSL_set_max_send_fragment(w->ssl_, args[0]->Int32Value());
1905
6
  args.GetReturnValue().Set(rv);
1906
}
1907
#endif  // SSL_set_max_send_fragment
1908
1909
1910
template <class Base>
1911
23
void SSLWrap<Base>::IsInitFinished(const FunctionCallbackInfo<Value>& args) {
1912
  Base* w;
1913

23
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1914
23
  bool yes = SSL_is_init_finished(w->ssl_);
1915
69
  args.GetReturnValue().Set(yes);
1916
}
1917
1918
1919
template <class Base>
1920
287
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
1921
  Base* w;
1922

331
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1923
1924
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
1925
  // peer certificate is questionable but it's compatible with what was
1926
  // here before.
1927
  long x509_verify_error =  // NOLINT(runtime/int)
1928
287
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
1929

287
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
1930
284
    X509_free(peer_cert);
1931
284
    x509_verify_error = SSL_get_verify_result(w->ssl_);
1932
  }
1933
1934

287
  if (x509_verify_error == X509_V_OK)
1935
88
    return args.GetReturnValue().SetNull();
1936
1937
  // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
1938
  // in the presence of invalid error codes.  Probably academical but something
1939
  // to keep in mind if/when node ever grows multi-isolate capabilities.
1940
243
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
1941
243
  const char* code = reason;
1942
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
1943














243
  switch (x509_verify_error) {
1944
3
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
1945
5
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
1946
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
1947
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
1948
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
1949
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
1950
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
1951
    CASE_X509_ERR(CERT_NOT_YET_VALID)
1952
29
    CASE_X509_ERR(CERT_HAS_EXPIRED)
1953
    CASE_X509_ERR(CRL_NOT_YET_VALID)
1954
    CASE_X509_ERR(CRL_HAS_EXPIRED)
1955
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
1956
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
1957
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
1958
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
1959
    CASE_X509_ERR(OUT_OF_MEM)
1960
107
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
1961
4
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
1962
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
1963
91
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
1964
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
1965
2
    CASE_X509_ERR(CERT_REVOKED)
1966
    CASE_X509_ERR(INVALID_CA)
1967
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
1968
1
    CASE_X509_ERR(INVALID_PURPOSE)
1969
    CASE_X509_ERR(CERT_UNTRUSTED)
1970
    CASE_X509_ERR(CERT_REJECTED)
1971
  }
1972
#undef CASE_X509_ERR
1973
1974
243
  Isolate* isolate = args.GetIsolate();
1975
243
  Local<String> reason_string = OneByteString(isolate, reason);
1976
243
  Local<Value> exception_value = Exception::Error(reason_string);
1977
243
  Local<Object> exception_object = exception_value->ToObject(isolate);
1978
972
  exception_object->Set(FIXED_ONE_BYTE_STRING(isolate, "code"),
1979
                        OneByteString(isolate, code));
1980
486
  args.GetReturnValue().Set(exception_object);
1981
}
1982
1983
1984
template <class Base>
1985
10
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
1986
  Base* w;
1987

10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1988
19
  Environment* env = w->ssl_env();
1989
1990
10
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
1991

10
  if (c == nullptr)
1992
    return;
1993
1994
10
  Local<Object> info = Object::New(env->isolate());
1995
10
  const char* cipher_name = SSL_CIPHER_get_name(c);
1996
40
  info->Set(env->name_string(), OneByteString(args.GetIsolate(), cipher_name));
1997
10
  const char* cipher_version = SSL_CIPHER_get_version(c);
1998
40
  info->Set(env->version_string(),
1999
            OneByteString(args.GetIsolate(), cipher_version));
2000
10
  args.GetReturnValue().Set(info);
2001
}
2002
2003
2004
template <class Base>
2005
3
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2006
  Base* w;
2007

3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2008
2009
3
  const char* tls_version = SSL_get_version(w->ssl_);
2010
6
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2011
}
2012
2013
2014
#ifdef OPENSSL_NPN_NEGOTIATED
2015
template <class Base>
2016
252
int SSLWrap<Base>::AdvertiseNextProtoCallback(SSL* s,
2017
                                              const unsigned char** data,
2018
                                              unsigned int* len,
2019
                                              void* arg) {
2020
252
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2021
252
  Environment* env = w->env();
2022
504
  HandleScope handle_scope(env->isolate());
2023
756
  Context::Scope context_scope(env->context());
2024
2025
  auto npn_buffer =
2026
252
      w->object()->GetPrivate(
2027
          env->context(),
2028
1008
          env->npn_buffer_private_symbol()).ToLocalChecked();
2029
2030

504
  if (npn_buffer->IsUndefined()) {
2031
    // No initialization - no NPN protocols
2032
143
    *data = reinterpret_cast<const unsigned char*>("");
2033
143
    *len = 0;
2034
  } else {
2035

109
    CHECK(Buffer::HasInstance(npn_buffer));
2036
109
    *data = reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2037
109
    *len = Buffer::Length(npn_buffer);
2038
  }
2039
2040
504
  return SSL_TLSEXT_ERR_OK;
2041
}
2042
2043
2044
template <class Base>
2045
251
int SSLWrap<Base>::SelectNextProtoCallback(SSL* s,
2046
                                           unsigned char** out,
2047
                                           unsigned char* outlen,
2048
                                           const unsigned char* in,
2049
                                           unsigned int inlen,
2050
                                           void* arg) {
2051
251
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2052
251
  Environment* env = w->env();
2053
502
  HandleScope handle_scope(env->isolate());
2054
753
  Context::Scope context_scope(env->context());
2055
2056
  auto npn_buffer =
2057
251
      w->object()->GetPrivate(
2058
          env->context(),
2059
1004
          env->npn_buffer_private_symbol()).ToLocalChecked();
2060
2061

502
  if (npn_buffer->IsUndefined()) {
2062
    // We should at least select one protocol
2063
    // If server is using NPN
2064
230
    *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
2065
230
    *outlen = 8;
2066
2067
    // set status: unsupported
2068

1610
    CHECK(
2069
        w->object()->SetPrivate(
2070
            env->context(),
2071
            env->selected_npn_buffer_private_symbol(),
2072
            False(env->isolate())).FromJust());
2073
2074
    return SSL_TLSEXT_ERR_OK;
2075
  }
2076
2077

21
  CHECK(Buffer::HasInstance(npn_buffer));
2078
  const unsigned char* npn_protos =
2079
21
      reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2080
21
  size_t len = Buffer::Length(npn_buffer);
2081
2082
21
  int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
2083
21
  Local<Value> result;
2084


21
  switch (status) {
2085
    case OPENSSL_NPN_UNSUPPORTED:
2086
      result = Null(env->isolate());
2087
      break;
2088
    case OPENSSL_NPN_NEGOTIATED:
2089
14
      result = OneByteString(env->isolate(), *out, *outlen);
2090
7
      break;
2091
    case OPENSSL_NPN_NO_OVERLAP:
2092
42
      result = False(env->isolate());
2093
14
      break;
2094
    default:
2095
      break;
2096
  }
2097
2098

84
  CHECK(
2099
      w->object()->SetPrivate(
2100
          env->context(),
2101
          env->selected_npn_buffer_private_symbol(),
2102
          result).FromJust());
2103
2104
  return SSL_TLSEXT_ERR_OK;
2105
}
2106
2107
2108
template <class Base>
2109
553
void SSLWrap<Base>::GetNegotiatedProto(
2110
    const FunctionCallbackInfo<Value>& args) {
2111
  Base* w;
2112

859
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2113
553
  Environment* env = w->env();
2114
2115

1105
  if (w->is_client()) {
2116
    auto selected_npn_buffer =
2117
255
        w->object()->GetPrivate(
2118
            env->context(),
2119
1020
            env->selected_npn_buffer_private_symbol()).ToLocalChecked();
2120
255
    args.GetReturnValue().Set(selected_npn_buffer);
2121
    return;
2122
  }
2123
2124
  const unsigned char* npn_proto;
2125
  unsigned int npn_proto_len;
2126
2127
298
  SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
2128
2129

298
  if (!npn_proto)
2130
102
    return args.GetReturnValue().Set(false);
2131
2132
988
  args.GetReturnValue().Set(
2133
      OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
2134
}
2135
2136
2137
template <class Base>
2138
142
void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
2139
  Base* w;
2140

142
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2141
142
  Environment* env = w->env();
2142
2143

142
  if (args.Length() < 1)
2144
    return env->ThrowTypeError("NPN protocols argument is mandatory");
2145
2146

142
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "NPN protocols");
2147
2148

710
  CHECK(
2149
      w->object()->SetPrivate(
2150
          env->context(),
2151
          env->npn_buffer_private_symbol(),
2152
          args[0]).FromJust());
2153
}
2154
#endif  // OPENSSL_NPN_NEGOTIATED
2155
2156
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2157
template <class Base>
2158
13
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2159
                                      const unsigned char** out,
2160
                                      unsigned char* outlen,
2161
                                      const unsigned char* in,
2162
                                      unsigned int inlen,
2163
                                      void* arg) {
2164
13
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2165
13
  Environment* env = w->env();
2166
26
  HandleScope handle_scope(env->isolate());
2167
39
  Context::Scope context_scope(env->context());
2168
2169
  Local<Value> alpn_buffer =
2170
13
      w->object()->GetPrivate(
2171
          env->context(),
2172
52
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2173

13
  CHECK(Buffer::HasInstance(alpn_buffer));
2174
  const unsigned char* alpn_protos =
2175
13
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2176
13
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2177
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2178
13
                                     alpn_protos, alpn_protos_len, in, inlen);
2179
2180

13
  switch (status) {
2181
    case OPENSSL_NPN_NO_OVERLAP:
2182
      // According to 3.2. Protocol Selection of RFC7301,
2183
      // fatal no_application_protocol alert shall be sent
2184
      // but current openssl does not support it yet. See
2185
      // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2186
      // Instead, we send a warning alert for now.
2187
      return SSL_TLSEXT_ERR_ALERT_WARNING;
2188
    case OPENSSL_NPN_NEGOTIATED:
2189
9
      return SSL_TLSEXT_ERR_OK;
2190
    default:
2191
      return SSL_TLSEXT_ERR_ALERT_FATAL;
2192
  }
2193
}
2194
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2195
2196
2197
template <class Base>
2198
553
void SSLWrap<Base>::GetALPNNegotiatedProto(
2199
    const FunctionCallbackInfo<v8::Value>& args) {
2200
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2201
  Base* w;
2202

1088
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2203
2204
  const unsigned char* alpn_proto;
2205
  unsigned int alpn_proto_len;
2206
2207
553
  SSL_get0_alpn_selected(w->ssl_, &alpn_proto, &alpn_proto_len);
2208
2209

553
  if (!alpn_proto)
2210
1070
    return args.GetReturnValue().Set(false);
2211
2212
72
  args.GetReturnValue().Set(
2213
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2214
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2215
}
2216
2217
2218
template <class Base>
2219
134
void SSLWrap<Base>::SetALPNProtocols(
2220
    const FunctionCallbackInfo<v8::Value>& args) {
2221
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2222
  Base* w;
2223

134
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2224
134
  Environment* env = w->env();
2225



268
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2226
    return env->ThrowTypeError("Must give a Buffer as first argument");
2227
2228

268
  if (w->is_client()) {
2229
    const unsigned char* alpn_protos =
2230
22
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2231
22
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2232
22
    int r = SSL_set_alpn_protos(w->ssl_, alpn_protos, alpn_protos_len);
2233

22
    CHECK_EQ(r, 0);
2234
  } else {
2235

560
    CHECK(
2236
        w->object()->SetPrivate(
2237
          env->context(),
2238
          env->alpn_buffer_private_symbol(),
2239
          args[0]).FromJust());
2240
    // Server should select ALPN protocol from list of advertised by client
2241
112
    SSL_CTX_set_alpn_select_cb(w->ssl_->ctx, SelectALPNCallback, nullptr);
2242
  }
2243
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2244
}
2245
2246
2247
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2248
template <class Base>
2249
7
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2250
7
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2251
7
  Environment* env = w->env();
2252
14
  HandleScope handle_scope(env->isolate());
2253
2254

13
  if (w->is_client()) {
2255
    // Incoming response
2256
    const unsigned char* resp;
2257
3
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2258
3
    Local<Value> arg;
2259

3
    if (resp == nullptr) {
2260
3
      arg = Null(env->isolate());
2261
    } else {
2262
6
      arg = Buffer::Copy(
2263
          env,
2264
          reinterpret_cast<char*>(const_cast<unsigned char*>(resp)),
2265
          len).ToLocalChecked();
2266
    }
2267
2268
3
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2269
2270
    // Somehow, client is expecting different return value here
2271
    return 1;
2272
  } else {
2273
    // Outgoing response
2274

8
    if (w->ocsp_response_.IsEmpty())
2275
      return SSL_TLSEXT_ERR_NOACK;
2276
2277
2
    Local<Object> obj = PersistentToLocal(env->isolate(), w->ocsp_response_);
2278
2
    char* resp = Buffer::Data(obj);
2279
2
    size_t len = Buffer::Length(obj);
2280
2281
    // OpenSSL takes control of the pointer after accepting it
2282
2
    char* data = reinterpret_cast<char*>(node::Malloc(len));
2283

2
    CHECK_NE(data, nullptr);
2284
2
    memcpy(data, resp, len);
2285
2286

2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2287
      free(data);
2288
2
    w->ocsp_response_.Reset();
2289
2290
    return SSL_TLSEXT_ERR_OK;
2291
  }
2292
}
2293
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2294
2295
2296
template <class Base>
2297
21
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2298
21
  cert_cb_ = cb;
2299
21
  cert_cb_arg_ = arg;
2300
21
}
2301
2302
2303
template <class Base>
2304
290
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2305
290
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2306
2307

577
  if (!w->is_server())
2308
    return 1;
2309
2310

563
  if (!w->is_waiting_cert_cb())
2311
    return 1;
2312
2313

21
  if (w->cert_cb_running_)
2314
    return -1;
2315
2316
21
  Environment* env = w->env();
2317
42
  HandleScope handle_scope(env->isolate());
2318
63
  Context::Scope context_scope(env->context());
2319
21
  w->cert_cb_running_ = true;
2320
2321
21
  Local<Object> info = Object::New(env->isolate());
2322
2323
21
  SSL_SESSION* sess = SSL_get_session(s);
2324

21
  if (sess != nullptr) {
2325

21
    if (sess->tlsext_hostname == nullptr) {
2326
40
      info->Set(env->servername_string(), String::Empty(env->isolate()));
2327
    } else {
2328
13
      Local<String> servername = OneByteString(env->isolate(),
2329
                                               sess->tlsext_hostname,
2330
26
                                               strlen(sess->tlsext_hostname));
2331
39
      info->Set(env->servername_string(), servername);
2332
    }
2333
105
    info->Set(env->tls_ticket_string(),
2334
21
              Boolean::New(env->isolate(), sess->tlsext_ticklen != 0));
2335
  }
2336
2337
21
  bool ocsp = false;
2338
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2339
21
  ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp;
2340
#endif
2341
2342
105
  info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp));
2343
2344
42
  Local<Value> argv[] = { info };
2345
42
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2346
2347

21
  if (!w->cert_cb_running_)
2348
    return 1;
2349
2350
  // Performing async action, wait...
2351
9
  return -1;
2352
}
2353
2354
2355
template <class Base>
2356
21
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2357
  Base* w;
2358

21
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2359
21
  Environment* env = w->env();
2360
2361



42
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2362
2363
42
  Local<Object> object = w->object();
2364
42
  Local<Value> ctx = object->Get(env->sni_context_string());
2365
21
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2366
2367
  // Not an object, probably undefined or null
2368

21
  if (!ctx->IsObject())
2369
    goto fire_cb;
2370
2371

10
  if (cons->HasInstance(ctx)) {
2372
    SecureContext* sc;
2373

10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2374
18
    w->sni_context_.Reset();
2375
18
    w->sni_context_.Reset(env->isolate(), ctx);
2376
2377
    int rv;
2378
2379
    // NOTE: reference count is not increased by this API methods
2380
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_);
2381
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_);
2382
    STACK_OF(X509)* chain;
2383
2384
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain);
2385

9
    if (rv)
2386
9
      rv = SSL_use_certificate(w->ssl_, x509);
2387

9
    if (rv)
2388
8
      rv = SSL_use_PrivateKey(w->ssl_, pkey);
2389


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

9
    if (rv)
2392
8
      rv = w->SetCACerts(sc);
2393

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

1
      if (!err)
2396
        return env->ThrowError("CertCbDone");
2397
1
      return ThrowCryptoError(env, err);
2398
    }
2399
  } else {
2400
    // Failure: incorrect SNI context object
2401
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2402
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2403
    return;
2404
  }
2405
2406
 fire_cb:
2407
  CertCb cb;
2408
  void* arg;
2409
2410
19
  cb = w->cert_cb_;
2411
19
  arg = w->cert_cb_arg_;
2412
2413
19
  w->cert_cb_running_ = false;
2414
19
  w->cert_cb_ = nullptr;
2415
19
  w->cert_cb_arg_ = nullptr;
2416
2417
19
  cb(arg);
2418
}
2419
2420
2421
template <class Base>
2422
2
void SSLWrap<Base>::SSLGetter(Local<String> property,
2423
                              const PropertyCallbackInfo<Value>& info) {
2424
  Base* base;
2425

4
  ASSIGN_OR_RETURN_UNWRAP(&base, info.This());
2426
  SSL* ssl = base->ssl_;
2427
  Local<External> ext = External::New(info.GetIsolate(), ssl);
2428
  info.GetReturnValue().Set(ext);
2429
}
2430
2431
2432
template <class Base>
2433
void SSLWrap<Base>::DestroySSL() {
2434
  if (ssl_ == nullptr)
2435
    return;
2436
2437
  SSL_free(ssl_);
2438
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2439
  ssl_ = nullptr;
2440
}
2441
2442
2443
template <class Base>
2444
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2445
  InitNPN(sc);
2446
  CHECK_EQ(SSL_set_SSL_CTX(ssl_, sc->ctx_), sc->ctx_);
2447
2448
  SetCACerts(sc);
2449
}
2450
2451
2452
template <class Base>
2453
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2454
8
  int err = SSL_set1_verify_cert_store(ssl_, SSL_CTX_get_cert_store(sc->ctx_));
2455

8
  if (err != 1)
2456
    return err;
2457
2458
8
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2459
16
      SSL_CTX_get_client_CA_list(sc->ctx_));
2460
2461
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2462
8
  SSL_set_client_CA_list(ssl_, list);
2463
8
  return 1;
2464
}
2465
2466
2467
3
void Connection::OnClientHelloParseEnd(void* arg) {
2468
3
  Connection* conn = static_cast<Connection*>(arg);
2469
2470
  // Write all accumulated data
2471
3
  int r = BIO_write(conn->bio_read_,
2472
                    reinterpret_cast<char*>(conn->hello_data_),
2473
6
                    conn->hello_offset_);
2474
3
  conn->HandleBIOError(conn->bio_read_, "BIO_write", r);
2475
3
  conn->SetShutdownFlags();
2476
3
}
2477
2478
2479
#ifdef SSL_PRINT_DEBUG
2480
# define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
2481
#else
2482
# define DEBUG_PRINT(...)
2483
#endif
2484
2485
2486
27
int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
2487
27
  if (rv >= 0)
2488
    return rv;
2489
2490
17
  int retry = BIO_should_retry(bio);
2491
  (void) retry;  // unused if !defined(SSL_PRINT_DEBUG)
2492
2493
17
  if (BIO_should_write(bio)) {
2494
    DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n",
2495
                ssl_,
2496
                func,
2497
                retry);
2498
    return 0;
2499
2500
17
  } else if (BIO_should_read(bio)) {
2501
    DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
2502
    return 0;
2503
2504
  } else {
2505
    char ssl_error_buf[512];
2506
    ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
2507
2508
    HandleScope scope(ssl_env()->isolate());
2509
    Local<Value> exception =
2510
        Exception::Error(OneByteString(ssl_env()->isolate(), ssl_error_buf));
2511
    object()->Set(ssl_env()->error_string(), exception);
2512
2513
    DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n",
2514
                ssl_,
2515
                func,
2516
                rv,
2517
                ssl_error_buf);
2518
2519
    return rv;
2520
  }
2521
2522
  return 0;
2523
}
2524
2525
2526
25
int Connection::HandleSSLError(const char* func,
2527
                               int rv,
2528
                               ZeroStatus zs,
2529
                               SyscallStatus ss) {
2530
  ClearErrorOnReturn clear_error_on_return;
2531
  (void) &clear_error_on_return;  // Silence unused variable warning.
2532
2533
25
  if (rv > 0)
2534
    return rv;
2535
21
  if (rv == 0 && zs == kZeroIsNotAnError)
2536
    return rv;
2537
2538
20
  int err = SSL_get_error(ssl_, rv);
2539
2540
20
  if (err == SSL_ERROR_NONE) {
2541
    return 0;
2542
2543
20
  } else if (err == SSL_ERROR_WANT_WRITE) {
2544
    DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
2545
    return 0;
2546
2547
20
  } else if (err == SSL_ERROR_WANT_READ) {
2548
    DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
2549
    return 0;
2550
2551
1
  } else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2552
    DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2553
    return 0;
2554
2555
1
  } else if (err == SSL_ERROR_ZERO_RETURN) {
2556
    HandleScope scope(ssl_env()->isolate());
2557
2558
    Local<Value> exception =
2559
        Exception::Error(ssl_env()->zero_return_string());
2560
    object()->Set(ssl_env()->error_string(), exception);
2561
    return rv;
2562
2563
1
  } else if (err == SSL_ERROR_SYSCALL && ss == kIgnoreSyscall) {
2564
    return 0;
2565
2566
  } else {
2567
2
    HandleScope scope(ssl_env()->isolate());
2568
    BUF_MEM* mem;
2569
    BIO *bio;
2570
2571
1
    CHECK(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
2572
2573
    // XXX We need to drain the error queue for this thread or else OpenSSL
2574
    // has the possibility of blocking connections? This problem is not well
2575
    // understood. And we should be somehow propagating these errors up
2576
    // into JavaScript. There is no test which demonstrates this problem.
2577
    // https://github.com/joyent/node/issues/1719
2578
1
    bio = BIO_new(BIO_s_mem());
2579
1
    if (bio != nullptr) {
2580
1
      ERR_print_errors(bio);
2581
1
      BIO_get_mem_ptr(bio, &mem);
2582
      Local<Value> exception = Exception::Error(
2583
          OneByteString(ssl_env()->isolate(),
2584
1
            mem->data,
2585
2
            mem->length));
2586
4
      object()->Set(ssl_env()->error_string(), exception);
2587
1
      BIO_free_all(bio);
2588
    }
2589
2590
    return rv;
2591
  }
2592
2593
  return 0;
2594
}
2595
2596
2597
void Connection::ClearError() {
2598
#ifndef NDEBUG
2599
  HandleScope scope(ssl_env()->isolate());
2600
2601
  // We should clear the error in JS-land
2602
  Local<String> error_key = ssl_env()->error_string();
2603
  Local<Value> error = object()->Get(error_key);
2604
  CHECK_EQ(error->BooleanValue(), false);
2605
#endif  // NDEBUG
2606
}
2607
2608
2609
36
void Connection::SetShutdownFlags() {
2610
72
  HandleScope scope(ssl_env()->isolate());
2611
2612
36
  int flags = SSL_get_shutdown(ssl_);
2613
2614
36
  if (flags & SSL_SENT_SHUTDOWN) {
2615
    Local<String> sent_shutdown_key = ssl_env()->sent_shutdown_string();
2616
    object()->Set(sent_shutdown_key, True(ssl_env()->isolate()));
2617
  }
2618
2619
36
  if (flags & SSL_RECEIVED_SHUTDOWN) {
2620
2
    Local<String> received_shutdown_key = ssl_env()->received_shutdown_string();
2621
5
    object()->Set(received_shutdown_key, True(ssl_env()->isolate()));
2622
  }
2623
36
}
2624
2625
2626
void Connection::NewSessionDoneCb() {
2627
  HandleScope scope(env()->isolate());
2628
2629
  MakeCallback(env()->onnewsessiondone_string(), 0, nullptr);
2630
}
2631
2632
2633
182
void Connection::Initialize(Environment* env, Local<Object> target) {
2634
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Connection::New);
2635
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
2636
182
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"));
2637
2638
182
  env->SetProtoMethod(t, "encIn", Connection::EncIn);
2639
182
  env->SetProtoMethod(t, "clearOut", Connection::ClearOut);
2640
182
  env->SetProtoMethod(t, "clearIn", Connection::ClearIn);
2641
182
  env->SetProtoMethod(t, "encOut", Connection::EncOut);
2642
182
  env->SetProtoMethod(t, "clearPending", Connection::ClearPending);
2643
182
  env->SetProtoMethod(t, "encPending", Connection::EncPending);
2644
182
  env->SetProtoMethod(t, "start", Connection::Start);
2645
182
  env->SetProtoMethod(t, "close", Connection::Close);
2646
2647
182
  SSLWrap<Connection>::AddMethods(env, t);
2648
2649
2650
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2651
182
  env->SetProtoMethod(t, "getServername", Connection::GetServername);
2652
182
  env->SetProtoMethod(t, "setSNICallback",  Connection::SetSNICallback);
2653
#endif
2654
2655
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"),
2656
182
              t->GetFunction());
2657
182
}
2658
2659
2660
inline int compar(const void* a, const void* b) {
2661
10
  return memcmp(a, b, CNNIC_WHITELIST_HASH_LEN);
2662
}
2663
2664
2665
65
inline int IsSelfSigned(X509* cert) {
2666
65
  return X509_NAME_cmp(X509_get_subject_name(cert),
2667
130
                       X509_get_issuer_name(cert)) == 0;
2668
}
2669
2670
2671
inline X509* FindRoot(STACK_OF(X509)* sk) {
2672
  for (int i = 0; i < sk_X509_num(sk); i++) {
2673
    X509* cert = sk_X509_value(sk, i);
2674
    if (IsSelfSigned(cert))
2675
      return cert;
2676
  }
2677
  return nullptr;
2678
}
2679
2680
2681
// Whitelist check for certs issued by CNNIC. See
2682
// https://blog.mozilla.org/security/2015/04/02
2683
// /distrusting-new-cnnic-certificates/
2684
65
inline CheckResult CheckWhitelistedServerCert(X509_STORE_CTX* ctx) {
2685
  unsigned char hash[CNNIC_WHITELIST_HASH_LEN];
2686
65
  unsigned int hashlen = CNNIC_WHITELIST_HASH_LEN;
2687
2688
65
  STACK_OF(X509)* chain = X509_STORE_CTX_get1_chain(ctx);
2689
65
  CHECK_NE(chain, nullptr);
2690
65
  CHECK_GT(sk_X509_num(chain), 0);
2691
2692
  // Take the last cert as root at the first time.
2693
65
  X509* root_cert = sk_X509_value(chain, sk_X509_num(chain)-1);
2694
65
  X509_NAME* root_name = X509_get_subject_name(root_cert);
2695
2696
65
  if (!IsSelfSigned(root_cert)) {
2697
    root_cert = FindRoot(chain);
2698
    CHECK_NE(root_cert, nullptr);
2699
    root_name = X509_get_subject_name(root_cert);
2700
  }
2701
2702
  // When the cert is issued from either CNNNIC ROOT CA or CNNNIC EV
2703
  // ROOT CA, check a hash of its leaf cert if it is in the whitelist.
2704

129
  if (X509_NAME_cmp(root_name, cnnic_name) == 0 ||
2705
64
      X509_NAME_cmp(root_name, cnnic_ev_name) == 0) {
2706
1
    X509* leaf_cert = sk_X509_value(chain, 0);
2707
1
    int ret = X509_digest(leaf_cert, EVP_sha256(), hash,
2708
1
                          &hashlen);
2709
1
    CHECK(ret);
2710
2711
    void* result = bsearch(hash, WhitelistedCNNICHashes,
2712
                           arraysize(WhitelistedCNNICHashes),
2713
1
                           CNNIC_WHITELIST_HASH_LEN, compar);
2714
1
    if (result == nullptr) {
2715
1
      sk_X509_pop_free(chain, X509_free);
2716
1
      return CHECK_CERT_REVOKED;
2717
    }
2718
  }
2719
2720
64
  sk_X509_pop_free(chain, X509_free);
2721
64
  return CHECK_OK;
2722
}
2723
2724
2725
527
inline int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2726
  // Failure on verification of the cert is handled in
2727
  // Connection::VerifyError.
2728

527
  if (preverify_ok == 0 || X509_STORE_CTX_get_error(ctx) != X509_V_OK)
2729
    return 1;
2730
2731
  // Server does not need to check the whitelist.
2732
  SSL* ssl = static_cast<SSL*>(
2733
82
      X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
2734
2735
82
  if (SSL_is_server(ssl))
2736
    return 1;
2737
2738
  // Client needs to check if the server cert is listed in the
2739
  // whitelist when it is issued by the specific rootCAs.
2740
65
  CheckResult ret = CheckWhitelistedServerCert(ctx);
2741
65
  if (ret == CHECK_CERT_REVOKED)
2742
1
    X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
2743
2744
65
  return ret;
2745
}
2746
2747
2748
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2749
3
int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
2750
3
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(s));
2751
3
  Environment* env = conn->env();
2752
6
  HandleScope scope(env->isolate());
2753
2754
3
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2755
2756
3
  if (servername) {
2757
2
    conn->servername_.Reset(env->isolate(),
2758
4
                            OneByteString(env->isolate(), servername));
2759
2760
    // Call the SNI callback and use its return value as context
2761
4
    if (!conn->sniObject_.IsEmpty()) {
2762
4
      conn->sni_context_.Reset();
2763
2764
      Local<Object> sni_obj = PersistentToLocal(env->isolate(),
2765
2
                                                conn->sniObject_);
2766
2767
4
      Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
2768
      Local<Value> ret = node::MakeCallback(env->isolate(),
2769
                                            sni_obj,
2770
                                            env->onselect_string(),
2771
                                            1,
2772
2
                                            &arg);
2773
2774
      // If ret is SecureContext
2775
      Local<FunctionTemplate> secure_context_constructor_template =
2776
2
          env->secure_context_constructor_template();
2777
2
      if (secure_context_constructor_template->HasInstance(ret)) {
2778
        conn->sni_context_.Reset(env->isolate(), ret);
2779
        SecureContext* sc;
2780
        ASSIGN_OR_RETURN_UNWRAP(&sc, ret.As<Object>(), SSL_TLSEXT_ERR_NOACK);
2781
        conn->SetSNIContext(sc);
2782
      } else {
2783
        return SSL_TLSEXT_ERR_NOACK;
2784
      }
2785
    }
2786
  }
2787
2788
  return SSL_TLSEXT_ERR_OK;
2789
}
2790
#endif
2791
2792
7
void Connection::New(const FunctionCallbackInfo<Value>& args) {
2793
7
  Environment* env = Environment::GetCurrent(args);
2794
2795

21
  if (args.Length() < 1 || !args[0]->IsObject()) {
2796
    env->ThrowError("First argument must be a tls module SecureContext");
2797
    return;
2798
  }
2799
2800
  SecureContext* sc;
2801
12
  ASSIGN_OR_RETURN_UNWRAP(&sc, args[0].As<Object>());
2802
2803
6
  bool is_server = args[1]->BooleanValue();
2804
2805
  SSLWrap<Connection>::Kind kind =
2806
6
      is_server ? SSLWrap<Connection>::kServer : SSLWrap<Connection>::kClient;
2807
6
  Connection* conn = new Connection(env, args.This(), sc, kind);
2808
6
  conn->bio_read_ = NodeBIO::New();
2809
6
  conn->bio_write_ = NodeBIO::New();
2810
2811
6
  SSL_set_app_data(conn->ssl_, conn);
2812
2813
6
  if (is_server)
2814
4
    SSL_set_info_callback(conn->ssl_, SSLInfoCallback);
2815
2816
6
  InitNPN(sc);
2817
2818
6
  SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
2819
2820
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2821
6
  if (is_server) {
2822
4
    SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
2823
4
  } else if (args[2]->IsString()) {
2824
    const node::Utf8Value servername(env->isolate(), args[2]);
2825
    SSL_set_tlsext_host_name(conn->ssl_, *servername);
2826
  }
2827
#endif
2828
2829
6
  SSL_set_bio(conn->ssl_, conn->bio_read_, conn->bio_write_);
2830
2831
#ifdef SSL_MODE_RELEASE_BUFFERS
2832
6
  long mode = SSL_get_mode(conn->ssl_);  // NOLINT(runtime/int)
2833
6
  SSL_set_mode(conn->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
2834
#endif
2835
2836
2837
  int verify_mode;
2838
6
  if (is_server) {
2839
4
    bool request_cert = args[2]->BooleanValue();
2840
4
    if (!request_cert) {
2841
      // Note reject_unauthorized ignored.
2842
      verify_mode = SSL_VERIFY_NONE;
2843
    } else {
2844
      bool reject_unauthorized = args[3]->BooleanValue();
2845
      verify_mode = SSL_VERIFY_PEER;
2846
      if (reject_unauthorized)
2847
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2848
    }
2849
  } else {
2850
    // Note request_cert and reject_unauthorized are ignored for clients.
2851
    verify_mode = SSL_VERIFY_NONE;
2852
  }
2853
2854
2855
  // Always allow a connection. We'll reject in javascript.
2856
6
  SSL_set_verify(conn->ssl_, verify_mode, VerifyCallback);
2857
2858
6
  if (is_server) {
2859
4
    SSL_set_accept_state(conn->ssl_);
2860
  } else {
2861
2
    SSL_set_connect_state(conn->ssl_);
2862
  }
2863
}
2864
2865
2866
48
void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
2867
48
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
2868
43
    return;
2869
2870
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
2871
  // a non-const SSL* in OpenSSL <= 0.9.7e.
2872
5
  SSL* ssl = const_cast<SSL*>(ssl_);
2873
5
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(ssl));
2874
5
  Environment* env = conn->env();
2875
10
  HandleScope handle_scope(env->isolate());
2876
15
  Context::Scope context_scope(env->context());
2877
2878
5
  if (where & SSL_CB_HANDSHAKE_START) {
2879
4
    conn->MakeCallback(env->onhandshakestart_string(), 0, nullptr);
2880
  }
2881
2882
5
  if (where & SSL_CB_HANDSHAKE_DONE) {
2883
1
    conn->MakeCallback(env->onhandshakedone_string(), 0, nullptr);
2884
  }
2885
}
2886
2887
2888
6
void Connection::EncIn(const FunctionCallbackInfo<Value>& args) {
2889
  Connection* conn;
2890
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2891
6
  Environment* env = conn->env();
2892
2893
6
  if (args.Length() < 3) {
2894
    return env->ThrowTypeError(
2895
        "Data, offset, and length arguments are mandatory");
2896
  }
2897
2898
6
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
2899
2900
6
  char* buffer_data = Buffer::Data(args[0]);
2901
6
  size_t buffer_length = Buffer::Length(args[0]);
2902
2903
6
  size_t off = args[1]->Int32Value();
2904
6
  size_t len = args[2]->Int32Value();
2905
2906
6
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
2907
    return env->ThrowRangeError("offset + length > buffer.length");
2908
2909
  int bytes_written;
2910
6
  char* data = buffer_data + off;
2911
2912

6
  if (conn->is_server() && !conn->hello_parser_.IsEnded()) {
2913
    // Just accumulate data, everything will be pushed to BIO later
2914
3
    if (conn->hello_parser_.IsPaused()) {
2915
      bytes_written = 0;
2916
    } else {
2917
      // Copy incoming data to the internal buffer
2918
      // (which has a size of the biggest possible TLS frame)
2919
3
      size_t available = sizeof(conn->hello_data_) - conn->hello_offset_;
2920
3
      size_t copied = len < available ? len : available;
2921
6
      memcpy(conn->hello_data_ + conn->hello_offset_, data, copied);
2922
3
      conn->hello_offset_ += copied;
2923
2924
3
      conn->hello_parser_.Parse(conn->hello_data_, conn->hello_offset_);
2925
3
      bytes_written = copied;
2926
    }
2927
  } else {
2928
3
    bytes_written = BIO_write(conn->bio_read_, data, len);
2929
3
    conn->HandleBIOError(conn->bio_read_, "BIO_write", bytes_written);
2930
3
    conn->SetShutdownFlags();
2931
  }
2932
2933
12
  args.GetReturnValue().Set(bytes_written);
2934
}
2935
2936
2937
16
void Connection::ClearOut(const FunctionCallbackInfo<Value>& args) {
2938
  Connection* conn;
2939
16
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2940
16
  Environment* env = conn->env();
2941
2942
16
  if (args.Length() < 3) {
2943
    return env->ThrowTypeError(
2944
        "Data, offset, and length arguments are mandatory");
2945
  }
2946
2947
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
2948
2949
16
  char* buffer_data = Buffer::Data(args[0]);
2950
16
  size_t buffer_length = Buffer::Length(args[0]);
2951
2952
16
  size_t off = args[1]->Int32Value();
2953
16
  size_t len = args[2]->Int32Value();
2954
2955
16
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
2956
    return env->ThrowRangeError("offset + length > buffer.length");
2957
2958
16
  if (!SSL_is_init_finished(conn->ssl_)) {
2959
    int rv;
2960
2961
10
    if (conn->is_server()) {
2962
10
      rv = SSL_accept(conn->ssl_);
2963
      conn->HandleSSLError("SSL_accept:ClearOut",
2964
                           rv,
2965
                           kZeroIsAnError,
2966
10
                           kSyscallError);
2967
    } else {
2968
      rv = SSL_connect(conn->ssl_);
2969
      conn->HandleSSLError("SSL_connect:ClearOut",
2970
                           rv,
2971
                           kZeroIsAnError,
2972
                           kSyscallError);
2973
    }
2974
2975
10
    if (rv < 0) {
2976
18
      return args.GetReturnValue().Set(rv);
2977
    }
2978
  }
2979
2980
7
  int bytes_read = SSL_read(conn->ssl_, buffer_data + off, len);
2981
  conn->HandleSSLError("SSL_read:ClearOut",
2982
                       bytes_read,
2983
                       kZeroIsNotAnError,
2984
7
                       kSyscallError);
2985
7
  conn->SetShutdownFlags();
2986
2987
14
  args.GetReturnValue().Set(bytes_read);
2988
}
2989
2990
2991
19
void Connection::ClearPending(const FunctionCallbackInfo<Value>& args) {
2992
  Connection* conn;
2993
19
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2994
19
  int bytes_pending = BIO_pending(conn->bio_read_);
2995
38
  args.GetReturnValue().Set(bytes_pending);
2996
}
2997
2998
2999
26
void Connection::EncPending(const FunctionCallbackInfo<Value>& args) {
3000
  Connection* conn;
3001
26
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3002
26
  int bytes_pending = BIO_pending(conn->bio_write_);
3003
52
  args.GetReturnValue().Set(bytes_pending);
3004
}
3005
3006
3007
21
void Connection::EncOut(const FunctionCallbackInfo<Value>& args) {
3008
  Connection* conn;
3009
21
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3010
21
  Environment* env = conn->env();
3011
3012
21
  if (args.Length() < 3) {
3013
    return env->ThrowTypeError(
3014
        "Data, offset, and length arguments are mandatory");
3015
  }
3016
3017
21
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3018
3019
21
  char* buffer_data = Buffer::Data(args[0]);
3020
21
  size_t buffer_length = Buffer::Length(args[0]);
3021
3022
21
  size_t off = args[1]->Int32Value();
3023
21
  size_t len = args[2]->Int32Value();
3024
3025
21
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3026
    return env->ThrowRangeError("offset + length > buffer.length");
3027
3028
21
  int bytes_read = BIO_read(conn->bio_write_, buffer_data + off, len);
3029
3030
21
  conn->HandleBIOError(conn->bio_write_, "BIO_read:EncOut", bytes_read);
3031
21
  conn->SetShutdownFlags();
3032
3033
42
  args.GetReturnValue().Set(bytes_read);
3034
}
3035
3036
3037
2
void Connection::ClearIn(const FunctionCallbackInfo<Value>& args) {
3038
  Connection* conn;
3039
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3040
2
  Environment* env = conn->env();
3041
3042
2
  if (args.Length() < 3) {
3043
    return env->ThrowTypeError(
3044
        "Data, offset, and length arguments are mandatory");
3045
  }
3046
3047
2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3048
3049
2
  char* buffer_data = Buffer::Data(args[0]);
3050
2
  size_t buffer_length = Buffer::Length(args[0]);
3051
3052
2
  size_t off = args[1]->Int32Value();
3053
2
  size_t len = args[2]->Int32Value();
3054
3055
2
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3056
    return env->ThrowRangeError("offset + length > buffer.length");
3057
3058
2
  if (!SSL_is_init_finished(conn->ssl_)) {
3059
    int rv;
3060
    if (conn->is_server()) {
3061
      rv = SSL_accept(conn->ssl_);
3062
      conn->HandleSSLError("SSL_accept:ClearIn",
3063
                           rv,
3064
                           kZeroIsAnError,
3065
                           kSyscallError);
3066
    } else {
3067
      rv = SSL_connect(conn->ssl_);
3068
      conn->HandleSSLError("SSL_connect:ClearIn",
3069
                           rv,
3070
                           kZeroIsAnError,
3071
                           kSyscallError);
3072
    }
3073
3074
    if (rv < 0) {
3075
      return args.GetReturnValue().Set(rv);
3076
    }
3077
  }
3078
3079
2
  int bytes_written = SSL_write(conn->ssl_, buffer_data + off, len);
3080
3081
2
  conn->HandleSSLError("SSL_write:ClearIn",
3082
                       bytes_written,
3083
                       len == 0 ? kZeroIsNotAnError : kZeroIsAnError,
3084
2
                       kSyscallError);
3085
2
  conn->SetShutdownFlags();
3086
3087
4
  args.GetReturnValue().Set(bytes_written);
3088
}
3089
3090
3091
6
void Connection::Start(const FunctionCallbackInfo<Value>& args) {
3092
  Connection* conn;
3093
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3094
3095
6
  int rv = 0;
3096
6
  if (!SSL_is_init_finished(conn->ssl_)) {
3097
6
    if (conn->is_server()) {
3098
4
      rv = SSL_accept(conn->ssl_);
3099
      conn->HandleSSLError("SSL_accept:Start",
3100
                           rv,
3101
                           kZeroIsAnError,
3102
4
                           kSyscallError);
3103
    } else {
3104
2
      rv = SSL_connect(conn->ssl_);
3105
      conn->HandleSSLError("SSL_connect:Start",
3106
                           rv,
3107
                           kZeroIsAnError,
3108
2
                           kSyscallError);
3109
    }
3110
  }
3111
12
  args.GetReturnValue().Set(rv);
3112
}
3113
3114
3115
2
void Connection::Close(const FunctionCallbackInfo<Value>& args) {
3116
  Connection* conn;
3117
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3118
3119
2
  if (conn->ssl_ != nullptr) {
3120
2
    SSL_free(conn->ssl_);
3121
2
    conn->ssl_ = nullptr;
3122
  }
3123
}
3124
3125
3126
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3127
1
void Connection::GetServername(const FunctionCallbackInfo<Value>& args) {
3128
  Connection* conn;
3129
1
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3130
3131

2
  if (conn->is_server() && !conn->servername_.IsEmpty()) {
3132
    args.GetReturnValue().Set(conn->servername_);
3133
  } else {
3134
2
    args.GetReturnValue().Set(false);
3135
  }
3136
}
3137
3138
3139
2
void Connection::SetSNICallback(const FunctionCallbackInfo<Value>& args) {
3140
  Connection* conn;
3141
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3142
2
  Environment* env = conn->env();
3143
3144

6
  if (args.Length() < 1 || !args[0]->IsFunction()) {
3145
    return env->ThrowError("Must give a Function as first argument");
3146
  }
3147
3148
2
  Local<Object> obj = Object::New(env->isolate());
3149
6
  obj->Set(FIXED_ONE_BYTE_STRING(args.GetIsolate(), "onselect"), args[0]);
3150
2
  conn->sniObject_.Reset(args.GetIsolate(), obj);
3151
}
3152
#endif
3153
3154
3155
182
void CipherBase::Initialize(Environment* env, Local<Object> target) {
3156
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3157
3158
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3159
3160
182
  env->SetProtoMethod(t, "init", Init);
3161
182
  env->SetProtoMethod(t, "initiv", InitIv);
3162
182
  env->SetProtoMethod(t, "update", Update);
3163
182
  env->SetProtoMethod(t, "final", Final);
3164
182
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
3165
182
  env->SetProtoMethod(t, "getAuthTag", GetAuthTag);
3166
182
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
3167
182
  env->SetProtoMethod(t, "setAAD", SetAAD);
3168
3169
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
3170
182
              t->GetFunction());
3171
182
}
3172
3173
3174
87
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
3175
87
  CHECK_EQ(args.IsConstructCall(), true);
3176
87
  CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher;
3177
87
  Environment* env = Environment::GetCurrent(args);
3178
87
  new CipherBase(env, args.This(), kind);
3179
87
}
3180
3181
3182
33
void CipherBase::Init(const char* cipher_type,
3183
                      const char* key_buf,
3184
                      int key_buf_len) {
3185
66
  HandleScope scope(env()->isolate());
3186
3187
#ifdef NODE_FIPS_MODE
3188
  if (FIPS_mode()) {
3189
    return env()->ThrowError(
3190
        "crypto.createCipher() is not supported in FIPS mode.");
3191
  }
3192
#endif  // NODE_FIPS_MODE
3193
3194
33
  CHECK_EQ(cipher_, nullptr);
3195
33
  cipher_ = EVP_get_cipherbyname(cipher_type);
3196
33
  if (cipher_ == nullptr) {
3197
    return env()->ThrowError("Unknown cipher");
3198
  }
3199
3200
  unsigned char key[EVP_MAX_KEY_LENGTH];
3201
  unsigned char iv[EVP_MAX_IV_LENGTH];
3202
3203
33
  int key_len = EVP_BytesToKey(cipher_,
3204
                               EVP_md5(),
3205
                               nullptr,
3206
                               reinterpret_cast<const unsigned char*>(key_buf),
3207
                               key_buf_len,
3208
                               1,
3209
                               key,
3210
33
                               iv);
3211
3212
33
  EVP_CIPHER_CTX_init(&ctx_);
3213
33
  const bool encrypt = (kind_ == kCipher);
3214
33
  EVP_CipherInit_ex(&ctx_, cipher_, nullptr, nullptr, nullptr, encrypt);
3215
33
  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3216
    EVP_CIPHER_CTX_cleanup(&ctx_);
3217
    return env()->ThrowError("Invalid key length");
3218
  }
3219
3220
33
  EVP_CipherInit_ex(&ctx_,
3221
                    nullptr,
3222
                    nullptr,
3223
                    reinterpret_cast<unsigned char*>(key),
3224
                    reinterpret_cast<unsigned char*>(iv),
3225
66
                    kind_ == kCipher);
3226
33
  initialised_ = true;
3227
}
3228
3229
3230
33
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
3231
  CipherBase* cipher;
3232
33
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3233
33
  Environment* env = cipher->env();
3234
3235
33
  if (args.Length() < 2) {
3236
    return env->ThrowError("Cipher type and key arguments are mandatory");
3237
  }
3238
3239
66
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3240
33
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3241
3242
99
  const node::Utf8Value cipher_type(args.GetIsolate(), args[0]);
3243
33
  const char* key_buf = Buffer::Data(args[1]);
3244
33
  ssize_t key_buf_len = Buffer::Length(args[1]);
3245
33
  cipher->Init(*cipher_type, key_buf, key_buf_len);
3246
}
3247
3248
3249
54
void CipherBase::InitIv(const char* cipher_type,
3250
                        const char* key,
3251
                        int key_len,
3252
                        const char* iv,
3253
                        int iv_len) {
3254
108
  HandleScope scope(env()->isolate());
3255
3256
54
  cipher_ = EVP_get_cipherbyname(cipher_type);
3257
54
  if (cipher_ == nullptr) {
3258
    return env()->ThrowError("Unknown cipher");
3259
  }
3260
3261
  /* OpenSSL versions up to 0.9.8l failed to return the correct
3262
     iv_length (0) for ECB ciphers */
3263

108
  if (EVP_CIPHER_iv_length(cipher_) != iv_len &&
3264
      !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_ECB_MODE && iv_len == 0) &&
3265

54
      !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_GCM_MODE) && iv_len > 0) {
3266
    return env()->ThrowError("Invalid IV length");
3267
  }
3268
3269
54
  EVP_CIPHER_CTX_init(&ctx_);
3270
54
  const bool encrypt = (kind_ == kCipher);
3271
54
  EVP_CipherInit_ex(&ctx_, cipher_, nullptr, nullptr, nullptr, encrypt);
3272
3273
  /* Set IV length. Only required if GCM cipher and IV is not default iv. */
3274

56
  if (EVP_CIPHER_mode(cipher_) == EVP_CIPH_GCM_MODE &&
3275
2
      iv_len != EVP_CIPHER_iv_length(cipher_)) {
3276
    if (!EVP_CIPHER_CTX_ctrl(&ctx_, EVP_CTRL_GCM_SET_IVLEN, iv_len, nullptr)) {
3277
      EVP_CIPHER_CTX_cleanup(&ctx_);
3278
      return env()->ThrowError("Invalid IV length");
3279
    }
3280
  }
3281
3282
54
  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3283
    EVP_CIPHER_CTX_cleanup(&ctx_);
3284
    return env()->ThrowError("Invalid key length");
3285
  }
3286
3287
54
  EVP_CipherInit_ex(&ctx_,
3288
                    nullptr,
3289
                    nullptr,
3290
                    reinterpret_cast<const unsigned char*>(key),
3291
                    reinterpret_cast<const unsigned char*>(iv),
3292
108
                    kind_ == kCipher);
3293
54
  initialised_ = true;
3294
}
3295
3296
3297
54
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
3298
  CipherBase* cipher;
3299
54
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3300
54
  Environment* env = cipher->env();
3301
3302
54
  if (args.Length() < 3) {
3303
    return env->ThrowError("Cipher type, key, and IV arguments are mandatory");
3304
  }
3305
3306
108
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3307
54
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3308
54
  THROW_AND_RETURN_IF_NOT_BUFFER(args[2], "IV");
3309
3310
108
  const node::Utf8Value cipher_type(env->isolate(), args[0]);
3311
54
  ssize_t key_len = Buffer::Length(args[1]);
3312
54
  const char* key_buf = Buffer::Data(args[1]);
3313
54
  ssize_t iv_len = Buffer::Length(args[2]);
3314
54
  const char* iv_buf = Buffer::Data(args[2]);
3315
54
  cipher->InitIv(*cipher_type, key_buf, key_len, iv_buf, iv_len);
3316
}
3317
3318
3319
bool CipherBase::IsAuthenticatedMode() const {
3320
  // check if this cipher operates in an AEAD mode that we support.
3321



92
  if (!cipher_)
3322
    return false;
3323
92
  int mode = EVP_CIPHER_mode(cipher_);
3324
92
  return mode == EVP_CIPH_GCM_MODE;
3325
}
3326
3327
3328
1
bool CipherBase::GetAuthTag(char** out, unsigned int* out_len) const {
3329
  // only callable after Final and if encrypting.
3330

1
  if (initialised_ || kind_ != kCipher || !auth_tag_)
3331
    return false;
3332
1
  *out_len = auth_tag_len_;
3333
2
  *out = static_cast<char*>(node::Malloc(auth_tag_len_));
3334
1
  CHECK_NE(*out, nullptr);
3335
2
  memcpy(*out, auth_tag_, auth_tag_len_);
3336
1
  return true;
3337
}
3338
3339
3340
1
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
3341
1
  Environment* env = Environment::GetCurrent(args);
3342
  CipherBase* cipher;
3343
1
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3344
3345
1
  char* out = nullptr;
3346
1
  unsigned int out_len = 0;
3347
3348
1
  if (cipher->GetAuthTag(&out, &out_len)) {
3349
2
    Local<Object> buf = Buffer::New(env, out, out_len).ToLocalChecked();
3350
1
    args.GetReturnValue().Set(buf);
3351
  } else {
3352
    env->ThrowError("Attempting to get auth tag in unsupported state");
3353
  }
3354
}
3355
3356
3357
1
bool CipherBase::SetAuthTag(const char* data, unsigned int len) {
3358


2
  if (!initialised_ || !IsAuthenticatedMode() || kind_ != kDecipher)
3359
    return false;
3360
1
  delete[] auth_tag_;
3361
1
  auth_tag_len_ = len;
3362
1
  auth_tag_ = new char[len];
3363
2
  memcpy(auth_tag_, data, len);
3364
1
  return true;
3365
}
3366
3367
3368
1
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
3369
1
  Environment* env = Environment::GetCurrent(args);
3370
3371
2
  Local<Object> buf = args[0].As<Object>();
3372
3373

1
  if (!buf->IsObject() || !Buffer::HasInstance(buf))
3374
    return env->ThrowTypeError("Auth tag must be a Buffer");
3375
3376
  CipherBase* cipher;
3377
1
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3378
3379
1
  if (!cipher->SetAuthTag(Buffer::Data(buf), Buffer::Length(buf)))
3380
    env->ThrowError("Attempting to set auth tag in unsupported state");
3381
}
3382
3383
3384
bool CipherBase::SetAAD(const char* data, unsigned int len) {
3385
  if (!initialised_ || !IsAuthenticatedMode())
3386
    return false;
3387
  int outlen;
3388
  if (!EVP_CipherUpdate(&ctx_,
3389
                        nullptr,
3390
                        &outlen,
3391
                        reinterpret_cast<const unsigned char*>(data),
3392
                        len)) {
3393
    return false;
3394
  }
3395
  return true;
3396
}
3397
3398
3399
void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
3400
  Environment* env = Environment::GetCurrent(args);
3401
3402
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "AAD");
3403
3404
  CipherBase* cipher;
3405
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3406
3407
  if (!cipher->SetAAD(Buffer::Data(args[0]), Buffer::Length(args[0])))
3408
    env->ThrowError("Attempting to set AAD in unsupported state");
3409
}
3410
3411
3412
81
bool CipherBase::Update(const char* data,
3413
                        int len,
3414
                        unsigned char** out,
3415
                        int* out_len) {
3416
81
  if (!initialised_)
3417
    return 0;
3418
3419
  // on first update:
3420


121
  if (kind_ == kDecipher && IsAuthenticatedMode() && auth_tag_ != nullptr) {
3421
1
    EVP_CIPHER_CTX_ctrl(&ctx_,
3422
                        EVP_CTRL_GCM_SET_TAG,
3423
1
                        auth_tag_len_,
3424
2
                        reinterpret_cast<unsigned char*>(auth_tag_));
3425
1
    delete[] auth_tag_;
3426
1
    auth_tag_ = nullptr;
3427
  }
3428
3429
81
  *out_len = len + EVP_CIPHER_CTX_block_size(&ctx_);
3430
81
  *out = new unsigned char[*out_len];
3431
81
  return EVP_CipherUpdate(&ctx_,
3432
                          *out,
3433
                          out_len,
3434
                          reinterpret_cast<const unsigned char*>(data),
3435
81
                          len);
3436
}
3437
3438
3439
83
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
3440
83
  Environment* env = Environment::GetCurrent(args);
3441
3442
  CipherBase* cipher;
3443
85
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3444
3445

314
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Cipher data");
3446
3447
83
  unsigned char* out = nullptr;
3448
  bool r;
3449
83
  int out_len = 0;
3450
3451
  // Only copy the data if we have to, because it's a string
3452
166
  if (args[0]->IsString()) {
3453
146
    StringBytes::InlineDecoder decoder;
3454
222
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3455
2
      return;
3456
72
    r = cipher->Update(decoder.out(), decoder.size(), &out, &out_len);
3457
  } else {
3458
9
    char* buf = Buffer::Data(args[0]);
3459
9
    size_t buflen = Buffer::Length(args[0]);
3460
9
    r = cipher->Update(buf, buflen, &out, &out_len);
3461
  }
3462
3463
81
  if (!r) {
3464