GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/src/node_crypto.cc Lines: 2487 2758 90.2 %
Date: 2016-07-26 Branches: 1124 2154 52.2 %

Line 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::V8;
87
using v8::Value;
88
89
90
// Subject DER of CNNIC ROOT CA and CNNIC EV ROOT CA are taken from
91
// https://hg.mozilla.org/mozilla-central/file/98820360ab66/security/
92
// certverifier/NSSCertDBTrustDomain.cpp#l672
93
// C = CN, O = CNNIC, CN = CNNIC ROOT
94
static const uint8_t CNNIC_ROOT_CA_SUBJECT_DATA[] =
95
    "\x30\x32\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x43\x4E\x31\x0E\x30"
96
    "\x0C\x06\x03\x55\x04\x0A\x13\x05\x43\x4E\x4E\x49\x43\x31\x13\x30\x11\x06"
97
    "\x03\x55\x04\x03\x13\x0A\x43\x4E\x4E\x49\x43\x20\x52\x4F\x4F\x54";
98
static const uint8_t* cnnic_p = CNNIC_ROOT_CA_SUBJECT_DATA;
99
1567
static X509_NAME* cnnic_name =
100
1567
    d2i_X509_NAME(nullptr, &cnnic_p, sizeof(CNNIC_ROOT_CA_SUBJECT_DATA)-1);
101
102
// C = CN, O = China Internet Network Information Center, CN = China
103
// Internet Network Information Center EV Certificates Root
104
static const uint8_t CNNIC_EV_ROOT_CA_SUBJECT_DATA[] =
105
    "\x30\x81\x8A\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x43\x4E\x31\x32"
106
    "\x30\x30\x06\x03\x55\x04\x0A\x0C\x29\x43\x68\x69\x6E\x61\x20\x49\x6E\x74"
107
    "\x65\x72\x6E\x65\x74\x20\x4E\x65\x74\x77\x6F\x72\x6B\x20\x49\x6E\x66\x6F"
108
    "\x72\x6D\x61\x74\x69\x6F\x6E\x20\x43\x65\x6E\x74\x65\x72\x31\x47\x30\x45"
109
    "\x06\x03\x55\x04\x03\x0C\x3E\x43\x68\x69\x6E\x61\x20\x49\x6E\x74\x65\x72"
110
    "\x6E\x65\x74\x20\x4E\x65\x74\x77\x6F\x72\x6B\x20\x49\x6E\x66\x6F\x72\x6D"
111
    "\x61\x74\x69\x6F\x6E\x20\x43\x65\x6E\x74\x65\x72\x20\x45\x56\x20\x43\x65"
112
    "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x73\x20\x52\x6F\x6F\x74";
113
static const uint8_t* cnnic_ev_p = CNNIC_EV_ROOT_CA_SUBJECT_DATA;
114
1567
static X509_NAME *cnnic_ev_name =
115
1567
    d2i_X509_NAME(nullptr, &cnnic_ev_p,
116
                  sizeof(CNNIC_EV_ROOT_CA_SUBJECT_DATA)-1);
117
118
static Mutex* mutexes;
119
120
const char* const root_certs[] = {
121
#include "node_root_certs.h"  // NOLINT(build/include_order)
122
};
123
124
X509_STORE* root_cert_store;
125
126
// Just to generate static methods
127
template class SSLWrap<TLSWrap>;
128
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
129
                                           Local<FunctionTemplate> t);
130
template void SSLWrap<TLSWrap>::InitNPN(SecureContext* sc);
131
template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc);
132
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
133
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
134
    SSL* s,
135
    unsigned char* key,
136
    int len,
137
    int* copy);
138
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
139
                                                  SSL_SESSION* sess);
140
template void SSLWrap<TLSWrap>::OnClientHello(
141
    void* arg,
142
    const ClientHelloParser::ClientHello& hello);
143
144
#ifdef OPENSSL_NPN_NEGOTIATED
145
template int SSLWrap<TLSWrap>::AdvertiseNextProtoCallback(
146
    SSL* s,
147
    const unsigned char** data,
148
    unsigned int* len,
149
    void* arg);
150
template int SSLWrap<TLSWrap>::SelectNextProtoCallback(
151
    SSL* s,
152
    unsigned char** out,
153
    unsigned char* outlen,
154
    const unsigned char* in,
155
    unsigned int inlen,
156
    void* arg);
157
#endif
158
159
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
160
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
161
#endif
162
163
template void SSLWrap<TLSWrap>::DestroySSL();
164
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
165
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
166
167
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
168
template int SSLWrap<TLSWrap>::SelectALPNCallback(
169
    SSL* s,
170
    const unsigned char** out,
171
    unsigned char* outlen,
172
    const unsigned char* in,
173
    unsigned int inlen,
174
    void* arg);
175
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
176
177
42906
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
178
  static_assert(sizeof(uv_thread_t) <= sizeof(void*),
179
                "uv_thread_t does not fit in a pointer");
180
42906
  CRYPTO_THREADID_set_pointer(tid, reinterpret_cast<void*>(uv_thread_self()));
181
42906
}
182
183
184
182
static void crypto_lock_init(void) {
185
182
  mutexes = new Mutex[CRYPTO_num_locks()];
186
182
}
187
188
189
1043744
static void crypto_lock_cb(int mode, int n, const char* file, int line) {
190
1043744
  CHECK(!(mode & CRYPTO_LOCK) ^ !(mode & CRYPTO_UNLOCK));
191
1043744
  CHECK(!(mode & CRYPTO_READ) ^ !(mode & CRYPTO_WRITE));
192
193
1043744
  auto mutex = &mutexes[n];
194
1043744
  if (mode & CRYPTO_LOCK)
195
    mutex->Lock();
196
  else
197
    mutex->Unlock();
198
1043744
}
199
200
201
16
static int CryptoPemCallback(char *buf, int size, int rwflag, void *u) {
202
16
  if (u) {
203
16
    size_t buflen = static_cast<size_t>(size);
204
16
    size_t len = strlen(static_cast<const char*>(u));
205
16
    len = len > buflen ? buflen : len;
206
16
    memcpy(buf, u, len);
207
16
    return len;
208
  }
209
210
  return 0;
211
}
212
213
214
22
void ThrowCryptoError(Environment* env,
215
                      unsigned long err,  // NOLINT(runtime/int)
216
                      const char* default_message = nullptr) {
217
44
  HandleScope scope(env->isolate());
218
22
  if (err != 0 || default_message == nullptr) {
219
16
    char errmsg[128] = { 0 };
220
16
    ERR_error_string_n(err, errmsg, sizeof(errmsg));
221
16
    env->ThrowError(errmsg);
222
  } else {
223
    env->ThrowError(default_message);
224
  }
225
22
}
226
227
228
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
229
// The entropy pool starts out empty and needs to fill up before the PRNG
230
// can be used securely.  Once the pool is filled, it never dries up again;
231
// its contents is stirred and reused when necessary.
232
//
233
// OpenSSL normally fills the pool automatically but not when someone starts
234
// generating random numbers before the pool is full: in that case OpenSSL
235
// keeps lowering the entropy estimate to thwart attackers trying to guess
236
// the initial state of the PRNG.
237
//
238
// When that happens, we will have to wait until enough entropy is available.
239
// That should normally never take longer than a few milliseconds.
240
//
241
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
242
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
243
// block under normal circumstances.
244
//
245
// The only time when /dev/urandom may conceivably block is right after boot,
246
// when the whole system is still low on entropy.  That's not something we can
247
// do anything about.
248
3158
inline void CheckEntropy() {
249
  for (;;) {
250
3158
    int status = RAND_status();
251
3158
    CHECK_GE(status, 0);  // Cannot fail.
252
3158
    if (status != 0)
253
      break;
254
255
    // Give up, RAND_poll() not supported.
256
    if (RAND_poll() == 0)
257
      break;
258
  }
259
3158
}
260
261
262
3116
bool EntropySource(unsigned char* buffer, size_t length) {
263
  // Ensure that OpenSSL's PRNG is properly seeded.
264
3116
  CheckEntropy();
265
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
266
  // random. That's okay, it's still better than V8's stock source of entropy,
267
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
268
3116
  return RAND_bytes(buffer, length) != -1;
269
}
270
271
272
182
void SecureContext::Initialize(Environment* env, Local<Object> target) {
273
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(SecureContext::New);
274
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
275
182
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"));
276
277
182
  env->SetProtoMethod(t, "init", SecureContext::Init);
278
182
  env->SetProtoMethod(t, "setKey", SecureContext::SetKey);
279
182
  env->SetProtoMethod(t, "setCert", SecureContext::SetCert);
280
182
  env->SetProtoMethod(t, "addCACert", SecureContext::AddCACert);
281
182
  env->SetProtoMethod(t, "addCRL", SecureContext::AddCRL);
282
182
  env->SetProtoMethod(t, "addRootCerts", SecureContext::AddRootCerts);
283
182
  env->SetProtoMethod(t, "setCiphers", SecureContext::SetCiphers);
284
182
  env->SetProtoMethod(t, "setECDHCurve", SecureContext::SetECDHCurve);
285
182
  env->SetProtoMethod(t, "setDHParam", SecureContext::SetDHParam);
286
182
  env->SetProtoMethod(t, "setOptions", SecureContext::SetOptions);
287
  env->SetProtoMethod(t, "setSessionIdContext",
288
182
                      SecureContext::SetSessionIdContext);
289
  env->SetProtoMethod(t, "setSessionTimeout",
290
182
                      SecureContext::SetSessionTimeout);
291
182
  env->SetProtoMethod(t, "close", SecureContext::Close);
292
182
  env->SetProtoMethod(t, "loadPKCS12", SecureContext::LoadPKCS12);
293
182
  env->SetProtoMethod(t, "getTicketKeys", SecureContext::GetTicketKeys);
294
182
  env->SetProtoMethod(t, "setTicketKeys", SecureContext::SetTicketKeys);
295
182
  env->SetProtoMethod(t, "setFreeListLength", SecureContext::SetFreeListLength);
296
  env->SetProtoMethod(t,
297
                      "enableTicketKeyCallback",
298
182
                      SecureContext::EnableTicketKeyCallback);
299
182
  env->SetProtoMethod(t, "getCertificate", SecureContext::GetCertificate<true>);
300
182
  env->SetProtoMethod(t, "getIssuer", SecureContext::GetCertificate<false>);
301
302
728
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyReturnIndex"),
303
182
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyReturnIndex));
304
728
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyHMACIndex"),
305
182
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyHMACIndex));
306
728
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyAESIndex"),
307
182
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyAESIndex));
308
728
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyNameIndex"),
309
182
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyNameIndex));
310
728
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyIVIndex"),
311
182
         Integer::NewFromUnsigned(env->isolate(), kTicketKeyIVIndex));
312
313
910
  t->PrototypeTemplate()->SetAccessor(
314
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
315
      CtxGetter,
316
      nullptr,
317
      env->as_external(),
318
      DEFAULT,
319
      static_cast<PropertyAttribute>(ReadOnly | DontDelete),
320
182
      AccessorSignature::New(env->isolate(), t));
321
322
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"),
323
182
              t->GetFunction());
324
182
  env->set_secure_context_constructor_template(t);
325
182
}
326
327
328
505
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
329
505
  Environment* env = Environment::GetCurrent(args);
330
505
  new SecureContext(env, args.This());
331
505
}
332
333
334
505
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
335
  SecureContext* sc;
336
505
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
337
505
  Environment* env = sc->env();
338
339
505
  const SSL_METHOD* method = SSLv23_method();
340
341
1082
  if (args.Length() == 1 && args[0]->IsString()) {
342
65
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
343
344
    // Note that SSLv2 and SSLv3 are disallowed but SSLv2_method and friends
345
    // are still accepted.  They are OpenSSL's way of saying that all known
346
    // protocols are supported unless explicitly disabled (which we do below
347
    // for SSLv2 and SSLv3.)
348
36
    if (strcmp(*sslmethod, "SSLv2_method") == 0) {
349
7
      return env->ThrowError("SSLv2 methods disabled");
350
35
    } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
351
      return env->ThrowError("SSLv2 methods disabled");
352
34
    } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
353
      return env->ThrowError("SSLv2 methods disabled");
354
33
    } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
355
      return env->ThrowError("SSLv3 methods disabled");
356
32
    } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
357
      return env->ThrowError("SSLv3 methods disabled");
358
31
    } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
359
      return env->ThrowError("SSLv3 methods disabled");
360
30
    } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
361
1
      method = SSLv23_method();
362
29
    } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
363
1
      method = SSLv23_server_method();
364
28
    } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
365
1
      method = SSLv23_client_method();
366
27
    } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
367
3
      method = TLSv1_method();
368
24
    } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
369
1
      method = TLSv1_server_method();
370
23
    } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
371
1
      method = TLSv1_client_method();
372
22
    } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
373
2
      method = TLSv1_1_method();
374
20
    } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
375
1
      method = TLSv1_1_server_method();
376
19
    } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
377
1
      method = TLSv1_1_client_method();
378
18
    } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
379
14
      method = TLSv1_2_method();
380
4
    } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
381
2
      method = TLSv1_2_server_method();
382
2
    } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
383
1
      method = TLSv1_2_client_method();
384
    } else {
385
      return env->ThrowError("Unknown method");
386
    }
387
  }
388
389
498
  sc->ctx_ = SSL_CTX_new(method);
390
498
  SSL_CTX_set_app_data(sc->ctx_, sc);
391
392
  // Disable SSLv2 in the case when method == SSLv23_method() and the
393
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
394
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
395
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
396
498
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv2);
397
498
  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv3);
398
399
  // SSL session cache configuration
400
498
  SSL_CTX_set_session_cache_mode(sc->ctx_,
401
                                 SSL_SESS_CACHE_SERVER |
402
                                 SSL_SESS_CACHE_NO_INTERNAL |
403
498
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
404
498
  SSL_CTX_sess_set_get_cb(sc->ctx_, SSLWrap<Connection>::GetSessionCallback);
405
498
  SSL_CTX_sess_set_new_cb(sc->ctx_, SSLWrap<Connection>::NewSessionCallback);
406
407
498
  sc->ca_store_ = nullptr;
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
525
static BIO* LoadBIO(Environment* env, Local<Value> v) {
414
1050
  HandleScope scope(env->isolate());
415
416
1050
  if (v->IsString()) {
417
60
    const node::Utf8Value s(env->isolate(), v);
418
30
    return NodeBIO::NewFixed(*s, s.length());
419
  }
420
421
495
  if (Buffer::HasInstance(v)) {
422
495
    return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
423
  }
424
425
  return nullptr;
426
}
427
428
429
206
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
430
206
  Environment* env = Environment::GetCurrent(args);
431
432
  SecureContext* sc;
433
210
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
434
435
206
  unsigned int len = args.Length();
436
206
  if (len < 1) {
437
    return env->ThrowError("Private key argument is mandatory");
438
  }
439
440
206
  if (len > 2) {
441
    return env->ThrowError("Only private key and pass phrase are expected");
442
  }
443
444
206
  if (len == 2) {
445
10
    THROW_AND_RETURN_IF_NOT_STRING(args[1], "Pass phrase");
446
  }
447
448
204
  BIO *bio = LoadBIO(env, args[0]);
449
204
  if (!bio)
450
    return;
451
452
406
  node::Utf8Value passphrase(env->isolate(), args[1]);
453
454
204
  EVP_PKEY* key = PEM_read_bio_PrivateKey(bio,
455
                                          nullptr,
456
                                          CryptoPemCallback,
457
204
                                          len == 1 ? nullptr : *passphrase);
458
459
204
  if (!key) {
460
1
    BIO_free_all(bio);
461
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
462
1
    if (!err) {
463
      return env->ThrowError("PEM_read_bio_PrivateKey");
464
    }
465
1
    return ThrowCryptoError(env, err);
466
  }
467
468
203
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_, key);
469
203
  EVP_PKEY_free(key);
470
203
  BIO_free_all(bio);
471
472
203
  if (!rv) {
473
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
474
1
    if (!err)
475
      return env->ThrowError("SSL_CTX_use_PrivateKey");
476
1
    return ThrowCryptoError(env, err);
477
  }
478
}
479
480
481
206
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
482
  int ret;
483
484
206
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
485
  X509_STORE_CTX store_ctx;
486
487
206
  ret = X509_STORE_CTX_init(&store_ctx, store, nullptr, nullptr);
488
206
  if (!ret)
489
    goto end;
490
491
206
  ret = X509_STORE_CTX_get1_issuer(issuer, &store_ctx, cert);
492
206
  X509_STORE_CTX_cleanup(&store_ctx);
493
494
 end:
495
206
  return ret;
496
}
497
498
499
211
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
500
                                  X509* x,
501
                                  STACK_OF(X509)* extra_certs,
502
                                  X509** cert,
503
                                  X509** issuer) {
504
211
  CHECK_EQ(*issuer, nullptr);
505
211
  CHECK_EQ(*cert, nullptr);
506
507
211
  int ret = SSL_CTX_use_certificate(ctx, x);
508
509
211
  if (ret) {
510
    // If we could set up our certificate, now proceed to
511
    // the CA certificates.
512
    int r;
513
514
211
    SSL_CTX_clear_extra_chain_certs(ctx);
515
516
216
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
517
5
      X509* ca = sk_X509_value(extra_certs, i);
518
519
      // NOTE: Increments reference count on `ca`
520
5
      r = SSL_CTX_add1_chain_cert(ctx, ca);
521
522
5
      if (!r) {
523
        ret = 0;
524
        *issuer = nullptr;
525
        goto end;
526
      }
527
      // Note that we must not free r if it was successfully
528
      // added to the chain (while we must free the main
529
      // certificate, since its reference count is increased
530
      // by SSL_CTX_use_certificate).
531
532
      // Find issuer
533
5
      if (*issuer != nullptr || X509_check_issued(ca, x) != X509_V_OK)
534
        continue;
535
536
5
      *issuer = ca;
537
    }
538
  }
539
540
  // Try getting issuer from a cert store
541
211
  if (ret) {
542
211
    if (*issuer == nullptr) {
543
206
      ret = SSL_CTX_get_issuer(ctx, x, issuer);
544
206
      ret = ret < 0 ? 0 : 1;
545
      // NOTE: get_cert_store doesn't increment reference count,
546
      // no need to free `store`
547
    } else {
548
      // Increment issuer reference count
549
5
      *issuer = X509_dup(*issuer);
550
5
      if (*issuer == nullptr) {
551
        ret = 0;
552
        goto end;
553
      }
554
    }
555
  }
556
557
 end:
558
211
  if (ret && x != nullptr) {
559
211
    *cert = X509_dup(x);
560
211
    if (*cert == nullptr)
561
      ret = 0;
562
  }
563
211
  return ret;
564
}
565
566
567
// Read a file that contains our certificate in "PEM" format,
568
// possibly followed by a sequence of CA certificates that should be
569
// sent to the peer in the Certificate message.
570
//
571
// Taken from OpenSSL - edited for style.
572
204
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
573
                                  BIO* in,
574
                                  X509** cert,
575
                                  X509** issuer) {
576
204
  X509* x = nullptr;
577
578
  // Just to ensure that `ERR_peek_last_error` below will return only errors
579
  // that we are interested in
580
204
  ERR_clear_error();
581
582
204
  x = PEM_read_bio_X509_AUX(in, nullptr, CryptoPemCallback, nullptr);
583
584
204
  if (x == nullptr) {
585
    SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
586
    return 0;
587
  }
588
589
204
  X509* extra = nullptr;
590
204
  int ret = 0;
591
204
  unsigned long err = 0;  // NOLINT(runtime/int)
592
593
  // Read extra certs
594
204
  STACK_OF(X509)* extra_certs = sk_X509_new_null();
595
204
  if (extra_certs == nullptr) {
596
    SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_MALLOC_FAILURE);
597
    goto done;
598
  }
599
600
206
  while ((extra = PEM_read_bio_X509(in, nullptr, CryptoPemCallback, nullptr))) {
601
2
    if (sk_X509_push(extra_certs, extra))
602
      continue;
603
604
    // Failure, free all certs
605
    goto done;
606
  }
607
204
  extra = nullptr;
608
609
  // When the while loop ends, it's usually just EOF.
610
204
  err = ERR_peek_last_error();
