GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/node_crypto.cc Lines: 2734 3088 88.5 %
Date: 2017-12-18 Branches: 1246 2194 56.8 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node.h"
23
#include "node_buffer.h"
24
#include "node_constants.h"
25
#include "node_crypto.h"
26
#include "node_crypto_bio.h"
27
#include "node_crypto_groups.h"
28
#include "node_crypto_clienthello-inl.h"
29
#include "node_mutex.h"
30
#include "tls_wrap.h"  // TLSWrap
31
32
#include "async_wrap-inl.h"
33
#include "env-inl.h"
34
#include "string_bytes.h"
35
#include "util-inl.h"
36
#include "v8.h"
37
// CNNIC Hash WhiteList is taken from
38
// https://hg.mozilla.org/mozilla-central/raw-file/98820360ab66/security/
39
// certverifier/CNNICHashWhitelist.inc
40
#include "CNNICHashWhitelist.inc"
41
// StartCom and WoSign root CA list is taken from
42
// https://hg.mozilla.org/mozilla-central/file/tip/security/certverifier/
43
// StartComAndWoSignData.inc
44
#include "StartComAndWoSignData.inc"
45
46
#include <algorithm>
47
#include <errno.h>
48
#include <limits.h>  // INT_MAX
49
#include <math.h>
50
#include <stdlib.h>
51
#include <string.h>
52
#include <vector>
53
54
#define THROW_AND_RETURN_IF_NOT_BUFFER(val, prefix)           \
55
  do {                                                        \
56
    if (!Buffer::HasInstance(val)) {                          \
57
      return env->ThrowTypeError(prefix " must be a buffer"); \
58
    }                                                         \
59
  } while (0)
60
61
#define THROW_AND_RETURN_IF_NOT_STRING(val, prefix)           \
62
  do {                                                        \
63
    if (!val->IsString()) {                                   \
64
      return env->ThrowTypeError(prefix " must be a string"); \
65
    }                                                         \
66
  } while (0)
67
68
static const char PUBLIC_KEY_PFX[] =  "-----BEGIN PUBLIC KEY-----";
69
static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
70
static const char PUBRSA_KEY_PFX[] =  "-----BEGIN RSA PUBLIC KEY-----";
71
static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
72
static const char CERTIFICATE_PFX[] =  "-----BEGIN CERTIFICATE-----";
73
static const int CERTIFICATE_PFX_LEN = sizeof(CERTIFICATE_PFX) - 1;
74
75
static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
76
                                 | ASN1_STRFLGS_UTF8_CONVERT
77
                                 | XN_FLAG_SEP_MULTILINE
78
                                 | XN_FLAG_FN_SN;
79
80
namespace node {
81
namespace crypto {
82
83
using v8::Array;
84
using v8::Boolean;
85
using v8::Context;
86
using v8::DEFAULT;
87
using v8::DontDelete;
88
using v8::EscapableHandleScope;
89
using v8::Exception;
90
using v8::External;
91
using v8::False;
92
using v8::FunctionCallbackInfo;
93
using v8::FunctionTemplate;
94
using v8::HandleScope;
95
using v8::Integer;
96
using v8::Isolate;
97
using v8::Local;
98
using v8::Maybe;
99
using v8::MaybeLocal;
100
using v8::Null;
101
using v8::Object;
102
using v8::ObjectTemplate;
103
using v8::Persistent;
104
using v8::PropertyAttribute;
105
using v8::ReadOnly;
106
using v8::Signature;
107
using v8::String;
108
using v8::Value;
109
110
111
#if OPENSSL_VERSION_NUMBER < 0x10100000L
112
71
static void RSA_get0_key(const RSA* r, const BIGNUM** n, const BIGNUM** e,
113
                         const BIGNUM** d) {
114
71
  if (n != nullptr) {
115
71
    *n = r->n;
116
  }
117
71
  if (e != nullptr) {
118
71
    *e = r->e;
119
  }
120
71
  if (d != nullptr) {
121
    *d = r->d;
122
  }
123
71
}
124
125
23
static void DH_get0_pqg(const DH* dh, const BIGNUM** p, const BIGNUM** q,
126
                        const BIGNUM** g) {
127
23
  if (p != nullptr) {
128
17
    *p = dh->p;
129
  }
130
23
  if (q != nullptr) {
131
    *q = dh->q;
132
  }
133
23
  if (g != nullptr) {
134
6
    *g = dh->g;
135
  }
136
23
}
137
138
31
static int DH_set0_pqg(DH* dh, BIGNUM* p, BIGNUM* q, BIGNUM* g) {
139

62
  if ((dh->p == nullptr && p == nullptr) ||
140
62
      (dh->g == nullptr && g == nullptr)) {
141
    return 0;
142
  }
143
144
31
  if (p != nullptr) {
145
31
    BN_free(dh->p);
146
31
    dh->p = p;
147
  }
148
31
  if (q != nullptr) {
149
    BN_free(dh->q);
150
    dh->q = q;
151
  }
152
31
  if (g != nullptr) {
153
31
    BN_free(dh->g);
154
31
    dh->g = g;
155
  }
156
157
31
  return 1;
158
}
159
160
74
static void DH_get0_key(const DH* dh, const BIGNUM** pub_key,
161
                        const BIGNUM** priv_key) {
162
74
  if (pub_key != nullptr) {
163
65
    *pub_key = dh->pub_key;
164
  }
165
74
  if (priv_key != nullptr) {
166
9
    *priv_key = dh->priv_key;
167
  }
168
74
}
169
170
100008
static int DH_set0_key(DH* dh, BIGNUM* pub_key, BIGNUM* priv_key) {
171
100008
  if (pub_key != nullptr) {
172
50003
    BN_free(dh->pub_key);
173
50003
    dh->pub_key = pub_key;
174
  }
175
100008
  if (priv_key != nullptr) {
176
50005
    BN_free(dh->priv_key);
177
50005
    dh->priv_key = priv_key;
178
  }
179
180
100008
  return 1;
181
}
182
183
819
static const SSL_METHOD* TLS_method() { return SSLv23_method(); }
184
185
9
static void SSL_SESSION_get0_ticket(const SSL_SESSION* s,
186
                                    const unsigned char** tick, size_t* len) {
187
9
  *len = s->tlsext_ticklen;
188
9
  if (tick != nullptr) {
189
9
    *tick = s->tlsext_tick;
190
  }
191
9
}
192
193
#define SSL_get_tlsext_status_type(ssl) (ssl->tlsext_status_type)
194
195
686
static int X509_STORE_up_ref(X509_STORE* store) {
196
686
  CRYPTO_add(&store->references, 1, CRYPTO_LOCK_X509_STORE);
197
686
  return 1;
198
}
199
200
30380
static int X509_up_ref(X509* cert) {
201
30380
  CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
202
30380
  return 1;
203
}
204
205
#define EVP_MD_CTX_new EVP_MD_CTX_create
206
#define EVP_MD_CTX_free EVP_MD_CTX_destroy
207
208
134
HMAC_CTX* HMAC_CTX_new() {
209
134
  HMAC_CTX* ctx = Malloc<HMAC_CTX>(1);
210
134
  HMAC_CTX_init(ctx);
211
134
  return ctx;
212
}
213
214
174
void HMAC_CTX_free(HMAC_CTX* ctx) {
215
174
  if (ctx == nullptr) {
216
217
    return;
217
  }
218
131
  HMAC_CTX_cleanup(ctx);
219
131
  free(ctx);
220
}
221
#endif  // OPENSSL_VERSION_NUMBER < 0x10100000L
222
223
// Subject DER of CNNIC ROOT CA and CNNIC EV ROOT CA are taken from
224
// https://hg.mozilla.org/mozilla-central/file/98820360ab66/security/
225
// certverifier/NSSCertDBTrustDomain.cpp#l672
226
// C = CN, O = CNNIC, CN = CNNIC ROOT
227
static const uint8_t CNNIC_ROOT_CA_SUBJECT_DATA[] =
228
    "\x30\x32\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x43\x4E\x31\x0E\x30"
229
    "\x0C\x06\x03\x55\x04\x0A\x13\x05\x43\x4E\x4E\x49\x43\x31\x13\x30\x11\x06"
230
    "\x03\x55\x04\x03\x13\x0A\x43\x4E\x4E\x49\x43\x20\x52\x4F\x4F\x54";
231
static const uint8_t* cnnic_p = CNNIC_ROOT_CA_SUBJECT_DATA;
232
3392
static X509_NAME* cnnic_name =
233
3392
    d2i_X509_NAME(nullptr, &cnnic_p, sizeof(CNNIC_ROOT_CA_SUBJECT_DATA)-1);
234
235
// C = CN, O = China Internet Network Information Center, CN = China
236
// Internet Network Information Center EV Certificates Root
237
static const uint8_t CNNIC_EV_ROOT_CA_SUBJECT_DATA[] =
238
    "\x30\x81\x8A\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x43\x4E\x31\x32"
239
    "\x30\x30\x06\x03\x55\x04\x0A\x0C\x29\x43\x68\x69\x6E\x61\x20\x49\x6E\x74"
240
    "\x65\x72\x6E\x65\x74\x20\x4E\x65\x74\x77\x6F\x72\x6B\x20\x49\x6E\x66\x6F"
241
    "\x72\x6D\x61\x74\x69\x6F\x6E\x20\x43\x65\x6E\x74\x65\x72\x31\x47\x30\x45"
242
    "\x06\x03\x55\x04\x03\x0C\x3E\x43\x68\x69\x6E\x61\x20\x49\x6E\x74\x65\x72"
243
    "\x6E\x65\x74\x20\x4E\x65\x74\x77\x6F\x72\x6B\x20\x49\x6E\x66\x6F\x72\x6D"
244
    "\x61\x74\x69\x6F\x6E\x20\x43\x65\x6E\x74\x65\x72\x20\x45\x56\x20\x43\x65"
245
    "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x73\x20\x52\x6F\x6F\x74";
246
static const uint8_t* cnnic_ev_p = CNNIC_EV_ROOT_CA_SUBJECT_DATA;
247
3392
static X509_NAME *cnnic_ev_name =
248
    d2i_X509_NAME(nullptr, &cnnic_ev_p,
249
3392
                  sizeof(CNNIC_EV_ROOT_CA_SUBJECT_DATA)-1);
250
251
static const char* const root_certs[] = {
252
#include "node_root_certs.h"  // NOLINT(build/include_order)
253
};
254
255
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
256
257
3392
static std::string extra_root_certs_file;  // NOLINT(runtime/string)
258
259
static X509_STORE* root_cert_store;
260
261
// Just to generate static methods
262
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
263
                                           Local<FunctionTemplate> t);
264
template void SSLWrap<TLSWrap>::InitNPN(SecureContext* sc);
265
template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc);
266
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
267
#if OPENSSL_VERSION_NUMBER < 0x10100000L
268
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
269
    SSL* s,
270
    unsigned char* key,
271
    int len,
272
    int* copy);
273
#else
274
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
275
    SSL* s,
276
    const unsigned char* key,
277
    int len,
278
    int* copy);
279
#endif
280
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
281
                                                  SSL_SESSION* sess);
282
template void SSLWrap<TLSWrap>::OnClientHello(
283
    void* arg,
284
    const ClientHelloParser::ClientHello& hello);
285
286
#ifndef OPENSSL_NO_NEXTPROTONEG
287
template int SSLWrap<TLSWrap>::AdvertiseNextProtoCallback(
288
    SSL* s,
289
    const unsigned char** data,
290
    unsigned int* len,
291
    void* arg);
292
template int SSLWrap<TLSWrap>::SelectNextProtoCallback(
293
    SSL* s,
294
    unsigned char** out,
295
    unsigned char* outlen,
296
    const unsigned char* in,
297
    unsigned int inlen,
298
    void* arg);
299
#endif
300
301
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
302
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
303
#endif
304
305
template void SSLWrap<TLSWrap>::DestroySSL();
306
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
307
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
308
309
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
310
template int SSLWrap<TLSWrap>::SelectALPNCallback(
311
    SSL* s,
312
    const unsigned char** out,
313
    unsigned char* outlen,
314
    const unsigned char* in,
315
    unsigned int inlen,
316
    void* arg);
317
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
318
319
#if OPENSSL_VERSION_NUMBER < 0x10100000L
320
static Mutex* mutexes;
321
322
66187
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
323
  static_assert(sizeof(uv_thread_t) <= sizeof(void*),
324
                "uv_thread_t does not fit in a pointer");
325
66187
  CRYPTO_THREADID_set_pointer(tid, reinterpret_cast<void*>(uv_thread_self()));
326
66187
}
327
328
329
420
static void crypto_lock_init(void) {
330

420
  mutexes = new Mutex[CRYPTO_num_locks()];
331
420
}
332
333
334
1811604
static void crypto_lock_cb(int mode, int n, const char* file, int line) {
335
1811604
  CHECK(!(mode & CRYPTO_LOCK) ^ !(mode & CRYPTO_UNLOCK));
336
1811604
  CHECK(!(mode & CRYPTO_READ) ^ !(mode & CRYPTO_WRITE));
337
338
1811604
  auto mutex = &mutexes[n];
339
1811604
  if (mode & CRYPTO_LOCK)
340
905802
    mutex->Lock();
341
  else
342
905802
    mutex->Unlock();
343
1811604
}
344
#endif
345
346
347
29
static int PasswordCallback(char *buf, int size, int rwflag, void *u) {
348
29
  if (u) {
349
26
    size_t buflen = static_cast<size_t>(size);
350
26
    size_t len = strlen(static_cast<const char*>(u));
351
26
    len = len > buflen ? buflen : len;
352
26
    memcpy(buf, u, len);
353
26
    return len;
354
  }
355
356
3
  return 0;
357
}
358
359
// Loads OpenSSL engine by engine id and returns it. The loaded engine
360
// gets a reference so remember the corresponding call to ENGINE_free.
361
// In case of error the appropriate js exception is scheduled
362
// and nullptr is returned.
363
#ifndef OPENSSL_NO_ENGINE
364
2
static ENGINE* LoadEngineById(const char* engine_id, char (*errmsg)[1024]) {
365
2
  MarkPopErrorOnReturn mark_pop_error_on_return;
366
367
2
  ENGINE* engine = ENGINE_by_id(engine_id);
368
369
2
  if (engine == nullptr) {
370
    // Engine not found, try loading dynamically.
371
2
    engine = ENGINE_by_id("dynamic");
372
2
    if (engine != nullptr) {
373

4
      if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", engine_id, 0) ||
374
2
          !ENGINE_ctrl_cmd_string(engine, "LOAD", nullptr, 0)) {
375
2
        ENGINE_free(engine);
376
2
        engine = nullptr;
377
      }
378
    }
379
  }
380
381
2
  if (engine == nullptr) {
382
2
    int err = ERR_get_error();
383
2
    if (err != 0) {
384
2
      ERR_error_string_n(err, *errmsg, sizeof(*errmsg));
385
    } else {
386
      snprintf(*errmsg, sizeof(*errmsg),
387
               "Engine \"%s\" was not found", engine_id);
388
    }
389
  }
390
391
2
  return engine;
