GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/src/node_crypto.cc Lines: 2492 2763 90.2 %
Date: 2016-07-18 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
1565
static X509_NAME* cnnic_name =
100
1565
    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
1565
static X509_NAME *cnnic_ev_name =
115
1565
    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
42615
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
42615
  CRYPTO_THREADID_set_pointer(tid, reinterpret_cast<void*>(uv_thread_self()));
181
42615
}
182
183
184
182
static void crypto_lock_init(void) {
185
182
  mutexes = new Mutex[CRYPTO_num_locks()];
186
182
}
187
188
189
1040684
static void crypto_lock_cb(int mode, int n, const char* file, int line) {
190
1040684
  CHECK(!(mode & CRYPTO_LOCK) ^ !(mode & CRYPTO_UNLOCK));
191
1040684
  CHECK(!(mode & CRYPTO_READ) ^ !(mode & CRYPTO_WRITE));
192
193
1040684
  auto mutex = &mutexes[n];
194
1040684
  if (mode & CRYPTO_LOCK)
195
    mutex->Lock();
196
  else
197
    mutex->Unlock();
198
1040684
}
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
3154
inline void CheckEntropy() {
249
  for (;;) {
250
3154
    int status = RAND_status();
251
3154
    CHECK_GE(status, 0);  // Cannot fail.
252
3154
    if (status != 0)
253
      break;
254
255
    // Give up, RAND_poll() not supported.
256
    if (RAND_poll() == 0)
257
      break;
258
  }
259
3154
}
260
261
262
3112
bool EntropySource(unsigned char* buffer, size_t length) {
263
  // Ensure that OpenSSL's PRNG is properly seeded.
264
3112
  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
3112
  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
4
  HandleScope scope(args.GetIsolate());
1826
1827
  Base* w;
1828
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1829
2
  Environment* env = w->env();
1830
1831
2
  if (args.Length() < 1)
1832
    return env->ThrowTypeError("OCSP response argument is mandatory");
1833
1834
2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "OCSP response");
1835
1836
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
1837
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1838
}
1839
1840
1841
template <class Base>
1842
3
void SSLWrap<Base>::RequestOCSP(
1843
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1844
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
1845
6
  HandleScope scope(args.GetIsolate());
1846
1847
  Base* w;
1848
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1849
1850
3
  SSL_set_tlsext_status_type(w->ssl_, TLSEXT_STATUSTYPE_ocsp);
1851
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
1852
}
1853
1854
1855
template <class Base>
1856
263
void SSLWrap<Base>::GetEphemeralKeyInfo(
1857
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1858
  Base* w;
1859
263
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1860
263
  Environment* env = Environment::GetCurrent(args);
1861
1862
263
  CHECK_NE(w->ssl_, nullptr);
1863
1864
  // tmp key is available on only client
1865
526
  if (w->is_server())
1866
10
    return args.GetReturnValue().SetNull();
1867
1868
258
  Local<Object> info = Object::New(env->isolate());
1869
1870
  EVP_PKEY* key;
1871
1872
258
  if (SSL_get_server_tmp_key(w->ssl_, &key)) {
1873
223
    switch (EVP_PKEY_id(key)) {
1874
      case EVP_PKEY_DH:
1875
24
        info->Set(env->type_string(),
1876
                  FIXED_ONE_BYTE_STRING(env->isolate(), "DH"));
1877
24
        info->Set(env->size_string(),
1878
                  Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1879
6
        break;
1880
      case EVP_PKEY_EC:
1881
        {
1882
217
          EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
1883
217
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
1884
217
          EC_KEY_free(ec);
1885
868
          info->Set(env->type_string(),
1886
                    FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"));
1887
1085
          info->Set(env->name_string(),
1888
                    OneByteString(args.GetIsolate(), OBJ_nid2sn(nid)));
1889
868
          info->Set(env->size_string(),
1890
                    Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1891
        }
1892
    }
1893
223
    EVP_PKEY_free(key);
1894
  }
1895
1896
258
  return args.GetReturnValue().Set(info);
1897
}
1898
1899
1900
#ifdef SSL_set_max_send_fragment
1901
template <class Base>
1902
3
void SSLWrap<Base>::SetMaxSendFragment(
1903
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1904
6
  HandleScope scope(args.GetIsolate());
1905
9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
1906
1907
  Base* w;
1908
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1909
1910
3
  int rv = SSL_set_max_send_fragment(w->ssl_, args[0]->Int32Value());
1911
6
  args.GetReturnValue().Set(rv);
1912
}
1913
#endif  // SSL_set_max_send_fragment
1914
1915
1916
template <class Base>
1917
23
void SSLWrap<Base>::IsInitFinished(const FunctionCallbackInfo<Value>& args) {
1918
  Base* w;
1919
23
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1920
23
  bool yes = SSL_is_init_finished(w->ssl_);
1921
69
  args.GetReturnValue().Set(yes);
1922
}
1923
1924
1925
template <class Base>
1926
287
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
1927
  Base* w;
1928
331
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1929
1930
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
1931
  // peer certificate is questionable but it's compatible with what was
1932
  // here before.
1933
  long x509_verify_error =  // NOLINT(runtime/int)
1934
287
      X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
1935
287
  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
1936
284
    X509_free(peer_cert);
1937
284
    x509_verify_error = SSL_get_verify_result(w->ssl_);
1938
  }
1939
1940
287
  if (x509_verify_error == X509_V_OK)
1941
88
    return args.GetReturnValue().SetNull();
1942
1943
  // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
1944
  // in the presence of invalid error codes.  Probably academical but something
1945
  // to keep in mind if/when node ever grows multi-isolate capabilities.
1946
243
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
1947
243
  const char* code = reason;
1948
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
1949
243
  switch (x509_verify_error) {
1950
3
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
1951
5
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
1952
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
1953
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
1954
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
1955
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
1956
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
1957
    CASE_X509_ERR(CERT_NOT_YET_VALID)
1958
29
    CASE_X509_ERR(CERT_HAS_EXPIRED)
1959
    CASE_X509_ERR(CRL_NOT_YET_VALID)
1960
    CASE_X509_ERR(CRL_HAS_EXPIRED)
1961
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
1962
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
1963
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
1964
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
1965
    CASE_X509_ERR(OUT_OF_MEM)
1966
107
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
1967
4
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
1968
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
1969
91
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
1970
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
1971
2
    CASE_X509_ERR(CERT_REVOKED)
1972
    CASE_X509_ERR(INVALID_CA)
1973
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
1974
1
    CASE_X509_ERR(INVALID_PURPOSE)
1975
    CASE_X509_ERR(CERT_UNTRUSTED)
1976
    CASE_X509_ERR(CERT_REJECTED)
1977
  }
1978
#undef CASE_X509_ERR
1979
1980
243
  Isolate* isolate = args.GetIsolate();
1981
243
  Local<String> reason_string = OneByteString(isolate, reason);
1982
243
  Local<Value> exception_value = Exception::Error(reason_string);
1983
243
  Local<Object> exception_object = exception_value->ToObject(isolate);
1984
972
  exception_object->Set(FIXED_ONE_BYTE_STRING(isolate, "code"),
1985
                        OneByteString(isolate, code));
1986
486
  args.GetReturnValue().Set(exception_object);
1987
}
1988
1989
1990
template <class Base>
1991
10
void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
1992
  Base* w;
1993
10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1994
19
  Environment* env = w->ssl_env();
1995
1996
10
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
1997
10
  if (c == nullptr)
1998
    return;
1999
2000
10
  Local<Object> info = Object::New(env->isolate());
2001
10
  const char* cipher_name = SSL_CIPHER_get_name(c);
2002
40
  info->Set(env->name_string(), OneByteString(args.GetIsolate(), cipher_name));
2003
10
  const char* cipher_version = SSL_CIPHER_get_version(c);
2004
40
  info->Set(env->version_string(),
2005
            OneByteString(args.GetIsolate(), cipher_version));
2006
10
  args.GetReturnValue().Set(info);
2007
}
2008
2009
2010
template <class Base>
2011
3
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2012
  Base* w;
2013
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2014
2015
3
  const char* tls_version = SSL_get_version(w->ssl_);
2016
6
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2017
}
2018
2019
2020
#ifdef OPENSSL_NPN_NEGOTIATED
2021
template <class Base>
2022
252
int SSLWrap<Base>::AdvertiseNextProtoCallback(SSL* s,
2023
                                              const unsigned char** data,
2024
                                              unsigned int* len,
2025
                                              void* arg) {
2026
252
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2027
252
  Environment* env = w->env();
2028
504
  HandleScope handle_scope(env->isolate());
2029
756
  Context::Scope context_scope(env->context());
2030
2031
  auto npn_buffer =
2032
252
      w->object()->GetPrivate(
2033
          env->context(),
2034
1008
          env->npn_buffer_private_symbol()).ToLocalChecked();
2035
2036
504
  if (npn_buffer->IsUndefined()) {
2037
    // No initialization - no NPN protocols
2038
143
    *data = reinterpret_cast<const unsigned char*>("");
2039
143
    *len = 0;
2040
  } else {
2041
109
    CHECK(Buffer::HasInstance(npn_buffer));
2042
109
    *data = reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2043
109
    *len = Buffer::Length(npn_buffer);
2044
  }
2045
2046
504
  return SSL_TLSEXT_ERR_OK;
2047
}
2048
2049
2050
template <class Base>
2051
251
int SSLWrap<Base>::SelectNextProtoCallback(SSL* s,
2052
                                           unsigned char** out,
2053
                                           unsigned char* outlen,
2054
                                           const unsigned char* in,
2055
                                           unsigned int inlen,
2056
                                           void* arg) {
2057
251
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2058
251
  Environment* env = w->env();
2059
502
  HandleScope handle_scope(env->isolate());
2060
753
  Context::Scope context_scope(env->context());
2061
2062
  auto npn_buffer =
2063
251
      w->object()->GetPrivate(
2064
          env->context(),
2065
1004
          env->npn_buffer_private_symbol()).ToLocalChecked();
2066
2067
502
  if (npn_buffer->IsUndefined()) {
2068
    // We should at least select one protocol
2069
    // If server is using NPN
2070
230
    *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
2071
230
    *outlen = 8;
2072
2073
    // set status: unsupported
2074
1610
    CHECK(
2075
        w->object()->SetPrivate(
2076
            env->context(),
2077
            env->selected_npn_buffer_private_symbol(),
2078
            False(env->isolate())).FromJust());
2079
2080
    return SSL_TLSEXT_ERR_OK;
2081
  }
2082
2083
21
  CHECK(Buffer::HasInstance(npn_buffer));
2084
  const unsigned char* npn_protos =
2085
21
      reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2086
21
  size_t len = Buffer::Length(npn_buffer);
2087
2088
21
  int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
2089
21
  Local<Value> result;
2090
21
  switch (status) {
2091
    case OPENSSL_NPN_UNSUPPORTED:
2092
      result = Null(env->isolate());
2093
      break;
2094
    case OPENSSL_NPN_NEGOTIATED:
2095
14
      result = OneByteString(env->isolate(), *out, *outlen);
2096
7
      break;
2097
    case OPENSSL_NPN_NO_OVERLAP:
2098
42
      result = False(env->isolate());
2099
14
      break;
2100
    default:
2101
      break;
2102
  }
2103
2104
84
  CHECK(
2105
      w->object()->SetPrivate(
2106
          env->context(),
2107
          env->selected_npn_buffer_private_symbol(),
2108
          result).FromJust());
2109
2110
  return SSL_TLSEXT_ERR_OK;
2111
}
2112
2113
2114
template <class Base>
2115
552
void SSLWrap<Base>::GetNegotiatedProto(
2116
    const FunctionCallbackInfo<Value>& args) {
2117
  Base* w;
2118
858
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2119
552
  Environment* env = w->env();
2120
2121
1103
  if (w->is_client()) {
2122
    auto selected_npn_buffer =
2123
255
        w->object()->GetPrivate(
2124
            env->context(),
2125
1020
            env->selected_npn_buffer_private_symbol()).ToLocalChecked();
2126
255
    args.GetReturnValue().Set(selected_npn_buffer);
2127
    return;
2128
  }
2129
2130
  const unsigned char* npn_proto;
2131
  unsigned int npn_proto_len;
2132
2133
297
  SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
2134
2135
297
  if (!npn_proto)
2136
102
    return args.GetReturnValue().Set(false);
2137
2138
984
  args.GetReturnValue().Set(
2139
      OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
2140
}
2141
2142
2143
template <class Base>
2144
142
void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
2145
  Base* w;
2146
142
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2147
142
  Environment* env = w->env();
2148
2149
142
  if (args.Length() < 1)
2150
    return env->ThrowTypeError("NPN protocols argument is mandatory");
2151
2152
142
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "NPN protocols");
2153
2154
710
  CHECK(
2155
      w->object()->SetPrivate(
2156
          env->context(),
2157
          env->npn_buffer_private_symbol(),
2158
          args[0]).FromJust());