611
408
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
612
204
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
613
204
    ERR_clear_error();
614
  } else  {
615
    // some real error
616
    goto done;
617
  }
618
619
204
  ret = SSL_CTX_use_certificate_chain(ctx, x, extra_certs, cert, issuer);
620
  if (!ret)
621
    goto done;
622
623
 done:
624
204
  if (extra_certs != nullptr)
625
204
    sk_X509_pop_free(extra_certs, X509_free);
626
204
  if (extra != nullptr)
627
    X509_free(extra);
628
204
  if (x != nullptr)
629
204
    X509_free(x);
630
631
  return ret;
632
}
633
634
635
204
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
636
204
  Environment* env = Environment::GetCurrent(args);
637
638
  SecureContext* sc;
639
204
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
640
641
204
  if (args.Length() != 1) {
642
    return env->ThrowTypeError("Certificate argument is mandatory");
643
  }
644
645
204
  BIO* bio = LoadBIO(env, args[0]);
646
204
  if (!bio)
647
    return;
648
649
  // Free previous certs
650
204
  if (sc->issuer_ != nullptr) {
651
    X509_free(sc->issuer_);
652
    sc->issuer_ = nullptr;
653
  }
654
204
  if (sc->cert_ != nullptr) {
655
1
    X509_free(sc->cert_);
656
1
    sc->cert_ = nullptr;
657
  }
658
659
204
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_,
660
                                         bio,
661
                                         &sc->cert_,
662
204
                                         &sc->issuer_);
663
664
204
  BIO_free_all(bio);
665
666
204
  if (!rv) {
667
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
668
    if (!err) {
669
      return env->ThrowError("SSL_CTX_use_certificate_chain");
670
    }
671
    return ThrowCryptoError(env, err);
672
  }
673
}
674
675
676
89
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
677
89
  bool newCAStore = false;
678
89
  Environment* env = Environment::GetCurrent(args);
679
680
  SecureContext* sc;
681
89
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
682
  ClearErrorOnReturn clear_error_on_return;
683
  (void) &clear_error_on_return;  // Silence compiler warning.
684
685
89
  if (args.Length() != 1) {
686
    return env->ThrowTypeError("CA certificate argument is mandatory");
687
  }
688
689
89
  if (!sc->ca_store_) {
690
75
    sc->ca_store_ = X509_STORE_new();
691
75
    newCAStore = true;
692
  }
693
694
89
  unsigned cert_count = 0;
695
89
  if (BIO* bio = LoadBIO(env, args[0])) {
696
91
    while (X509* x509 =
697
180
        PEM_read_bio_X509(bio, nullptr, CryptoPemCallback, nullptr)) {
698
91
      X509_STORE_add_cert(sc->ca_store_, x509);
699
91
      SSL_CTX_add_client_CA(sc->ctx_, x509);
700
91
      X509_free(x509);
701
91
      cert_count += 1;
702
    }
703
89
    BIO_free_all(bio);
704
  }
705
706
89
  if (cert_count > 0 && newCAStore) {
707
74
    SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
708
  }
709
}
710
711
712
6
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
713
6
  Environment* env = Environment::GetCurrent(args);
714
715
  SecureContext* sc;
716
6
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
717
718
6
  if (args.Length() != 1) {
719
    return env->ThrowTypeError("CRL argument is mandatory");
720
  }
721
722
  ClearErrorOnReturn clear_error_on_return;
723
  (void) &clear_error_on_return;  // Silence compiler warning.
724
725
6
  BIO *bio = LoadBIO(env, args[0]);
726
6
  if (!bio)
727
    return;
728
729
  X509_CRL *x509 =
730
6
      PEM_read_bio_X509_CRL(bio, nullptr, CryptoPemCallback, nullptr);
731
732
6
  if (x509 == nullptr) {
733
    BIO_free_all(bio);
734
    return;
735
  }
736
737
6
  X509_STORE_add_crl(sc->ca_store_, x509);
738
6
  X509_STORE_set_flags(sc->ca_store_, X509_V_FLAG_CRL_CHECK |
739
6
                                      X509_V_FLAG_CRL_CHECK_ALL);
740
6
  BIO_free_all(bio);
741
6
  X509_CRL_free(x509);
742
}
743
744
745
746
420
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
747
  SecureContext* sc;
748
420
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
749
  ClearErrorOnReturn clear_error_on_return;
750
  (void) &clear_error_on_return;  // Silence compiler warning.
751
752
420
  CHECK_EQ(sc->ca_store_, nullptr);
753
754
420
  if (!root_cert_store) {
755
124
    root_cert_store = X509_STORE_new();
756
757
18724
    for (size_t i = 0; i < arraysize(root_certs); i++) {
758
18600
      BIO* bp = NodeBIO::NewFixed(root_certs[i], strlen(root_certs[i]));
759
18600
      if (bp == nullptr) {
760
        return;
761
      }
762
763
18600
      X509 *x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr);
764
18600
      if (x509 == nullptr) {
765
        BIO_free_all(bp);
766
        return;
767
      }
768
769
18600
      X509_STORE_add_cert(root_cert_store, x509);
770
771
18600
      BIO_free_all(bp);
772
18600
      X509_free(x509);
773
    }
774
  }
775
776
420
  sc->ca_store_ = root_cert_store;
777
420
  SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
778
}
779
780
781
495
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
782
  SecureContext* sc;
783
497
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
784
495
  Environment* env = sc->env();
785
  ClearErrorOnReturn clear_error_on_return;
786
  (void) &clear_error_on_return;  // Silence compiler warning.
787
788
495
  if (args.Length() != 1) {
789
    return env->ThrowTypeError("Ciphers argument is mandatory");
790
  }
791
792
990
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Ciphers");
793
794
1479
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
795
493
  SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
796
}
797
798
799
491
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
800
  SecureContext* sc;
801
492
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
802
491
  Environment* env = sc->env();
803
804
491
  if (args.Length() != 1)
805
    return env->ThrowTypeError("ECDH curve name argument is mandatory");
806
807
982
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "ECDH curve name");
808
809
980
  node::Utf8Value curve(env->isolate(), args[0]);
810
811
490
  int nid = OBJ_sn2nid(*curve);
812
813
490
  if (nid == NID_undef)
814
    return env->ThrowTypeError("First argument should be a valid curve name");
815
816
490
  EC_KEY* ecdh = EC_KEY_new_by_curve_name(nid);
817
818
490
  if (ecdh == nullptr)
819
    return env->ThrowTypeError("First argument should be a valid curve name");
820
821
490
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_ECDH_USE);
822
490
  SSL_CTX_set_tmp_ecdh(sc->ctx_, ecdh);
823
824
490
  EC_KEY_free(ecdh);
825
}
826
827
828
9
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
829
  SecureContext* sc;
830
9
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
831
9
  Environment* env = sc->env();
832
  ClearErrorOnReturn clear_error_on_return;
833
  (void) &clear_error_on_return;  // Silence compiler warning.
834
835
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
836
  // to be specifed explicitly
837
9
  if (args.Length() != 1)
838
    return env->ThrowTypeError("DH argument is mandatory");
839
840
  // Invalid dhparam is silently discarded and DHE is no longer used.
841
9
  BIO* bio = LoadBIO(env, args[0]);
842
9
  if (!bio)
843
    return;
844
845
9
  DH* dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
846
9
  BIO_free_all(bio);
847
848
9
  if (dh == nullptr)
849
    return;
850
851
8
  const int size = BN_num_bits(dh->p);
852
8
  if (size < 1024) {
853
    return env->ThrowError("DH parameter is less than 1024 bits");
854
6
  } else if (size < 2048) {
855
6
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
856
        env->isolate(), "WARNING: DH parameter is less than 2048 bits"));
857
  }
858
859
6
  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE);
860
6
  int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh);
861
6
  DH_free(dh);
862
863
6
  if (!r)
864
    return env->ThrowTypeError("Error setting temp DH parameter");
865
}
866
867
868
178
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
869
  SecureContext* sc;
870
178
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
871
872
534
  if (args.Length() != 1 || !args[0]->IntegerValue()) {
873
    return sc->env()->ThrowTypeError("Options must be an integer value");
874
  }
875
876
178
  SSL_CTX_set_options(
877
      sc->ctx_,
878
178
      static_cast<long>(args[0]->IntegerValue()));  // NOLINT(runtime/int)
879
}
880
881
882
173
void SecureContext::SetSessionIdContext(
883
    const FunctionCallbackInfo<Value>& args) {
884
  SecureContext* sc;
885
346
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
886
173
  Environment* env = sc->env();
887
888
173
  if (args.Length() != 1) {
889
    return env->ThrowTypeError("Session ID context argument is mandatory");
890
  }
891
892
346
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Session ID context");
893
894
346
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
895
  const unsigned char* sid_ctx =
896
173
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
897
173
  unsigned int sid_ctx_len = sessionIdContext.length();
898
899
173
  int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
900
173
  if (r == 1)
901
    return;
902
903
  BIO* bio;
904
  BUF_MEM* mem;
905
  Local<String> message;
906
907
  bio = BIO_new(BIO_s_mem());
908
  if (bio == nullptr) {
909
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
910
                                    "SSL_CTX_set_session_id_context error");
911
  } else {
912
    ERR_print_errors(bio);
913
    BIO_get_mem_ptr(bio, &mem);
914
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
915
    BIO_free_all(bio);
916
  }
917
918
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
919
}
920
921
922
1
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
923
  SecureContext* sc;
924
1
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
925
926
3
  if (args.Length() != 1 || !args[0]->IsInt32()) {
927
1
    return sc->env()->ThrowTypeError(
928
        "Session timeout must be a 32-bit integer");
929
  }
930
931
  int32_t sessionTimeout = args[0]->Int32Value();
932
  SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
933
}
934
935
936
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
937
  SecureContext* sc;
938
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
939
  sc->FreeCTXMem();
940
}
941
942
943
// Takes .pfx or .p12 and password in string or buffer format
944
13
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
945
13
  Environment* env = Environment::GetCurrent(args);
946
947
13
  BIO* in = nullptr;
948
13
  PKCS12* p12 = nullptr;
949
13
  EVP_PKEY* pkey = nullptr;
950
13
  X509* cert = nullptr;
951
13
  STACK_OF(X509)* extra_certs = nullptr;
952
13
  char* pass = nullptr;
953
13
  bool ret = false;
954
955
  SecureContext* sc;
956
19
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
957
  ClearErrorOnReturn clear_error_on_return;
958
  (void) &clear_error_on_return;  // Silence compiler warning.
959
960
13
  if (args.Length() < 1) {
961
    return env->ThrowTypeError("PFX certificate argument is mandatory");
962
  }
963
964
13
  in = LoadBIO(env, args[0]);
965
13
  if (in == nullptr) {
966
    return env->ThrowError("Unable to load BIO");
967
  }
968
969
13
  if (args.Length() >= 2) {
970
11
    THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Pass phrase");
971
11
    size_t passlen = Buffer::Length(args[1]);
972
11
    pass = new char[passlen + 1];
973
22
    memcpy(pass, Buffer::Data(args[1]), passlen);
974
11
    pass[passlen] = '\0';
975
  }
976
977
  // Free previous certs
978
13
  if (sc->issuer_ != nullptr) {
979
    X509_free(sc->issuer_);
980
    sc->issuer_ = nullptr;
981
  }
982
13
  if (sc->cert_ != nullptr) {
983
    X509_free(sc->cert_);
984
    sc->cert_ = nullptr;
985
  }
986
987
37
  if (d2i_PKCS12_bio(in, &p12) &&
988
18
      PKCS12_parse(p12, pass, &pkey, &cert, &extra_certs) &&
989
7
      SSL_CTX_use_certificate_chain(sc->ctx_,
990
                                    cert,
991
                                    extra_certs,
992
                                    &sc->cert_,
993
20
                                    &sc->issuer_) &&
994
7
      SSL_CTX_use_PrivateKey(sc->ctx_, pkey)) {
995
    // Add CA certs too
996
13
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
997
3
      X509* ca = sk_X509_value(extra_certs, i);
998
999
3
      if (!sc->ca_store_) {
1000
        sc->ca_store_ = X509_STORE_new();
1001
        SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
1002
      }
1003
3
      X509_STORE_add_cert(sc->ca_store_, ca);
1004
3
      SSL_CTX_add_client_CA(sc->ctx_, ca);
1005
    }
1006
    ret = true;
1007
  }
1008
1009
13
  if (pkey != nullptr)
1010
7
    EVP_PKEY_free(pkey);
1011
13
  if (cert != nullptr)
1012
7
    X509_free(cert);
1013
13
  if (extra_certs != nullptr)
1014
3
    sk_X509_pop_free(extra_certs, X509_free);
1015
1016
13
  PKCS12_free(p12);
1017
13
  BIO_free_all(in);
1018
13
  delete[] pass;
1019
1020
13
  if (!ret) {
1021
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1022
6
    const char* str = ERR_reason_error_string(err);
1023
    return env->ThrowError(str);
1024
  }
1025
}
1026
1027
1028
7
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1029
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1030
1031
  SecureContext* wrap;
1032
7
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1033
1034
14
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1035
7
  if (SSL_CTX_get_tlsext_ticket_keys(wrap->ctx_,
1036
                                     Buffer::Data(buff),
1037
                                     Buffer::Length(buff)) != 1) {
1038
    return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
1039
  }
1040
1041
7
  args.GetReturnValue().Set(buff);
1042
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1043
}
1044
1045
1046
16
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1047
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1048
  SecureContext* wrap;
1049
16
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1050
16
  Environment* env = wrap->env();
1051
1052
16
  if (args.Length() < 1) {
1053
    return env->ThrowTypeError("Ticket keys argument is mandatory");
1054
  }
1055
1056
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Ticket keys");
1057
1058
15
  if (Buffer::Length(args[0]) != 48) {
1059
    return env->ThrowTypeError("Ticket keys length must be 48 bytes");
1060
  }
1061
1062
28
  if (SSL_CTX_set_tlsext_ticket_keys(wrap->ctx_,
1063
                                     Buffer::Data(args[0]),
1064
                                     Buffer::Length(args[0])) != 1) {
1065
    return env->ThrowError("Failed to fetch tls ticket keys");
1066
  }
1067
1068
28
  args.GetReturnValue().Set(true);
1069
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1070
}
1071
1072
1073
274
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1074
  SecureContext* wrap;
1075
274
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1076
1077
548
  wrap->ctx_->freelist_max_len = args[0]->Int32Value();
1078
}
1079
1080
1081
1
void SecureContext::EnableTicketKeyCallback(
1082
    const FunctionCallbackInfo<Value>& args) {
1083
  SecureContext* wrap;
1084
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1085
1086
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_, TicketKeyCallback);
1087
}
1088
1089
1090
3
int SecureContext::TicketKeyCallback(SSL* ssl,
1091
                                     unsigned char* name,
1092
                                     unsigned char* iv,
1093
                                     EVP_CIPHER_CTX* ectx,
1094
                                     HMAC_CTX* hctx,
1095
                                     int enc) {
1096
  static const int kTicketPartSize = 16;
1097
1098
  SecureContext* sc = static_cast<SecureContext*>(
1099
3
      SSL_CTX_get_app_data(ssl->ctx));
1100
1101
3
  Environment* env = sc->env();
1102
6
  HandleScope handle_scope(env->isolate());
1103
9
  Context::Scope context_scope(env->context());
1104
1105
  Local<Value> argv[] = {
1106
3
    Buffer::Copy(env,
1107
                 reinterpret_cast<char*>(name),
1108
                 kTicketPartSize).ToLocalChecked(),
1109
3
    Buffer::Copy(env,
1110
                 reinterpret_cast<char*>(iv),
1111
                 kTicketPartSize).ToLocalChecked(),
1112
    Boolean::New(env->isolate(), enc != 0)
1113
18
  };
1114
  Local<Value> ret = node::MakeCallback(env,
1115
                                        sc->object(),
1116
                                        env->ticketkeycallback_string(),
1117
3
                                        arraysize(argv),
1118
9
                                        argv);
1119
3
  Local<Array> arr = ret.As<Array>();
1120
1121
6
  int r = arr->Get(kTicketKeyReturnIndex)->Int32Value();
1122
3
  if (r < 0)
1123
    return r;
1124
1125
3
  Local<Value> hmac = arr->Get(kTicketKeyHMACIndex);
1126
3
  Local<Value> aes = arr->Get(kTicketKeyAESIndex);
1127
3
  if (Buffer::Length(aes) != kTicketPartSize)
1128
    return -1;
1129
1130
3
  if (enc) {
1131
2
    Local<Value> name_val = arr->Get(kTicketKeyNameIndex);
1132
2
    Local<Value> iv_val = arr->Get(kTicketKeyIVIndex);
1133
1134
4
    if (Buffer::Length(name_val) != kTicketPartSize ||
1135
2
        Buffer::Length(iv_val) != kTicketPartSize) {
1136
      return -1;
1137
    }
1138
1139
4
    memcpy(name, Buffer::Data(name_val), kTicketPartSize);
1140
4
    memcpy(iv, Buffer::Data(iv_val), kTicketPartSize);
1141
  }
1142
1143
6
  HMAC_Init_ex(hctx,
1144
3
               Buffer::Data(hmac),
1145
3
               Buffer::Length(hmac),
1146
               EVP_sha256(),
1147
3
               nullptr);
1148
1149
  const unsigned char* aes_key =
1150
3
      reinterpret_cast<unsigned char*>(Buffer::Data(aes));
1151
3
  if (enc) {
1152
2
    EVP_EncryptInit_ex(ectx,
1153
                       EVP_aes_128_cbc(),
1154
                       nullptr,
1155
                       aes_key,
1156
2
                       iv);
1157
  } else {
1158
1
    EVP_DecryptInit_ex(ectx,
1159
                       EVP_aes_128_cbc(),
1160
                       nullptr,
1161
                       aes_key,
1162
1
                       iv);
1163
  }
1164
1165
  return r;
1166
}
1167
1168
1169
1170
1171
2
void SecureContext::CtxGetter(Local<String> property,
1172
                              const PropertyCallbackInfo<Value>& info) {
1173
  SecureContext* sc;
1174
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1175
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_);
1176
4
  info.GetReturnValue().Set(ext);
1177
}
1178
1179
1180
template <bool primary>
1181
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1182
  SecureContext* wrap;
1183
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1184
6
  Environment* env = wrap->env();
1185
  X509* cert;
1186
1187
  if (primary)
1188
3
    cert = wrap->cert_;
1189
  else
1190
3
    cert = wrap->issuer_;
1191
6
  if (cert == nullptr)
1192
    return args.GetReturnValue().Set(Null(env->isolate()));
1193
1194
6
  int size = i2d_X509(cert, nullptr);
1195
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1196
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1197
6
      Buffer::Data(buff));
1198
6
  i2d_X509(cert, &serialized);
1199
1200
12
  args.GetReturnValue().Set(buff);
1201
}
1202
1203
1204
template <class Base>
1205
321
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1206
642
  HandleScope scope(env->isolate());
1207
1208
321
  env->SetProtoMethod(t, "getPeerCertificate", GetPeerCertificate);
1209
321
  env->SetProtoMethod(t, "getSession", GetSession);
1210
321
  env->SetProtoMethod(t, "setSession", SetSession);
1211
321
  env->SetProtoMethod(t, "loadSession", LoadSession);
1212
321
  env->SetProtoMethod(t, "isSessionReused", IsSessionReused);
1213
321
  env->SetProtoMethod(t, "isInitFinished", IsInitFinished);
1214
321
  env->SetProtoMethod(t, "verifyError", VerifyError);
1215
321
  env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
1216
321
  env->SetProtoMethod(t, "endParser", EndParser);
1217
321
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1218
321
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1219
321
  env->SetProtoMethod(t, "shutdownSSL", Shutdown);
1220
321
  env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket);
