GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/out/../src/node_crypto.cc Lines: 2547 2788 91.4 %
Date: 2017-01-02 Branches: 1165 2148 54.2 %

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

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

1166
  if (args.Length() == 1 && args[0]->IsString()) {
344
65
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
345
346
    // Note that SSLv2 and SSLv3 are disallowed but SSLv2_method and friends
347
    // are still accepted.  They are OpenSSL's way of saying that all known
348
    // protocols are supported unless explicitly disabled (which we do below
349
    // for SSLv2 and SSLv3.)
350
36
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
351
7
      return env->ThrowError("SSLv2 methods disabled");
352
35
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
353
      return env->ThrowError("SSLv2 methods disabled");
354
34
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
355
      return env->ThrowError("SSLv2 methods disabled");
356
33
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
357
      return env->ThrowError("SSLv3 methods disabled");
358
32
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
359
      return env->ThrowError("SSLv3 methods disabled");
360
31
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
361
      return env->ThrowError("SSLv3 methods disabled");
362
30
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
363
1
      method = SSLv23_method();
364
29
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
365
1
      method = SSLv23_server_method();
366
28
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
367
1
      method = SSLv23_client_method();
368
27
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
369
3
      method = TLSv1_method();
370
24
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
371
1
      method = TLSv1_server_method();
372
23
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
373
1
      method = TLSv1_client_method();
374
22
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
375
2
      method = TLSv1_1_method();
376
20
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
377
1
      method = TLSv1_1_server_method();
378
19
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
379
1
      method = TLSv1_1_client_method();
380
18
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
381
14
      method = TLSv1_2_method();
382
4
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
383
2
      method = TLSv1_2_server_method();
384
2
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
385
1
      method = TLSv1_2_client_method();
386
    } else {
387
      return env->ThrowError("Unknown method");
388
    }
389
  }
390
391
540
  sc->ctx_ = SSL_CTX_new(method);
392
540
  SSL_CTX_set_app_data(sc->ctx_, sc);
393
394
  // Disable SSLv2 in the case when method == SSLv23_method() and the
395
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
396
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
397
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
398
540
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv2);
399
540
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv3);
400
401
  // SSL session cache configuration
402
540
  SSL_CTX_set_session_cache_mode(sc->ctx_,
403
                                 SSL_SESS_CACHE_SERVER |
404
                                 SSL_SESS_CACHE_NO_INTERNAL |
405
540
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
406
540
  SSL_CTX_sess_set_get_cb(sc->ctx_, SSLWrap<Connection>::GetSessionCallback);
407
540
  SSL_CTX_sess_set_new_cb(sc->ctx_, SSLWrap<Connection>::NewSessionCallback);
408
}
409
410
411
// Takes a string or buffer and loads it into a BIO.
412
// Caller responsible for BIO_free_all-ing the returned object.
413
589
static BIO* LoadBIO(Environment* env, Local<Value> v) {
414
1178
  HandleScope scope(env->isolate());
415
416
1178
  if (v->IsString()) {
417
94
    const node::Utf8Value s(env->isolate(), v);
418
47
    return NodeBIO::NewFixed(*s, s.length());
419
  }
420
421
542
  if (Buffer::HasInstance(v)) {
422
542
    return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
423
  }
424
425
  return nullptr;
426
}
427
428
429
236
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
430
236
  Environment* env = Environment::GetCurrent(args);
431
432
  SecureContext* sc;
433
246
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
434
435
236
  unsigned int len = args.Length();
436
236
  if (len < 1) {
437
    return env->ThrowError("Private key argument is mandatory");
438
  }
439
440
236
  if (len > 2) {
441
    return env->ThrowError("Only private key and pass phrase are expected");
442
  }
443
444
236
  if (len == 2) {
445

754
    if (args[1]->IsUndefined() || args[1]->IsNull())
446
      len = 1;
447
    else
448
46
      THROW_AND_RETURN_IF_NOT_STRING(args[1], "Pass phrase");
449
  }