392
}
393
#endif  // !OPENSSL_NO_ENGINE
394
395
// This callback is used to avoid the default passphrase callback in OpenSSL
396
// which will typically prompt for the passphrase. The prompting is designed
397
// for the OpenSSL CLI, but works poorly for Node.js because it involves
398
// synchronous interaction with the controlling terminal, something we never
399
// want, and use this function to avoid it.
400
static int NoPasswordCallback(char *buf, int size, int rwflag, void *u) {
401
  return 0;
402
}
403
404
405
29
void ThrowCryptoError(Environment* env,
406
                      unsigned long err,  // NOLINT(runtime/int)
407
                      const char* default_message = nullptr) {
408
29
  HandleScope scope(env->isolate());
409
  Local<String> message;
410
411

29
  if (err != 0 || default_message == nullptr) {
412
25
    char errmsg[128] = { 0 };
413
25
    ERR_error_string_n(err, errmsg, sizeof(errmsg));
414
    message = String::NewFromUtf8(env->isolate(), errmsg,
415
25
                                  v8::NewStringType::kNormal)
416
50
                                      .ToLocalChecked();
417
  } else {
418
    message = String::NewFromUtf8(env->isolate(), default_message,
419
4
                                  v8::NewStringType::kNormal)
420
8
                                      .ToLocalChecked();
421
  }
422
423
29
  Local<Value> exception_v = Exception::Error(message);
424
29
  CHECK(!exception_v.IsEmpty());
425
29
  Local<Object> exception = exception_v.As<Object>();
426
427
58
  std::vector<Local<String>> errors;
428
  for (;;) {
429
60
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
430
60
    if (err == 0) {
431
29
      break;
432
    }
433
    char tmp_str[256];
434
31
    ERR_error_string_n(err, tmp_str, sizeof(tmp_str));
435
    errors.push_back(String::NewFromUtf8(env->isolate(), tmp_str,
436
31
                                         v8::NewStringType::kNormal)
437
62
                     .ToLocalChecked());
438
31
  }
439
440
  // ERR_get_error returns errors in order of most specific to least
441
  // specific. We wish to have the reverse ordering:
442
  // opensslErrorStack: [
443
  // 'error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib',
444
  // 'error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 err'
445
  // ]
446
29
  if (!errors.empty()) {
447
11
    std::reverse(errors.begin(), errors.end());
448
11
    Local<Array> errors_array = Array::New(env->isolate(), errors.size());
449
42
    for (size_t i = 0; i < errors.size(); i++) {
450
124
      errors_array->Set(env->context(), i, errors[i]).FromJust();
451
    }
452
44
    exception->Set(env->context(), env->openssl_error_stack(), errors_array)
453
22
        .FromJust();
454
  }
455
456
58
  env->isolate()->ThrowException(exception);
457
29
}
458
459
460
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
461
// The entropy pool starts out empty and needs to fill up before the PRNG
462
// can be used securely.  Once the pool is filled, it never dries up again;
463
// its contents is stirred and reused when necessary.
464
//
465
// OpenSSL normally fills the pool automatically but not when someone starts
466
// generating random numbers before the pool is full: in that case OpenSSL
467
// keeps lowering the entropy estimate to thwart attackers trying to guess
468
// the initial state of the PRNG.
469
//
470
// When that happens, we will have to wait until enough entropy is available.
471
// That should normally never take longer than a few milliseconds.
472
//
473
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
474
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
475
// block under normal circumstances.
476
//
477
// The only time when /dev/urandom may conceivably block is right after boot,
478
// when the whole system is still low on entropy.  That's not something we can
479
// do anything about.
480
6901
inline void CheckEntropy() {
481
  for (;;) {
482
6901
    int status = RAND_status();
483
6901
    CHECK_GE(status, 0);  // Cannot fail.
484
6901
    if (status != 0)
485
6901
      break;
486
487
    // Give up, RAND_poll() not supported.
488
    if (RAND_poll() == 0)
489
      break;
490
  }
491
6901
}
492
493
494
6758
bool EntropySource(unsigned char* buffer, size_t length) {
495
  // Ensure that OpenSSL's PRNG is properly seeded.
496
6758
  CheckEntropy();
497
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
498
  // random. That's okay, it's still better than V8's stock source of entropy,
499
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
500
6758
  return RAND_bytes(buffer, length) != -1;
501
}
502
503
504
420
void SecureContext::Initialize(Environment* env, Local<Object> target) {
505
420
  Local<FunctionTemplate> t = env->NewFunctionTemplate(SecureContext::New);
506
840
  t->InstanceTemplate()->SetInternalFieldCount(1);
507
  Local<String> secureContextString =
508
420
      FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext");
509
420
  t->SetClassName(secureContextString);
510
511
420
  env->SetProtoMethod(t, "init", Init);
512
420
  env->SetProtoMethod(t, "setKey", SetKey);
513
420
  env->SetProtoMethod(t, "setCert", SetCert);
514
420
  env->SetProtoMethod(t, "addCACert", AddCACert);
515
420
  env->SetProtoMethod(t, "addCRL", AddCRL);
516
420
  env->SetProtoMethod(t, "addRootCerts", AddRootCerts);
517
420
  env->SetProtoMethod(t, "setCiphers", SetCiphers);
518
420
  env->SetProtoMethod(t, "setECDHCurve", SetECDHCurve);
519
420
  env->SetProtoMethod(t, "setDHParam", SetDHParam);
520
420
  env->SetProtoMethod(t, "setOptions", SetOptions);
521
420
  env->SetProtoMethod(t, "setSessionIdContext", SetSessionIdContext);
522
420
  env->SetProtoMethod(t, "setSessionTimeout", SetSessionTimeout);
523
420
  env->SetProtoMethod(t, "close", Close);
524
420
  env->SetProtoMethod(t, "loadPKCS12", LoadPKCS12);
525
#ifndef OPENSSL_NO_ENGINE
526
420
  env->SetProtoMethod(t, "setClientCertEngine", SetClientCertEngine);
527
#endif  // !OPENSSL_NO_ENGINE
528
420
  env->SetProtoMethod(t, "getTicketKeys", GetTicketKeys);
529
420
  env->SetProtoMethod(t, "setTicketKeys", SetTicketKeys);
530
420
  env->SetProtoMethod(t, "setFreeListLength", SetFreeListLength);
531
420
  env->SetProtoMethod(t, "enableTicketKeyCallback", EnableTicketKeyCallback);
532
420
  env->SetProtoMethod(t, "getCertificate", GetCertificate<true>);
533
420
  env->SetProtoMethod(t, "getIssuer", GetCertificate<false>);
534
535
420
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyReturnIndex"),
536
1260
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyReturnIndex));
537
420
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyHMACIndex"),
538
1260
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyHMACIndex));
539
420
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyAESIndex"),
540
1260
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyAESIndex));
541
420
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyNameIndex"),
542
1260
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyNameIndex));
543
420
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyIVIndex"),
544
1260
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyIVIndex));
545
546
  Local<FunctionTemplate> ctx_getter_templ =
547
      FunctionTemplate::New(env->isolate(),
548
                            CtxGetter,
549
                            env->as_external(),
550
840
                            Signature::New(env->isolate(), t));
551
552
553
1260
  t->PrototypeTemplate()->SetAccessorProperty(
554
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
555
      ctx_getter_templ,
556
      Local<FunctionTemplate>(),
557
1260
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
558
559
840
  target->Set(secureContextString, t->GetFunction());
560
420
  env->set_secure_context_constructor_template(t);
561
420
}
562
563
564
818
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
565
818
  Environment* env = Environment::GetCurrent(args);
566
818
  new SecureContext(env, args.This());
567
818
}
568
569
570
818
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
571
  SecureContext* sc;
572
825
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
573
818
  Environment* env = sc->env();
574
575
818
  const SSL_METHOD* method = TLS_method();
576
577


1750
  if (args.Length() == 1 && args[0]->IsString()) {
578
38
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
579
580
    // Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends
581
    // are still accepted.  They are OpenSSL's way of saying that all known
582
    // protocols are supported unless explicitly disabled (which we do below
583
    // for SSLv2 and SSLv3.)
584
38
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
585
1
      return env->ThrowError("SSLv2 methods disabled");
586
37
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
587
1
      return env->ThrowError("SSLv2 methods disabled");
588
36
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
589
1
      return env->ThrowError("SSLv2 methods disabled");
590
35
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
591
1
      return env->ThrowError("SSLv3 methods disabled");
592
34
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
593
1
      return env->ThrowError("SSLv3 methods disabled");
594
33
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
595
1
      return env->ThrowError("SSLv3 methods disabled");
596
32
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
597
2
      method = SSLv23_method();
598
30
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
599
1
      method = SSLv23_server_method();
600
29
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
601
1
      method = SSLv23_client_method();
602
28
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
603
4
      method = TLSv1_method();
604
24
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
605
1
      method = TLSv1_server_method();
606
23
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
607
1
      method = TLSv1_client_method();
608
22
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
609
2
      method = TLSv1_1_method();
610
20
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
611
1
      method = TLSv1_1_server_method();
612
19
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
613
1
      method = TLSv1_1_client_method();
614
18
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
615
14
      method = TLSv1_2_method();
616
4
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
617
2
      method = TLSv1_2_server_method();
618
2
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
619
1
      method = TLSv1_2_client_method();
620
    } else {
621
1
      return env->ThrowError("Unknown method");
622
31
    }
623
  }
624
625
811
  sc->ctx_ = SSL_CTX_new(method);
626
811
  SSL_CTX_set_app_data(sc->ctx_, sc);
627
628
  // Disable SSLv2 in the case when method == TLS_method() and the
629
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
630
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
631
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
632
811
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv2);
633
811
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv3);
634
635
  // SSL session cache configuration
636
811
  SSL_CTX_set_session_cache_mode(sc->ctx_,
637
                                 SSL_SESS_CACHE_SERVER |
638
                                 SSL_SESS_CACHE_NO_INTERNAL |
639
811
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
640
811
  SSL_CTX_sess_set_get_cb(sc->ctx_, SSLWrap<Connection>::GetSessionCallback);
641
811
  SSL_CTX_sess_set_new_cb(sc->ctx_, SSLWrap<Connection>::NewSessionCallback);
642
643
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
644
  // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was
645
  // exposed in the public API. To retain compatibility, install a callback
646
  // which restores the old algorithm.
647
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
648
      RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 ||
649
      RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) {
650
    return env->ThrowError("Error generating ticket keys");
651
  }
652
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_,
653
                                   SecureContext::TicketCompatibilityCallback);
654
#endif
655
}
656
657
658
// Takes a string or buffer and loads it into a BIO.
659
// Caller responsible for BIO_free_all-ing the returned object.
660
850
static BIO* LoadBIO(Environment* env, Local<Value> v) {
661
850
  HandleScope scope(env->isolate());
662
663
1700
  if (v->IsString()) {
664
126
    const node::Utf8Value s(env->isolate(), v);
665
126
    return NodeBIO::NewFixed(*s, s.length());
666
  }
667
668
724
  if (Buffer::HasInstance(v)) {
669
724
    return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
670
  }
671
672
  return nullptr;
673
}
674
675
676
339
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
677
339
  Environment* env = Environment::GetCurrent(args);
678
679
  SecureContext* sc;
680
349
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
681
682
339
  unsigned int len = args.Length();
683
339
  if (len < 1) {
684
    return env->ThrowError("Private key argument is mandatory");
685
  }
686
687
339
  if (len > 2) {
688
    return env->ThrowError("Only private key and pass phrase are expected");
689
  }
690
691
339
  if (len == 2) {
692


1425
    if (args[1]->IsUndefined() || args[1]->IsNull())
693
316
      len = 1;
694
    else
695
69
      THROW_AND_RETURN_IF_NOT_STRING(args[1], "Pass phrase");
696
  }
697
698
337
  BIO *bio = LoadBIO(env, args[0]);
699
337
  if (!bio)
700
    return;
701
702
337
  node::Utf8Value passphrase(env->isolate(), args[1]);
703
704
  EVP_PKEY* key = PEM_read_bio_PrivateKey(bio,
705
                                          nullptr,
706
                                          PasswordCallback,
707
337
                                          len == 1 ? nullptr : *passphrase);
708
709
337
  if (!key) {
710
7
    BIO_free_all(bio);
711
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
712
7
    if (!err) {
713
      return env->ThrowError("PEM_read_bio_PrivateKey");
714
    }
715
7
    return ThrowCryptoError(env, err);
716
  }
717
718
330
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_, key);
719
330
  EVP_PKEY_free(key);
720
330
  BIO_free_all(bio);
721
722
330
  if (!rv) {
723
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
724
1
    if (!err)
725
      return env->ThrowError("SSL_CTX_use_PrivateKey");
726
1
    return ThrowCryptoError(env, err);
727
329
  }
728
}
729
730
731
358
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
732
358
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
733
358
  X509_STORE_CTX* store_ctx = X509_STORE_CTX_new();
734
358
  int ret = store_ctx != nullptr &&
735

716
            X509_STORE_CTX_init(store_ctx, store, nullptr, nullptr) == 1 &&
736
716
            X509_STORE_CTX_get1_issuer(issuer, store_ctx, cert) == 1;
737
358
  X509_STORE_CTX_free(store_ctx);
738
358
  return ret;
739
}
740
741
742
364
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
743
                                  X509* x,
744
                                  STACK_OF(X509)* extra_certs,
745
                                  X509** cert,
746
                                  X509** issuer) {
747
364
  CHECK_EQ(*issuer, nullptr);
748
364
  CHECK_EQ(*cert, nullptr);
749
750
364
  int ret = SSL_CTX_use_certificate(ctx, x);
751
752
364
  if (ret) {
753
    // If we could set up our certificate, now proceed to
754
    // the CA certificates.
755
    int r;
756
757
364
    SSL_CTX_clear_extra_chain_certs(ctx);
758
759
372
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
760
8
      X509* ca = sk_X509_value(extra_certs, i);
761
762
      // NOTE: Increments reference count on `ca`
763
8
      r = SSL_CTX_add1_chain_cert(ctx, ca);
764
765
8
      if (!r) {
766
        ret = 0;
767
        *issuer = nullptr;
768
        goto end;
769
      }
770
      // Note that we must not free r if it was successfully
771
      // added to the chain (while we must free the main
772
      // certificate, since its reference count is increased
773
      // by SSL_CTX_use_certificate).
774
775
      // Find issuer
776

8
      if (*issuer != nullptr || X509_check_issued(ca, x) != X509_V_OK)
777
        continue;
778
779
8
      *issuer = ca;
780
    }
781
  }
782
783
  // Try getting issuer from a cert store
784
364
  if (ret) {
785
364
    if (*issuer == nullptr) {
786
356
      ret = SSL_CTX_get_issuer(ctx, x, issuer);
787
356
      ret = ret < 0 ? 0 : 1;
788
      // NOTE: get_cert_store doesn't increment reference count,
789
      // no need to free `store`
790
    } else {
791
      // Increment issuer reference count
792
8
      *issuer = X509_dup(*issuer);
793
8
      if (*issuer == nullptr) {
794
        ret = 0;
795
        goto end;
796
      }
797
    }
798
  }
799
800
 end:
801

364
  if (ret && x != nullptr) {
802
364
    *cert = X509_dup(x);
803
364
    if (*cert == nullptr)
804
      ret = 0;
805
  }
806
364
  return ret;
807
}
808
809
810
// Read a file that contains our certificate in "PEM" format,
811
// possibly followed by a sequence of CA certificates that should be
812
// sent to the peer in the Certificate message.
813
//
814
// Taken from OpenSSL - edited for style.
815
355
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
816
                                  BIO* in,
817
                                  X509** cert,