1221
321
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1222
321
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1223
321
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1224
321
  env->SetProtoMethod(t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
1225
321
  env->SetProtoMethod(t, "getProtocol", GetProtocol);
1226
1227
#ifdef SSL_set_max_send_fragment
1228
321
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1229
#endif  // SSL_set_max_send_fragment
1230
1231
#ifdef OPENSSL_NPN_NEGOTIATED
1232
321
  env->SetProtoMethod(t, "getNegotiatedProtocol", GetNegotiatedProto);
1233
#endif  // OPENSSL_NPN_NEGOTIATED
1234
1235
#ifdef OPENSSL_NPN_NEGOTIATED
1236
321
  env->SetProtoMethod(t, "setNPNProtocols", SetNPNProtocols);
1237
#endif
1238
1239
321
  env->SetProtoMethod(t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
1240
321
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1241
1242
1605
  t->PrototypeTemplate()->SetAccessor(
1243
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
1244
      SSLGetter,
1245
      nullptr,
1246
      env->as_external(),
1247
      DEFAULT,
1248
      static_cast<PropertyAttribute>(ReadOnly | DontDelete),
1249
      AccessorSignature::New(env->isolate(), t));
1250
321
}
1251
1252
1253
template <class Base>
1254
599
void SSLWrap<Base>::InitNPN(SecureContext* sc) {
1255
#ifdef OPENSSL_NPN_NEGOTIATED
1256
  // Server should advertise NPN protocols
1257
599
  SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
1258
                                        AdvertiseNextProtoCallback,
1259
                                        nullptr);
1260
  // Client should select protocol from list of advertised
1261
  // If server supports NPN
1262
599
  SSL_CTX_set_next_proto_select_cb(sc->ctx_, SelectNextProtoCallback, nullptr);
1263
#endif  // OPENSSL_NPN_NEGOTIATED
1264
1265
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1266
  // OCSP stapling
1267
599
  SSL_CTX_set_tlsext_status_cb(sc->ctx_, TLSExtStatusCallback);
1268
599
  SSL_CTX_set_tlsext_status_arg(sc->ctx_, nullptr);
1269
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1270
599
}
1271
1272
1273
template <class Base>
1274
6
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1275
                                               unsigned char* key,
1276
                                               int len,
1277
                                               int* copy) {
1278
6
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1279
1280
6
  *copy = 0;
1281
6
  SSL_SESSION* sess = w->next_sess_;
1282
6
  w->next_sess_ = nullptr;
1283
1284
6
  return sess;
1285
}
1286
1287
1288
template <class Base>
1289
5
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1290
5
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1291
10
  Environment* env = w->ssl_env();
1292
10
  HandleScope handle_scope(env->isolate());
1293
15
  Context::Scope context_scope(env->context());
1294
1295
5
  if (!w->session_callbacks_)
1296
    return 0;
1297
1298
  // Check if session is small enough to be stored
1299
2
  int size = i2d_SSL_SESSION(sess, nullptr);
1300
2
  if (size > SecureContext::kMaxSessionSize)
1301
    return 0;
1302
1303
  // Serialize session
1304
4
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1305
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1306
2
      Buffer::Data(buff));
1307
4
  memset(serialized, 0, size);
1308
2
  i2d_SSL_SESSION(sess, &serialized);
1309
1310
2
  Local<Object> session = Buffer::Copy(
1311
      env,
1312
      reinterpret_cast<char*>(sess->session_id),
1313
4
      sess->session_id_length).ToLocalChecked();
1314
6
  Local<Value> argv[] = { session, buff };
1315
2
  w->new_session_wait_ = true;
1316
4
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1317
1318
2
  return 0;
1319
}
1320
1321
1322
template <class Base>
1323
17
void SSLWrap<Base>::OnClientHello(void* arg,
1324
                                  const ClientHelloParser::ClientHello& hello) {
1325
17
  Base* w = static_cast<Base*>(arg);
1326
31
  Environment* env = w->ssl_env();
1327
34
  HandleScope handle_scope(env->isolate());
1328
51
  Context::Scope context_scope(env->context());
1329
1330
17
  Local<Object> hello_obj = Object::New(env->isolate());
1331
17
  Local<Object> buff = Buffer::Copy(
1332
      env,
1333
17
      reinterpret_cast<const char*>(hello.session_id()),
1334
51
      hello.session_size()).ToLocalChecked();
1335
51
  hello_obj->Set(env->session_id_string(), buff);
1336
17
  if (hello.servername() == nullptr) {
1337
15
    hello_obj->Set(env->servername_string(), String::Empty(env->isolate()));
1338
  } else {
1339
14
    Local<String> servername = OneByteString(env->isolate(),
1340
                                             hello.servername(),
1341
28
                                             hello.servername_size());
1342
42
    hello_obj->Set(env->servername_string(), servername);
1343
  }
1344
85
  hello_obj->Set(env->tls_ticket_string(),
1345
17
                 Boolean::New(env->isolate(), hello.has_ticket()));
1346
85
  hello_obj->Set(env->ocsp_request_string(),
1347
17
                 Boolean::New(env->isolate(), hello.ocsp_request()));
1348
1349
34
  Local<Value> argv[] = { hello_obj };
1350
34
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1351
17
}
1352
1353
1354
25
static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1355
25
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1356
1357
25
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1358
    return false;
1359
1360
2
  const unsigned char* p = ext->value->data;
1361
2
  GENERAL_NAMES* names = reinterpret_cast<GENERAL_NAMES*>(ASN1_item_d2i(
1362
      NULL,
1363
      &p,
1364
2
      ext->value->length,
1365
4
      ASN1_ITEM_ptr(method->it)));
1366
2
  if (names == NULL)
1367
    return false;
1368
1369
14
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1370
6
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1371
1372
6
    if (i != 0)
1373
4
      BIO_write(out, ", ", 2);
1374
1375
6
    if (gen->type == GEN_DNS) {
1376
3
      ASN1_IA5STRING* name = gen->d.dNSName;
1377
1378
3
      BIO_write(out, "DNS:", 4);
1379
3
      BIO_write(out, name->data, name->length);
1380
    } else {
1381
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1382
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, NULL);
1383
3
      if (nval == NULL)
1384
        return false;
1385
3
      X509V3_EXT_val_prn(out, nval, 0, 0);
1386
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1387
    }
1388
  }
1389
2
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1390
1391
2
  return true;
1392
}
1393
1394
1395
46
static Local<Object> X509ToObject(Environment* env, X509* cert) {
1396
92
  EscapableHandleScope scope(env->isolate());
1397
1398
46
  Local<Object> info = Object::New(env->isolate());
1399
1400
46
  BIO* bio = BIO_new(BIO_s_mem());
1401
  BUF_MEM* mem;
1402
46
  if (X509_NAME_print_ex(bio,
1403
                         X509_get_subject_name(cert),
1404
                         0,
1405
                         X509_NAME_FLAGS) > 0) {
1406
46
    BIO_get_mem_ptr(bio, &mem);
1407
276
    info->Set(env->subject_string(),
1408
46
              String::NewFromUtf8(env->isolate(), mem->data,
1409
92
                                  String::kNormalString, mem->length));
1410
  }
1411
46
  (void) BIO_reset(bio);
1412
1413
46
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1414
46
  if (X509_NAME_print_ex(bio, issuer_name, 0, X509_NAME_FLAGS) > 0) {
1415
46
    BIO_get_mem_ptr(bio, &mem);
1416
276
    info->Set(env->issuer_string(),
1417
46
              String::NewFromUtf8(env->isolate(), mem->data,
1418
92
                                  String::kNormalString, mem->length));
1419
  }
1420
46
  (void) BIO_reset(bio);
1421
1422
46
  int nids[] = { NID_subject_alt_name, NID_info_access };
1423
  Local<String> keys[] = { env->subjectaltname_string(),
1424
138
                           env->infoaccess_string() };
1425
46
  CHECK_EQ(arraysize(nids), arraysize(keys));
1426
138
  for (size_t i = 0; i < arraysize(nids); i++) {
1427
92
    int index = X509_get_ext_by_NID(cert, nids[i], -1);
1428
92
    if (index < 0)
1429
      continue;
1430
1431
    X509_EXTENSION* ext;
1432
    int rv;
1433
1434
25
    ext = X509_get_ext(cert, index);
1435
25
    CHECK_NE(ext, nullptr);
1436
1437
25
    if (!SafeX509ExtPrint(bio, ext)) {
1438
23
      rv = X509V3_EXT_print(bio, ext, 0, 0);
1439
23
      CHECK_EQ(rv, 1);
1440
    }
1441
1442
25
    BIO_get_mem_ptr(bio, &mem);
1443
125
    info->Set(keys[i],
1444
25
              String::NewFromUtf8(env->isolate(), mem->data,
1445
50
                                  String::kNormalString, mem->length));
1446
1447
25
    (void) BIO_reset(bio);
1448
  }
1449
1450
46
  EVP_PKEY* pkey = X509_get_pubkey(cert);
1451
46
  RSA* rsa = nullptr;
1452
46
  if (pkey != nullptr)
1453
46
    rsa = EVP_PKEY_get1_RSA(pkey);
1454
1455
46
  if (rsa != nullptr) {
1456
45
      BN_print(bio, rsa->n);
1457
45
      BIO_get_mem_ptr(bio, &mem);
1458
270
      info->Set(env->modulus_string(),
1459
45
                String::NewFromUtf8(env->isolate(), mem->data,
1460
90
                                    String::kNormalString, mem->length));
1461
45
      (void) BIO_reset(bio);
1462
1463
45
      BN_ULONG exponent_word = BN_get_word(rsa->e);
1464
45
      BIO_printf(bio, "0x%lx", exponent_word);
1465
1466
45
      BIO_get_mem_ptr(bio, &mem);
1467
270
      info->Set(env->exponent_string(),
1468
45
                String::NewFromUtf8(env->isolate(), mem->data,
1469
90
                                    String::kNormalString, mem->length));
1470
45
      (void) BIO_reset(bio);
1471
  }
1472
1473
46
  if (pkey != nullptr) {
1474
46
    EVP_PKEY_free(pkey);
1475
46
    pkey = nullptr;
1476
  }
1477
46
  if (rsa != nullptr) {
1478
45
    RSA_free(rsa);
1479
45
    rsa = nullptr;
1480
  }
1481
1482
46
  ASN1_TIME_print(bio, X509_get_notBefore(cert));
1483
46
  BIO_get_mem_ptr(bio, &mem);
1484
276
  info->Set(env->valid_from_string(),
1485
46
            String::NewFromUtf8(env->isolate(), mem->data,
1486
92
                                String::kNormalString, mem->length));
1487
46
  (void) BIO_reset(bio);
1488
1489
46
  ASN1_TIME_print(bio, X509_get_notAfter(cert));
1490
46
  BIO_get_mem_ptr(bio, &mem);
1491
276
  info->Set(env->valid_to_string(),
1492
46
            String::NewFromUtf8(env->isolate(), mem->data,
1493
92
                                String::kNormalString, mem->length));
1494
46
  BIO_free_all(bio);
1495
1496
  unsigned int md_size, i;
1497
  unsigned char md[EVP_MAX_MD_SIZE];
1498
46
  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1499
46
    const char hex[] = "0123456789ABCDEF";
1500
    char fingerprint[EVP_MAX_MD_SIZE * 3];
1501
1502
    // TODO(indutny): Unify it with buffer's code
1503
966
    for (i = 0; i < md_size; i++) {
1504
920
      fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1505
920
      fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1506
920
      fingerprint[(3*i)+2] = ':';
1507
    }
1508
1509
46
    if (md_size > 0) {
1510
46
      fingerprint[(3*(md_size-1))+2] = '\0';
1511
    } else {
1512
      fingerprint[0] = '\0';
1513
    }
1514
1515
230
    info->Set(env->fingerprint_string(),
1516
46
              OneByteString(env->isolate(), fingerprint));
1517
  }
1518
1519
  STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
1520
46
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr));
1521
46
  if (eku != nullptr) {
1522
1
    Local<Array> ext_key_usage = Array::New(env->isolate());
1523
    char buf[256];
1524
1525
1
    int j = 0;
1526
2
    for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1527
1
      if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku, i), 1) >= 0)
1528
3
        ext_key_usage->Set(j++, OneByteString(env->isolate(), buf));
1529
    }
1530
1531
1
    sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1532
3
    info->Set(env->ext_key_usage_string(), ext_key_usage);
1533
  }
1534
1535
46
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1536
46
    if (BIGNUM* bn = ASN1_INTEGER_to_BN(serial_number, nullptr)) {
1537
46
      if (char* buf = BN_bn2hex(bn)) {
1538
230
        info->Set(env->serial_number_string(),
1539
46
                  OneByteString(env->isolate(), buf));
1540
46
        OPENSSL_free(buf);
1541
      }
1542
46
      BN_free(bn);
1543
    }
1544
  }
1545
1546
  // Raw DER certificate
1547
46
  int size = i2d_X509(cert, nullptr);
1548
92
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1549
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1550
46
      Buffer::Data(buff));
1551
46
  i2d_X509(cert, &serialized);
1552
138
  info->Set(env->raw_string(), buff);
1553
1554
92
  return scope.Escape(info);
1555
}
1556
1557
1558
// TODO(indutny): Split it into multiple smaller functions
1559
template <class Base>
1560
46
void SSLWrap<Base>::GetPeerCertificate(
1561
    const FunctionCallbackInfo<Value>& args) {
1562
  Base* w;
1563
46
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1564
91
  Environment* env = w->ssl_env();
1565
1566
  ClearErrorOnReturn clear_error_on_return;
1567
  (void) &clear_error_on_return;  // Silence unused variable warning.
1568
1569
46
  Local<Object> result;
1570
46
  Local<Object> info;
1571
1572
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1573
  // contains the `peer_certificate`, but on server it doesn't
1574
91
  X509* cert = w->is_server() ? SSL_get_peer_certificate(w->ssl_) : nullptr;
1575
46
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_);
1576
46
  STACK_OF(X509)* peer_certs = nullptr;
1577
46
  if (cert == nullptr && ssl_certs == nullptr)
1578
    goto done;
1579
1580
45
  if (cert == nullptr && sk_X509_num(ssl_certs) == 0)
1581
    goto done;
1582
1583
  // Short result requested
1584
135
  if (args.Length() < 1 || !args[0]->IsTrue()) {
1585
44
    result = X509ToObject(env,
1586
                          cert == nullptr ? sk_X509_value(ssl_certs, 0) : cert);
1587
44
    goto done;
1588
  }
1589
1590
  // Clone `ssl_certs`, because we are going to destruct it
1591
1
  peer_certs = sk_X509_new(nullptr);
1592
1
  if (cert != nullptr)
1593
    sk_X509_push(peer_certs, cert);
1594
5
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
1595
2
    cert = X509_dup(sk_X509_value(ssl_certs, i));
1596
2
    if (cert == nullptr)
1597
      goto done;
1598
2
    if (!sk_X509_push(peer_certs, cert))
1599
      goto done;
1600
  }
1601
1602
  // First and main certificate
1603
1
  cert = sk_X509_value(peer_certs, 0);
1604
1
  result = X509ToObject(env, cert);
1605
1
  info = result;
1606
1607
  // Put issuer inside the object
1608
1
  cert = sk_X509_delete(peer_certs, 0);
1609
1
  while (sk_X509_num(peer_certs) > 0) {
1610
    int i;
1611
1
    for (i = 0; i < sk_X509_num(peer_certs); i++) {
1612
1
      X509* ca = sk_X509_value(peer_certs, i);
1613
1
      if (X509_check_issued(ca, cert) != X509_V_OK)
1614
        continue;
1615
1616
1
      Local<Object> ca_info = X509ToObject(env, ca);
1617
3
      info->Set(env->issuercert_string(), ca_info);
1618
1
      info = ca_info;
1619
1620
      // NOTE: Intentionally freeing cert that is not used anymore
1621
1
      X509_free(cert);
1622
1623
      // Delete cert and continue aggregating issuers
1624
1
      cert = sk_X509_delete(peer_certs, i);
1625
1
      break;
1626
    }
1627
1628
    // Issuer not found, break out of the loop
1629
1
    if (i == sk_X509_num(peer_certs))
1630
      break;
1631
  }
1632
1633
  // Last certificate should be self-signed
1634
1
  while (X509_check_issued(cert, cert) != X509_V_OK) {
1635
    X509* ca;
1636
    if (SSL_CTX_get_issuer(w->ssl_->ctx, cert, &ca) <= 0)
1637
      break;
1638
1639
    Local<Object> ca_info = X509ToObject(env, ca);
1640
    info->Set(env->issuercert_string(), ca_info);
1641
    info = ca_info;
1642
1643
    // NOTE: Intentionally freeing cert that is not used anymore
1644
    X509_free(cert);
1645
1646
    // Delete cert and continue aggregating issuers
1647
    cert = ca;
1648
  }
1649
1650
  // Self-issued certificate
1651
1
  if (X509_check_issued(cert, cert) == X509_V_OK)
1652
3
    info->Set(env->issuercert_string(), info);
1653
1654
1
  CHECK_NE(cert, nullptr);
1655
1656
 done:
1657
46
  if (cert != nullptr)
1658
8
    X509_free(cert);
1659
46
  if (peer_certs != nullptr)
1660
1
    sk_X509_pop_free(peer_certs, X509_free);
1661
46
  if (result.IsEmpty())
1662
1
    result = Object::New(env->isolate());
1663
92
  args.GetReturnValue().Set(result);
1664
}
1665
1666
1667
template <class Base>
1668
105
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1669
105
  Environment* env = Environment::GetCurrent(args);
1670
1671
  Base* w;
1672
105
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1673
1674
105
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1675
105
  if (sess == nullptr)
1676
    return;
1677
1678
105
  int slen = i2d_SSL_SESSION(sess, nullptr);
1679
105
  CHECK_GT(slen, 0);
1680
1681
105
  char* sbuf = new char[slen];
1682
105
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1683
105
  i2d_SSL_SESSION(sess, &p);
1684
315
  args.GetReturnValue().Set(Encode(env->isolate(), sbuf, slen, BUFFER));
1685
105
  delete[] sbuf;
1686
}
1687
1688
1689
template <class Base>
1690
62
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1691
62
  Environment* env = Environment::GetCurrent(args);
1692
1693
  Base* w;
1694
62
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1695
1696
62
  if (args.Length() < 1) {
1697
    return env->ThrowError("Session argument is mandatory");
1698
  }
1699
1700
62
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Session");
1701
62
  size_t slen = Buffer::Length(args[0]);
1702
62
  char* sbuf = new char[slen];
1703
124
  memcpy(sbuf, Buffer::Data(args[0]), slen);
1704
1705
62
  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1706
62
  SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1707
1708
62
  delete[] sbuf;
1709
1710
62
  if (sess == nullptr)
1711
    return;
1712
1713
62
  int r = SSL_set_session(w->ssl_, sess);
1714
62
  SSL_SESSION_free(sess);
1715
1716
62
  if (!r)
1717
    return env->ThrowError("SSL_set_session error");
1718
}
1719
1720
1721
template <class Base>
1722
8
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1723
  Base* w;
1724
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1725
13
  Environment* env = w->ssl_env();
1726
1727
16
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1728
5
    ssize_t slen = Buffer::Length(args[0]);
1729
5
    char* sbuf = Buffer::Data(args[0]);
1730
1731
5
    const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1732
5
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1733
1734
    // Setup next session and move hello to the BIO buffer
1735
5
    if (w->next_sess_ != nullptr)
1736
      SSL_SESSION_free(w->next_sess_);
1737
5
    w->next_sess_ = sess;
1738
1739
5
    Local<Object> info = Object::New(env->isolate());
1740
#ifndef OPENSSL_NO_TLSEXT
1741
5
    if (sess->tlsext_hostname == nullptr) {
1742
      info->Set(env->servername_string(), False(args.GetIsolate()));
1743
    } else {
1744
20
      info->Set(env->servername_string(),
1745
5
                OneByteString(args.GetIsolate(), sess->tlsext_hostname));
1746
    }
1747
#endif
1748
10
    args.GetReturnValue().Set(info);
1749
  }
1750
}
1751
1752
1753
template <class Base>
1754
56
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1755
  Base* w;
1756
56
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1757
56
  bool yes = SSL_session_reused(w->ssl_);
1758
168
  args.GetReturnValue().Set(yes);
1759
}
1760
1761
1762
template <class Base>
1763
16
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
1764
  Base* w;
1765
16
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1766
16
  w->hello_parser_.End();
1767
}
1768
1769
1770
template <class Base>
1771
1
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1772
  Base* w;
1773
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1774
1775
  ClearErrorOnReturn clear_error_on_return;