450
451
234
  BIO *bio = LoadBIO(env, args[0]);
452
234
  if (!bio)
453
    return;
454
455
460
  node::Utf8Value passphrase(env->isolate(), args[1]);
456
457
234
  EVP_PKEY* key = PEM_read_bio_PrivateKey(bio,
458
                                          nullptr,
459
                                          CryptoPemCallback,
460
234
                                          len == 1 ? nullptr : *passphrase);
461
462
234
  if (!key) {
463
7
    BIO_free_all(bio);
464
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
465
7
    if (!err) {
466
      return env->ThrowError("PEM_read_bio_PrivateKey");
467
    }
468
7
    return ThrowCryptoError(env, err);
469
  }
470
471
227
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_, key);
472
227
  EVP_PKEY_free(key);
473
227
  BIO_free_all(bio);
474
475
227
  if (!rv) {
476
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
477
1
    if (!err)
478
      return env->ThrowError("SSL_CTX_use_PrivateKey");
479
1
    return ThrowCryptoError(env, err);
480
  }
481
}
482
483
484
236
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
485
  int ret;
486
487
236
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
488
  X509_STORE_CTX store_ctx;
489
490
236
  ret = X509_STORE_CTX_init(&store_ctx, store, nullptr, nullptr);
491
236
  if (!ret)
492
    goto end;
493
494
236
  ret = X509_STORE_CTX_get1_issuer(issuer, &store_ctx, cert);
495
236
  X509_STORE_CTX_cleanup(&store_ctx);
496
497
 end:
498
236
  return ret;
499
}
500
501
502
241
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
503
                                  X509* x,
504
                                  STACK_OF(X509)* extra_certs,
505
                                  X509** cert,
506
                                  X509** issuer) {
507
241
  CHECK_EQ(*issuer, nullptr);
508
241
  CHECK_EQ(*cert, nullptr);
509
510
241
  int ret = SSL_CTX_use_certificate(ctx, x);
511
512
241
  if (ret) {
513
    // If we could set up our certificate, now proceed to
514
    // the CA certificates.
515
    int r;
516
517
241
    SSL_CTX_clear_extra_chain_certs(ctx);
518
519
246
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
520
5
      X509* ca = sk_X509_value(extra_certs, i);
521
522
      // NOTE: Increments reference count on `ca`
523
5
      r = SSL_CTX_add1_chain_cert(ctx, ca);
524
525
5
      if (!r) {
526
        ret = 0;
527
        *issuer = nullptr;
528
        goto end;
529
      }
530
      // Note that we must not free r if it was successfully
531
      // added to the chain (while we must free the main
532
      // certificate, since its reference count is increased
533
      // by SSL_CTX_use_certificate).
534
535
      // Find issuer
536

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

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

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

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

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

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

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

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

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

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

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

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

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

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

97
  X509* cert = w->is_server() ? SSL_get_peer_certificate(w->ssl_) : nullptr;
1656
49
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_);
1657
49
  STACK_OF(X509)* peer_certs = nullptr;
1658

49
  if (cert == nullptr && ssl_certs == nullptr)
1659
    goto done;
1660
1661



48
  if (cert == nullptr && sk_X509_num(ssl_certs) == 0)
1662
    goto done;
1663
1664
  // Short result requested
1665



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

47
    result = X509ToObject(env,
1667
                          cert == nullptr ? sk_X509_value(ssl_certs, 0) : cert);
1668
47
    goto done;
1669
  }
1670
1671
  // Clone `ssl_certs`, because we are going to destruct it
1672
1
  peer_certs = sk_X509_new(nullptr);
1673

1
  if (cert != nullptr)
1674
    sk_X509_push(peer_certs, cert);
1675

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

2
    if (cert == nullptr)
1678
      goto done;
1679

2
    if (!sk_X509_push(peer_certs, cert))
1680
      goto done;
1681
  }
1682
1683
  // First and main certificate
1684
1
  cert = sk_X509_value(peer_certs, 0);
1685
1
  result = X509ToObject(env, cert);