818
                                  X509** issuer) {
819
355
  X509* x = nullptr;
820
821
  // Just to ensure that `ERR_peek_last_error` below will return only errors
822
  // that we are interested in
823
355
  ERR_clear_error();
824
825
355
  x = PEM_read_bio_X509_AUX(in, nullptr, NoPasswordCallback, nullptr);
826
827
355
  if (x == nullptr) {
828
    return 0;
829
  }
830
831
355
  X509* extra = nullptr;
832
355
  int ret = 0;
833
355
  unsigned long err = 0;  // NOLINT(runtime/int)
834
835
  // Read extra certs
836
355
  STACK_OF(X509)* extra_certs = sk_X509_new_null();
837
355
  if (extra_certs == nullptr) {
838
    goto done;
839
  }
840
841
714
  while ((extra = PEM_read_bio_X509(in,
842
                                    nullptr,
843
                                    NoPasswordCallback,
844
                                    nullptr))) {
845
4
    if (sk_X509_push(extra_certs, extra))
846
4
      continue;
847
848
    // Failure, free all certs
849
    goto done;
850
  }
851
355
  extra = nullptr;
852
853
  // When the while loop ends, it's usually just EOF.
854
355
  err = ERR_peek_last_error();
855

710
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
856
355
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
857
355
    ERR_clear_error();
858
  } else  {
859
    // some real error
860
    goto done;
861
  }
862
863
355
  ret = SSL_CTX_use_certificate_chain(ctx, x, extra_certs, cert, issuer);
864
355
  if (!ret)
865
    goto done;
866
867
 done:
868
355
  if (extra_certs != nullptr)
869
355
    sk_X509_pop_free(extra_certs, X509_free);
870
355
  if (extra != nullptr)
871
    X509_free(extra);
872
355
  if (x != nullptr)
873
355
    X509_free(x);
874
875
355
  return ret;
876
}
877
878
879
355
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
880
355
  Environment* env = Environment::GetCurrent(args);
881
882
  SecureContext* sc;
883
355
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
884
885
355
  if (args.Length() != 1) {
886
    return env->ThrowTypeError("Certificate argument is mandatory");
887
  }
888
889
355
  BIO* bio = LoadBIO(env, args[0]);
890
355
  if (!bio)
891
    return;
892
893
  // Free previous certs
894
355
  if (sc->issuer_ != nullptr) {
895
    X509_free(sc->issuer_);
896
    sc->issuer_ = nullptr;
897
  }
898
355
  if (sc->cert_ != nullptr) {
899
15
    X509_free(sc->cert_);
900
15
    sc->cert_ = nullptr;
901
  }
902
903
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_,
904
                                         bio,
905
                                         &sc->cert_,
906
355
                                         &sc->issuer_);
907
908
355
  BIO_free_all(bio);
909
910
355
  if (!rv) {
911
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
912
    if (!err) {
913
      return env->ThrowError("SSL_CTX_use_certificate_chain");
914
    }
915
    return ThrowCryptoError(env, err);
916
  }
917
}
918
919
920
196
static X509_STORE* NewRootCertStore() {
921

196
  static std::vector<X509*> root_certs_vector;
922
196
  if (root_certs_vector.empty()) {
923
29172
    for (size_t i = 0; i < arraysize(root_certs); i++) {
924
28985
      BIO* bp = NodeBIO::NewFixed(root_certs[i], strlen(root_certs[i]));
925
28985
      X509 *x509 = PEM_read_bio_X509(bp, nullptr, NoPasswordCallback, nullptr);
926
28985
      BIO_free(bp);
927
928
      // Parse errors from the built-in roots are fatal.
929
28985
      CHECK_NE(x509, nullptr);
930
931
28985
      root_certs_vector.push_back(x509);
932
    }
933
  }
934
935
196
  X509_STORE* store = X509_STORE_new();
936
196
  if (*system_cert_path != '\0') {
937
    X509_STORE_load_locations(store, system_cert_path, nullptr);
938
  }
939
196
  if (ssl_openssl_cert_store) {
940
    X509_STORE_set_default_paths(store);
941
  } else {
942
30576
    for (X509 *cert : root_certs_vector) {
943
30380
      X509_up_ref(cert);
944
30380
      X509_STORE_add_cert(store, cert);
945
    }
946
  }
947
948
196
  return store;
949
}
950
951
952
127
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
953
127
  Environment* env = Environment::GetCurrent(args);
954
955
  SecureContext* sc;
956
127
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
957
  ClearErrorOnReturn clear_error_on_return;
958
959
127
  if (args.Length() != 1) {
960
    return env->ThrowTypeError("CA certificate argument is mandatory");
961
  }
962
963
127
  BIO* bio = LoadBIO(env, args[0]);
964
127
  if (!bio) {
965
    return;
966
  }
967
968
127
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
969
  while (X509* x509 =
970
257
             PEM_read_bio_X509(bio, nullptr, NoPasswordCallback, nullptr)) {
971
130
    if (cert_store == root_cert_store) {
972
1
      cert_store = NewRootCertStore();
973
1
      SSL_CTX_set_cert_store(sc->ctx_, cert_store);
974
    }
975
130
    X509_STORE_add_cert(cert_store, x509);
976
130
    SSL_CTX_add_client_CA(sc->ctx_, x509);
977
130
    X509_free(x509);
978
  }
979
980
127
  BIO_free_all(bio);
981
}
982
983
984
7
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
985
7
  Environment* env = Environment::GetCurrent(args);
986
987
  SecureContext* sc;
988
8
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
989
990
7
  if (args.Length() != 1) {
991
    return env->ThrowTypeError("CRL argument is mandatory");
992
  }
993
994
  ClearErrorOnReturn clear_error_on_return;
995
996
7
  BIO *bio = LoadBIO(env, args[0]);
997
7
  if (!bio)
998
    return;
999
1000
  X509_CRL* crl =
1001
7
      PEM_read_bio_X509_CRL(bio, nullptr, NoPasswordCallback, nullptr);
1002
1003
7
  if (crl == nullptr) {
1004
1
    BIO_free_all(bio);
1005
1
    return env->ThrowError("Failed to parse CRL");
1006
  }
1007
1008
6
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
1009
6
  if (cert_store == root_cert_store) {
1010
5
    cert_store = NewRootCertStore();
1011
5
    SSL_CTX_set_cert_store(sc->ctx_, cert_store);
1012
  }
1013
1014
6
  X509_STORE_add_crl(cert_store, crl);
1015
  X509_STORE_set_flags(cert_store,
1016
6
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1017
1018
6
  BIO_free_all(bio);
1019
6
  X509_CRL_free(crl);
1020
}
1021
1022
1023
2
void UseExtraCaCerts(const std::string& file) {
1024
2
  extra_root_certs_file = file;
1025
2
}
1026
1027
1028
2
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1029
    X509_STORE* store,
1030
    const char* file) {
1031
2
  ERR_clear_error();
1032
2
  MarkPopErrorOnReturn mark_pop_error_on_return;
1033
1034
2
  BIO* bio = BIO_new_file(file, "r");
1035
2
  if (!bio) {
1036
1
    return ERR_get_error();
1037
  }
1038
1039
  while (X509* x509 =
1040
2
      PEM_read_bio_X509(bio, nullptr, NoPasswordCallback, nullptr)) {
1041
1
    X509_STORE_add_cert(store, x509);
1042
1
    X509_free(x509);
1043
  }
1044
1
  BIO_free_all(bio);
1045
1046
1
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1047
  // Ignore error if its EOF/no start line found.
1048

2
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1049
1
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1050
1
    return 0;
1051
  }
1052
1053
  return err;
1054
}
1055
1056
686
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
1057
  SecureContext* sc;
1058
1372
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1059
  ClearErrorOnReturn clear_error_on_return;
1060
1061
686
  if (!root_cert_store) {
1062
187
    root_cert_store = NewRootCertStore();
1063
1064
187
    if (!extra_root_certs_file.empty()) {
1065
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1066
                                           root_cert_store,
1067
2
                                           extra_root_certs_file.c_str());
1068
2
      if (err) {
1069
        // We do not call back into JS after this line anyway, so ignoring
1070
        // the return value of ProcessEmitWarning does not affect how a
1071
        // possible exception would be propagated.
1072
        ProcessEmitWarning(sc->env(),
1073
                           "Ignoring extra certs from `%s`, "
1074
                           "load failed: %s\n",
1075
                           extra_root_certs_file.c_str(),
1076
1
                           ERR_error_string(err, nullptr));
1077
      }
1078
    }
1079
  }
1080
1081
  // Increment reference count so global store is not deleted along with CTX.
1082
686
  X509_STORE_up_ref(root_cert_store);
1083
686
  SSL_CTX_set_cert_store(sc->ctx_, root_cert_store);
1084
}
1085
1086
1087
739
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
1088
  SecureContext* sc;
1089
741
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1090
739
  Environment* env = sc->env();
1091
  ClearErrorOnReturn clear_error_on_return;
1092
1093
739
  if (args.Length() != 1) {
1094
    return env->ThrowTypeError("Ciphers argument is mandatory");
1095
  }
1096
1097
2217
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Ciphers");
1098
1099
1474
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1100
1474
  SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
1101
}
1102
1103
1104
735
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
1105
  SecureContext* sc;
1106
1464
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1107
735
  Environment* env = sc->env();
1108
1109
735
  if (args.Length() != 1)
1110
    return env->ThrowTypeError("ECDH curve name argument is mandatory");
1111
1112
2205
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "ECDH curve name");
1113
1114
734
  node::Utf8Value curve(env->isolate(), args[0]);
1115
1116
#if OPENSSL_VERSION_NUMBER < 0x10100000L
1117
734
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_ECDH_USE);
1118
734
  SSL_CTX_set_ecdh_auto(sc->ctx_, 1);
1119
#endif
1120
1121
734
  if (strcmp(*curve, "auto") == 0)
1122
725
    return;
1123
1124
9
  if (!SSL_CTX_set1_curves_list(sc->ctx_, *curve))
1125
3
    return env->ThrowError("Failed to set ECDH curve");
1126
}
1127
1128
1129
9
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
1130
  SecureContext* sc;
1131
12
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
1132
9
  Environment* env = sc->env();
1133
  ClearErrorOnReturn clear_error_on_return;
1134
1135
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
1136
  // to be specified explicitly
1137
9
  if (args.Length() != 1)
1138
    return env->ThrowTypeError("DH argument is mandatory");
1139
1140
  // Invalid dhparam is silently discarded and DHE is no longer used.
1141
9
  BIO* bio = LoadBIO(env, args[0]);
1142
9
  if (!bio)
1143
    return;
1144
1145
9
  DH* dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
1146
9
  BIO_free_all(bio);
1147
1148
9
  if (dh == nullptr)
1149
1
    return;
1150
1151
  const BIGNUM* p;
1152
8
  DH_get0_pqg(dh, &p, nullptr, nullptr);
1153
8
  const int size = BN_num_bits(p);
1154
8
  if (size < 1024) {
1155
2
    return env->ThrowError("DH parameter is less than 1024 bits");
1156
6
  } else if (size < 2048) {
1157
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1158
9
        env->isolate(), "DH parameter is less than 2048 bits"));
1159
  }
1160
1161
6
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE);
1162
6
  int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh);
1163
6
  DH_free(dh);
1164
1165
6
  if (!r)
1166
    return env->ThrowTypeError("Error setting temp DH parameter");
1167
}
1168
1169
1170
355
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1171
  SecureContext* sc;
1172
355
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1173
1174


1420
  if (args.Length() != 1 || !args[0]->IntegerValue()) {
1175
    return sc->env()->ThrowTypeError("Options must be an integer value");
1176
  }
1177
1178
1065
  SSL_CTX_set_options(
1179
      sc->ctx_,
1180
355
      static_cast<long>(args[0]->IntegerValue()));  // NOLINT(runtime/int)
1181
}
1182
1183
1184
284
void SecureContext::SetSessionIdContext(
1185
    const FunctionCallbackInfo<Value>& args) {
1186
  SecureContext* sc;
1187
568
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1188
284
  Environment* env = sc->env();
1189
1190
284
  if (args.Length() != 1) {
1191
    return env->ThrowTypeError("Session ID context argument is mandatory");
1192
  }
1193
1194
852
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Session ID context");
1195
1196
284
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1197
  const unsigned char* sid_ctx =
1198
284
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1199
284
  unsigned int sid_ctx_len = sessionIdContext.length();
1200
1201
284
  int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
1202
284
  if (r == 1)
1203
284
    return;
1204
1205
  BIO* bio;
1206
  BUF_MEM* mem;
1207
  Local<String> message;
1208
1209
  bio = BIO_new(BIO_s_mem());
1210
  if (bio == nullptr) {
1211
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1212
                                    "SSL_CTX_set_session_id_context error");
1213
  } else {
1214
    ERR_print_errors(bio);
1215
    BIO_get_mem_ptr(bio, &mem);
1216
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1217
    BIO_free_all(bio);
1218
  }
1219
1220
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1221
}
1222
1223
1224
1
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1225
  SecureContext* sc;
1226
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1227
1228


4
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1229
    return sc->env()->ThrowTypeError(
1230
1
        "Session timeout must be a 32-bit integer");
1231
  }
1232
1233
  int32_t sessionTimeout = args[0]->Int32Value();
1234
  SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
1235
}
1236
1237
1238
338
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1239
  SecureContext* sc;
1240
676
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1241
338
  sc->FreeCTXMem();
1242
}
1243
1244
1245
// Takes .pfx or .p12 and password in string or buffer format
1246
15
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1247
15
  Environment* env = Environment::GetCurrent(args);
1248
1249
15
  BIO* in = nullptr;
1250
15
  PKCS12* p12 = nullptr;
1251
15
  EVP_PKEY* pkey = nullptr;
1252
15
  X509* cert = nullptr;
1253
15
  STACK_OF(X509)* extra_certs = nullptr;
1254
15
  char* pass = nullptr;
1255
15
  bool ret = false;
1256
1257
  SecureContext* sc;
1258
21
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1259
  ClearErrorOnReturn clear_error_on_return;
1260
1261
15
  if (args.Length() < 1) {
1262
    return env->ThrowTypeError("PFX certificate argument is mandatory");
1263
  }
1264
1265
15
  in = LoadBIO(env, args[0]);
1266
15
  if (in == nullptr) {
1267
    return env->ThrowError("Unable to load BIO");
1268
  }
1269
1270
15
  if (args.Length() >= 2) {
1271
12
    THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Pass phrase");
1272
12
    size_t passlen = Buffer::Length(args[1]);
1273
12
    pass = new char[passlen + 1];
1274
12
    memcpy(pass, Buffer::Data(args[1]), passlen);
1275
12
    pass[passlen] = '\0';
1276
  }
1277
1278
  // Free previous certs
1279
15
  if (sc->issuer_ != nullptr) {
1280
1
    X509_free(sc->issuer_);
1281
1
    sc->issuer_ = nullptr;
1282
  }
1283
15
  if (sc->cert_ != nullptr) {
1284
1
    X509_free(sc->cert_);
1285
1
    sc->cert_ = nullptr;
1286
  }
1287
1288
15
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
1289
1290