1776
  (void) &clear_error_on_return;  // Silence unused variable warning.
1777
1778
1
  bool yes = SSL_renegotiate(w->ssl_) == 1;
1779
3
  args.GetReturnValue().Set(yes);
1780
}
1781
1782
1783
template <class Base>
1784
2
void SSLWrap<Base>::Shutdown(const FunctionCallbackInfo<Value>& args) {
1785
  Base* w;
1786
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1787
1788
2
  int rv = SSL_shutdown(w->ssl_);
1789
4
  args.GetReturnValue().Set(rv);
1790
}
1791
1792
1793
template <class Base>
1794
9
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1795
  Base* w;
1796
9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1797
18
  Environment* env = w->ssl_env();
1798
1799
9
  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1800
9
  if (sess == nullptr || sess->tlsext_tick == nullptr)
1801
    return;
1802
1803
9
  Local<Object> buff = Buffer::Copy(
1804
      env,
1805
      reinterpret_cast<char*>(sess->tlsext_tick),
1806
18
      sess->tlsext_ticklen).ToLocalChecked();
1807
1808
9
  args.GetReturnValue().Set(buff);
1809
}
1810
1811
1812
template <class Base>
1813
2
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1814
  Base* w;
1815
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1816
2
  w->new_session_wait_ = false;
1817
2
  w->NewSessionDoneCb();
1818
}
1819
1820
1821
template <class Base>
1822
2
void SSLWrap<Base>::SetOCSPResponse(
1823
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1824
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1825
  Base* w;
1826
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1827
2
  Environment* env = w->env();
1828
1829
2
  if (args.Length() < 1)
1830
    return env->ThrowTypeError("OCSP response argument is mandatory");
1831
1832
2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "OCSP response");
1833
1834
6
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
1835
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1836
}
1837
1838
1839
template <class Base>
1840
3
void SSLWrap<Base>::RequestOCSP(
1841
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1842
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1843
  Base* w;
1844
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1845
1846
3
  SSL_set_tlsext_status_type(w->ssl_, TLSEXT_STATUSTYPE_ocsp);
1847
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1848
}
1849
1850
1851
template <class Base>
1852
263
void SSLWrap<Base>::GetEphemeralKeyInfo(
1853
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1854
  Base* w;
1855
263
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1856
263
  Environment* env = Environment::GetCurrent(args);
1857
1858
263
  CHECK_NE(w->ssl_, nullptr);
1859
1860
  // tmp key is available on only client
1861
526
  if (w->is_server())
1862
10
    return args.GetReturnValue().SetNull();
1863
1864
258
  Local<Object> info = Object::New(env->isolate());
1865
1866
  EVP_PKEY* key;
1867
1868
258
  if (SSL_get_server_tmp_key(w->ssl_, &key)) {
1869
223
    switch (EVP_PKEY_id(key)) {
1870
      case EVP_PKEY_DH:
1871
24
        info->Set(env->type_string(),
1872
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH"));
1873
24
        info->Set(env->size_string(),
1874
                  Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1875
6
        break;
1876
      case EVP_PKEY_EC:
1877
        {
1878
217
          EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
1879
217
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
1880
217
          EC_KEY_free(ec);
1881
868
          info->Set(env->type_string(),
1882
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"));
1883
1085
          info->Set(env->name_string(),
1884
                    OneByteString(args.GetIsolate(), OBJ_nid2sn(nid)));
1885
868
          info->Set(env->size_string(),
1886
                    Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1887
        }
1888
    }
1889
223
    EVP_PKEY_free(key);
1890
  }
1891
1892
258
  return args.GetReturnValue().Set(info);
1893
}
1894
1895
1896
#ifdef SSL_set_max_send_fragment
1897
template <class Base>
1898
3
void SSLWrap<Base>::SetMaxSendFragment(
1899
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1900
9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
1901
1902
  Base* w;
1903
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1904
1905
3
  int rv = SSL_set_max_send_fragment(w->ssl_, args[0]->Int32Value());
1906
6
  args.GetReturnValue().Set(rv);
1907
}
1908
#endif  // SSL_set_max_send_fragment
1909
1910
1911
template <class Base>
1912
23
void SSLWrap<Base>::IsInitFinished(const FunctionCallbackInfo<Value>& args) {
1913
  Base* w;
1914
23
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1915
23
  bool yes = SSL_is_init_finished(w->ssl_);
1916
69
  args.GetReturnValue().Set(yes);
1917
}
1918
1919
1920
template <class Base>
1921
287
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
1922
  Base* w;
1923
331
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1924
1925
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
1926
  // peer certificate is questionable but it's compatible with what was
1927
  // here before.
1928
  long x509_verify_error =  // NOLINT(runtime/int)
1929
287
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
1930
287
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
1931
284
    X509_free(peer_cert);
1932
284
    x509_verify_error = SSL_get_verify_result(w->ssl_);
1933
  }
1934
1935
287
  if (x509_verify_error == X509_V_OK)
1936
88
    return args.GetReturnValue().SetNull();
1937
1938
  // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
1939
  // in the presence of invalid error codes.  Probably academical but something
1940
  // to keep in mind if/when node ever grows multi-isolate capabilities.
1941
243
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
1942
243
  const char* code = reason;
1943
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
1944
243
  switch (x509_verify_error) {
1945
3
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
1946
5
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
1947
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
1948
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
1949
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
1950
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
1951
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
1952
    CASE_X509_ERR(CERT_NOT_YET_VALID)
1953
29
    CASE_X509_ERR(CERT_HAS_EXPIRED)
1954
    CASE_X509_ERR(CRL_NOT_YET_VALID)
1955
    CASE_X509_ERR(CRL_HAS_EXPIRED)
1956
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
1957
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
1958
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
1959
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
1960
    CASE_X509_ERR(OUT_OF_MEM)
1961
107
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
1962
4
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
1963
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
1964
91
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
1965
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
1966
2
    CASE_X509_ERR(CERT_REVOKED)
1967
    CASE_X509_ERR(INVALID_CA)
1968
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
1969
1
    CASE_X509_ERR(INVALID_PURPOSE)
1970
    CASE_X509_ERR(CERT_UNTRUSTED)
1971
    CASE_X509_ERR(CERT_REJECTED)
1972
  }
1973
#undef CASE_X509_ERR
1974
1975
243
  Isolate* isolate = args.GetIsolate();
1976
243
  Local<String> reason_string = OneByteString(isolate, reason);
1977
243
  Local<Value> exception_value = Exception::Error(reason_string);
1978
243
  Local<Object> exception_object = exception_value->ToObject(isolate);
1979
972
  exception_object->Set(FIXED_ONE_BYTE_STRING(isolate, "code"),
1980
                        OneByteString(isolate, code));
1981
486
  args.GetReturnValue().Set(exception_object);
1982
}
1983
1984
1985
template <class Base>
1986
10
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
1987
  Base* w;
1988
10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1989
19
  Environment* env = w->ssl_env();
1990
1991
10
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
1992
10
  if (c == nullptr)
1993
    return;
1994
1995
10
  Local<Object> info = Object::New(env->isolate());
1996
10
  const char* cipher_name = SSL_CIPHER_get_name(c);
1997
40
  info->Set(env->name_string(), OneByteString(args.GetIsolate(), cipher_name));
1998
10
  const char* cipher_version = SSL_CIPHER_get_version(c);
1999
40
  info->Set(env->version_string(),
2000
            OneByteString(args.GetIsolate(), cipher_version));
2001
10
  args.GetReturnValue().Set(info);
2002
}
2003
2004
2005
template <class Base>
2006
3
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2007
  Base* w;
2008
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2009
2010
3
  const char* tls_version = SSL_get_version(w->ssl_);
2011
6
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2012
}
2013
2014
2015
#ifdef OPENSSL_NPN_NEGOTIATED
2016
template <class Base>
2017
252
int SSLWrap<Base>::AdvertiseNextProtoCallback(SSL* s,
2018
                                              const unsigned char** data,
2019
                                              unsigned int* len,
2020
                                              void* arg) {
2021
252
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2022
252
  Environment* env = w->env();
2023
504
  HandleScope handle_scope(env->isolate());
2024
756
  Context::Scope context_scope(env->context());
2025
2026
  auto npn_buffer =
2027
252
      w->object()->GetPrivate(
2028
          env->context(),
2029
1008
          env->npn_buffer_private_symbol()).ToLocalChecked();
2030
2031
504
  if (npn_buffer->IsUndefined()) {
2032
    // No initialization - no NPN protocols
2033
143
    *data = reinterpret_cast<const unsigned char*>("");
2034
143
    *len = 0;
2035
  } else {
2036
109
    CHECK(Buffer::HasInstance(npn_buffer));
2037
109
    *data = reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2038
109
    *len = Buffer::Length(npn_buffer);
2039
  }
2040
2041
504
  return SSL_TLSEXT_ERR_OK;
2042
}
2043
2044
2045
template <class Base>
2046
251
int SSLWrap<Base>::SelectNextProtoCallback(SSL* s,
2047
                                           unsigned char** out,
2048
                                           unsigned char* outlen,
2049
                                           const unsigned char* in,
2050
                                           unsigned int inlen,
2051
                                           void* arg) {
2052
251
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2053
251
  Environment* env = w->env();
2054
502
  HandleScope handle_scope(env->isolate());
2055
753
  Context::Scope context_scope(env->context());
2056
2057
  auto npn_buffer =
2058
251
      w->object()->GetPrivate(
2059
          env->context(),
2060
1004
          env->npn_buffer_private_symbol()).ToLocalChecked();
2061
2062
502
  if (npn_buffer->IsUndefined()) {
2063
    // We should at least select one protocol
2064
    // If server is using NPN
2065
230
    *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
2066
230
    *outlen = 8;
2067
2068
    // set status: unsupported
2069
1610
    CHECK(
2070
        w->object()->SetPrivate(
2071
            env->context(),
2072
            env->selected_npn_buffer_private_symbol(),
2073
            False(env->isolate())).FromJust());
2074
2075
    return SSL_TLSEXT_ERR_OK;
2076
  }
2077
2078
21
  CHECK(Buffer::HasInstance(npn_buffer));
2079
  const unsigned char* npn_protos =
2080
21
      reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2081
21
  size_t len = Buffer::Length(npn_buffer);
2082
2083
21
  int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
2084
21
  Local<Value> result;
2085
21
  switch (status) {
2086
    case OPENSSL_NPN_UNSUPPORTED:
2087
      result = Null(env->isolate());
2088
      break;
2089
    case OPENSSL_NPN_NEGOTIATED:
2090
14
      result = OneByteString(env->isolate(), *out, *outlen);
2091
7
      break;
2092
    case OPENSSL_NPN_NO_OVERLAP:
2093
42
      result = False(env->isolate());
2094
14
      break;
2095
    default:
2096
      break;
2097
  }
2098
2099
84
  CHECK(
2100
      w->object()->SetPrivate(
2101
          env->context(),
2102
          env->selected_npn_buffer_private_symbol(),
2103
          result).FromJust());
2104
2105
  return SSL_TLSEXT_ERR_OK;
2106
}
2107
2108
2109
template <class Base>
2110
553
void SSLWrap<Base>::GetNegotiatedProto(
2111
    const FunctionCallbackInfo<Value>& args) {
2112
  Base* w;
2113
859
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2114
553
  Environment* env = w->env();
2115
2116
1105
  if (w->is_client()) {
2117
    auto selected_npn_buffer =
2118
255
        w->object()->GetPrivate(
2119
            env->context(),
2120
1020
            env->selected_npn_buffer_private_symbol()).ToLocalChecked();
2121
255
    args.GetReturnValue().Set(selected_npn_buffer);
2122
    return;
2123
  }
2124
2125
  const unsigned char* npn_proto;
2126
  unsigned int npn_proto_len;
2127
2128
298
  SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
2129
2130
298
  if (!npn_proto)
2131
102
    return args.GetReturnValue().Set(false);
2132
2133
988
  args.GetReturnValue().Set(
2134
      OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
2135
}
2136
2137
2138
template <class Base>
2139
142
void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
2140
  Base* w;
2141
142
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2142
142
  Environment* env = w->env();
2143
2144
142
  if (args.Length() < 1)
2145
    return env->ThrowTypeError("NPN protocols argument is mandatory");
2146
2147
142
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "NPN protocols");
2148
2149
710
  CHECK(
2150
      w->object()->SetPrivate(
2151
          env->context(),
2152
          env->npn_buffer_private_symbol(),
2153
          args[0]).FromJust());
2154
}
2155
#endif  // OPENSSL_NPN_NEGOTIATED
2156
2157
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2158
template <class Base>
2159
13
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2160
                                      const unsigned char** out,
2161
                                      unsigned char* outlen,
2162
                                      const unsigned char* in,
2163
                                      unsigned int inlen,
2164
                                      void* arg) {
2165
13
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2166
13
  Environment* env = w->env();
2167
26
  HandleScope handle_scope(env->isolate());
2168
39
  Context::Scope context_scope(env->context());
2169
2170
  Local<Value> alpn_buffer =
2171
13
      w->object()->GetPrivate(
2172
          env->context(),
2173
52
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2174
13
  CHECK(Buffer::HasInstance(alpn_buffer));
2175
  const unsigned char* alpn_protos =
2176
13
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2177
13
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2178
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2179
13
                                     alpn_protos, alpn_protos_len, in, inlen);
2180
2181
13
  switch (status) {
2182
    case OPENSSL_NPN_NO_OVERLAP:
2183
      // According to 3.2. Protocol Selection of RFC7301,
2184
      // fatal no_application_protocol alert shall be sent
2185
      // but current openssl does not support it yet. See
2186
      // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2187
      // Instead, we send a warning alert for now.
2188
      return SSL_TLSEXT_ERR_ALERT_WARNING;
2189
    case OPENSSL_NPN_NEGOTIATED:
2190
9
      return SSL_TLSEXT_ERR_OK;
2191
    default:
2192
      return SSL_TLSEXT_ERR_ALERT_FATAL;
2193
  }
2194
}
2195
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2196
2197
2198
template <class Base>
2199
553
void SSLWrap<Base>::GetALPNNegotiatedProto(
2200
    const FunctionCallbackInfo<v8::Value>& args) {
2201
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2202
  Base* w;
2203
1088
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2204
2205
  const unsigned char* alpn_proto;
2206
  unsigned int alpn_proto_len;
2207
2208
553
  SSL_get0_alpn_selected(w->ssl_, &alpn_proto, &alpn_proto_len);
2209
2210
553
  if (!alpn_proto)
2211
1070
    return args.GetReturnValue().Set(false);
2212
2213
72
  args.GetReturnValue().Set(
2214
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2215
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2216
}
2217
2218
2219
template <class Base>
2220
134
void SSLWrap<Base>::SetALPNProtocols(
2221
    const FunctionCallbackInfo<v8::Value>& args) {
2222
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2223
  Base* w;
2224
134
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2225
134
  Environment* env = w->env();
2226
268
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2227
    return env->ThrowTypeError("Must give a Buffer as first argument");
2228
2229
268
  if (w->is_client()) {
2230
    const unsigned char* alpn_protos =
2231
22
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2232
22
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2233
22
    int r = SSL_set_alpn_protos(w->ssl_, alpn_protos, alpn_protos_len);
2234
22
    CHECK_EQ(r, 0);
2235
  } else {
2236
560
    CHECK(
2237
        w->object()->SetPrivate(
2238
          env->context(),
2239
          env->alpn_buffer_private_symbol(),
2240
          args[0]).FromJust());
2241
    // Server should select ALPN protocol from list of advertised by client
2242
112
    SSL_CTX_set_alpn_select_cb(w->ssl_->ctx, SelectALPNCallback, nullptr);
2243
  }
2244
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2245
}
2246
2247
2248
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2249
template <class Base>
2250
7
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2251
7
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2252
7
  Environment* env = w->env();
2253
14
  HandleScope handle_scope(env->isolate());
2254
2255
13
  if (w->is_client()) {
2256
    // Incoming response
2257
    const unsigned char* resp;
2258
3
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2259
3
    Local<Value> arg;
2260
3
    if (resp == nullptr) {
2261
3
      arg = Null(env->isolate());
2262
    } else {
2263
6
      arg = Buffer::Copy(
2264
          env,
2265
          reinterpret_cast<char*>(const_cast<unsigned char*>(resp)),
2266
          len).ToLocalChecked();
2267
    }
2268
2269
3
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2270
2271
    // Somehow, client is expecting different return value here
2272
    return 1;
2273
  } else {
2274
    // Outgoing response
2275
8
    if (w->ocsp_response_.IsEmpty())
2276
      return SSL_TLSEXT_ERR_NOACK;
2277
2278
2
    Local<Object> obj = PersistentToLocal(env->isolate(), w->ocsp_response_);
2279
2
    char* resp = Buffer::Data(obj);
2280
2
    size_t len = Buffer::Length(obj);
2281
2282
    // OpenSSL takes control of the pointer after accepting it
2283
2
    char* data = reinterpret_cast<char*>(malloc(len));
2284
2
    CHECK_NE(data, nullptr);
2285
2
    memcpy(data, resp, len);
2286
2287
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2288
      free(data);
2289
2
    w->ocsp_response_.Reset();
2290
2291
    return SSL_TLSEXT_ERR_OK;
2292
  }
2293
}
2294
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2295
2296
2297
template <class Base>
2298
21
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2299
21
  cert_cb_ = cb;
2300
21
  cert_cb_arg_ = arg;
2301
21
}
2302
2303
2304
template <class Base>
2305
290
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2306
290
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2307
2308
577
  if (!w->is_server())
2309
    return 1;
2310
2311
563
  if (!w->is_waiting_cert_cb())
2312
    return 1;
2313
2314
21
  if (w->cert_cb_running_)
2315
    return -1;
2316
2317
21
  Environment* env = w->env();
2318
42
  HandleScope handle_scope(env->isolate());
2319
63
  Context::Scope context_scope(env->context());
2320
21
  w->cert_cb_running_ = true;
2321
2322
21
  Local<Object> info = Object::New(env->isolate());
2323
2324
21
  SSL_SESSION* sess = SSL_get_session(s);
2325
21
  if (sess != nullptr) {
2326
21
    if (sess->tlsext_hostname == nullptr) {
2327
40
      info->Set(env->servername_string(), String::Empty(env->isolate()));
2328
    } else {
2329
13
      Local<String> servername = OneByteString(env->isolate(),
2330
                                               sess->tlsext_hostname,
2331
26
                                               strlen(sess->tlsext_hostname));
2332
39
      info->Set(env->servername_string(), servername);
2333
    }
2334
105
    info->Set(env->tls_ticket_string(),
2335
21
              Boolean::New(env->isolate(), sess->tlsext_ticklen != 0));
2336
  }
2337
2338
21
  bool ocsp = false;
2339
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2340
21
  ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp;
2341
#endif
2342
2343
105
  info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp));
2344
2345
42
  Local<Value> argv[] = { info };
2346
42
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2347
2348
21
  if (!w->cert_cb_running_)
2349
    return 1;
2350
2351
  // Performing async action, wait...
2352
9
  return -1;
2353
}
2354
2355
2356
template <class Base>
2357
21
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2358
  Base* w;
2359
21
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2360
21
  Environment* env = w->env();
2361
2362
42
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2363
2364
42
  Local<Object> object = w->object();
2365
42
  Local<Value> ctx = object->Get(env->sni_context_string());
2366
21
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2367
2368
  // Not an object, probably undefined or null
2369
21
  if (!ctx->IsObject())
2370
    goto fire_cb;
2371
2372
10
  if (cons->HasInstance(ctx)) {
2373
    SecureContext* sc;
2374
10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2375
18
    w->sni_context_.Reset();
2376
18
    w->sni_context_.Reset(env->isolate(), ctx);
2377
2378
    int rv;
2379
2380
    // NOTE: reference count is not increased by this API methods
2381
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_);
2382
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_);
2383
    STACK_OF(X509)* chain;
2384
2385
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain);
2386
9
    if (rv)
2387
9
      rv = SSL_use_certificate(w->ssl_, x509);
2388
9
    if (rv)
2389
8
      rv = SSL_use_PrivateKey(w->ssl_, pkey);
2390
9
    if (rv && chain != nullptr)
2391
1
      rv = SSL_set1_chain(w->ssl_, chain);
