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: 2695 3061 88.0 %
Date: 2017-10-21 Branches: 1280 2242 57.1 %

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

407
  mutexes = new Mutex[CRYPTO_num_locks()];
216
407
}
217
218
219
1627900
static void crypto_lock_cb(int mode, int n, const char* file, int line) {
220
1627900
  CHECK(!(mode & CRYPTO_LOCK) ^ !(mode & CRYPTO_UNLOCK));
221
1627900
  CHECK(!(mode & CRYPTO_READ) ^ !(mode & CRYPTO_WRITE));
222
223
1627900
  auto mutex = &mutexes[n];
224
1627900
  if (mode & CRYPTO_LOCK)
225
813950
    mutex->Lock();
226
  else
227
813950
    mutex->Unlock();
228
1627900
}
229
230
231
29
static int PasswordCallback(char *buf, int size, int rwflag, void *u) {
232
29
  if (u) {
233
26
    size_t buflen = static_cast<size_t>(size);
234
26
    size_t len = strlen(static_cast<const char*>(u));
235
26
    len = len > buflen ? buflen : len;
236
26
    memcpy(buf, u, len);
237
26
    return len;
238
  }
239
240
3
  return 0;
241
}
242
243
244
// This callback is used to avoid the default passphrase callback in OpenSSL
245
// which will typically prompt for the passphrase. The prompting is designed
246
// for the OpenSSL CLI, but works poorly for Node.js because it involves
247
// synchronous interaction with the controlling terminal, something we never
248
// want, and use this function to avoid it.
249
static int NoPasswordCallback(char *buf, int size, int rwflag, void *u) {
250
  return 0;
251
}
252
253
254
29
void ThrowCryptoError(Environment* env,
255
                      unsigned long err,  // NOLINT(runtime/int)
256
                      const char* default_message = nullptr) {
257
29
  HandleScope scope(env->isolate());
258
  Local<String> message;
259
260

29
  if (err != 0 || default_message == nullptr) {
261
25
    char errmsg[128] = { 0 };
262
25
    ERR_error_string_n(err, errmsg, sizeof(errmsg));
263
    message = String::NewFromUtf8(env->isolate(), errmsg,
264
25
                                  v8::NewStringType::kNormal)
265
50
                                      .ToLocalChecked();
266
  } else {
267
    message = String::NewFromUtf8(env->isolate(), default_message,
268
4
                                  v8::NewStringType::kNormal)
269
8
                                      .ToLocalChecked();
270
  }
271
272
29
  Local<Value> exception_v = Exception::Error(message);
273
29
  CHECK(!exception_v.IsEmpty());
274
29
  Local<Object> exception = exception_v.As<Object>();
275
29
  ERR_STATE* es = ERR_get_state();
276
277
29
  if (es->bottom != es->top) {
278
11
    Local<Array> error_stack = Array::New(env->isolate());
279
11
    int top = es->top;
280
281
    // Build the error_stack array to be added to opensslErrorStack property.
282
53
    for (unsigned int i = 0; es->bottom != es->top;) {
283
31
      unsigned long err_buf = es->err_buffer[es->top];  // NOLINT(runtime/int)
284
      // Only add error string if there is valid err_buffer.
285
31
      if (err_buf) {
286
        char tmp_str[256];
287
31
        ERR_error_string_n(err_buf, tmp_str, sizeof(tmp_str));
288
31
        error_stack->Set(env->context(), i,
289
                        String::NewFromUtf8(env->isolate(), tmp_str,
290
31
                                              v8::NewStringType::kNormal)
291
124
                                                  .ToLocalChecked()).FromJust();
292
        // Only increment if we added to error_stack.
293
31
        i++;
294
      }
295
296
      // Since the ERR_STATE is a ring buffer, we need to use modular
297
      // arithmetic to loop back around in the case where bottom is after top.
298
      // Using ERR_NUM_ERRORS  macro defined in openssl.
299
31
      es->top = (((es->top - 1) % ERR_NUM_ERRORS) + ERR_NUM_ERRORS) %
300
31
          ERR_NUM_ERRORS;
301
    }
302
303
    // Restore top.
304
11
    es->top = top;
305
306
    // Add the opensslErrorStack property to the exception object.
307
    // The new property will look like the following:
308
    // opensslErrorStack: [
309
    // 'error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib',
310
    // 'error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 err'
311
    // ]
312
44
    exception->Set(env->context(), env->openssl_error_stack(), error_stack)
313
22
        .FromJust();
314
  }
315
316
29
  env->isolate()->ThrowException(exception);
317
29
}
318
319
320
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
321
// The entropy pool starts out empty and needs to fill up before the PRNG
322
// can be used securely.  Once the pool is filled, it never dries up again;
323
// its contents is stirred and reused when necessary.
324
//
325
// OpenSSL normally fills the pool automatically but not when someone starts
326
// generating random numbers before the pool is full: in that case OpenSSL
327
// keeps lowering the entropy estimate to thwart attackers trying to guess
328
// the initial state of the PRNG.
329
//
330
// When that happens, we will have to wait until enough entropy is available.
331
// That should normally never take longer than a few milliseconds.
332
//
333
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
334
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
335
// block under normal circumstances.
336
//
337
// The only time when /dev/urandom may conceivably block is right after boot,
338
// when the whole system is still low on entropy.  That's not something we can
339
// do anything about.
340
6612
inline void CheckEntropy() {
341
  for (;;) {
342
6612
    int status = RAND_status();
343
6612
    CHECK_GE(status, 0);  // Cannot fail.
344
6612
    if (status != 0)
345
6612
      break;
346
347
    // Give up, RAND_poll() not supported.
348
    if (RAND_poll() == 0)
349
      break;
350
  }
351
6612
}
352
353
354
6472
bool EntropySource(unsigned char* buffer, size_t length) {
355
  // Ensure that OpenSSL's PRNG is properly seeded.
356
6472
  CheckEntropy();
357
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
358
  // random. That's okay, it's still better than V8's stock source of entropy,
359
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
360
6472
  return RAND_bytes(buffer, length) != -1;
361
}
362
363
364
407
void SecureContext::Initialize(Environment* env, Local<Object> target) {
365
407
  Local<FunctionTemplate> t = env->NewFunctionTemplate(SecureContext::New);
366
814
  t->InstanceTemplate()->SetInternalFieldCount(1);
367
  Local<String> secureContextString =
368
407
      FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext");
369
407
  t->SetClassName(secureContextString);
370
371
407
  env->SetProtoMethod(t, "init", SecureContext::Init);
372
407
  env->SetProtoMethod(t, "setKey", SecureContext::SetKey);
373
407
  env->SetProtoMethod(t, "setCert", SecureContext::SetCert);
374
407
  env->SetProtoMethod(t, "addCACert", SecureContext::AddCACert);
375
407
  env->SetProtoMethod(t, "addCRL", SecureContext::AddCRL);
376
407
  env->SetProtoMethod(t, "addRootCerts", SecureContext::AddRootCerts);
377
407
  env->SetProtoMethod(t, "setCiphers", SecureContext::SetCiphers);
378
407
  env->SetProtoMethod(t, "setECDHCurve", SecureContext::SetECDHCurve);
379
407
  env->SetProtoMethod(t, "setDHParam", SecureContext::SetDHParam);
380
407
  env->SetProtoMethod(t, "setOptions", SecureContext::SetOptions);
381
  env->SetProtoMethod(t, "setSessionIdContext",
382
407
                      SecureContext::SetSessionIdContext);
383
  env->SetProtoMethod(t, "setSessionTimeout",
384
407
                      SecureContext::SetSessionTimeout);
385
407
  env->SetProtoMethod(t, "close", SecureContext::Close);
386
407
  env->SetProtoMethod(t, "loadPKCS12", SecureContext::LoadPKCS12);
387
407
  env->SetProtoMethod(t, "getTicketKeys", SecureContext::GetTicketKeys);
388
407
  env->SetProtoMethod(t, "setTicketKeys", SecureContext::SetTicketKeys);
389
407
  env->SetProtoMethod(t, "setFreeListLength", SecureContext::SetFreeListLength);
390
  env->SetProtoMethod(t,
391
                      "enableTicketKeyCallback",
392
407
                      SecureContext::EnableTicketKeyCallback);
393
407
  env->SetProtoMethod(t, "getCertificate", SecureContext::GetCertificate<true>);
394
407
  env->SetProtoMethod(t, "getIssuer", SecureContext::GetCertificate<false>);
395
396
407
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyReturnIndex"),
397
1221
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyReturnIndex));
398
407
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyHMACIndex"),
399
1221
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyHMACIndex));
400
407
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyAESIndex"),
401
1221
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyAESIndex));
402
407
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyNameIndex"),
403
1221
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyNameIndex));
404
407
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyIVIndex"),
405
1221
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyIVIndex));
406
407
407
  t->PrototypeTemplate()->SetAccessor(
408
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
409
      CtxGetter,
410
      nullptr,
411
      env->as_external(),
412
      DEFAULT,
413
      static_cast<PropertyAttribute>(ReadOnly | DontDelete),
414
1628
      AccessorSignature::New(env->isolate(), t));
415
416
814
  target->Set(secureContextString, t->GetFunction());
417
407
  env->set_secure_context_constructor_template(t);
418
407
}
419
420
421
802
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
422
802
  Environment* env = Environment::GetCurrent(args);
423
802
  new SecureContext(env, args.This());
424
802
}
425
426
427
802
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
428
  SecureContext* sc;
429
809
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
430
802
  Environment* env = sc->env();
431
432
802
  const SSL_METHOD* method = SSLv23_method();
433
434


1718
  if (args.Length() == 1 && args[0]->IsString()) {
435
38
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
436
437
    // Note that SSLv2 and SSLv3 are disallowed but SSLv2_method and friends
438
    // are still accepted.  They are OpenSSL's way of saying that all known
439
    // protocols are supported unless explicitly disabled (which we do below
440
    // for SSLv2 and SSLv3.)
441
38
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
442
1
      return env->ThrowError("SSLv2 methods disabled");
443
37
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
444
1
      return env->ThrowError("SSLv2 methods disabled");
445
36
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
446
1
      return env->ThrowError("SSLv2 methods disabled");
447
35
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
448
1
      return env->ThrowError("SSLv3 methods disabled");
449
34
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
450
1
      return env->ThrowError("SSLv3 methods disabled");
451
33
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
452
1
      return env->ThrowError("SSLv3 methods disabled");
453
32
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
454
2
      method = SSLv23_method();
455
30
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
456
1
      method = SSLv23_server_method();
457
29
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
458
1
      method = SSLv23_client_method();
459
28
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
460
4
      method = TLSv1_method();
461
24
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
462
1
      method = TLSv1_server_method();
463
23
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
464
1
      method = TLSv1_client_method();
465
22
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
466
2
      method = TLSv1_1_method();
467
20
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
468
1
      method = TLSv1_1_server_method();
469
19
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
470
1
      method = TLSv1_1_client_method();
471
18
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
472
14
      method = TLSv1_2_method();
473
4
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
474
2
      method = TLSv1_2_server_method();
475
2
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
476
1
      method = TLSv1_2_client_method();
477
    } else {
478
1
      return env->ThrowError("Unknown method");
479
31
    }
480
  }
481
482
795
  sc->ctx_ = SSL_CTX_new(method);
483
795
  SSL_CTX_set_app_data(sc->ctx_, sc);
484
485
  // Disable SSLv2 in the case when method == SSLv23_method() and the
486
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
487
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
488
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
489
795
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv2);
490
795
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv3);
491
492
  // SSL session cache configuration
493
795
  SSL_CTX_set_session_cache_mode(sc->ctx_,
494
                                 SSL_SESS_CACHE_SERVER |
495
                                 SSL_SESS_CACHE_NO_INTERNAL |
496
795
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
497
795
  SSL_CTX_sess_set_get_cb(sc->ctx_, SSLWrap<Connection>::GetSessionCallback);
498
795
  SSL_CTX_sess_set_new_cb(sc->ctx_, SSLWrap<Connection>::NewSessionCallback);
499
}
500
501
502
// Takes a string or buffer and loads it into a BIO.
503
// Caller responsible for BIO_free_all-ing the returned object.
504
838
static BIO* LoadBIO(Environment* env, Local<Value> v) {
505
838
  HandleScope scope(env->isolate());
506
507
1676
  if (v->IsString()) {
508
132
    const node::Utf8Value s(env->isolate(), v);
509
132
    return NodeBIO::NewFixed(*s, s.length());
510
  }
511
512
706
  if (Buffer::HasInstance(v)) {
513
706
    return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
514
  }
515
516
  return nullptr;
517
}
518
519
520
332
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
521
332
  Environment* env = Environment::GetCurrent(args);
522
523
  SecureContext* sc;
524
342
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
525
526
332
  unsigned int len = args.Length();
527
332
  if (len < 1) {
528
    return env->ThrowError("Private key argument is mandatory");
529
  }
530
531
332
  if (len > 2) {
532
    return env->ThrowError("Only private key and pass phrase are expected");
533
  }
534
535
332
  if (len == 2) {
536


1397
    if (args[1]->IsUndefined() || args[1]->IsNull())
537
309
      len = 1;
538
    else
539
69
      THROW_AND_RETURN_IF_NOT_STRING(args[1], "Pass phrase");
540
  }
541
542
330
  BIO *bio = LoadBIO(env, args[0]);
543
330
  if (!bio)
544
    return;
545
546
330
  node::Utf8Value passphrase(env->isolate(), args[1]);
547
548
  EVP_PKEY* key = PEM_read_bio_PrivateKey(bio,
549
                                          nullptr,
550
                                          PasswordCallback,
551
330
                                          len == 1 ? nullptr : *passphrase);
552
553
330
  if (!key) {
554
7
    BIO_free_all(bio);
555
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
556
7
    if (!err) {
557
      return env->ThrowError("PEM_read_bio_PrivateKey");
558
    }
559
7
    return ThrowCryptoError(env, err);
560
  }
561
562
323
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_, key);
563
323
  EVP_PKEY_free(key);
564
323
  BIO_free_all(bio);
565
566
323
  if (!rv) {
567
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
568
1
    if (!err)
569
      return env->ThrowError("SSL_CTX_use_PrivateKey");
570
1
    return ThrowCryptoError(env, err);
571
322
  }
572
}
573
574
575
351
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
576
  int ret;
577
578
351
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
579
  X509_STORE_CTX store_ctx;