2159
}
2160
#endif  // OPENSSL_NPN_NEGOTIATED
2161
2162
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2163
template <class Base>
2164
13
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2165
                                      const unsigned char** out,
2166
                                      unsigned char* outlen,
2167
                                      const unsigned char* in,
2168
                                      unsigned int inlen,
2169
                                      void* arg) {
2170
13
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2171
13
  Environment* env = w->env();
2172
26
  HandleScope handle_scope(env->isolate());
2173
39
  Context::Scope context_scope(env->context());
2174
2175
  Local<Value> alpn_buffer =
2176
13
      w->object()->GetPrivate(
2177
          env->context(),
2178
52
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2179
13
  CHECK(Buffer::HasInstance(alpn_buffer));
2180
  const unsigned char* alpn_protos =
2181
13
      reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2182
13
  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2183
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2184
13
                                     alpn_protos, alpn_protos_len, in, inlen);
2185
2186
13
  switch (status) {
2187
    case OPENSSL_NPN_NO_OVERLAP:
2188
      // According to 3.2. Protocol Selection of RFC7301,
2189
      // fatal no_application_protocol alert shall be sent
2190
      // but current openssl does not support it yet. See
2191
      // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2192
      // Instead, we send a warning alert for now.
2193
      return SSL_TLSEXT_ERR_ALERT_WARNING;
2194
    case OPENSSL_NPN_NEGOTIATED:
2195
9
      return SSL_TLSEXT_ERR_OK;
2196
    default:
2197
      return SSL_TLSEXT_ERR_ALERT_FATAL;
2198
  }
2199
}
2200
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2201
2202
2203
template <class Base>
2204
552
void SSLWrap<Base>::GetALPNNegotiatedProto(
2205
    const FunctionCallbackInfo<v8::Value>& args) {
2206
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2207
570
  HandleScope scope(args.GetIsolate());
2208
  Base* w;
2209
1086
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2210
2211
  const unsigned char* alpn_proto;
2212
  unsigned int alpn_proto_len;
2213
2214
552
  SSL_get0_alpn_selected(w->ssl_, &alpn_proto, &alpn_proto_len);
2215
2216
552
  if (!alpn_proto)
2217
1068
    return args.GetReturnValue().Set(false);
2218
2219
72
  args.GetReturnValue().Set(
2220
      OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2221
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2222
}
2223
2224
2225
template <class Base>
2226
134
void SSLWrap<Base>::SetALPNProtocols(
2227
    const FunctionCallbackInfo<v8::Value>& args) {
2228
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2229
268
  HandleScope scope(args.GetIsolate());
2230
  Base* w;
2231
134
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2232
134
  Environment* env = w->env();
2233
268
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2234
    return env->ThrowTypeError("Must give a Buffer as first argument");
2235
2236
268
  if (w->is_client()) {
2237
    const unsigned char* alpn_protos =
2238
22
        reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2239
22
    unsigned alpn_protos_len = Buffer::Length(args[0]);
2240
22
    int r = SSL_set_alpn_protos(w->ssl_, alpn_protos, alpn_protos_len);
2241
22
    CHECK_EQ(r, 0);
2242
  } else {
2243
560
    CHECK(
2244
        w->object()->SetPrivate(
2245
          env->context(),
2246
          env->alpn_buffer_private_symbol(),
2247
          args[0]).FromJust());
2248
    // Server should select ALPN protocol from list of advertised by client
2249
112
    SSL_CTX_set_alpn_select_cb(w->ssl_->ctx, SelectALPNCallback, nullptr);
2250
  }
2251
#endif  // TLSEXT_TYPE_application_layer_protocol_negotiation
2252
}
2253
2254
2255
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2256
template <class Base>
2257
7
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2258
7
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2259
7
  Environment* env = w->env();
2260
14
  HandleScope handle_scope(env->isolate());
2261
2262
13
  if (w->is_client()) {
2263
    // Incoming response
2264
    const unsigned char* resp;
2265
3
    int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2266
3
    Local<Value> arg;
2267
3
    if (resp == nullptr) {
2268
3
      arg = Null(env->isolate());
2269
    } else {
2270
6
      arg = Buffer::Copy(
2271
          env,
2272
          reinterpret_cast<char*>(const_cast<unsigned char*>(resp)),
2273
          len).ToLocalChecked();
2274
    }
2275
2276
3
    w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2277
2278
    // Somehow, client is expecting different return value here
2279
    return 1;
2280
  } else {
2281
    // Outgoing response
2282
8
    if (w->ocsp_response_.IsEmpty())
2283
      return SSL_TLSEXT_ERR_NOACK;
2284
2285
2
    Local<Object> obj = PersistentToLocal(env->isolate(), w->ocsp_response_);
2286
2
    char* resp = Buffer::Data(obj);
2287
2
    size_t len = Buffer::Length(obj);
2288
2289
    // OpenSSL takes control of the pointer after accepting it
2290
2
    char* data = reinterpret_cast<char*>(malloc(len));
2291
2
    CHECK_NE(data, nullptr);
2292
2
    memcpy(data, resp, len);
2293
2294
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2295
      free(data);
2296
2
    w->ocsp_response_.Reset();
2297
2298
    return SSL_TLSEXT_ERR_OK;
2299
  }
2300
}
2301
#endif  // NODE__HAVE_TLSEXT_STATUS_CB
2302
2303
2304
template <class Base>
2305
21
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2306
21
  cert_cb_ = cb;
2307
21
  cert_cb_arg_ = arg;
2308
21
}
2309
2310
2311
template <class Base>
2312
290
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2313
290
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2314
2315
577
  if (!w->is_server())
2316
    return 1;
2317
2318
563
  if (!w->is_waiting_cert_cb())
2319
    return 1;
2320
2321
21
  if (w->cert_cb_running_)
2322
    return -1;
2323
2324
21
  Environment* env = w->env();
2325
42
  HandleScope handle_scope(env->isolate());
2326
63
  Context::Scope context_scope(env->context());
2327
21
  w->cert_cb_running_ = true;
2328
2329
21
  Local<Object> info = Object::New(env->isolate());
2330
2331
21
  SSL_SESSION* sess = SSL_get_session(s);
2332
21
  if (sess != nullptr) {
2333
21
    if (sess->tlsext_hostname == nullptr) {
2334
40
      info->Set(env->servername_string(), String::Empty(env->isolate()));
2335
    } else {
2336
13
      Local<String> servername = OneByteString(env->isolate(),
2337
                                               sess->tlsext_hostname,
2338
26
                                               strlen(sess->tlsext_hostname));
2339
39
      info->Set(env->servername_string(), servername);
2340
    }
2341
105
    info->Set(env->tls_ticket_string(),
2342
21
              Boolean::New(env->isolate(), sess->tlsext_ticklen != 0));
2343
  }
2344
2345
21
  bool ocsp = false;
2346
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
2347
21
  ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp;
2348
#endif
2349
2350
105
  info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp));
2351
2352
42
  Local<Value> argv[] = { info };
2353
42
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2354
2355
21
  if (!w->cert_cb_running_)
2356
    return 1;
2357
2358
  // Performing async action, wait...
2359
9
  return -1;
2360
}
2361
2362
2363
template <class Base>
2364
21
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2365
  Base* w;
2366
21
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2367
21
  Environment* env = w->env();
2368
2369
42
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2370
2371
42
  Local<Object> object = w->object();
2372
42
  Local<Value> ctx = object->Get(env->sni_context_string());
2373
21
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2374
2375
  // Not an object, probably undefined or null
2376
21
  if (!ctx->IsObject())
2377
    goto fire_cb;
2378
2379
10
  if (cons->HasInstance(ctx)) {
2380
    SecureContext* sc;
2381
10
    ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2382
18
    w->sni_context_.Reset();
2383
18
    w->sni_context_.Reset(env->isolate(), ctx);
2384
2385
    int rv;
2386
2387
    // NOTE: reference count is not increased by this API methods
2388
9
    X509* x509 = SSL_CTX_get0_certificate(sc->ctx_);
2389
9
    EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_);
2390
    STACK_OF(X509)* chain;
2391
2392
9
    rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain);
2393
9
    if (rv)
2394
9
      rv = SSL_use_certificate(w->ssl_, x509);
2395
9
    if (rv)
2396
8
      rv = SSL_use_PrivateKey(w->ssl_, pkey);
2397
9
    if (rv && chain != nullptr)
2398
1
      rv = SSL_set1_chain(w->ssl_, chain);
2399
9
    if (rv)
2400
8
      rv = w->SetCACerts(sc);
2401
9
    if (!rv) {
2402
1
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2403
1
      if (!err)
2404
        return env->ThrowError("CertCbDone");
2405
1
      return ThrowCryptoError(env, err);
2406
    }
2407
  } else {
2408
    // Failure: incorrect SNI context object
2409
1
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2410
1
    w->MakeCallback(env->onerror_string(), 1, &err);
2411
    return;
2412
  }
2413
2414
 fire_cb:
2415
  CertCb cb;
2416
  void* arg;
2417
2418
19
  cb = w->cert_cb_;
2419
19
  arg = w->cert_cb_arg_;
2420
2421
19
  w->cert_cb_running_ = false;
2422
19
  w->cert_cb_ = nullptr;
2423
19
  w->cert_cb_arg_ = nullptr;
2424
2425
19
  cb(arg);
2426
}
2427
2428
2429
template <class Base>
2430
2
void SSLWrap<Base>::SSLGetter(Local<String> property,
2431
                              const PropertyCallbackInfo<Value>& info) {
2432
  Base* base;
2433
4
  ASSIGN_OR_RETURN_UNWRAP(&base, info.This());
2434
  SSL* ssl = base->ssl_;
2435
  Local<External> ext = External::New(info.GetIsolate(), ssl);
2436
  info.GetReturnValue().Set(ext);
2437
}
2438
2439
2440
template <class Base>
2441
208
void SSLWrap<Base>::DestroySSL() {
2442
210
  if (ssl_ == nullptr)
2443
    return;
2444
2445
208
  SSL_free(ssl_);
2446
416
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2447
208
  ssl_ = nullptr;
2448
}
2449
2450
2451
template <class Base>
2452
void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2453
  InitNPN(sc);
2454
  CHECK_EQ(SSL_set_SSL_CTX(ssl_, sc->ctx_), sc->ctx_);
2455
2456
  SetCACerts(sc);
2457
}
2458
2459
2460
template <class Base>
2461
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2462
8
  int err = SSL_set1_verify_cert_store(ssl_, SSL_CTX_get_cert_store(sc->ctx_));
2463
8
  if (err != 1)
2464
    return err;
2465
2466
8
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2467
16
      SSL_CTX_get_client_CA_list(sc->ctx_));
2468
2469
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2470
8
  SSL_set_client_CA_list(ssl_, list);
2471
8
  return 1;
2472
}
2473
2474
2475
3
void Connection::OnClientHelloParseEnd(void* arg) {
2476
3
  Connection* conn = static_cast<Connection*>(arg);
2477
2478
  // Write all accumulated data
2479
3
  int r = BIO_write(conn->bio_read_,
2480
                    reinterpret_cast<char*>(conn->hello_data_),
2481
6
                    conn->hello_offset_);
2482
3
  conn->HandleBIOError(conn->bio_read_, "BIO_write", r);
2483
3
  conn->SetShutdownFlags();
2484
3
}
2485
2486
2487
#ifdef SSL_PRINT_DEBUG
2488
# define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
2489
#else
2490
# define DEBUG_PRINT(...)
2491
#endif
2492
2493
2494
27
int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
2495
27
  if (rv >= 0)
2496
    return rv;
2497
2498
17
  int retry = BIO_should_retry(bio);
2499
  (void) retry;  // unused if !defined(SSL_PRINT_DEBUG)
2500
2501
17
  if (BIO_should_write(bio)) {
2502
    DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n",
2503
                ssl_,
2504
                func,
2505
                retry);
2506
    return 0;
2507
2508
17
  } else if (BIO_should_read(bio)) {
2509
    DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
2510
    return 0;
2511
2512
  } else {
2513
    char ssl_error_buf[512];
2514
    ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
2515
2516
    HandleScope scope(ssl_env()->isolate());
2517
    Local<Value> exception =
2518
        Exception::Error(OneByteString(ssl_env()->isolate(), ssl_error_buf));
2519
    object()->Set(ssl_env()->error_string(), exception);
2520
2521
    DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n",
2522
                ssl_,
2523
                func,
2524
                rv,
2525
                ssl_error_buf);
2526
2527
    return rv;
2528
  }
2529
2530
  return 0;