2392
9
    if (rv)
2393
8
      rv = w->SetCACerts(sc);
2394
9
    if (!rv) {
2395
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2396
1
      if (!err)
2397
        return env->ThrowError("CertCbDone");
2398
1
      return ThrowCryptoError(env, err);
2399
    }
2400
  } else {
2401
    // Failure: incorrect SNI context object
2402
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2403
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2404
    return;
2405
  }
2406
2407
 fire_cb:
2408
  CertCb cb;
2409
  void* arg;
2410
2411
19
  cb = w->cert_cb_;
2412
19
  arg = w->cert_cb_arg_;
2413
2414
19
  w->cert_cb_running_ = false;
2415
19
  w->cert_cb_ = nullptr;
2416
19
  w->cert_cb_arg_ = nullptr;
2417
2418
19
  cb(arg);
2419
}
2420
2421
2422
template <class Base>
2423
2
void SSLWrap<Base>::SSLGetter(Local<String> property,
2424
                              const PropertyCallbackInfo<Value>& info) {
2425
  Base* base;
2426
4
  ASSIGN_OR_RETURN_UNWRAP(&base, info.This());
2427
  SSL* ssl = base->ssl_;
2428
  Local<External> ext = External::New(info.GetIsolate(), ssl);
2429
  info.GetReturnValue().Set(ext);
2430
}
2431
2432
2433
template <class Base>
2434
208
void SSLWrap<Base>::DestroySSL() {
2435
210
  if (ssl_ == nullptr)
2436
    return;
2437
2438
208
  SSL_free(ssl_);
2439
416
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2440
208
  ssl_ = nullptr;
2441
}
2442
2443
2444
template <class Base>
2445
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2446
  InitNPN(sc);
2447
  CHECK_EQ(SSL_set_SSL_CTX(ssl_, sc->ctx_), sc->ctx_);
2448
2449
  SetCACerts(sc);
2450
}
2451
2452
2453
template <class Base>
2454
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2455
8
  int err = SSL_set1_verify_cert_store(ssl_, SSL_CTX_get_cert_store(sc->ctx_));
2456
8
  if (err != 1)
2457
    return err;
2458
2459
8
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2460
16
      SSL_CTX_get_client_CA_list(sc->ctx_));
2461
2462
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2463
8
  SSL_set_client_CA_list(ssl_, list);
2464
8
  return 1;
2465
}
2466
2467
2468
3
void Connection::OnClientHelloParseEnd(void* arg) {
2469
3
  Connection* conn = static_cast<Connection*>(arg);
2470
2471
  // Write all accumulated data
2472
3
  int r = BIO_write(conn->bio_read_,
2473
                    reinterpret_cast<char*>(conn->hello_data_),
2474
6
                    conn->hello_offset_);
2475
3
  conn->HandleBIOError(conn->bio_read_, "BIO_write", r);
2476
3
  conn->SetShutdownFlags();
2477
3
}
2478
2479
2480
#ifdef SSL_PRINT_DEBUG
2481
# define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
2482
#else
2483
# define DEBUG_PRINT(...)
2484
#endif
2485
2486
2487
27
int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
2488
27
  if (rv >= 0)
2489
    return rv;
2490
2491
17
  int retry = BIO_should_retry(bio);
2492
  (void) retry;  // unused if !defined(SSL_PRINT_DEBUG)
2493
2494
17
  if (BIO_should_write(bio)) {
2495
    DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n",
2496
                ssl_,
2497
                func,
2498
                retry);
2499
    return 0;
2500
2501
17
  } else if (BIO_should_read(bio)) {
2502
    DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
2503
    return 0;
2504
2505
  } else {
2506
    char ssl_error_buf[512];
2507
    ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
2508
2509
    HandleScope scope(ssl_env()->isolate());
2510
    Local<Value> exception =
2511
        Exception::Error(OneByteString(ssl_env()->isolate(), ssl_error_buf));
2512
    object()->Set(ssl_env()->error_string(), exception);
2513
2514
    DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n",
2515
                ssl_,
2516
                func,
2517
                rv,
2518
                ssl_error_buf);
2519
2520
    return rv;
2521
  }
2522
2523
  return 0;
2524
}
2525
2526
2527
25
int Connection::HandleSSLError(const char* func,
2528
                               int rv,
2529
                               ZeroStatus zs,
2530
                               SyscallStatus ss) {
2531
  ClearErrorOnReturn clear_error_on_return;
2532
  (void) &clear_error_on_return;  // Silence unused variable warning.
2533
2534
25
  if (rv > 0)
2535
    return rv;
2536
21
  if (rv == 0 && zs == kZeroIsNotAnError)
2537
    return rv;
2538
2539
20
  int err = SSL_get_error(ssl_, rv);
2540
2541
20
  if (err == SSL_ERROR_NONE) {
2542
    return 0;
2543
2544
20
  } else if (err == SSL_ERROR_WANT_WRITE) {
2545
    DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
2546
    return 0;
2547
2548
20
  } else if (err == SSL_ERROR_WANT_READ) {
2549
    DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
2550
    return 0;
2551
2552
1
  } else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2553
    DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2554
    return 0;
2555
2556
1
  } else if (err == SSL_ERROR_ZERO_RETURN) {
2557
    HandleScope scope(ssl_env()->isolate());
2558
2559
    Local<Value> exception =
2560
        Exception::Error(ssl_env()->zero_return_string());
2561
    object()->Set(ssl_env()->error_string(), exception);
2562
    return rv;
2563
2564
1
  } else if (err == SSL_ERROR_SYSCALL && ss == kIgnoreSyscall) {
2565
    return 0;
2566
2567
  } else {
2568
2
    HandleScope scope(ssl_env()->isolate());
2569
    BUF_MEM* mem;
2570
    BIO *bio;
2571
2572
1
    CHECK(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
2573
2574
    // XXX We need to drain the error queue for this thread or else OpenSSL
2575
    // has the possibility of blocking connections? This problem is not well
2576
    // understood. And we should be somehow propagating these errors up
2577
    // into JavaScript. There is no test which demonstrates this problem.
2578
    // https://github.com/joyent/node/issues/1719
2579
1
    bio = BIO_new(BIO_s_mem());
2580
1
    if (bio != nullptr) {
2581
1
      ERR_print_errors(bio);
2582
1
      BIO_get_mem_ptr(bio, &mem);
2583
      Local<Value> exception = Exception::Error(
2584
          OneByteString(ssl_env()->isolate(),
2585
1
            mem->data,
2586
2
            mem->length));
2587
4
      object()->Set(ssl_env()->error_string(), exception);
2588
1
      BIO_free_all(bio);
2589
    }
2590
2591
    return rv;
2592
  }
2593
2594
  return 0;
2595
}
2596
2597
2598
void Connection::ClearError() {
2599
#ifndef NDEBUG
2600
  HandleScope scope(ssl_env()->isolate());
2601
2602
  // We should clear the error in JS-land
2603
  Local<String> error_key = ssl_env()->error_string();
2604
  Local<Value> error = object()->Get(error_key);
2605
  CHECK_EQ(error->BooleanValue(), false);
2606
#endif  // NDEBUG
2607
}
2608
2609
2610
36
void Connection::SetShutdownFlags() {
2611
72
  HandleScope scope(ssl_env()->isolate());
2612
2613
36
  int flags = SSL_get_shutdown(ssl_);
2614
2615
36
  if (flags & SSL_SENT_SHUTDOWN) {
2616
    Local<String> sent_shutdown_key = ssl_env()->sent_shutdown_string();
2617
    object()->Set(sent_shutdown_key, True(ssl_env()->isolate()));
2618
  }
2619
2620
36
  if (flags & SSL_RECEIVED_SHUTDOWN) {
2621
2
    Local<String> received_shutdown_key = ssl_env()->received_shutdown_string();
2622
5
    object()->Set(received_shutdown_key, True(ssl_env()->isolate()));
2623
  }
2624
36
}
2625
2626
2627
void Connection::NewSessionDoneCb() {
2628
  HandleScope scope(env()->isolate());
2629
2630
  MakeCallback(env()->onnewsessiondone_string(), 0, nullptr);
2631
}
2632
2633
2634
182
void Connection::Initialize(Environment* env, Local<Object> target) {
2635
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Connection::New);
2636
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
2637
182
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"));
2638
2639
182
  env->SetProtoMethod(t, "encIn", Connection::EncIn);
2640
182
  env->SetProtoMethod(t, "clearOut", Connection::ClearOut);
2641
182
  env->SetProtoMethod(t, "clearIn", Connection::ClearIn);
2642
182
  env->SetProtoMethod(t, "encOut", Connection::EncOut);
2643
182
  env->SetProtoMethod(t, "clearPending", Connection::ClearPending);
2644
182
  env->SetProtoMethod(t, "encPending", Connection::EncPending);
2645
182
  env->SetProtoMethod(t, "start", Connection::Start);
2646
182
  env->SetProtoMethod(t, "close", Connection::Close);
2647
2648
182
  SSLWrap<Connection>::AddMethods(env, t);
2649
2650
2651
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2652
182
  env->SetProtoMethod(t, "getServername", Connection::GetServername);
2653
182
  env->SetProtoMethod(t, "setSNICallback",  Connection::SetSNICallback);
2654
#endif
2655
2656
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"),
2657
182
              t->GetFunction());
2658
182
}
2659
2660
2661
inline int compar(const void* a, const void* b) {
2662
10
  return memcmp(a, b, CNNIC_WHITELIST_HASH_LEN);
2663
}
2664
2665
2666
65
inline int IsSelfSigned(X509* cert) {
2667
65
  return X509_NAME_cmp(X509_get_subject_name(cert),
2668
130
                       X509_get_issuer_name(cert)) == 0;
2669
}
2670
2671
2672
inline X509* FindRoot(STACK_OF(X509)* sk) {
2673
  for (int i = 0; i < sk_X509_num(sk); i++) {
2674
    X509* cert = sk_X509_value(sk, i);
2675
    if (IsSelfSigned(cert))
2676
      return cert;
2677
  }
2678
  return nullptr;
2679
}
2680
2681
2682
// Whitelist check for certs issued by CNNIC. See
2683
// https://blog.mozilla.org/security/2015/04/02
2684
// /distrusting-new-cnnic-certificates/
2685
65
inline CheckResult CheckWhitelistedServerCert(X509_STORE_CTX* ctx) {
2686
  unsigned char hash[CNNIC_WHITELIST_HASH_LEN];
2687
65
  unsigned int hashlen = CNNIC_WHITELIST_HASH_LEN;
2688
2689
65
  STACK_OF(X509)* chain = X509_STORE_CTX_get1_chain(ctx);
2690
65
  CHECK_NE(chain, nullptr);
2691
65
  CHECK_GT(sk_X509_num(chain), 0);
2692
2693
  // Take the last cert as root at the first time.
2694
65
  X509* root_cert = sk_X509_value(chain, sk_X509_num(chain)-1);
2695
65
  X509_NAME* root_name = X509_get_subject_name(root_cert);
2696
2697
65
  if (!IsSelfSigned(root_cert)) {
2698
    root_cert = FindRoot(chain);
2699
    CHECK_NE(root_cert, nullptr);
2700
    root_name = X509_get_subject_name(root_cert);
2701
  }
2702
2703
  // When the cert is issued from either CNNNIC ROOT CA or CNNNIC EV
2704
  // ROOT CA, check a hash of its leaf cert if it is in the whitelist.
2705
129
  if (X509_NAME_cmp(root_name, cnnic_name) == 0 ||
2706
64
      X509_NAME_cmp(root_name, cnnic_ev_name) == 0) {
2707
1
    X509* leaf_cert = sk_X509_value(chain, 0);
2708
1
    int ret = X509_digest(leaf_cert, EVP_sha256(), hash,
2709
1
                          &hashlen);
2710
1
    CHECK(ret);
2711
2712
    void* result = bsearch(hash, WhitelistedCNNICHashes,
2713
                           arraysize(WhitelistedCNNICHashes),
2714
1
                           CNNIC_WHITELIST_HASH_LEN, compar);
2715
1
    if (result == nullptr) {
2716
1
      sk_X509_pop_free(chain, X509_free);
2717
1
      return CHECK_CERT_REVOKED;
2718
    }
2719
  }
2720
2721
64
  sk_X509_pop_free(chain, X509_free);
2722
64
  return CHECK_OK;
2723
}
2724
2725
2726
527
inline int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2727
  // Failure on verification of the cert is handled in
2728
  // Connection::VerifyError.
2729
527
  if (preverify_ok == 0 || X509_STORE_CTX_get_error(ctx) != X509_V_OK)
2730
    return 1;
2731
2732
  // Server does not need to check the whitelist.
2733
  SSL* ssl = static_cast<SSL*>(
2734
82
      X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
2735
2736
82
  if (SSL_is_server(ssl))
2737
    return 1;
2738
2739
  // Client needs to check if the server cert is listed in the
2740
  // whitelist when it is issued by the specific rootCAs.
2741
65
  CheckResult ret = CheckWhitelistedServerCert(ctx);
2742
65
  if (ret == CHECK_CERT_REVOKED)
2743
1
    X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
2744
2745
65
  return ret;
2746
}
2747
2748
2749
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2750
3
int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
2751
3
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(s));
2752
3
  Environment* env = conn->env();
2753
6
  HandleScope scope(env->isolate());
2754
2755
3
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2756
2757
3
  if (servername) {
2758
2
    conn->servername_.Reset(env->isolate(),
2759
4
                            OneByteString(env->isolate(), servername));
2760
2761
    // Call the SNI callback and use its return value as context
2762
4
    if (!conn->sniObject_.IsEmpty()) {
2763
4
      conn->sni_context_.Reset();
2764
2765
      Local<Object> sni_obj = PersistentToLocal(env->isolate(),
2766
2
                                                conn->sniObject_);
2767
2768
4
      Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
2769
      Local<Value> ret = node::MakeCallback(env->isolate(),
2770
                                            sni_obj,
2771
                                            env->onselect_string(),
2772
                                            1,
2773
2
                                            &arg);
2774
2775
      // If ret is SecureContext
2776
      Local<FunctionTemplate> secure_context_constructor_template =
2777
2
          env->secure_context_constructor_template();
2778
2
      if (secure_context_constructor_template->HasInstance(ret)) {
2779
        conn->sni_context_.Reset(env->isolate(), ret);
2780
        SecureContext* sc;
2781
        ASSIGN_OR_RETURN_UNWRAP(&sc, ret.As<Object>(), SSL_TLSEXT_ERR_NOACK);
2782
        conn->SetSNIContext(sc);
2783
      } else {
2784
        return SSL_TLSEXT_ERR_NOACK;
2785
      }
2786
    }
2787
  }
2788
2789
  return SSL_TLSEXT_ERR_OK;
2790
}
2791
#endif
2792
2793
7
void Connection::New(const FunctionCallbackInfo<Value>& args) {
2794
7
  Environment* env = Environment::GetCurrent(args);
2795
2796
21
  if (args.Length() < 1 || !args[0]->IsObject()) {
2797
    env->ThrowError("First argument must be a tls module SecureContext");
2798
    return;
2799
  }
2800
2801
  SecureContext* sc;
2802
12
  ASSIGN_OR_RETURN_UNWRAP(&sc, args[0].As<Object>());
2803
2804
6
  bool is_server = args[1]->BooleanValue();
2805
2806
  SSLWrap<Connection>::Kind kind =
2807
6
      is_server ? SSLWrap<Connection>::kServer : SSLWrap<Connection>::kClient;
2808
6
  Connection* conn = new Connection(env, args.This(), sc, kind);
2809
6
  conn->bio_read_ = NodeBIO::New();
2810
6
  conn->bio_write_ = NodeBIO::New();
2811
2812
6
  SSL_set_app_data(conn->ssl_, conn);
2813
2814
6
  if (is_server)
2815
4
    SSL_set_info_callback(conn->ssl_, SSLInfoCallback);
2816
2817
6
  InitNPN(sc);
2818
2819
6
  SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
2820
2821
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2822
6
  if (is_server) {
2823
4
    SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
2824
4
  } else if (args[2]->IsString()) {
2825
    const node::Utf8Value servername(env->isolate(), args[2]);
2826
    SSL_set_tlsext_host_name(conn->ssl_, *servername);
2827
  }
2828
#endif
2829
2830
6
  SSL_set_bio(conn->ssl_, conn->bio_read_, conn->bio_write_);
2831
2832
#ifdef SSL_MODE_RELEASE_BUFFERS
2833
6
  long mode = SSL_get_mode(conn->ssl_);  // NOLINT(runtime/int)
2834
6
  SSL_set_mode(conn->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
2835
#endif
2836
2837
2838
  int verify_mode;
2839
6
  if (is_server) {
2840
4
    bool request_cert = args[2]->BooleanValue();
2841
4
    if (!request_cert) {
2842
      // Note reject_unauthorized ignored.
2843
      verify_mode = SSL_VERIFY_NONE;
2844
    } else {
2845
      bool reject_unauthorized = args[3]->BooleanValue();
2846
      verify_mode = SSL_VERIFY_PEER;
2847
      if (reject_unauthorized)
2848
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2849
    }
2850
  } else {
2851
    // Note request_cert and reject_unauthorized are ignored for clients.
2852
    verify_mode = SSL_VERIFY_NONE;
2853
  }
2854
2855
2856
  // Always allow a connection. We'll reject in javascript.
2857
6
  SSL_set_verify(conn->ssl_, verify_mode, VerifyCallback);
2858
2859
6
  if (is_server) {
2860
4
    SSL_set_accept_state(conn->ssl_);
2861
  } else {
2862
2
    SSL_set_connect_state(conn->ssl_);
2863
  }
2864
}
2865
2866
2867
48
void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
2868
48
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
2869
43
    return;
2870
2871
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
2872
  // a non-const SSL* in OpenSSL <= 0.9.7e.
2873
5
  SSL* ssl = const_cast<SSL*>(ssl_);
2874
5
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(ssl));
2875
5
  Environment* env = conn->env();
2876
10
  HandleScope handle_scope(env->isolate());
2877
15
  Context::Scope context_scope(env->context());
2878
2879
5
  if (where & SSL_CB_HANDSHAKE_START) {
2880
4
    conn->MakeCallback(env->onhandshakestart_string(), 0, nullptr);
2881
  }
2882
2883
5
  if (where & SSL_CB_HANDSHAKE_DONE) {
2884
1
    conn->MakeCallback(env->onhandshakedone_string(), 0, nullptr);
2885
  }