580
581
351
  ret = X509_STORE_CTX_init(&store_ctx, store, nullptr, nullptr);
582
351
  if (!ret)
583
    goto end;
584
585
351
  ret = X509_STORE_CTX_get1_issuer(issuer, &store_ctx, cert);
586
351
  X509_STORE_CTX_cleanup(&store_ctx);
587
588
 end:
589
351
  return ret;
590
}
591
592
593
357
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
594
                                  X509* x,
595
                                  STACK_OF(X509)* extra_certs,
596
                                  X509** cert,
597
                                  X509** issuer) {
598
357
  CHECK_EQ(*issuer, nullptr);
599
357
  CHECK_EQ(*cert, nullptr);
600
601
357
  int ret = SSL_CTX_use_certificate(ctx, x);
602
603
357
  if (ret) {
604
    // If we could set up our certificate, now proceed to
605
    // the CA certificates.
606
    int r;
607
608
357
    SSL_CTX_clear_extra_chain_certs(ctx);
609
610
365
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
611
8
      X509* ca = sk_X509_value(extra_certs, i);
612
613
      // NOTE: Increments reference count on `ca`
614
8
      r = SSL_CTX_add1_chain_cert(ctx, ca);
615
616
8
      if (!r) {
617
        ret = 0;
618
        *issuer = nullptr;
619
        goto end;
620
      }
621
      // Note that we must not free r if it was successfully
622
      // added to the chain (while we must free the main
623
      // certificate, since its reference count is increased
624
      // by SSL_CTX_use_certificate).
625
626
      // Find issuer
627

8
      if (*issuer != nullptr || X509_check_issued(ca, x) != X509_V_OK)
628
        continue;
629
630
8
      *issuer = ca;
631
    }
632
  }
633
634
  // Try getting issuer from a cert store
635
357
  if (ret) {
636
357
    if (*issuer == nullptr) {
637
349
      ret = SSL_CTX_get_issuer(ctx, x, issuer);
638
349
      ret = ret < 0 ? 0 : 1;
639
      // NOTE: get_cert_store doesn't increment reference count,
640
      // no need to free `store`
641
    } else {
642
      // Increment issuer reference count
643
8
      *issuer = X509_dup(*issuer);
644
8
      if (*issuer == nullptr) {
645
        ret = 0;
646
        goto end;
647
      }
648
    }
649
  }
650
651
 end:
652

357
  if (ret && x != nullptr) {
653
357
    *cert = X509_dup(x);
654
357
    if (*cert == nullptr)
655
      ret = 0;
656
  }
657
357
  return ret;
658
}
659
660
661
// Read a file that contains our certificate in "PEM" format,
662
// possibly followed by a sequence of CA certificates that should be
663
// sent to the peer in the Certificate message.
664
//
665
// Taken from OpenSSL - edited for style.
666
348
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
667
                                  BIO* in,
668
                                  X509** cert,
669
                                  X509** issuer) {
670
348
  X509* x = nullptr;
671
672
  // Just to ensure that `ERR_peek_last_error` below will return only errors
673
  // that we are interested in
674
348
  ERR_clear_error();
675
676
348
  x = PEM_read_bio_X509_AUX(in, nullptr, NoPasswordCallback, nullptr);
677
678
348
  if (x == nullptr) {
679
    SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
680
    return 0;
681
  }
682
683
348
  X509* extra = nullptr;
684
348
  int ret = 0;
685
348
  unsigned long err = 0;  // NOLINT(runtime/int)
686
687
  // Read extra certs
688
348
  STACK_OF(X509)* extra_certs = sk_X509_new_null();
689
348
  if (extra_certs == nullptr) {
690
    SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_MALLOC_FAILURE);
691
    goto done;
692
  }
693
694
700
  while ((extra = PEM_read_bio_X509(in,
695
                                    nullptr,
696
                                    NoPasswordCallback,
697
                                    nullptr))) {
698
4
    if (sk_X509_push(extra_certs, extra))
699
4
      continue;
700
701
    // Failure, free all certs
702
    goto done;
703
  }
704
348
  extra = nullptr;
705
706
  // When the while loop ends, it's usually just EOF.
707
348
  err = ERR_peek_last_error();
708

696
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
709
348
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
710
348
    ERR_clear_error();
711
  } else  {
712
    // some real error
713
    goto done;
714
  }
715
716
348
  ret = SSL_CTX_use_certificate_chain(ctx, x, extra_certs, cert, issuer);
717
348
  if (!ret)
718
    goto done;
719
720
 done:
721
348
  if (extra_certs != nullptr)
722
348
    sk_X509_pop_free(extra_certs, X509_free);
723
348
  if (extra != nullptr)
724
    X509_free(extra);
725
348
  if (x != nullptr)
726
348
    X509_free(x);
727
728
348
  return ret;
729
}
730
731
732
348
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
733
348
  Environment* env = Environment::GetCurrent(args);
734
735
  SecureContext* sc;
736
348
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
737
738
348
  if (args.Length() != 1) {
739
    return env->ThrowTypeError("Certificate argument is mandatory");
740
  }
741
742
348
  BIO* bio = LoadBIO(env, args[0]);
743
348
  if (!bio)
744
    return;
745
746
  // Free previous certs
747
348
  if (sc->issuer_ != nullptr) {
748
    X509_free(sc->issuer_);
749
    sc->issuer_ = nullptr;
750
  }
751
348
  if (sc->cert_ != nullptr) {
752
15
    X509_free(sc->cert_);
753
15
    sc->cert_ = nullptr;
754
  }
755
756
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_,
757
                                         bio,
758
                                         &sc->cert_,
759
348
                                         &sc->issuer_);
760
761
348
  BIO_free_all(bio);
762
763
348
  if (!rv) {
764
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
765
    if (!err) {
766
      return env->ThrowError("SSL_CTX_use_certificate_chain");
767
    }
768
    return ThrowCryptoError(env, err);
769
  }
770
}
771
772
773
#if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(OPENSSL_IS_BORINGSSL)
774
// This section contains OpenSSL 1.1.0 functions reimplemented for OpenSSL
775
// 1.0.2 so that the following code can be written without lots of #if lines.
776
777
670
static int X509_STORE_up_ref(X509_STORE* store) {
778
670
  CRYPTO_add(&store->references, 1, CRYPTO_LOCK_X509_STORE);
779
670
  return 1;
780
}
781
782
29140
static int X509_up_ref(X509* cert) {
783
29140
  CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
784
29140
  return 1;
785
}
786
#endif  // OPENSSL_VERSION_NUMBER < 0x10100000L && !OPENSSL_IS_BORINGSSL
787
788
789
188
static X509_STORE* NewRootCertStore() {
790

188
  static std::vector<X509*> root_certs_vector;
791
188
  if (root_certs_vector.empty()) {
792
27924
    for (size_t i = 0; i < arraysize(root_certs); i++) {
793
27745
      BIO* bp = NodeBIO::NewFixed(root_certs[i], strlen(root_certs[i]));
794
27745
      X509 *x509 = PEM_read_bio_X509(bp, nullptr, NoPasswordCallback, nullptr);
795
27745
      BIO_free(bp);
796
797
      // Parse errors from the built-in roots are fatal.
798
27745
      CHECK_NE(x509, nullptr);
799
800
27745
      root_certs_vector.push_back(x509);
801
    }
802
  }
803
804
188
  X509_STORE* store = X509_STORE_new();
805
188
  if (ssl_openssl_cert_store) {
806
    X509_STORE_set_default_paths(store);
807
  } else {
808
29328
    for (X509 *cert : root_certs_vector) {
809
29140
      X509_up_ref(cert);
810
29140
      X509_STORE_add_cert(store, cert);
811
    }
812
  }
813
814
188
  return store;
815
}
816
817
818
129
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
819
129
  Environment* env = Environment::GetCurrent(args);
820
821
  SecureContext* sc;
822
129
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
823
  ClearErrorOnReturn clear_error_on_return;
824
825
129
  if (args.Length() != 1) {
826
    return env->ThrowTypeError("CA certificate argument is mandatory");
827
  }
828
829
129
  BIO* bio = LoadBIO(env, args[0]);
830
129
  if (!bio) {
831
    return;
832
  }
833
834
129
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
835
  while (X509* x509 =
836
261
             PEM_read_bio_X509(bio, nullptr, NoPasswordCallback, nullptr)) {
837
132
    if (cert_store == root_cert_store) {
838
1
      cert_store = NewRootCertStore();
839
1
      SSL_CTX_set_cert_store(sc->ctx_, cert_store);
840
    }
841
132
    X509_STORE_add_cert(cert_store, x509);
842
132
    SSL_CTX_add_client_CA(sc->ctx_, x509);
843
132
    X509_free(x509);
844
  }
845
846
129
  BIO_free_all(bio);
847
}
848
849
850
7
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
851
7
  Environment* env = Environment::GetCurrent(args);
852
853
  SecureContext* sc;
854
8
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
855
856
7
  if (args.Length() != 1) {
857
    return env->ThrowTypeError("CRL argument is mandatory");
858
  }
859
860
  ClearErrorOnReturn clear_error_on_return;
861
862
7
  BIO *bio = LoadBIO(env, args[0]);
863
7
  if (!bio)
864
    return;
865
866
  X509_CRL* crl =
867
7
      PEM_read_bio_X509_CRL(bio, nullptr, NoPasswordCallback, nullptr);
868
869
7
  if (crl == nullptr) {
870
1
    BIO_free_all(bio);
871
1
    return env->ThrowError("Failed to parse CRL");
872
  }
873
874
6
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
875
6
  if (cert_store == root_cert_store) {
876
5
    cert_store = NewRootCertStore();
877
5
    SSL_CTX_set_cert_store(sc->ctx_, cert_store);
878
  }
879
880
6
  X509_STORE_add_crl(cert_store, crl);
881
  X509_STORE_set_flags(cert_store,
882
6
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
883
884
6
  BIO_free_all(bio);
885
6
  X509_CRL_free(crl);
886
}
887
888
889
2
void UseExtraCaCerts(const std::string& file) {
890
2
  extra_root_certs_file = file;
891
2
}
892
893
894
2
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
895
    X509_STORE* store,
896
    const char* file) {
897
2
  ERR_clear_error();
898
2
  MarkPopErrorOnReturn mark_pop_error_on_return;
899
900
2
  BIO* bio = BIO_new_file(file, "r");
901
2
  if (!bio) {
902
1
    return ERR_get_error();
903
  }
904
905
  while (X509* x509 =
906
2
      PEM_read_bio_X509(bio, nullptr, NoPasswordCallback, nullptr)) {
907
1
    X509_STORE_add_cert(store, x509);
908
1
    X509_free(x509);
909
  }
910
1
  BIO_free_all(bio);
911
912
1
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
913
  // Ignore error if its EOF/no start line found.
914

2
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
915
1
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
916
1
    return 0;
917
  }
918
919
  return err;
920
}
921
922
670
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
923
  SecureContext* sc;
924
1340
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
925
  ClearErrorOnReturn clear_error_on_return;
926
927
670
  if (!root_cert_store) {
928
179
    root_cert_store = NewRootCertStore();
929
930
179
    if (!extra_root_certs_file.empty()) {
931
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
932
                                           root_cert_store,
933
2
                                           extra_root_certs_file.c_str());
934
2
      if (err) {
935
        ProcessEmitWarning(sc->env(),
936
                           "Ignoring extra certs from `%s`, load failed: %s\n",
937
                           extra_root_certs_file.c_str(),
938
1
                           ERR_error_string(err, nullptr));
939
      }
940
    }
941
  }
942
943
  // Increment reference count so global store is not deleted along with CTX.
944
670
  X509_STORE_up_ref(root_cert_store);
945
670
  SSL_CTX_set_cert_store(sc->ctx_, root_cert_store);
946
}
947
948
949
723
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
950
  SecureContext* sc;
951
725
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
952
723
  Environment* env = sc->env();
953
  ClearErrorOnReturn clear_error_on_return;
954
955
723
  if (args.Length() != 1) {
956
    return env->ThrowTypeError("Ciphers argument is mandatory");
957
  }
958
959
2169
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Ciphers");
960
961
1442
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
962
1442
  SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
963
}
964
965
966
719
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
967
  SecureContext* sc;
968
724
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
969
719
  Environment* env = sc->env();
970
971
719
  if (args.Length() != 1)
972
    return env->ThrowTypeError("ECDH curve name argument is mandatory");
973
974
2157
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "ECDH curve name");
975
976
718
  node::Utf8Value curve(env->isolate(), args[0]);
977
978
718
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_ECDH_USE);
979
718
  SSL_CTX_set_ecdh_auto(sc->ctx_, 1);
980
981
718
  if (strcmp(*curve, "auto") == 0)
982
1
    return;
983
984
717
  if (!SSL_CTX_set1_curves_list(sc->ctx_, *curve))
985
3
    return env->ThrowError("Failed to set ECDH curve");
986
}
987
988
989
9
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
990
  SecureContext* sc;
991
12
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
992
9
  Environment* env = sc->env();
993
  ClearErrorOnReturn clear_error_on_return;
994
995
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
996
  // to be specified explicitly
997
9
  if (args.Length() != 1)
998
    return env->ThrowTypeError("DH argument is mandatory");
999
1000
  // Invalid dhparam is silently discarded and DHE is no longer used.
1001
9
  BIO* bio = LoadBIO(env, args[0]);
1002
9
  if (!bio)
1003
    return;
1004
1005
9
  DH* dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
1006
9
  BIO_free_all(bio);
1007
1008
9
  if (dh == nullptr)
1009
1
    return;
1010
1011
8
  const int size = BN_num_bits(dh->p);
1012
8
  if (size < 1024) {
1013
2
    return env->ThrowError("DH parameter is less than 1024 bits");
1014
6
  } else if (size < 2048) {
1015
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1016
9
        env->isolate(), "DH parameter is less than 2048 bits"));
1017
  }
1018
1019
6
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE);
1020
6
  int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh);
1021
6
  DH_free(dh);
1022
1023
6
  if (!r)
1024
    return env->ThrowTypeError("Error setting temp DH parameter");
1025
}
1026
1027
1028
352
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1029
  SecureContext* sc;
1030
352
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1031
1032


1408
  if (args.Length() != 1 || !args[0]->IntegerValue()) {
1033
    return sc->env()->ThrowTypeError("Options must be an integer value");
1034
  }