2531
}
2532
2533
2534
25
int Connection::HandleSSLError(const char* func,
2535
                               int rv,
2536
                               ZeroStatus zs,
2537
                               SyscallStatus ss) {
2538
  ClearErrorOnReturn clear_error_on_return;
2539
  (void) &clear_error_on_return;  // Silence unused variable warning.
2540
2541
25
  if (rv > 0)
2542
    return rv;
2543
21
  if (rv == 0 && zs == kZeroIsNotAnError)
2544
    return rv;
2545
2546
20
  int err = SSL_get_error(ssl_, rv);
2547
2548
20
  if (err == SSL_ERROR_NONE) {
2549
    return 0;
2550
2551
20
  } else if (err == SSL_ERROR_WANT_WRITE) {
2552
    DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
2553
    return 0;
2554
2555
20
  } else if (err == SSL_ERROR_WANT_READ) {
2556
    DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
2557
    return 0;
2558
2559
1
  } else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2560
    DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2561
    return 0;
2562
2563
1
  } else if (err == SSL_ERROR_ZERO_RETURN) {
2564
    HandleScope scope(ssl_env()->isolate());
2565
2566
    Local<Value> exception =
2567
        Exception::Error(ssl_env()->zero_return_string());
2568
    object()->Set(ssl_env()->error_string(), exception);
2569
    return rv;
2570
2571
1
  } else if (err == SSL_ERROR_SYSCALL && ss == kIgnoreSyscall) {
2572
    return 0;
2573
2574
  } else {
2575
2
    HandleScope scope(ssl_env()->isolate());
2576
    BUF_MEM* mem;
2577
    BIO *bio;
2578
2579
1
    CHECK(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
2580
2581
    // XXX We need to drain the error queue for this thread or else OpenSSL
2582
    // has the possibility of blocking connections? This problem is not well
2583
    // understood. And we should be somehow propagating these errors up
2584
    // into JavaScript. There is no test which demonstrates this problem.
2585
    // https://github.com/joyent/node/issues/1719
2586
1
    bio = BIO_new(BIO_s_mem());
2587
1
    if (bio != nullptr) {
2588
1
      ERR_print_errors(bio);
2589
1
      BIO_get_mem_ptr(bio, &mem);
2590
      Local<Value> exception = Exception::Error(
2591
          OneByteString(ssl_env()->isolate(),
2592
1
            mem->data,
2593
2
            mem->length));
2594
4
      object()->Set(ssl_env()->error_string(), exception);
2595
1
      BIO_free_all(bio);
2596
    }
2597
2598
    return rv;
2599
  }
2600
2601
  return 0;
2602
}
2603
2604
2605
void Connection::ClearError() {
2606
#ifndef NDEBUG
2607
  HandleScope scope(ssl_env()->isolate());
2608
2609
  // We should clear the error in JS-land
2610
  Local<String> error_key = ssl_env()->error_string();
2611
  Local<Value> error = object()->Get(error_key);
2612
  CHECK_EQ(error->BooleanValue(), false);
2613
#endif  // NDEBUG
2614
}
2615
2616
2617
36
void Connection::SetShutdownFlags() {
2618
72
  HandleScope scope(ssl_env()->isolate());
2619
2620
36
  int flags = SSL_get_shutdown(ssl_);
2621
2622
36
  if (flags & SSL_SENT_SHUTDOWN) {
2623
    Local<String> sent_shutdown_key = ssl_env()->sent_shutdown_string();
2624
    object()->Set(sent_shutdown_key, True(ssl_env()->isolate()));
2625
  }
2626
2627
36
  if (flags & SSL_RECEIVED_SHUTDOWN) {
2628
2
    Local<String> received_shutdown_key = ssl_env()->received_shutdown_string();
2629
5
    object()->Set(received_shutdown_key, True(ssl_env()->isolate()));
2630
  }
2631
36
}
2632
2633
2634
void Connection::NewSessionDoneCb() {
2635
  HandleScope scope(env()->isolate());
2636
2637
  MakeCallback(env()->onnewsessiondone_string(), 0, nullptr);
2638
}
2639
2640
2641
182
void Connection::Initialize(Environment* env, Local<Object> target) {
2642
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Connection::New);
2643
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
2644
182
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"));
2645
2646
182
  env->SetProtoMethod(t, "encIn", Connection::EncIn);
2647
182
  env->SetProtoMethod(t, "clearOut", Connection::ClearOut);
2648
182
  env->SetProtoMethod(t, "clearIn", Connection::ClearIn);
2649
182
  env->SetProtoMethod(t, "encOut", Connection::EncOut);
2650
182
  env->SetProtoMethod(t, "clearPending", Connection::ClearPending);
2651
182
  env->SetProtoMethod(t, "encPending", Connection::EncPending);
2652
182
  env->SetProtoMethod(t, "start", Connection::Start);
2653
182
  env->SetProtoMethod(t, "close", Connection::Close);
2654
2655
182
  SSLWrap<Connection>::AddMethods(env, t);
2656
2657
2658
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2659
182
  env->SetProtoMethod(t, "getServername", Connection::GetServername);
2660
182
  env->SetProtoMethod(t, "setSNICallback",  Connection::SetSNICallback);
2661
#endif
2662
2663
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"),
2664
182
              t->GetFunction());
2665
182
}
2666
2667
2668
inline int compar(const void* a, const void* b) {
2669
10
  return memcmp(a, b, CNNIC_WHITELIST_HASH_LEN);
2670
}
2671
2672
2673
65
inline int IsSelfSigned(X509* cert) {
2674
65
  return X509_NAME_cmp(X509_get_subject_name(cert),
2675
130
                       X509_get_issuer_name(cert)) == 0;
2676
}
2677
2678
2679
inline X509* FindRoot(STACK_OF(X509)* sk) {
2680
  for (int i = 0; i < sk_X509_num(sk); i++) {
2681
    X509* cert = sk_X509_value(sk, i);
2682
    if (IsSelfSigned(cert))
2683
      return cert;
2684
  }
2685
  return nullptr;
2686
}
2687
2688
2689
// Whitelist check for certs issued by CNNIC. See
2690
// https://blog.mozilla.org/security/2015/04/02
2691
// /distrusting-new-cnnic-certificates/
2692
65
inline CheckResult CheckWhitelistedServerCert(X509_STORE_CTX* ctx) {
2693
  unsigned char hash[CNNIC_WHITELIST_HASH_LEN];
2694
65
  unsigned int hashlen = CNNIC_WHITELIST_HASH_LEN;
2695
2696
65
  STACK_OF(X509)* chain = X509_STORE_CTX_get1_chain(ctx);
2697
65
  CHECK_NE(chain, nullptr);
2698
65
  CHECK_GT(sk_X509_num(chain), 0);
2699
2700
  // Take the last cert as root at the first time.
2701
65
  X509* root_cert = sk_X509_value(chain, sk_X509_num(chain)-1);
2702
65
  X509_NAME* root_name = X509_get_subject_name(root_cert);
2703
2704
65
  if (!IsSelfSigned(root_cert)) {
2705
    root_cert = FindRoot(chain);
2706
    CHECK_NE(root_cert, nullptr);
2707
    root_name = X509_get_subject_name(root_cert);
2708
  }
2709
2710
  // When the cert is issued from either CNNNIC ROOT CA or CNNNIC EV
2711
  // ROOT CA, check a hash of its leaf cert if it is in the whitelist.
2712
129
  if (X509_NAME_cmp(root_name, cnnic_name) == 0 ||
2713
64
      X509_NAME_cmp(root_name, cnnic_ev_name) == 0) {
2714
1
    X509* leaf_cert = sk_X509_value(chain, 0);
2715
1
    int ret = X509_digest(leaf_cert, EVP_sha256(), hash,
2716
1
                          &hashlen);
2717
1
    CHECK(ret);
2718
2719
    void* result = bsearch(hash, WhitelistedCNNICHashes,
2720
                           arraysize(WhitelistedCNNICHashes),
2721
1
                           CNNIC_WHITELIST_HASH_LEN, compar);
2722
1
    if (result == nullptr) {
2723
1
      sk_X509_pop_free(chain, X509_free);
2724
1
      return CHECK_CERT_REVOKED;
2725
    }
2726
  }
2727
2728
64
  sk_X509_pop_free(chain, X509_free);
2729
64
  return CHECK_OK;
2730
}
2731
2732
2733
527
inline int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2734
  // Failure on verification of the cert is handled in
2735
  // Connection::VerifyError.
2736
527
  if (preverify_ok == 0 || X509_STORE_CTX_get_error(ctx) != X509_V_OK)
2737
    return 1;
2738
2739
  // Server does not need to check the whitelist.
2740
  SSL* ssl = static_cast<SSL*>(
2741
82
      X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
2742
2743
82
  if (SSL_is_server(ssl))
2744
    return 1;
2745
2746
  // Client needs to check if the server cert is listed in the
2747
  // whitelist when it is issued by the specific rootCAs.
2748
65
  CheckResult ret = CheckWhitelistedServerCert(ctx);
2749
65
  if (ret == CHECK_CERT_REVOKED)
2750
1
    X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
2751
2752
65
  return ret;
2753
}
2754
2755
2756
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2757
3
int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
2758
3
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(s));
2759
3
  Environment* env = conn->env();
2760
6
  HandleScope scope(env->isolate());
2761
2762
3
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2763
2764
3
  if (servername) {
2765
2
    conn->servername_.Reset(env->isolate(),
2766
4
                            OneByteString(env->isolate(), servername));
2767
2768
    // Call the SNI callback and use its return value as context
2769
4
    if (!conn->sniObject_.IsEmpty()) {
2770
4
      conn->sni_context_.Reset();
2771
2772
      Local<Object> sni_obj = PersistentToLocal(env->isolate(),
2773
2
                                                conn->sniObject_);
2774
2775
4
      Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
2776
      Local<Value> ret = node::MakeCallback(env->isolate(),
2777
                                            sni_obj,
2778
                                            env->onselect_string(),
2779
                                            1,
2780
2
                                            &arg);
2781
2782
      // If ret is SecureContext
2783
      Local<FunctionTemplate> secure_context_constructor_template =
2784
2
          env->secure_context_constructor_template();
2785
2
      if (secure_context_constructor_template->HasInstance(ret)) {
2786
        conn->sni_context_.Reset(env->isolate(), ret);
2787
        SecureContext* sc;
2788
        ASSIGN_OR_RETURN_UNWRAP(&sc, ret.As<Object>(), SSL_TLSEXT_ERR_NOACK);
2789
        conn->SetSNIContext(sc);
2790
      } else {
2791
        return SSL_TLSEXT_ERR_NOACK;
2792
      }
2793
    }
2794
  }
2795
2796
  return SSL_TLSEXT_ERR_OK;