2886
}
2887
2888
2889
6
void Connection::EncIn(const FunctionCallbackInfo<Value>& args) {
2890
  Connection* conn;
2891
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2892
6
  Environment* env = conn->env();
2893
2894
6
  if (args.Length() < 3) {
2895
    return env->ThrowTypeError(
2896
        "Data, offset, and length arguments are mandatory");
2897
  }
2898
2899
6
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
2900
2901
6
  char* buffer_data = Buffer::Data(args[0]);
2902
6
  size_t buffer_length = Buffer::Length(args[0]);
2903
2904
6
  size_t off = args[1]->Int32Value();
2905
6
  size_t len = args[2]->Int32Value();
2906
2907
6
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
2908
    return env->ThrowRangeError("offset + length > buffer.length");
2909
2910
  int bytes_written;
2911
6
  char* data = buffer_data + off;
2912
2913
6
  if (conn->is_server() && !conn->hello_parser_.IsEnded()) {
2914
    // Just accumulate data, everything will be pushed to BIO later
2915
3
    if (conn->hello_parser_.IsPaused()) {
2916
      bytes_written = 0;
2917
    } else {
2918
      // Copy incoming data to the internal buffer
2919
      // (which has a size of the biggest possible TLS frame)
2920
3
      size_t available = sizeof(conn->hello_data_) - conn->hello_offset_;
2921
3
      size_t copied = len < available ? len : available;
2922
6
      memcpy(conn->hello_data_ + conn->hello_offset_, data, copied);
2923
3
      conn->hello_offset_ += copied;
2924
2925
3
      conn->hello_parser_.Parse(conn->hello_data_, conn->hello_offset_);
2926
3
      bytes_written = copied;
2927
    }
2928
  } else {
2929
3
    bytes_written = BIO_write(conn->bio_read_, data, len);
2930
3
    conn->HandleBIOError(conn->bio_read_, "BIO_write", bytes_written);
2931
3
    conn->SetShutdownFlags();
2932
  }
2933
2934
12
  args.GetReturnValue().Set(bytes_written);
2935
}
2936
2937
2938
16
void Connection::ClearOut(const FunctionCallbackInfo<Value>& args) {
2939
  Connection* conn;
2940
16
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2941
16
  Environment* env = conn->env();
2942
2943
16
  if (args.Length() < 3) {
2944
    return env->ThrowTypeError(
2945
        "Data, offset, and length arguments are mandatory");
2946
  }
2947
2948
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
2949
2950
16
  char* buffer_data = Buffer::Data(args[0]);
2951
16
  size_t buffer_length = Buffer::Length(args[0]);
2952
2953
16
  size_t off = args[1]->Int32Value();
2954
16
  size_t len = args[2]->Int32Value();
2955
2956
16
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
2957
    return env->ThrowRangeError("offset + length > buffer.length");
2958
2959
16
  if (!SSL_is_init_finished(conn->ssl_)) {
2960
    int rv;
2961
2962
10
    if (conn->is_server()) {
2963
10
      rv = SSL_accept(conn->ssl_);
2964
      conn->HandleSSLError("SSL_accept:ClearOut",
2965
                           rv,
2966
                           kZeroIsAnError,
2967
10
                           kSyscallError);
2968
    } else {
2969
      rv = SSL_connect(conn->ssl_);
2970
      conn->HandleSSLError("SSL_connect:ClearOut",
2971
                           rv,
2972
                           kZeroIsAnError,
2973
                           kSyscallError);
2974
    }
2975
2976
10
    if (rv < 0) {
2977
18
      return args.GetReturnValue().Set(rv);
2978
    }
2979
  }
2980
2981
7
  int bytes_read = SSL_read(conn->ssl_, buffer_data + off, len);
2982
  conn->HandleSSLError("SSL_read:ClearOut",
2983
                       bytes_read,
2984
                       kZeroIsNotAnError,
2985
7
                       kSyscallError);
2986
7
  conn->SetShutdownFlags();
2987
2988
14
  args.GetReturnValue().Set(bytes_read);
2989
}
2990
2991
2992
19
void Connection::ClearPending(const FunctionCallbackInfo<Value>& args) {
2993
  Connection* conn;
2994
19
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2995
19
  int bytes_pending = BIO_pending(conn->bio_read_);
2996
38
  args.GetReturnValue().Set(bytes_pending);
2997
}
2998
2999
3000
26
void Connection::EncPending(const FunctionCallbackInfo<Value>& args) {
3001
  Connection* conn;
3002
26
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3003
26
  int bytes_pending = BIO_pending(conn->bio_write_);
3004
52
  args.GetReturnValue().Set(bytes_pending);
3005
}
3006
3007
3008
21
void Connection::EncOut(const FunctionCallbackInfo<Value>& args) {
3009
  Connection* conn;
3010
21
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3011
21
  Environment* env = conn->env();
3012
3013
21
  if (args.Length() < 3) {
3014
    return env->ThrowTypeError(
3015
        "Data, offset, and length arguments are mandatory");
3016
  }
3017
3018
21
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3019
3020
21
  char* buffer_data = Buffer::Data(args[0]);
3021
21
  size_t buffer_length = Buffer::Length(args[0]);
3022
3023
21
  size_t off = args[1]->Int32Value();
3024
21
  size_t len = args[2]->Int32Value();
3025
3026
21
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3027
    return env->ThrowRangeError("offset + length > buffer.length");
3028
3029
21
  int bytes_read = BIO_read(conn->bio_write_, buffer_data + off, len);
3030
3031
21
  conn->HandleBIOError(conn->bio_write_, "BIO_read:EncOut", bytes_read);
3032
21
  conn->SetShutdownFlags();
3033
3034
42
  args.GetReturnValue().Set(bytes_read);
3035
}
3036
3037
3038
2
void Connection::ClearIn(const FunctionCallbackInfo<Value>& args) {
3039
  Connection* conn;
3040
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3041
2
  Environment* env = conn->env();
3042
3043
2
  if (args.Length() < 3) {
3044
    return env->ThrowTypeError(
3045
        "Data, offset, and length arguments are mandatory");
3046
  }
3047
3048
2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3049
3050
2
  char* buffer_data = Buffer::Data(args[0]);
3051
2
  size_t buffer_length = Buffer::Length(args[0]);
3052
3053
2
  size_t off = args[1]->Int32Value();
3054
2
  size_t len = args[2]->Int32Value();
3055
3056
2
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3057
    return env->ThrowRangeError("offset + length > buffer.length");
3058
3059
2
  if (!SSL_is_init_finished(conn->ssl_)) {
3060
    int rv;
3061
    if (conn->is_server()) {
3062
      rv = SSL_accept(conn->ssl_);
3063
      conn->HandleSSLError("SSL_accept:ClearIn",
3064
                           rv,
3065
                           kZeroIsAnError,
3066
                           kSyscallError);
3067
    } else {
3068
      rv = SSL_connect(conn->ssl_);
3069
      conn->HandleSSLError("SSL_connect:ClearIn",
3070
                           rv,
3071
                           kZeroIsAnError,
3072
                           kSyscallError);
3073
    }
3074
3075
    if (rv < 0) {
3076
      return args.GetReturnValue().Set(rv);
3077
    }
3078
  }
3079
3080
2
  int bytes_written = SSL_write(conn->ssl_, buffer_data + off, len);
3081
3082
2
  conn->HandleSSLError("SSL_write:ClearIn",
3083
                       bytes_written,
3084
                       len == 0 ? kZeroIsNotAnError : kZeroIsAnError,
3085
2
                       kSyscallError);
3086
2
  conn->SetShutdownFlags();
3087
3088
4
  args.GetReturnValue().Set(bytes_written);
3089
}
3090
3091
3092
6
void Connection::Start(const FunctionCallbackInfo<Value>& args) {
3093
  Connection* conn;
3094
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3095
3096
6
  int rv = 0;
3097
6
  if (!SSL_is_init_finished(conn->ssl_)) {
3098
6
    if (conn->is_server()) {
3099
4
      rv = SSL_accept(conn->ssl_);
3100
      conn->HandleSSLError("SSL_accept:Start",
3101
                           rv,
3102
                           kZeroIsAnError,
3103
4
                           kSyscallError);
3104
    } else {
3105
2
      rv = SSL_connect(conn->ssl_);
3106
      conn->HandleSSLError("SSL_connect:Start",
3107
                           rv,
3108
                           kZeroIsAnError,
3109
2
                           kSyscallError);
3110
    }
3111
  }
3112
12
  args.GetReturnValue().Set(rv);
3113
}
3114
3115
3116
2
void Connection::Close(const FunctionCallbackInfo<Value>& args) {
3117
  Connection* conn;
3118
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3119
3120
2
  if (conn->ssl_ != nullptr) {
3121
2
    SSL_free(conn->ssl_);
3122
2
    conn->ssl_ = nullptr;
3123
  }
3124
}
3125
3126
3127
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3128
1
void Connection::GetServername(const FunctionCallbackInfo<Value>& args) {
3129
  Connection* conn;
3130
1
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3131
3132
2
  if (conn->is_server() && !conn->servername_.IsEmpty()) {
3133
    args.GetReturnValue().Set(conn->servername_);
3134
  } else {
3135
2
    args.GetReturnValue().Set(false);
3136
  }
3137
}
3138
3139
3140
2
void Connection::SetSNICallback(const FunctionCallbackInfo<Value>& args) {
3141
  Connection* conn;
3142
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3143
2
  Environment* env = conn->env();
3144
3145
6
  if (args.Length() < 1 || !args[0]->IsFunction()) {
3146
    return env->ThrowError("Must give a Function as first argument");
3147
  }
3148
3149
2
  Local<Object> obj = Object::New(env->isolate());
3150
6
  obj->Set(FIXED_ONE_BYTE_STRING(args.GetIsolate(), "onselect"), args[0]);
3151
2
  conn->sniObject_.Reset(args.GetIsolate(), obj);
3152
}
3153
#endif
3154
3155
3156
182
void CipherBase::Initialize(Environment* env, Local<Object> target) {
3157
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3158
3159
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3160
3161
182
  env->SetProtoMethod(t, "init", Init);
3162
182
  env->SetProtoMethod(t, "initiv", InitIv);
3163
182
  env->SetProtoMethod(t, "update", Update);
3164
182
  env->SetProtoMethod(t, "final", Final);
3165
182
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
3166
182
  env->SetProtoMethod(t, "getAuthTag", GetAuthTag);
3167
182
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
3168
182
  env->SetProtoMethod(t, "setAAD", SetAAD);
3169
3170
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
3171
182
              t->GetFunction());
3172
182
}
3173
3174
3175
83
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
3176
83
  CHECK_EQ(args.IsConstructCall(), true);
3177
83
  CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher;
3178
83
  Environment* env = Environment::GetCurrent(args);
3179
83
  new CipherBase(env, args.This(), kind);
3180
83
}
3181
3182
3183
29
void CipherBase::Init(const char* cipher_type,
3184
                      const char* key_buf,
3185
                      int key_buf_len) {
3186
58
  HandleScope scope(env()->isolate());
3187
3188
#ifdef NODE_FIPS_MODE
3189
  if (FIPS_mode()) {
3190
    return env()->ThrowError(
3191
        "crypto.createCipher() is not supported in FIPS mode.");
3192
  }
3193
#endif  // NODE_FIPS_MODE
3194
3195
29
  CHECK_EQ(cipher_, nullptr);
3196
29
  cipher_ = EVP_get_cipherbyname(cipher_type);
3197
29
  if (cipher_ == nullptr) {
3198
    return env()->ThrowError("Unknown cipher");
3199
  }
3200
3201
  unsigned char key[EVP_MAX_KEY_LENGTH];
3202
  unsigned char iv[EVP_MAX_IV_LENGTH];
3203
3204
29
  int key_len = EVP_BytesToKey(cipher_,
3205
                               EVP_md5(),
3206
                               nullptr,
3207
                               reinterpret_cast<const unsigned char*>(key_buf),
3208
                               key_buf_len,
3209
                               1,
3210
                               key,
3211
29
                               iv);
3212
3213
29
  EVP_CIPHER_CTX_init(&ctx_);
3214
29
  const bool encrypt = (kind_ == kCipher);
3215
29
  EVP_CipherInit_ex(&ctx_, cipher_, nullptr, nullptr, nullptr, encrypt);
3216
29
  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3217
    EVP_CIPHER_CTX_cleanup(&ctx_);
3218
    return env()->ThrowError("Invalid key length");
3219
  }
3220
3221
29
  EVP_CipherInit_ex(&ctx_,
3222
                    nullptr,
3223
                    nullptr,
3224
                    reinterpret_cast<unsigned char*>(key),
3225
                    reinterpret_cast<unsigned char*>(iv),
3226
58
                    kind_ == kCipher);
3227
29
  initialised_ = true;
3228
}
3229
3230
3231
29
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
3232
  CipherBase* cipher;
3233
29
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3234
29
  Environment* env = cipher->env();
3235
3236
29
  if (args.Length() < 2) {
3237
    return env->ThrowError("Cipher type and key arguments are mandatory");
3238
  }
3239
3240
58
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3241
29
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3242
3243
87
  const node::Utf8Value cipher_type(args.GetIsolate(), args[0]);
3244
29
  const char* key_buf = Buffer::Data(args[1]);
3245
29
  ssize_t key_buf_len = Buffer::Length(args[1]);
3246
29
  cipher->Init(*cipher_type, key_buf, key_buf_len);
3247
}
3248
3249
3250
54
void CipherBase::InitIv(const char* cipher_type,
3251
                        const char* key,
3252
                        int key_len,
3253
                        const char* iv,
3254
                        int iv_len) {
3255
108
  HandleScope scope(env()->isolate());
3256
3257
54
  cipher_ = EVP_get_cipherbyname(cipher_type);
3258
54
  if (cipher_ == nullptr) {
3259
    return env()->ThrowError("Unknown cipher");
3260
  }
3261
3262
  /* OpenSSL versions up to 0.9.8l failed to return the correct
3263
     iv_length (0) for ECB ciphers */
3264
108
  if (EVP_CIPHER_iv_length(cipher_) != iv_len &&
3265
      !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_ECB_MODE && iv_len == 0) &&
3266
54
      !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_GCM_MODE) && iv_len > 0) {
3267
    return env()->ThrowError("Invalid IV length");
3268
  }
3269
3270
54
  EVP_CIPHER_CTX_init(&ctx_);
3271
54
  const bool encrypt = (kind_ == kCipher);
3272
54
  EVP_CipherInit_ex(&ctx_, cipher_, nullptr, nullptr, nullptr, encrypt);
3273
3274
  /* Set IV length. Only required if GCM cipher and IV is not default iv. */
3275
56
  if (EVP_CIPHER_mode(cipher_) == EVP_CIPH_GCM_MODE &&
3276
2
      iv_len != EVP_CIPHER_iv_length(cipher_)) {
3277
    if (!EVP_CIPHER_CTX_ctrl(&ctx_, EVP_CTRL_GCM_SET_IVLEN, iv_len, nullptr)) {
3278
      EVP_CIPHER_CTX_cleanup(&ctx_);
3279
      return env()->ThrowError("Invalid IV length");
3280
    }
3281
  }
3282
3283
54
  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3284
    EVP_CIPHER_CTX_cleanup(&ctx_);
3285
    return env()->ThrowError("Invalid key length");
3286
  }
3287
3288
54
  EVP_CipherInit_ex(&ctx_,
3289
                    nullptr,
3290
                    nullptr,
3291
                    reinterpret_cast<const unsigned char*>(key),
3292
                    reinterpret_cast<const unsigned char*>(iv),
3293
108
                    kind_ == kCipher);
3294
54
  initialised_ = true;
3295
}
3296
3297
3298
54
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
3299
  CipherBase* cipher;
3300
54
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3301
54
  Environment* env = cipher->env();
3302
3303
54
  if (args.Length() < 3) {
3304
    return env->ThrowError("Cipher type, key, and IV arguments are mandatory");
3305
  }
3306
3307
108
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3308
54
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3309
54
  THROW_AND_RETURN_IF_NOT_BUFFER(args[2], "IV");
3310
3311
108
  const node::Utf8Value cipher_type(env->isolate(), args[0]);
3312
54
  ssize_t key_len = Buffer::Length(args[1]);
3313
54
  const char* key_buf = Buffer::Data(args[1]);
3314
54
  ssize_t iv_len = Buffer::Length(args[2]);
3315
54
  const char* iv_buf = Buffer::Data(args[2]);
3316
54
  cipher->InitIv(*cipher_type, key_buf, key_len, iv_buf, iv_len);
3317
}
3318
3319
3320
bool CipherBase::IsAuthenticatedMode() const {
3321
  // check if this cipher operates in an AEAD mode that we support.
3322
88
  if (!cipher_)
3323
    return false;
3324
88
  int mode = EVP_CIPHER_mode(cipher_);
3325
88
  return mode == EVP_CIPH_GCM_MODE;
3326
}
3327
3328
3329
1
bool CipherBase::GetAuthTag(char** out, unsigned int* out_len) const {
3330
  // only callable after Final and if encrypting.
3331
1
  if (initialised_ || kind_ != kCipher || !auth_tag_)
3332
    return false;
3333
1
  *out_len = auth_tag_len_;
3334
1
  *out = static_cast<char*>(malloc(auth_tag_len_));
3335
1
  CHECK_NE(*out, nullptr);
3336
2
  memcpy(*out, auth_tag_, auth_tag_len_);
3337
1
  return true;
3338
}
3339
3340
3341
1
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
3342
1
  Environment* env = Environment::GetCurrent(args);
3343
  CipherBase* cipher;
3344
1
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3345
3346
1
  char* out = nullptr;
3347
1
  unsigned int out_len = 0;
3348
3349
1
  if (cipher->GetAuthTag(&out, &out_len)) {
3350
2
    Local<Object> buf = Buffer::New(env, out, out_len).ToLocalChecked();
3351
1
    args.GetReturnValue().Set(buf);
3352
  } else {
3353
    env->ThrowError("Attempting to get auth tag in unsupported state");
3354
  }
3355
}
3356
3357
3358
1
bool CipherBase::SetAuthTag(const char* data, unsigned int len) {
3359
2
  if (!initialised_ || !IsAuthenticatedMode() || kind_ != kDecipher)
3360
    return false;
3361
1
  delete[] auth_tag_;
3362
1
  auth_tag_len_ = len;
3363
1
  auth_tag_ = new char[len];
3364
2
  memcpy(auth_tag_, data, len);
3365
1
  return true;
3366
}
3367
3368
3369
1
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
3370
1
  Environment* env = Environment::GetCurrent(args);
3371
3372
2
  Local<Object> buf = args[0].As<Object>();
3373
3374
1
  if (!buf->IsObject() || !Buffer::HasInstance(buf))
3375
    return env->ThrowTypeError("Auth tag must be a Buffer");
3376
3377
  CipherBase* cipher;
3378
1
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3379
3380
1
  if (!cipher->SetAuthTag(Buffer::Data(buf), Buffer::Length(buf)))
3381
    env->ThrowError("Attempting to set auth tag in unsupported state");
3382
}
3383
3384
3385
bool CipherBase::SetAAD(const char* data, unsigned int len) {
3386
  if (!initialised_ || !IsAuthenticatedMode())
3387
    return false;
3388
  int outlen;
3389
  if (!EVP_CipherUpdate(&ctx_,
3390
                        nullptr,
3391
                        &outlen,
3392
                        reinterpret_cast<const unsigned char*>(data),
3393
                        len)) {
3394
    return false;
3395
  }
3396
  return true;
3397
}
3398
3399
3400
void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
3401
  Environment* env = Environment::GetCurrent(args);
3402
3403
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "AAD");
3404
3405
  CipherBase* cipher;
3406
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3407
3408
  if (!cipher->SetAAD(Buffer::Data(args[0]), Buffer::Length(args[0])))
3409
    env->ThrowError("Attempting to set AAD in unsupported state");
3410
}
3411
3412
3413
77
bool CipherBase::Update(const char* data,
3414
                        int len,
3415
                        unsigned char** out,
3416
                        int* out_len) {
3417
77
  if (!initialised_)
3418
    return 0;
3419
3420
  // on first update:
3421
114
  if (kind_ == kDecipher && IsAuthenticatedMode() && auth_tag_ != nullptr) {
3422
1
    EVP_CIPHER_CTX_ctrl(&ctx_,
3423
                        EVP_CTRL_GCM_SET_TAG,
3424
1
                        auth_tag_len_,
3425
2
                        reinterpret_cast<unsigned char*>(auth_tag_));
3426
1
    delete[] auth_tag_;
3427
1
    auth_tag_ = nullptr;
3428
  }
3429
3430
77
  *out_len = len + EVP_CIPHER_CTX_block_size(&ctx_);
3431
77
  *out = new unsigned char[*out_len];
3432
77
  return EVP_CipherUpdate(&ctx_,
3433
                          *out,
3434
                          out_len,
3435
                          reinterpret_cast<const unsigned char*>(data),
3436
77
                          len);
3437
}
3438
3439
3440
79
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
3441
79
  Environment* env = Environment::GetCurrent(args);
3442
3443
  CipherBase* cipher;
3444
81
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3445
3446
298
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Cipher data");
3447
3448
79
  unsigned char* out = nullptr;
3449
  bool r;
3450
79
  int out_len = 0;
3451
3452
  // Only copy the data if we have to, because it's a string
3453
158
  if (args[0]->IsString()) {
3454
138
    StringBytes::InlineDecoder decoder;
3455
210
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3456
2
      return;
3457
68
    r = cipher->Update(decoder.out(), decoder.size(), &out, &out_len);
3458
  } else {
3459
9
    char* buf = Buffer::Data(args[0]);
3460
9
    size_t buflen = Buffer::Length(args[0]);
3461
9
    r = cipher->Update(buf, buflen, &out, &out_len);
3462
  }
3463
3464
77
  if (!r) {
3465
    delete[] out;
3466
    return ThrowCryptoError(env,
3467
                            ERR_get_error(),
3468
                            "Trying to add data in unsupported state");
3469
  }