1035
1036
1056
  SSL_CTX_set_options(
1037
      sc->ctx_,
1038
352
      static_cast<long>(args[0]->IntegerValue()));  // NOLINT(runtime/int)
1039
}
1040
1041
1042
281
void SecureContext::SetSessionIdContext(
1043
    const FunctionCallbackInfo<Value>& args) {
1044
  SecureContext* sc;
1045
562
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1046
281
  Environment* env = sc->env();
1047
1048
281
  if (args.Length() != 1) {
1049
    return env->ThrowTypeError("Session ID context argument is mandatory");
1050
  }
1051
1052
843
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Session ID context");
1053
1054
281
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1055
  const unsigned char* sid_ctx =
1056
281
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1057
281
  unsigned int sid_ctx_len = sessionIdContext.length();
1058
1059
281
  int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
1060
281
  if (r == 1)
1061
281
    return;
1062
1063
  BIO* bio;
1064
  BUF_MEM* mem;
1065
  Local<String> message;
1066
1067
  bio = BIO_new(BIO_s_mem());
1068
  if (bio == nullptr) {
1069
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1070
                                    "SSL_CTX_set_session_id_context error");
1071
  } else {
1072
    ERR_print_errors(bio);
1073
    BIO_get_mem_ptr(bio, &mem);
1074
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1075
    BIO_free_all(bio);
1076
  }
1077
1078
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1079
}
1080
1081
1082
1
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1083
  SecureContext* sc;
1084
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1085
1086


4
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1087
    return sc->env()->ThrowTypeError(
1088
1
        "Session timeout must be a 32-bit integer");
1089
  }
1090
1091
  int32_t sessionTimeout = args[0]->Int32Value();
1092
  SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
1093
}
1094
1095
1096
342
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1097
  SecureContext* sc;
1098
684
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1099
342
  sc->FreeCTXMem();
1100
}
1101
1102
1103
// Takes .pfx or .p12 and password in string or buffer format
1104
15
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1105
15
  Environment* env = Environment::GetCurrent(args);
1106
1107
15
  BIO* in = nullptr;
1108
15
  PKCS12* p12 = nullptr;
1109
15
  EVP_PKEY* pkey = nullptr;
1110
15
  X509* cert = nullptr;
1111
15
  STACK_OF(X509)* extra_certs = nullptr;
1112
15
  char* pass = nullptr;
1113
15
  bool ret = false;
1114
1115
  SecureContext* sc;
1116
21
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1117
  ClearErrorOnReturn clear_error_on_return;
1118
1119
15
  if (args.Length() < 1) {
1120
    return env->ThrowTypeError("PFX certificate argument is mandatory");
1121
  }
1122
1123
15
  in = LoadBIO(env, args[0]);
1124
15
  if (in == nullptr) {
1125
    return env->ThrowError("Unable to load BIO");
1126
  }
1127
1128
15
  if (args.Length() >= 2) {
1129
12
    THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Pass phrase");
1130
12
    size_t passlen = Buffer::Length(args[1]);
1131
12
    pass = new char[passlen + 1];
1132
12
    memcpy(pass, Buffer::Data(args[1]), passlen);
1133
12
    pass[passlen] = '\0';
1134
  }
1135
1136
  // Free previous certs
1137
15
  if (sc->issuer_ != nullptr) {
1138
1
    X509_free(sc->issuer_);
1139
1
    sc->issuer_ = nullptr;
1140
  }
1141
15
  if (sc->cert_ != nullptr) {
1142
1
    X509_free(sc->cert_);
1143
1
    sc->cert_ = nullptr;
1144
  }
1145
1146
15
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
1147
1148

43
  if (d2i_PKCS12_bio(in, &p12) &&
1149
22
      PKCS12_parse(p12, pass, &pkey, &cert, &extra_certs) &&
1150
      SSL_CTX_use_certificate_chain(sc->ctx_,
1151
                                    cert,
1152
                                    extra_certs,
1153
                                    &sc->cert_,
1154

33
                                    &sc->issuer_) &&
1155
9
      SSL_CTX_use_PrivateKey(sc->ctx_, pkey)) {
1156
    // Add CA certs too
1157
13
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
1158
4
      X509* ca = sk_X509_value(extra_certs, i);
1159
1160
4
      if (cert_store == root_cert_store) {
1161
3
        cert_store = NewRootCertStore();
1162
3
        SSL_CTX_set_cert_store(sc->ctx_, cert_store);
1163
      }
1164
4
      X509_STORE_add_cert(cert_store, ca);
1165
4
      SSL_CTX_add_client_CA(sc->ctx_, ca);
1166
    }
1167
9
    ret = true;
1168
  }
1169
1170
15
  if (pkey != nullptr)
1171
9
    EVP_PKEY_free(pkey);
1172
15
  if (cert != nullptr)
1173
9
    X509_free(cert);
1174
15
  if (extra_certs != nullptr)
1175
4
    sk_X509_pop_free(extra_certs, X509_free);
1176
1177
15
  PKCS12_free(p12);
1178
15
  BIO_free_all(in);
1179
15
  delete[] pass;
1180
1181
15
  if (!ret) {
1182
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1183
6
    const char* str = ERR_reason_error_string(err);
1184
6
    return env->ThrowError(str);
1185
9
  }
1186
}
1187
1188
1189
7
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1190
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1191
1192
  SecureContext* wrap;
1193
7
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1194
1195
14
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1196
7
  if (SSL_CTX_get_tlsext_ticket_keys(wrap->ctx_,
1197
                                     Buffer::Data(buff),
1198
                                     Buffer::Length(buff)) != 1) {
1199
    return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
1200
  }
1201
1202
14
  args.GetReturnValue().Set(buff);
1203
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1204
}
1205
1206
1207
16
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1208
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1209
  SecureContext* wrap;
1210
18
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1211
16
  Environment* env = wrap->env();
1212
1213
16
  if (args.Length() < 1) {
1214
    return env->ThrowTypeError("Ticket keys argument is mandatory");
1215
  }
1216
1217
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Ticket keys");
1218
1219
15
  if (Buffer::Length(args[0]) != 48) {
1220
1
    return env->ThrowTypeError("Ticket keys length must be 48 bytes");
1221
  }
1222
1223
28
  if (SSL_CTX_set_tlsext_ticket_keys(wrap->ctx_,
1224
                                     Buffer::Data(args[0]),
1225
                                     Buffer::Length(args[0])) != 1) {
1226
    return env->ThrowError("Failed to fetch tls ticket keys");
1227
  }
1228
1229
28
  args.GetReturnValue().Set(true);
1230
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1231
}
1232
1233
1234
352
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1235
#if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(OPENSSL_IS_BORINGSSL)
1236
  // |freelist_max_len| was removed in OpenSSL 1.1.0. In that version OpenSSL
1237
  // mallocs and frees buffers directly, without the use of a freelist.
1238
  SecureContext* wrap;
1239
704
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1240
1241
1056
  wrap->ctx_->freelist_max_len = args[0]->Int32Value();
1242
#endif
1243
}
1244
1245
1246
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1247
// the regression test in test/parallel/test-https-resume-after-renew.js.
1248
1
void SecureContext::EnableTicketKeyCallback(
1249
    const FunctionCallbackInfo<Value>& args) {
1250
  SecureContext* wrap;
1251
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1252
1253
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_, TicketKeyCallback);
1254
}
1255
1256
1257
3
int SecureContext::TicketKeyCallback(SSL* ssl,
1258
                                     unsigned char* name,
1259
                                     unsigned char* iv,
1260
                                     EVP_CIPHER_CTX* ectx,
1261
                                     HMAC_CTX* hctx,
1262
                                     int enc) {
1263
  static const int kTicketPartSize = 16;
1264
1265
  SecureContext* sc = static_cast<SecureContext*>(
1266
3
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1267
1268
3
  Environment* env = sc->env();
1269
3
  HandleScope handle_scope(env->isolate());
1270
3
  Context::Scope context_scope(env->context());
1271
1272
  Local<Value> argv[] = {
1273
    Buffer::Copy(env,
1274
                 reinterpret_cast<char*>(name),
1275
                 kTicketPartSize).ToLocalChecked(),
1276
    Buffer::Copy(env,
1277
                 reinterpret_cast<char*>(iv),
1278
                 kTicketPartSize).ToLocalChecked(),
1279
    Boolean::New(env->isolate(), enc != 0)
1280
12
  };
1281
1282
  Local<Value> ret = node::MakeCallback(env->isolate(),
1283
                                        sc->object(),
1284
                                        env->ticketkeycallback_string(),
1285
3
                                        arraysize(argv),
1286
                                        argv,
1287
9
                                        {0, 0}).ToLocalChecked();
1288
3
  Local<Array> arr = ret.As<Array>();
1289
1290
6
  int r = arr->Get(kTicketKeyReturnIndex)->Int32Value();
1291
3
  if (r < 0)
1292
    return r;
1293
1294
3
  Local<Value> hmac = arr->Get(kTicketKeyHMACIndex);
1295
3
  Local<Value> aes = arr->Get(kTicketKeyAESIndex);
1296
3
  if (Buffer::Length(aes) != kTicketPartSize)
1297
    return -1;
1298
1299
3
  if (enc) {
1300
2
    Local<Value> name_val = arr->Get(kTicketKeyNameIndex);
1301
2
    Local<Value> iv_val = arr->Get(kTicketKeyIVIndex);
1302
1303

4
    if (Buffer::Length(name_val) != kTicketPartSize ||
1304
2
        Buffer::Length(iv_val) != kTicketPartSize) {
1305
      return -1;
1306
    }
1307
1308
2
    memcpy(name, Buffer::Data(name_val), kTicketPartSize);
1309
2
    memcpy(iv, Buffer::Data(iv_val), kTicketPartSize);
1310
  }
1311
1312
  HMAC_Init_ex(hctx,
1313
3
               Buffer::Data(hmac),
1314
3
               Buffer::Length(hmac),
1315
               EVP_sha256(),
1316
9
               nullptr);
1317
1318
  const unsigned char* aes_key =
1319
3
      reinterpret_cast<unsigned char*>(Buffer::Data(aes));
1320
3
  if (enc) {
1321
    EVP_EncryptInit_ex(ectx,
1322
                       EVP_aes_128_cbc(),
1323
                       nullptr,
1324
                       aes_key,
1325
2
                       iv);
1326
  } else {
1327
    EVP_DecryptInit_ex(ectx,
1328
                       EVP_aes_128_cbc(),
1329
                       nullptr,
1330
                       aes_key,
1331
1
                       iv);
1332
  }
1333
1334
6
  return r;
1335
}
1336
1337
1338
1339
1340
2
void SecureContext::CtxGetter(Local<String> property,
1341
                              const PropertyCallbackInfo<Value>& info) {
1342
  SecureContext* sc;
1343
4
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1344
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_);
1345
4
  info.GetReturnValue().Set(ext);
1346
}
1347
1348
1349
template <bool primary>
1350
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1351
  SecureContext* wrap;
1352

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1353
6
  Environment* env = wrap->env();
1354
  X509* cert;
1355
1356
  if (primary)
1357
3
    cert = wrap->cert_;
1358
  else
1359
3
    cert = wrap->issuer_;
1360

6
  if (cert == nullptr)
1361
    return args.GetReturnValue().Set(Null(env->isolate()));
1362
1363
6
  int size = i2d_X509(cert, nullptr);
1364
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1365
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1366
6
      Buffer::Data(buff));
1367
6
  i2d_X509(cert, &serialized);
1368
1369
12
  args.GetReturnValue().Set(buff);
1370
}
1371
1372
1373
template <class Base>
1374
734
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1375
734
  HandleScope scope(env->isolate());
1376
1377
734
  env->SetProtoMethod(t, "getPeerCertificate", GetPeerCertificate);
1378
734
  env->SetProtoMethod(t, "getSession", GetSession);
1379
734
  env->SetProtoMethod(t, "setSession", SetSession);
1380
734
  env->SetProtoMethod(t, "loadSession", LoadSession);
1381
734
  env->SetProtoMethod(t, "isSessionReused", IsSessionReused);
1382
734
  env->SetProtoMethod(t, "isInitFinished", IsInitFinished);
1383
734
  env->SetProtoMethod(t, "verifyError", VerifyError);
1384
734
  env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
1385
734
  env->SetProtoMethod(t, "endParser", EndParser);
1386
734
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1387
734
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1388
734
  env->SetProtoMethod(t, "shutdownSSL", Shutdown);
1389
734
  env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket);
1390
734
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1391
734
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1392
734
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1393
734
  env->SetProtoMethod(t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
1394
734
  env->SetProtoMethod(t, "getProtocol", GetProtocol);
1395
1396
#ifdef SSL_set_max_send_fragment
1397
734
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1398
#endif  // SSL_set_max_send_fragment
1399
1400
#ifndef OPENSSL_NO_NEXTPROTONEG
1401
734
  env->SetProtoMethod(t, "getNegotiatedProtocol", GetNegotiatedProto);
1402
#endif  // OPENSSL_NO_NEXTPROTONEG
1403
1404
#ifndef OPENSSL_NO_NEXTPROTONEG
1405
734
  env->SetProtoMethod(t, "setNPNProtocols", SetNPNProtocols);
1406
#endif
1407
1408
734
  env->SetProtoMethod(t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
1409
734
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1410
1411
2936
  t->PrototypeTemplate()->SetAccessor(
1412
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
1413
      SSLGetter,
1414
      nullptr,
1415
      env->as_external(),
1416
      DEFAULT,
1417
      static_cast<PropertyAttribute>(ReadOnly | DontDelete),
1418
734
      AccessorSignature::New(env->isolate(), t));
1419
734
}
1420
1421
1422
template <class Base>
1423
10800
void SSLWrap<Base>::InitNPN(SecureContext* sc) {
1424
#ifndef OPENSSL_NO_NEXTPROTONEG
1425
  // Server should advertise NPN protocols
1426
10800
  SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
1427
                                        AdvertiseNextProtoCallback,
1428
10800
                                        nullptr);
1429
  // Client should select protocol from list of advertised
1430
  // If server supports NPN
1431
10800
  SSL_CTX_set_next_proto_select_cb(sc->ctx_, SelectNextProtoCallback, nullptr);
1432
#endif  // OPENSSL_NO_NEXTPROTONEG
1433
1434
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1435
  // OCSP stapling
1436
10800
  SSL_CTX_set_tlsext_status_cb(sc->ctx_, TLSExtStatusCallback);
1437
10800
  SSL_CTX_set_tlsext_status_arg(sc->ctx_, nullptr);
1438
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1439
10800
}
1440
1441
1442
template <class Base>
1443
11
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1444
                                               unsigned char* key,