43
  if (d2i_PKCS12_bio(in, &p12) &&
1291
22
      PKCS12_parse(p12, pass, &pkey, &cert, &extra_certs) &&
1292
      SSL_CTX_use_certificate_chain(sc->ctx_,
1293
                                    cert,
1294
                                    extra_certs,
1295
                                    &sc->cert_,
1296

33
                                    &sc->issuer_) &&
1297
9
      SSL_CTX_use_PrivateKey(sc->ctx_, pkey)) {
1298
    // Add CA certs too
1299
13
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
1300
4
      X509* ca = sk_X509_value(extra_certs, i);
1301
1302
4
      if (cert_store == root_cert_store) {
1303
3
        cert_store = NewRootCertStore();
1304
3
        SSL_CTX_set_cert_store(sc->ctx_, cert_store);
1305
      }
1306
4
      X509_STORE_add_cert(cert_store, ca);
1307
4
      SSL_CTX_add_client_CA(sc->ctx_, ca);
1308
    }
1309
9
    ret = true;
1310
  }
1311
1312
15
  if (pkey != nullptr)
1313
9
    EVP_PKEY_free(pkey);
1314
15
  if (cert != nullptr)
1315
9
    X509_free(cert);
1316
15
  if (extra_certs != nullptr)
1317
4
    sk_X509_pop_free(extra_certs, X509_free);
1318
1319
15
  PKCS12_free(p12);
1320
15
  BIO_free_all(in);
1321
15
  delete[] pass;
1322
1323
15
  if (!ret) {
1324
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1325
6
    const char* str = ERR_reason_error_string(err);
1326
6
    return env->ThrowError(str);
1327
9
  }
1328
}
1329
1330
1331
#ifndef OPENSSL_NO_ENGINE
1332
void SecureContext::SetClientCertEngine(
1333
    const FunctionCallbackInfo<Value>& args) {
1334
  Environment* env = Environment::GetCurrent(args);
1335
  CHECK_EQ(args.Length(), 1);
1336
  CHECK(args[0]->IsString());
1337
1338
  SecureContext* sc;
1339
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1340
1341
  MarkPopErrorOnReturn mark_pop_error_on_return;
1342
1343
  // SSL_CTX_set_client_cert_engine does not itself support multiple
1344
  // calls by cleaning up before overwriting the client_cert_engine
1345
  // internal context variable.
1346
  // Instead of trying to fix up this problem we in turn also do not
1347
  // support multiple calls to SetClientCertEngine.
1348
  if (sc->client_cert_engine_provided_) {
1349
    return env->ThrowError(
1350
        "Multiple calls to SetClientCertEngine are not allowed");
1351
  }
1352
1353
  const node::Utf8Value engine_id(env->isolate(), args[0]);
1354
  char errmsg[1024];
1355
  ENGINE* engine = LoadEngineById(*engine_id, &errmsg);
1356
1357
  if (engine == nullptr) {
1358
    return env->ThrowError(errmsg);
1359
  }
1360
1361
  int r = SSL_CTX_set_client_cert_engine(sc->ctx_, engine);
1362
  // Free reference (SSL_CTX_set_client_cert_engine took it via ENGINE_init).
1363
  ENGINE_free(engine);
1364
  if (r == 0) {
1365
    return ThrowCryptoError(env, ERR_get_error());
1366
  }
1367
  sc->client_cert_engine_provided_ = true;
1368
}
1369
#endif  // !OPENSSL_NO_ENGINE
1370
1371
1372
7
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1373
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1374
1375
  SecureContext* wrap;
1376
7
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1377
1378
14
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1379
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
1380
  memcpy(Buffer::Data(buff), wrap->ticket_key_name_, 16);
1381
  memcpy(Buffer::Data(buff) + 16, wrap->ticket_key_hmac_, 16);
1382
  memcpy(Buffer::Data(buff) + 32, wrap->ticket_key_aes_, 16);
1383
#else
1384
7
  if (SSL_CTX_get_tlsext_ticket_keys(wrap->ctx_,
1385
                                     Buffer::Data(buff),
1386
                                     Buffer::Length(buff)) != 1) {
1387
    return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
1388
  }
1389
#endif
1390
1391
14
  args.GetReturnValue().Set(buff);
1392
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1393
}
1394
1395
1396
16
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1397
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1398
  SecureContext* wrap;
1399
18
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1400
16
  Environment* env = wrap->env();
1401
1402
16
  if (args.Length() < 1) {
1403
    return env->ThrowTypeError("Ticket keys argument is mandatory");
1404
  }
1405
1406
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Ticket keys");
1407
1408
15
  if (Buffer::Length(args[0]) != 48) {
1409
1
    return env->ThrowTypeError("Ticket keys length must be 48 bytes");
1410
  }
1411
1412
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
1413
  memcpy(wrap->ticket_key_name_, Buffer::Data(args[0]), 16);
1414
  memcpy(wrap->ticket_key_hmac_, Buffer::Data(args[0]) + 16, 16);
1415
  memcpy(wrap->ticket_key_aes_, Buffer::Data(args[0]) + 32, 16);
1416
#else
1417
28
  if (SSL_CTX_set_tlsext_ticket_keys(wrap->ctx_,
1418
                                     Buffer::Data(args[0]),
1419
                                     Buffer::Length(args[0])) != 1) {
1420
    return env->ThrowError("Failed to fetch tls ticket keys");
1421
  }
1422
#endif
1423
1424
28
  args.GetReturnValue().Set(true);
1425
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1426
}
1427
1428
1429
356
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1430
#if OPENSSL_VERSION_NUMBER < 0x10100000L
1431
  // |freelist_max_len| was removed in OpenSSL 1.1.0. In that version OpenSSL
1432
  // mallocs and frees buffers directly, without the use of a freelist.
1433
  SecureContext* wrap;
1434
712
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1435
1436
1068
  wrap->ctx_->freelist_max_len = args[0]->Int32Value();
1437
#endif
1438
}
1439
1440
1441
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1442
// the regression test in test/parallel/test-https-resume-after-renew.js.
1443
1
void SecureContext::EnableTicketKeyCallback(
1444
    const FunctionCallbackInfo<Value>& args) {
1445
  SecureContext* wrap;
1446
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1447
1448
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_, TicketKeyCallback);
1449
}
1450
1451
1452
3
int SecureContext::TicketKeyCallback(SSL* ssl,
1453
                                     unsigned char* name,
1454
                                     unsigned char* iv,
1455
                                     EVP_CIPHER_CTX* ectx,
1456
                                     HMAC_CTX* hctx,
1457
                                     int enc) {
1458
  static const int kTicketPartSize = 16;
1459
1460
  SecureContext* sc = static_cast<SecureContext*>(
1461
3
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1462
1463
3
  Environment* env = sc->env();
1464
3
  HandleScope handle_scope(env->isolate());
1465
3
  Context::Scope context_scope(env->context());
1466
1467
  Local<Value> argv[] = {
1468
    Buffer::Copy(env,
1469
                 reinterpret_cast<char*>(name),
1470
                 kTicketPartSize).ToLocalChecked(),
1471
    Buffer::Copy(env,
1472
                 reinterpret_cast<char*>(iv),
1473
                 kTicketPartSize).ToLocalChecked(),
1474
    Boolean::New(env->isolate(), enc != 0)
1475
12
  };
1476
1477
  Local<Value> ret = node::MakeCallback(env->isolate(),
1478
                                        sc->object(),
1479
                                        env->ticketkeycallback_string(),
1480
3
                                        arraysize(argv),
1481
                                        argv,
1482
9
                                        {0, 0}).ToLocalChecked();
1483
3
  Local<Array> arr = ret.As<Array>();
1484
1485
6
  int r = arr->Get(kTicketKeyReturnIndex)->Int32Value();
1486
3
  if (r < 0)
1487
    return r;
1488
1489
3
  Local<Value> hmac = arr->Get(kTicketKeyHMACIndex);
1490
3
  Local<Value> aes = arr->Get(kTicketKeyAESIndex);
1491
3
  if (Buffer::Length(aes) != kTicketPartSize)
1492
    return -1;
1493
1494
3
  if (enc) {
1495
2
    Local<Value> name_val = arr->Get(kTicketKeyNameIndex);
1496
2
    Local<Value> iv_val = arr->Get(kTicketKeyIVIndex);
1497
1498

4
    if (Buffer::Length(name_val) != kTicketPartSize ||
1499
2
        Buffer::Length(iv_val) != kTicketPartSize) {
1500
      return -1;
1501
    }
1502
1503
2
    memcpy(name, Buffer::Data(name_val), kTicketPartSize);
1504
2
    memcpy(iv, Buffer::Data(iv_val), kTicketPartSize);
1505
  }
1506
1507
  HMAC_Init_ex(hctx,
1508
3
               Buffer::Data(hmac),
1509
3
               Buffer::Length(hmac),
1510
               EVP_sha256(),
1511
9
               nullptr);
1512
1513
  const unsigned char* aes_key =
1514
3
      reinterpret_cast<unsigned char*>(Buffer::Data(aes));
1515
3
  if (enc) {
1516
    EVP_EncryptInit_ex(ectx,
1517
                       EVP_aes_128_cbc(),
1518
                       nullptr,
1519
                       aes_key,
1520
2
                       iv);
1521
  } else {
1522
    EVP_DecryptInit_ex(ectx,
1523
                       EVP_aes_128_cbc(),
1524
                       nullptr,
1525
                       aes_key,
1526
1
                       iv);
1527
  }
1528
1529
6
  return r;
1530
}
1531
1532
1533
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
1534
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1535
                                               unsigned char* name,
1536
                                               unsigned char* iv,
1537
                                               EVP_CIPHER_CTX* ectx,
1538
                                               HMAC_CTX* hctx,
1539
                                               int enc) {
1540
  SecureContext* sc = static_cast<SecureContext*>(
1541
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1542
1543
  if (enc) {
1544
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1545
    if (RAND_bytes(iv, 16) <= 0 ||
1546
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1547
                           sc->ticket_key_aes_, iv) <= 0 ||
1548
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1549
                     EVP_sha256(), nullptr) <= 0) {
1550
      return -1;
1551
    }
1552
    return 1;
1553
  }
1554
1555
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1556
    // The ticket key name does not match. Discard the ticket.
1557
    return 0;
1558
  }
1559
1560
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1561
                         iv) <= 0 ||
1562
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1563
                   EVP_sha256(), nullptr) <= 0) {
1564
    return -1;
1565
  }
1566
  return 1;
1567
}
1568
#endif
1569
1570
1571
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1572
  SecureContext* sc;
1573
4
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1574
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_);
1575
4
  info.GetReturnValue().Set(ext);
1576
}
1577
1578
1579
template <bool primary>
1580
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1581
  SecureContext* wrap;
1582

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1583
6
  Environment* env = wrap->env();
1584
  X509* cert;
1585
1586
  if (primary)
1587
3
    cert = wrap->cert_;
1588
  else
1589
3
    cert = wrap->issuer_;
1590

6
  if (cert == nullptr)
1591
    return args.GetReturnValue().SetNull();
1592
1593
6
  int size = i2d_X509(cert, nullptr);
1594
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1595
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1596
6
      Buffer::Data(buff));
1597
6
  i2d_X509(cert, &serialized);
1598
1599
12
  args.GetReturnValue().Set(buff);
1600
}
1601
1602
1603
template <class Base>
1604
765
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1605
765
  HandleScope scope(env->isolate());
1606
1607
765
  env->SetProtoMethod(t, "getPeerCertificate", GetPeerCertificate);
1608
765
  env->SetProtoMethod(t, "getSession", GetSession);
1609
765
  env->SetProtoMethod(t, "setSession", SetSession);
1610
765
  env->SetProtoMethod(t, "loadSession", LoadSession);
1611
765
  env->SetProtoMethod(t, "isSessionReused", IsSessionReused);
1612
765
  env->SetProtoMethod(t, "isInitFinished", IsInitFinished);
1613
765
  env->SetProtoMethod(t, "verifyError", VerifyError);
1614
765
  env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
1615
765
  env->SetProtoMethod(t, "endParser", EndParser);
1616
765
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1617
765
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1618
765
  env->SetProtoMethod(t, "shutdownSSL", Shutdown);
1619
765
  env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket);
1620
765
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1621
765
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1622
765
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1623
765
  env->SetProtoMethod(t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
1624
765
  env->SetProtoMethod(t, "getProtocol", GetProtocol);
1625
1626
#ifdef SSL_set_max_send_fragment
1627
765
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1628
#endif  // SSL_set_max_send_fragment
1629
1630
#ifndef OPENSSL_NO_NEXTPROTONEG
1631
765
  env->SetProtoMethod(t, "getNegotiatedProtocol", GetNegotiatedProto);
1632
#endif  // OPENSSL_NO_NEXTPROTONEG
1633
1634
#ifndef OPENSSL_NO_NEXTPROTONEG
1635
765
  env->SetProtoMethod(t, "setNPNProtocols", SetNPNProtocols);
1636
#endif
1637
1638
765
  env->SetProtoMethod(t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
1639
765
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1640
1641
  Local<FunctionTemplate> ssl_getter_templ =
1642
      FunctionTemplate::New(env->isolate(),
1643
                            SSLGetter,
1644
                            env->as_external(),
1645
1530
                            Signature::New(env->isolate(), t));
1646
1647
1530
  t->PrototypeTemplate()->SetAccessorProperty(
1648
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
1649
      ssl_getter_templ,
1650
      Local<FunctionTemplate>(),
1651
3060
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
1652
765
}
1653
1654
1655
template <class Base>
1656
10813
void SSLWrap<Base>::InitNPN(SecureContext* sc) {
1657
#ifndef OPENSSL_NO_NEXTPROTONEG
1658
  // Server should advertise NPN protocols
1659
10813
  SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
1660
                                        AdvertiseNextProtoCallback,
1661
10813
                                        nullptr);
1662
  // Client should select protocol from list of advertised
1663
  // If server supports NPN
1664
10813
  SSL_CTX_set_next_proto_select_cb(sc->ctx_, SelectNextProtoCallback, nullptr);
1665
#endif  // OPENSSL_NO_NEXTPROTONEG
1666
1667
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1668
  // OCSP stapling
1669
10813
  SSL_CTX_set_tlsext_status_cb(sc->ctx_, TLSExtStatusCallback);
1670
10813
  SSL_CTX_set_tlsext_status_arg(sc->ctx_, nullptr);
1671
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1672
10813
}
1673
1674
1675
#if OPENSSL_VERSION_NUMBER < 0x10100000L
1676
template <class Base>
1677
11
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1678
                                               unsigned char* key,
1679
                                               int len,
1680
                                               int* copy) {
1681
#else
1682
template <class Base>
1683
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1684
                                               const unsigned char* key,
1685
                                               int len,
1686
                                               int* copy) {
1687
#endif
1688
11
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1689
1690
11
  *copy = 0;
1691
11
  SSL_SESSION* sess = w->next_sess_;
1692
11
  w->next_sess_ = nullptr;
1693
1694
11
  return sess;
1695
}
1696
1697
1698
template <class Base>
1699
11
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1700
11
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1701
11
  Environment* env = w->ssl_env();
1702
11
  HandleScope handle_scope(env->isolate());
1703
11
  Context::Scope context_scope(env->context());
1704
1705

11
  if (!w->session_callbacks_)
1706
3
    return 0;
1707
1708
  // Check if session is small enough to be stored
1709
8
  int size = i2d_SSL_SESSION(sess, nullptr);
1710

8
  if (size > SecureContext::kMaxSessionSize)
1711
    return 0;
1712
1713
  // Serialize session
1714
16
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1715
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1716
8
      Buffer::Data(buff));
1717
8
  memset(serialized, 0, size);
1718
8
  i2d_SSL_SESSION(sess, &serialized);