2797
}
2798
#endif
2799
2800
7
void Connection::New(const FunctionCallbackInfo<Value>& args) {
2801
7
  Environment* env = Environment::GetCurrent(args);
2802
2803
21
  if (args.Length() < 1 || !args[0]->IsObject()) {
2804
    env->ThrowError("First argument must be a tls module SecureContext");
2805
    return;
2806
  }
2807
2808
  SecureContext* sc;
2809
12
  ASSIGN_OR_RETURN_UNWRAP(&sc, args[0].As<Object>());
2810
2811
6
  bool is_server = args[1]->BooleanValue();
2812
2813
  SSLWrap<Connection>::Kind kind =
2814
6
      is_server ? SSLWrap<Connection>::kServer : SSLWrap<Connection>::kClient;
2815
6
  Connection* conn = new Connection(env, args.This(), sc, kind);
2816
6
  conn->bio_read_ = NodeBIO::New();
2817
6
  conn->bio_write_ = NodeBIO::New();
2818
2819
6
  SSL_set_app_data(conn->ssl_, conn);
2820
2821
6
  if (is_server)
2822
4
    SSL_set_info_callback(conn->ssl_, SSLInfoCallback);
2823
2824
6
  InitNPN(sc);
2825
2826
6
  SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
2827
2828
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2829
6
  if (is_server) {
2830
4
    SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
2831
4
  } else if (args[2]->IsString()) {
2832
    const node::Utf8Value servername(env->isolate(), args[2]);
2833
    SSL_set_tlsext_host_name(conn->ssl_, *servername);
2834
  }
2835
#endif
2836
2837
6
  SSL_set_bio(conn->ssl_, conn->bio_read_, conn->bio_write_);
2838
2839
#ifdef SSL_MODE_RELEASE_BUFFERS
2840
6
  long mode = SSL_get_mode(conn->ssl_);  // NOLINT(runtime/int)
2841
6
  SSL_set_mode(conn->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
2842
#endif
2843
2844
2845
  int verify_mode;
2846
6
  if (is_server) {
2847
4
    bool request_cert = args[2]->BooleanValue();
2848
4
    if (!request_cert) {
2849
      // Note reject_unauthorized ignored.
2850
      verify_mode = SSL_VERIFY_NONE;
2851
    } else {
2852
      bool reject_unauthorized = args[3]->BooleanValue();
2853
      verify_mode = SSL_VERIFY_PEER;
2854
      if (reject_unauthorized)
2855
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2856
    }
2857
  } else {
2858
    // Note request_cert and reject_unauthorized are ignored for clients.
2859
    verify_mode = SSL_VERIFY_NONE;
2860
  }
2861
2862
2863
  // Always allow a connection. We'll reject in javascript.
2864
6
  SSL_set_verify(conn->ssl_, verify_mode, VerifyCallback);
2865
2866
6
  if (is_server) {
2867
4
    SSL_set_accept_state(conn->ssl_);
2868
  } else {
2869
2
    SSL_set_connect_state(conn->ssl_);
2870
  }
2871
}
2872
2873
2874
48
void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
2875
48
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
2876
43
    return;
2877
2878
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
2879
  // a non-const SSL* in OpenSSL <= 0.9.7e.
2880
5
  SSL* ssl = const_cast<SSL*>(ssl_);
2881
5
  Connection* conn = static_cast<Connection*>(SSL_get_app_data(ssl));
2882
5
  Environment* env = conn->env();
2883
10
  HandleScope handle_scope(env->isolate());
2884
15
  Context::Scope context_scope(env->context());
2885
2886
5
  if (where & SSL_CB_HANDSHAKE_START) {
2887
4
    conn->MakeCallback(env->onhandshakestart_string(), 0, nullptr);
2888
  }
2889
2890
5
  if (where & SSL_CB_HANDSHAKE_DONE) {
2891
1
    conn->MakeCallback(env->onhandshakedone_string(), 0, nullptr);
2892
  }
2893
}
2894
2895
2896
6
void Connection::EncIn(const FunctionCallbackInfo<Value>& args) {
2897
  Connection* conn;
2898
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2899
6
  Environment* env = conn->env();
2900
2901
6
  if (args.Length() < 3) {
2902
    return env->ThrowTypeError(
2903
        "Data, offset, and length arguments are mandatory");
2904
  }
2905
2906
6
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
2907
2908
6
  char* buffer_data = Buffer::Data(args[0]);
2909
6
  size_t buffer_length = Buffer::Length(args[0]);
2910
2911
6
  size_t off = args[1]->Int32Value();
2912
6
  size_t len = args[2]->Int32Value();
2913
2914
6
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
2915
    return env->ThrowRangeError("offset + length > buffer.length");
2916
2917
  int bytes_written;
2918
6
  char* data = buffer_data + off;
2919
2920
6
  if (conn->is_server() && !conn->hello_parser_.IsEnded()) {
2921
    // Just accumulate data, everything will be pushed to BIO later
2922
3
    if (conn->hello_parser_.IsPaused()) {
2923
      bytes_written = 0;
2924
    } else {
2925
      // Copy incoming data to the internal buffer
2926
      // (which has a size of the biggest possible TLS frame)
2927
3
      size_t available = sizeof(conn->hello_data_) - conn->hello_offset_;
2928
3
      size_t copied = len < available ? len : available;
2929
6
      memcpy(conn->hello_data_ + conn->hello_offset_, data, copied);
2930
3
      conn->hello_offset_ += copied;
2931
2932
3
      conn->hello_parser_.Parse(conn->hello_data_, conn->hello_offset_);
2933
3
      bytes_written = copied;
2934
    }
2935
  } else {
2936
3
    bytes_written = BIO_write(conn->bio_read_, data, len);
2937
3
    conn->HandleBIOError(conn->bio_read_, "BIO_write", bytes_written);
2938
3
    conn->SetShutdownFlags();
2939
  }
2940
2941
12
  args.GetReturnValue().Set(bytes_written);
2942
}
2943
2944
2945
16
void Connection::ClearOut(const FunctionCallbackInfo<Value>& args) {
2946
  Connection* conn;
2947
16
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
2948
16
  Environment* env = conn->env();
2949
2950
16
  if (args.Length() < 3) {
2951
    return env->ThrowTypeError(
2952
        "Data, offset, and length arguments are mandatory");
2953
  }
2954
2955
16
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
2956
2957
16
  char* buffer_data = Buffer::Data(args[0]);
2958
16
  size_t buffer_length = Buffer::Length(args[0]);
2959
2960
16
  size_t off = args[1]->Int32Value();
2961
16
  size_t len = args[2]->Int32Value();
2962
2963
16
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
2964
    return env->ThrowRangeError("offset + length > buffer.length");
2965
2966
16
  if (!SSL_is_init_finished(conn->ssl_)) {
2967
    int rv;
2968
2969
10
    if (conn->is_server()) {
2970
10
      rv = SSL_accept(conn->ssl_);
2971
      conn->HandleSSLError("SSL_accept:ClearOut",
2972
                           rv,
2973
                           kZeroIsAnError,
2974
10
                           kSyscallError);
2975
    } else {
2976
      rv = SSL_connect(conn->ssl_);
2977
      conn->HandleSSLError("SSL_connect:ClearOut",
2978
                           rv,
2979
                           kZeroIsAnError,
2980
                           kSyscallError);
2981
    }
2982
2983
10
    if (rv < 0) {
2984
18
      return args.GetReturnValue().Set(rv);
2985
    }
2986
  }
2987
2988
7
  int bytes_read = SSL_read(conn->ssl_, buffer_data + off, len);
2989
  conn->HandleSSLError("SSL_read:ClearOut",
2990
                       bytes_read,
2991
                       kZeroIsNotAnError,
2992
7
                       kSyscallError);
2993
7
  conn->SetShutdownFlags();
2994
2995
14
  args.GetReturnValue().Set(bytes_read);
2996
}
2997
2998
2999
19
void Connection::ClearPending(const FunctionCallbackInfo<Value>& args) {
3000
  Connection* conn;
3001
19
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3002
19
  int bytes_pending = BIO_pending(conn->bio_read_);
3003
38
  args.GetReturnValue().Set(bytes_pending);
3004
}
3005
3006
3007
26
void Connection::EncPending(const FunctionCallbackInfo<Value>& args) {
3008
  Connection* conn;
3009
26
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3010
26
  int bytes_pending = BIO_pending(conn->bio_write_);
3011
52
  args.GetReturnValue().Set(bytes_pending);
3012
}
3013
3014
3015
21
void Connection::EncOut(const FunctionCallbackInfo<Value>& args) {
3016
  Connection* conn;
3017
21
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3018
21
  Environment* env = conn->env();
3019
3020
21
  if (args.Length() < 3) {
3021
    return env->ThrowTypeError(
3022
        "Data, offset, and length arguments are mandatory");
3023
  }
3024
3025
21
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3026
3027
21
  char* buffer_data = Buffer::Data(args[0]);
3028
21
  size_t buffer_length = Buffer::Length(args[0]);
3029
3030
21
  size_t off = args[1]->Int32Value();
3031
21
  size_t len = args[2]->Int32Value();
3032
3033
21
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3034
    return env->ThrowRangeError("offset + length > buffer.length");
3035
3036
21
  int bytes_read = BIO_read(conn->bio_write_, buffer_data + off, len);
3037
3038
21
  conn->HandleBIOError(conn->bio_write_, "BIO_read:EncOut", bytes_read);
3039
21
  conn->SetShutdownFlags();
3040
3041
42
  args.GetReturnValue().Set(bytes_read);
3042
}
3043
3044
3045
2
void Connection::ClearIn(const FunctionCallbackInfo<Value>& args) {
3046
  Connection* conn;
3047
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3048
2
  Environment* env = conn->env();
3049
3050
2
  if (args.Length() < 3) {
3051
    return env->ThrowTypeError(
3052
        "Data, offset, and length arguments are mandatory");
3053
  }
3054
3055
2
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3056
3057
2
  char* buffer_data = Buffer::Data(args[0]);
3058
2
  size_t buffer_length = Buffer::Length(args[0]);
3059
3060
2
  size_t off = args[1]->Int32Value();
3061
2
  size_t len = args[2]->Int32Value();
3062
3063
2
  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3064
    return env->ThrowRangeError("offset + length > buffer.length");
3065
3066
2
  if (!SSL_is_init_finished(conn->ssl_)) {
3067
    int rv;
3068
    if (conn->is_server()) {
3069
      rv = SSL_accept(conn->ssl_);
3070
      conn->HandleSSLError("SSL_accept:ClearIn",
3071
                           rv,
3072
                           kZeroIsAnError,
3073
                           kSyscallError);
3074
    } else {
3075
      rv = SSL_connect(conn->ssl_);
3076
      conn->HandleSSLError("SSL_connect:ClearIn",
3077
                           rv,
3078
                           kZeroIsAnError,
3079
                           kSyscallError);
3080
    }
3081
3082
    if (rv < 0) {
3083
      return args.GetReturnValue().Set(rv);
3084
    }
3085
  }
3086
3087
2
  int bytes_written = SSL_write(conn->ssl_, buffer_data + off, len);
3088
3089
2
  conn->HandleSSLError("SSL_write:ClearIn",
3090
                       bytes_written,
3091
                       len == 0 ? kZeroIsNotAnError : kZeroIsAnError,
3092
2
                       kSyscallError);
3093
2
  conn->SetShutdownFlags();
3094
3095
4
  args.GetReturnValue().Set(bytes_written);
3096
}
3097
3098
3099
6
void Connection::Start(const FunctionCallbackInfo<Value>& args) {
3100
  Connection* conn;
3101
6
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3102
3103
6
  int rv = 0;
3104
6
  if (!SSL_is_init_finished(conn->ssl_)) {
3105
6
    if (conn->is_server()) {
3106
4
      rv = SSL_accept(conn->ssl_);
3107
      conn->HandleSSLError("SSL_accept:Start",
3108
                           rv,
3109
                           kZeroIsAnError,
3110
4
                           kSyscallError);
3111
    } else {
3112
2
      rv = SSL_connect(conn->ssl_);
3113
      conn->HandleSSLError("SSL_connect:Start",
3114
                           rv,
3115
                           kZeroIsAnError,
3116
2
                           kSyscallError);
3117
    }
3118
  }
3119
12
  args.GetReturnValue().Set(rv);
3120
}
3121
3122
3123
2
void Connection::Close(const FunctionCallbackInfo<Value>& args) {
3124
  Connection* conn;
3125
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3126
3127
2
  if (conn->ssl_ != nullptr) {
3128
2
    SSL_free(conn->ssl_);
3129
2
    conn->ssl_ = nullptr;
3130
  }
3131
}
3132
3133
3134
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3135
1
void Connection::GetServername(const FunctionCallbackInfo<Value>& args) {
3136
  Connection* conn;
3137
1
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3138
3139
2
  if (conn->is_server() && !conn->servername_.IsEmpty()) {
3140
    args.GetReturnValue().Set(conn->servername_);
3141
  } else {
3142
2
    args.GetReturnValue().Set(false);
3143
  }
3144
}
3145
3146
3147
2
void Connection::SetSNICallback(const FunctionCallbackInfo<Value>& args) {
3148
  Connection* conn;
3149
2
  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3150
2
  Environment* env = conn->env();
3151
3152
6
  if (args.Length() < 1 || !args[0]->IsFunction()) {
3153
    return env->ThrowError("Must give a Function as first argument");
3154
  }
3155
3156
2
  Local<Object> obj = Object::New(env->isolate());
3157
6
  obj->Set(FIXED_ONE_BYTE_STRING(args.GetIsolate(), "onselect"), args[0]);
3158
2
  conn->sniObject_.Reset(args.GetIsolate(), obj);
3159
}
3160
#endif
3161
3162
3163
182
void CipherBase::Initialize(Environment* env, Local<Object> target) {
3164
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3165
3166
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3167
3168
182
  env->SetProtoMethod(t, "init", Init);
3169
182
  env->SetProtoMethod(t, "initiv", InitIv);
3170
182
  env->SetProtoMethod(t, "update", Update);
3171
182
  env->SetProtoMethod(t, "final", Final);
3172
182
  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
3173
182
  env->SetProtoMethod(t, "getAuthTag", GetAuthTag);
3174
182
  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
3175
182
  env->SetProtoMethod(t, "setAAD", SetAAD);
3176
3177
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
3178
182
              t->GetFunction());
3179
182
}
3180
3181
3182
83
void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
3183
83
  CHECK_EQ(args.IsConstructCall(), true);
3184
83
  CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher;
3185
83
  Environment* env = Environment::GetCurrent(args);
3186
83
  new CipherBase(env, args.This(), kind);