1445
                                               int len,
1446
                                               int* copy) {
1447
11
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1448
1449
11
  *copy = 0;
1450
11
  SSL_SESSION* sess = w->next_sess_;
1451
11
  w->next_sess_ = nullptr;
1452
1453
11
  return sess;
1454
}
1455
1456
1457
template <class Base>
1458
11
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1459
11
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1460
11
  Environment* env = w->ssl_env();
1461
11
  HandleScope handle_scope(env->isolate());
1462
11
  Context::Scope context_scope(env->context());
1463
1464

11
  if (!w->session_callbacks_)
1465
3
    return 0;
1466
1467
  // Check if session is small enough to be stored
1468
8
  int size = i2d_SSL_SESSION(sess, nullptr);
1469

8
  if (size > SecureContext::kMaxSessionSize)
1470
    return 0;
1471
1472
  // Serialize session
1473
16
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1474
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1475
8
      Buffer::Data(buff));
1476
8
  memset(serialized, 0, size);
1477
8
  i2d_SSL_SESSION(sess, &serialized);
1478
1479
  unsigned int session_id_length;
1480
  const unsigned char* session_id = SSL_SESSION_get_id(sess,
1481
8
                                                       &session_id_length);
1482
  Local<Object> session = Buffer::Copy(
1483
      env,
1484
      reinterpret_cast<const char*>(session_id),
1485
16
      session_id_length).ToLocalChecked();
1486
24
  Local<Value> argv[] = { session, buff };
1487
8
  w->new_session_wait_ = true;
1488
8
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1489
1490
19
  return 0;
1491
}
1492
1493
1494
template <class Base>
1495
23
void SSLWrap<Base>::OnClientHello(void* arg,
1496
                                  const ClientHelloParser::ClientHello& hello) {
1497
23
  Base* w = static_cast<Base*>(arg);
1498
23
  Environment* env = w->ssl_env();
1499
23
  HandleScope handle_scope(env->isolate());
1500
23
  Context::Scope context_scope(env->context());
1501
1502
23
  Local<Object> hello_obj = Object::New(env->isolate());
1503
  Local<Object> buff = Buffer::Copy(
1504
      env,
1505
23
      reinterpret_cast<const char*>(hello.session_id()),
1506
69
      hello.session_size()).ToLocalChecked();
1507
46
  hello_obj->Set(env->session_id_string(), buff);
1508

23
  if (hello.servername() == nullptr) {
1509
9
    hello_obj->Set(env->servername_string(), String::Empty(env->isolate()));
1510
  } else {
1511
    Local<String> servername = OneByteString(env->isolate(),
1512
                                             hello.servername(),
1513
20
                                             hello.servername_size());
1514
40
    hello_obj->Set(env->servername_string(), servername);
1515
  }
1516
23
  hello_obj->Set(env->tls_ticket_string(),
1517
92
                 Boolean::New(env->isolate(), hello.has_ticket()));
1518
23
  hello_obj->Set(env->ocsp_request_string(),
1519
92
                 Boolean::New(env->isolate(), hello.ocsp_request()));
1520
1521
46
  Local<Value> argv[] = { hello_obj };
1522
46
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1523
23
}
1524
1525
1526
35
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1527
35
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1528
1529
35
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1530
31
    return false;
1531
1532
4
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
1533
4
  if (names == NULL)
1534
    return false;
1535
1536
16
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1537
12
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1538
1539
12
    if (i != 0)
1540
8
      BIO_write(out, ", ", 2);
1541
1542
12
    if (gen->type == GEN_DNS) {
1543
9
      ASN1_IA5STRING* name = gen->d.dNSName;
1544
1545
9
      BIO_write(out, "DNS:", 4);
1546
9
      BIO_write(out, name->data, name->length);
1547
    } else {
1548
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1549
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, NULL);
1550
3
      if (nval == NULL)
1551
        return false;
1552
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1553
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1554
    }
1555
  }
1556
4
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1557
1558
4
  return true;
1559
}
1560
1561
1562
71
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1563
71
  EscapableHandleScope scope(env->isolate());
1564
1565
71
  Local<Object> info = Object::New(env->isolate());
1566
1567
71
  BIO* bio = BIO_new(BIO_s_mem());
1568
  BUF_MEM* mem;
1569
71
  if (X509_NAME_print_ex(bio,
1570
                         X509_get_subject_name(cert),
1571
                         0,
1572
71
                         X509_NAME_FLAGS) > 0) {
1573
71
    BIO_get_mem_ptr(bio, &mem);
1574
    info->Set(env->subject_string(),
1575
              String::NewFromUtf8(env->isolate(), mem->data,
1576
213
                                  String::kNormalString, mem->length));
1577
  }
1578
71
  (void) BIO_reset(bio);
1579
1580
71
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1581
71
  if (X509_NAME_print_ex(bio, issuer_name, 0, X509_NAME_FLAGS) > 0) {
1582
71
    BIO_get_mem_ptr(bio, &mem);
1583
    info->Set(env->issuer_string(),
1584
              String::NewFromUtf8(env->isolate(), mem->data,
1585
213
                                  String::kNormalString, mem->length));
1586
  }
1587
71
  (void) BIO_reset(bio);
1588
1589
71
  int nids[] = { NID_subject_alt_name, NID_info_access };
1590
  Local<String> keys[] = { env->subjectaltname_string(),
1591
71
                           env->infoaccess_string() };
1592
71
  CHECK_EQ(arraysize(nids), arraysize(keys));
1593
213
  for (size_t i = 0; i < arraysize(nids); i++) {
1594
142
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1595
142
    if (index < 0)
1596
107
      continue;
1597
1598
    X509_EXTENSION* ext;
1599
    int rv;
1600
1601
35
    ext = X509_get_ext(cert, index);
1602
35
    CHECK_NE(ext, nullptr);
1603
1604
35
    if (!SafeX509ExtPrint(bio, ext)) {
1605
31
      rv = X509V3_EXT_print(bio, ext, 0, 0);
1606
31
      CHECK_EQ(rv, 1);
1607
    }
1608
1609
35
    BIO_get_mem_ptr(bio, &mem);
1610
    info->Set(keys[i],
1611
              String::NewFromUtf8(env->isolate(), mem->data,
1612
70
                                  String::kNormalString, mem->length));
1613
1614
35
    (void) BIO_reset(bio);
1615
  }
1616
1617
71
  EVP_PKEY* pkey = X509_get_pubkey(cert);
1618
71
  RSA* rsa = nullptr;
1619
71
  if (pkey != nullptr)
1620
71
    rsa = EVP_PKEY_get1_RSA(pkey);
1621
1622
71
  if (rsa != nullptr) {
1623
70
    BN_print(bio, rsa->n);
1624
70
    BIO_get_mem_ptr(bio, &mem);
1625
    info->Set(env->modulus_string(),
1626
              String::NewFromUtf8(env->isolate(), mem->data,
1627
210
                                  String::kNormalString, mem->length));
1628
70
    (void) BIO_reset(bio);
1629
1630
70
    uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(rsa->e));
1631
70
    uint32_t lo = static_cast<uint32_t>(exponent_word);
1632
70
    uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
1633
70
    if (hi == 0) {
1634
70
      BIO_printf(bio, "0x%x", lo);
1635
    } else {
1636
      BIO_printf(bio, "0x%x%08x", hi, lo);
1637
    }
1638
70
    BIO_get_mem_ptr(bio, &mem);
1639
    info->Set(env->exponent_string(),
1640
              String::NewFromUtf8(env->isolate(), mem->data,
1641
210
                                  String::kNormalString, mem->length));
1642
70
    (void) BIO_reset(bio);
1643
  }
1644
1645
71
  if (pkey != nullptr) {
1646
71
    EVP_PKEY_free(pkey);
1647
71
    pkey = nullptr;
1648
  }
1649
71
  if (rsa != nullptr) {
1650
70
    RSA_free(rsa);
1651
70
    rsa = nullptr;
1652
  }
1653
1654
71
  ASN1_TIME_print(bio, X509_get_notBefore(cert));
1655
71
  BIO_get_mem_ptr(bio, &mem);
1656
  info->Set(env->valid_from_string(),
1657
            String::NewFromUtf8(env->isolate(), mem->data,
1658
213
                                String::kNormalString, mem->length));
1659
71
  (void) BIO_reset(bio);
1660
1661
71
  ASN1_TIME_print(bio, X509_get_notAfter(cert));
1662
71
  BIO_get_mem_ptr(bio, &mem);
1663
  info->Set(env->valid_to_string(),
1664
            String::NewFromUtf8(env->isolate(), mem->data,
1665
213
                                String::kNormalString, mem->length));
1666
71
  BIO_free_all(bio);
1667
1668
  unsigned int md_size, i;
1669
  unsigned char md[EVP_MAX_MD_SIZE];
1670
71
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1671
71
    const char hex[] = "0123456789ABCDEF";
1672
    char fingerprint[EVP_MAX_MD_SIZE * 3];
1673
1674
1491
    for (i = 0; i < md_size; i++) {
1675
1420
      fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1676
1420
      fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1677
1420
      fingerprint[(3*i)+2] = ':';
1678
    }
1679
1680
71
    if (md_size > 0) {
1681
71
      fingerprint[(3*(md_size-1))+2] = '\0';
1682
    } else {
1683
      fingerprint[0] = '\0';
1684
    }
1685
1686
    info->Set(env->fingerprint_string(),
1687
213
              OneByteString(env->isolate(), fingerprint));
1688
  }
1689
1690
  STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
1691
71
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr));
1692
71
  if (eku != nullptr) {
1693
3
    Local<Array> ext_key_usage = Array::New(env->isolate());
1694
    char buf[256];
1695
1696
3
    int j = 0;
1697
8
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1698
5
      if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku, i), 1) >= 0)
1699
15
        ext_key_usage->Set(j++, OneByteString(env->isolate(), buf));
1700
    }
1701
1702
3
    sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1703
6
    info->Set(env->ext_key_usage_string(), ext_key_usage);
1704
  }
1705
1706
71
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1707
71
    if (BIGNUM* bn = ASN1_INTEGER_to_BN(serial_number, nullptr)) {
1708
71
      if (char* buf = BN_bn2hex(bn)) {
1709
        info->Set(env->serial_number_string(),
1710
213
                  OneByteString(env->isolate(), buf));
1711
71
        OPENSSL_free(buf);
1712
      }
1713
71
      BN_free(bn);
1714
    }
1715
  }
1716
1717
  // Raw DER certificate
1718
71
  int size = i2d_X509(cert, nullptr);
1719
142
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1720
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1721
71
      Buffer::Data(buff));
1722
71
  i2d_X509(cert, &serialized);
1723
142
  info->Set(env->raw_string(), buff);
1724
1725
71
  return scope.Escape(info);
1726
}
1727
1728
1729
// TODO(indutny): Split it into multiple smaller functions
1730
template <class Base>
1731
69
void SSLWrap<Base>::GetPeerCertificate(
1732
    const FunctionCallbackInfo<Value>& args) {
1733
  Base* w;
1734

138
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1735
69
  Environment* env = w->ssl_env();
1736
1737
  ClearErrorOnReturn clear_error_on_return;
1738
1739
  Local<Object> result;
1740
  Local<Object> info;
1741
1742
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1743
  // contains the `peer_certificate`, but on server it doesn't
1744

69
  X509* cert = w->is_server() ? SSL_get_peer_certificate(w->ssl_) : nullptr;
1745
69
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_);
1746
69
  STACK_OF(X509)* peer_certs = nullptr;
1747


69
  if (cert == nullptr && ssl_certs == nullptr)
1748
3
    goto done;
1749
1750



66
  if (cert == nullptr && sk_X509_num(ssl_certs) == 0)
1751
    goto done;
1752
1753
  // Short result requested
1754




264
  if (args.Length() < 1 || !args[0]->IsTrue()) {
1755
63
    result = X509ToObject(env,
1756

63
                          cert == nullptr ? sk_X509_value(ssl_certs, 0) : cert);
1757
63
    goto done;
1758
  }
1759
1760
  // Clone `ssl_certs`, because we are going to destruct it
1761
3
  peer_certs = sk_X509_new(nullptr);
1762

3
  if (cert != nullptr)
1763
    sk_X509_push(peer_certs, cert);
1764

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

6
    if (cert == nullptr)
1767
      goto done;
1768

6
    if (!sk_X509_push(peer_certs, cert))
1769
      goto done;
1770
  }
1771
1772
  // First and main certificate
1773
3
  cert = sk_X509_value(peer_certs, 0);
1774
3
  result = X509ToObject(env, cert);
1775
3
  info = result;
1776
1777
  // Put issuer inside the object
1778
3
  cert = sk_X509_delete(peer_certs, 0);
1779

3
  while (sk_X509_num(peer_certs) > 0) {
1780
    int i;
1781

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

3
      if (X509_check_issued(ca, cert) != X509_V_OK)
1784
        continue;
1785
1786
3
      Local<Object> ca_info = X509ToObject(env, ca);
1787
6
      info->Set(env->issuercert_string(), ca_info);
1788
3
      info = ca_info;
1789
1790
      // NOTE: Intentionally freeing cert that is not used anymore
1791
3
      X509_free(cert);
1792
1793
      // Delete cert and continue aggregating issuers
1794
3
      cert = sk_X509_delete(peer_certs, i);
1795
3
      break;
1796
    }
1797
1798
    // Issuer not found, break out of the loop
1799

3
    if (i == sk_X509_num(peer_certs))
1800
3
      break;
1801
  }
1802
1803
  // Last certificate should be self-signed
1804

8
  while (X509_check_issued(cert, cert) != X509_V_OK) {
1805
    X509* ca;
1806

2
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(w->ssl_), cert, &ca) <= 0)
1807
      break;
1808
1809
2
    Local<Object> ca_info = X509ToObject(env, ca);
1810
4
    info->Set(env->issuercert_string(), ca_info);
1811
2
    info = ca_info;
1812
1813
    // NOTE: Intentionally freeing cert that is not used anymore
1814
2
    X509_free(cert);
1815
1816
    // Delete cert and continue aggregating issuers
1817
2
    cert = ca;
1818
  }
1819
1820
  // Self-issued certificate
1821

3
  if (X509_check_issued(cert, cert) == X509_V_OK)