1686
1
  info = result;
1687
1688
  // Put issuer inside the object
1689
1
  cert = sk_X509_delete(peer_certs, 0);
1690

1
  while (sk_X509_num(peer_certs) > 0) {
1691
    int i;
1692

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

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

1
    if (i == sk_X509_num(peer_certs))
1711
      break;
1712
  }
1713
1714
  // Last certificate should be self-signed
1715

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

1
  if (X509_check_issued(cert, cert) == X509_V_OK)
1733
3
    info->Set(env->issuercert_string(), info);
1734
1735

1
  CHECK_NE(cert, nullptr);
1736
1737
 done:
1738

49
  if (cert != nullptr)
1739
8
    X509_free(cert);
1740

49
  if (peer_certs != nullptr)
1741
1
    sk_X509_pop_free(peer_certs, X509_free);
1742

49
  if (result.IsEmpty())
1743
1
    result = Object::New(env->isolate());
1744
98
  args.GetReturnValue().Set(result);
1745
}
1746
1747
1748
template <class Base>
1749
106
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1750
106
  Environment* env = Environment::GetCurrent(args);
1751
1752
  Base* w;
1753

106
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1754
1755
106
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1756

106
  if (sess == nullptr)
1757
    return;
1758
1759
106
  int slen = i2d_SSL_SESSION(sess, nullptr);
1760

106
  CHECK_GT(slen, 0);
1761
1762
106
  char* sbuf = new char[slen];
1763
106
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1764
106
  i2d_SSL_SESSION(sess, &p);
1765
318
  args.GetReturnValue().Set(Encode(env->isolate(), sbuf, slen, BUFFER));
1766

106
  delete[] sbuf;
1767
}
1768
1769
1770
template <class Base>
1771
62
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1772
62
  Environment* env = Environment::GetCurrent(args);
1773
1774
  Base* w;
1775

62
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1776
1777

62
  if (args.Length() < 1) {
1778
    return env->ThrowError("Session argument is mandatory");
1779
  }
1780
1781

62
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Session");
1782
62
  size_t slen = Buffer::Length(args[0]);
1783
62
  char* sbuf = new char[slen];
1784
124
  memcpy(sbuf, Buffer::Data(args[0]), slen);
1785
1786
62
  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1787
62
  SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1788
1789

62
  delete[] sbuf;
1790
1791

62
  if (sess == nullptr)
1792
    return;
1793
1794
62
  int r = SSL_set_session(w->ssl_, sess);
1795
62
  SSL_SESSION_free(sess);
1796
1797

62
  if (!r)
1798
    return env->ThrowError("SSL_set_session error");
1799
}
1800
1801
1802
template <class Base>
1803
8
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1804
  Base* w;
1805

8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1806
13
  Environment* env = w->ssl_env();
1807
1808



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

5
    if (w->next_sess_ != nullptr)
1817
      SSL_SESSION_free(w->next_sess_);
1818
5
    w->next_sess_ = sess;
1819
1820
5
    Local<Object> info = Object::New(env->isolate());
1821
#ifndef OPENSSL_NO_TLSEXT
1822

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

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

16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1847
16
  w->hello_parser_.End();
1848
}
1849
1850
1851
template <class Base>
1852
1
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1853
  Base* w;
1854

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

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

9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1878
18
  Environment* env = w->ssl_env();
1879
1880
9
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1881


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

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

2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1908
2
  Environment* env = w->env();
1909
1910

2
  if (args.Length() < 1)
1911
    return env->ThrowTypeError("OCSP response argument is mandatory");
1912
1913

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

3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1926
1927
3
  SSL_set_tlsext_status_type(w->ssl_, TLSEXT_STATUSTYPE_ocsp);