3187
83
}
3188
3189
3190
29
void CipherBase::Init(const char* cipher_type,
3191
                      const char* key_buf,
3192
                      int key_buf_len) {
3193
58
  HandleScope scope(env()->isolate());
3194
3195
#ifdef NODE_FIPS_MODE
3196
  if (FIPS_mode()) {
3197
    return env()->ThrowError(
3198
        "crypto.createCipher() is not supported in FIPS mode.");
3199
  }
3200
#endif  // NODE_FIPS_MODE
3201
3202
29
  CHECK_EQ(cipher_, nullptr);
3203
29
  cipher_ = EVP_get_cipherbyname(cipher_type);
3204
29
  if (cipher_ == nullptr) {
3205
    return env()->ThrowError("Unknown cipher");
3206
  }
3207
3208
  unsigned char key[EVP_MAX_KEY_LENGTH];
3209
  unsigned char iv[EVP_MAX_IV_LENGTH];
3210
3211
29
  int key_len = EVP_BytesToKey(cipher_,
3212
                               EVP_md5(),
3213
                               nullptr,
3214
                               reinterpret_cast<const unsigned char*>(key_buf),
3215
                               key_buf_len,
3216
                               1,
3217
                               key,
3218
29
                               iv);
3219
3220
29
  EVP_CIPHER_CTX_init(&ctx_);
3221
29
  const bool encrypt = (kind_ == kCipher);
3222
29
  EVP_CipherInit_ex(&ctx_, cipher_, nullptr, nullptr, nullptr, encrypt);
3223
29
  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3224
    EVP_CIPHER_CTX_cleanup(&ctx_);
3225
    return env()->ThrowError("Invalid key length");
3226
  }
3227
3228
29
  EVP_CipherInit_ex(&ctx_,
3229
                    nullptr,
3230
                    nullptr,
3231
                    reinterpret_cast<unsigned char*>(key),
3232
                    reinterpret_cast<unsigned char*>(iv),
3233
58
                    kind_ == kCipher);
3234
29
  initialised_ = true;
3235
}
3236
3237
3238
29
void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
3239
  CipherBase* cipher;
3240
29
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3241
29
  Environment* env = cipher->env();
3242
3243
29
  if (args.Length() < 2) {
3244
    return env->ThrowError("Cipher type and key arguments are mandatory");
3245
  }
3246
3247
58
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3248
29
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3249
3250
87
  const node::Utf8Value cipher_type(args.GetIsolate(), args[0]);
3251
29
  const char* key_buf = Buffer::Data(args[1]);
3252
29
  ssize_t key_buf_len = Buffer::Length(args[1]);
3253
29
  cipher->Init(*cipher_type, key_buf, key_buf_len);
3254
}
3255
3256
3257
54
void CipherBase::InitIv(const char* cipher_type,
3258
                        const char* key,
3259
                        int key_len,
3260
                        const char* iv,
3261
                        int iv_len) {
3262
108
  HandleScope scope(env()->isolate());
3263
3264
54
  cipher_ = EVP_get_cipherbyname(cipher_type);
3265
54
  if (cipher_ == nullptr) {
3266
    return env()->ThrowError("Unknown cipher");
3267
  }
3268
3269
  /* OpenSSL versions up to 0.9.8l failed to return the correct
3270
     iv_length (0) for ECB ciphers */
3271
108
  if (EVP_CIPHER_iv_length(cipher_) != iv_len &&
3272
      !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_ECB_MODE && iv_len == 0) &&
3273
54
      !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_GCM_MODE) && iv_len > 0) {
3274
    return env()->ThrowError("Invalid IV length");
3275
  }
3276
3277
54
  EVP_CIPHER_CTX_init(&ctx_);
3278
54
  const bool encrypt = (kind_ == kCipher);
3279
54
  EVP_CipherInit_ex(&ctx_, cipher_, nullptr, nullptr, nullptr, encrypt);
3280
3281
  /* Set IV length. Only required if GCM cipher and IV is not default iv. */
3282
56
  if (EVP_CIPHER_mode(cipher_) == EVP_CIPH_GCM_MODE &&
3283
2
      iv_len != EVP_CIPHER_iv_length(cipher_)) {
3284
    if (!EVP_CIPHER_CTX_ctrl(&ctx_, EVP_CTRL_GCM_SET_IVLEN, iv_len, nullptr)) {
3285
      EVP_CIPHER_CTX_cleanup(&ctx_);
3286
      return env()->ThrowError("Invalid IV length");
3287
    }
3288
  }
3289
3290
54
  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3291
    EVP_CIPHER_CTX_cleanup(&ctx_);
3292
    return env()->ThrowError("Invalid key length");
3293
  }
3294
3295
54
  EVP_CipherInit_ex(&ctx_,
3296
                    nullptr,
3297
                    nullptr,
3298
                    reinterpret_cast<const unsigned char*>(key),
3299
                    reinterpret_cast<const unsigned char*>(iv),
3300
108
                    kind_ == kCipher);
3301
54
  initialised_ = true;
3302
}
3303
3304
3305
54
void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
3306
  CipherBase* cipher;
3307
54
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3308
54
  Environment* env = cipher->env();
3309
3310
54
  if (args.Length() < 3) {
3311
    return env->ThrowError("Cipher type, key, and IV arguments are mandatory");
3312
  }
3313
3314
108
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3315
54
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3316
54
  THROW_AND_RETURN_IF_NOT_BUFFER(args[2], "IV");
3317
3318
108
  const node::Utf8Value cipher_type(env->isolate(), args[0]);
3319
54
  ssize_t key_len = Buffer::Length(args[1]);
3320
54
  const char* key_buf = Buffer::Data(args[1]);
3321
54
  ssize_t iv_len = Buffer::Length(args[2]);
3322
54
  const char* iv_buf = Buffer::Data(args[2]);
3323
54
  cipher->InitIv(*cipher_type, key_buf, key_len, iv_buf, iv_len);
3324
}
3325
3326
3327
bool CipherBase::IsAuthenticatedMode() const {
3328
  // check if this cipher operates in an AEAD mode that we support.
3329
88
  if (!cipher_)
3330
    return false;
3331
88
  int mode = EVP_CIPHER_mode(cipher_);
3332
88
  return mode == EVP_CIPH_GCM_MODE;
3333
}
3334
3335
3336
1
bool CipherBase::GetAuthTag(char** out, unsigned int* out_len) const {
3337
  // only callable after Final and if encrypting.
3338
1
  if (initialised_ || kind_ != kCipher || !auth_tag_)
3339
    return false;
3340
1
  *out_len = auth_tag_len_;
3341
1
  *out = static_cast<char*>(malloc(auth_tag_len_));
3342
1
  CHECK_NE(*out, nullptr);
3343
2
  memcpy(*out, auth_tag_, auth_tag_len_);
3344
1
  return true;
3345
}
3346
3347
3348
1
void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
3349
1
  Environment* env = Environment::GetCurrent(args);
3350
  CipherBase* cipher;
3351
1
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3352
3353
1
  char* out = nullptr;
3354
1
  unsigned int out_len = 0;
3355
3356
1
  if (cipher->GetAuthTag(&out, &out_len)) {
3357
2
    Local<Object> buf = Buffer::New(env, out, out_len).ToLocalChecked();
3358
1
    args.GetReturnValue().Set(buf);
3359
  } else {
3360
    env->ThrowError("Attempting to get auth tag in unsupported state");
3361
  }
3362
}
3363
3364
3365
1
bool CipherBase::SetAuthTag(const char* data, unsigned int len) {
3366
2
  if (!initialised_ || !IsAuthenticatedMode() || kind_ != kDecipher)
3367
    return false;
3368
1
  delete[] auth_tag_;
3369
1
  auth_tag_len_ = len;
3370
1
  auth_tag_ = new char[len];
3371
2
  memcpy(auth_tag_, data, len);
3372
1
  return true;
3373
}
3374
3375
3376
1
void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
3377
1
  Environment* env = Environment::GetCurrent(args);
3378
3379
2
  Local<Object> buf = args[0].As<Object>();
3380
3381
1
  if (!buf->IsObject() || !Buffer::HasInstance(buf))
3382
    return env->ThrowTypeError("Auth tag must be a Buffer");
3383
3384
  CipherBase* cipher;
3385
1
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3386
3387
1
  if (!cipher->SetAuthTag(Buffer::Data(buf), Buffer::Length(buf)))
3388
    env->ThrowError("Attempting to set auth tag in unsupported state");
3389
}
3390
3391
3392
bool CipherBase::SetAAD(const char* data, unsigned int len) {
3393
  if (!initialised_ || !IsAuthenticatedMode())
3394
    return false;
3395
  int outlen;
3396
  if (!EVP_CipherUpdate(&ctx_,
3397
                        nullptr,
3398
                        &outlen,
3399
                        reinterpret_cast<const unsigned char*>(data),
3400
                        len)) {
3401
    return false;
3402
  }
3403
  return true;
3404
}
3405
3406
3407
void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
3408
  Environment* env = Environment::GetCurrent(args);
3409
3410
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "AAD");
3411
3412
  CipherBase* cipher;
3413
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3414
3415
  if (!cipher->SetAAD(Buffer::Data(args[0]), Buffer::Length(args[0])))
3416
    env->ThrowError("Attempting to set AAD in unsupported state");
3417
}
3418
3419
3420
77
bool CipherBase::Update(const char* data,
3421
                        int len,
3422
                        unsigned char** out,
3423
                        int* out_len) {
3424
77
  if (!initialised_)
3425
    return 0;
3426
3427
  // on first update:
3428
114
  if (kind_ == kDecipher && IsAuthenticatedMode() && auth_tag_ != nullptr) {
3429
1
    EVP_CIPHER_CTX_ctrl(&ctx_,
3430
                        EVP_CTRL_GCM_SET_TAG,
3431
1
                        auth_tag_len_,
3432
2
                        reinterpret_cast<unsigned char*>(auth_tag_));
3433
1
    delete[] auth_tag_;
3434
1
    auth_tag_ = nullptr;
3435
  }
3436
3437
77
  *out_len = len + EVP_CIPHER_CTX_block_size(&ctx_);
3438
77
  *out = new unsigned char[*out_len];
3439
77
  return EVP_CipherUpdate(&ctx_,
3440
                          *out,
3441
                          out_len,
3442
                          reinterpret_cast<const unsigned char*>(data),
3443
77
                          len);
3444
}
3445
3446
3447
79
void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
3448
79
  Environment* env = Environment::GetCurrent(args);
3449
3450
  CipherBase* cipher;
3451
81
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3452
3453
298
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Cipher data");
3454
3455
79
  unsigned char* out = nullptr;
3456
  bool r;
3457
79
  int out_len = 0;
3458
3459
  // Only copy the data if we have to, because it's a string
3460
158
  if (args[0]->IsString()) {
3461
138
    StringBytes::InlineDecoder decoder;
3462
210
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3463
2
      return;
3464
68
    r = cipher->Update(decoder.out(), decoder.size(), &out, &out_len);
3465
  } else {
3466
9
    char* buf = Buffer::Data(args[0]);
3467
9
    size_t buflen = Buffer::Length(args[0]);
3468
9
    r = cipher->Update(buf, buflen, &out, &out_len);
3469
  }
3470
3471
77
  if (!r) {
3472
    delete[] out;
3473
    return ThrowCryptoError(env,
3474
                            ERR_get_error(),
3475
                            "Trying to add data in unsupported state");
3476
  }
3477
3478
77
  CHECK(out != nullptr || out_len == 0);
3479
  Local<Object> buf =
3480
154
      Buffer::Copy(env, reinterpret_cast<char*>(out), out_len).ToLocalChecked();
3481
77
  if (out)
3482
77
    delete[] out;
3483
3484
154
  args.GetReturnValue().Set(buf);
3485
}
3486
3487
3488
bool CipherBase::SetAutoPadding(bool auto_padding) {
3489
18
  if (!initialised_)
3490
    return false;
3491
18
  return EVP_CIPHER_CTX_set_padding(&ctx_, auto_padding);
3492
}
3493
3494
3495
18
void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
3496
  CipherBase* cipher;
3497
18
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3498
72
  cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue());
3499
}
3500
3501
3502
85
bool CipherBase::Final(unsigned char** out, int *out_len) {
3503
85
  if (!initialised_)
3504
    return false;
3505
3506
81
  *out = new unsigned char[EVP_CIPHER_CTX_block_size(&ctx_)];
3507
81
  int r = EVP_CipherFinal_ex(&ctx_, *out, out_len);
3508
3509
81
  if (r && kind_ == kCipher) {
3510
40
    delete[] auth_tag_;
3511
40
    auth_tag_ = nullptr;
3512
40
    if (IsAuthenticatedMode()) {
3513
1
      auth_tag_len_ = EVP_GCM_TLS_TAG_LEN;  // use default tag length
3514
1
      auth_tag_ = new char[auth_tag_len_];
3515
2
      memset(auth_tag_, 0, auth_tag_len_);
3516
1
      EVP_CIPHER_CTX_ctrl(&ctx_,
3517
                          EVP_CTRL_GCM_GET_TAG,
3518
                          auth_tag_len_,
3519
1
                          reinterpret_cast<unsigned char*>(auth_tag_));
3520
    }
3521
  }
3522
3523
81
  EVP_CIPHER_CTX_cleanup(&ctx_);
3524
81
  initialised_ = false;
3525
3526
81
  return r == 1;
3527
}
3528
3529
3530
85
void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
3531
85
  Environment* env = Environment::GetCurrent(args);