1822
6
    info->Set(env->issuercert_string(), info);
1823
1824

3
  CHECK_NE(cert, nullptr);
1825
1826
 done:
1827

69
  if (cert != nullptr)
1828
10
    X509_free(cert);
1829

69
  if (peer_certs != nullptr)
1830
3
    sk_X509_pop_free(peer_certs, X509_free);
1831

69
  if (result.IsEmpty())
1832
3
    result = Object::New(env->isolate());
1833
138
  args.GetReturnValue().Set(result);
1834
}
1835
1836
1837
template <class Base>
1838
123
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1839
123
  Environment* env = Environment::GetCurrent(args);
1840
1841
  Base* w;
1842

123
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1843
1844
123
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1845

123
  if (sess == nullptr)
1846
    return;
1847
1848
123
  int slen = i2d_SSL_SESSION(sess, nullptr);
1849

123
  CHECK_GT(slen, 0);
1850
1851
123
  char* sbuf = Malloc(slen);
1852
123
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1853
123
  i2d_SSL_SESSION(sess, &p);
1854
369
  args.GetReturnValue().Set(Buffer::New(env, sbuf, slen).ToLocalChecked());
1855
}
1856
1857
1858
template <class Base>
1859
72
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1860
72
  Environment* env = Environment::GetCurrent(args);
1861
1862
  Base* w;
1863

72
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1864
1865

72
  if (args.Length() < 1) {
1866
    return env->ThrowError("Session argument is mandatory");
1867
  }
1868
1869

72
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Session");
1870
72
  size_t slen = Buffer::Length(args[0]);
1871
72
  char* sbuf = new char[slen];
1872
72
  memcpy(sbuf, Buffer::Data(args[0]), slen);
1873
1874
72
  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1875
72
  SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1876
1877

72
  delete[] sbuf;
1878
1879

72
  if (sess == nullptr)
1880
    return;
1881
1882
72
  int r = SSL_set_session(w->ssl_, sess);
1883
72
  SSL_SESSION_free(sess);
1884
1885

72
  if (!r)
1886
    return env->ThrowError("SSL_set_session error");
1887
}
1888
1889
1890
template <class Base>
1891
13
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1892
  Base* w;
1893

26
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1894
1895



26
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1896
10
    ssize_t slen = Buffer::Length(args[0]);
1897
10
    char* sbuf = Buffer::Data(args[0]);
1898
1899
10
    const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1900
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1901
1902
    // Setup next session and move hello to the BIO buffer
1903

10
    if (w->next_sess_ != nullptr)
1904
      SSL_SESSION_free(w->next_sess_);
1905
10
    w->next_sess_ = sess;
1906
  }
1907
}
1908
1909
1910
template <class Base>
1911
76
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1912
  Base* w;
1913

152
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1914
76
  bool yes = SSL_session_reused(w->ssl_);
1915
228
  args.GetReturnValue().Set(yes);
1916
}
1917
1918
1919
template <class Base>
1920
22
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
1921
  Base* w;
1922

44
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1923
22
  w->hello_parser_.End();
1924
}
1925
1926
1927
template <class Base>
1928
3
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1929
  Base* w;
1930

6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1931
1932
  ClearErrorOnReturn clear_error_on_return;
1933
1934
3
  bool yes = SSL_renegotiate(w->ssl_) == 1;
1935
9
  args.GetReturnValue().Set(yes);
1936
}
1937
1938
1939
template <class Base>
1940
2
void SSLWrap<Base>::Shutdown(const FunctionCallbackInfo<Value>& args) {
1941
  Base* w;
1942

4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1943
1944
2
  int rv = SSL_shutdown(w->ssl_);
1945
4
  args.GetReturnValue().Set(rv);
1946
}
1947
1948
1949
template <class Base>
1950
9
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1951
  Base* w;
1952

9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1953
9
  Environment* env = w->ssl_env();
1954
1955
9
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1956


9
  if (sess == nullptr || sess->tlsext_tick == nullptr)
1957
    return;
1958
1959
  Local<Object> buff = Buffer::Copy(
1960
      env,
1961
      reinterpret_cast<char*>(sess->tlsext_tick),
1962
18
      sess->tlsext_ticklen).ToLocalChecked();
1963
1964
18
  args.GetReturnValue().Set(buff);
1965
}
1966
1967
1968
template <class Base>
1969
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1970
  Base* w;
1971

16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1972
8
  w->new_session_wait_ = false;
1973
8
  w->NewSessionDoneCb();
1974
}
1975
1976
1977
template <class Base>
1978
2
void SSLWrap<Base>::SetOCSPResponse(
1979
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1980
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1981
  Base* w;
1982

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1983
2
  Environment* env = w->env();
1984
1985

2
  if (args.Length() < 1)
1986
    return env->ThrowTypeError("OCSP response argument is mandatory");
1987
1988

2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "OCSP response");
1989
1990
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
1991
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1992
}
1993
1994
1995
template <class Base>
1996
4
void SSLWrap<Base>::RequestOCSP(
1997
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1998
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1999
  Base* w;
2000

8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2001
2002
4
  SSL_set_tlsext_status_type(w->ssl_, TLSEXT_STATUSTYPE_ocsp);
2003
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2004
}
2005
2006
2007
template <class Base>
2008
340
void SSLWrap<Base>::GetEphemeralKeyInfo(
2009
    const v8::FunctionCallbackInfo<v8::Value>& args) {
2010
  Base* w;
2011

340
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2012
340
  Environment* env = Environment::GetCurrent(args);
2013
2014

340
  CHECK_NE(w->ssl_, nullptr);
2015
2016
  // tmp key is available on only client
2017

340
  if (w->is_server())
2018
10
    return args.GetReturnValue().SetNull();
2019
2020
335
  Local<Object> info = Object::New(env->isolate());
2021
2022
  EVP_PKEY* key;
2023
2024

335
  if (SSL_get_server_tmp_key(w->ssl_, &key)) {
2025

295
    switch (EVP_PKEY_id(key)) {
2026
      case EVP_PKEY_DH:
2027
6
        info->Set(env->type_string(),
2028
24
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH"));
2029
6
        info->Set(env->size_string(),
2030
24
                  Integer::New(env->isolate(), EVP_PKEY_bits(key)));
2031
6
        break;
2032
      case EVP_PKEY_EC:
2033
        {
2034
289
          EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
2035
289
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2036
289
          EC_KEY_free(ec);
2037
289
          info->Set(env->type_string(),
2038
1156
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"));
2039
289
          info->Set(env->name_string(),
2040
1445
                    OneByteString(args.GetIsolate(), OBJ_nid2sn(nid)));
2041
289
          info->Set(env->size_string(),
2042
1156
                    Integer::New(env->isolate(), EVP_PKEY_bits(key)));
2043
        }
2044
    }
2045
295
    EVP_PKEY_free(key);
2046
  }
2047
2048
670
  return args.GetReturnValue().Set(info);
2049
}
2050
2051
2052
#ifdef SSL_set_max_send_fragment
2053
template <class Base>
2054
3
void SSLWrap<Base>::SetMaxSendFragment(
2055
    const v8::FunctionCallbackInfo<v8::Value>& args) {
2056




12
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2057
2058
  Base* w;
2059

6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2060
2061
6
  int rv = SSL_set_max_send_fragment(w->ssl_, args[0]->Int32Value());
2062
6
  args.GetReturnValue().Set(rv);
2063
}
2064
#endif  // SSL_set_max_send_fragment
2065
2066
2067
template <class Base>
2068
23
void SSLWrap<Base>::IsInitFinished(const FunctionCallbackInfo<Value>& args) {
2069
  Base* w;
2070

46
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2071
23
  bool yes = SSL_is_init_finished(w->ssl_);
2072
69
  args.GetReturnValue().Set(yes);
2073
}
2074
2075
2076
template <class Base>
2077
396
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2078
  Base* w;
2079

483
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2080
2081
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2082
  // peer certificate is questionable but it's compatible with what was
2083
  // here before.
2084
  long x509_verify_error =  // NOLINT(runtime/int)
2085
396
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2086

396
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
2087
393
    X509_free(peer_cert);
2088
393
    x509_verify_error = SSL_get_verify_result(w->ssl_);
2089
  }
2090
2091

396
  if (x509_verify_error == X509_V_OK)
2092
174
    return args.GetReturnValue().SetNull();
2093
2094
  // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
2095
  // in the presence of invalid error codes.  Probably academical but something
2096
  // to keep in mind if/when node ever grows multi-isolate capabilities.
2097
309
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2098
309
  const char* code = reason;
2099
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2100














309
  switch (x509_verify_error) {
2101
3
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2102
5
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
2103
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2104
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2105
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2106
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2107
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2108
    CASE_X509_ERR(CERT_NOT_YET_VALID)
2109
35
    CASE_X509_ERR(CERT_HAS_EXPIRED)
2110
    CASE_X509_ERR(CRL_NOT_YET_VALID)
2111
    CASE_X509_ERR(CRL_HAS_EXPIRED)
2112
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2113
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2114
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2115
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2116
    CASE_X509_ERR(OUT_OF_MEM)
2117
138
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2118
6
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2119
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2120
117
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2121
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2122
3
    CASE_X509_ERR(CERT_REVOKED)
2123
    CASE_X509_ERR(INVALID_CA)
2124
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2125
1
    CASE_X509_ERR(INVALID_PURPOSE)
2126
    CASE_X509_ERR(CERT_UNTRUSTED)
2127
    CASE_X509_ERR(CERT_REJECTED)
2128
  }
2129
#undef CASE_X509_ERR
2130
2131
309
  Isolate* isolate = args.GetIsolate();
2132
309
  Local<String> reason_string = OneByteString(isolate, reason);
2133
309
  Local<Value> exception_value = Exception::Error(reason_string);
2134
309
  Local<Object> exception_object = exception_value->ToObject(isolate);
2135
927
  exception_object->Set(w->env()->code_string(), OneByteString(isolate, code));
2136
618
  args.GetReturnValue().Set(exception_object);
2137
}
2138
2139
2140
template <class Base>
2141
12
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
2142
  Base* w;
2143

12
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2144
12
  Environment* env = w->ssl_env();
2145
2146
12
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
2147

12
  if (c == nullptr)
2148
    return;
2149
2150
12
  Local<Object> info = Object::New(env->isolate());
2151
12
  const char* cipher_name = SSL_CIPHER_get_name(c);
2152
36
  info->Set(env->name_string(), OneByteString(args.GetIsolate(), cipher_name));
2153
12
  const char* cipher_version = SSL_CIPHER_get_version(c);
2154
12
  info->Set(env->version_string(),
2155
48
            OneByteString(args.GetIsolate(), cipher_version));
2156
24
  args.GetReturnValue().Set(info);
2157
}
2158
2159
2160
template <class Base>
2161
3
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2162
  Base* w;
2163

6
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2164
2165
3
  const char* tls_version = SSL_get_version(w->ssl_);
2166
9
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2167
}
2168
2169
2170
#ifndef OPENSSL_NO_NEXTPROTONEG
2171
template <class Base>
2172
323
int SSLWrap<Base>::AdvertiseNextProtoCallback(SSL* s,
2173
                                              const unsigned char** data,
2174
                                              unsigned int* len,
2175
                                              void* arg) {
2176
323
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2177
323
  Environment* env = w->env();
2178
323
  HandleScope handle_scope(env->isolate());
2179
323
  Context::Scope context_scope(env->context());
2180
2181
  auto npn_buffer =
2182
323
      w->object()->GetPrivate(
2183
          env->context(),
2184
1292
          env->npn_buffer_private_symbol()).ToLocalChecked();
2185
2186

646
  if (npn_buffer->IsUndefined()) {
2187
    // No initialization - no NPN protocols
2188
196
    *data = reinterpret_cast<const unsigned char*>("");
2189
196
    *len = 0;
2190
  } else {
2191

127
    CHECK(Buffer::HasInstance(npn_buffer));
2192
127
    *data = reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2193
127
    *len = Buffer::Length(npn_buffer);
2194
  }
2195
2196
646
  return SSL_TLSEXT_ERR_OK;
2197
}
2198
2199
2200
template <class Base>
2201
322
int SSLWrap<Base>::SelectNextProtoCallback(SSL* s,
2202
                                           unsigned char** out,
2203
                                           unsigned char* outlen,
2204
                                           const unsigned char* in,
2205
                                           unsigned int inlen,
2206
                                           void* arg) {
2207
322
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2208
322
  Environment* env = w->env();
2209
322
  HandleScope handle_scope(env->isolate());
2210
322
  Context::Scope context_scope(env->context());
2211
2212
  auto npn_buffer =
2213
322
      w->object()->GetPrivate(
2214
          env->context(),
2215
1288
          env->npn_buffer_private_symbol()).ToLocalChecked();
2216
2217

644
  if (npn_buffer->IsUndefined()) {
2218
    // We should at least select one protocol
2219
    // If server is using NPN
2220
301
    *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
2221
301
    *outlen = 8;
2222
2223
    // set status: unsupported
2224

1204
    CHECK(
2225
        w->object()->SetPrivate(
2226
            env->context(),
2227
            env->selected_npn_buffer_private_symbol(),
2228
            False(env->isolate())).FromJust());
2229
2230
301
    return SSL_TLSEXT_ERR_OK;
2231
  }
2232
2233

21
  CHECK(Buffer::HasInstance(npn_buffer));
2234
  const unsigned char* npn_protos =
2235
21
      reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2236
21
  size_t len = Buffer::Length(npn_buffer);
2237
2238
21
  int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
2239
  Local<Value> result;
2240


21
  switch (status) {
2241
    case OPENSSL_NPN_UNSUPPORTED:
2242
      result = Null(env->isolate());
2243
      break;
2244
    case OPENSSL_NPN_NEGOTIATED:
2245
14
      result = OneByteString(env->isolate(), *out, *outlen);
2246
7
      break;
2247
    case OPENSSL_NPN_NO_OVERLAP:
2248
28
      result = False(env->isolate());
2249
14
      break;
2250
    default:
2251
      break;
2252
  }
2253
2254

63
  CHECK(
2255
      w->object()->SetPrivate(
2256
          env->context(),
2257
          env->selected_npn_buffer_private_symbol(),
2258
          result).FromJust());
2259
2260
343
  return SSL_TLSEXT_ERR_OK;
2261
}
2262
2263
2264
template <class Base>
2265
719
void SSLWrap<Base>::GetNegotiatedProto(
2266
    const FunctionCallbackInfo<Value>& args) {
2267
  Base* w;
2268

1119
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2269
719
  Environment* env = w->env();
2270
2271

719
  if (w->is_client()) {
2272
    auto selected_npn_buffer =
2273
336
        w->object()->GetPrivate(
2274
            env->context(),
2275
1344
            env->selected_npn_buffer_private_symbol()).ToLocalChecked();
2276
672
    args.GetReturnValue().Set(selected_npn_buffer);
2277
336
    return;
2278
  }
2279
2280
  const unsigned char* npn_proto;
2281
  unsigned int npn_proto_len;
2282
2283
383
  SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
2284
2285

383
  if (!npn_proto)
2286
128
    return args.GetReturnValue().Set(false);
2287
2288
  args.GetReturnValue().Set(
2289
1276
      OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
2290
}
2291
2292
2293
template <class Base>
2294
158
void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
2295
  Base* w;
2296

158
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2297
158
  Environment* env = w->env();
2298
2299

158
  if (args.Length() < 1)
2300
    return env->ThrowTypeError("NPN protocols argument is mandatory");
2301
2302

158
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "NPN protocols");
2303
2304