1719
1720
  unsigned int session_id_length;
1721
  const unsigned char* session_id = SSL_SESSION_get_id(sess,
1722
8
                                                       &session_id_length);
1723
  Local<Object> session = Buffer::Copy(
1724
      env,
1725
      reinterpret_cast<const char*>(session_id),
1726
16
      session_id_length).ToLocalChecked();
1727
24
  Local<Value> argv[] = { session, buff };
1728
8
  w->new_session_wait_ = true;
1729
8
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1730
1731
19
  return 0;
1732
}
1733
1734
1735
template <class Base>
1736
23
void SSLWrap<Base>::OnClientHello(void* arg,
1737
                                  const ClientHelloParser::ClientHello& hello) {
1738
23
  Base* w = static_cast<Base*>(arg);
1739
23
  Environment* env = w->ssl_env();
1740
23
  HandleScope handle_scope(env->isolate());
1741
23
  Context::Scope context_scope(env->context());
1742
1743
23
  Local<Object> hello_obj = Object::New(env->isolate());
1744
  Local<Object> buff = Buffer::Copy(
1745
      env,
1746
23
      reinterpret_cast<const char*>(hello.session_id()),
1747
69
      hello.session_size()).ToLocalChecked();
1748
46
  hello_obj->Set(env->session_id_string(), buff);
1749

23
  if (hello.servername() == nullptr) {
1750
9
    hello_obj->Set(env->servername_string(), String::Empty(env->isolate()));
1751
  } else {
1752
    Local<String> servername = OneByteString(env->isolate(),
1753
                                             hello.servername(),
1754
20
                                             hello.servername_size());
1755
40
    hello_obj->Set(env->servername_string(), servername);
1756
  }
1757
23
  hello_obj->Set(env->tls_ticket_string(),
1758
92
                 Boolean::New(env->isolate(), hello.has_ticket()));
1759
23
  hello_obj->Set(env->ocsp_request_string(),
1760
92
                 Boolean::New(env->isolate(), hello.ocsp_request()));
1761
1762
46
  Local<Value> argv[] = { hello_obj };
1763
46
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1764
23
}
1765
1766
1767
36
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1768
36
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1769
1770
36
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1771
32
    return false;
1772
1773
4
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
1774
4
  if (names == nullptr)
1775
    return false;
1776
1777
16
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1778
12
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1779
1780
12
    if (i != 0)
1781
8
      BIO_write(out, ", ", 2);
1782
1783
12
    if (gen->type == GEN_DNS) {
1784
9
      ASN1_IA5STRING* name = gen->d.dNSName;
1785
1786
9
      BIO_write(out, "DNS:", 4);
1787
9
      BIO_write(out, name->data, name->length);
1788
    } else {
1789
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1790
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
1791
3
      if (nval == nullptr)
1792
        return false;
1793
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1794
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1795
    }
1796
  }
1797
4
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1798
1799
4
  return true;
1800
}
1801
1802
1803
72
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1804
72
  EscapableHandleScope scope(env->isolate());
1805
1806
72
  Local<Object> info = Object::New(env->isolate());
1807
1808
72
  BIO* bio = BIO_new(BIO_s_mem());
1809
  BUF_MEM* mem;
1810
72
  if (X509_NAME_print_ex(bio,
1811
                         X509_get_subject_name(cert),
1812
                         0,
1813
72
                         X509_NAME_FLAGS) > 0) {
1814
72
    BIO_get_mem_ptr(bio, &mem);
1815
    info->Set(env->subject_string(),
1816
              String::NewFromUtf8(env->isolate(), mem->data,
1817
216
                                  String::kNormalString, mem->length));
1818
  }
1819
72
  USE(BIO_reset(bio));
1820
1821
72
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1822
72
  if (X509_NAME_print_ex(bio, issuer_name, 0, X509_NAME_FLAGS) > 0) {
1823
72
    BIO_get_mem_ptr(bio, &mem);
1824
    info->Set(env->issuer_string(),
1825
              String::NewFromUtf8(env->isolate(), mem->data,
1826
216
                                  String::kNormalString, mem->length));
1827
  }
1828
72
  USE(BIO_reset(bio));
1829
1830
72
  int nids[] = { NID_subject_alt_name, NID_info_access };
1831
  Local<String> keys[] = { env->subjectaltname_string(),
1832
72
                           env->infoaccess_string() };
1833
72
  CHECK_EQ(arraysize(nids), arraysize(keys));
1834
216
  for (size_t i = 0; i < arraysize(nids); i++) {
1835
144
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1836
144
    if (index < 0)
1837
108
      continue;
1838
1839
    X509_EXTENSION* ext;
1840
    int rv;
1841
1842
36
    ext = X509_get_ext(cert, index);
1843
36
    CHECK_NE(ext, nullptr);
1844
1845
36
    if (!SafeX509ExtPrint(bio, ext)) {
1846
32
      rv = X509V3_EXT_print(bio, ext, 0, 0);
1847
32
      CHECK_EQ(rv, 1);
1848
    }
1849
1850
36
    BIO_get_mem_ptr(bio, &mem);
1851
    info->Set(keys[i],
1852
              String::NewFromUtf8(env->isolate(), mem->data,
1853
72
                                  String::kNormalString, mem->length));
1854
1855
36
    USE(BIO_reset(bio));
1856
  }
1857
1858
72
  EVP_PKEY* pkey = X509_get_pubkey(cert);
1859
72
  RSA* rsa = nullptr;
1860
72
  if (pkey != nullptr)
1861
72
    rsa = EVP_PKEY_get1_RSA(pkey);
1862
1863
72
  if (rsa != nullptr) {
1864
    const BIGNUM* n;
1865
    const BIGNUM* e;
1866
71
    RSA_get0_key(rsa, &n, &e, nullptr);
1867
71
    BN_print(bio, n);
1868
71
    BIO_get_mem_ptr(bio, &mem);
1869
    info->Set(env->modulus_string(),
1870
              String::NewFromUtf8(env->isolate(), mem->data,
1871
213
                                  String::kNormalString, mem->length));
1872
71
    USE(BIO_reset(bio));
1873
1874
71
    uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
1875
71
    uint32_t lo = static_cast<uint32_t>(exponent_word);
1876
71
    uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
1877
71
    if (hi == 0) {
1878
71
      BIO_printf(bio, "0x%x", lo);
1879
    } else {
1880
      BIO_printf(bio, "0x%x%08x", hi, lo);
1881
    }
1882
71
    BIO_get_mem_ptr(bio, &mem);
1883
    info->Set(env->exponent_string(),
1884
              String::NewFromUtf8(env->isolate(), mem->data,
1885
213
                                  String::kNormalString, mem->length));
1886
71
    USE(BIO_reset(bio));
1887
  }
1888
1889
72
  if (pkey != nullptr) {
1890
72
    EVP_PKEY_free(pkey);
1891
72
    pkey = nullptr;
1892
  }
1893
72
  if (rsa != nullptr) {
1894
71
    RSA_free(rsa);
1895
71
    rsa = nullptr;
1896
  }
1897
1898
72
  ASN1_TIME_print(bio, X509_get_notBefore(cert));
1899
72
  BIO_get_mem_ptr(bio, &mem);
1900
  info->Set(env->valid_from_string(),
1901
            String::NewFromUtf8(env->isolate(), mem->data,
1902
216
                                String::kNormalString, mem->length));
1903
72
  USE(BIO_reset(bio));
1904
1905
72
  ASN1_TIME_print(bio, X509_get_notAfter(cert));
1906
72
  BIO_get_mem_ptr(bio, &mem);
1907
  info->Set(env->valid_to_string(),
1908
            String::NewFromUtf8(env->isolate(), mem->data,
1909
216
                                String::kNormalString, mem->length));
1910
72
  BIO_free_all(bio);
1911
1912
  unsigned int md_size, i;
1913
  unsigned char md[EVP_MAX_MD_SIZE];
1914
72
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1915
72
    const char hex[] = "0123456789ABCDEF";
1916
    char fingerprint[EVP_MAX_MD_SIZE * 3];
1917
1918
1512
    for (i = 0; i < md_size; i++) {
1919
1440
      fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1920
1440
      fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1921
1440
      fingerprint[(3*i)+2] = ':';
1922
    }
1923
1924
72
    if (md_size > 0) {
1925
72
      fingerprint[(3*(md_size-1))+2] = '\0';
1926
    } else {
1927
      fingerprint[0] = '\0';
1928
    }
1929
1930
    info->Set(env->fingerprint_string(),
1931
216
              OneByteString(env->isolate(), fingerprint));
1932
  }
1933
1934
  STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
1935
72
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr));
1936
72
  if (eku != nullptr) {
1937
3
    Local<Array> ext_key_usage = Array::New(env->isolate());
1938
    char buf[256];
1939
1940
3
    int j = 0;
1941
8
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1942
5
      if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku, i), 1) >= 0)
1943
15
        ext_key_usage->Set(j++, OneByteString(env->isolate(), buf));
1944
    }
1945
1946
3
    sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1947
6
    info->Set(env->ext_key_usage_string(), ext_key_usage);
1948
  }
1949
1950
72
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1951
72
    if (BIGNUM* bn = ASN1_INTEGER_to_BN(serial_number, nullptr)) {
1952
72
      if (char* buf = BN_bn2hex(bn)) {
1953
        info->Set(env->serial_number_string(),
1954
216
                  OneByteString(env->isolate(), buf));
1955
72
        OPENSSL_free(buf);
1956
      }
1957
72
      BN_free(bn);
1958
    }
1959
  }
1960
1961
  // Raw DER certificate
1962
72
  int size = i2d_X509(cert, nullptr);
1963
144
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1964
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1965
72
      Buffer::Data(buff));
1966
72
  i2d_X509(cert, &serialized);
1967
144
  info->Set(env->raw_string(), buff);
1968
1969
72
  return scope.Escape(info);
1970
}
1971
1972
1973
// TODO(indutny): Split it into multiple smaller functions
1974
template <class Base>
1975
70
void SSLWrap<Base>::GetPeerCertificate(
1976
    const FunctionCallbackInfo<Value>& args) {
1977
  Base* w;
1978

140
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1979
70
  Environment* env = w->ssl_env();
1980
1981
  ClearErrorOnReturn clear_error_on_return;
1982
1983
  Local<Object> result;
1984
  Local<Object> info;
1985
1986
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1987
  // contains the `peer_certificate`, but on server it doesn't
1988

70
  X509* cert = w->is_server() ? SSL_get_peer_certificate(w->ssl_) : nullptr;
1989
70
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_);
1990
70
  STACK_OF(X509)* peer_certs = nullptr;
1991


70
  if (cert == nullptr && ssl_certs == nullptr)
1992
3
    goto done;
1993
1994



67
  if (cert == nullptr && sk_X509_num(ssl_certs) == 0)
1995
    goto done;
1996
1997
  // Short result requested
1998




268
  if (args.Length() < 1 || !args[0]->IsTrue()) {
1999
64
    result = X509ToObject(env,
2000

64
                          cert == nullptr ? sk_X509_value(ssl_certs, 0) : cert);
2001
64
    goto done;
2002
  }
2003
2004
  // Clone `ssl_certs`, because we are going to destruct it
2005
3
  peer_certs = sk_X509_new(nullptr);
2006

3
  if (cert != nullptr)
2007
    sk_X509_push(peer_certs, cert);
2008

9
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
2009
6
    cert = X509_dup(sk_X509_value(ssl_certs, i));
2010

6
    if (cert == nullptr)
2011
      goto done;
2012

6
    if (!sk_X509_push(peer_certs, cert))
2013
      goto done;
2014
  }
2015
2016
  // First and main certificate
2017
3
  cert = sk_X509_value(peer_certs, 0);
2018
3
  result = X509ToObject(env, cert);
2019
3
  info = result;
2020
2021
  // Put issuer inside the object
2022
3
  cert = sk_X509_delete(peer_certs, 0);
2023

3
  while (sk_X509_num(peer_certs) > 0) {
2024
    int i;
2025

6
    for (i = 0; i < sk_X509_num(peer_certs); i++) {
2026
3
      X509* ca = sk_X509_value(peer_certs, i);
2027

3
      if (X509_check_issued(ca, cert) != X509_V_OK)
2028
        continue;
2029
2030
3
      Local<Object> ca_info = X509ToObject(env, ca);
2031
6
      info->Set(env->issuercert_string(), ca_info);
2032
3
      info = ca_info;
2033
2034
      // NOTE: Intentionally freeing cert that is not used anymore
2035
3
      X509_free(cert);
2036
2037
      // Delete cert and continue aggregating issuers
2038
3
      cert = sk_X509_delete(peer_certs, i);
2039
3
      break;
2040
    }
2041
2042
    // Issuer not found, break out of the loop
2043

3
    if (i == sk_X509_num(peer_certs))
2044
3
      break;
2045
  }
2046
2047
  // Last certificate should be self-signed
2048

8
  while (X509_check_issued(cert, cert) != X509_V_OK) {
2049
    X509* ca;
2050

2
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(w->ssl_), cert, &ca) <= 0)
2051
      break;
2052
2053
2
    Local<Object> ca_info = X509ToObject(env, ca);
2054
4
    info->Set(env->issuercert_string(), ca_info);
2055
2
    info = ca_info;
2056
2057
    // NOTE: Intentionally freeing cert that is not used anymore
2058
2
    X509_free(cert);
2059
2060
    // Delete cert and continue aggregating issuers
2061
2
    cert = ca;
2062
  }
2063
2064
  // Self-issued certificate
2065

3
  if (X509_check_issued(cert, cert) == X509_V_OK)
2066
6
    info->Set(env->issuercert_string(), info);
2067
2068

3
  CHECK_NE(cert, nullptr);
2069
2070
 done:
2071

70
  if (cert != nullptr)
2072
10
    X509_free(cert);
2073

70
  if (peer_certs != nullptr)
2074
3
    sk_X509_pop_free(peer_certs, X509_free);
2075

70
  if (result.IsEmpty())
2076
3
    result = Object::New(env->isolate());
2077
140
  args.GetReturnValue().Set(result);
2078
}
2079
2080
2081
template <class Base>
2082
125
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
2083
125
  Environment* env = Environment::GetCurrent(args);
2084
2085
  Base* w;
2086

125
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2087
2088
125
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
2089

125
  if (sess == nullptr)
2090
    return;
2091
2092
125
  int slen = i2d_SSL_SESSION(sess, nullptr);
2093

125
  CHECK_GT(slen, 0);
2094
2095
125
  char* sbuf = Malloc(slen);
2096
125
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
2097
125
  i2d_SSL_SESSION(sess, &p);
2098
375
  args.GetReturnValue().Set(Buffer::New(env, sbuf, slen).ToLocalChecked());
2099
}
2100
2101
2102
template <class Base>
2103
76
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
2104
76
  Environment* env = Environment::GetCurrent(args);
2105
2106
  Base* w;
2107

76
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2108
2109

76
  if (args.Length() < 1) {
2110
    return env->ThrowError("Session argument is mandatory");
2111
  }
2112
2113

76
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Session");
2114
76
  size_t slen = Buffer::Length(args[0]);
2115
76
  char* sbuf = new char[slen];
2116
76
  memcpy(sbuf, Buffer::Data(args[0]), slen);
2117
2118
76
  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
2119
76
  SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
2120
2121

76
  delete[] sbuf;
2122
2123

76
  if (sess == nullptr)
2124
    return;
2125
2126
76
  int r = SSL_set_session(w->ssl_, sess);