3532
3533
  CipherBase* cipher;
3534
95
  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3535
3536
85
  unsigned char* out_value = nullptr;
3537
85
  int out_len = -1;
3538
85
  Local<Value> outString;
3539
3540
85
  bool r = cipher->Final(&out_value, &out_len);
3541
3542
85
  if (out_len <= 0 || !r) {
3543
35
    delete[] out_value;
3544
35
    out_value = nullptr;
3545
35
    out_len = 0;
3546
35
    if (!r) {
3547
20
      const char* msg = cipher->IsAuthenticatedMode() ?
3548
          "Unsupported state or unable to authenticate data" :
3549
10
          "Unsupported state";
3550
3551
10
      return ThrowCryptoError(env,
3552
                              ERR_get_error(),
3553
10
                              msg);
3554
    }
3555
  }
3556
3557
150
  Local<Object> buf = Buffer::Copy(
3558
      env,
3559
      reinterpret_cast<char*>(out_value),
3560
150
      out_len).ToLocalChecked();
3561
150
  args.GetReturnValue().Set(buf);
3562
75
  delete[] out_value;
3563
}
3564
3565
3566
182
void Hmac::Initialize(Environment* env, v8::Local<v8::Object> target) {
3567
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3568
3569
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3570
3571
182
  env->SetProtoMethod(t, "init", HmacInit);
3572
182
  env->SetProtoMethod(t, "update", HmacUpdate);
3573
182
  env->SetProtoMethod(t, "digest", HmacDigest);
3574
3575
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hmac"), t->GetFunction());
3576
182
}
3577
3578
3579
126
void Hmac::New(const FunctionCallbackInfo<Value>& args) {
3580
126
  Environment* env = Environment::GetCurrent(args);
3581
252
  new Hmac(env, args.This());
3582
126
}
3583
3584
3585
126
void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) {
3586
252
  HandleScope scope(env()->isolate());
3587
3588
126
  CHECK_EQ(initialised_, false);
3589
126
  const EVP_MD* md = EVP_get_digestbyname(hash_type);
3590
126
  if (md == nullptr) {
3591
    return env()->ThrowError("Unknown message digest");
3592
  }
3593
126
  HMAC_CTX_init(&ctx_);
3594
126
  if (key_len == 0) {
3595
6
    key = "";
3596
  }
3597
126
  if (!HMAC_Init_ex(&ctx_, key, key_len, md, nullptr)) {
3598
    return ThrowCryptoError(env(), ERR_get_error());
3599
  }
3600
126
  initialised_ = true;
3601
}
3602
3603
3604
126
void Hmac::HmacInit(const FunctionCallbackInfo<Value>& args) {
3605
  Hmac* hmac;
3606
126
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3607
126
  Environment* env = hmac->env();
3608
3609
126
  if (args.Length() < 2) {
3610
    return env->ThrowError("Hash type and key arguments are mandatory");
3611
  }
3612
3613
252
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Hash type");
3614
126
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3615
3616
252
  const node::Utf8Value hash_type(env->isolate(), args[0]);
3617
126
  const char* buffer_data = Buffer::Data(args[1]);
3618
126
  size_t buffer_length = Buffer::Length(args[1]);
3619
126
  hmac->HmacInit(*hash_type, buffer_data, buffer_length);
3620
}
3621
3622
3623
bool Hmac::HmacUpdate(const char* data, int len) {
3624
128
  if (!initialised_)
3625
    return false;
3626
128
  HMAC_Update(&ctx_, reinterpret_cast<const unsigned char*>(data), len);
3627
  return true;
3628
}
3629
3630
3631
128
void Hmac::HmacUpdate(const FunctionCallbackInfo<Value>& args) {
3632
128
  Environment* env = Environment::GetCurrent(args);
3633
3634
  Hmac* hmac;
3635
128
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3636
3637
328
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Data");
3638
3639
  // Only copy the data if we have to, because it's a string
3640
  bool r;
3641
256
  if (args[0]->IsString()) {
3642
72
    StringBytes::InlineDecoder decoder;
3643
108
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3644
      return;
3645
72
    r = hmac->HmacUpdate(decoder.out(), decoder.size());
3646
  } else {
3647
92
    char* buf = Buffer::Data(args[0]);
3648
92
    size_t buflen = Buffer::Length(args[0]);
3649
184
    r = hmac->HmacUpdate(buf, buflen);
3650
  }
3651
3652
128
  if (!r) {
3653
    return env->ThrowTypeError("HmacUpdate fail");
3654
  }
3655
}
3656
3657
3658
126
bool Hmac::HmacDigest(unsigned char** md_value, unsigned int* md_len) {
3659
126
  if (!initialised_)
3660
    return false;
3661
126
  *md_value = new unsigned char[EVP_MAX_MD_SIZE];
3662
126
  HMAC_Final(&ctx_, *md_value, md_len);
3663
126
  HMAC_CTX_cleanup(&ctx_);
3664
126
  initialised_ = false;
3665
126
  return true;
3666
}
3667
3668
3669
126
void Hmac::HmacDigest(const FunctionCallbackInfo<Value>& args) {
3670
126
  Environment* env = Environment::GetCurrent(args);
3671
3672
  Hmac* hmac;
3673
126
  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3674
3675
126
  enum encoding encoding = BUFFER;
3676
126
  if (args.Length() >= 1) {
3677
392
    encoding = ParseEncoding(env->isolate(),
3678
                             args[0]->ToString(env->isolate()),
3679
98
                             BUFFER);
3680
  }
3681
3682
126
  unsigned char* md_value = nullptr;
3683
126
  unsigned int md_len = 0;
3684
3685
126
  bool r = hmac->HmacDigest(&md_value, &md_len);
3686
126
  if (!r) {
3687
    md_value = nullptr;
3688
    md_len = 0;
3689
  }
3690
3691
  Local<Value> rc = StringBytes::Encode(env->isolate(),
3692
                                        reinterpret_cast<const char*>(md_value),
3693
                                        md_len,
3694
126
                                        encoding);
3695
126
  delete[] md_value;
3696
252
  args.GetReturnValue().Set(rc);
3697
}
3698
3699
3700
182
void Hash::Initialize(Environment* env, v8::Local<v8::Object> target) {
3701
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3702
3703
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3704
3705
182
  env->SetProtoMethod(t, "update", HashUpdate);
3706
182
  env->SetProtoMethod(t, "digest", HashDigest);
3707
3708
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hash"), t->GetFunction());
3709
182
}
3710
3711
3712
227
void Hash::New(const FunctionCallbackInfo<Value>& args) {
3713
227
  Environment* env = Environment::GetCurrent(args);
3714
3715
908
  if (args.Length() == 0 || !args[0]->IsString()) {
3716
2
    return env->ThrowError("Must give hashtype string as argument");
3717
  }
3718
3719
452
  const node::Utf8Value hash_type(env->isolate(), args[0]);
3720
3721
454
  Hash* hash = new Hash(env, args.This());
3722
227
  if (!hash->HashInit(*hash_type)) {
3723
2
    return ThrowCryptoError(env, ERR_get_error(),
3724
2
                            "Digest method not supported");
3725
  }
3726
}
3727
3728
3729
227
bool Hash::HashInit(const char* hash_type) {
3730
227
  CHECK_EQ(initialised_, false);
3731
227
  const EVP_MD* md = EVP_get_digestbyname(hash_type);
3732
227
  if (md == nullptr)
3733
    return false;
3734
225
  EVP_MD_CTX_init(&mdctx_);
3735
225
  if (EVP_DigestInit_ex(&mdctx_, md, nullptr) <= 0) {
3736
    return false;
3737
  }
3738
225
  initialised_ = true;
3739
225
  finalized_ = false;
3740
225
  return true;
3741
}
3742
3743
3744
bool Hash::HashUpdate(const char* data, int len) {
3745
538
  if (!initialised_)
3746
    return false;
3747
538
  EVP_DigestUpdate(&mdctx_, data, len);
3748
  return true;
3749
}
3750
3751
3752
542
void Hash::HashUpdate(const FunctionCallbackInfo<Value>& args) {
3753
542
  Environment* env = Environment::GetCurrent(args);
3754
3755
  Hash* hash;
3756
542
  ASSIGN_OR_RETURN_UNWRAP(&hash, args.Holder());
3757
3758
1504
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Data");
3759
3760
540
  if (!hash->initialised_) {
3761
    return env->ThrowError("Not initialized");
3762
  }
3763
540
  if (hash->finalized_) {
3764
    return env->ThrowError("Digest already called");
3765
  }
3766
3767
  // Only copy the data if we have to, because it's a string
3768
  bool r;
3769
1078
  if (args[0]->IsString()) {
3770
413
    StringBytes::InlineDecoder decoder;
3771
621
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3772
1
      return;
3773
412
    r = hash->HashUpdate(decoder.out(), decoder.size());
3774
  } else {
3775
332
    char* buf = Buffer::Data(args[0]);
3776
332
    size_t buflen = Buffer::Length(args[0]);
3777
664
    r = hash->HashUpdate(buf, buflen);
3778
  }
3779
3780
538
  if (!r) {
3781
    return env->ThrowTypeError("HashUpdate fail");
3782
  }
3783
}
3784
3785
3786
218
void Hash::HashDigest(const FunctionCallbackInfo<Value>& args) {
3787
218
  Environment* env = Environment::GetCurrent(args);
3788
3789
  Hash* hash;
3790
219
  ASSIGN_OR_RETURN_UNWRAP(&hash, args.Holder());
3791
3792
218
  if (!hash->initialised_) {
3793
    return env->ThrowError("Not initialized");
3794
  }
3795
218
  if (hash->finalized_) {
3796
    return env->ThrowError("Digest already called");
3797
  }
3798
3799
217
  enum encoding encoding = BUFFER;
3800
217
  if (args.Length() >= 1) {
3801
844
    encoding = ParseEncoding(env->isolate(),
3802
                             args[0]->ToString(env->isolate()),
3803
211
                             BUFFER);
3804
  }
3805
3806
  unsigned char md_value[EVP_MAX_MD_SIZE];
3807
  unsigned int md_len;
3808
3809
217
  EVP_DigestFinal_ex(&hash->mdctx_, md_value, &md_len);
3810
217
  EVP_MD_CTX_cleanup(&hash->mdctx_);
3811
217
  hash->finalized_ = true;
3812
3813
  Local<Value> rc = StringBytes::Encode(env->isolate(),
3814
                                        reinterpret_cast<const char*>(md_value),
3815
                                        md_len,
3816
217
                                        encoding);
3817
434
  args.GetReturnValue().Set(rc);
3818
}
3819
3820
3821
91
void SignBase::CheckThrow(SignBase::Error error) {
3822
91
  HandleScope scope(env()->isolate());
3823
3824
91
  switch (error) {
3825
    case kSignUnknownDigest:
3826
91
      return env()->ThrowError("Unknown message digest");
3827
3828
    case kSignNotInitialised:
3829
      return env()->ThrowError("Not initialised");
3830
3831
    case kSignInit:
3832
    case kSignUpdate:
3833
    case kSignPrivateKey:
3834
    case kSignPublicKey:
3835
      {
3836
4
        unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
3837
4
        if (err)
3838
4
          return ThrowCryptoError(env(), err);
3839
        switch (error) {
3840
          case kSignInit:
3841
            return env()->ThrowError("EVP_SignInit_ex failed");
3842
          case kSignUpdate:
3843
            return env()->ThrowError("EVP_SignUpdate failed");
3844
          case kSignPrivateKey:
3845
            return env()->ThrowError("PEM_read_bio_PrivateKey failed");
3846
          case kSignPublicKey:
3847
            return env()->ThrowError("PEM_read_bio_PUBKEY failed");
3848
          default:
3849
            ABORT();
3850
        }
3851
      }
3852
3853
    case kSignOk:
3854
      return;
3855
  }
3856
}
3857
3858
3859
3860
3861
182
void Sign::Initialize(Environment* env, v8::Local<v8::Object> target) {
3862
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3863
3864
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
3865
3866
182
  env->SetProtoMethod(t, "init", SignInit);
3867
182
  env->SetProtoMethod(t, "update", SignUpdate);
3868
182
  env->SetProtoMethod(t, "sign", SignFinal);
3869
3870
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Sign"), t->GetFunction());
3871
182
}
3872
3873
3874
21
void Sign::New(const FunctionCallbackInfo<Value>& args) {
3875
21
  Environment* env = Environment::GetCurrent(args);
3876
21
  new Sign(env, args.This());
3877
21
}
3878
3879
3880
21
SignBase::Error Sign::SignInit(const char* sign_type) {
3881
21
  CHECK_EQ(initialised_, false);
3882
21
  const EVP_MD* md = EVP_get_digestbyname(sign_type);
3883
21
  if (md == nullptr)
3884
    return kSignUnknownDigest;
3885
3886
21
  EVP_MD_CTX_init(&mdctx_);
3887
21
  if (!EVP_SignInit_ex(&mdctx_, md, nullptr))
3888
    return kSignInit;
3889
21
  initialised_ = true;
3890
3891
21
  return kSignOk;
3892
}
3893
3894
3895
21
void Sign::SignInit(const FunctionCallbackInfo<Value>& args) {
3896
  Sign* sign;
3897
21
  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
3898
21
  Environment* env = sign->env();
3899
3900
21
  if (args.Length() == 0) {
3901
    return env->ThrowError("Sign type argument is mandatory");
3902
  }
3903
3904
42
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Sign type");
3905
3906
63
  const node::Utf8Value sign_type(args.GetIsolate(), args[0]);
3907
21
  sign->CheckThrow(sign->SignInit(*sign_type));
3908
}
3909
3910
3911
SignBase::Error Sign::SignUpdate(const char* data, int len) {
3912
19
  if (!initialised_)
3913
    return kSignNotInitialised;
3914
19
  if (!EVP_SignUpdate(&mdctx_, data, len))
3915
    return kSignUpdate;
3916
  return kSignOk;
3917
}
3918
3919
3920
20
void Sign::SignUpdate(const FunctionCallbackInfo<Value>& args) {
3921
20
  Environment* env = Environment::GetCurrent(args);
3922
3923
  Sign* sign;
3924
20
  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
3925
3926
76
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Data");
3927
3928
  // Only copy the data if we have to, because it's a string
3929
  Error err;
3930
40
  if (args[0]->IsString()) {
3931
35
    StringBytes::InlineDecoder decoder;
3932
54
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3933
1
      return;
3934
34
    err = sign->SignUpdate(decoder.out(), decoder.size());
3935
  } else {
3936
2
    char* buf = Buffer::Data(args[0]);
3937
2
    size_t buflen = Buffer::Length(args[0]);
3938
4
    err = sign->SignUpdate(buf, buflen);
3939
  }
3940
3941
19
  sign->CheckThrow(err);
3942
}
3943
3944
3945
20
SignBase::Error Sign::SignFinal(const char* key_pem,
3946
                                int key_pem_len,
3947
                                const char* passphrase,
3948
                                unsigned char** sig,
3949
                                unsigned int *sig_len) {
3950
20
  if (!initialised_)
3951
    return kSignNotInitialised;
3952
3953
20
  BIO* bp = nullptr;
3954
20
  EVP_PKEY* pkey = nullptr;
3955
20
  bool fatal = true;
3956
3957
20
  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
3958
20
  if (bp == nullptr)
3959
    goto exit;
3960
3961
  pkey = PEM_read_bio_PrivateKey(bp,
3962
                                 nullptr,
3963
                                 CryptoPemCallback,
3964
20
                                 const_cast<char*>(passphrase));
3965
3966
  // Errors might be injected into OpenSSL's error stack
3967
  // without `pkey` being set to nullptr;
3968
  // cf. the test of `test_bad_rsa_privkey.pem` for an example.
3969
20
  if (pkey == nullptr || 0 != ERR_peek_error())
3970
    goto exit;
3971
3972
#ifdef NODE_FIPS_MODE
3973
  /* Validate DSA2 parameters from FIPS 186-4 */
3974
  if (FIPS_mode() && EVP_PKEY_DSA == pkey->type) {
3975
    size_t L = BN_num_bits(pkey->pkey.dsa->p);
3976
    size_t N = BN_num_bits(pkey->pkey.dsa->q);
3977
    bool result = false;
3978
3979
    if (L == 1024 && N == 160)
3980
      result = true;
3981
    else if (L == 2048 && N == 224)
3982
      result = true;
3983
    else if (L == 2048 && N == 256)
3984
      result = true;
3985
    else if (L == 3072 && N == 256)
3986
      result = true;
3987
3988
    if (!result) {
3989
      fatal = true;
3990
      goto exit;
3991
    }
3992
  }
3993
#endif  // NODE_FIPS_MODE
3994
3995
17
  if (EVP_SignFinal(&mdctx_, *sig, sig_len, pkey))
3996
16
    fatal = false;
3997
3998
17
  initialised_ = false;
3999
4000
 exit:
4001
20
  if (pkey != nullptr)
4002
18
    EVP_PKEY_free(pkey);
4003
20
  if (bp != nullptr)
4004
20
    BIO_free_all(bp);
4005
4006
20
  EVP_MD_CTX_cleanup(&mdctx_);
4007
4008
20
  if (fatal)
4009
    return kSignPrivateKey;
4010
4011
16
  return kSignOk;
4012
}
4013
4014
4015
20
void Sign::SignFinal(const FunctionCallbackInfo<Value>& args) {
4016
20
  Environment* env = Environment::GetCurrent(args);
4017
4018
  Sign* sign;
4019
24
  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
4020
4021
  unsigned char* md_value;
4022
  unsigned int md_len;
4023
4024
20
  unsigned int len = args.Length();
4025
20
  enum encoding encoding = BUFFER;
4026
60
  if (len >= 2 && args[1]->IsString()) {
4027
    encoding = ParseEncoding(env->isolate(),
4028
                             args[1]->ToString(env->isolate()),
4029
                             BUFFER);
4030
  }
4031
4032
36
  node::Utf8Value passphrase(env->isolate(), args[2]);
4033
4034
20
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
4035
20
  size_t buf_len = Buffer::Length(args[0]);
4036
20
  char* buf = Buffer::Data(args[0]);
4037
4038
20
  md_len = 8192;  // Maximum key size is 8192 bits
4039
20
  md_value = new unsigned char[md_len];
4040
4041
16
  ClearErrorOnReturn clear_error_on_return;
4042
  (void) &clear_error_on_return;  // Silence compiler warning.
4043
4044
24
  Error err = sign->SignFinal(
4045
      buf,
4046
      buf_len,
4047
40
      len >= 3 && !args[2]->IsNull() ? *passphrase : nullptr,
4048
      &md_value,
4049
20
      &md_len);
4050
20
  if (err != kSignOk) {
4051
4
    delete[] md_value;
4052
4
    md_value = nullptr;
4053
4
    md_len = 0;
4054
4
    return sign->CheckThrow(err);
4055
  }
4056
4057
  Local<Value> rc = StringBytes::Encode(env->isolate(),
4058
                                        reinterpret_cast<const char*>(md_value),
4059
                                        md_len,
4060
16
                                        encoding);
4061
16
  delete[] md_value;
4062
32
  args.GetReturnValue().Set(rc);
4063
}
4064
4065
4066
182
void Verify::Initialize(Environment* env, v8::Local<v8::Object> target) {
4067
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
4068
4069
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
4070
4071
182
  env->SetProtoMethod(t, "init", VerifyInit);
4072
182
  env->SetProtoMethod(t, "update", VerifyUpdate);
4073
182
  env->SetProtoMethod(t, "verify", VerifyFinal);
4074
4075
910
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Verify"),
4076
182
              t->GetFunction());