474
  CHECK(
2305
      w->object()->SetPrivate(
2306
          env->context(),
2307
          env->npn_buffer_private_symbol(),
2308
          args[0]).FromJust());
2309
}
2310
#endif  // OPENSSL_NO_NEXTPROTONEG
2311
2312
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2313
template <class Base>
2314
24
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2315
                                      const unsigned char** out,
2316
                                      unsigned char* outlen,
2317
                                      const unsigned char* in,
2318
                                      unsigned int inlen,
2319
                                      void* arg) {
2320
24
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2321
24
  Environment* env = w->env();
2322
24
  HandleScope handle_scope(env->isolate());
2323
24
  Context::Scope context_scope(env->context());
2324
2325
  Local<Value> alpn_buffer =
2326
24
      w->object()->GetPrivate(
2327
          env->context(),
2328
96
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2329

24
  CHECK(Buffer::HasInstance(alpn_buffer));
2330
  const unsigned char* alpn_protos =
2331
24
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2332
24
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2333
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2334
24
                                     alpn_protos, alpn_protos_len, in, inlen);
2335
2336

24
  switch (status) {
2337
    case OPENSSL_NPN_NO_OVERLAP:
2338
      // According to 3.2. Protocol Selection of RFC7301,
2339
      // fatal no_application_protocol alert shall be sent
2340
      // but current openssl does not support it yet. See
2341
      // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2342
      // Instead, we send a warning alert for now.
2343
5
      return SSL_TLSEXT_ERR_ALERT_WARNING;
2344
    case OPENSSL_NPN_NEGOTIATED:
2345
19
      return SSL_TLSEXT_ERR_OK;
2346
    default:
2347
      return SSL_TLSEXT_ERR_ALERT_FATAL;
2348
24
  }
2349
}
2350
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2351
2352
2353
template <class Base>
2354
719
void SSLWrap<Base>::GetALPNNegotiatedProto(
2355
    const FunctionCallbackInfo<v8::Value>& args) {
2356
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2357
  Base* w;
2358

1410
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2359
2360
  const unsigned char* alpn_proto;
2361
  unsigned int alpn_proto_len;
2362
2363
719
  SSL_get0_alpn_selected(w->ssl_, &alpn_proto, &alpn_proto_len);
2364
2365

719
  if (!alpn_proto)
2366
1382
    return args.GetReturnValue().Set(false);
2367
2368
  args.GetReturnValue().Set(
2369
112
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2370
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2371
}
2372
2373
2374
template <class Base>
2375
178
void SSLWrap<Base>::SetALPNProtocols(
2376
    const FunctionCallbackInfo<v8::Value>& args) {
2377
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2378
  Base* w;
2379

178
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2380
178
  Environment* env = w->env();
2381



356
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2382
    return env->ThrowTypeError("Must give a Buffer as first argument");
2383
2384

178
  if (w->is_client()) {
2385
    const unsigned char* alpn_protos =
2386
35
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2387
35
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2388
35
    int r = SSL_set_alpn_protos(w->ssl_, alpn_protos, alpn_protos_len);
2389

35
    CHECK_EQ(r, 0);
2390
  } else {
2391

429
    CHECK(
2392
        w->object()->SetPrivate(
2393
          env->context(),
2394
          env->alpn_buffer_private_symbol(),
2395
          args[0]).FromJust());
2396
    // Server should select ALPN protocol from list of advertised by client
2397
143
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_), SelectALPNCallback,
2398
143
                               nullptr);
2399
  }
2400
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2401
}
2402
2403
2404
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2405
template <class Base>
2406
9
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2407
9
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2408
9
  Environment* env = w->env();
2409
9
  HandleScope handle_scope(env->isolate());
2410
2411

9
  if (w->is_client()) {
2412
    // Incoming response
2413
    const unsigned char* resp;
2414
4
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2415
    Local<Value> arg;
2416

4
    if (resp == nullptr) {
2417
4
      arg = Null(env->isolate());
2418
    } else {
2419
4
      arg =
2420
2
          Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2421
          .ToLocalChecked();
2422
    }
2423
2424
4
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2425
2426
    // Somehow, client is expecting different return value here
2427
4
    return 1;
2428
  } else {
2429
    // Outgoing response
2430

10
    if (w->ocsp_response_.IsEmpty())
2431
3
      return SSL_TLSEXT_ERR_NOACK;
2432
2433
2
    Local<Object> obj = PersistentToLocal(env->isolate(), w->ocsp_response_);
2434
2
    char* resp = Buffer::Data(obj);
2435
2
    size_t len = Buffer::Length(obj);
2436
2437
    // OpenSSL takes control of the pointer after accepting it
2438
2
    char* data = node::Malloc(len);
2439
2
    memcpy(data, resp, len);
2440
2441

2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2442
      free(data);
2443
2
    w->ocsp_response_.Reset();
2444
2445
2
    return SSL_TLSEXT_ERR_OK;
2446
9
  }
2447
}
2448
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2449
2450
2451
template <class Base>
2452
22
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2453
22
  cert_cb_ = cb;
2454
22
  cert_cb_arg_ = arg;
2455
22
}
2456
2457
2458
template <class Base>
2459
400
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2460
400
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2461
2462

400
  if (!w->is_server())
2463
28
    return 1;
2464
2465

372
  if (!w->is_waiting_cert_cb())
2466
350
    return 1;
2467
2468

22
  if (w->cert_cb_running_)
2469
    return -1;
2470
2471
22
  Environment* env = w->env();
2472
22
  HandleScope handle_scope(env->isolate());
2473
22
  Context::Scope context_scope(env->context());
2474
22
  w->cert_cb_running_ = true;
2475
2476
22
  Local<Object> info = Object::New(env->isolate());
2477
2478
22
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2479

22
  if (servername == nullptr) {
2480
24
    info->Set(env->servername_string(), String::Empty(env->isolate()));
2481
  } else {
2482
    Local<String> str = OneByteString(env->isolate(), servername,
2483
14
                                      strlen(servername));
2484
28
    info->Set(env->servername_string(), str);
2485
  }
2486
2487
22
  bool ocsp = false;
2488
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2489
22
  ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp;
2490
#endif
2491
2492
66
  info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp));
2493
2494
44
  Local<Value> argv[] = { info };
2495
22
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2496
2497

22
  if (!w->cert_cb_running_)
2498
13
    return 1;
2499
2500
  // Performing async action, wait...
2501
31
  return -1;
2502
}
2503
2504
2505
template <class Base>
2506
22
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2507
  Base* w;
2508

24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2509
22
  Environment* env = w->env();
2510
2511



22
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2512
2513
22
  Local<Object> object = w->object();
2514
44
  Local<Value> ctx = object->Get(env->sni_context_string());
2515
22
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2516
2517
  // Not an object, probably undefined or null
2518

22
  if (!ctx->IsObject())
2519
12
    goto fire_cb;
2520
2521

10
  if (cons->HasInstance(ctx)) {
2522
    SecureContext* sc;
2523

10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2524
9
    w->sni_context_.Reset();
2525
9
    w->sni_context_.Reset(env->isolate(), ctx);
2526
2527
    int rv;
2528
2529
    // NOTE: reference count is not increased by this API methods
2530
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_);
2531
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_);
2532
    STACK_OF(X509)* chain;
2533
2534
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain);
2535

9
    if (rv)
2536
9
      rv = SSL_use_certificate(w->ssl_, x509);
2537

9
    if (rv)
2538
8
      rv = SSL_use_PrivateKey(w->ssl_, pkey);
2539


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

9
    if (rv)
2542
8
      rv = w->SetCACerts(sc);
2543

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

1
      if (!err)
2546
        return env->ThrowError("CertCbDone");
2547
1
      return ThrowCryptoError(env, err);
2548
    }
2549
  } else {
2550
    // Failure: incorrect SNI context object
2551
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2552
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2553
1
    return;
2554
  }
2555
2556
 fire_cb:
2557
  CertCb cb;
2558
  void* arg;
2559
2560
20
  cb = w->cert_cb_;
2561
20
  arg = w->cert_cb_arg_;
2562
2563
20
  w->cert_cb_running_ = false;
2564
20
  w->cert_cb_ = nullptr;
2565
20
  w->cert_cb_arg_ = nullptr;
2566
2567
20
  cb(arg);
2568
}
2569
2570
2571
template <class Base>
2572
void SSLWrap<Base>::SSLGetter(Local<String> property,
2573
                              const PropertyCallbackInfo<Value>& info) {
2574
  Base* base;
2575
  ASSIGN_OR_RETURN_UNWRAP(&base, info.This());
2576
  SSL* ssl = base->ssl_;
2577
  Local<External> ext = External::New(info.GetIsolate(), ssl);
2578
  info.GetReturnValue().Set(ext);
2579
}
2580
2581
2582
template <class Base>
2583
21526
void SSLWrap<Base>::DestroySSL() {
2584

21526
  if (ssl_ == nullptr)
2585
32280
    return;
2586
2587
10772
  SSL_free(ssl_);
2588
10772
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2589
10772
  ssl_ = nullptr;
2590
}
2591
2592
2593
template <class Base>
2594
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2595
  InitNPN(sc);
2596
  CHECK_EQ(SSL_set_SSL_CTX(ssl_, sc->ctx_), sc->ctx_);
2597
2598
  SetCACerts(sc);
2599
}
2600
2601
2602
template <class Base>
2603
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2604
8
  int err = SSL_set1_verify_cert_store(ssl_, SSL_CTX_get_cert_store(sc->ctx_));
2605

8
  if (err != 1)
2606
    return err;
2607
2608
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2609
8
      SSL_CTX_get_client_CA_list(sc->ctx_));
2610
2611
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2612
8
  SSL_set_client_CA_list(ssl_, list);
2613
8
  return 1;
2614
}
2615
2616
2617
3
void Connection::OnClientHelloParseEnd(void* arg) {
2618
3
  Connection* conn = static_cast<Connection*>(arg);
2619
2620
  // Write all accumulated data
2621
  int r = BIO_write(conn->bio_read_,
2622
                    reinterpret_cast<char*>(conn->hello_data_),
2623
3
                    conn->hello_offset_);
2624
3
  conn->HandleBIOError(conn->bio_read_, "BIO_write", r);
2625
3
  conn->SetShutdownFlags();
2626
3
}
2627
2628
2629
#ifdef SSL_PRINT_DEBUG
2630
# define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
2631
#else
2632
# define DEBUG_PRINT(...)
2633
#endif
2634
2635
2636
27
int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
2637
27
  if (rv >= 0)
2638
10
    return rv;
2639
2640
17
  int retry = BIO_should_retry(bio);
2641
  (void) retry;  // unused if !defined(SSL_PRINT_DEBUG)
2642
2643
17
  if (BIO_should_write(bio)) {
2644
    DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n",
2645
                ssl_,
2646
                func,
2647
                retry);
2648
    return 0;
2649
2650
17
  } else if (BIO_should_read(bio)) {
2651
    DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
2652
17
    return 0;
2653
2654
  } else {
2655
    char ssl_error_buf[512];
2656
    ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
2657
2658
    HandleScope scope(ssl_env()->isolate());
2659
    Local<Value> exception =
2660
        Exception::Error(OneByteString(ssl_env()->isolate(), ssl_error_buf));
2661
    object()->Set(ssl_env()->error_string(), exception);
2662
2663
    DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n",
2664
                ssl_,
2665
                func,
2666
                rv,
2667
                ssl_error_buf);
2668
2669
    return rv;
2670
  }
2671
2672
  return 0;