2127
76
  SSL_SESSION_free(sess);
2128
2129

76
  if (!r)
2130
    return env->ThrowError("SSL_set_session error");
2131
}
2132
2133
2134
template <class Base>
2135
13
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
2136
  Base* w;
2137

26
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2138
2139



26
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
2140
10
    ssize_t slen = Buffer::Length(args[0]);
2141
10
    char* sbuf = Buffer::Data(args[0]);
2142
2143
10
    const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
2144
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
2145
2146
    // Setup next session and move hello to the BIO buffer
2147

10
    if (w->next_sess_ != nullptr)
2148
      SSL_SESSION_free(w->next_sess_);
2149
10
    w->next_sess_ = sess;
2150
  }
2151
}
2152
2153
2154
template <class Base>
2155
79
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2156
  Base* w;
2157

158
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2158
79
  bool yes = SSL_session_reused(w->ssl_);
2159
237
  args.GetReturnValue().Set(yes);
2160
}
2161
2162
2163
template <class Base>
2164
22
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2165
  Base* w;
2166

44
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2167
22
  w->hello_parser_.End();
2168
}
2169
2170
2171
template <class Base>
2172
3
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2173
  Base* w;
2174

6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2175
2176
  ClearErrorOnReturn clear_error_on_return;
2177
2178
3
  bool yes = SSL_renegotiate(w->ssl_) == 1;
2179
9
  args.GetReturnValue().Set(yes);
2180
}
2181
2182
2183
template <class Base>
2184
2
void SSLWrap<Base>::Shutdown(const FunctionCallbackInfo<Value>& args) {
2185
  Base* w;
2186

4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2187
2188
2
  int rv = SSL_shutdown(w->ssl_);
2189
4
  args.GetReturnValue().Set(rv);
2190
}
2191
2192
2193
template <class Base>
2194
9
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2195
  Base* w;
2196

9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2197
9
  Environment* env = w->ssl_env();
2198
2199
9
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
2200

9
  if (sess == nullptr)
2201
    return;
2202
2203
  const unsigned char *ticket;
2204
  size_t length;
2205
9
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2206
2207

9
  if (ticket == nullptr)
2208
    return;
2209
2210
  Local<Object> buff = Buffer::Copy(
2211
18
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2212
2213
18
  args.GetReturnValue().Set(buff);
2214
}
2215
2216
2217
template <class Base>
2218
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2219
  Base* w;
2220

16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2221
8
  w->new_session_wait_ = false;
2222
8
  w->NewSessionDoneCb();
2223
}
2224
2225
2226
template <class Base>
2227
2
void SSLWrap<Base>::SetOCSPResponse(
2228
    const v8::FunctionCallbackInfo<v8::Value>& args) {
2229
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2230
  Base* w;
2231

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2232
2
  Environment* env = w->env();
2233
2234

2
  if (args.Length() < 1)
2235
    return env->ThrowTypeError("OCSP response argument is mandatory");
2236
2237

2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "OCSP response");
2238
2239
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
2240
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2241
}
2242
2243
2244
template <class Base>
2245
4
void SSLWrap<Base>::RequestOCSP(
2246
    const v8::FunctionCallbackInfo<v8::Value>& args) {
2247
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2248
  Base* w;
2249

8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2250
2251
4
  SSL_set_tlsext_status_type(w->ssl_, TLSEXT_STATUSTYPE_ocsp);
2252
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2253
}
2254
2255
2256
template <class Base>
2257
352
void SSLWrap<Base>::GetEphemeralKeyInfo(
2258
    const v8::FunctionCallbackInfo<v8::Value>& args) {
2259
  Base* w;
2260

352
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2261
352
  Environment* env = Environment::GetCurrent(args);
2262
2263

352
  CHECK_NE(w->ssl_, nullptr);
2264
2265
  // tmp key is available on only client
2266

352
  if (w->is_server())
2267
10
    return args.GetReturnValue().SetNull();
2268
2269
347
  Local<Object> info = Object::New(env->isolate());
2270
2271
  EVP_PKEY* key;
2272
2273

347
  if (SSL_get_server_tmp_key(w->ssl_, &key)) {
2274

305
    switch (EVP_PKEY_id(key)) {
2275
      case EVP_PKEY_DH:
2276
6
        info->Set(env->type_string(),
2277
24
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH"));
2278
6
        info->Set(env->size_string(),
2279
24
                  Integer::New(env->isolate(), EVP_PKEY_bits(key)));
2280
6
        break;
2281
      case EVP_PKEY_EC:
2282
        {
2283
299
          EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
2284
299
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2285
299
          EC_KEY_free(ec);
2286
299
          info->Set(env->type_string(),
2287
1196
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"));
2288
299
          info->Set(env->name_string(),
2289
1495
                    OneByteString(args.GetIsolate(), OBJ_nid2sn(nid)));
2290
299
          info->Set(env->size_string(),
2291
1196
                    Integer::New(env->isolate(), EVP_PKEY_bits(key)));
2292
        }
2293
    }
2294
305
    EVP_PKEY_free(key);
2295
  }
2296
2297
694
  return args.GetReturnValue().Set(info);
2298
}
2299
2300
2301
#ifdef SSL_set_max_send_fragment
2302
template <class Base>
2303
3
void SSLWrap<Base>::SetMaxSendFragment(
2304
    const v8::FunctionCallbackInfo<v8::Value>& args) {
2305




12
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2306
2307
  Base* w;
2308

6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2309
2310
6
  int rv = SSL_set_max_send_fragment(w->ssl_, args[0]->Int32Value());
2311
6
  args.GetReturnValue().Set(rv);
2312
}
2313
#endif  // SSL_set_max_send_fragment
2314
2315
2316
template <class Base>
2317
23
void SSLWrap<Base>::IsInitFinished(const FunctionCallbackInfo<Value>& args) {
2318
  Base* w;
2319

46
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2320
23
  bool yes = SSL_is_init_finished(w->ssl_);
2321
69
  args.GetReturnValue().Set(yes);
2322
}
2323
2324
2325
template <class Base>
2326
408
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2327
  Base* w;
2328

498
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2329
2330
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2331
  // peer certificate is questionable but it's compatible with what was
2332
  // here before.
2333
  long x509_verify_error =  // NOLINT(runtime/int)
2334
408
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2335

408
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
2336
407
    X509_free(peer_cert);
2337
407
    x509_verify_error = SSL_get_verify_result(w->ssl_);
2338
  }
2339
2340

408
  if (x509_verify_error == X509_V_OK)
2341
180
    return args.GetReturnValue().SetNull();
2342
2343
  // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
2344
  // in the presence of invalid error codes.  Probably academical but something
2345
  // to keep in mind if/when node ever grows multi-isolate capabilities.
2346
318
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2347
318
  const char* code = reason;
2348
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2349














318
  switch (x509_verify_error) {
2350
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2351
5
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2352
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2353
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2354
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2355
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2356
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2357
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2358
35
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2359
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2360
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2361
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2362
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2363
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2364
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2365
    CASE_X509_ERR(OUT_OF_MEM)
2366
138
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2367
6
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2368
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2369
128
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2370
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2371
3
    CASE_X509_ERR(CERT_REVOKED)
2372
    CASE_X509_ERR(INVALID_CA)
2373
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2374
1
    CASE_X509_ERR(INVALID_PURPOSE)
2375
    CASE_X509_ERR(CERT_UNTRUSTED)
2376
    CASE_X509_ERR(CERT_REJECTED)
2377
  }
2378
#undef CASE_X509_ERR
2379
2380
318
  Isolate* isolate = args.GetIsolate();
2381
318
  Local<String> reason_string = OneByteString(isolate, reason);
2382
318
  Local<Value> exception_value = Exception::Error(reason_string);
2383
318
  Local<Object> exception_object = exception_value->ToObject(isolate);
2384
954
  exception_object->Set(w->env()->code_string(), OneByteString(isolate, code));
2385
636
  args.GetReturnValue().Set(exception_object);
2386
}
2387
2388
2389
template <class Base>
2390
12
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
2391
  Base* w;
2392

12
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2393
12
  Environment* env = w->ssl_env();
2394
2395
12
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
2396

12
  if (c == nullptr)
2397
    return;
2398
2399
12
  Local<Object> info = Object::New(env->isolate());
2400
12
  const char* cipher_name = SSL_CIPHER_get_name(c);
2401
36
  info->Set(env->name_string(), OneByteString(args.GetIsolate(), cipher_name));
2402
12
  info->Set(env->version_string(),
2403
48
            OneByteString(args.GetIsolate(), "TLSv1/SSLv3"));
2404
24
  args.GetReturnValue().Set(info);
2405
}
2406
2407
2408
template <class Base>
2409
3
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2410
  Base* w;
2411

6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2412
2413
3
  const char* tls_version = SSL_get_version(w->ssl_);
2414
9
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2415
}
2416
2417
2418
#ifndef OPENSSL_NO_NEXTPROTONEG
2419
template <class Base>
2420
324
int SSLWrap<Base>::AdvertiseNextProtoCallback(SSL* s,
2421
                                              const unsigned char** data,
2422
                                              unsigned int* len,
2423
                                              void* arg) {
2424
324
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2425
324
  Environment* env = w->env();
2426
324
  HandleScope handle_scope(env->isolate());
2427
324
  Context::Scope context_scope(env->context());
2428
2429
  auto npn_buffer =
2430
324
      w->object()->GetPrivate(
2431
          env->context(),
2432
1296
          env->npn_buffer_private_symbol()).ToLocalChecked();
2433
2434

648
  if (npn_buffer->IsUndefined()) {
2435
    // No initialization - no NPN protocols
2436
196
    *data = reinterpret_cast<const unsigned char*>("");
2437
196
    *len = 0;
2438
  } else {
2439

128
    CHECK(Buffer::HasInstance(npn_buffer));
2440
128
    *data = reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2441
128
    *len = Buffer::Length(npn_buffer);
2442
  }
2443
2444
648
  return SSL_TLSEXT_ERR_OK;
2445
}
2446
2447
2448
template <class Base>
2449
323
int SSLWrap<Base>::SelectNextProtoCallback(SSL* s,
2450
                                           unsigned char** out,
2451
                                           unsigned char* outlen,
2452
                                           const unsigned char* in,
2453
                                           unsigned int inlen,
2454
                                           void* arg) {
2455
323
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2456
323
  Environment* env = w->env();
2457
323
  HandleScope handle_scope(env->isolate());
2458
323
  Context::Scope context_scope(env->context());
2459
2460
  auto npn_buffer =
2461
323
      w->object()->GetPrivate(
2462
          env->context(),
2463
1292
          env->npn_buffer_private_symbol()).ToLocalChecked();
2464
2465

646
  if (npn_buffer->IsUndefined()) {
2466
    // We should at least select one protocol
2467
    // If server is using NPN
2468
301
    *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
2469
301
    *outlen = 8;
2470
2471
    // set status: unsupported
2472

1204
    CHECK(
2473
        w->object()->SetPrivate(
2474
            env->context(),
2475
            env->selected_npn_buffer_private_symbol(),
2476
            False(env->isolate())).FromJust());
2477
2478
301
    return SSL_TLSEXT_ERR_OK;
2479
  }
2480
2481

22
  CHECK(Buffer::HasInstance(npn_buffer));
2482
  const unsigned char* npn_protos =
2483
22
      reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2484
22
  size_t len = Buffer::Length(npn_buffer);
2485
2486
22
  int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
2487
  Local<Value> result;
2488


22
  switch (status) {
2489
    case OPENSSL_NPN_UNSUPPORTED:
2490
      result = Null(env->isolate());
2491
      break;
2492
    case OPENSSL_NPN_NEGOTIATED:
2493
16
      result = OneByteString(env->isolate(), *out, *outlen);
2494
8
      break;
2495
    case OPENSSL_NPN_NO_OVERLAP:
2496
28
      result = False(env->isolate());
2497
14
      break;
2498
    default:
2499
      break;
2500
  }
2501
2502

66
  CHECK(
2503
      w->object()->SetPrivate(
2504
          env->context(),
2505
          env->selected_npn_buffer_private_symbol(),
2506
          result).FromJust());
2507
2508
345
  return SSL_TLSEXT_ERR_OK;
2509
}
2510
2511
2512
template <class Base>
2513
741
void SSLWrap<Base>::GetNegotiatedProto(
2514
    const FunctionCallbackInfo<Value>& args) {
2515
  Base* w;
2516

1161
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2517
741
  Environment* env = w->env();
2518
2519

741
  if (w->is_client()) {
2520
    auto selected_npn_buffer =
2521
348
        w->object()->GetPrivate(
2522
            env->context(),
2523
1392
            env->selected_npn_buffer_private_symbol()).ToLocalChecked();
2524
696
    args.GetReturnValue().Set(selected_npn_buffer);
2525
348
    return;
2526
  }
2527
2528
  const unsigned char* npn_proto;
2529
  unsigned int npn_proto_len;
2530
2531
393
  SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
2532
2533

393
  if (!npn_proto)
2534
144
    return args.GetReturnValue().Set(false);
2535
2536
  args.GetReturnValue().Set(
2537
1284
      OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
2538
}
2539
2540
2541
template <class Base>
2542
162
void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
2543
  Base* w;
2544

162
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2545
162
  Environment* env = w->env();
2546
2547

162
  if (args.Length() < 1)
2548
    return env->ThrowTypeError("NPN protocols argument is mandatory");
2549
2550

162
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "NPN protocols");
2551
2552

486
  CHECK(
2553
      w->object()->SetPrivate(
2554
          env->context(),
2555
          env->npn_buffer_private_symbol(),
2556
          args[0]).FromJust());
2557
}
2558
#endif  // OPENSSL_NO_NEXTPROTONEG
2559
2560
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2561
template <class Base>
2562
27
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2563
                                      const unsigned char** out,
2564
                                      unsigned char* outlen,
2565
                                      const unsigned char* in,
2566
                                      unsigned int inlen,
2567
                                      void* arg) {
2568
27
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2569
27
  Environment* env = w->env();
2570
27
  HandleScope handle_scope(env->isolate());
2571
27
  Context::Scope context_scope(env->context());
2572
2573
  Local<Value> alpn_buffer =
2574
27
      w->object()->GetPrivate(
2575
          env->context(),
2576
108
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2577

27
  CHECK(Buffer::HasInstance(alpn_buffer));
2578
  const unsigned char* alpn_protos =
2579
27
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2580
27
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2581
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2582
27
                                     alpn_protos, alpn_protos_len, in, inlen);
2583
  // According to 3.2. Protocol Selection of RFC7301, fatal
2584
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2585
  // support it yet. See
2586
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2587
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2588

54
                                          : SSL_TLSEXT_ERR_NOACK;
2589
}
2590
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2591
2592
2593
template <class Base>
2594
741
void SSLWrap<Base>::GetALPNNegotiatedProto(
2595
    const FunctionCallbackInfo<v8::Value>& args) {
2596
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2597
  Base* w;
2598

1438
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2599
2600
  const unsigned char* alpn_proto;
2601
  unsigned int alpn_proto_len;
2602
2603
741
  SSL_get0_alpn_selected(w->ssl_, &alpn_proto, &alpn_proto_len);
2604
2605

741
  if (!alpn_proto)
2606
1394
    return args.GetReturnValue().Set(false);
2607
2608
  args.GetReturnValue().Set(
2609
176
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2610
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2611
}
2612
2613
2614
template <class Base>
2615
186
void SSLWrap<Base>::SetALPNProtocols(
2616
    const FunctionCallbackInfo<v8::Value>& args) {
2617
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2618
  Base* w;
2619

186
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2620
186
  Environment* env = w->env();
2621



372
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2622
    return env->ThrowTypeError("Must give a Buffer as first argument");
2623
2624

186
  if (w->is_client()) {
2625
    const unsigned char* alpn_protos =
2626
39
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2627
39
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2628
39
    int r = SSL_set_alpn_protos(w->ssl_, alpn_protos, alpn_protos_len);
2629

39
    CHECK_EQ(r, 0);
2630
  } else {
2631

441
    CHECK(
2632
        w->object()->SetPrivate(
2633
          env->context(),
2634
          env->alpn_buffer_private_symbol(),
2635
          args[0]).FromJust());
2636
    // Server should select ALPN protocol from list of advertised by client
2637
147
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_), SelectALPNCallback,
2638
147
                               nullptr);
2639
  }