4077
182
}
4078
4079
4080
19
void Verify::New(const FunctionCallbackInfo<Value>& args) {
4081
19
  Environment* env = Environment::GetCurrent(args);
4082
19
  new Verify(env, args.This());
4083
19
}
4084
4085
4086
19
SignBase::Error Verify::VerifyInit(const char* verify_type) {
4087
19
  CHECK_EQ(initialised_, false);
4088
19
  const EVP_MD* md = EVP_get_digestbyname(verify_type);
4089
19
  if (md == nullptr)
4090
    return kSignUnknownDigest;
4091
4092
19
  EVP_MD_CTX_init(&mdctx_);
4093
19
  if (!EVP_VerifyInit_ex(&mdctx_, md, nullptr))
4094
    return kSignInit;
4095
19
  initialised_ = true;
4096
4097
19
  return kSignOk;
4098
}
4099
4100
4101
19
void Verify::VerifyInit(const FunctionCallbackInfo<Value>& args) {
4102
  Verify* verify;
4103
19
  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4104
19
  Environment* env = verify->env();
4105
4106
19
  if (args.Length() == 0) {
4107
    return env->ThrowError("Verify type argument is mandatory");
4108
  }
4109
4110
38
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Verify type");
4111
4112
57
  const node::Utf8Value verify_type(args.GetIsolate(), args[0]);
4113
19
  verify->CheckThrow(verify->VerifyInit(*verify_type));
4114
}
4115
4116
4117
SignBase::Error Verify::VerifyUpdate(const char* data, int len) {
4118
28
  if (!initialised_)
4119
    return kSignNotInitialised;
4120
4121
28
  if (!EVP_VerifyUpdate(&mdctx_, data, len))
4122
    return kSignUpdate;
4123
4124
  return kSignOk;
4125
}
4126
4127
4128
29
void Verify::VerifyUpdate(const FunctionCallbackInfo<Value>& args) {
4129
29
  Environment* env = Environment::GetCurrent(args);
4130
4131
  Verify* verify;
4132
29
  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4133
4134
104
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Data");
4135
4136
  // Only copy the data if we have to, because it's a string
4137
  Error err;
4138
58
  if (args[0]->IsString()) {
4139
45
    StringBytes::InlineDecoder decoder;
4140
69
    if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
4141
1
      return;
4142
44
    err = verify->VerifyUpdate(decoder.out(), decoder.size());
4143
  } else {
4144
6
    char* buf = Buffer::Data(args[0]);
4145
6
    size_t buflen = Buffer::Length(args[0]);
4146
12
    err = verify->VerifyUpdate(buf, buflen);
4147
  }
4148
4149
28
  verify->CheckThrow(err);
4150
}
4151
4152
4153
18
SignBase::Error Verify::VerifyFinal(const char* key_pem,
4154
                                    int key_pem_len,
4155
                                    const char* sig,
4156
                                    int siglen,
4157
                                    bool* verify_result) {
4158
18
  if (!initialised_)
4159
    return kSignNotInitialised;
4160
4161
  ClearErrorOnReturn clear_error_on_return;
4162
  (void) &clear_error_on_return;  // Silence compiler warning.
4163
4164
18
  EVP_PKEY* pkey = nullptr;
4165
18
  BIO* bp = nullptr;
4166
18
  X509* x509 = nullptr;
4167
18
  bool fatal = true;
4168
18
  int r = 0;
4169
4170
18
  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
4171
18
  if (bp == nullptr)
4172
    goto exit;
4173
4174
  // Check if this is a PKCS#8 or RSA public key before trying as X.509.
4175
  // Split this out into a separate function once we have more than one
4176
  // consumer of public keys.
4177
18
  if (strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
4178
6
    pkey = PEM_read_bio_PUBKEY(bp, nullptr, CryptoPemCallback, nullptr);
4179
6
    if (pkey == nullptr)
4180
      goto exit;
4181
12
  } else if (strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
4182
    RSA* rsa =
4183
2
        PEM_read_bio_RSAPublicKey(bp, nullptr, CryptoPemCallback, nullptr);
4184
2
    if (rsa) {
4185
2
      pkey = EVP_PKEY_new();
4186
2
      if (pkey)
4187
2
        EVP_PKEY_set1_RSA(pkey, rsa);
4188
2
      RSA_free(rsa);
4189
    }
4190
2
    if (pkey == nullptr)
4191
      goto exit;
4192
  } else {
4193
    // X.509 fallback
4194
10
    x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr);
4195
10
    if (x509 == nullptr)
4196
      goto exit;
4197
4198
10
    pkey = X509_get_pubkey(x509);
4199
10
    if (pkey == nullptr)
4200
      goto exit;
4201
  }
4202
4203
18
  fatal = false;
4204
18
  r = EVP_VerifyFinal(&mdctx_,
4205
                      reinterpret_cast<const unsigned char*>(sig),
4206
                      siglen,
4207
18
                      pkey);
4208
4209
 exit:
4210
18
  if (pkey != nullptr)
4211
18
    EVP_PKEY_free(pkey);
4212
18
  if (bp != nullptr)
4213
18
    BIO_free_all(bp);
4214
18
  if (x509 != nullptr)
4215
10
    X509_free(x509);
4216
4217
18
  EVP_MD_CTX_cleanup(&mdctx_);
4218
18
  initialised_ = false;
4219
4220
18
  if (fatal)
4221
    return kSignPublicKey;
4222
4223
18
  *verify_result = r == 1;
4224
18
  return kSignOk;
4225
}
4226
4227
4228
18
void Verify::VerifyFinal(const FunctionCallbackInfo<Value>& args) {
4229
18
  Environment* env = Environment::GetCurrent(args);
4230
4231
  Verify* verify;
4232
18
  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4233
4234
18
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Key");
4235
18
  char* kbuf = Buffer::Data(args[0]);
4236
18
  ssize_t klen = Buffer::Length(args[0]);
4237
4238
36
  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[1], "Hash");
4239
4240
18
  enum encoding encoding = UTF8;