1928
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1929
}
1930
1931
1932
template <class Base>
1933
288
void SSLWrap<Base>::GetEphemeralKeyInfo(
1934
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1935
  Base* w;
1936

288
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1937
288
  Environment* env = Environment::GetCurrent(args);
1938
1939

288
  CHECK_NE(w->ssl_, nullptr);
1940
1941
  // tmp key is available on only client
1942

576
  if (w->is_server())
1943
10
    return args.GetReturnValue().SetNull();
1944
1945
283
  Local<Object> info = Object::New(env->isolate());
1946
1947
  EVP_PKEY* key;
1948
1949

283
  if (SSL_get_server_tmp_key(w->ssl_, &key)) {
1950

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



9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
1982
1983
  Base* w;
1984

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

23
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1996
23
  bool yes = SSL_is_init_finished(w->ssl_);
1997
69
  args.GetReturnValue().Set(yes);
1998
}
1999
2000
2001
template <class Base>
2002
333
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2003
  Base* w;
2004

401
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2005
2006
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2007
  // peer certificate is questionable but it's compatible with what was
2008
  // here before.
2009
  long x509_verify_error =  // NOLINT(runtime/int)
2010
333
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2011

333
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
2012
330
    X509_free(peer_cert);
2013
330
    x509_verify_error = SSL_get_verify_result(w->ssl_);
2014
  }
2015
2016

333
  if (x509_verify_error == X509_V_OK)
2017
136
    return args.GetReturnValue().SetNull();
2018
2019
  // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
2020
  // in the presence of invalid error codes.  Probably academical but something
2021
  // to keep in mind if/when node ever grows multi-isolate capabilities.
2022
265
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2023
265
  const char* code = reason;
2024
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2025














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

10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2070
19
  Environment* env = w->ssl_env();
2071
2072
10
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
2073

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

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

554
  if (npn_buffer->IsUndefined()) {
2113
    // No initialization - no NPN protocols
2114
167
    *data = reinterpret_cast<const unsigned char*>("");
2115
167
    *len = 0;
2116
  } else {
2117

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

552
  if (npn_buffer->IsUndefined()) {
2144
    // We should at least select one protocol
2145
    // If server is using NPN
2146
255
    *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
2147
255
    *outlen = 8;
2148
2149
    // set status: unsupported
2150

1785
    CHECK(
2151
        w->object()->SetPrivate(
2152
            env->context(),
2153
            env->selected_npn_buffer_private_symbol(),
2154
            False(env->isolate())).FromJust());
2155
2156
    return SSL_TLSEXT_ERR_OK;
2157
  }
2158
2159

21
  CHECK(Buffer::HasInstance(npn_buffer));
2160
  const unsigned char* npn_protos =
2161
21
      reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2162
21
  size_t len = Buffer::Length(npn_buffer);
2163
2164
21
  int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
2165
21
  Local<Value> result;
2166


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

84
  CHECK(
2181
      w->object()->SetPrivate(
2182
          env->context(),
2183
          env->selected_npn_buffer_private_symbol(),
2184
          result).FromJust());
2185
2186
  return SSL_TLSEXT_ERR_OK;
2187
}
2188
2189
2190
template <class Base>
2191
603
void SSLWrap<Base>::GetNegotiatedProto(
2192
    const FunctionCallbackInfo<Value>& args) {
2193
  Base* w;
2194

934
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2195
603
  Environment* env = w->env();
2196
2197

1205
  if (w->is_client()) {
2198
    auto selected_npn_buffer =
2199
280
        w->object()->GetPrivate(
2200
            env->context(),
2201
1120
            env->selected_npn_buffer_private_symbol()).ToLocalChecked();
2202
280
    args.GetReturnValue().Set(selected_npn_buffer);
2203
    return;
2204
  }
2205
2206
  const unsigned char* npn_proto;
2207
  unsigned int npn_proto_len;
2208
2209
323
  SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
2210
2211

323
  if (!npn_proto)
2212
102
    return args.GetReturnValue().Set(false);
2213
2214
1088
  args.GetReturnValue().Set(
2215
      OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
2216
}
2217
2218
2219
template <class Base>
2220
143
void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
2221
  Base* w;
2222

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

143
  if (args.Length() < 1)
2226
    return env->ThrowTypeError("NPN protocols argument is mandatory");
2227
2228

143
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "NPN protocols");
2229
2230

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