2673
}
2674
2675
2676
35
int Connection::HandleSSLError(const char* func,
2677
                               int rv,
2678
                               ZeroStatus zs,
2679
                               SyscallStatus ss) {
2680
  ClearErrorOnReturn clear_error_on_return;
2681
2682
35
  if (rv > 0)
2683
4
    return rv;
2684

31
  if (rv == 0 && zs == kZeroIsNotAnError)
2685
1
    return rv;
2686
2687
30
  int err = SSL_get_error(ssl_, rv);
2688
2689
30
  if (err == SSL_ERROR_NONE) {
2690
    return 0;
2691
2692
30
  } else if (err == SSL_ERROR_WANT_WRITE) {
2693
    DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
2694
    return 0;
2695
2696
30
  } else if (err == SSL_ERROR_WANT_READ) {
2697
    DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
2698
29
    return 0;
2699
2700
1
  } else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2701
    DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2702
    return 0;
2703
2704
1
  } else if (err == SSL_ERROR_ZERO_RETURN) {
2705
    HandleScope scope(ssl_env()->isolate());
2706
2707
    Local<Value> exception =
2708
        Exception::Error(ssl_env()->zero_return_string());
2709
    object()->Set(ssl_env()->error_string(), exception);
2710
    return rv;
2711
2712

1
  } else if (err == SSL_ERROR_SYSCALL && ss == kIgnoreSyscall) {
2713
    return 0;
2714
2715
  } else {
2716
1
    HandleScope scope(ssl_env()->isolate());
2717
    BUF_MEM* mem;
2718
    BIO *bio;
2719
2720

1
    CHECK(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
2721
2722
    // XXX We need to drain the error queue for this thread or else OpenSSL
2723
    // has the possibility of blocking connections? This problem is not well
2724
    // understood. And we should be somehow propagating these errors up
2725
    // into JavaScript. There is no test which demonstrates this problem.
2726
    // https://github.com/joyent/node/issues/1719
2727
1
    bio = BIO_new(BIO_s_mem());
2728
1
    if (bio != nullptr) {
2729
1
      ERR_print_errors(bio);
2730
1
      BIO_get_mem_ptr(bio, &mem);
2731
      Local<Value> exception = Exception::Error(
2732
          OneByteString(ssl_env()->isolate(),
2733
            mem->data,
2734
1
            mem->length));
2735
3
      object()->Set(ssl_env()->error_string(), exception);
2736
1
      BIO_free_all(bio);
2737
    }
2738
2739
1
    return rv;
2740
  }
2741
2742
35
  return 0;
2743
}
2744
2745
2746
36
void Connection::SetShutdownFlags() {
2747
36
  HandleScope scope(ssl_env()->isolate());
2748
2749
36
  int flags = SSL_get_shutdown(ssl_);
2750
2751
36
  if (flags & SSL_SENT_SHUTDOWN) {
2752
    Local<String> sent_shutdown_key = ssl_env()->sent_shutdown_string();
2753
    object()->Set(sent_shutdown_key, True(ssl_env()->isolate()));
2754
  }
2755
2756
36
  if (flags & SSL_RECEIVED_SHUTDOWN) {
2757
1
    Local<String> received_shutdown_key = ssl_env()->received_shutdown_string();
2758
3
    object()->Set(received_shutdown_key, True(ssl_env()->isolate()));
2759
36
  }
2760
36
}
2761
2762
2763
void Connection::NewSessionDoneCb() {
2764
  HandleScope scope(env()->isolate());
2765
2766
  MakeCallback(env()->onnewsessiondone_string(), 0, nullptr);
2767
}
2768
2769
2770
407
void Connection::Initialize(Environment* env, Local<Object> target) {
2771
407
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Connection::New);
2772
814
  t->InstanceTemplate()->SetInternalFieldCount(1);
2773
814
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"));
2774
2775
407
  AsyncWrap::AddWrapMethods(env, t);
2776
407
  env->SetProtoMethod(t, "encIn", Connection::EncIn);
2777
407
  env->SetProtoMethod(t, "clearOut", Connection::ClearOut);
2778
407
  env->SetProtoMethod(t, "clearIn", Connection::ClearIn);
2779
407
  env->SetProtoMethod(t, "encOut", Connection::EncOut);
2780
407
  env->SetProtoMethod(t, "clearPending", Connection::ClearPending);
2781
407
  env->SetProtoMethod(t, "encPending", Connection::EncPending);
2782
407
  env->SetProtoMethod(t, "start", Connection::Start);
2783
407
  env->SetProtoMethod(t, "close", Connection::Close);
2784
2785
407
  SSLWrap<Connection>::AddMethods(env, t);
2786
2787
2788
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2789
407
  env->SetProtoMethod(t, "getServername", Connection::GetServername);
2790
407
  env->SetProtoMethod(t, "setSNICallback",  Connection::SetSNICallback);
2791
#endif
2792
2793
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"),
2794
1221
              t->GetFunction());
2795
407
}
2796
2797
2798
9
inline int compar(const void* a, const void* b) {
2799
9
  return memcmp(a, b, CNNIC_WHITELIST_HASH_LEN);
2800
}
2801
2802
2803
113
inline int IsSelfSigned(X509* cert) {
2804
113
  return X509_NAME_cmp(X509_get_subject_name(cert),
2805
226
                       X509_get_issuer_name(cert)) == 0;
2806
}
2807
2808
2809
inline X509* FindRoot(STACK_OF(X509)* sk) {
2810
  for (int i = 0; i < sk_X509_num(sk); i++) {
2811
    X509* cert = sk_X509_value(sk, i);
2812
    if (IsSelfSigned(cert))
2813
      return cert;
2814
  }
2815
  return nullptr;
2816
}
2817
2818
2819
113
inline bool CertIsStartComOrWoSign(X509_NAME* name) {
2820
  const unsigned char* startcom_wosign_data;
2821
  X509_NAME* startcom_wosign_name;
2822
2823
757
  for (const auto& dn : StartComAndWoSignDNs) {
2824
661
    startcom_wosign_data = dn.data;
2825
    startcom_wosign_name = d2i_X509_NAME(nullptr, &startcom_wosign_data,
2826
661
                                         dn.len);
2827
661
    int cmp = X509_NAME_cmp(name, startcom_wosign_name);
2828
661
    X509_NAME_free(startcom_wosign_name);
2829
661
    if (cmp == 0)
2830
17
      return true;
2831
  }
2832
2833
96
  return false;
2834
}
2835
2836
// Revoke the certificates issued by StartCom or WoSign that has
2837
// notBefore after 00:00:00 on October 21, 2016 (1477008000 in epoch).
2838
113
inline bool CheckStartComOrWoSign(X509_NAME* root_name, X509* cert) {
2839
113
  if (!CertIsStartComOrWoSign(root_name))
2840
96
    return true;
2841
2842
17
  time_t october_21_2016 = static_cast<time_t>(1477008000);
2843
17
  if (X509_cmp_time(X509_get_notBefore(cert), &october_21_2016) < 0)
2844
16
    return true;
2845
2846
1
  return false;
2847
}
2848
2849
2850
// Whitelist check for certs issued by CNNIC, StartCom and WoSign. See
2851
// https://blog.mozilla.org/security/2015/04/02
2852
// /distrusting-new-cnnic-certificates/ and
2853
// https://blog.mozilla.org/security/2016/10/24/
2854
// distrusting-new-wosign-and-startcom-certificates
2855
113
inline CheckResult CheckWhitelistedServerCert(X509_STORE_CTX* ctx) {
2856
  unsigned char hash[CNNIC_WHITELIST_HASH_LEN];
2857
113
  unsigned int hashlen = CNNIC_WHITELIST_HASH_LEN;
2858
2859
113
  STACK_OF(X509)* chain = X509_STORE_CTX_get1_chain(ctx);
2860
113
  CHECK_NE(chain, nullptr);
2861
113
  CHECK_GT(sk_X509_num(chain), 0);
2862
2863
  // Take the last cert as root at the first time.
2864
113
  X509* root_cert = sk_X509_value(chain, sk_X509_num(chain)-1);
2865
113
  X509_NAME* root_name = X509_get_subject_name(root_cert);
2866
2867
113
  if (!IsSelfSigned(root_cert)) {
2868
    root_cert = FindRoot(chain);
2869
    CHECK_NE(root_cert, nullptr);
2870
    root_name = X509_get_subject_name(root_cert);
2871
  }
2872
2873
113
  X509* leaf_cert = sk_X509_value(chain, 0);
2874
113
  if (!CheckStartComOrWoSign(root_name, leaf_cert)) {
2875
1
    sk_X509_pop_free(chain, X509_free);
2876
1
    return CHECK_CERT_REVOKED;
2877
  }
2878
2879
  // When the cert is issued from either CNNNIC ROOT CA or CNNNIC EV
2880
  // ROOT CA, check a hash of its leaf cert if it is in the whitelist.
2881

223
  if (X509_NAME_cmp(root_name, cnnic_name) == 0 ||
2882
111
      X509_NAME_cmp(root_name, cnnic_ev_name) == 0) {
2883
    int ret = X509_digest(leaf_cert, EVP_sha256(), hash,
2884
1
                          &hashlen);
2885
1
    CHECK(ret);
2886
2887
    void* result = bsearch(hash, WhitelistedCNNICHashes,
2888
                           arraysize(WhitelistedCNNICHashes),
2889
1
                           CNNIC_WHITELIST_HASH_LEN, compar);
2890
1
    if (result == nullptr) {
2891
1
      sk_X509_pop_free(chain, X509_free);
2892
1
      return CHECK_CERT_REVOKED;
2893
    }
2894
  }
2895
2896
111
  sk_X509_pop_free(chain, X509_free);
2897
111
  return CHECK_OK;
2898
}
2899
2900
2901
720
inline int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2902
  // Failure on verification of the cert is handled in
2903
  // Connection::VerifyError.
2904

720
  if (preverify_ok == 0 || X509_STORE_CTX_get_error(ctx) != X509_V_OK)
2905
569
    return CHECK_OK;
2906
2907
  // Server does not need to check the whitelist.
2908
  SSL* ssl = static_cast<SSL*>(
2909
151
      X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
2910
2911
151
  if (SSL_is_server(ssl))
2912
38
    return CHECK_OK;
2913
2914
  // Client needs to check if the server cert is listed in the
2915
  // whitelist when it is issued by the specific rootCAs.
2916
113
  CheckResult ret = CheckWhitelistedServerCert(ctx);
2917
113
  if (ret == CHECK_CERT_REVOKED)
2918
2
    X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
2919
2920
113
  return ret;
2921
}
2922
2923
2924
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2925
3
int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
2926
3
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(s));
2927
3
  Environment* env = conn->env();
2928
3
  HandleScope scope(env->isolate());
2929
2930
3
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2931
2932
3
  if (servername) {
2933
    conn->servername_.Reset(env->isolate(),
2934
4
                            OneByteString(env->isolate(), servername));
2935
2936
    // Call the SNI callback and use its return value as context
2937
4
    if (!conn->sniObject_.IsEmpty()) {
2938
2
      conn->sni_context_.Reset();
2939
2940
      Local<Object> sni_obj = PersistentToLocal(env->isolate(),
2941
2
                                                conn->sniObject_);
2942
2943
2
      Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
2944
      Local<Value> ret = node::MakeCallback(env->isolate(),
2945
                                            sni_obj,
2946
                                            env->onselect_string(),
2947
                                            1,
2948
2
                                            &arg);
2949
2950
      // If ret is SecureContext
2951
      Local<FunctionTemplate> secure_context_constructor_template =
2952
2
          env->secure_context_constructor_template();
2953
2
      if (secure_context_constructor_template->HasInstance(ret)) {
2954
        conn->sni_context_.Reset(env->isolate(), ret);
2955
        SecureContext* sc;
2956
        ASSIGN_OR_RETURN_UNWRAP(&sc, ret.As<Object>(), SSL_TLSEXT_ERR_NOACK);
2957
        conn->SetSNIContext(sc);
2958
      } else {
2959
2
        return SSL_TLSEXT_ERR_NOACK;
2960
      }
2961
    }
2962
  }
2963
2964
1
  return SSL_TLSEXT_ERR_OK;
2965
}
2966
#endif
2967
2968
10017
void Connection::New(const FunctionCallbackInfo<Value>& args) {
2969
10017
  Environment* env = Environment::GetCurrent(args);
2970
2971


40068
  if (args.Length() < 1 || !args[0]->IsObject()) {
2972
1
    env->ThrowError("First argument must be a tls module SecureContext");
2973
1
    return;
2974
  }
2975
2976
  SecureContext* sc;
2977
20032
  ASSIGN_OR_RETURN_UNWRAP(&sc, args[0].As<Object>());
2978
2979
20032
  bool is_server = args[1]->BooleanValue();
2980
2981
  SSLWrap<Connection>::Kind kind =
2982
10016
      is_server ? SSLWrap<Connection>::kServer : SSLWrap<Connection>::kClient;
2983
10016
  Connection* conn = new Connection(env, args.This(), sc, kind);
2984
10016
  conn->bio_read_ = NodeBIO::New();
2985
10016
  conn->bio_write_ = NodeBIO::New();
2986
2987
10016
  SSL_set_app_data(conn->ssl_, conn);
2988
2989
10016
  if (is_server)
2990
12
    SSL_set_info_callback(conn->ssl_, SSLInfoCallback);
2991
2992
10016
  InitNPN(sc);
2993
2994
10016
  SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
2995
2996
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2997
10016
  if (is_server) {
2998
12
    SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
2999
30012
  } else if (args[2]->IsString()) {
3000
    const node::Utf8Value servername(env->isolate(), args[2]);
3001
    SSL_set_tlsext_host_name(conn->ssl_, *servername);
3002
  }
3003
#endif
3004
3005
10016
  SSL_set_bio(conn->ssl_, conn->bio_read_, conn->bio_write_);
3006
3007
#ifdef SSL_MODE_RELEASE_BUFFERS
3008
10016
  long mode = SSL_get_mode(conn->ssl_);  // NOLINT(runtime/int)
3009
10016
  SSL_set_mode(conn->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
3010
#endif
3011
3012
3013
  int verify_mode;
3014
10016
  if (is_server) {
3015
24
    bool request_cert = args[2]->BooleanValue();
3016
12
    if (!request_cert) {
3017
      // Note reject_unauthorized ignored.
3018
4
      verify_mode = SSL_VERIFY_NONE;
3019
    } else {
3020
16
      bool reject_unauthorized = args[3]->BooleanValue();
3021
8
      verify_mode = SSL_VERIFY_PEER;
3022
8
      if (reject_unauthorized)
3023
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3024
    }
3025
  } else {
3026
    // Note request_cert and reject_unauthorized are ignored for clients.
3027
10004
    verify_mode = SSL_VERIFY_NONE;
3028
  }
3029
3030
3031
  // Always allow a connection. We'll reject in javascript.
3032
10016
  SSL_set_verify(conn->ssl_, verify_mode, VerifyCallback);
3033
3034
10016
  if (is_server) {
3035
12
    SSL_set_accept_state(conn->ssl_);
3036
  } else {
3037
10004
    SSL_set_connect_state(conn->ssl_);
3038
  }
3039
}
3040
3041
3042
72
void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
3043
72
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
3044
131
    return;
3045
3046
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
3047
  // a non-const SSL* in OpenSSL <= 0.9.7e.
3048
13
  SSL* ssl = const_cast<SSL*>(ssl_);
3049
13
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(ssl));
3050
13
  Environment* env = conn->env();
3051
13
  HandleScope handle_scope(env->isolate());
3052
13
  Context::Scope context_scope(env->context());
3053
3054
13
  if (where & SSL_CB_HANDSHAKE_START) {
3055
12
    conn->MakeCallback(env->onhandshakestart_string(), 0, nullptr);
3056
  }
3057
3058
13
  if (where & SSL_CB_HANDSHAKE_DONE) {
3059
1
    conn->MakeCallback(env->onhandshakedone_string(), 0, nullptr);
3060
13
  }