3470
3471
77
  CHECK(out != nullptr || out_len == 0);
3472
  Local<Object> buf =
3473
154
      Buffer::Copy(env, reinterpret_cast<char*>(out), out_len).ToLocalChecked();
3474
77
  if (out)
3475
77
    delete[] out;
3476
3477
154
  args.GetReturnValue().Set(buf);
3478
}
3479
3480
3481
bool CipherBase::SetAutoPadding(bool auto_padding) {
3482
18
  if (!initialised_)
3483
    return false;
3484
18
  return EVP_CIPHER_CTX_set_padding(&ctx_, auto_padding);
3485
}
3486
3487
3488
18
void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
3489
  CipherBase* cipher;
3490
18
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3491
72
  cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue());
3492
}
3493
3494
3495
85
bool CipherBase::Final(unsigned char** out, int *out_len) {
3496
85
  if (!initialised_)
3497
    return false;
3498
3499
81
  *out = new unsigned char[EVP_CIPHER_CTX_block_size(&ctx_)];
3500
81
  int r = EVP_CipherFinal_ex(&ctx_, *out, out_len);
3501
3502
81
  if (r && kind_ == kCipher) {
3503
40
    delete[] auth_tag_;
3504
40
    auth_tag_ = nullptr;
3505
40
    if (IsAuthenticatedMode()) {
3506
1
      auth_tag_len_ = EVP_GCM_TLS_TAG_LEN;  // use default tag length
3507
1
      auth_tag_ = new char[auth_tag_len_];
3508
2
      memset(auth_tag_, 0, auth_tag_len_);
3509
1
      EVP_CIPHER_CTX_ctrl(&ctx_,
3510
                          EVP_CTRL_GCM_GET_TAG,
3511
                          auth_tag_len_,
3512
1
                          reinterpret_cast<unsigned char*>(auth_tag_));
3513
    }
3514
  }
3515
3516
81
  EVP_CIPHER_CTX_cleanup(&ctx_);
3517
81
  initialised_ = false;
3518
3519
81
  return r == 1;
3520
}
3521
3522
3523
85
void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
3524
85
  Environment* env = Environment::GetCurrent(args);
3525
3526
  CipherBase* cipher;
3527
95
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3528
3529
85
  unsigned char* out_value = nullptr;
3530
85
  int out_len = -1;
3531
85
  Local<Value> outString;
3532
3533
85
  bool r = cipher->Final(&out_value, &out_len);
3534
3535
85
  if (out_len <= 0 || !r) {
3536
35
    delete[] out_value;
3537
35
    out_value = nullptr;
3538
35
    out_len = 0;
3539
35
    if (!r) {
3540
20
      const char* msg = cipher->IsAuthenticatedMode() ?
3541
          "Unsupported state or unable to authenticate data" :
3542
10
          "Unsupported state";
3543
3544
10
      return ThrowCryptoError(env,
3545
                              ERR_get_error(),
3546
10
                              msg);
3547
    }
3548
  }
3549
3550
150
  Local<Object> buf = Buffer::Copy(
3551
      env,
3552
      reinterpret_cast<char*>(out_value),
3553
150
      out_len).ToLocalChecked();
3554
150
  args.GetReturnValue().Set(buf);
3555
75
  delete[] out_value;
3556
}
3557
3558
3559
182
void Hmac::Initialize(Environment* env, v8::Local<v8::Object> target) {
3560
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3561
3562
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3563
3564
182
  env->SetProtoMethod(t, "init", HmacInit);
3565
182
  env->SetProtoMethod(t, "update", HmacUpdate);
3566
182
  env->SetProtoMethod(t, "digest", HmacDigest);
3567
3568
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hmac"), t->GetFunction());
3569
182
}
3570
3571
3572
126
void Hmac::New(const FunctionCallbackInfo<Value>& args) {
3573
126
  Environment* env = Environment::GetCurrent(args);
3574
252
  new Hmac(env, args.This());
3575
126
}
3576
3577
3578
126
void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) {
3579
252
  HandleScope scope(env()->isolate());
3580
3581
126
  CHECK_EQ(initialised_, false);
3582
126
  const EVP_MD* md = EVP_get_digestbyname(hash_type);
3583
126
  if (md == nullptr) {
3584
    return env()->ThrowError("Unknown message digest");
3585
  }
3586
126
  HMAC_CTX_init(&ctx_);
3587
126
  if (key_len == 0) {
3588
6
    key = "";
3589
  }
3590
126
  if (!HMAC_Init_ex(&ctx_, key, key_len, md, nullptr)) {
3591
    return ThrowCryptoError(env(), ERR_get_error());
3592
  }
3593
126
  initialised_ = true;
3594
}
3595
3596
3597
126
void Hmac::HmacInit(const FunctionCallbackInfo<Value>& args) {
3598
  Hmac* hmac;
3599
126
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3600
126
  Environment* env = hmac->env();
3601
3602
126
  if (args.Length() < 2) {
3603
    return env->ThrowError("Hash type and key arguments are mandatory");
3604
  }
3605
3606
252
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Hash type");
3607
126
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3608
3609
252
  const node::Utf8Value hash_type(env->isolate(), args[0]);
3610
126
  const char* buffer_data = Buffer::Data(args[1]);
3611
126
  size_t buffer_length = Buffer::Length(args[1]);
3612
126
  hmac->HmacInit(*hash_type, buffer_data, buffer_length);
3613
}
3614
3615
3616
bool Hmac::HmacUpdate(const char* data, int len) {
3617
128
  if (!initialised_)
3618
    return false;
3619
128
  HMAC_Update(&ctx_, reinterpret_cast<const unsigned char*>(data), len);
3620
  return true;
3621
}
3622
3623
3624
128
void Hmac::HmacUpdate(const FunctionCallbackInfo<Value>& args) {
3625
128
  Environment* env = Environment::GetCurrent(args);
3626
3627
  Hmac* hmac;
3628
128
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3629
3630
328
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Data");
3631
3632
  // Only copy the data if we have to, because it's a string
3633
  bool r;
3634
256
  if (args[0]->IsString()) {
3635
72
    StringBytes::InlineDecoder decoder;
3636
108
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3637
      return;
3638
72
    r = hmac->HmacUpdate(decoder.out(), decoder.size());
3639
  } else {
3640
92
    char* buf = Buffer::Data(args[0]);
3641
92
    size_t buflen = Buffer::Length(args[0]);
3642
184
    r = hmac->HmacUpdate(buf, buflen);
3643
  }
3644
3645
128
  if (!r) {
3646
    return env->ThrowTypeError("HmacUpdate fail");
3647
  }
3648
}
3649
3650
3651
126
bool Hmac::HmacDigest(unsigned char** md_value, unsigned int* md_len) {
3652
126
  if (!initialised_)
3653
    return false;
3654
126
  *md_value = new unsigned char[EVP_MAX_MD_SIZE];
3655
126
  HMAC_Final(&ctx_, *md_value, md_len);
3656
126
  HMAC_CTX_cleanup(&ctx_);
3657
126
  initialised_ = false;
3658
126
  return true;
3659
}
3660
3661
3662
126
void Hmac::HmacDigest(const FunctionCallbackInfo<Value>& args) {
3663
126
  Environment* env = Environment::GetCurrent(args);
3664
3665
  Hmac* hmac;
3666
126
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3667
3668
126
  enum encoding encoding = BUFFER;
3669
126
  if (args.Length() >= 1) {
3670
392
    encoding = ParseEncoding(env->isolate(),
3671
                             args[0]->ToString(env->isolate()),
3672
98
                             BUFFER);
3673
  }
3674
3675
126
  unsigned char* md_value = nullptr;
3676
126
  unsigned int md_len = 0;
3677
3678
126
  bool r = hmac->HmacDigest(&md_value, &md_len);
3679
126
  if (!r) {
3680
    md_value = nullptr;
3681
    md_len = 0;
3682
  }
3683
3684
  Local<Value> rc = StringBytes::Encode(env->isolate(),
3685
                                        reinterpret_cast<const char*>(md_value),
3686
                                        md_len,
3687
126
                                        encoding);
3688
126
  delete[] md_value;
3689
252
  args.GetReturnValue().Set(rc);
3690
}
3691
3692
3693
182
void Hash::Initialize(Environment* env, v8::Local<v8::Object> target) {
3694
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3695
3696
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3697
3698
182
  env->SetProtoMethod(t, "update", HashUpdate);
3699
182
  env->SetProtoMethod(t, "digest", HashDigest);
3700
3701
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hash"), t->GetFunction());
3702
182
}
3703
3704
3705
227
void Hash::New(const FunctionCallbackInfo<Value>& args) {
3706
227
  Environment* env = Environment::GetCurrent(args);
3707
3708
908
  if (args.Length() == 0 || !args[0]->IsString()) {
3709
2
    return env->ThrowError("Must give hashtype string as argument");
3710
  }
3711
3712
452
  const node::Utf8Value hash_type(env->isolate(), args[0]);
3713
3714
454
  Hash* hash = new Hash(env, args.This());
3715
227
  if (!hash->HashInit(*hash_type)) {
3716
2
    return ThrowCryptoError(env, ERR_get_error(),
3717
2
                            "Digest method not supported");
3718
  }
3719
}
3720
3721
3722
227
bool Hash::HashInit(const char* hash_type) {
3723
227
  CHECK_EQ(initialised_, false);
3724
227
  const EVP_MD* md = EVP_get_digestbyname(hash_type);
3725
227
  if (md == nullptr)
3726
    return false;
3727
225
  EVP_MD_CTX_init(&mdctx_);
3728
225
  if (EVP_DigestInit_ex(&mdctx_, md, nullptr) <= 0) {
3729
    return false;
3730
  }
3731
225
  initialised_ = true;
3732
225
  finalized_ = false;
3733
225
  return true;
3734
}
3735
3736
3737
bool Hash::HashUpdate(const char* data, int len) {
3738
542
  if (!initialised_)
3739
    return false;
3740
542
  EVP_DigestUpdate(&mdctx_, data, len);
3741
  return true;
3742
}
3743
3744
3745
546
void Hash::HashUpdate(const FunctionCallbackInfo<Value>& args) {
3746
546
  Environment* env = Environment::GetCurrent(args);
3747
3748
  Hash* hash;
3749
546
  ASSIGN_OR_RETURN_UNWRAP(&hash, args.Holder());
3750
3751
1512
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Data");
3752
3753
544
  if (!hash->initialised_) {
3754
    return env->ThrowError("Not initialized");
3755
  }
3756
544
  if (hash->finalized_) {
3757
    return env->ThrowError("Digest already called");
3758
  }
3759
3760
  // Only copy the data if we have to, because it's a string
3761
  bool r;
3762
1086
  if (args[0]->IsString()) {
3763
413
    StringBytes::InlineDecoder decoder;
3764
621
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3765
1
      return;
3766
412
    r = hash->HashUpdate(decoder.out(), decoder.size());
3767
  } else {
3768
336
    char* buf = Buffer::Data(args[0]);
3769
336
    size_t buflen = Buffer::Length(args[0]);
3770
672
    r = hash->HashUpdate(buf, buflen);
3771
  }
3772
3773
542
  if (!r) {
3774
    return env->ThrowTypeError("HashUpdate fail");
3775
  }
3776
}
3777
3778
3779
218
void Hash::HashDigest(const FunctionCallbackInfo<Value>& args) {
3780
218
  Environment* env = Environment::GetCurrent(args);
3781
3782
  Hash* hash;
3783
219
  ASSIGN_OR_RETURN_UNWRAP(&hash, args.Holder());
3784
3785
218
  if (!hash->initialised_) {
3786
    return env->ThrowError("Not initialized");
3787
  }
3788
218
  if (hash->finalized_) {
3789
    return env->ThrowError("Digest already called");
3790
  }
3791
3792
217
  enum encoding encoding = BUFFER;
3793
217
  if (args.Length() >= 1) {
3794
844
    encoding = ParseEncoding(env->isolate(),
3795
                             args[0]->ToString(env->isolate()),
3796
211
                             BUFFER);
3797
  }
3798
3799
  unsigned char md_value[EVP_MAX_MD_SIZE];
3800
  unsigned int md_len;
3801
3802
217
  EVP_DigestFinal_ex(&hash->mdctx_, md_value, &md_len);
3803
217
  EVP_MD_CTX_cleanup(&hash->mdctx_);
3804
217
  hash->finalized_ = true;
3805
3806
  Local<Value> rc = StringBytes::Encode(env->isolate(),
3807
                                        reinterpret_cast<const char*>(md_value),
3808
                                        md_len,
3809
217
                                        encoding);
3810
434
  args.GetReturnValue().Set(rc);
3811
}
3812
3813
3814
91
void SignBase::CheckThrow(SignBase::Error error) {
3815
91
  HandleScope scope(env()->isolate());
3816
3817
91
  switch (error) {
3818
    case kSignUnknownDigest:
3819
91
      return env()->ThrowError("Unknown message digest");
3820
3821
    case kSignNotInitialised:
3822
      return env()->ThrowError("Not initialised");
3823
3824
    case kSignInit:
3825
    case kSignUpdate:
3826
    case kSignPrivateKey:
3827
    case kSignPublicKey:
3828
      {
3829
4
        unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
3830
4
        if (err)
3831
4
          return ThrowCryptoError(env(), err);
3832
        switch (error) {
3833
          case kSignInit:
3834
            return env()->ThrowError("EVP_SignInit_ex failed");
3835
          case kSignUpdate:
3836
            return env()->ThrowError("EVP_SignUpdate failed");
3837
          case kSignPrivateKey:
3838
            return env()->ThrowError("PEM_read_bio_PrivateKey failed");
3839
          case kSignPublicKey:
3840
            return env()->ThrowError("PEM_read_bio_PUBKEY failed");
3841
          default:
3842
            ABORT();
3843
        }
3844
      }
3845
3846
    case kSignOk:
3847
      return;
3848
  }
3849
}
3850
3851
3852
3853
3854
182
void Sign::Initialize(Environment* env, v8::Local<v8::Object> target) {
3855
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3856
3857
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3858
3859
182
  env->SetProtoMethod(t, "init", SignInit);
3860
182
  env->SetProtoMethod(t, "update", SignUpdate);
3861
182
  env->SetProtoMethod(t, "sign", SignFinal);
3862
3863
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Sign"), t->GetFunction());
3864
182
}
3865
3866
3867
21
void Sign::New(const FunctionCallbackInfo<Value>& args) {
3868
21
  Environment* env = Environment::GetCurrent(args);
3869
21
  new Sign(env, args.This());
3870
21
}
3871
3872
3873
21
SignBase::Error Sign::SignInit(const char* sign_type) {
3874
21
  CHECK_EQ(initialised_, false);
3875
21
  const EVP_MD* md = EVP_get_digestbyname(sign_type);
3876
21
  if (md == nullptr)
3877
    return kSignUnknownDigest;
3878
3879
21
  EVP_MD_CTX_init(&mdctx_);
3880
21
  if (!EVP_SignInit_ex(&mdctx_, md, nullptr))
3881
    return kSignInit;
3882
21
  initialised_ = true;
3883
3884
21
  return kSignOk;
3885
}
3886
3887
3888
21
void Sign::SignInit(const FunctionCallbackInfo<Value>& args) {
3889
  Sign* sign;
3890
21
  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
3891
21
  Environment* env = sign->env();
3892
3893
21
  if (args.Length() == 0) {
3894
    return env->ThrowError("Sign type argument is mandatory");
3895
  }
3896
3897
42
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Sign type");
3898
3899
63
  const node::Utf8Value sign_type(args.GetIsolate(), args[0]);
3900
21
  sign->CheckThrow(sign->SignInit(*sign_type));
3901
}
3902
3903
3904
SignBase::Error Sign::SignUpdate(const char* data, int len) {
3905
19
  if (!initialised_)
3906
    return kSignNotInitialised;
3907
19
  if (!EVP_SignUpdate(&mdctx_, data, len))
3908
    return kSignUpdate;
3909
  return kSignOk;
3910
}
3911
3912
3913
20
void Sign::SignUpdate(const FunctionCallbackInfo<Value>& args) {
3914
20
  Environment* env = Environment::GetCurrent(args);
3915
3916
  Sign* sign;
3917
20
  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
3918
3919
76
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Data");
3920
3921
  // Only copy the data if we have to, because it's a string
3922
  Error err;
3923
40
  if (args[0]->IsString()) {
3924
35
    StringBytes::InlineDecoder decoder;
3925
54
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3926
1
      return;
3927
34
    err = sign->SignUpdate(decoder.out(), decoder.size());
3928
  } else {
3929
2
    char* buf = Buffer::Data(args[0]);
3930
2
    size_t buflen = Buffer::Length(args[0]);
3931
4
    err = sign->SignUpdate(buf, buflen);
3932
  }
3933
3934
19
  sign->CheckThrow(err);
3935
}
3936
3937
3938
20
SignBase::Error Sign::SignFinal(const char* key_pem,
3939
                                int key_pem_len,
3940
                                const char* passphrase,
3941
                                unsigned char** sig,
3942
                                unsigned int *sig_len) {
3943
20
  if (!initialised_)
3944
    return kSignNotInitialised;
3945
3946
20
  BIO* bp = nullptr;
3947
20
  EVP_PKEY* pkey = nullptr;
3948
20
  bool fatal = true;
3949
3950
20
  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
3951
20
  if (bp == nullptr)
3952
    goto exit;
3953
3954
  pkey = PEM_read_bio_PrivateKey(bp,
3955
                                 nullptr,
3956
                                 CryptoPemCallback,
3957
20
                                 const_cast<char*>(passphrase));
3958
3959
  // Errors might be injected into OpenSSL's error stack
3960
  // without `pkey` being set to nullptr;
3961
  // cf. the test of `test_bad_rsa_privkey.pem` for an example.
3962
20
  if (pkey == nullptr || 0 != ERR_peek_error())
3963
    goto exit;
3964
3965
#ifdef NODE_FIPS_MODE
3966
  /* Validate DSA2 parameters from FIPS 186-4 */
3967
  if (FIPS_mode() && EVP_PKEY_DSA == pkey->type) {
3968
    size_t L = BN_num_bits(pkey->pkey.dsa->p);
3969
    size_t N = BN_num_bits(pkey->pkey.dsa->q);
3970
    bool result = false;
3971
3972
    if (L == 1024 && N == 160)
3973
      result = true;
3974
    else if (L == 2048 && N == 224)
3975
      result = true;
3976
    else if (L == 2048 && N == 256)
3977
      result = true;
3978
    else if (L == 3072 && N == 256)
3979
      result = true;
3980
3981
    if (!result) {
3982
      fatal = true;
3983
      goto exit;
3984
    }
3985
  }
3986
#endif  // NODE_FIPS_MODE
3987
3988
17
  if (EVP_SignFinal(&mdctx_, *sig, sig_len, pkey))
3989
16
    fatal = false;
3990
3991
17
  initialised_ = false;
3992
3993
 exit:
3994
20
  if (pkey != nullptr)
3995
18
    EVP_PKEY_free(pkey);
3996
20
  if (bp != nullptr)
3997
20
    BIO_free_all(bp);
3998
3999
20
  EVP_MD_CTX_cleanup(&mdctx_);
4000
4001
20
  if (fatal)
4002
    return kSignPrivateKey;
4003
4004
16
  return kSignOk;
4005
}
4006
4007
4008
20
void Sign::SignFinal(const FunctionCallbackInfo<Value>& args) {
4009
20
  Environment* env = Environment::GetCurrent(args);
4010
4011
  Sign* sign;
4012
24
  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
4013
4014
  unsigned char* md_value;
4015
  unsigned int md_len;
4016
4017
20
  unsigned int len = args.Length();
4018
20
  enum encoding encoding = BUFFER;
4019
60
  if (len >= 2 && args[1]->IsString()) {
4020
    encoding = ParseEncoding(env->isolate(),
4021
                             args[1]->ToString(env->isolate()),
4022
                             BUFFER);
4023
  }
4024
4025
36
  node::Utf8Value passphrase(env->isolate(), args[2]);
4026
4027
20
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
4028
20
  size_t buf_len = Buffer::Length(args[0]);
4029
20
  char* buf = Buffer::Data(args[0]);
4030
4031
20
  md_len = 8192;  // Maximum key size is 8192 bits
4032
20
  md_value = new unsigned char[md_len];
4033
4034
16
  ClearErrorOnReturn clear_error_on_return;
4035
  (void) &clear_error_on_return;  // Silence compiler warning.
4036
4037
24
  Error err = sign->SignFinal(
4038
      buf,
4039
      buf_len,
4040
40
      len >= 3 && !args[2]->IsNull() ? *passphrase : nullptr,
4041
      &md_value,
4042
20
      &md_len);
4043
20
  if (err != kSignOk) {
4044
4
    delete[] md_value;
4045
4
    md_value = nullptr;
4046
4
    md_len = 0;
4047
4
    return sign->CheckThrow(err);
4048
  }
4049
4050
  Local<Value> rc = StringBytes::Encode(env->isolate(),
4051
                                        reinterpret_cast<const char*>(md_value),
4052
                                        md_len,
4053
16
                                        encoding);
4054
16
  delete[] md_value;
4055
32
  args.GetReturnValue().Set(rc);
4056
}
4057
4058
4059
182
void Verify::Initialize(Environment* env, v8::Local<v8::Object> target) {
4060
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
4061
4062
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
4063
4064
182
  env->SetProtoMethod(t, "init", VerifyInit);
4065
182
  env->SetProtoMethod(t, "update", VerifyUpdate);
4066
182
  env->SetProtoMethod(t, "verify", VerifyFinal);
4067
4068
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Verify"),
4069
182
              t->GetFunction());