2640
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2641
}
2642
2643
2644
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2645
template <class Base>
2646
9
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2647
9
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2648
9
  Environment* env = w->env();
2649
9
  HandleScope handle_scope(env->isolate());
2650
2651

9
  if (w->is_client()) {
2652
    // Incoming response
2653
    const unsigned char* resp;
2654
4
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2655
    Local<Value> arg;
2656

4
    if (resp == nullptr) {
2657
4
      arg = Null(env->isolate());
2658
    } else {
2659
4
      arg =
2660
2
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2661
          .ToLocalChecked();
2662
    }
2663
2664
4
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2665
2666
    // Somehow, client is expecting different return value here
2667
4
    return 1;
2668
  } else {
2669
    // Outgoing response
2670

10
    if (w->ocsp_response_.IsEmpty())
2671
3
      return SSL_TLSEXT_ERR_NOACK;
2672
2673
2
    Local<Object> obj = PersistentToLocal(env->isolate(), w->ocsp_response_);
2674
2
    char* resp = Buffer::Data(obj);
2675
2
    size_t len = Buffer::Length(obj);
2676
2677
    // OpenSSL takes control of the pointer after accepting it
2678
2
    char* data = node::Malloc(len);
2679
2
    memcpy(data, resp, len);
2680
2681

2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2682
      free(data);
2683
2
    w->ocsp_response_.Reset();
2684
2685
2
    return SSL_TLSEXT_ERR_OK;
2686
9
  }
2687
}
2688
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2689
2690
2691
template <class Base>
2692
22
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2693
22
  cert_cb_ = cb;
2694
22
  cert_cb_arg_ = arg;
2695
22
}
2696
2697
2698
template <class Base>
2699
404
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2700
404
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2701
2702

404
  if (!w->is_server())
2703
28
    return 1;
2704
2705

376
  if (!w->is_waiting_cert_cb())
2706
354
    return 1;
2707
2708

22
  if (w->cert_cb_running_)
2709
    return -1;
2710
2711
22
  Environment* env = w->env();
2712
22
  HandleScope handle_scope(env->isolate());
2713
22
  Context::Scope context_scope(env->context());
2714
22
  w->cert_cb_running_ = true;
2715
2716
22
  Local<Object> info = Object::New(env->isolate());
2717
2718
22
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2719

22
  if (servername == nullptr) {
2720
24
    info->Set(env->servername_string(), String::Empty(env->isolate()));
2721
  } else {
2722
    Local<String> str = OneByteString(env->isolate(), servername,
2723
14
                                      strlen(servername));
2724
28
    info->Set(env->servername_string(), str);
2725
  }
2726
2727
22
  bool ocsp = false;
2728
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2729
22
  ocsp = SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp;
2730
#endif
2731
2732
66
  info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp));
2733
2734
44
  Local<Value> argv[] = { info };
2735
22
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2736
2737

22
  if (!w->cert_cb_running_)
2738
13
    return 1;
2739
2740
  // Performing async action, wait...
2741
31
  return -1;
2742
}
2743
2744
2745
template <class Base>
2746
22
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2747
  Base* w;
2748

24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2749
22
  Environment* env = w->env();
2750
2751



22
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2752
2753
22
  Local<Object> object = w->object();
2754
44
  Local<Value> ctx = object->Get(env->sni_context_string());
2755
22
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2756
2757
  // Not an object, probably undefined or null
2758

22
  if (!ctx->IsObject())
2759
12
    goto fire_cb;
2760
2761

10
  if (cons->HasInstance(ctx)) {
2762
    SecureContext* sc;
2763

10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2764
9
    w->sni_context_.Reset();
2765
9
    w->sni_context_.Reset(env->isolate(), ctx);
2766
2767
    int rv;
2768
2769
    // NOTE: reference count is not increased by this API methods
2770
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_);
2771
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_);
2772
    STACK_OF(X509)* chain;
2773
2774
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain);
2775

9
    if (rv)
2776
9
      rv = SSL_use_certificate(w->ssl_, x509);
2777

9
    if (rv)
2778
8
      rv = SSL_use_PrivateKey(w->ssl_, pkey);
2779


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

9
    if (rv)
2782
8
      rv = w->SetCACerts(sc);
2783

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

1
      if (!err)
2786
        return env->ThrowError("CertCbDone");
2787
1
      return ThrowCryptoError(env, err);
2788
    }
2789
  } else {
2790
    // Failure: incorrect SNI context object
2791
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2792
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2793
1
    return;
2794
  }
2795
2796
 fire_cb:
2797
  CertCb cb;
2798
  void* arg;
2799
2800
20
  cb = w->cert_cb_;
2801
20
  arg = w->cert_cb_arg_;
2802
2803
20
  w->cert_cb_running_ = false;
2804
20
  w->cert_cb_ = nullptr;
2805
20
  w->cert_cb_arg_ = nullptr;
2806
2807
20
  cb(arg);
2808
}
2809
2810
2811
template <class Base>
2812
void SSLWrap<Base>::SSLGetter(const FunctionCallbackInfo<Value>& info) {
2813
  Base* base;
2814
  ASSIGN_OR_RETURN_UNWRAP(&base, info.This());
2815
  SSL* ssl = base->ssl_;
2816
  Local<External> ext = External::New(info.GetIsolate(), ssl);
2817
  info.GetReturnValue().Set(ext);
2818
}
2819
2820
2821
template <class Base>
2822
21522
void SSLWrap<Base>::DestroySSL() {
2823

21522
  if (ssl_ == nullptr)
2824
32274
    return;
2825
2826
10770
  SSL_free(ssl_);
2827
10770
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2828
10770
  ssl_ = nullptr;
2829
}
2830
2831
2832
template <class Base>
2833
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2834
  InitNPN(sc);
2835
  CHECK_EQ(SSL_set_SSL_CTX(ssl_, sc->ctx_), sc->ctx_);
2836
2837
  SetCACerts(sc);
2838
}
2839
2840
2841
template <class Base>
2842
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2843
8
  int err = SSL_set1_verify_cert_store(ssl_, SSL_CTX_get_cert_store(sc->ctx_));
2844

8
  if (err != 1)
2845
    return err;
2846
2847
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2848
8
      SSL_CTX_get_client_CA_list(sc->ctx_));
2849
2850
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2851
8
  SSL_set_client_CA_list(ssl_, list);
2852
8
  return 1;
2853
}
2854
2855
2856
10016
Connection::Connection(Environment* env,
2857
                       v8::Local<v8::Object> wrap,
2858
                       SecureContext* sc,
2859
                       SSLWrap<Connection>::Kind kind)
2860
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_SSLCONNECTION),
2861
      SSLWrap<Connection>(env, sc, kind),
2862
      bio_read_(nullptr),
2863
      bio_write_(nullptr),
2864
50080
      hello_offset_(0) {
2865
10016
  MakeWeak<Connection>(this);
2866
10016
  Wrap(wrap, this);
2867
  hello_parser_.Start(SSLWrap<Connection>::OnClientHello,
2868
                      OnClientHelloParseEnd,
2869
10016
                      this);
2870
10016
  enable_session_callbacks();
2871
10016
}
2872
2873
2874
3
void Connection::OnClientHelloParseEnd(void* arg) {
2875
3
  Connection* conn = static_cast<Connection*>(arg);
2876
2877
  // Write all accumulated data
2878
  int r = BIO_write(conn->bio_read_,
2879
                    reinterpret_cast<char*>(conn->hello_data_),
2880
3
                    conn->hello_offset_);
2881
3
  conn->HandleBIOError(conn->bio_read_, "BIO_write", r);
2882
3
  conn->SetShutdownFlags();
2883
3
}
2884
2885
2886
#ifdef SSL_PRINT_DEBUG
2887
# define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
2888
#else
2889
# define DEBUG_PRINT(...)
2890
#endif
2891
2892
2893
27
int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
2894
27
  if (rv >= 0)
2895
10
    return rv;
2896
2897
17
  int retry = BIO_should_retry(bio);
2898
17
  USE(retry);  // unused if !defined(SSL_PRINT_DEBUG)
2899
2900
17
  if (BIO_should_write(bio)) {
2901
    DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n",
2902
                ssl_,
2903
                func,
2904
                retry);
2905
    return 0;
2906
2907
17
  } else if (BIO_should_read(bio)) {
2908
    DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
2909
17
    return 0;
2910
2911
  } else {
2912
    char ssl_error_buf[512];
2913
    ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
2914
2915
    HandleScope scope(ssl_env()->isolate());
2916
    Local<Value> exception =
2917
        Exception::Error(OneByteString(ssl_env()->isolate(), ssl_error_buf));
2918
    object()->Set(ssl_env()->error_string(), exception);
2919
2920
    DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n",
2921
                ssl_,
2922
                func,
2923
                rv,
2924
                ssl_error_buf);
2925
2926
    return rv;
2927
  }
2928
2929
  return 0;
2930
}
2931
2932
2933
35
int Connection::HandleSSLError(const char* func,
2934
                               int rv,
2935
                               ZeroStatus zs,
2936
                               SyscallStatus ss) {
2937
  ClearErrorOnReturn clear_error_on_return;
2938
2939
35
  if (rv > 0)
2940
4
    return rv;
2941

31
  if (rv == 0 && zs == kZeroIsNotAnError)
2942
1
    return rv;
2943
2944
30
  int err = SSL_get_error(ssl_, rv);
2945
2946
30
  if (err == SSL_ERROR_NONE) {
2947
    return 0;
2948
2949
30
  } else if (err == SSL_ERROR_WANT_WRITE) {
2950
    DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
2951
    return 0;
2952
2953
30
  } else if (err == SSL_ERROR_WANT_READ) {
2954
    DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
2955
29
    return 0;
2956
2957
1
  } else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2958
    DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2959
    return 0;
2960
2961
1
  } else if (err == SSL_ERROR_ZERO_RETURN) {
2962
    HandleScope scope(ssl_env()->isolate());
2963
2964
    Local<Value> exception =
2965
        Exception::Error(ssl_env()->zero_return_string());
2966
    object()->Set(ssl_env()->error_string(), exception);
2967
    return rv;
2968
2969

1
  } else if (err == SSL_ERROR_SYSCALL && ss == kIgnoreSyscall) {
2970
    return 0;
2971
2972
  } else {
2973
1
    HandleScope scope(ssl_env()->isolate());
2974
    BUF_MEM* mem;
2975
    BIO *bio;
2976
2977

1
    CHECK(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
2978
2979
    // XXX We need to drain the error queue for this thread or else OpenSSL
2980
    // has the possibility of blocking connections? This problem is not well
2981
    // understood. And we should be somehow propagating these errors up
2982
    // into JavaScript. There is no test which demonstrates this problem.
2983
    // https://github.com/joyent/node/issues/1719
2984
1
    bio = BIO_new(BIO_s_mem());
2985
1
    if (bio != nullptr) {
2986
1
      ERR_print_errors(bio);
2987
1
      BIO_get_mem_ptr(bio, &mem);
2988
      Local<Value> exception = Exception::Error(
2989
          OneByteString(ssl_env()->isolate(),
2990
            mem->data,
2991
1
            mem->length));
2992
3
      object()->Set(ssl_env()->error_string(), exception);
2993
1
      BIO_free_all(bio);
2994
    }
2995
2996
1
    return rv;
2997
  }
2998
2999
35
  return 0;
3000
}
3001
3002
3003
36
void Connection::SetShutdownFlags() {
3004
36
  HandleScope scope(ssl_env()->isolate());
3005
3006
36
  int flags = SSL_get_shutdown(ssl_);
3007
3008
36
  if (flags & SSL_SENT_SHUTDOWN) {
3009
    Local<String> sent_shutdown_key = ssl_env()->sent_shutdown_string();
3010
    object()->Set(sent_shutdown_key, True(ssl_env()->isolate()));
3011
  }
3012
3013
36
  if (flags & SSL_RECEIVED_SHUTDOWN) {
3014
1
    Local<String> received_shutdown_key = ssl_env()->received_shutdown_string();
3015
3
    object()->Set(received_shutdown_key, True(ssl_env()->isolate()));
3016
36
  }
3017
36
}
3018
3019
3020
void Connection::NewSessionDoneCb() {
3021
  HandleScope scope(env()->isolate());
3022
3023
  MakeCallback(env()->onnewsessiondone_string(), 0, nullptr);
3024
}
3025
3026
3027
420
void Connection::Initialize(Environment* env, Local<Object> target) {
3028
420
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Connection::New);
3029
840
  t->InstanceTemplate()->SetInternalFieldCount(1);
3030
840
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"));
3031
3032
420
  AsyncWrap::AddWrapMethods(env, t);
3033
420
  env->SetProtoMethod(t, "encIn", EncIn);
3034
420
  env->SetProtoMethod(t, "clearOut", ClearOut);
3035
420
  env->SetProtoMethod(t, "clearIn", ClearIn);
3036
420
  env->SetProtoMethod(t, "encOut", EncOut);
3037
420
  env->SetProtoMethod(t, "clearPending", ClearPending);
3038
420
  env->SetProtoMethod(t, "encPending", EncPending);
3039
420
  env->SetProtoMethod(t, "start", Start);
3040
420
  env->SetProtoMethod(t, "close", Close);
3041
3042
420
  SSLWrap<Connection>::AddMethods(env, t);
3043
3044
3045
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3046
420
  env->SetProtoMethod(t, "getServername", GetServername);
3047
420
  env->SetProtoMethod(t, "setSNICallback",  SetSNICallback);
3048
#endif
3049
3050
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"),
3051
1260
              t->GetFunction());