4241
18
  if (args.Length() >= 3) {
4242
    encoding = ParseEncoding(env->isolate(),
4243
                             args[2]->ToString(env->isolate()),
4244
                             UTF8);
4245
  }
4246
4247
18
  ssize_t hlen = StringBytes::Size(env->isolate(), args[1], encoding);
4248
4249
  // only copy if we need to, because it's a string.
4250
  char* hbuf;
4251
36
  if (args[1]->IsString()) {
4252
    hbuf = new char[hlen];
4253
    ssize_t hwritten = StringBytes::Write(env->isolate(),
4254
                                          hbuf,
4255
                                          hlen,
4256
                                          args[1],
4257
                                          encoding);
4258
    CHECK_EQ(hwritten, hlen);
4259
  } else {
4260
18
    hbuf = Buffer::Data(args[1]);
4261
  }
4262
4263
  bool verify_result;
4264
18
  Error err = verify->VerifyFinal(kbuf, klen, hbuf, hlen, &verify_result);
4265
36
  if (args[1]->IsString())
4266
    delete[] hbuf;
4267
18
  if (err != kSignOk)
4268
    return verify->CheckThrow(err);
4269
54
  args.GetReturnValue().Set(verify_result);
4270
}
4271
4272
4273
template <PublicKeyCipher::Operation operation,
4274
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
4275
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
4276
23
bool PublicKeyCipher::Cipher(const char* key_pem,
4277
                             int key_pem_len,
4278
                             const char* passphrase,
4279
                             int padding,
4280
                             const unsigned char* data,
4281
                             int len,
4282
                             unsigned char** out,
4283
                             size_t* out_len) {
4284
23
  EVP_PKEY* pkey = nullptr;
4285
23
  EVP_PKEY_CTX* ctx = nullptr;
4286
23
  BIO* bp = nullptr;
4287
23
  X509* x509 = nullptr;
4288
23
  bool fatal = true;
4289
4290
23
  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
4291
23
  if (bp == nullptr)
4292
    goto exit;
4293
4294
  // Check if this is a PKCS#8 or RSA public key before trying as X.509 and
4295
  // private key.
4296
11
  if (operation == kPublic &&
4297
11
      strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
4298
4
    pkey = PEM_read_bio_PUBKEY(bp, nullptr, nullptr, nullptr);
4299
4
    if (pkey == nullptr)
4300
      goto exit;
4301
7
  } else if (operation == kPublic &&
4302
7
             strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
4303
    RSA* rsa = PEM_read_bio_RSAPublicKey(bp, nullptr, nullptr, nullptr);
4304
    if (rsa) {
4305
      pkey = EVP_PKEY_new();
4306
      if (pkey)
4307
        EVP_PKEY_set1_RSA(pkey, rsa);
4308
      RSA_free(rsa);
4309
    }
4310
    if (pkey == nullptr)
4311
      goto exit;
4312
7
  } else if (operation == kPublic &&
4313
7
             strncmp(key_pem, CERTIFICATE_PFX, CERTIFICATE_PFX_LEN) == 0) {
4314
1
    x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr);
4315
1
    if (x509 == nullptr)
4316
      goto exit;
4317
4318
1
    pkey = X509_get_pubkey(x509);
4319
1
    if (pkey == nullptr)
4320
      goto exit;
4321
  } else {
4322
18
    pkey = PEM_read_bio_PrivateKey(bp,
4323
                                   nullptr,
4324
                                   CryptoPemCallback,
4325
                                   const_cast<char*>(passphrase));
4326
18
    if (pkey == nullptr)
4327
      goto exit;
4328
  }
4329
4330
20
  ctx = EVP_PKEY_CTX_new(pkey, nullptr);
4331
20
  if (!ctx)
4332
    goto exit;
4333
20
  if (EVP_PKEY_cipher_init(ctx) <= 0)
4334
    goto exit;
4335
20
  if (EVP_PKEY_CTX_set_rsa_padding(ctx, padding) <= 0)
4336
    goto exit;
4337
4338
20
  if (EVP_PKEY_cipher(ctx, nullptr, out_len, data, len) <= 0)
4339
    goto exit;
4340
4341
20
  *out = new unsigned char[*out_len];
4342
4343
20
  if (EVP_PKEY_cipher(ctx, *out, out_len, data, len) <= 0)
4344
    goto exit;
4345
4346
20
  fatal = false;
4347
4348
 exit:
4349
11
  if (x509 != nullptr)
4350
1
    X509_free(x509);
4351
23
  if (pkey != nullptr)
4352
20
    EVP_PKEY_free(pkey);
4353
23
  if (bp != nullptr)
4354
23
    BIO_free_all(bp);
4355
23
  if (ctx != nullptr)
4356
20
    EVP_PKEY_CTX_free(ctx);
4357
4358
23
  return !fatal;
4359
}
4360
4361
4362
template <PublicKeyCipher::Operation operation,
4363
          PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
4364
          PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
4365
23
void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
4366
23
  Environment* env = Environment::GetCurrent(args);
4367
4368
26
  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Key");
4369
23
  char* kbuf = Buffer::Data(args[0]);
4370
23
  ssize_t klen = Buffer::Length(args[0]);
4371
4372
23
  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Data");
4373
23
  char* buf = Buffer::Data(args[1]);
4374
23
  ssize_t len = Buffer::Length(args[1]);
4375
4376
23
  int padding = args[2]->Uint32Value();
4377
4378
43
  String::Utf8Value passphrase(args[3]);
4379
4380
23
  unsigned char* out_value = nullptr;
4381
23
  size_t out_len = 0;
4382
4383
  ClearErrorOnReturn clear_error_on_return;
4384
  (void) &clear_error_on_return;  // Silence compiler warning.
4385
4386
92
  bool r = Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
4387
      kbuf,
4388
      klen,
4389
92
      args.Length() >= 3 && !args[2]->IsNull() ? *passphrase : nullptr,
4390
      padding,
4391
      reinterpret_cast<const unsigned char*>(buf),
4392
      len,
4393
      &out_value,
4394
23
      &out_len);
4395
4396
23
  if (out_len == 0 || !r) {
4397
3
    delete[] out_value;
4398
3
    out_value = nullptr;
4399
3
    out_len = 0;
4400
3
    if (!r) {
4401
3
      return ThrowCryptoError(env,
4402
3
        ERR_get_error());
4403
    }
4404
  }
4405
4406
20
  Local<Object> vbuf = Buffer::Copy(
4407
      env,
4408
      reinterpret_cast<char*>(out_value),
4409
40
      out_len).ToLocalChecked();
4410
40
  args.GetReturnValue().Set(vbuf);
4411
20
  delete[] out_value;
4412
}
4413
4414
4415
182
void DiffieHellman::Initialize(Environment* env, Local<Object> target) {
4416
364
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
4417
4418
  const PropertyAttribute attributes =
4419
182
      static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
4420
4421
364
  t->InstanceTemplate()->SetInternalFieldCount(1);
4422
4423
182
  env->SetProtoMethod(t, "generateKeys", GenerateKeys);
4424
182
  env->SetProtoMethod(t, "computeSecret", ComputeSecret);
4425
182
  env->SetProtoMethod(t, "getPrime", GetPrime);
4426
182
  env->SetProtoMethod(t, "getGenerator", GetGenerator);
4427
182
  env->SetProtoMethod(t, "getPublicKey", GetPublicKey);
4428
182
  env->SetProtoMethod(t, "getPrivateKey", GetPrivateKey);
4429
182
  env->SetProtoMethod(t, "setPublicKey", SetPublicKey);
4430
182
  env->SetProtoMethod(t, "setPrivateKey", SetPrivateKey);
4431
4432
1092
  t->InstanceTemplate()->SetAccessor(
4433
      env->verify_error_string(),
4434
      DiffieHellman::VerifyErrorGetter,
4435
      nullptr,
4436
      env->as_external(),
4437
      DEFAULT,
4438
      attributes,
4439
182
      AccessorSignature::New(env->isolate(), t));
4440
4441
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellman"),
4442
182
              t->GetFunction());
4443
4444
364
  Local<FunctionTemplate> t2 = env->NewFunctionTemplate(DiffieHellmanGroup);
4445
364
  t2->InstanceTemplate()->SetInternalFieldCount(1);
4446
4447
182
  env->SetProtoMethod(t2, "generateKeys", GenerateKeys);
4448
182
  env->SetProtoMethod(t2, "computeSecret", ComputeSecret);
4449
182
  env->SetProtoMethod(t2, "getPrime", GetPrime);
4450
182
  env->SetProtoMethod(t2, "getGenerator", GetGenerator);
4451
182
  env->SetProtoMethod(t2, "getPublicKey", GetPublicKey);
4452
182
  env->SetProtoMethod(t2, "getPrivateKey", GetPrivateKey);
4453
4454
1092
  t2->InstanceTemplate()->SetAccessor(
4455
      env->verify_error_string(),
4456
      DiffieHellman::VerifyErrorGetter,
4457
      nullptr,
4458
      env->as_external(),
4459
      DEFAULT,
4460
      attributes,
4461
182
      AccessorSignature::New(env->isolate(), t2));
4462
4463
728
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellmanGroup"),
4464
182
              t2->GetFunction());
4465
182
}
4466
4467
4468
3
bool DiffieHellman::Init(int primeLength, int g) {
4469
3
  dh = DH_new();
4470
3
  if (!DH_generate_parameters_ex(dh, primeLength, g, 0))
4471
    return false;
4472
3
  bool result = VerifyContext();
4473
3
  if (!result)
4474
    return false;
4475
3
  initialised_ = true;
4476
3
  return true;
4477
}
4478
4479
4480
8
bool DiffieHellman::Init(const char* p, int p_len, int g) {
4481
8
  dh = DH_new();
4482
8
  dh->p = BN_bin2bn(reinterpret_cast<const unsigned char*>(p), p_len, 0);
4483
8
  dh->g = BN_new();
4484
8
  if (!BN_set_word(dh->g, g))
4485
    return false;
4486
8
  bool result = VerifyContext();
4487
8
  if (!result)
4488
    return false;
4489
8
  initialised_ = true;
4490
8
  return true;
4491
}
4492
4493
4494
7
bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) {
4495
7
  dh = DH_new();
4496
7
  dh->p = BN_bin2bn(reinterpret_cast<const unsigned char*>(p), p_len, 0);
4497
7
  dh->g = BN_bin2bn(reinterpret_cast<const unsigned char*>(g), g_len, 0);
4498
7
  bool result = VerifyContext();
4499
7
  if (!result)
4500
    return false;
4501
7
  initialised_ = true;
4502
7
  return true;
4503
}
4504
4505
4506
4
void DiffieHellman::DiffieHellmanGroup(
4507
    const FunctionCallbackInfo<Value>& args) {
4508
4
  Environment* env = Environment::GetCurrent(args);
4509
4
  DiffieHellman* diffieHellman = new DiffieHellman(env, args.This());
4510
4511
4
  if (args.Length() != 1) {
4512
4
    return env->ThrowError("Group name argument is mandatory");
4513
  }
4514
4515
8
  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Group name");
4516
4517
4
  bool initialized = false;
4518
4519
4
  const node::Utf8Value group_name(env->isolate(), args[0]);
4520
12
  for (size_t i = 0; i < arraysize(modp_groups); ++i) {
4521
12
    const modp_group* it = modp_groups + i;
4522
4523
12
    if (!StringEqualNoCase(*group_name, it->name))
4524
      continue;
4525
4526
8
    initialized = diffieHellman->Init(it->prime,
4527
4
                                      it->prime_size,
4528
4
                                      it->gen,
4529
8
                                      it->gen_size);
4530
4
    if (!initialized)
4531
      env->ThrowError("Initialization failed");
4532
    return;
4533
  }
4534
4535
  env->ThrowError("Unknown group");
4536
}
4537
4538
4539
14
void DiffieHellman::New(const FunctionCallbackInfo<Value>& args) {
4540
14
  Environment* env = Environment::GetCurrent(args);
4541
  DiffieHellman* diffieHellman =
4542
14
      new DiffieHellman(env, args.This());
4543
14
  bool initialized = false;
4544
4545
14
  if (args.Length() == 2) {
4546
14
    if (args[0]->IsInt32()) {
4547
3
      if (args[1]->IsInt32()) {
4548
6
        initialized = diffieHellman->Init(args[0]->Int32Value(),
4549
3
                                          args[1]->Int32Value());
4550
      }
4551
    } else {
4552
11
      if (args[1]->IsInt32()) {
4553
24
        initialized = diffieHellman->Init(Buffer::Data(args[0]),
4554
8
                                          Buffer::Length(args[0]),
4555
8
                                          args[1]->Int32Value());
4556
      } else {
4557
9
        initialized = diffieHellman->Init(Buffer::Data(args[0]),
4558
3
                                          Buffer::Length(args[0]),
4559
3
                                          Buffer::Data(args[1]),
4560
6
                                          Buffer::Length(args[1]));
4561