3061
}
3062
3063
3064
6
void Connection::EncIn(const FunctionCallbackInfo<Value>& args) {
3065
  Connection* conn;
3066
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3067
6
  Environment* env = conn->env();
3068
3069
6
  if (args.Length() < 3) {
3070
    return env->ThrowTypeError(
3071
        "Data, offset, and length arguments are mandatory");
3072
  }
3073
3074
6
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3075
3076
6
  char* buffer_data = Buffer::Data(args[0]);
3077
6
  size_t buffer_length = Buffer::Length(args[0]);
3078
3079
12
  size_t off = args[1]->Int32Value();
3080
12
  size_t len = args[2]->Int32Value();
3081
3082
6
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3083
    return env->ThrowRangeError("offset + length > buffer.length");
3084
3085
  int bytes_written;
3086
6
  char* data = buffer_data + off;
3087
3088

6
  if (conn->is_server() && !conn->hello_parser_.IsEnded()) {
3089
    // Just accumulate data, everything will be pushed to BIO later
3090
3
    if (conn->hello_parser_.IsPaused()) {
3091
      bytes_written = 0;
3092
    } else {
3093
      // Copy incoming data to the internal buffer
3094
      // (which has a size of the biggest possible TLS frame)
3095
3
      size_t available = sizeof(conn->hello_data_) - conn->hello_offset_;
3096
3
      size_t copied = len < available ? len : available;
3097
3
      memcpy(conn->hello_data_ + conn->hello_offset_, data, copied);
3098
3
      conn->hello_offset_ += copied;
3099
3100
3
      conn->hello_parser_.Parse(conn->hello_data_, conn->hello_offset_);
3101
3
      bytes_written = copied;
3102
    }
3103
  } else {
3104
3
    bytes_written = BIO_write(conn->bio_read_, data, len);
3105
3
    conn->HandleBIOError(conn->bio_read_, "BIO_write", bytes_written);
3106
3
    conn->SetShutdownFlags();
3107
  }
3108
3109
12
  args.GetReturnValue().Set(bytes_written);
3110
}
3111
3112
3113
16
void Connection::ClearOut(const FunctionCallbackInfo<Value>& args) {
3114
  Connection* conn;
3115
25
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3116
16
  Environment* env = conn->env();
3117
3118
16
  if (args.Length() < 3) {
3119
    return env->ThrowTypeError(
3120
        "Data, offset, and length arguments are mandatory");
3121
  }
3122
3123
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3124
3125
16
  char* buffer_data = Buffer::Data(args[0]);
3126
16
  size_t buffer_length = Buffer::Length(args[0]);
3127
3128
32
  size_t off = args[1]->Int32Value();
3129
32
  size_t len = args[2]->Int32Value();
3130
3131
16
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3132
    return env->ThrowRangeError("offset + length > buffer.length");
3133
3134
16
  if (!SSL_is_init_finished(conn->ssl_)) {
3135
    int rv;
3136
3137
10
    if (conn->is_server()) {
3138
10
      rv = SSL_accept(conn->ssl_);
3139
      conn->HandleSSLError("SSL_accept:ClearOut",
3140
                           rv,
3141
                           kZeroIsAnError,
3142
10
                           kSyscallError);
3143
    } else {
3144
      rv = SSL_connect(conn->ssl_);
3145
      conn->HandleSSLError("SSL_connect:ClearOut",
3146
                           rv,
3147
                           kZeroIsAnError,
3148
                           kSyscallError);
3149
    }
3150
3151
10
    if (rv < 0) {
3152
18
      return args.GetReturnValue().Set(rv);
3153
    }
3154
  }
3155
3156
7
  int bytes_read = SSL_read(conn->ssl_, buffer_data + off, len);
3157
  conn->HandleSSLError("SSL_read:ClearOut",
3158
                       bytes_read,
3159
                       kZeroIsNotAnError,
3160
7
                       kSyscallError);
3161
7
  conn->SetShutdownFlags();
3162
3163
14
  args.GetReturnValue().Set(bytes_read);
3164
}
3165
3166
3167
19
void Connection::ClearPending(const FunctionCallbackInfo<Value>& args) {
3168
  Connection* conn;
3169
38
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3170
19
  int bytes_pending = BIO_pending(conn->bio_read_);
3171
38
  args.GetReturnValue().Set(bytes_pending);
3172
}
3173
3174
3175
26
void Connection::EncPending(const FunctionCallbackInfo<Value>& args) {
3176
  Connection* conn;
3177
52
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3178
26
  int bytes_pending = BIO_pending(conn->bio_write_);
3179
52
  args.GetReturnValue().Set(bytes_pending);
3180
}
3181
3182
3183
21
void Connection::EncOut(const FunctionCallbackInfo<Value>& args) {
3184
  Connection* conn;
3185
21
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3186
21
  Environment* env = conn->env();
3187
3188
21
  if (args.Length() < 3) {
3189
    return env->ThrowTypeError(
3190
        "Data, offset, and length arguments are mandatory");
3191
  }
3192
3193
21
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3194
3195
21
  char* buffer_data = Buffer::Data(args[0]);
3196
21
  size_t buffer_length = Buffer::Length(args[0]);
3197
3198
42
  size_t off = args[1]->Int32Value();
3199
42
  size_t len = args[2]->Int32Value();
3200
3201
21
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3202
    return env->ThrowRangeError("offset + length > buffer.length");
3203
3204
21
  int bytes_read = BIO_read(conn->bio_write_, buffer_data + off, len);
3205
3206
21
  conn->HandleBIOError(conn->bio_write_, "BIO_read:EncOut", bytes_read);
3207
21
  conn->SetShutdownFlags();
3208
3209
42
  args.GetReturnValue().Set(bytes_read);
3210
}
3211
3212
3213
2
void Connection::ClearIn(const FunctionCallbackInfo<Value>& args) {
3214
  Connection* conn;
3215
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3216
2
  Environment* env = conn->env();
3217
3218
2
  if (args.Length() < 3) {
3219
    return env->ThrowTypeError(
3220
        "Data, offset, and length arguments are mandatory");
3221
  }
3222
3223
2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3224
3225
2
  char* buffer_data = Buffer::Data(args[0]);
3226
2
  size_t buffer_length = Buffer::Length(args[0]);
3227
3228
4
  size_t off = args[1]->Int32Value();
3229
4
  size_t len = args[2]->Int32Value();
3230
3231
2
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3232
    return env->ThrowRangeError("offset + length > buffer.length");
3233
3234
2
  if (!SSL_is_init_finished(conn->ssl_)) {
3235
    int rv;
3236
    if (conn->is_server()) {
3237
      rv = SSL_accept(conn->ssl_);
3238
      conn->HandleSSLError("SSL_accept:ClearIn",
3239
                           rv,
3240
                           kZeroIsAnError,
3241
                           kSyscallError);
3242
    } else {
3243
      rv = SSL_connect(conn->ssl_);
3244
      conn->HandleSSLError("SSL_connect:ClearIn",
3245
                           rv,
3246
                           kZeroIsAnError,
3247
                           kSyscallError);
3248
    }
3249
3250
    if (rv < 0) {
3251
      return args.GetReturnValue().Set(rv);
3252
    }
3253
  }
3254
3255
2
  int bytes_written = SSL_write(conn->ssl_, buffer_data + off, len);
3256
3257
  conn->HandleSSLError("SSL_write:ClearIn",
3258
                       bytes_written,
3259
                       len == 0 ? kZeroIsNotAnError : kZeroIsAnError,
3260
2
                       kSyscallError);
3261
2
  conn->SetShutdownFlags();
3262
3263
4
  args.GetReturnValue().Set(bytes_written);
3264
}
3265
3266
3267
16
void Connection::Start(const FunctionCallbackInfo<Value>& args) {
3268
  Connection* conn;
3269
32
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3270
3271
16
  int rv = 0;
3272
16
  if (!SSL_is_init_finished(conn->ssl_)) {
3273
16
    if (conn->is_server()) {
3274
12
      rv = SSL_accept(conn->ssl_);
3275
      conn->HandleSSLError("SSL_accept:Start",
3276
                           rv,
3277
                           kZeroIsAnError,
3278
12
                           kSyscallError);
3279
    } else {
3280
4
      rv = SSL_connect(conn->ssl_);
3281
      conn->HandleSSLError("SSL_connect:Start",
3282
                           rv,
3283
                           kZeroIsAnError,
3284
4
                           kSyscallError);
3285
    }
3286
  }
3287
32
  args.GetReturnValue().Set(rv);
3288
}
3289
3290
3291
10002
void Connection::Close(const FunctionCallbackInfo<Value>& args) {
3292
  Connection* conn;
3293
20004
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3294
10002
  conn->DestroySSL();
3295
}
3296
3297
3298
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3299
1
void Connection::GetServername(const FunctionCallbackInfo<Value>& args) {
3300
  Connection* conn;
3301
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3302
3303

2
  if (conn->is_server() && !conn->servername_.IsEmpty()) {
3304
    args.GetReturnValue().Set(conn->servername_);
3305
  } else {
3306
2
    args.GetReturnValue().Set(false);
3307
  }
3308
}
3309
3310
3311
2
void Connection::SetSNICallback(const FunctionCallbackInfo<Value>& args) {
3312
  Connection* conn;
3313
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3314
2
  Environment* env = conn->env();
3315
3316


8
  if (args.Length() < 1 || !args[0]->IsFunction()) {
3317
    return env->ThrowError("Must give a Function as first argument");
3318
  }
3319
3320
2
  Local<Object> obj = Object::New(env->isolate());
3321
4
  obj->Set(env->onselect_string(), args[0]);
3322
2
  conn->sniObject_.Reset(args.GetIsolate(), obj);
3323
}
3324
#endif
3325
3326
3327
407
void CipherBase::Initialize(Environment* env, Local<Object> target) {
3328
407
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3329
3330
814
  t->InstanceTemplate()->SetInternalFieldCount(1);
3331
3332
407
  env->SetProtoMethod(t, "init", Init);
3333
407
  env->SetProtoMethod(t, "initiv", InitIv);
3334
407
  env->SetProtoMethod(t, "update", Update);
3335
407
  env->SetProtoMethod(t, "final", Final);
3336
407
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
3337
407
  env->SetProtoMethod(t, "getAuthTag", GetAuthTag);
3338
407
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
3339
407
  env->SetProtoMethod(t, "setAAD", SetAAD);
3340
3341
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
3342
1221
              t->GetFunction());
3343
407
}
3344
3345
3346
1021
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
3347
1021
  CHECK(args.IsConstructCall());
3348
2042
  CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher;
3349
1021
  Environment* env = Environment::GetCurrent(args);
3350
1021
  new CipherBase(env, args.This(), kind);
3351
1021
}
3352
3353
3354
46
void CipherBase::Init(const char* cipher_type,
3355
                      const char* key_buf,
3356
                      int key_buf_len) {
3357
46
  HandleScope scope(env()->isolate());
3358
3359
#ifdef NODE_FIPS_MODE
3360
  if (FIPS_mode()) {
3361
    return env()->ThrowError(
3362
        "crypto.createCipher() is not supported in FIPS mode.");
3363
  }
3364
#endif  // NODE_FIPS_MODE
3365
3366
46
  CHECK_EQ(initialised_, false);
3367
46
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
3368
46
  if (cipher == nullptr) {
3369
46
    return env()->ThrowError("Unknown cipher");
3370
  }
3371
3372
  unsigned char key[EVP_MAX_KEY_LENGTH];
3373
  unsigned char iv[EVP_MAX_IV_LENGTH];
3374
3375
  int key_len = EVP_BytesToKey(cipher,
3376
                               EVP_md5(),
3377
                               nullptr,
3378
                               reinterpret_cast<const unsigned char*>(key_buf),
3379
                               key_buf_len,
3380
                               1,
3381
                               key,
3382
46
                               iv);
3383
3384
46
  EVP_CIPHER_CTX_init(&ctx_);
3385
46
  const bool encrypt = (kind_ == kCipher);
3386
46
  EVP_CipherInit_ex(&ctx_, cipher, nullptr, nullptr, nullptr, encrypt);
3387
3388
46
  int mode = EVP_CIPHER_CTX_mode(&ctx_);
3389


46
  if (encrypt && (mode == EVP_CIPH_CTR_MODE || mode == EVP_CIPH_GCM_MODE ||
3390
      mode == EVP_CIPH_CCM_MODE)) {
3391
    ProcessEmitWarning(env(), "Use Cipheriv for counter mode of %s",
3392
2
                       cipher_type);
3393
  }
3394
3395
46
  if (mode == EVP_CIPH_WRAP_MODE)
3396
2
    EVP_CIPHER_CTX_set_flags(&ctx_, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
3397
3398
46
  CHECK_EQ(1, EVP_CIPHER_CTX_set_key_length(&ctx_, key_len));
3399
3400
  EVP_CipherInit_ex(&ctx_,
3401
                    nullptr,
3402
                    nullptr,
3403
                    reinterpret_cast<unsigned char*>(key),
3404
                    reinterpret_cast<unsigned char*>(iv),
3405
46
                    kind_ == kCipher);
3406
46
  initialised_ = true;
3407
}
3408
3409
3410
46
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
3411
  CipherBase* cipher;
3412
46
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3413
46
  Environment* env = cipher->env();
3414
3415
46
  if (args.Length() < 2) {
3416
    return env->ThrowError("Cipher type and key arguments are mandatory");
3417
  }
3418
3419
138
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3420
46
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3421
3422
46
  const node::Utf8Value cipher_type(args.GetIsolate(), args[0]);
3423
46
  const char* key_buf = Buffer::Data(args[1]);
3424
46
  ssize_t key_buf_len = Buffer::Length(args[1]);
3425
46
  cipher->Init(*cipher_type, key_buf, key_buf_len);
3426
}
3427
3428
3429
975
void CipherBase::InitIv(const char* cipher_type,
3430
                        const char* key,
3431
                        int key_len,
3432
                        const char* iv,
3433
                        int iv_len) {
3434
975
  HandleScope scope(env()->isolate());
3435
3436
975
  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
3437
975
  if (cipher == nullptr) {
3438
    return env()->ThrowError("Unknown cipher");
3439
  }
3440
3441
975
  const int expected_iv_len = EVP_CIPHER_iv_length(cipher);
3442
975
  const int mode = EVP_CIPHER_mode(cipher);
3443
975
  const bool is_gcm_mode = (EVP_CIPH_GCM_MODE == mode);
3444
3445

975
  if (is_gcm_mode == false && iv_len != expected_iv_len) {
3446
510
    return env()->ThrowError("Invalid IV length");
3447
  }
3448
<