4070
182
}
4071
4072
4073
19
void Verify::New(const FunctionCallbackInfo<Value>& args) {
4074
19
  Environment* env = Environment::GetCurrent(args);
4075
19
  new Verify(env, args.This());
4076
19
}
4077
4078
4079
19
SignBase::Error Verify::VerifyInit(const char* verify_type) {
4080
19
  CHECK_EQ(initialised_, false);
4081
19
  const EVP_MD* md = EVP_get_digestbyname(verify_type);
4082
19
  if (md == nullptr)
4083
    return kSignUnknownDigest;
4084
4085
19
  EVP_MD_CTX_init(&mdctx_);
4086
19
  if (!EVP_VerifyInit_ex(&mdctx_, md, nullptr))
4087
    return kSignInit;
4088
19
  initialised_ = true;
4089
4090
19
  return kSignOk;
4091
}
4092
4093
4094
19
void Verify::VerifyInit(const FunctionCallbackInfo<Value>& args) {
4095
  Verify* verify;
4096
19
  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4097
19
  Environment* env = verify->env();
4098
4099
19
  if (args.Length() == 0) {
4100
    return env->ThrowError("Verify type argument is mandatory");
4101
  }
4102
4103
38
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Verify type");
4104
4105
57
  const node::Utf8Value verify_type(args.GetIsolate(), args[0]);
4106
19
  verify->CheckThrow(verify->VerifyInit(*verify_type));
4107
}
4108
4109
4110
SignBase::Error Verify::VerifyUpdate(const char* data, int len) {
4111
28
  if (!initialised_)
4112
    return kSignNotInitialised;
4113
4114
28
  if (!EVP_VerifyUpdate(&mdctx_, data, len))
4115
    return kSignUpdate;
4116
4117
  return kSignOk;
4118
}
4119
4120
4121
29
void Verify::VerifyUpdate(const FunctionCallbackInfo<Value>& args) {
4122
29
  Environment* env = Environment::GetCurrent(args);
4123
4124
  Verify* verify;
4125
29
  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4126
4127
104
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Data");
4128
4129
  // Only copy the data if we have to, because it's a string
4130
  Error err;
4131
58
  if (args[0]->IsString()) {
4132
45
    StringBytes::InlineDecoder decoder;
4133
69
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
4134
1
      return;
4135
44
    err = verify->VerifyUpdate(decoder.out(), decoder.size());
4136
  } else {
4137
6
    char* buf = Buffer::Data(args[0]);
4138
6
    size_t buflen = Buffer::Length(args[0]);
4139
12
    err = verify->VerifyUpdate(buf, buflen);
4140
  }
4141
4142
28
  verify->CheckThrow(err);
4143
}
4144
4145
4146
18
SignBase::Error Verify::VerifyFinal(const char* key_pem,
4147
                                    int key_pem_len,
4148
                                    const char* sig,
4149
                                    int siglen,
4150
                                    bool* verify_result) {
4151
18
  if (!initialised_)
4152
    return kSignNotInitialised;
4153
4154
  ClearErrorOnReturn clear_error_on_return;
4155
  (void) &clear_error_on_return;  // Silence compiler warning.
4156
4157
18
  EVP_PKEY* pkey = nullptr;
4158
18
  BIO* bp = nullptr;
4159
18
  X509* x509 = nullptr;
4160
18
  bool fatal = true;
4161
18
  int r = 0;
4162
4163
18
  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
4164
18
  if (bp == nullptr)
4165
    goto exit;
4166
4167
  // Check if this is a PKCS#8 or RSA public key before trying as X.509.
4168
  // Split this out into a separate function once we have more than one
4169
  // consumer of public keys.
4170
18
  if (strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
4171
6
    pkey = PEM_read_bio_PUBKEY(bp, nullptr, CryptoPemCallback, nullptr);
4172
6
    if (pkey == nullptr)
4173
      goto exit;
4174
12
  } else if (strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
4175
    RSA* rsa =
4176
2
        PEM_read_bio_RSAPublicKey(bp, nullptr, CryptoPemCallback, nullptr);
4177
2
    if (rsa) {
4178
2
      pkey = EVP_PKEY_new();
4179
2
      if (pkey)
4180
2
        EVP_PKEY_set1_RSA(pkey, rsa);
4181
2
      RSA_free(rsa);
4182
    }
4183
2
    if (pkey == nullptr)
4184
      goto exit;
4185
  } else {
4186
    // X.509 fallback
4187
10
    x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr);
4188
10
    if (x509 == nullptr)
4189
      goto exit;
4190
4191
10
    pkey = X509_get_pubkey(x509);
4192
10
    if (pkey == nullptr)
4193
      goto exit;
4194
  }
4195
4196
18
  fatal = false;
4197
18
  r = EVP_VerifyFinal(&mdctx_,
4198
                      reinterpret_cast<const unsigned char*>(sig),
4199
                      siglen,
4200
18
                      pkey);
4201
4202
 exit:
4203
18
  if (pkey != nullptr)
4204
18
    EVP_PKEY_free(pkey);
4205
18
  if (bp != nullptr)
4206
18
    BIO_free_all(bp);
4207
18
  if (x509 != nullptr)
4208
10
    X509_free(x509);
4209
4210
18
  EVP_MD_CTX_cleanup(&mdctx_);
4211
18
  initialised_ = false;
4212
4213
18
  if (fatal)
4214
    return kSignPublicKey;
4215
4216
18
  *verify_result = r == 1;
4217
18
  return kSignOk;
4218
}
4219
4220
4221
18
void Verify::VerifyFinal(const FunctionCallbackInfo<Value>& args) {
4222
18
  Environment* env = Environment::GetCurrent(args);
4223
4224
  Verify* verify;
4225
18
  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4226
4227
18
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Key");
4228
18
  char* kbuf = Buffer::Data(args[0]);
4229
18
  ssize_t klen = Buffer::Length(args[0]);
4230
4231
36
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[1], "Hash");
4232
4233
18
  enum encoding encoding = UTF8;
4234
18
  if (args.Length() >= 3) {
4235
    encoding = ParseEncoding(env->isolate(),
4236
                             args[2]->ToString(env->isolate()),
4237
                             UTF8);
4238
  }
4239
4240
18
  ssize_t hlen = StringBytes::Size(env->isolate(), args[1], encoding);
4241
4242
  // only copy if we need to, because it's a string.
4243
  char* hbuf;
4244
36
  if (args[1]->IsString()) {
4245
    hbuf = new char[hlen];
4246
    ssize_t hwritten = StringBytes::Write(env->isolate(),
4247
                                          hbuf,
4248
                                          hlen,
4249
                                          args[1],
4250
                                          encoding);
4251
    CHECK_EQ(hwritten, hlen);
4252
  } else {
4253
18
    hbuf = Buffer::Data(args[1]);
4254
  }
4255
4256
  bool verify_result;
4257
18
  Error err = verify->VerifyFinal(kbuf, klen, hbuf, hlen, &verify_result);
4258
36
  if (args[1]->IsString())
4259
    delete[] hbuf;
4260
18
  if (err != kSignOk)
4261
    return verify->CheckThrow(err);
4262
54
  args.GetReturnValue().Set(verify_result);
4263
}
4264
4265
4266
template <PublicKeyCipher::Operation operation,
4267
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
4268
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
4269
23
bool PublicKeyCipher::Cipher(const char* key_pem,
4270
                             int key_pem_len,
4271
                             const char* passphrase,
4272
                             int padding,
4273
                             const unsigned char* data,
4274
                             int len,
4275
                             unsigned char** out,
4276
                             size_t* out_len) {
4277
23
  EVP_PKEY* pkey = nullptr;
4278
23
  EVP_PKEY_CTX* ctx = nullptr;
4279
23
  BIO* bp = nullptr;
4280
23
  X509* x509 = nullptr;
4281
23
  bool fatal = true;
4282
4283
23
  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
4284
23
  if (bp == nullptr)
4285
    goto exit;
4286
4287
  // Check if this is a PKCS#8 or RSA public key before trying as X.509 and
4288
  // private key.
4289
11
  if (operation == kPublic &&
4290
11
      strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
4291
4
    pkey = PEM_read_bio_PUBKEY(bp, nullptr, nullptr, nullptr);
4292
4
    if (pkey == nullptr)
4293
      goto exit;
4294
7
  } else if (operation == kPublic &&
4295
7
             strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
4296
    RSA* rsa = PEM_read_bio_RSAPublicKey(bp, nullptr, nullptr, nullptr);
4297
    if (rsa) {
4298
      pkey = EVP_PKEY_new();
4299
      if (pkey)
4300
        EVP_PKEY_set1_RSA(pkey, rsa);
4301
      RSA_free(rsa);
4302
    }
4303
    if (pkey == nullptr)
4304
      goto exit;
4305
7
  } else if (operation == kPublic &&
4306
7
             strncmp(key_pem, CERTIFICATE_PFX, CERTIFICATE_PFX_LEN) == 0) {
4307
1
    x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr);
4308
1
    if (x509 == nullptr)
4309
      goto exit;
4310
4311
1
    pkey = X509_get_pubkey(x509);
4312
1
    if (pkey == nullptr)
4313
      goto exit;
4314
  } else {
4315
18
    pkey = PEM_read_bio_PrivateKey(bp,
4316
                                   nullptr,
4317
                                   CryptoPemCallback,
4318
                                   const_cast<char*>(passphrase));
4319
18
    if (pkey == nullptr)
4320
      goto exit;
4321
  }
4322
4323
20
  ctx = EVP_PKEY_CTX_new(pkey, nullptr);
4324
20
  if (!ctx)
4325
    goto exit;
4326
20
  if (EVP_PKEY_cipher_init(ctx) <= 0)
4327
    goto exit;
4328
20
  if (EVP_PKEY_CTX_set_rsa_padding(ctx, padding) <= 0)
4329
    goto exit;
4330
4331
20
  if (EVP_PKEY_cipher(ctx, nullptr, out_len, data, len) <= 0)
4332
    goto exit;
4333
4334
20
  *out = new unsigned char[*out_len];
4335
4336
20
  if (EVP_PKEY_cipher(ctx, *out, out_len, data, len) <= 0)
4337
    goto exit;
4338
4339
20
  fatal = false;
4340
4341
 exit:
4342
11
  if (x509 != nullptr)
4343
1
    X509_free(x509);
4344
23
  if (pkey != nullptr)
4345
20
    EVP_PKEY_free(pkey);
4346
23
  if (bp != nullptr)
4347
23
    BIO_free_all(bp);
4348
23
  if (ctx != nullptr)
4349
20
    EVP_PKEY_CTX_free(ctx);
4350
4351
23
  return !fatal;
4352
}
4353
4354
4355
template <PublicKeyCipher::Operation operation,
4356
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
4357
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
4358
23
void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
4359
23
  Environment* env = Environment::GetCurrent(args);
4360
4361
26
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Key");
4362
23
  char* kbuf = Buffer::Data(args[0]);
4363
23
  ssize_t klen = Buffer::Length(args[0]);
4364
4365
23
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Data");
4366
23
  char* buf = Buffer::Data(args[1]);
4367
23
  ssize_t len = Buffer::Length(args[1]);
4368
4369
23
  int padding = args[2]->Uint32Value();
4370
4371
43
  String::Utf8Value passphrase(args[3]);
4372
4373
23
  unsigned char* out_value = nullptr;
4374
23
  size_t out_len = 0;
4375
4376
  ClearErrorOnReturn clear_error_on_return;
4377
  (void) &clear_error_on_return;  // Silence compiler warning.
4378
4379
92
  bool r = Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
4380
      kbuf,
4381
      klen,
4382
92
      args.Length() >= 3 && !args[2]->IsNull() ? *passphrase : nullptr,
4383
      padding,
4384
      reinterpret_cast<const unsigned char*>(buf),
4385
      len,
4386
      &out_value,
4387
23
      &out_len);
4388
4389
23
  if (out_len == 0 || !r) {
4390
3
    delete[] out_value;
4391
3
    out_value = nullptr;
4392
3
    out_len = 0;
4393
3
    if (!r) {
4394
3
      return ThrowCryptoError(env,
4395
3
        ERR_get_error());
4396
    }
4397
  }
4398
4399
20
  Local<Object> vbuf = Buffer::Copy(
4400
      env,
4401
      reinterpret_cast<char*>(out_value),
4402
40
      out_len).ToLocalChecked();
4403
40
  args.GetReturnValue().Set(vbuf);
4404
20
  delete[] out_value;
4405
}
4406
4407
4408
182
void DiffieHellman::Initialize(Environment* env, Local<Object> target) {
4409
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
4410
4411
  const PropertyAttribute attributes =
4412
182
      static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
4413
4414
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
4415
4416
182
  env->SetProtoMethod(t, "generateKeys", GenerateKeys);
4417
182
  env->SetProtoMethod(t, "computeSecret", ComputeSecret);
4418
182
  env->SetProtoMethod(t, "getPrime", GetPrime);
4419
182
  env->SetProtoMethod(t, "getGenerator", GetGenerator);
4420
182
  env->SetProtoMethod(t, "getPublicKey", GetPublicKey);
4421
182
  env->SetProtoMethod(t, "getPrivateKey", GetPrivateKey);
4422
182
  env->SetProtoMethod(t, "setPublicKey", SetPublicKey);
4423
182
  env->SetProtoMethod(t, "setPrivateKey", SetPrivateKey);
4424
4425
1092
  t->InstanceTemplate()->SetAccessor(
4426
      env->verify_error_string(),
4427
      DiffieHellman::VerifyErrorGetter,
4428
      nullptr,
4429
      env->as_external(),
4430
      DEFAULT,
4431
      attributes,
4432
182
      AccessorSignature::New(env->isolate(), t));
4433
4434
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellman"),
4435
182
              t->GetFunction());
4436
4437
364
  Local<FunctionTemplate> t2 = env->NewFunctionTemplate(DiffieHellmanGroup);
4438
364
  t2->InstanceTemplate()->SetInternalFieldCount(1);
4439
4440
182
  env->SetProtoMethod(t2, "generateKeys", GenerateKeys);
4441
182
  env->SetProtoMethod(t2, "computeSecret", ComputeSecret);
4442
182
  env->SetProtoMethod(t2, "getPrime", GetPrime);
4443
182
  env->SetProtoMethod(t2, "getGenerator", GetGenerator);
4444
182
  env->SetProtoMethod(t2, "getPublicKey", GetPublicKey);
4445
182
  env->SetProtoMethod(t2, "getPrivateKey", GetPrivateKey);
4446
4447
1092
  t2->InstanceTemplate()->SetAccessor(
4448
      env->verify_error_string(),
4449
      DiffieHellman::VerifyErrorGetter,
4450
      nullptr,
4451
      env->as_external(),
4452
      DEFAULT,
4453
      attributes,
4454
182
      AccessorSignature::New(env->isolate(), t2));
4455
4456
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellmanGroup"),
4457
182
              t2->GetFunction());
4458
182
}
4459
4460
4461
3
bool DiffieHellman::Init(int primeLength, int g) {
4462
3
  dh = DH_new();
4463
3
  if (!DH_generate_parameters_ex(dh, primeLength, g, 0))
4464
    return false;
4465
3
  bool result = VerifyContext();
4466
3
  if (!result)
4467
    return false;
4468
3
  initialised_ = true;
4469
3
  return true;
4470
}
4471
4472
4473
8
bool DiffieHellman::Init(const char* p, int p_len, int g) {
4474
8
  dh = DH_new();
4475
8
  dh->p = BN_bin2bn(reinterpret_cast<const unsigned char*>(p), p_len, 0);
4476
8
  dh->g = BN_new();
4477
8
  if (!BN_set_word(dh->g, g))
4478
    return false;
4479
8
  bool result = VerifyContext();
4480
8
  if (!result)
4481
    return false;
4482
8
  initialised_ = true;
4483
8
  return true;
4484
}
4485
4486
4487
7
bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) {
4488
7
  dh = DH_new();
4489
7
  dh->p = BN_bin2bn(reinterpret_cast<const unsigned char*>(p), p_len, 0);
4490
7
  dh->g = BN_bin2bn(reinterpret_cast<const unsigned char*>(g), g_len, 0);
4491
7
  bool result = VerifyContext();
4492
7
  if (!result)
4493
    return false;
4494
7
  initialised_ = true;
4495
7
  return true;
4496
}
4497
4498
4499
4
void DiffieHellman::DiffieHellmanGroup(
4500
    const FunctionCallbackInfo<Value>& args) {
4501
4
  Environment* env = Environment::GetCurrent(args);
4502
4
  DiffieHellman* diffieHellman = new DiffieHellman(env, args.This());
4503
4504
4
  if (args.Length() != 1) {
4505
4
    return env->ThrowError("Group name argument is mandatory");
4506
  }
4507
4508
8
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Group name");
4509
4510
4
  bool initialized = false;
4511
4512
4
  const node::Utf8Value group_name(env->isolate(), args[0]);
4513
12
  for (size_t i = 0; i < arraysize(modp_groups); ++i) {
4514
12
    const modp_group* it = modp_groups + i;
4515
4516
12
    if (!StringEqualNoCase(*group_name, it->name))
4517
      continue;
4518
4519
8
    initialized = diffieHellman->Init(it->prime,
4520
4
                                      it->prime_size,
4521
4
                                      it->gen,
4522
8
                                      it->gen_size);
4523
4
    if (!initialized)
4524
      env->ThrowError("Initialization failed");
4525
    return;
4526
  }
4527
4528
  env->ThrowError("Unknown group");
4529
}
4530
4531
4532
14
void DiffieHellman::New(const FunctionCallbackInfo<Value>& args) {
4533
14
  Environment* env = Environment::GetCurrent(args);
4534
  DiffieHellman* diffieHellman =
4535
14
      new DiffieHellman(env, args.This());
4536
14
  bool initialized = false;
4537
4538
14
  if (args.Length() == 2) {
4539
14
    if (args[0]->IsInt32()) {
4540
3
      if (args[1]->IsInt32()) {
4541
6
        initialized = diffieHellman->Init(args[0]->Int32Value(),
4542
3
                                          args[1]->Int32Value());
4543
      }
4544
    } else {
4545
11
      if (args[1]->IsInt32()) {
4546
24
        initialized = diffieHellman->Init(Buffer::Data(args[0]),
4547
8
                                          Buffer::Length(args[0]),
4548
8
                                          args[1]->Int32Value());
4549
      } else {
4550
9
        initialized = diffieHellman->Init(Buffer::Data(args[0]),
4551
3
                                          Buffer::Length(args[0]),
4552
3
                                          Buffer::Data(args[1]),
4553
6
                                          Buffer::Length(args[1]));
4554
      }
4555
    }
4556
  }
4557
4558
14
  if (!initialized) {
4559
    return ThrowCryptoError(env, ERR_get_error(), "Initialization failed");
4560
  }
4561
}
4562