3052
420
}
3053
3054
3055
9
inline int compar(const void* a, const void* b) {
3056
9
  return memcmp(a, b, CNNIC_WHITELIST_HASH_LEN);
3057
}
3058
3059
3060
113
inline int IsSelfSigned(X509* cert) {
3061
113
  return X509_NAME_cmp(X509_get_subject_name(cert),
3062
226
                       X509_get_issuer_name(cert)) == 0;
3063
}
3064
3065
3066
inline X509* FindRoot(STACK_OF(X509)* sk) {
3067
  for (int i = 0; i < sk_X509_num(sk); i++) {
3068
    X509* cert = sk_X509_value(sk, i);
3069
    if (IsSelfSigned(cert))
3070
      return cert;
3071
  }
3072
  return nullptr;
3073
}
3074
3075
3076
113
inline bool CertIsStartComOrWoSign(X509_NAME* name) {
3077
  const unsigned char* startcom_wosign_data;
3078
  X509_NAME* startcom_wosign_name;
3079
3080
757
  for (const auto& dn : StartComAndWoSignDNs) {
3081
661
    startcom_wosign_data = dn.data;
3082
    startcom_wosign_name = d2i_X509_NAME(nullptr, &startcom_wosign_data,
3083
661
                                         dn.len);
3084
661
    int cmp = X509_NAME_cmp(name, startcom_wosign_name);
3085
661
    X509_NAME_free(startcom_wosign_name);
3086
661
    if (cmp == 0)
3087
17
      return true;
3088
  }
3089
3090
96
  return false;
3091
}
3092
3093
// Revoke the certificates issued by StartCom or WoSign that has
3094
// notBefore after 00:00:00 on October 21, 2016 (1477008000 in epoch).
3095
113
inline bool CheckStartComOrWoSign(X509_NAME* root_name, X509* cert) {
3096
113
  if (!CertIsStartComOrWoSign(root_name))
3097
96
    return true;
3098
3099
17
  time_t october_21_2016 = static_cast<time_t>(1477008000);
3100
17
  if (X509_cmp_time(X509_get_notBefore(cert), &october_21_2016) < 0)
3101
16
    return true;
3102
3103
1
  return false;
3104
}
3105
3106
3107
// Whitelist check for certs issued by CNNIC, StartCom and WoSign. See
3108
// https://blog.mozilla.org/security/2015/04/02
3109
// /distrusting-new-cnnic-certificates/ and
3110
// https://blog.mozilla.org/security/2016/10/24/
3111
// distrusting-new-wosign-and-startcom-certificates
3112
113
inline CheckResult CheckWhitelistedServerCert(X509_STORE_CTX* ctx) {
3113
  unsigned char hash[CNNIC_WHITELIST_HASH_LEN];
3114
113
  unsigned int hashlen = CNNIC_WHITELIST_HASH_LEN;
3115
3116
113
  STACK_OF(X509)* chain = X509_STORE_CTX_get1_chain(ctx);
3117
113
  CHECK_NE(chain, nullptr);
3118
113
  CHECK_GT(sk_X509_num(chain), 0);
3119
3120
  // Take the last cert as root at the first time.
3121
113
  X509* root_cert = sk_X509_value(chain, sk_X509_num(chain)-1);
3122
113
  X509_NAME* root_name = X509_get_subject_name(root_cert);
3123
3124
113
  if (!IsSelfSigned(root_cert)) {
3125
    root_cert = FindRoot(chain);
3126
    CHECK_NE(root_cert, nullptr);
3127
    root_name = X509_get_subject_name(root_cert);
3128
  }
3129
3130
113
  X509* leaf_cert = sk_X509_value(chain, 0);
3131
113
  if (!CheckStartComOrWoSign(root_name, leaf_cert)) {
3132
1
    sk_X509_pop_free(chain, X509_free);
3133
1
    return CHECK_CERT_REVOKED;
3134
  }
3135
3136
  // When the cert is issued from either CNNNIC ROOT CA or CNNNIC EV
3137
  // ROOT CA, check a hash of its leaf cert if it is in the whitelist.
3138

223
  if (X509_NAME_cmp(root_name, cnnic_name) == 0 ||
3139
111
      X509_NAME_cmp(root_name, cnnic_ev_name) == 0) {
3140
    int ret = X509_digest(leaf_cert, EVP_sha256(), hash,
3141
1
                          &hashlen);
3142
1
    CHECK(ret);
3143
3144
    void* result = bsearch(hash, WhitelistedCNNICHashes,
3145
                           arraysize(WhitelistedCNNICHashes),
3146
1
                           CNNIC_WHITELIST_HASH_LEN, compar);
3147
1
    if (result == nullptr) {
3148
1
      sk_X509_pop_free(chain, X509_free);
3149
1
      return CHECK_CERT_REVOKED;
3150
    }
3151
  }
3152
3153
111
  sk_X509_pop_free(chain, X509_free);
3154
111
  return CHECK_OK;
3155
}
3156
3157
3158
742
inline int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
3159
  // Failure on verification of the cert is handled in
3160
  // Connection::VerifyError.
3161

742
  if (preverify_ok == 0 || X509_STORE_CTX_get_error(ctx) != X509_V_OK)
3162
591
    return CHECK_OK;
3163
3164
  // Server does not need to check the whitelist.
3165
  SSL* ssl = static_cast<SSL*>(
3166
151
      X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
3167
3168
151
  if (SSL_is_server(ssl))
3169
38
    return CHECK_OK;
3170
3171
  // Client needs to check if the server cert is listed in the
3172
  // whitelist when it is issued by the specific rootCAs.
3173
113
  CheckResult ret = CheckWhitelistedServerCert(ctx);
3174
113
  if (ret == CHECK_CERT_REVOKED)
3175
2
    X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
3176
3177
113
  return ret;
3178
}
3179
3180
3181
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3182
3
int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
3183
3
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(s));
3184
3
  Environment* env = conn->env();
3185
3
  HandleScope scope(env->isolate());
3186
3187
3
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3188
3189
3
  if (servername) {
3190
    conn->servername_.Reset(env->isolate(),
3191
4
                            OneByteString(env->isolate(), servername));
3192
3193
    // Call the SNI callback and use its return value as context
3194
4
    if (!conn->sniObject_.IsEmpty()) {
3195
2
      conn->sni_context_.Reset();
3196
3197
      Local<Object> sni_obj = PersistentToLocal(env->isolate(),
3198
2
                                                conn->sniObject_);
3199
3200
2
      Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
3201
      Local<Value> ret = node::MakeCallback(env->isolate(),
3202
                                            sni_obj,
3203
                                            env->onselect_string(),
3204
                                            1,
3205
2
                                            &arg);
3206
3207
      // If ret is SecureContext
3208
      Local<FunctionTemplate> secure_context_constructor_template =
3209
2
          env->secure_context_constructor_template();
3210
2
      if (secure_context_constructor_template->HasInstance(ret)) {
3211
        conn->sni_context_.Reset(env->isolate(), ret);
3212
        SecureContext* sc;
3213
        ASSIGN_OR_RETURN_UNWRAP(&sc, ret.As<Object>(), SSL_TLSEXT_ERR_NOACK);
3214
        conn->SetSNIContext(sc);
3215
      } else {
3216
2
        return SSL_TLSEXT_ERR_NOACK;
3217
      }
3218
    }
3219
  }
3220
3221
1
  return SSL_TLSEXT_ERR_OK;
3222
}
3223
#endif
3224
3225
10017
void Connection::New(const FunctionCallbackInfo<Value>& args) {
3226
10017
  Environment* env = Environment::GetCurrent(args);
3227
3228


40068
  if (args.Length() < 1 || !args[0]->IsObject()) {
3229
1
    env->ThrowError("First argument must be a tls module SecureContext");
3230
1
    return;
3231
  }
3232
3233
  SecureContext* sc;
3234
20032
  ASSIGN_OR_RETURN_UNWRAP(&sc, args[0].As<Object>());
3235
3236
20032
  bool is_server = args[1]->BooleanValue();
3237
3238
  SSLWrap<Connection>::Kind kind =
3239
10016
      is_server ? SSLWrap<Connection>::kServer : SSLWrap<Connection>::kClient;
3240
10016
  Connection* conn = new Connection(env, args.This(), sc, kind);
3241
10016
  conn->bio_read_ = NodeBIO::New();
3242
10016
  conn->bio_write_ = NodeBIO::New();
3243
3244
10016
  SSL_set_app_data(conn->ssl_, conn);
3245
3246
10016
  if (is_server)
3247
12
    SSL_set_info_callback(conn->ssl_, SSLInfoCallback);
3248
3249
10016
  InitNPN(sc);
3250
3251
10016
  SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
3252
3253
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3254
10016
  if (is_server) {
3255
12
    SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
3256
30012
  } else if (args[2]->IsString()) {
3257
    const node::Utf8Value servername(env->isolate(), args[2]);
3258
    SSL_set_tlsext_host_name(conn->ssl_, *servername);
3259
  }
3260
#endif
3261
3262
10016
  SSL_set_bio(conn->ssl_, conn->bio_read_, conn->bio_write_);
3263
3264
#ifdef SSL_MODE_RELEASE_BUFFERS
3265
10016
  long mode = SSL_get_mode(conn->ssl_);  // NOLINT(runtime/int)
3266
10016
  SSL_set_mode(conn->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
3267
#endif
3268
3269
3270
  int verify_mode;
3271
10016
  if (is_server) {
3272
24
    bool request_cert = args[2]->BooleanValue();
3273
12
    if (!request_cert) {
3274
      // Note reject_unauthorized ignored.
3275
4
      verify_mode = SSL_VERIFY_NONE;
3276
    } else {
3277
16
      bool reject_unauthorized = args[3]->BooleanValue();
3278
8
      verify_mode = SSL_VERIFY_PEER;
3279
8
      if (reject_unauthorized)
3280
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3281
    }
3282
  } else {
3283
    // Note request_cert and reject_unauthorized are ignored for clients.
3284
10004
    verify_mode = SSL_VERIFY_NONE;
3285
  }
3286
3287
3288
  // Always allow a connection. We'll reject in javascript.
3289
10016
  SSL_set_verify(conn->ssl_, verify_mode, VerifyCallback);
3290
3291
10016
  if (is_server) {
3292
12
    SSL_set_accept_state(conn->ssl_);
3293
  } else {
3294
10004
    SSL_set_connect_state(conn->ssl_);
3295
  }
3296
}
3297
3298
3299
72
void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
3300
72
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
3301
131
    return;
3302
3303
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
3304
  // a non-const SSL* in OpenSSL <= 0.9.7e.
3305
13
  SSL* ssl = const_cast<SSL*>(ssl_);
3306
13
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(ssl));
3307
13
  Environment* env = conn->env();
3308
13
  HandleScope handle_scope(env->isolate());
3309
13
  Context::Scope context_scope(env->context());
3310
3311
13
  if (where & SSL_CB_HANDSHAKE_START) {
3312
12
    conn->MakeCallback(env->onhandshakestart_string(), 0, nullptr);
3313
  }
3314
3315
13
  if (where & SSL_CB_HANDSHAKE_DONE) {
3316
1
    conn->MakeCallback(env->onhandshakedone_string(), 0, nullptr);
3317
13
  }
3318
}
3319
3320
3321
6
void Connection::EncIn(const FunctionCallbackInfo<Value>& args) {
3322
  Connection* conn;
3323
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3324
6
  Environment* env = conn->env();
3325
3326
6
  if (args.Length() < 3) {
3327
    return env->ThrowTypeError(
3328
        "Data, offset, and length arguments are mandatory");
3329
  }
3330
3331
6
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3332
3333
6
  char* buffer_data = Buffer::Data(args[0]);
3334
6
  size_t buffer_length = Buffer::Length(args[0]);
3335
3336
12
  size_t off = args[1]->Int32Value();
3337
12
  size_t len = args[2]->Int32Value();
3338
3339
6
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3340
    return env->ThrowRangeError("offset + length > buffer.length");
3341
3342
  int bytes_written;
3343
6
  char* data = buffer_data + off;
3344
3345

6
  if (conn->is_server() && !conn->hello_parser_.IsEnded()) {
3346
    // Just accumulate data, everything will be pushed to BIO later
3347
3
    if (conn->hello_parser_.IsPaused()) {
3348
      bytes_written = 0;
3349
    } else {
3350
      // Copy incoming data to the internal buffer
3351
      // (which has a size of the biggest possible TLS frame)
3352
3
      size_t available = sizeof(conn->hello_data_) - conn->hello_offset_;
3353
3
      size_t copied = len < available ? len : available;
3354
3
      memcpy(conn->hello_data_ + conn->hello_offset_, data, copied);
3355
3
      conn->hello_offset_ += copied;
3356
3357
3
      conn->hello_parser_.Parse(conn->hello_data_, conn->hello_offset_);
3358
3
      bytes_written = copied;
3359
    }
3360
  } else {
3361
3
    bytes_written = BIO_write(conn->bio_read_, data, len);
3362
3
    conn->HandleBIOError(conn->bio_read_, "BIO_write", bytes_written);
3363
3
    conn->SetShutdownFlags();
3364
  }
3365
3366
12
  args.GetReturnValue().Set(bytes_written);
3367
}
3368
3369
3370
16
void Connection::ClearOut(const FunctionCallbackInfo<Value>& args) {
3371
  Connection* conn;
3372
25
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3373
16
  Environment* env = conn->env();
3374
3375
16
  if (args.Length() < 3) {
3376
    return env->ThrowTypeError(
3377
        "Data, offset, and length arguments are mandatory");
3378
  }
3379
3380
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3381
3382
16
  char* buffer_data = Buffer::Data(args[0]);
3383
16
  size_t buffer_length = Buffer::Length(args[0]);
3384
3385
32
  size_t off = args[1]->Int32Value();
3386
32
  size_t len = args[2]->Int32Value();
3387
3388
16
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3389
    return env->ThrowRangeError("offset + length > buffer.length");
3390
3391
16
  if (!SSL_is_init_finished(conn->ssl_)) {
3392
    int rv;
3393
3394
10
    if (conn->is_server()) {
3395
10
      rv = SSL_accept(conn->ssl_);
3396
      conn->HandleSSLError("SSL_accept:ClearOut",
3397
                           rv,
3398
                           kZeroIsAnError,
3399
10
                           kSyscallError);
3400
    } else {
3401
      rv = SSL_connect(conn->ssl_);
3402
      conn->HandleSSLError("SSL_connect:ClearOut",
3403
                           rv,
3404
                           kZeroIsAnError,
3405
                           kSyscallError);
3406
    }
3407
3408
10
    if (rv < 0) {
3409
18
      return args.GetReturnValue().Set(rv);
3410
    }
3411
  }
3412
3413
7
  int bytes_read = SSL_read(conn->ssl_, buffer_data + off, len);
3414
  conn->HandleSSLError("SSL_read:ClearOut",
3415
                       bytes_read,
3416
                       kZeroIsNotAnError,
3417
7
                       kSyscallError);
3418
7
  conn->SetShutdownFlags();
3419
3420
14
  args.GetReturnValue().Set(bytes_read);
3421
}
3422
3423
3424
19
void Connection::ClearPending(const FunctionCallbackInfo<Value>& args) {
3425
  Connection* conn;
3426
38
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3427
19
  int bytes_pending = BIO_pending(conn->bio_read_);
3428
38
  args.GetReturnValue().Set(bytes_pending);
3429
}
3430
3431
3432
26
void Connection::EncPending(const FunctionCallbackInfo<Value>& args) {
3433
  Connection* conn;
3434
52
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3435
26
  int bytes_pending = BIO_pending(conn->bio_write_);
3436
52
  args.GetReturnValue().Set(bytes_pending);
3437
}
3438
3439
3440
21
void Connection::EncOut(const FunctionCallbackInfo<Value>& args) {
3441
  Connection* conn;
3442
21
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3443
21
  Environment* env = conn->env();
3444
3445
21
  if (args.Length() < 3) {
3446
    return env->ThrowTypeError(
3447
        "Data, offset, and length arguments are mandatory");
3448
  }
3449
3450
21
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3451
3452
21
  char* buffer_data = Buffer::Data(args[0]);
3453
21
  size_t buffer_length = Buffer::Length(args[0]);
3454
3455
42
  size_t off = args[1]->Int32Value();
3456
42
  size_t len = args[2]->Int32Value();
3457