13
  CHECK(Buffer::HasInstance(alpn_buffer));
2256
  const unsigned char* alpn_protos =
2257
13
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2258
13
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2259
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2260
13
                                     alpn_protos, alpn_protos_len, in, inlen);
2261
2262

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

1188
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2285
2286
  const unsigned char* alpn_proto;
2287
  unsigned int alpn_proto_len;
2288
2289
603
  SSL_get0_alpn_selected(w->ssl_, &alpn_proto, &alpn_proto_len);
2290
2291

603
  if (!alpn_proto)
2292
1170
    return args.GetReturnValue().Set(false);
2293
2294
72
  args.GetReturnValue().Set(
2295
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2296
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2297
}
2298
2299
2300
template <class Base>
2301
135
void SSLWrap<Base>::SetALPNProtocols(
2302
    const FunctionCallbackInfo<v8::Value>& args) {
2303
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2304
  Base* w;
2305

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



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

270
  if (w->is_client()) {
2311
    const unsigned char* alpn_protos =
2312
22
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2313
22
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2314
22
    int r = SSL_set_alpn_protos(w->ssl_, alpn_protos, alpn_protos_len);
2315

22
    CHECK_EQ(r, 0);
2316
  } else {
2317

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

13
  if (w->is_client()) {
2338
    // Incoming response
2339
    const unsigned char* resp;
2340
3
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2341
3
    Local<Value> arg;
2342

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

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

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

669
  if (!w->is_server())
2390
    return 1;
2391
2392

613
  if (!w->is_waiting_cert_cb())
2393
    return 1;
2394
2395

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

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

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

21
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2436
21
  Environment* env = w->env();
2437
2438



42
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2439
2440
42
  Local<Object> object = w->object();
2441
42
  Local<Value> ctx = object->Get(env->sni_context_string());
2442
21
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2443
2444
  // Not an object, probably undefined or null
2445

21
  if (!ctx->IsObject())
2446
    goto fire_cb;
2447
2448

10
  if (cons->HasInstance(ctx)) {
2449
    SecureContext* sc;
2450

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

9
    if (rv)
2463
9
      rv = SSL_use_certificate(w->ssl_, x509);
2464

9
    if (rv)
2465
8
      rv = SSL_use_PrivateKey(w->ssl_, pkey);
2466


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

9
    if (rv)
2469
8
      rv = w->SetCACerts(sc);
2470

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

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

4
  ASSIGN_OR_RETURN_UNWRAP(&base, info.This());
2503
  SSL* ssl = base->ssl_;
2504
  Local<External> ext = External::New(info.GetIsolate(), ssl);
2505
  info.GetReturnValue().Set(ext);
2506
}
2507
2508
2509
template <class Base>
2510
698
void SSLWrap<Base>::DestroySSL() {
2511

698
  if (ssl_ == nullptr)
2512
    return;
2513
2514
636
  SSL_free(ssl_);
2515
1272
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2516
636
  ssl_ = nullptr;
2517
}
2518
2519
2520
template <class Base>
2521
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2522
  InitNPN(sc);
2523
  CHECK_EQ(SSL_set_SSL_CTX(ssl_, sc->ctx_), sc->ctx_);
2524
2525
  SetCACerts(sc);
2526
}
2527
2528
2529
template <class Base>
2530
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2531
8
  int err = SSL_set1_verify_cert_store(ssl_, SSL_CTX_get_cert_store(sc->ctx_));
2532

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

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

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

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

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

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

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

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



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

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


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

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

51
  if (!initialised_ || !IsAuthenticatedMode())
3458
    return false;
3459
  int outlen;
3460
25
  if (!EVP_CipherUpdate(&ctx_,
3461
                        nullptr,
3462
                        &outlen,
3463
                        reinterpret_cast<const unsigned char*>(data),
3464
                        len)) {
3465
    return false;
3466
  }