Node.js  v8.x
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine
node_crypto.cc
Go to the documentation of this file.
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 
22 #include "node.h"
23 #include "node_buffer.h"
24 #include "node_constants.h"
25 #include "node_crypto.h"
26 #include "node_crypto_bio.h"
27 #include "node_crypto_groups.h"
28 #include "node_mutex.h"
29 #include "tls_wrap.h" // TLSWrap
30 
31 #include "async-wrap.h"
32 #include "async-wrap-inl.h"
33 #include "env.h"
34 #include "env-inl.h"
35 #include "string_bytes.h"
36 #include "util.h"
37 #include "util-inl.h"
38 #include "v8.h"
39 // CNNIC Hash WhiteList is taken from
40 // https://hg.mozilla.org/mozilla-central/raw-file/98820360ab66/security/
41 // certverifier/CNNICHashWhitelist.inc
42 #include "CNNICHashWhitelist.inc"
43 // StartCom and WoSign root CA list is taken from
44 // https://hg.mozilla.org/mozilla-central/file/tip/security/certverifier/
45 // StartComAndWoSignData.inc
47 
48 #include <errno.h>
49 #include <limits.h> // INT_MAX
50 #include <math.h>
51 #include <stdlib.h>
52 #include <string.h>
53 
54 #define THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(val, prefix) \
55  do { \
56  if (!Buffer::HasInstance(val) && !val->IsString()) { \
57  return env->ThrowTypeError(prefix " must be a string or a buffer"); \
58  } \
59  } while (0)
60 
61 #define THROW_AND_RETURN_IF_NOT_BUFFER(val, prefix) \
62  do { \
63  if (!Buffer::HasInstance(val)) { \
64  return env->ThrowTypeError(prefix " must be a buffer"); \
65  } \
66  } while (0)
67 
68 #define THROW_AND_RETURN_IF_NOT_STRING(val, prefix) \
69  do { \
70  if (!val->IsString()) { \
71  return env->ThrowTypeError(prefix " must be a string"); \
72  } \
73  } while (0)
74 
75 static const char PUBLIC_KEY_PFX[] = "-----BEGIN PUBLIC KEY-----";
76 static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
77 static const char PUBRSA_KEY_PFX[] = "-----BEGIN RSA PUBLIC KEY-----";
78 static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
79 static const char CERTIFICATE_PFX[] = "-----BEGIN CERTIFICATE-----";
80 static const int CERTIFICATE_PFX_LEN = sizeof(CERTIFICATE_PFX) - 1;
81 
82 static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
83  | ASN1_STRFLGS_UTF8_CONVERT
84  | XN_FLAG_SEP_MULTILINE
85  | XN_FLAG_FN_SN;
86 
87 namespace node {
88 namespace crypto {
89 
90 using v8::AccessorSignature;
91 using v8::Array;
92 using v8::Boolean;
93 using v8::Context;
94 using v8::DEFAULT;
95 using v8::DontDelete;
96 using v8::EscapableHandleScope;
97 using v8::Exception;
98 using v8::External;
99 using v8::False;
100 using v8::FunctionCallbackInfo;
101 using v8::FunctionTemplate;
102 using v8::HandleScope;
103 using v8::Integer;
104 using v8::Isolate;
105 using v8::Local;
106 using v8::Maybe;
107 using v8::MaybeLocal;
108 using v8::Null;
109 using v8::Object;
110 using v8::ObjectTemplate;
111 using v8::Persistent;
112 using v8::PropertyAttribute;
113 using v8::PropertyCallbackInfo;
114 using v8::ReadOnly;
115 using v8::String;
116 using v8::Value;
117 
118 
119 // Subject DER of CNNIC ROOT CA and CNNIC EV ROOT CA are taken from
120 // https://hg.mozilla.org/mozilla-central/file/98820360ab66/security/
121 // certverifier/NSSCertDBTrustDomain.cpp#l672
122 // C = CN, O = CNNIC, CN = CNNIC ROOT
123 static const uint8_t CNNIC_ROOT_CA_SUBJECT_DATA[] =
124  "\x30\x32\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x43\x4E\x31\x0E\x30"
125  "\x0C\x06\x03\x55\x04\x0A\x13\x05\x43\x4E\x4E\x49\x43\x31\x13\x30\x11\x06"
126  "\x03\x55\x04\x03\x13\x0A\x43\x4E\x4E\x49\x43\x20\x52\x4F\x4F\x54";
127 static const uint8_t* cnnic_p = CNNIC_ROOT_CA_SUBJECT_DATA;
128 static X509_NAME* cnnic_name =
129  d2i_X509_NAME(nullptr, &cnnic_p, sizeof(CNNIC_ROOT_CA_SUBJECT_DATA)-1);
130 
131 // C = CN, O = China Internet Network Information Center, CN = China
132 // Internet Network Information Center EV Certificates Root
133 static const uint8_t CNNIC_EV_ROOT_CA_SUBJECT_DATA[] =
134  "\x30\x81\x8A\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x43\x4E\x31\x32"
135  "\x30\x30\x06\x03\x55\x04\x0A\x0C\x29\x43\x68\x69\x6E\x61\x20\x49\x6E\x74"
136  "\x65\x72\x6E\x65\x74\x20\x4E\x65\x74\x77\x6F\x72\x6B\x20\x49\x6E\x66\x6F"
137  "\x72\x6D\x61\x74\x69\x6F\x6E\x20\x43\x65\x6E\x74\x65\x72\x31\x47\x30\x45"
138  "\x06\x03\x55\x04\x03\x0C\x3E\x43\x68\x69\x6E\x61\x20\x49\x6E\x74\x65\x72"
139  "\x6E\x65\x74\x20\x4E\x65\x74\x77\x6F\x72\x6B\x20\x49\x6E\x66\x6F\x72\x6D"
140  "\x61\x74\x69\x6F\x6E\x20\x43\x65\x6E\x74\x65\x72\x20\x45\x56\x20\x43\x65"
141  "\x72\x74\x69\x66\x69\x63\x61\x74\x65\x73\x20\x52\x6F\x6F\x74";
142 static const uint8_t* cnnic_ev_p = CNNIC_EV_ROOT_CA_SUBJECT_DATA;
143 static X509_NAME *cnnic_ev_name =
144  d2i_X509_NAME(nullptr, &cnnic_ev_p,
145  sizeof(CNNIC_EV_ROOT_CA_SUBJECT_DATA)-1);
146 
147 static Mutex* mutexes;
148 
149 static const char* const root_certs[] = {
150 #include "node_root_certs.h" // NOLINT(build/include_order)
151 };
152 
153 static std::string extra_root_certs_file; // NOLINT(runtime/string)
154 
155 static X509_STORE* root_cert_store;
156 
157 // Just to generate static methods
158 template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
159  Local<FunctionTemplate> t);
160 template void SSLWrap<TLSWrap>::InitNPN(SecureContext* sc);
161 template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc);
162 template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
163 template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
164  SSL* s,
165  unsigned char* key,
166  int len,
167  int* copy);
168 template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
169  SSL_SESSION* sess);
170 template void SSLWrap<TLSWrap>::OnClientHello(
171  void* arg,
172  const ClientHelloParser::ClientHello& hello);
173 
174 #ifndef OPENSSL_NO_NEXTPROTONEG
175 template int SSLWrap<TLSWrap>::AdvertiseNextProtoCallback(
176  SSL* s,
177  const unsigned char** data,
178  unsigned int* len,
179  void* arg);
180 template int SSLWrap<TLSWrap>::SelectNextProtoCallback(
181  SSL* s,
182  unsigned char** out,
183  unsigned char* outlen,
184  const unsigned char* in,
185  unsigned int inlen,
186  void* arg);
187 #endif
188 
189 #ifdef NODE__HAVE_TLSEXT_STATUS_CB
190 template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
191 #endif
192 
193 template void SSLWrap<TLSWrap>::DestroySSL();
194 template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
195 template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
196 
197 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
198 template int SSLWrap<TLSWrap>::SelectALPNCallback(
199  SSL* s,
200  const unsigned char** out,
201  unsigned char* outlen,
202  const unsigned char* in,
203  unsigned int inlen,
204  void* arg);
205 #endif // TLSEXT_TYPE_application_layer_protocol_negotiation
206 
207 static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
208  static_assert(sizeof(uv_thread_t) <= sizeof(void*),
209  "uv_thread_t does not fit in a pointer");
210  CRYPTO_THREADID_set_pointer(tid, reinterpret_cast<void*>(uv_thread_self()));
211 }
212 
213 
214 static void crypto_lock_init(void) {
215  mutexes = new Mutex[CRYPTO_num_locks()];
216 }
217 
218 
219 static void crypto_lock_cb(int mode, int n, const char* file, int line) {
220  CHECK(!(mode & CRYPTO_LOCK) ^ !(mode & CRYPTO_UNLOCK));
221  CHECK(!(mode & CRYPTO_READ) ^ !(mode & CRYPTO_WRITE));
222 
223  auto mutex = &mutexes[n];
224  if (mode & CRYPTO_LOCK)
225  mutex->Lock();
226  else
227  mutex->Unlock();
228 }
229 
230 
231 static int PasswordCallback(char *buf, int size, int rwflag, void *u) {
232  if (u) {
233  size_t buflen = static_cast<size_t>(size);
234  size_t len = strlen(static_cast<const char*>(u));
235  len = len > buflen ? buflen : len;
236  memcpy(buf, u, len);
237  return len;
238  }
239 
240  return 0;
241 }
242 
243 
244 // This callback is used to avoid the default passphrase callback in OpenSSL
245 // which will typically prompt for the passphrase. The prompting is designed
246 // for the OpenSSL CLI, but works poorly for Node.js because it involves
247 // synchronous interaction with the controlling terminal, something we never
248 // want, and use this function to avoid it.
249 static int NoPasswordCallback(char *buf, int size, int rwflag, void *u) {
250  return 0;
251 }
252 
253 
254 void ThrowCryptoError(Environment* env,
255  unsigned long err, // NOLINT(runtime/int)
256  const char* default_message = nullptr) {
257  HandleScope scope(env->isolate());
258  if (err != 0 || default_message == nullptr) {
259  char errmsg[128] = { 0 };
260  ERR_error_string_n(err, errmsg, sizeof(errmsg));
261  env->ThrowError(errmsg);
262  } else {
263  env->ThrowError(default_message);
264  }
265 }
266 
267 
268 // Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
269 // The entropy pool starts out empty and needs to fill up before the PRNG
270 // can be used securely. Once the pool is filled, it never dries up again;
271 // its contents is stirred and reused when necessary.
272 //
273 // OpenSSL normally fills the pool automatically but not when someone starts
274 // generating random numbers before the pool is full: in that case OpenSSL
275 // keeps lowering the entropy estimate to thwart attackers trying to guess
276 // the initial state of the PRNG.
277 //
278 // When that happens, we will have to wait until enough entropy is available.
279 // That should normally never take longer than a few milliseconds.
280 //
281 // OpenSSL draws from /dev/random and /dev/urandom. While /dev/random may
282 // block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
283 // block under normal circumstances.
284 //
285 // The only time when /dev/urandom may conceivably block is right after boot,
286 // when the whole system is still low on entropy. That's not something we can
287 // do anything about.
288 inline void CheckEntropy() {
289  for (;;) {
290  int status = RAND_status();
291  CHECK_GE(status, 0); // Cannot fail.
292  if (status != 0)
293  break;
294 
295  // Give up, RAND_poll() not supported.
296  if (RAND_poll() == 0)
297  break;
298  }
299 }
300 
301 
302 bool EntropySource(unsigned char* buffer, size_t length) {
303  // Ensure that OpenSSL's PRNG is properly seeded.
304  CheckEntropy();
305  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
306  // random. That's okay, it's still better than V8's stock source of entropy,
307  // which is /dev/urandom on UNIX platforms and the current time on Windows.
308  return RAND_bytes(buffer, length) != -1;
309 }
310 
311 
312 void SecureContext::Initialize(Environment* env, Local<Object> target) {
313  Local<FunctionTemplate> t = env->NewFunctionTemplate(SecureContext::New);
314  t->InstanceTemplate()->SetInternalFieldCount(1);
315  Local<String> secureContextString =
316  FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext");
317  t->SetClassName(secureContextString);
318 
319  env->SetProtoMethod(t, "init", SecureContext::Init);
320  env->SetProtoMethod(t, "setKey", SecureContext::SetKey);
321  env->SetProtoMethod(t, "setCert", SecureContext::SetCert);
322  env->SetProtoMethod(t, "addCACert", SecureContext::AddCACert);
323  env->SetProtoMethod(t, "addCRL", SecureContext::AddCRL);
324  env->SetProtoMethod(t, "addRootCerts", SecureContext::AddRootCerts);
325  env->SetProtoMethod(t, "setCiphers", SecureContext::SetCiphers);
326  env->SetProtoMethod(t, "setECDHCurve", SecureContext::SetECDHCurve);
327  env->SetProtoMethod(t, "setDHParam", SecureContext::SetDHParam);
328  env->SetProtoMethod(t, "setOptions", SecureContext::SetOptions);
329  env->SetProtoMethod(t, "setSessionIdContext",
330  SecureContext::SetSessionIdContext);
331  env->SetProtoMethod(t, "setSessionTimeout",
332  SecureContext::SetSessionTimeout);
333  env->SetProtoMethod(t, "close", SecureContext::Close);
334  env->SetProtoMethod(t, "loadPKCS12", SecureContext::LoadPKCS12);
335  env->SetProtoMethod(t, "getTicketKeys", SecureContext::GetTicketKeys);
336  env->SetProtoMethod(t, "setTicketKeys", SecureContext::SetTicketKeys);
337  env->SetProtoMethod(t, "setFreeListLength", SecureContext::SetFreeListLength);
338  env->SetProtoMethod(t,
339  "enableTicketKeyCallback",
340  SecureContext::EnableTicketKeyCallback);
341  env->SetProtoMethod(t, "getCertificate", SecureContext::GetCertificate<true>);
342  env->SetProtoMethod(t, "getIssuer", SecureContext::GetCertificate<false>);
343 
344  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyReturnIndex"),
345  Integer::NewFromUnsigned(env->isolate(), kTicketKeyReturnIndex));
346  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyHMACIndex"),
347  Integer::NewFromUnsigned(env->isolate(), kTicketKeyHMACIndex));
348  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyAESIndex"),
349  Integer::NewFromUnsigned(env->isolate(), kTicketKeyAESIndex));
350  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyNameIndex"),
351  Integer::NewFromUnsigned(env->isolate(), kTicketKeyNameIndex));
352  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyIVIndex"),
353  Integer::NewFromUnsigned(env->isolate(), kTicketKeyIVIndex));
354 
355  t->PrototypeTemplate()->SetAccessor(
356  FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
357  CtxGetter,
358  nullptr,
359  env->as_external(),
360  DEFAULT,
361  static_cast<PropertyAttribute>(ReadOnly | DontDelete),
362  AccessorSignature::New(env->isolate(), t));
363 
364  target->Set(secureContextString, t->GetFunction());
365  env->set_secure_context_constructor_template(t);
366 }
367 
368 
369 void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
370  Environment* env = Environment::GetCurrent(args);
371  new SecureContext(env, args.This());
372 }
373 
374 
375 void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
376  SecureContext* sc;
377  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
378  Environment* env = sc->env();
379 
380  const SSL_METHOD* method = SSLv23_method();
381 
382  if (args.Length() == 1 && args[0]->IsString()) {
383  const node::Utf8Value sslmethod(env->isolate(), args[0]);
384 
385  // Note that SSLv2 and SSLv3 are disallowed but SSLv2_method and friends
386  // are still accepted. They are OpenSSL's way of saying that all known
387  // protocols are supported unless explicitly disabled (which we do below
388  // for SSLv2 and SSLv3.)
389  if (strcmp(*sslmethod, "SSLv2_method") == 0) {
390  return env->ThrowError("SSLv2 methods disabled");
391  } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
392  return env->ThrowError("SSLv2 methods disabled");
393  } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
394  return env->ThrowError("SSLv2 methods disabled");
395  } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
396  return env->ThrowError("SSLv3 methods disabled");
397  } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
398  return env->ThrowError("SSLv3 methods disabled");
399  } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
400  return env->ThrowError("SSLv3 methods disabled");
401  } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
402  method = SSLv23_method();
403  } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
404  method = SSLv23_server_method();
405  } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
406  method = SSLv23_client_method();
407  } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
408  method = TLSv1_method();
409  } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
410  method = TLSv1_server_method();
411  } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
412  method = TLSv1_client_method();
413  } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
414  method = TLSv1_1_method();
415  } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
416  method = TLSv1_1_server_method();
417  } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
418  method = TLSv1_1_client_method();
419  } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
420  method = TLSv1_2_method();
421  } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
422  method = TLSv1_2_server_method();
423  } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
424  method = TLSv1_2_client_method();
425  } else {
426  return env->ThrowError("Unknown method");
427  }
428  }
429 
430  sc->ctx_ = SSL_CTX_new(method);
431  SSL_CTX_set_app_data(sc->ctx_, sc);
432 
433  // Disable SSLv2 in the case when method == SSLv23_method() and the
434  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
435  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
436  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
437  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv2);
438  SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv3);
439 
440  // SSL session cache configuration
441  SSL_CTX_set_session_cache_mode(sc->ctx_,
442  SSL_SESS_CACHE_SERVER |
443  SSL_SESS_CACHE_NO_INTERNAL |
444  SSL_SESS_CACHE_NO_AUTO_CLEAR);
445  SSL_CTX_sess_set_get_cb(sc->ctx_, SSLWrap<Connection>::GetSessionCallback);
446  SSL_CTX_sess_set_new_cb(sc->ctx_, SSLWrap<Connection>::NewSessionCallback);
447 }
448 
449 
450 // Takes a string or buffer and loads it into a BIO.
451 // Caller responsible for BIO_free_all-ing the returned object.
452 static BIO* LoadBIO(Environment* env, Local<Value> v) {
453  HandleScope scope(env->isolate());
454 
455  if (v->IsString()) {
456  const node::Utf8Value s(env->isolate(), v);
457  return NodeBIO::NewFixed(*s, s.length());
458  }
459 
460  if (Buffer::HasInstance(v)) {
461  return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
462  }
463 
464  return nullptr;
465 }
466 
467 
468 void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
469  Environment* env = Environment::GetCurrent(args);
470 
471  SecureContext* sc;
472  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
473 
474  unsigned int len = args.Length();
475  if (len < 1) {
476  return env->ThrowError("Private key argument is mandatory");
477  }
478 
479  if (len > 2) {
480  return env->ThrowError("Only private key and pass phrase are expected");
481  }
482 
483  if (len == 2) {
484  if (args[1]->IsUndefined() || args[1]->IsNull())
485  len = 1;
486  else
487  THROW_AND_RETURN_IF_NOT_STRING(args[1], "Pass phrase");
488  }
489 
490  BIO *bio = LoadBIO(env, args[0]);
491  if (!bio)
492  return;
493 
494  node::Utf8Value passphrase(env->isolate(), args[1]);
495 
496  EVP_PKEY* key = PEM_read_bio_PrivateKey(bio,
497  nullptr,
498  PasswordCallback,
499  len == 1 ? nullptr : *passphrase);
500 
501  if (!key) {
502  BIO_free_all(bio);
503  unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
504  if (!err) {
505  return env->ThrowError("PEM_read_bio_PrivateKey");
506  }
507  return ThrowCryptoError(env, err);
508  }
509 
510  int rv = SSL_CTX_use_PrivateKey(sc->ctx_, key);
511  EVP_PKEY_free(key);
512  BIO_free_all(bio);
513 
514  if (!rv) {
515  unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
516  if (!err)
517  return env->ThrowError("SSL_CTX_use_PrivateKey");
518  return ThrowCryptoError(env, err);
519  }
520 }
521 
522 
523 int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
524  int ret;
525 
526  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
527  X509_STORE_CTX store_ctx;
528 
529  ret = X509_STORE_CTX_init(&store_ctx, store, nullptr, nullptr);
530  if (!ret)
531  goto end;
532 
533  ret = X509_STORE_CTX_get1_issuer(issuer, &store_ctx, cert);
534  X509_STORE_CTX_cleanup(&store_ctx);
535 
536  end:
537  return ret;
538 }
539 
540 
542  X509* x,
543  STACK_OF(X509)* extra_certs,
544  X509** cert,
545  X509** issuer) {
546  CHECK_EQ(*issuer, nullptr);
547  CHECK_EQ(*cert, nullptr);
548 
549  int ret = SSL_CTX_use_certificate(ctx, x);
550 
551  if (ret) {
552  // If we could set up our certificate, now proceed to
553  // the CA certificates.
554  int r;
555 
556  SSL_CTX_clear_extra_chain_certs(ctx);
557 
558  for (int i = 0; i < sk_X509_num(extra_certs); i++) {
559  X509* ca = sk_X509_value(extra_certs, i);
560 
561  // NOTE: Increments reference count on `ca`
562  r = SSL_CTX_add1_chain_cert(ctx, ca);
563 
564  if (!r) {
565  ret = 0;
566  *issuer = nullptr;
567  goto end;
568  }
569  // Note that we must not free r if it was successfully
570  // added to the chain (while we must free the main
571  // certificate, since its reference count is increased
572  // by SSL_CTX_use_certificate).
573 
574  // Find issuer
575  if (*issuer != nullptr || X509_check_issued(ca, x) != X509_V_OK)
576  continue;
577 
578  *issuer = ca;
579  }
580  }
581 
582  // Try getting issuer from a cert store
583  if (ret) {
584  if (*issuer == nullptr) {
585  ret = SSL_CTX_get_issuer(ctx, x, issuer);
586  ret = ret < 0 ? 0 : 1;
587  // NOTE: get_cert_store doesn't increment reference count,
588  // no need to free `store`
589  } else {
590  // Increment issuer reference count
591  *issuer = X509_dup(*issuer);
592  if (*issuer == nullptr) {
593  ret = 0;
594  goto end;
595  }
596  }
597  }
598 
599  end:
600  if (ret && x != nullptr) {
601  *cert = X509_dup(x);
602  if (*cert == nullptr)
603  ret = 0;
604  }
605  return ret;
606 }
607 
608 
609 // Read a file that contains our certificate in "PEM" format,
610 // possibly followed by a sequence of CA certificates that should be
611 // sent to the peer in the Certificate message.
612 //
613 // Taken from OpenSSL - edited for style.
615  BIO* in,
616  X509** cert,
617  X509** issuer) {
618  X509* x = nullptr;
619 
620  // Just to ensure that `ERR_peek_last_error` below will return only errors
621  // that we are interested in
622  ERR_clear_error();
623 
624  x = PEM_read_bio_X509_AUX(in, nullptr, NoPasswordCallback, nullptr);
625 
626  if (x == nullptr) {
627  SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
628  return 0;
629  }
630 
631  X509* extra = nullptr;
632  int ret = 0;
633  unsigned long err = 0; // NOLINT(runtime/int)
634 
635  // Read extra certs
636  STACK_OF(X509)* extra_certs = sk_X509_new_null();
637  if (extra_certs == nullptr) {
638  SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_MALLOC_FAILURE);
639  goto done;
640  }
641 
642  while ((extra = PEM_read_bio_X509(in,
643  nullptr,
644  NoPasswordCallback,
645  nullptr))) {
646  if (sk_X509_push(extra_certs, extra))
647  continue;
648 
649  // Failure, free all certs
650  goto done;
651  }
652  extra = nullptr;
653 
654  // When the while loop ends, it's usually just EOF.
655  err = ERR_peek_last_error();
656  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
657  ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
658  ERR_clear_error();
659  } else {
660  // some real error
661  goto done;
662  }
663 
664  ret = SSL_CTX_use_certificate_chain(ctx, x, extra_certs, cert, issuer);
665  if (!ret)
666  goto done;
667 
668  done:
669  if (extra_certs != nullptr)
670  sk_X509_pop_free(extra_certs, X509_free);
671  if (extra != nullptr)
672  X509_free(extra);
673  if (x != nullptr)
674  X509_free(x);
675 
676  return ret;
677 }
678 
679 
680 void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
681  Environment* env = Environment::GetCurrent(args);
682 
683  SecureContext* sc;
684  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
685 
686  if (args.Length() != 1) {
687  return env->ThrowTypeError("Certificate argument is mandatory");
688  }
689 
690  BIO* bio = LoadBIO(env, args[0]);
691  if (!bio)
692  return;
693 
694  // Free previous certs
695  if (sc->issuer_ != nullptr) {
696  X509_free(sc->issuer_);
697  sc->issuer_ = nullptr;
698  }
699  if (sc->cert_ != nullptr) {
700  X509_free(sc->cert_);
701  sc->cert_ = nullptr;
702  }
703 
704  int rv = SSL_CTX_use_certificate_chain(sc->ctx_,
705  bio,
706  &sc->cert_,
707  &sc->issuer_);
708 
709  BIO_free_all(bio);
710 
711  if (!rv) {
712  unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
713  if (!err) {
714  return env->ThrowError("SSL_CTX_use_certificate_chain");
715  }
716  return ThrowCryptoError(env, err);
717  }
718 }
719 
720 
721 #if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(OPENSSL_IS_BORINGSSL)
722 // This section contains OpenSSL 1.1.0 functions reimplemented for OpenSSL
723 // 1.0.2 so that the following code can be written without lots of #if lines.
724 
725 static int X509_STORE_up_ref(X509_STORE* store) {
726  CRYPTO_add(&store->references, 1, CRYPTO_LOCK_X509_STORE);
727  return 1;
728 }
729 
730 static int X509_up_ref(X509* cert) {
731  CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
732  return 1;
733 }
734 #endif // OPENSSL_VERSION_NUMBER < 0x10100000L && !OPENSSL_IS_BORINGSSL
735 
736 
737 static X509_STORE* NewRootCertStore() {
738  static std::vector<X509*> root_certs_vector;
739  if (root_certs_vector.empty()) {
740  for (size_t i = 0; i < arraysize(root_certs); i++) {
741  BIO* bp = NodeBIO::NewFixed(root_certs[i], strlen(root_certs[i]));
742  X509 *x509 = PEM_read_bio_X509(bp, nullptr, NoPasswordCallback, nullptr);
743  BIO_free(bp);
744 
745  // Parse errors from the built-in roots are fatal.
746  CHECK_NE(x509, nullptr);
747 
748  root_certs_vector.push_back(x509);
749  }
750  }
751 
752  X509_STORE* store = X509_STORE_new();
753  if (ssl_openssl_cert_store) {
754  X509_STORE_set_default_paths(store);
755  } else {
756  for (X509 *cert : root_certs_vector) {
757  X509_up_ref(cert);
758  X509_STORE_add_cert(store, cert);
759  }
760  }
761 
762  return store;
763 }
764 
765 
766 void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
767  Environment* env = Environment::GetCurrent(args);
768 
769  SecureContext* sc;
770  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
771  ClearErrorOnReturn clear_error_on_return;
772 
773  if (args.Length() != 1) {
774  return env->ThrowTypeError("CA certificate argument is mandatory");
775  }
776 
777  BIO* bio = LoadBIO(env, args[0]);
778  if (!bio) {
779  return;
780  }
781 
782  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
783  while (X509* x509 =
784  PEM_read_bio_X509(bio, nullptr, NoPasswordCallback, nullptr)) {
785  if (cert_store == root_cert_store) {
786  cert_store = NewRootCertStore();
787  SSL_CTX_set_cert_store(sc->ctx_, cert_store);
788  }
789  X509_STORE_add_cert(cert_store, x509);
790  SSL_CTX_add_client_CA(sc->ctx_, x509);
791  X509_free(x509);
792  }
793 
794  BIO_free_all(bio);
795 }
796 
797 
798 void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
799  Environment* env = Environment::GetCurrent(args);
800 
801  SecureContext* sc;
802  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
803 
804  if (args.Length() != 1) {
805  return env->ThrowTypeError("CRL argument is mandatory");
806  }
807 
808  ClearErrorOnReturn clear_error_on_return;
809 
810  BIO *bio = LoadBIO(env, args[0]);
811  if (!bio)
812  return;
813 
814  X509_CRL* crl =
815  PEM_read_bio_X509_CRL(bio, nullptr, NoPasswordCallback, nullptr);
816 
817  if (crl == nullptr) {
818  BIO_free_all(bio);
819  return env->ThrowError("Failed to parse CRL");
820  }
821 
822  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
823  if (cert_store == root_cert_store) {
824  cert_store = NewRootCertStore();
825  SSL_CTX_set_cert_store(sc->ctx_, cert_store);
826  }
827 
828  X509_STORE_add_crl(cert_store, crl);
829  X509_STORE_set_flags(cert_store,
830  X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
831 
832  BIO_free_all(bio);
833  X509_CRL_free(crl);
834 }
835 
836 
837 void UseExtraCaCerts(const std::string& file) {
838  extra_root_certs_file = file;
839 }
840 
841 
842 static unsigned long AddCertsFromFile( // NOLINT(runtime/int)
843  X509_STORE* store,
844  const char* file) {
845  ERR_clear_error();
846  MarkPopErrorOnReturn mark_pop_error_on_return;
847 
848  BIO* bio = BIO_new_file(file, "r");
849  if (!bio) {
850  return ERR_get_error();
851  }
852 
853  while (X509* x509 =
854  PEM_read_bio_X509(bio, nullptr, NoPasswordCallback, nullptr)) {
855  X509_STORE_add_cert(store, x509);
856  X509_free(x509);
857  }
858  BIO_free_all(bio);
859 
860  unsigned long err = ERR_peek_error(); // NOLINT(runtime/int)
861  // Ignore error if its EOF/no start line found.
862  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
863  ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
864  return 0;
865  }
866 
867  return err;
868 }
869 
870 void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
871  SecureContext* sc;
872  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
873  ClearErrorOnReturn clear_error_on_return;
874 
875  if (!root_cert_store) {
876  root_cert_store = NewRootCertStore();
877 
878  if (!extra_root_certs_file.empty()) {
879  unsigned long err = AddCertsFromFile( // NOLINT(runtime/int)
880  root_cert_store,
881  extra_root_certs_file.c_str());
882  if (err) {
883  ProcessEmitWarning(sc->env(),
884  "Ignoring extra certs from `%s`, load failed: %s\n",
885  extra_root_certs_file.c_str(),
886  ERR_error_string(err, nullptr));
887  }
888  }
889  }
890 
891  // Increment reference count so global store is not deleted along with CTX.
892  X509_STORE_up_ref(root_cert_store);
893  SSL_CTX_set_cert_store(sc->ctx_, root_cert_store);
894 }
895 
896 
897 void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
898  SecureContext* sc;
899  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
900  Environment* env = sc->env();
901  ClearErrorOnReturn clear_error_on_return;
902 
903  if (args.Length() != 1) {
904  return env->ThrowTypeError("Ciphers argument is mandatory");
905  }
906 
907  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Ciphers");
908 
909  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
910  SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
911 }
912 
913 
914 void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
915  SecureContext* sc;
916  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
917  Environment* env = sc->env();
918 
919  if (args.Length() != 1)
920  return env->ThrowTypeError("ECDH curve name argument is mandatory");
921 
922  THROW_AND_RETURN_IF_NOT_STRING(args[0], "ECDH curve name");
923 
924  node::Utf8Value curve(env->isolate(), args[0]);
925 
926  int nid = OBJ_sn2nid(*curve);
927 
928  if (nid == NID_undef)
929  return env->ThrowTypeError("First argument should be a valid curve name");
930 
931  EC_KEY* ecdh = EC_KEY_new_by_curve_name(nid);
932 
933  if (ecdh == nullptr)
934  return env->ThrowTypeError("First argument should be a valid curve name");
935 
936  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_ECDH_USE);
937  SSL_CTX_set_tmp_ecdh(sc->ctx_, ecdh);
938 
939  EC_KEY_free(ecdh);
940 }
941 
942 
943 void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
944  SecureContext* sc;
945  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
946  Environment* env = sc->env();
947  ClearErrorOnReturn clear_error_on_return;
948 
949  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
950  // to be specified explicitly
951  if (args.Length() != 1)
952  return env->ThrowTypeError("DH argument is mandatory");
953 
954  // Invalid dhparam is silently discarded and DHE is no longer used.
955  BIO* bio = LoadBIO(env, args[0]);
956  if (!bio)
957  return;
958 
959  DH* dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
960  BIO_free_all(bio);
961 
962  if (dh == nullptr)
963  return;
964 
965  const int size = BN_num_bits(dh->p);
966  if (size < 1024) {
967  return env->ThrowError("DH parameter is less than 1024 bits");
968  } else if (size < 2048) {
969  args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
970  env->isolate(), "DH parameter is less than 2048 bits"));
971  }
972 
973  SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE);
974  int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh);
975  DH_free(dh);
976 
977  if (!r)
978  return env->ThrowTypeError("Error setting temp DH parameter");
979 }
980 
981 
982 void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
983  SecureContext* sc;
984  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
985 
986  if (args.Length() != 1 || !args[0]->IntegerValue()) {
987  return sc->env()->ThrowTypeError("Options must be an integer value");
988  }
989 
990  SSL_CTX_set_options(
991  sc->ctx_,
992  static_cast<long>(args[0]->IntegerValue())); // NOLINT(runtime/int)
993 }
994 
995 
996 void SecureContext::SetSessionIdContext(
997  const FunctionCallbackInfo<Value>& args) {
998  SecureContext* sc;
999  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1000  Environment* env = sc->env();
1001 
1002  if (args.Length() != 1) {
1003  return env->ThrowTypeError("Session ID context argument is mandatory");
1004  }
1005 
1006  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Session ID context");
1007 
1008  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1009  const unsigned char* sid_ctx =
1010  reinterpret_cast<const unsigned char*>(*sessionIdContext);
1011  unsigned int sid_ctx_len = sessionIdContext.length();
1012 
1013  int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
1014  if (r == 1)
1015  return;
1016 
1017  BIO* bio;
1018  BUF_MEM* mem;
1019  Local<String> message;
1020 
1021  bio = BIO_new(BIO_s_mem());
1022  if (bio == nullptr) {
1023  message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1024  "SSL_CTX_set_session_id_context error");
1025  } else {
1026  ERR_print_errors(bio);
1027  BIO_get_mem_ptr(bio, &mem);
1028  message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1029  BIO_free_all(bio);
1030  }
1031 
1032  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1033 }
1034 
1035 
1036 void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1037  SecureContext* sc;
1038  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1039 
1040  if (args.Length() != 1 || !args[0]->IsInt32()) {
1041  return sc->env()->ThrowTypeError(
1042  "Session timeout must be a 32-bit integer");
1043  }
1044 
1045  int32_t sessionTimeout = args[0]->Int32Value();
1046  SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
1047 }
1048 
1049 
1050 void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1051  SecureContext* sc;
1052  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1053  sc->FreeCTXMem();
1054 }
1055 
1056 
1057 // Takes .pfx or .p12 and password in string or buffer format
1058 void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1059  Environment* env = Environment::GetCurrent(args);
1060 
1061  BIO* in = nullptr;
1062  PKCS12* p12 = nullptr;
1063  EVP_PKEY* pkey = nullptr;
1064  X509* cert = nullptr;
1065  STACK_OF(X509)* extra_certs = nullptr;
1066  char* pass = nullptr;
1067  bool ret = false;
1068 
1069  SecureContext* sc;
1070  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1071  ClearErrorOnReturn clear_error_on_return;
1072 
1073  if (args.Length() < 1) {
1074  return env->ThrowTypeError("PFX certificate argument is mandatory");
1075  }
1076 
1077  in = LoadBIO(env, args[0]);
1078  if (in == nullptr) {
1079  return env->ThrowError("Unable to load BIO");
1080  }
1081 
1082  if (args.Length() >= 2) {
1083  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Pass phrase");
1084  size_t passlen = Buffer::Length(args[1]);
1085  pass = new char[passlen + 1];
1086  memcpy(pass, Buffer::Data(args[1]), passlen);
1087  pass[passlen] = '\0';
1088  }
1089 
1090  // Free previous certs
1091  if (sc->issuer_ != nullptr) {
1092  X509_free(sc->issuer_);
1093  sc->issuer_ = nullptr;
1094  }
1095  if (sc->cert_ != nullptr) {
1096  X509_free(sc->cert_);
1097  sc->cert_ = nullptr;
1098  }
1099 
1100  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_);
1101 
1102  if (d2i_PKCS12_bio(in, &p12) &&
1103  PKCS12_parse(p12, pass, &pkey, &cert, &extra_certs) &&
1105  cert,
1106  extra_certs,
1107  &sc->cert_,
1108  &sc->issuer_) &&
1109  SSL_CTX_use_PrivateKey(sc->ctx_, pkey)) {
1110  // Add CA certs too
1111  for (int i = 0; i < sk_X509_num(extra_certs); i++) {
1112  X509* ca = sk_X509_value(extra_certs, i);
1113 
1114  if (cert_store == root_cert_store) {
1115  cert_store = NewRootCertStore();
1116  SSL_CTX_set_cert_store(sc->ctx_, cert_store);
1117  }
1118  X509_STORE_add_cert(cert_store, ca);
1119  SSL_CTX_add_client_CA(sc->ctx_, ca);
1120  }
1121  ret = true;
1122  }
1123 
1124  if (pkey != nullptr)
1125  EVP_PKEY_free(pkey);
1126  if (cert != nullptr)
1127  X509_free(cert);
1128  if (extra_certs != nullptr)
1129  sk_X509_pop_free(extra_certs, X509_free);
1130 
1131  PKCS12_free(p12);
1132  BIO_free_all(in);
1133  delete[] pass;
1134 
1135  if (!ret) {
1136  unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
1137  const char* str = ERR_reason_error_string(err);
1138  return env->ThrowError(str);
1139  }
1140 }
1141 
1142 
1143 void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1144 #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1145 
1146  SecureContext* wrap;
1147  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1148 
1149  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1150  if (SSL_CTX_get_tlsext_ticket_keys(wrap->ctx_,
1151  Buffer::Data(buff),
1152  Buffer::Length(buff)) != 1) {
1153  return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
1154  }
1155 
1156  args.GetReturnValue().Set(buff);
1157 #endif // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1158 }
1159 
1160 
1161 void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1162 #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1163  SecureContext* wrap;
1164  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1165  Environment* env = wrap->env();
1166 
1167  if (args.Length() < 1) {
1168  return env->ThrowTypeError("Ticket keys argument is mandatory");
1169  }
1170 
1171  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Ticket keys");
1172 
1173  if (Buffer::Length(args[0]) != 48) {
1174  return env->ThrowTypeError("Ticket keys length must be 48 bytes");
1175  }
1176 
1177  if (SSL_CTX_set_tlsext_ticket_keys(wrap->ctx_,
1178  Buffer::Data(args[0]),
1179  Buffer::Length(args[0])) != 1) {
1180  return env->ThrowError("Failed to fetch tls ticket keys");
1181  }
1182 
1183  args.GetReturnValue().Set(true);
1184 #endif // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1185 }
1186 
1187 
1188 void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1189 #if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(OPENSSL_IS_BORINGSSL)
1190  // |freelist_max_len| was removed in OpenSSL 1.1.0. In that version OpenSSL
1191  // mallocs and frees buffers directly, without the use of a freelist.
1192  SecureContext* wrap;
1193  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1194 
1195  wrap->ctx_->freelist_max_len = args[0]->Int32Value();
1196 #endif
1197 }
1198 
1199 
1200 // Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1201 // the regression test in test/parallel/test-https-resume-after-renew.js.
1202 void SecureContext::EnableTicketKeyCallback(
1203  const FunctionCallbackInfo<Value>& args) {
1204  SecureContext* wrap;
1205  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1206 
1207  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_, TicketKeyCallback);
1208 }
1209 
1210 
1211 int SecureContext::TicketKeyCallback(SSL* ssl,
1212  unsigned char* name,
1213  unsigned char* iv,
1214  EVP_CIPHER_CTX* ectx,
1215  HMAC_CTX* hctx,
1216  int enc) {
1217  static const int kTicketPartSize = 16;
1218 
1219  SecureContext* sc = static_cast<SecureContext*>(
1220  SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1221 
1222  Environment* env = sc->env();
1223  HandleScope handle_scope(env->isolate());
1224  Context::Scope context_scope(env->context());
1225 
1226  Local<Value> argv[] = {
1227  Buffer::Copy(env,
1228  reinterpret_cast<char*>(name),
1229  kTicketPartSize).ToLocalChecked(),
1230  Buffer::Copy(env,
1231  reinterpret_cast<char*>(iv),
1232  kTicketPartSize).ToLocalChecked(),
1233  Boolean::New(env->isolate(), enc != 0)
1234  };
1235 
1236  Local<Value> ret = node::MakeCallback(env->isolate(),
1237  sc->object(),
1238  env->ticketkeycallback_string(),
1239  arraysize(argv),
1240  argv,
1241  {0, 0}).ToLocalChecked();
1242  Local<Array> arr = ret.As<Array>();
1243 
1244  int r = arr->Get(kTicketKeyReturnIndex)->Int32Value();
1245  if (r < 0)
1246  return r;
1247 
1248  Local<Value> hmac = arr->Get(kTicketKeyHMACIndex);
1249  Local<Value> aes = arr->Get(kTicketKeyAESIndex);
1250  if (Buffer::Length(aes) != kTicketPartSize)
1251  return -1;
1252 
1253  if (enc) {
1254  Local<Value> name_val = arr->Get(kTicketKeyNameIndex);
1255  Local<Value> iv_val = arr->Get(kTicketKeyIVIndex);
1256 
1257  if (Buffer::Length(name_val) != kTicketPartSize ||
1258  Buffer::Length(iv_val) != kTicketPartSize) {
1259  return -1;
1260  }
1261 
1262  memcpy(name, Buffer::Data(name_val), kTicketPartSize);
1263  memcpy(iv, Buffer::Data(iv_val), kTicketPartSize);
1264  }
1265 
1266  HMAC_Init_ex(hctx,
1267  Buffer::Data(hmac),
1268  Buffer::Length(hmac),
1269  EVP_sha256(),
1270  nullptr);
1271 
1272  const unsigned char* aes_key =
1273  reinterpret_cast<unsigned char*>(Buffer::Data(aes));
1274  if (enc) {
1275  EVP_EncryptInit_ex(ectx,
1276  EVP_aes_128_cbc(),
1277  nullptr,
1278  aes_key,
1279  iv);
1280  } else {
1281  EVP_DecryptInit_ex(ectx,
1282  EVP_aes_128_cbc(),
1283  nullptr,
1284  aes_key,
1285  iv);
1286  }
1287 
1288  return r;
1289 }
1290 
1291 
1292 
1293 
1294 void SecureContext::CtxGetter(Local<String> property,
1295  const PropertyCallbackInfo<Value>& info) {
1296  SecureContext* sc;
1297  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1298  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_);
1299  info.GetReturnValue().Set(ext);
1300 }
1301 
1302 
1303 template <bool primary>
1304 void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1305  SecureContext* wrap;
1306  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1307  Environment* env = wrap->env();
1308  X509* cert;
1309 
1310  if (primary)
1311  cert = wrap->cert_;
1312  else
1313  cert = wrap->issuer_;
1314  if (cert == nullptr)
1315  return args.GetReturnValue().Set(Null(env->isolate()));
1316 
1317  int size = i2d_X509(cert, nullptr);
1318  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1319  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1320  Buffer::Data(buff));
1321  i2d_X509(cert, &serialized);
1322 
1323  args.GetReturnValue().Set(buff);
1324 }
1325 
1326 
1327 template <class Base>
1328 void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1329  HandleScope scope(env->isolate());
1330 
1331  env->SetProtoMethod(t, "getPeerCertificate", GetPeerCertificate);
1332  env->SetProtoMethod(t, "getSession", GetSession);
1333  env->SetProtoMethod(t, "setSession", SetSession);
1334  env->SetProtoMethod(t, "loadSession", LoadSession);
1335  env->SetProtoMethod(t, "isSessionReused", IsSessionReused);
1336  env->SetProtoMethod(t, "isInitFinished", IsInitFinished);
1337  env->SetProtoMethod(t, "verifyError", VerifyError);
1338  env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
1339  env->SetProtoMethod(t, "endParser", EndParser);
1340  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1341  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1342  env->SetProtoMethod(t, "shutdownSSL", Shutdown);
1343  env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket);
1344  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1345  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1346  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1347  env->SetProtoMethod(t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
1348  env->SetProtoMethod(t, "getProtocol", GetProtocol);
1349 
1350 #ifdef SSL_set_max_send_fragment
1351  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1352 #endif // SSL_set_max_send_fragment
1353 
1354 #ifndef OPENSSL_NO_NEXTPROTONEG
1355  env->SetProtoMethod(t, "getNegotiatedProtocol", GetNegotiatedProto);
1356 #endif // OPENSSL_NO_NEXTPROTONEG
1357 
1358 #ifndef OPENSSL_NO_NEXTPROTONEG
1359  env->SetProtoMethod(t, "setNPNProtocols", SetNPNProtocols);
1360 #endif
1361 
1362  env->SetProtoMethod(t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
1363  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1364 
1365  t->PrototypeTemplate()->SetAccessor(
1366  FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
1367  SSLGetter,
1368  nullptr,
1369  env->as_external(),
1370  DEFAULT,
1371  static_cast<PropertyAttribute>(ReadOnly | DontDelete),
1372  AccessorSignature::New(env->isolate(), t));
1373 }
1374 
1375 
1376 template <class Base>
1377 void SSLWrap<Base>::InitNPN(SecureContext* sc) {
1378 #ifndef OPENSSL_NO_NEXTPROTONEG
1379  // Server should advertise NPN protocols
1380  SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
1381  AdvertiseNextProtoCallback,
1382  nullptr);
1383  // Client should select protocol from list of advertised
1384  // If server supports NPN
1385  SSL_CTX_set_next_proto_select_cb(sc->ctx_, SelectNextProtoCallback, nullptr);
1386 #endif // OPENSSL_NO_NEXTPROTONEG
1387 
1388 #ifdef NODE__HAVE_TLSEXT_STATUS_CB
1389  // OCSP stapling
1390  SSL_CTX_set_tlsext_status_cb(sc->ctx_, TLSExtStatusCallback);
1391  SSL_CTX_set_tlsext_status_arg(sc->ctx_, nullptr);
1392 #endif // NODE__HAVE_TLSEXT_STATUS_CB
1393 }
1394 
1395 
1396 template <class Base>
1397 SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1398  unsigned char* key,
1399  int len,
1400  int* copy) {
1401  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1402 
1403  *copy = 0;
1404  SSL_SESSION* sess = w->next_sess_;
1405  w->next_sess_ = nullptr;
1406 
1407  return sess;
1408 }
1409 
1410 
1411 template <class Base>
1412 int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1413  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1414  Environment* env = w->ssl_env();
1415  HandleScope handle_scope(env->isolate());
1416  Context::Scope context_scope(env->context());
1417 
1418  if (!w->session_callbacks_)
1419  return 0;
1420 
1421  // Check if session is small enough to be stored
1422  int size = i2d_SSL_SESSION(sess, nullptr);
1423  if (size > SecureContext::kMaxSessionSize)
1424  return 0;
1425 
1426  // Serialize session
1427  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1428  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1429  Buffer::Data(buff));
1430  memset(serialized, 0, size);
1431  i2d_SSL_SESSION(sess, &serialized);
1432 
1433  Local<Object> session = Buffer::Copy(
1434  env,
1435  reinterpret_cast<char*>(sess->session_id),
1436  sess->session_id_length).ToLocalChecked();
1437  Local<Value> argv[] = { session, buff };
1438  w->new_session_wait_ = true;
1439  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1440 
1441  return 0;
1442 }
1443 
1444 
1445 template <class Base>
1446 void SSLWrap<Base>::OnClientHello(void* arg,
1447  const ClientHelloParser::ClientHello& hello) {
1448  Base* w = static_cast<Base*>(arg);
1449  Environment* env = w->ssl_env();
1450  HandleScope handle_scope(env->isolate());
1451  Context::Scope context_scope(env->context());
1452 
1453  Local<Object> hello_obj = Object::New(env->isolate());
1454  Local<Object> buff = Buffer::Copy(
1455  env,
1456  reinterpret_cast<const char*>(hello.session_id()),
1457  hello.session_size()).ToLocalChecked();
1458  hello_obj->Set(env->session_id_string(), buff);
1459  if (hello.servername() == nullptr) {
1460  hello_obj->Set(env->servername_string(), String::Empty(env->isolate()));
1461  } else {
1462  Local<String> servername = OneByteString(env->isolate(),
1463  hello.servername(),
1464  hello.servername_size());
1465  hello_obj->Set(env->servername_string(), servername);
1466  }
1467  hello_obj->Set(env->tls_ticket_string(),
1468  Boolean::New(env->isolate(), hello.has_ticket()));
1469  hello_obj->Set(env->ocsp_request_string(),
1470  Boolean::New(env->isolate(), hello.ocsp_request()));
1471 
1472  Local<Value> argv[] = { hello_obj };
1473  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1474 }
1475 
1476 
1477 static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) {
1478  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
1479 
1480  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
1481  return false;
1482 
1483  const unsigned char* p = ext->value->data;
1484  GENERAL_NAMES* names = reinterpret_cast<GENERAL_NAMES*>(ASN1_item_d2i(
1485  NULL,
1486  &p,
1487  ext->value->length,
1488  ASN1_ITEM_ptr(method->it)));
1489  if (names == NULL)
1490  return false;
1491 
1492  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1493  GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
1494 
1495  if (i != 0)
1496  BIO_write(out, ", ", 2);
1497 
1498  if (gen->type == GEN_DNS) {
1499  ASN1_IA5STRING* name = gen->d.dNSName;
1500 
1501  BIO_write(out, "DNS:", 4);
1502  BIO_write(out, name->data, name->length);
1503  } else {
1504  STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
1505  const_cast<X509V3_EXT_METHOD*>(method), gen, NULL);
1506  if (nval == NULL)
1507  return false;
1508  X509V3_EXT_val_prn(out, nval, 0, 0);
1509  sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
1510  }
1511  }
1512  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1513 
1514  return true;
1515 }
1516 
1517 
1518 static Local<Object> X509ToObject(Environment* env, X509* cert) {
1519  EscapableHandleScope scope(env->isolate());
1520 
1521  Local<Object> info = Object::New(env->isolate());
1522 
1523  BIO* bio = BIO_new(BIO_s_mem());
1524  BUF_MEM* mem;
1525  if (X509_NAME_print_ex(bio,
1526  X509_get_subject_name(cert),
1527  0,
1528  X509_NAME_FLAGS) > 0) {
1529  BIO_get_mem_ptr(bio, &mem);
1530  info->Set(env->subject_string(),
1531  String::NewFromUtf8(env->isolate(), mem->data,
1532  String::kNormalString, mem->length));
1533  }
1534  (void) BIO_reset(bio);
1535 
1536  X509_NAME* issuer_name = X509_get_issuer_name(cert);
1537  if (X509_NAME_print_ex(bio, issuer_name, 0, X509_NAME_FLAGS) > 0) {
1538  BIO_get_mem_ptr(bio, &mem);
1539  info->Set(env->issuer_string(),
1540  String::NewFromUtf8(env->isolate(), mem->data,
1541  String::kNormalString, mem->length));
1542  }
1543  (void) BIO_reset(bio);
1544 
1545  int nids[] = { NID_subject_alt_name, NID_info_access };
1546  Local<String> keys[] = { env->subjectaltname_string(),
1547  env->infoaccess_string() };
1548  CHECK_EQ(arraysize(nids), arraysize(keys));
1549  for (size_t i = 0; i < arraysize(nids); i++) {
1550  int index = X509_get_ext_by_NID(cert, nids[i], -1);
1551  if (index < 0)
1552  continue;
1553 
1554  X509_EXTENSION* ext;
1555  int rv;
1556 
1557  ext = X509_get_ext(cert, index);
1558  CHECK_NE(ext, nullptr);
1559 
1560  if (!SafeX509ExtPrint(bio, ext)) {
1561  rv = X509V3_EXT_print(bio, ext, 0, 0);
1562  CHECK_EQ(rv, 1);
1563  }
1564 
1565  BIO_get_mem_ptr(bio, &mem);
1566  info->Set(keys[i],
1567  String::NewFromUtf8(env->isolate(), mem->data,
1568  String::kNormalString, mem->length));
1569 
1570  (void) BIO_reset(bio);
1571  }
1572 
1573  EVP_PKEY* pkey = X509_get_pubkey(cert);
1574  RSA* rsa = nullptr;
1575  if (pkey != nullptr)
1576  rsa = EVP_PKEY_get1_RSA(pkey);
1577 
1578  if (rsa != nullptr) {
1579  BN_print(bio, rsa->n);
1580  BIO_get_mem_ptr(bio, &mem);
1581  info->Set(env->modulus_string(),
1582  String::NewFromUtf8(env->isolate(), mem->data,
1583  String::kNormalString, mem->length));
1584  (void) BIO_reset(bio);
1585 
1586  uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(rsa->e));
1587  uint32_t lo = static_cast<uint32_t>(exponent_word);
1588  uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
1589  if (hi == 0) {
1590  BIO_printf(bio, "0x%x", lo);
1591  } else {
1592  BIO_printf(bio, "0x%x%08x", hi, lo);
1593  }
1594  BIO_get_mem_ptr(bio, &mem);
1595  info->Set(env->exponent_string(),
1596  String::NewFromUtf8(env->isolate(), mem->data,
1597  String::kNormalString, mem->length));
1598  (void) BIO_reset(bio);
1599  }
1600 
1601  if (pkey != nullptr) {
1602  EVP_PKEY_free(pkey);
1603  pkey = nullptr;
1604  }
1605  if (rsa != nullptr) {
1606  RSA_free(rsa);
1607  rsa = nullptr;
1608  }
1609 
1610  ASN1_TIME_print(bio, X509_get_notBefore(cert));
1611  BIO_get_mem_ptr(bio, &mem);
1612  info->Set(env->valid_from_string(),
1613  String::NewFromUtf8(env->isolate(), mem->data,
1614  String::kNormalString, mem->length));
1615  (void) BIO_reset(bio);
1616 
1617  ASN1_TIME_print(bio, X509_get_notAfter(cert));
1618  BIO_get_mem_ptr(bio, &mem);
1619  info->Set(env->valid_to_string(),
1620  String::NewFromUtf8(env->isolate(), mem->data,
1621  String::kNormalString, mem->length));
1622  BIO_free_all(bio);
1623 
1624  unsigned int md_size, i;
1625  unsigned char md[EVP_MAX_MD_SIZE];
1626  if (X509_digest(cert, EVP_sha1(), md, &md_size)) {
1627  const char hex[] = "0123456789ABCDEF";
1628  char fingerprint[EVP_MAX_MD_SIZE * 3];
1629 
1630  // TODO(indutny): Unify it with buffer's code
1631  for (i = 0; i < md_size; i++) {
1632  fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1633  fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1634  fingerprint[(3*i)+2] = ':';
1635  }
1636 
1637  if (md_size > 0) {
1638  fingerprint[(3*(md_size-1))+2] = '\0';
1639  } else {
1640  fingerprint[0] = '\0';
1641  }
1642 
1643  info->Set(env->fingerprint_string(),
1644  OneByteString(env->isolate(), fingerprint));
1645  }
1646 
1647  STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
1648  X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr));
1649  if (eku != nullptr) {
1650  Local<Array> ext_key_usage = Array::New(env->isolate());
1651  char buf[256];
1652 
1653  int j = 0;
1654  for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1655  if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku, i), 1) >= 0)
1656  ext_key_usage->Set(j++, OneByteString(env->isolate(), buf));
1657  }
1658 
1659  sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1660  info->Set(env->ext_key_usage_string(), ext_key_usage);
1661  }
1662 
1663  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
1664  if (BIGNUM* bn = ASN1_INTEGER_to_BN(serial_number, nullptr)) {
1665  if (char* buf = BN_bn2hex(bn)) {
1666  info->Set(env->serial_number_string(),
1667  OneByteString(env->isolate(), buf));
1668  OPENSSL_free(buf);
1669  }
1670  BN_free(bn);
1671  }
1672  }
1673 
1674  // Raw DER certificate
1675  int size = i2d_X509(cert, nullptr);
1676  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1677  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1678  Buffer::Data(buff));
1679  i2d_X509(cert, &serialized);
1680  info->Set(env->raw_string(), buff);
1681 
1682  return scope.Escape(info);
1683 }
1684 
1685 
1686 // TODO(indutny): Split it into multiple smaller functions
1687 template <class Base>
1688 void SSLWrap<Base>::GetPeerCertificate(
1689  const FunctionCallbackInfo<Value>& args) {
1690  Base* w;
1691  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1692  Environment* env = w->ssl_env();
1693 
1694  ClearErrorOnReturn clear_error_on_return;
1695 
1696  Local<Object> result;
1697  Local<Object> info;
1698 
1699  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1700  // contains the `peer_certificate`, but on server it doesn't
1701  X509* cert = w->is_server() ? SSL_get_peer_certificate(w->ssl_) : nullptr;
1702  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_);
1703  STACK_OF(X509)* peer_certs = nullptr;
1704  if (cert == nullptr && ssl_certs == nullptr)
1705  goto done;
1706 
1707  if (cert == nullptr && sk_X509_num(ssl_certs) == 0)
1708  goto done;
1709 
1710  // Short result requested
1711  if (args.Length() < 1 || !args[0]->IsTrue()) {
1712  result = X509ToObject(env,
1713  cert == nullptr ? sk_X509_value(ssl_certs, 0) : cert);
1714  goto done;
1715  }
1716 
1717  // Clone `ssl_certs`, because we are going to destruct it
1718  peer_certs = sk_X509_new(nullptr);
1719  if (cert != nullptr)
1720  sk_X509_push(peer_certs, cert);
1721  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
1722  cert = X509_dup(sk_X509_value(ssl_certs, i));
1723  if (cert == nullptr)
1724  goto done;
1725  if (!sk_X509_push(peer_certs, cert))
1726  goto done;
1727  }
1728 
1729  // First and main certificate
1730  cert = sk_X509_value(peer_certs, 0);
1731  result = X509ToObject(env, cert);
1732  info = result;
1733 
1734  // Put issuer inside the object
1735  cert = sk_X509_delete(peer_certs, 0);
1736  while (sk_X509_num(peer_certs) > 0) {
1737  int i;
1738  for (i = 0; i < sk_X509_num(peer_certs); i++) {
1739  X509* ca = sk_X509_value(peer_certs, i);
1740  if (X509_check_issued(ca, cert) != X509_V_OK)
1741  continue;
1742 
1743  Local<Object> ca_info = X509ToObject(env, ca);
1744  info->Set(env->issuercert_string(), ca_info);
1745  info = ca_info;
1746 
1747  // NOTE: Intentionally freeing cert that is not used anymore
1748  X509_free(cert);
1749 
1750  // Delete cert and continue aggregating issuers
1751  cert = sk_X509_delete(peer_certs, i);
1752  break;
1753  }
1754 
1755  // Issuer not found, break out of the loop
1756  if (i == sk_X509_num(peer_certs))
1757  break;
1758  }
1759 
1760  // Last certificate should be self-signed
1761  while (X509_check_issued(cert, cert) != X509_V_OK) {
1762  X509* ca;
1763  if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(w->ssl_), cert, &ca) <= 0)
1764  break;
1765 
1766  Local<Object> ca_info = X509ToObject(env, ca);
1767  info->Set(env->issuercert_string(), ca_info);
1768  info = ca_info;
1769 
1770  // NOTE: Intentionally freeing cert that is not used anymore
1771  X509_free(cert);
1772 
1773  // Delete cert and continue aggregating issuers
1774  cert = ca;
1775  }
1776 
1777  // Self-issued certificate
1778  if (X509_check_issued(cert, cert) == X509_V_OK)
1779  info->Set(env->issuercert_string(), info);
1780 
1781  CHECK_NE(cert, nullptr);
1782 
1783  done:
1784  if (cert != nullptr)
1785  X509_free(cert);
1786  if (peer_certs != nullptr)
1787  sk_X509_pop_free(peer_certs, X509_free);
1788  if (result.IsEmpty())
1789  result = Object::New(env->isolate());
1790  args.GetReturnValue().Set(result);
1791 }
1792 
1793 
1794 template <class Base>
1795 void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1796  Environment* env = Environment::GetCurrent(args);
1797 
1798  Base* w;
1799  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1800 
1801  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1802  if (sess == nullptr)
1803  return;
1804 
1805  int slen = i2d_SSL_SESSION(sess, nullptr);
1806  CHECK_GT(slen, 0);
1807 
1808  char* sbuf = Malloc(slen);
1809  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1810  i2d_SSL_SESSION(sess, &p);
1811  args.GetReturnValue().Set(Buffer::New(env, sbuf, slen).ToLocalChecked());
1812 }
1813 
1814 
1815 template <class Base>
1816 void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1817  Environment* env = Environment::GetCurrent(args);
1818 
1819  Base* w;
1820  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1821 
1822  if (args.Length() < 1) {
1823  return env->ThrowError("Session argument is mandatory");
1824  }
1825 
1826  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Session");
1827  size_t slen = Buffer::Length(args[0]);
1828  char* sbuf = new char[slen];
1829  memcpy(sbuf, Buffer::Data(args[0]), slen);
1830 
1831  const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1832  SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1833 
1834  delete[] sbuf;
1835 
1836  if (sess == nullptr)
1837  return;
1838 
1839  int r = SSL_set_session(w->ssl_, sess);
1840  SSL_SESSION_free(sess);
1841 
1842  if (!r)
1843  return env->ThrowError("SSL_set_session error");
1844 }
1845 
1846 
1847 template <class Base>
1848 void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1849  Base* w;
1850  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1851 
1852  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1853  ssize_t slen = Buffer::Length(args[0]);
1854  char* sbuf = Buffer::Data(args[0]);
1855 
1856  const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1857  SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, slen);
1858 
1859  // Setup next session and move hello to the BIO buffer
1860  if (w->next_sess_ != nullptr)
1861  SSL_SESSION_free(w->next_sess_);
1862  w->next_sess_ = sess;
1863  }
1864 }
1865 
1866 
1867 template <class Base>
1868 void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1869  Base* w;
1870  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1871  bool yes = SSL_session_reused(w->ssl_);
1872  args.GetReturnValue().Set(yes);
1873 }
1874 
1875 
1876 template <class Base>
1877 void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
1878  Base* w;
1879  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1880  w->hello_parser_.End();
1881 }
1882 
1883 
1884 template <class Base>
1885 void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1886  Base* w;
1887  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1888 
1889  ClearErrorOnReturn clear_error_on_return;
1890 
1891  bool yes = SSL_renegotiate(w->ssl_) == 1;
1892  args.GetReturnValue().Set(yes);
1893 }
1894 
1895 
1896 template <class Base>
1897 void SSLWrap<Base>::Shutdown(const FunctionCallbackInfo<Value>& args) {
1898  Base* w;
1899  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1900 
1901  int rv = SSL_shutdown(w->ssl_);
1902  args.GetReturnValue().Set(rv);
1903 }
1904 
1905 
1906 template <class Base>
1907 void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1908  Base* w;
1909  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1910  Environment* env = w->ssl_env();
1911 
1912  SSL_SESSION* sess = SSL_get_session(w->ssl_);
1913  if (sess == nullptr || sess->tlsext_tick == nullptr)
1914  return;
1915 
1916  Local<Object> buff = Buffer::Copy(
1917  env,
1918  reinterpret_cast<char*>(sess->tlsext_tick),
1919  sess->tlsext_ticklen).ToLocalChecked();
1920 
1921  args.GetReturnValue().Set(buff);
1922 }
1923 
1924 
1925 template <class Base>
1926 void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1927  Base* w;
1928  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1929  w->new_session_wait_ = false;
1930  w->NewSessionDoneCb();
1931 }
1932 
1933 
1934 template <class Base>
1935 void SSLWrap<Base>::SetOCSPResponse(
1936  const v8::FunctionCallbackInfo<v8::Value>& args) {
1937 #ifdef NODE__HAVE_TLSEXT_STATUS_CB
1938  Base* w;
1939  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1940  Environment* env = w->env();
1941 
1942  if (args.Length() < 1)
1943  return env->ThrowTypeError("OCSP response argument is mandatory");
1944 
1945  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "OCSP response");
1946 
1947  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<Object>());
1948 #endif // NODE__HAVE_TLSEXT_STATUS_CB
1949 }
1950 
1951 
1952 template <class Base>
1953 void SSLWrap<Base>::RequestOCSP(
1954  const v8::FunctionCallbackInfo<v8::Value>& args) {
1955 #ifdef NODE__HAVE_TLSEXT_STATUS_CB
1956  Base* w;
1957  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1958 
1959  SSL_set_tlsext_status_type(w->ssl_, TLSEXT_STATUSTYPE_ocsp);
1960 #endif // NODE__HAVE_TLSEXT_STATUS_CB
1961 }
1962 
1963 
1964 template <class Base>
1965 void SSLWrap<Base>::GetEphemeralKeyInfo(
1966  const v8::FunctionCallbackInfo<v8::Value>& args) {
1967  Base* w;
1968  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1969  Environment* env = Environment::GetCurrent(args);
1970 
1971  CHECK_NE(w->ssl_, nullptr);
1972 
1973  // tmp key is available on only client
1974  if (w->is_server())
1975  return args.GetReturnValue().SetNull();
1976 
1977  Local<Object> info = Object::New(env->isolate());
1978 
1979  EVP_PKEY* key;
1980 
1981  if (SSL_get_server_tmp_key(w->ssl_, &key)) {
1982  switch (EVP_PKEY_id(key)) {
1983  case EVP_PKEY_DH:
1984  info->Set(env->type_string(),
1985  FIXED_ONE_BYTE_STRING(env->isolate(), "DH"));
1986  info->Set(env->size_string(),
1987  Integer::New(env->isolate(), EVP_PKEY_bits(key)));
1988  break;
1989  case EVP_PKEY_EC:
1990  {
1991  EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
1992  int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
1993  EC_KEY_free(ec);
1994  info->Set(env->type_string(),
1995  FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"));
1996  info->Set(env->name_string(),
1997  OneByteString(args.GetIsolate(), OBJ_nid2sn(nid)));
1998  info->Set(env->size_string(),
1999  Integer::New(env->isolate(), EVP_PKEY_bits(key)));
2000  }
2001  }
2002  EVP_PKEY_free(key);
2003  }
2004 
2005  return args.GetReturnValue().Set(info);
2006 }
2007 
2008 
2009 #ifdef SSL_set_max_send_fragment
2010 template <class Base>
2011 void SSLWrap<Base>::SetMaxSendFragment(
2012  const v8::FunctionCallbackInfo<v8::Value>& args) {
2013  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2014 
2015  Base* w;
2016  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2017 
2018  int rv = SSL_set_max_send_fragment(w->ssl_, args[0]->Int32Value());
2019  args.GetReturnValue().Set(rv);
2020 }
2021 #endif // SSL_set_max_send_fragment
2022 
2023 
2024 template <class Base>
2025 void SSLWrap<Base>::IsInitFinished(const FunctionCallbackInfo<Value>& args) {
2026  Base* w;
2027  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2028  bool yes = SSL_is_init_finished(w->ssl_);
2029  args.GetReturnValue().Set(yes);
2030 }
2031 
2032 
2033 template <class Base>
2034 void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2035  Base* w;
2036  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2037 
2038  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2039  // peer certificate is questionable but it's compatible with what was
2040  // here before.
2041  long x509_verify_error = // NOLINT(runtime/int)
2042  X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2043  if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
2044  X509_free(peer_cert);
2045  x509_verify_error = SSL_get_verify_result(w->ssl_);
2046  }
2047 
2048  if (x509_verify_error == X509_V_OK)
2049  return args.GetReturnValue().SetNull();
2050 
2051  // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
2052  // in the presence of invalid error codes. Probably academical but something
2053  // to keep in mind if/when node ever grows multi-isolate capabilities.
2054  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2055  const char* code = reason;
2056 #define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
2057  switch (x509_verify_error) {
2058  CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
2059  CASE_X509_ERR(UNABLE_TO_GET_CRL)
2060  CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
2061  CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
2062  CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
2063  CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
2064  CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
2065  CASE_X509_ERR(CERT_NOT_YET_VALID)
2066  CASE_X509_ERR(CERT_HAS_EXPIRED)
2067  CASE_X509_ERR(CRL_NOT_YET_VALID)
2068  CASE_X509_ERR(CRL_HAS_EXPIRED)
2069  CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
2070  CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
2071  CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
2072  CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
2073  CASE_X509_ERR(OUT_OF_MEM)
2074  CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
2075  CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
2076  CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2077  CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
2078  CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
2079  CASE_X509_ERR(CERT_REVOKED)
2080  CASE_X509_ERR(INVALID_CA)
2081  CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
2082  CASE_X509_ERR(INVALID_PURPOSE)
2083  CASE_X509_ERR(CERT_UNTRUSTED)
2084  CASE_X509_ERR(CERT_REJECTED)
2085  }
2086 #undef CASE_X509_ERR
2087 
2088  Isolate* isolate = args.GetIsolate();
2089  Local<String> reason_string = OneByteString(isolate, reason);
2090  Local<Value> exception_value = Exception::Error(reason_string);
2091  Local<Object> exception_object = exception_value->ToObject(isolate);
2092  exception_object->Set(w->env()->code_string(), OneByteString(isolate, code));
2093  args.GetReturnValue().Set(exception_object);
2094 }
2095 
2096 
2097 template <class Base>
2098 void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
2099  Base* w;
2100  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2101  Environment* env = w->ssl_env();
2102 
2103  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
2104  if (c == nullptr)
2105  return;
2106 
2107  Local<Object> info = Object::New(env->isolate());
2108  const char* cipher_name = SSL_CIPHER_get_name(c);
2109  info->Set(env->name_string(), OneByteString(args.GetIsolate(), cipher_name));
2110  const char* cipher_version = SSL_CIPHER_get_version(c);
2111  info->Set(env->version_string(),
2112  OneByteString(args.GetIsolate(), cipher_version));
2113  args.GetReturnValue().Set(info);
2114 }
2115 
2116 
2117 template <class Base>
2118 void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2119  Base* w;
2120  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2121 
2122  const char* tls_version = SSL_get_version(w->ssl_);
2123  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2124 }
2125 
2126 
2127 #ifndef OPENSSL_NO_NEXTPROTONEG
2128 template <class Base>
2129 int SSLWrap<Base>::AdvertiseNextProtoCallback(SSL* s,
2130  const unsigned char** data,
2131  unsigned int* len,
2132  void* arg) {
2133  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2134  Environment* env = w->env();
2135  HandleScope handle_scope(env->isolate());
2136  Context::Scope context_scope(env->context());
2137 
2138  auto npn_buffer =
2139  w->object()->GetPrivate(
2140  env->context(),
2141  env->npn_buffer_private_symbol()).ToLocalChecked();
2142 
2143  if (npn_buffer->IsUndefined()) {
2144  // No initialization - no NPN protocols
2145  *data = reinterpret_cast<const unsigned char*>("");
2146  *len = 0;
2147  } else {
2148  CHECK(Buffer::HasInstance(npn_buffer));
2149  *data = reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2150  *len = Buffer::Length(npn_buffer);
2151  }
2152 
2153  return SSL_TLSEXT_ERR_OK;
2154 }
2155 
2156 
2157 template <class Base>
2158 int SSLWrap<Base>::SelectNextProtoCallback(SSL* s,
2159  unsigned char** out,
2160  unsigned char* outlen,
2161  const unsigned char* in,
2162  unsigned int inlen,
2163  void* arg) {
2164  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2165  Environment* env = w->env();
2166  HandleScope handle_scope(env->isolate());
2167  Context::Scope context_scope(env->context());
2168 
2169  auto npn_buffer =
2170  w->object()->GetPrivate(
2171  env->context(),
2172  env->npn_buffer_private_symbol()).ToLocalChecked();
2173 
2174  if (npn_buffer->IsUndefined()) {
2175  // We should at least select one protocol
2176  // If server is using NPN
2177  *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
2178  *outlen = 8;
2179 
2180  // set status: unsupported
2181  CHECK(
2182  w->object()->SetPrivate(
2183  env->context(),
2184  env->selected_npn_buffer_private_symbol(),
2185  False(env->isolate())).FromJust());
2186 
2187  return SSL_TLSEXT_ERR_OK;
2188  }
2189 
2190  CHECK(Buffer::HasInstance(npn_buffer));
2191  const unsigned char* npn_protos =
2192  reinterpret_cast<const unsigned char*>(Buffer::Data(npn_buffer));
2193  size_t len = Buffer::Length(npn_buffer);
2194 
2195  int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
2196  Local<Value> result;
2197  switch (status) {
2198  case OPENSSL_NPN_UNSUPPORTED:
2199  result = Null(env->isolate());
2200  break;
2201  case OPENSSL_NPN_NEGOTIATED:
2202  result = OneByteString(env->isolate(), *out, *outlen);
2203  break;
2204  case OPENSSL_NPN_NO_OVERLAP:
2205  result = False(env->isolate());
2206  break;
2207  default:
2208  break;
2209  }
2210 
2211  CHECK(
2212  w->object()->SetPrivate(
2213  env->context(),
2214  env->selected_npn_buffer_private_symbol(),
2215  result).FromJust());
2216 
2217  return SSL_TLSEXT_ERR_OK;
2218 }
2219 
2220 
2221 template <class Base>
2222 void SSLWrap<Base>::GetNegotiatedProto(
2223  const FunctionCallbackInfo<Value>& args) {
2224  Base* w;
2225  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2226  Environment* env = w->env();
2227 
2228  if (w->is_client()) {
2229  auto selected_npn_buffer =
2230  w->object()->GetPrivate(
2231  env->context(),
2232  env->selected_npn_buffer_private_symbol()).ToLocalChecked();
2233  args.GetReturnValue().Set(selected_npn_buffer);
2234  return;
2235  }
2236 
2237  const unsigned char* npn_proto;
2238  unsigned int npn_proto_len;
2239 
2240  SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
2241 
2242  if (!npn_proto)
2243  return args.GetReturnValue().Set(false);
2244 
2245  args.GetReturnValue().Set(
2246  OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
2247 }
2248 
2249 
2250 template <class Base>
2251 void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
2252  Base* w;
2253  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2254  Environment* env = w->env();
2255 
2256  if (args.Length() < 1)
2257  return env->ThrowTypeError("NPN protocols argument is mandatory");
2258 
2259  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "NPN protocols");
2260 
2261  CHECK(
2262  w->object()->SetPrivate(
2263  env->context(),
2264  env->npn_buffer_private_symbol(),
2265  args[0]).FromJust());
2266 }
2267 #endif // OPENSSL_NO_NEXTPROTONEG
2268 
2269 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2270 template <class Base>
2271 int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2272  const unsigned char** out,
2273  unsigned char* outlen,
2274  const unsigned char* in,
2275  unsigned int inlen,
2276  void* arg) {
2277  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2278  Environment* env = w->env();
2279  HandleScope handle_scope(env->isolate());
2280  Context::Scope context_scope(env->context());
2281 
2282  Local<Value> alpn_buffer =
2283  w->object()->GetPrivate(
2284  env->context(),
2285  env->alpn_buffer_private_symbol()).ToLocalChecked();
2286  CHECK(Buffer::HasInstance(alpn_buffer));
2287  const unsigned char* alpn_protos =
2288  reinterpret_cast<const unsigned char*>(Buffer::Data(alpn_buffer));
2289  unsigned alpn_protos_len = Buffer::Length(alpn_buffer);
2290  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2291  alpn_protos, alpn_protos_len, in, inlen);
2292 
2293  switch (status) {
2294  case OPENSSL_NPN_NO_OVERLAP:
2295  // According to 3.2. Protocol Selection of RFC7301,
2296  // fatal no_application_protocol alert shall be sent
2297  // but current openssl does not support it yet. See
2298  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2299  // Instead, we send a warning alert for now.
2300  return SSL_TLSEXT_ERR_ALERT_WARNING;
2301  case OPENSSL_NPN_NEGOTIATED:
2302  return SSL_TLSEXT_ERR_OK;
2303  default:
2304  return SSL_TLSEXT_ERR_ALERT_FATAL;
2305  }
2306 }
2307 #endif // TLSEXT_TYPE_application_layer_protocol_negotiation
2308 
2309 
2310 template <class Base>
2311 void SSLWrap<Base>::GetALPNNegotiatedProto(
2312  const FunctionCallbackInfo<v8::Value>& args) {
2313 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2314  Base* w;
2315  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2316 
2317  const unsigned char* alpn_proto;
2318  unsigned int alpn_proto_len;
2319 
2320  SSL_get0_alpn_selected(w->ssl_, &alpn_proto, &alpn_proto_len);
2321 
2322  if (!alpn_proto)
2323  return args.GetReturnValue().Set(false);
2324 
2325  args.GetReturnValue().Set(
2326  OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len));
2327 #endif // TLSEXT_TYPE_application_layer_protocol_negotiation
2328 }
2329 
2330 
2331 template <class Base>
2332 void SSLWrap<Base>::SetALPNProtocols(
2333  const FunctionCallbackInfo<v8::Value>& args) {
2334 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2335  Base* w;
2336  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2337  Environment* env = w->env();
2338  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2339  return env->ThrowTypeError("Must give a Buffer as first argument");
2340 
2341  if (w->is_client()) {
2342  const unsigned char* alpn_protos =
2343  reinterpret_cast<const unsigned char*>(Buffer::Data(args[0]));
2344  unsigned alpn_protos_len = Buffer::Length(args[0]);
2345  int r = SSL_set_alpn_protos(w->ssl_, alpn_protos, alpn_protos_len);
2346  CHECK_EQ(r, 0);
2347  } else {
2348  CHECK(
2349  w->object()->SetPrivate(
2350  env->context(),
2351  env->alpn_buffer_private_symbol(),
2352  args[0]).FromJust());
2353  // Server should select ALPN protocol from list of advertised by client
2354  SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_), SelectALPNCallback,
2355  nullptr);
2356  }
2357 #endif // TLSEXT_TYPE_application_layer_protocol_negotiation
2358 }
2359 
2360 
2361 #ifdef NODE__HAVE_TLSEXT_STATUS_CB
2362 template <class Base>
2363 int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2364  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2365  Environment* env = w->env();
2366  HandleScope handle_scope(env->isolate());
2367 
2368  if (w->is_client()) {
2369  // Incoming response
2370  const unsigned char* resp;
2371  int len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
2372  Local<Value> arg;
2373  if (resp == nullptr) {
2374  arg = Null(env->isolate());
2375  } else {
2376  arg =
2377  Buffer::Copy(env, reinterpret_cast<const char*>(resp), len)
2378  .ToLocalChecked();
2379  }
2380 
2381  w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2382 
2383  // Somehow, client is expecting different return value here
2384  return 1;
2385  } else {
2386  // Outgoing response
2387  if (w->ocsp_response_.IsEmpty())
2388  return SSL_TLSEXT_ERR_NOACK;
2389 
2390  Local<Object> obj = PersistentToLocal(env->isolate(), w->ocsp_response_);
2391  char* resp = Buffer::Data(obj);
2392  size_t len = Buffer::Length(obj);
2393 
2394  // OpenSSL takes control of the pointer after accepting it
2395  char* data = node::Malloc(len);
2396  memcpy(data, resp, len);
2397 
2398  if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2399  free(data);
2400  w->ocsp_response_.Reset();
2401 
2402  return SSL_TLSEXT_ERR_OK;
2403  }
2404 }
2405 #endif // NODE__HAVE_TLSEXT_STATUS_CB
2406 
2407 
2408 template <class Base>
2409 void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2410  cert_cb_ = cb;
2411  cert_cb_arg_ = arg;
2412 }
2413 
2414 
2415 template <class Base>
2416 int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2417  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2418 
2419  if (!w->is_server())
2420  return 1;
2421 
2422  if (!w->is_waiting_cert_cb())
2423  return 1;
2424 
2425  if (w->cert_cb_running_)
2426  return -1;
2427 
2428  Environment* env = w->env();
2429  HandleScope handle_scope(env->isolate());
2430  Context::Scope context_scope(env->context());
2431  w->cert_cb_running_ = true;
2432 
2433  Local<Object> info = Object::New(env->isolate());
2434 
2435  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2436  if (servername == nullptr) {
2437  info->Set(env->servername_string(), String::Empty(env->isolate()));
2438  } else {
2439  Local<String> str = OneByteString(env->isolate(), servername,
2440  strlen(servername));
2441  info->Set(env->servername_string(), str);
2442  }
2443 
2444  bool ocsp = false;
2445 #ifdef NODE__HAVE_TLSEXT_STATUS_CB
2446  ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp;
2447 #endif
2448 
2449  info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp));
2450 
2451  Local<Value> argv[] = { info };
2452  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2453 
2454  if (!w->cert_cb_running_)
2455  return 1;
2456 
2457  // Performing async action, wait...
2458  return -1;
2459 }
2460 
2461 
2462 template <class Base>
2463 void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2464  Base* w;
2465  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2466  Environment* env = w->env();
2467 
2468  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2469 
2470  Local<Object> object = w->object();
2471  Local<Value> ctx = object->Get(env->sni_context_string());
2472  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2473 
2474  // Not an object, probably undefined or null
2475  if (!ctx->IsObject())
2476  goto fire_cb;
2477 
2478  if (cons->HasInstance(ctx)) {
2479  SecureContext* sc;
2480  ASSIGN_OR_RETURN_UNWRAP(&sc, ctx.As<Object>());
2481  w->sni_context_.Reset();
2482  w->sni_context_.Reset(env->isolate(), ctx);
2483 
2484  int rv;
2485 
2486  // NOTE: reference count is not increased by this API methods
2487  X509* x509 = SSL_CTX_get0_certificate(sc->ctx_);
2488  EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_);
2489  STACK_OF(X509)* chain;
2490 
2491  rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain);
2492  if (rv)
2493  rv = SSL_use_certificate(w->ssl_, x509);
2494  if (rv)
2495  rv = SSL_use_PrivateKey(w->ssl_, pkey);
2496  if (rv && chain != nullptr)
2497  rv = SSL_set1_chain(w->ssl_, chain);
2498  if (rv)
2499  rv = w->SetCACerts(sc);
2500  if (!rv) {
2501  unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
2502  if (!err)
2503  return env->ThrowError("CertCbDone");
2504  return ThrowCryptoError(env, err);
2505  }
2506  } else {
2507  // Failure: incorrect SNI context object
2508  Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2509  w->MakeCallback(env->onerror_string(), 1, &err);
2510  return;
2511  }
2512 
2513  fire_cb:
2514  CertCb cb;
2515  void* arg;
2516 
2517  cb = w->cert_cb_;
2518  arg = w->cert_cb_arg_;
2519 
2520  w->cert_cb_running_ = false;
2521  w->cert_cb_ = nullptr;
2522  w->cert_cb_arg_ = nullptr;
2523 
2524  cb(arg);
2525 }
2526 
2527 
2528 template <class Base>
2529 void SSLWrap<Base>::SSLGetter(Local<String> property,
2530  const PropertyCallbackInfo<Value>& info) {
2531  Base* base;
2532  ASSIGN_OR_RETURN_UNWRAP(&base, info.This());
2533  SSL* ssl = base->ssl_;
2534  Local<External> ext = External::New(info.GetIsolate(), ssl);
2535  info.GetReturnValue().Set(ext);
2536 }
2537 
2538 
2539 template <class Base>
2540 void SSLWrap<Base>::DestroySSL() {
2541  if (ssl_ == nullptr)
2542  return;
2543 
2544  SSL_free(ssl_);
2545  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2546  ssl_ = nullptr;
2547 }
2548 
2549 
2550 template <class Base>
2551 void SSLWrap<Base>::SetSNIContext(SecureContext* sc) {
2552  InitNPN(sc);
2553  CHECK_EQ(SSL_set_SSL_CTX(ssl_, sc->ctx_), sc->ctx_);
2554 
2555  SetCACerts(sc);
2556 }
2557 
2558 
2559 template <class Base>
2560 int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2561  int err = SSL_set1_verify_cert_store(ssl_, SSL_CTX_get_cert_store(sc->ctx_));
2562  if (err != 1)
2563  return err;
2564 
2565  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2566  SSL_CTX_get_client_CA_list(sc->ctx_));
2567 
2568  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2569  SSL_set_client_CA_list(ssl_, list);
2570  return 1;
2571 }
2572 
2573 
2574 void Connection::OnClientHelloParseEnd(void* arg) {
2575  Connection* conn = static_cast<Connection*>(arg);
2576 
2577  // Write all accumulated data
2578  int r = BIO_write(conn->bio_read_,
2579  reinterpret_cast<char*>(conn->hello_data_),
2580  conn->hello_offset_);
2581  conn->HandleBIOError(conn->bio_read_, "BIO_write", r);
2582  conn->SetShutdownFlags();
2583 }
2584 
2585 
2586 #ifdef SSL_PRINT_DEBUG
2587 # define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
2588 #else
2589 # define DEBUG_PRINT(...)
2590 #endif
2591 
2592 
2593 int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
2594  if (rv >= 0)
2595  return rv;
2596 
2597  int retry = BIO_should_retry(bio);
2598  (void) retry; // unused if !defined(SSL_PRINT_DEBUG)
2599 
2600  if (BIO_should_write(bio)) {
2601  DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n",
2602  ssl_,
2603  func,
2604  retry);
2605  return 0;
2606 
2607  } else if (BIO_should_read(bio)) {
2608  DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
2609  return 0;
2610 
2611  } else {
2612  char ssl_error_buf[512];
2613  ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
2614 
2615  HandleScope scope(ssl_env()->isolate());
2616  Local<Value> exception =
2617  Exception::Error(OneByteString(ssl_env()->isolate(), ssl_error_buf));
2618  object()->Set(ssl_env()->error_string(), exception);
2619 
2620  DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n",
2621  ssl_,
2622  func,
2623  rv,
2624  ssl_error_buf);
2625 
2626  return rv;
2627  }
2628 
2629  return 0;
2630 }
2631 
2632 
2633 int Connection::HandleSSLError(const char* func,
2634  int rv,
2635  ZeroStatus zs,
2636  SyscallStatus ss) {
2637  ClearErrorOnReturn clear_error_on_return;
2638 
2639  if (rv > 0)
2640  return rv;
2641  if (rv == 0 && zs == kZeroIsNotAnError)
2642  return rv;
2643 
2644  int err = SSL_get_error(ssl_, rv);
2645 
2646  if (err == SSL_ERROR_NONE) {
2647  return 0;
2648 
2649  } else if (err == SSL_ERROR_WANT_WRITE) {
2650  DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
2651  return 0;
2652 
2653  } else if (err == SSL_ERROR_WANT_READ) {
2654  DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
2655  return 0;
2656 
2657  } else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2658  DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2659  return 0;
2660 
2661  } else if (err == SSL_ERROR_ZERO_RETURN) {
2662  HandleScope scope(ssl_env()->isolate());
2663 
2664  Local<Value> exception =
2665  Exception::Error(ssl_env()->zero_return_string());
2666  object()->Set(ssl_env()->error_string(), exception);
2667  return rv;
2668 
2669  } else if (err == SSL_ERROR_SYSCALL && ss == kIgnoreSyscall) {
2670  return 0;
2671 
2672  } else {
2673  HandleScope scope(ssl_env()->isolate());
2674  BUF_MEM* mem;
2675  BIO *bio;
2676 
2677  CHECK(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
2678 
2679  // XXX We need to drain the error queue for this thread or else OpenSSL
2680  // has the possibility of blocking connections? This problem is not well
2681  // understood. And we should be somehow propagating these errors up
2682  // into JavaScript. There is no test which demonstrates this problem.
2683  // https://github.com/joyent/node/issues/1719
2684  bio = BIO_new(BIO_s_mem());
2685  if (bio != nullptr) {
2686  ERR_print_errors(bio);
2687  BIO_get_mem_ptr(bio, &mem);
2688  Local<Value> exception = Exception::Error(
2689  OneByteString(ssl_env()->isolate(),
2690  mem->data,
2691  mem->length));
2692  object()->Set(ssl_env()->error_string(), exception);
2693  BIO_free_all(bio);
2694  }
2695 
2696  return rv;
2697  }
2698 
2699  return 0;
2700 }
2701 
2702 
2703 void Connection::SetShutdownFlags() {
2704  HandleScope scope(ssl_env()->isolate());
2705 
2706  int flags = SSL_get_shutdown(ssl_);
2707 
2708  if (flags & SSL_SENT_SHUTDOWN) {
2709  Local<String> sent_shutdown_key = ssl_env()->sent_shutdown_string();
2710  object()->Set(sent_shutdown_key, True(ssl_env()->isolate()));
2711  }
2712 
2713  if (flags & SSL_RECEIVED_SHUTDOWN) {
2714  Local<String> received_shutdown_key = ssl_env()->received_shutdown_string();
2715  object()->Set(received_shutdown_key, True(ssl_env()->isolate()));
2716  }
2717 }
2718 
2719 
2720 void Connection::NewSessionDoneCb() {
2721  HandleScope scope(env()->isolate());
2722 
2723  MakeCallback(env()->onnewsessiondone_string(), 0, nullptr);
2724 }
2725 
2726 
2727 void Connection::Initialize(Environment* env, Local<Object> target) {
2728  Local<FunctionTemplate> t = env->NewFunctionTemplate(Connection::New);
2729  t->InstanceTemplate()->SetInternalFieldCount(1);
2730  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"));
2731 
2732  AsyncWrap::AddWrapMethods(env, t);
2733  env->SetProtoMethod(t, "encIn", Connection::EncIn);
2734  env->SetProtoMethod(t, "clearOut", Connection::ClearOut);
2735  env->SetProtoMethod(t, "clearIn", Connection::ClearIn);
2736  env->SetProtoMethod(t, "encOut", Connection::EncOut);
2737  env->SetProtoMethod(t, "clearPending", Connection::ClearPending);
2738  env->SetProtoMethod(t, "encPending", Connection::EncPending);
2739  env->SetProtoMethod(t, "start", Connection::Start);
2740  env->SetProtoMethod(t, "close", Connection::Close);
2741 
2742  SSLWrap<Connection>::AddMethods(env, t);
2743 
2744 
2745 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2746  env->SetProtoMethod(t, "getServername", Connection::GetServername);
2747  env->SetProtoMethod(t, "setSNICallback", Connection::SetSNICallback);
2748 #endif
2749 
2750  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"),
2751  t->GetFunction());
2752 }
2753 
2754 
2755 inline int compar(const void* a, const void* b) {
2756  return memcmp(a, b, CNNIC_WHITELIST_HASH_LEN);
2757 }
2758 
2759 
2760 inline int IsSelfSigned(X509* cert) {
2761  return X509_NAME_cmp(X509_get_subject_name(cert),
2762  X509_get_issuer_name(cert)) == 0;
2763 }
2764 
2765 
2766 inline X509* FindRoot(STACK_OF(X509)* sk) {
2767  for (int i = 0; i < sk_X509_num(sk); i++) {
2768  X509* cert = sk_X509_value(sk, i);
2769  if (IsSelfSigned(cert))
2770  return cert;
2771  }
2772  return nullptr;
2773 }
2774 
2775 
2776 inline bool CertIsStartComOrWoSign(X509_NAME* name) {
2777  const unsigned char* startcom_wosign_data;
2778  X509_NAME* startcom_wosign_name;
2779 
2780  for (const auto& dn : StartComAndWoSignDNs) {
2781  startcom_wosign_data = dn.data;
2782  startcom_wosign_name = d2i_X509_NAME(nullptr, &startcom_wosign_data,
2783  dn.len);
2784  int cmp = X509_NAME_cmp(name, startcom_wosign_name);
2785  X509_NAME_free(startcom_wosign_name);
2786  if (cmp == 0)
2787  return true;
2788  }
2789 
2790  return false;
2791 }
2792 
2793 // Revoke the certificates issued by StartCom or WoSign that has
2794 // notBefore after 00:00:00 on October 21, 2016 (1477008000 in epoch).
2795 inline bool CheckStartComOrWoSign(X509_NAME* root_name, X509* cert) {
2796  if (!CertIsStartComOrWoSign(root_name))
2797  return true;
2798 
2799  time_t october_21_2016 = static_cast<time_t>(1477008000);
2800  if (X509_cmp_time(X509_get_notBefore(cert), &october_21_2016) < 0)
2801  return true;
2802 
2803  return false;
2804 }
2805 
2806 
2807 // Whitelist check for certs issued by CNNIC, StartCom and WoSign. See
2808 // https://blog.mozilla.org/security/2015/04/02
2809 // /distrusting-new-cnnic-certificates/ and
2810 // https://blog.mozilla.org/security/2016/10/24/
2811 // distrusting-new-wosign-and-startcom-certificates
2812 inline CheckResult CheckWhitelistedServerCert(X509_STORE_CTX* ctx) {
2813  unsigned char hash[CNNIC_WHITELIST_HASH_LEN];
2814  unsigned int hashlen = CNNIC_WHITELIST_HASH_LEN;
2815 
2816  STACK_OF(X509)* chain = X509_STORE_CTX_get1_chain(ctx);
2817  CHECK_NE(chain, nullptr);
2818  CHECK_GT(sk_X509_num(chain), 0);
2819 
2820  // Take the last cert as root at the first time.
2821  X509* root_cert = sk_X509_value(chain, sk_X509_num(chain)-1);
2822  X509_NAME* root_name = X509_get_subject_name(root_cert);
2823 
2824  if (!IsSelfSigned(root_cert)) {
2825  root_cert = FindRoot(chain);
2826  CHECK_NE(root_cert, nullptr);
2827  root_name = X509_get_subject_name(root_cert);
2828  }
2829 
2830  X509* leaf_cert = sk_X509_value(chain, 0);
2831  if (!CheckStartComOrWoSign(root_name, leaf_cert)) {
2832  sk_X509_pop_free(chain, X509_free);
2833  return CHECK_CERT_REVOKED;
2834  }
2835 
2836  // When the cert is issued from either CNNNIC ROOT CA or CNNNIC EV
2837  // ROOT CA, check a hash of its leaf cert if it is in the whitelist.
2838  if (X509_NAME_cmp(root_name, cnnic_name) == 0 ||
2839  X509_NAME_cmp(root_name, cnnic_ev_name) == 0) {
2840  int ret = X509_digest(leaf_cert, EVP_sha256(), hash,
2841  &hashlen);
2842  CHECK(ret);
2843 
2844  void* result = bsearch(hash, WhitelistedCNNICHashes,
2845  arraysize(WhitelistedCNNICHashes),
2846  CNNIC_WHITELIST_HASH_LEN, compar);
2847  if (result == nullptr) {
2848  sk_X509_pop_free(chain, X509_free);
2849  return CHECK_CERT_REVOKED;
2850  }
2851  }
2852 
2853  sk_X509_pop_free(chain, X509_free);
2854  return CHECK_OK;
2855 }
2856 
2857 
2858 inline int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2859  // Failure on verification of the cert is handled in
2860  // Connection::VerifyError.
2861  if (preverify_ok == 0 || X509_STORE_CTX_get_error(ctx) != X509_V_OK)
2862  return CHECK_OK;
2863 
2864  // Server does not need to check the whitelist.
2865  SSL* ssl = static_cast<SSL*>(
2866  X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
2867 
2868  if (SSL_is_server(ssl))
2869  return CHECK_OK;
2870 
2871  // Client needs to check if the server cert is listed in the
2872  // whitelist when it is issued by the specific rootCAs.
2873  CheckResult ret = CheckWhitelistedServerCert(ctx);
2874  if (ret == CHECK_CERT_REVOKED)
2875  X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
2876 
2877  return ret;
2878 }
2879 
2880 
2881 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2882 int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
2883  Connection* conn = static_cast<Connection*>(SSL_get_app_data(s));
2884  Environment* env = conn->env();
2885  HandleScope scope(env->isolate());
2886 
2887  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2888 
2889  if (servername) {
2890  conn->servername_.Reset(env->isolate(),
2891  OneByteString(env->isolate(), servername));
2892 
2893  // Call the SNI callback and use its return value as context
2894  if (!conn->sniObject_.IsEmpty()) {
2895  conn->sni_context_.Reset();
2896 
2897  Local<Object> sni_obj = PersistentToLocal(env->isolate(),
2898  conn->sniObject_);
2899 
2900  Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
2901  Local<Value> ret = node::MakeCallback(env->isolate(),
2902  sni_obj,
2903  env->onselect_string(),
2904  1,
2905  &arg);
2906 
2907  // If ret is SecureContext
2908  Local<FunctionTemplate> secure_context_constructor_template =
2909  env->secure_context_constructor_template();
2910  if (secure_context_constructor_template->HasInstance(ret)) {
2911  conn->sni_context_.Reset(env->isolate(), ret);
2912  SecureContext* sc;
2913  ASSIGN_OR_RETURN_UNWRAP(&sc, ret.As<Object>(), SSL_TLSEXT_ERR_NOACK);
2914  conn->SetSNIContext(sc);
2915  } else {
2916  return SSL_TLSEXT_ERR_NOACK;
2917  }
2918  }
2919  }
2920 
2921  return SSL_TLSEXT_ERR_OK;
2922 }
2923 #endif
2924 
2925 void Connection::New(const FunctionCallbackInfo<Value>& args) {
2926  Environment* env = Environment::GetCurrent(args);
2927 
2928  if (args.Length() < 1 || !args[0]->IsObject()) {
2929  env->ThrowError("First argument must be a tls module SecureContext");
2930  return;
2931  }
2932 
2933  SecureContext* sc;
2934  ASSIGN_OR_RETURN_UNWRAP(&sc, args[0].As<Object>());
2935 
2936  bool is_server = args[1]->BooleanValue();
2937 
2938  SSLWrap<Connection>::Kind kind =
2939  is_server ? SSLWrap<Connection>::kServer : SSLWrap<Connection>::kClient;
2940  Connection* conn = new Connection(env, args.This(), sc, kind);
2941  conn->bio_read_ = NodeBIO::New();
2942  conn->bio_write_ = NodeBIO::New();
2943 
2944  SSL_set_app_data(conn->ssl_, conn);
2945 
2946  if (is_server)
2947  SSL_set_info_callback(conn->ssl_, SSLInfoCallback);
2948 
2949  InitNPN(sc);
2950 
2951  SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
2952 
2953 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2954  if (is_server) {
2955  SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
2956  } else if (args[2]->IsString()) {
2957  const node::Utf8Value servername(env->isolate(), args[2]);
2958  SSL_set_tlsext_host_name(conn->ssl_, *servername);
2959  }
2960 #endif
2961 
2962  SSL_set_bio(conn->ssl_, conn->bio_read_, conn->bio_write_);
2963 
2964 #ifdef SSL_MODE_RELEASE_BUFFERS
2965  long mode = SSL_get_mode(conn->ssl_); // NOLINT(runtime/int)
2966  SSL_set_mode(conn->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
2967 #endif
2968 
2969 
2970  int verify_mode;
2971  if (is_server) {
2972  bool request_cert = args[2]->BooleanValue();
2973  if (!request_cert) {
2974  // Note reject_unauthorized ignored.
2975  verify_mode = SSL_VERIFY_NONE;
2976  } else {
2977  bool reject_unauthorized = args[3]->BooleanValue();
2978  verify_mode = SSL_VERIFY_PEER;
2979  if (reject_unauthorized)
2980  verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2981  }
2982  } else {
2983  // Note request_cert and reject_unauthorized are ignored for clients.
2984  verify_mode = SSL_VERIFY_NONE;
2985  }
2986 
2987 
2988  // Always allow a connection. We'll reject in javascript.
2989  SSL_set_verify(conn->ssl_, verify_mode, VerifyCallback);
2990 
2991  if (is_server) {
2992  SSL_set_accept_state(conn->ssl_);
2993  } else {
2994  SSL_set_connect_state(conn->ssl_);
2995  }
2996 }
2997 
2998 
2999 void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
3000  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
3001  return;
3002 
3003  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
3004  // a non-const SSL* in OpenSSL <= 0.9.7e.
3005  SSL* ssl = const_cast<SSL*>(ssl_);
3006  Connection* conn = static_cast<Connection*>(SSL_get_app_data(ssl));
3007  Environment* env = conn->env();
3008  HandleScope handle_scope(env->isolate());
3009  Context::Scope context_scope(env->context());
3010 
3011  if (where & SSL_CB_HANDSHAKE_START) {
3012  conn->MakeCallback(env->onhandshakestart_string(), 0, nullptr);
3013  }
3014 
3015  if (where & SSL_CB_HANDSHAKE_DONE) {
3016  conn->MakeCallback(env->onhandshakedone_string(), 0, nullptr);
3017  }
3018 }
3019 
3020 
3021 void Connection::EncIn(const FunctionCallbackInfo<Value>& args) {
3022  Connection* conn;
3023  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3024  Environment* env = conn->env();
3025 
3026  if (args.Length() < 3) {
3027  return env->ThrowTypeError(
3028  "Data, offset, and length arguments are mandatory");
3029  }
3030 
3031  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3032 
3033  char* buffer_data = Buffer::Data(args[0]);
3034  size_t buffer_length = Buffer::Length(args[0]);
3035 
3036  size_t off = args[1]->Int32Value();
3037  size_t len = args[2]->Int32Value();
3038 
3039  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3040  return env->ThrowRangeError("offset + length > buffer.length");
3041 
3042  int bytes_written;
3043  char* data = buffer_data + off;
3044 
3045  if (conn->is_server() && !conn->hello_parser_.IsEnded()) {
3046  // Just accumulate data, everything will be pushed to BIO later
3047  if (conn->hello_parser_.IsPaused()) {
3048  bytes_written = 0;
3049  } else {
3050  // Copy incoming data to the internal buffer
3051  // (which has a size of the biggest possible TLS frame)
3052  size_t available = sizeof(conn->hello_data_) - conn->hello_offset_;
3053  size_t copied = len < available ? len : available;
3054  memcpy(conn->hello_data_ + conn->hello_offset_, data, copied);
3055  conn->hello_offset_ += copied;
3056 
3057  conn->hello_parser_.Parse(conn->hello_data_, conn->hello_offset_);
3058  bytes_written = copied;
3059  }
3060  } else {
3061  bytes_written = BIO_write(conn->bio_read_, data, len);
3062  conn->HandleBIOError(conn->bio_read_, "BIO_write", bytes_written);
3063  conn->SetShutdownFlags();
3064  }
3065 
3066  args.GetReturnValue().Set(bytes_written);
3067 }
3068 
3069 
3070 void Connection::ClearOut(const FunctionCallbackInfo<Value>& args) {
3071  Connection* conn;
3072  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3073  Environment* env = conn->env();
3074 
3075  if (args.Length() < 3) {
3076  return env->ThrowTypeError(
3077  "Data, offset, and length arguments are mandatory");
3078  }
3079 
3080  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3081 
3082  char* buffer_data = Buffer::Data(args[0]);
3083  size_t buffer_length = Buffer::Length(args[0]);
3084 
3085  size_t off = args[1]->Int32Value();
3086  size_t len = args[2]->Int32Value();
3087 
3088  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3089  return env->ThrowRangeError("offset + length > buffer.length");
3090 
3091  if (!SSL_is_init_finished(conn->ssl_)) {
3092  int rv;
3093 
3094  if (conn->is_server()) {
3095  rv = SSL_accept(conn->ssl_);
3096  conn->HandleSSLError("SSL_accept:ClearOut",
3097  rv,
3098  kZeroIsAnError,
3099  kSyscallError);
3100  } else {
3101  rv = SSL_connect(conn->ssl_);
3102  conn->HandleSSLError("SSL_connect:ClearOut",
3103  rv,
3104  kZeroIsAnError,
3105  kSyscallError);
3106  }
3107 
3108  if (rv < 0) {
3109  return args.GetReturnValue().Set(rv);
3110  }
3111  }
3112 
3113  int bytes_read = SSL_read(conn->ssl_, buffer_data + off, len);
3114  conn->HandleSSLError("SSL_read:ClearOut",
3115  bytes_read,
3116  kZeroIsNotAnError,
3117  kSyscallError);
3118  conn->SetShutdownFlags();
3119 
3120  args.GetReturnValue().Set(bytes_read);
3121 }
3122 
3123 
3124 void Connection::ClearPending(const FunctionCallbackInfo<Value>& args) {
3125  Connection* conn;
3126  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3127  int bytes_pending = BIO_pending(conn->bio_read_);
3128  args.GetReturnValue().Set(bytes_pending);
3129 }
3130 
3131 
3132 void Connection::EncPending(const FunctionCallbackInfo<Value>& args) {
3133  Connection* conn;
3134  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3135  int bytes_pending = BIO_pending(conn->bio_write_);
3136  args.GetReturnValue().Set(bytes_pending);
3137 }
3138 
3139 
3140 void Connection::EncOut(const FunctionCallbackInfo<Value>& args) {
3141  Connection* conn;
3142  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3143  Environment* env = conn->env();
3144 
3145  if (args.Length() < 3) {
3146  return env->ThrowTypeError(
3147  "Data, offset, and length arguments are mandatory");
3148  }
3149 
3150  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3151 
3152  char* buffer_data = Buffer::Data(args[0]);
3153  size_t buffer_length = Buffer::Length(args[0]);
3154 
3155  size_t off = args[1]->Int32Value();
3156  size_t len = args[2]->Int32Value();
3157 
3158  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3159  return env->ThrowRangeError("offset + length > buffer.length");
3160 
3161  int bytes_read = BIO_read(conn->bio_write_, buffer_data + off, len);
3162 
3163  conn->HandleBIOError(conn->bio_write_, "BIO_read:EncOut", bytes_read);
3164  conn->SetShutdownFlags();
3165 
3166  args.GetReturnValue().Set(bytes_read);
3167 }
3168 
3169 
3170 void Connection::ClearIn(const FunctionCallbackInfo<Value>& args) {
3171  Connection* conn;
3172  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3173  Environment* env = conn->env();
3174 
3175  if (args.Length() < 3) {
3176  return env->ThrowTypeError(
3177  "Data, offset, and length arguments are mandatory");
3178  }
3179 
3180  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
3181 
3182  char* buffer_data = Buffer::Data(args[0]);
3183  size_t buffer_length = Buffer::Length(args[0]);
3184 
3185  size_t off = args[1]->Int32Value();
3186  size_t len = args[2]->Int32Value();
3187 
3188  if (!Buffer::IsWithinBounds(off, len, buffer_length))
3189  return env->ThrowRangeError("offset + length > buffer.length");
3190 
3191  if (!SSL_is_init_finished(conn->ssl_)) {
3192  int rv;
3193  if (conn->is_server()) {
3194  rv = SSL_accept(conn->ssl_);
3195  conn->HandleSSLError("SSL_accept:ClearIn",
3196  rv,
3197  kZeroIsAnError,
3198  kSyscallError);
3199  } else {
3200  rv = SSL_connect(conn->ssl_);
3201  conn->HandleSSLError("SSL_connect:ClearIn",
3202  rv,
3203  kZeroIsAnError,
3204  kSyscallError);
3205  }
3206 
3207  if (rv < 0) {
3208  return args.GetReturnValue().Set(rv);
3209  }
3210  }
3211 
3212  int bytes_written = SSL_write(conn->ssl_, buffer_data + off, len);
3213 
3214  conn->HandleSSLError("SSL_write:ClearIn",
3215  bytes_written,
3216  len == 0 ? kZeroIsNotAnError : kZeroIsAnError,
3217  kSyscallError);
3218  conn->SetShutdownFlags();
3219 
3220  args.GetReturnValue().Set(bytes_written);
3221 }
3222 
3223 
3224 void Connection::Start(const FunctionCallbackInfo<Value>& args) {
3225  Connection* conn;
3226  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3227 
3228  int rv = 0;
3229  if (!SSL_is_init_finished(conn->ssl_)) {
3230  if (conn->is_server()) {
3231  rv = SSL_accept(conn->ssl_);
3232  conn->HandleSSLError("SSL_accept:Start",
3233  rv,
3234  kZeroIsAnError,
3235  kSyscallError);
3236  } else {
3237  rv = SSL_connect(conn->ssl_);
3238  conn->HandleSSLError("SSL_connect:Start",
3239  rv,
3240  kZeroIsAnError,
3241  kSyscallError);
3242  }
3243  }
3244  args.GetReturnValue().Set(rv);
3245 }
3246 
3247 
3248 void Connection::Close(const FunctionCallbackInfo<Value>& args) {
3249  Connection* conn;
3250  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3251  conn->DestroySSL();
3252 }
3253 
3254 
3255 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
3256 void Connection::GetServername(const FunctionCallbackInfo<Value>& args) {
3257  Connection* conn;
3258  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3259 
3260  if (conn->is_server() && !conn->servername_.IsEmpty()) {
3261  args.GetReturnValue().Set(conn->servername_);
3262  } else {
3263  args.GetReturnValue().Set(false);
3264  }
3265 }
3266 
3267 
3268 void Connection::SetSNICallback(const FunctionCallbackInfo<Value>& args) {
3269  Connection* conn;
3270  ASSIGN_OR_RETURN_UNWRAP(&conn, args.Holder());
3271  Environment* env = conn->env();
3272 
3273  if (args.Length() < 1 || !args[0]->IsFunction()) {
3274  return env->ThrowError("Must give a Function as first argument");
3275  }
3276 
3277  Local<Object> obj = Object::New(env->isolate());
3278  obj->Set(env->onselect_string(), args[0]);
3279  conn->sniObject_.Reset(args.GetIsolate(), obj);
3280 }
3281 #endif
3282 
3283 
3284 void CipherBase::Initialize(Environment* env, Local<Object> target) {
3285  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3286 
3287  t->InstanceTemplate()->SetInternalFieldCount(1);
3288 
3289  env->SetProtoMethod(t, "init", Init);
3290  env->SetProtoMethod(t, "initiv", InitIv);
3291  env->SetProtoMethod(t, "update", Update);
3292  env->SetProtoMethod(t, "final", Final);
3293  env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding);
3294  env->SetProtoMethod(t, "getAuthTag", GetAuthTag);
3295  env->SetProtoMethod(t, "setAuthTag", SetAuthTag);
3296  env->SetProtoMethod(t, "setAAD", SetAAD);
3297 
3298  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
3299  t->GetFunction());
3300 }
3301 
3302 
3303 void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
3304  CHECK(args.IsConstructCall());
3305  CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher;
3306  Environment* env = Environment::GetCurrent(args);
3307  new CipherBase(env, args.This(), kind);
3308 }
3309 
3310 
3311 void CipherBase::Init(const char* cipher_type,
3312  const char* key_buf,
3313  int key_buf_len) {
3314  HandleScope scope(env()->isolate());
3315 
3316 #ifdef NODE_FIPS_MODE
3317  if (FIPS_mode()) {
3318  return env()->ThrowError(
3319  "crypto.createCipher() is not supported in FIPS mode.");
3320  }
3321 #endif // NODE_FIPS_MODE
3322 
3323  CHECK_EQ(initialised_, false);
3324  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
3325  if (cipher == nullptr) {
3326  return env()->ThrowError("Unknown cipher");
3327  }
3328 
3329  unsigned char key[EVP_MAX_KEY_LENGTH];
3330  unsigned char iv[EVP_MAX_IV_LENGTH];
3331 
3332  int key_len = EVP_BytesToKey(cipher,
3333  EVP_md5(),
3334  nullptr,
3335  reinterpret_cast<const unsigned char*>(key_buf),
3336  key_buf_len,
3337  1,
3338  key,
3339  iv);
3340 
3341  EVP_CIPHER_CTX_init(&ctx_);
3342  const bool encrypt = (kind_ == kCipher);
3343  EVP_CipherInit_ex(&ctx_, cipher, nullptr, nullptr, nullptr, encrypt);
3344 
3345  int mode = EVP_CIPHER_CTX_mode(&ctx_);
3346  if (encrypt && (mode == EVP_CIPH_CTR_MODE || mode == EVP_CIPH_GCM_MODE ||
3347  mode == EVP_CIPH_CCM_MODE)) {
3348  ProcessEmitWarning(env(), "Use Cipheriv for counter mode of %s",
3349  cipher_type);
3350  }
3351 
3352  if (mode == EVP_CIPH_WRAP_MODE)
3353  EVP_CIPHER_CTX_set_flags(&ctx_, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
3354 
3355  CHECK_EQ(1, EVP_CIPHER_CTX_set_key_length(&ctx_, key_len));
3356 
3357  EVP_CipherInit_ex(&ctx_,
3358  nullptr,
3359  nullptr,
3360  reinterpret_cast<unsigned char*>(key),
3361  reinterpret_cast<unsigned char*>(iv),
3362  kind_ == kCipher);
3363  initialised_ = true;
3364 }
3365 
3366 
3367 void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
3368  CipherBase* cipher;
3369  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3370  Environment* env = cipher->env();
3371 
3372  if (args.Length() < 2) {
3373  return env->ThrowError("Cipher type and key arguments are mandatory");
3374  }
3375 
3376  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3377  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3378 
3379  const node::Utf8Value cipher_type(args.GetIsolate(), args[0]);
3380  const char* key_buf = Buffer::Data(args[1]);
3381  ssize_t key_buf_len = Buffer::Length(args[1]);
3382  cipher->Init(*cipher_type, key_buf, key_buf_len);
3383 }
3384 
3385 
3386 void CipherBase::InitIv(const char* cipher_type,
3387  const char* key,
3388  int key_len,
3389  const char* iv,
3390  int iv_len) {
3391  HandleScope scope(env()->isolate());
3392 
3393  const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type);
3394  if (cipher == nullptr) {
3395  return env()->ThrowError("Unknown cipher");
3396  }
3397 
3398  const int expected_iv_len = EVP_CIPHER_iv_length(cipher);
3399  const int mode = EVP_CIPHER_mode(cipher);
3400  const bool is_gcm_mode = (EVP_CIPH_GCM_MODE == mode);
3401 
3402  if (is_gcm_mode == false && iv_len != expected_iv_len) {
3403  return env()->ThrowError("Invalid IV length");
3404  }
3405 
3406  EVP_CIPHER_CTX_init(&ctx_);
3407 
3408  if (mode == EVP_CIPH_WRAP_MODE)
3409  EVP_CIPHER_CTX_set_flags(&ctx_, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
3410 
3411  const bool encrypt = (kind_ == kCipher);
3412  EVP_CipherInit_ex(&ctx_, cipher, nullptr, nullptr, nullptr, encrypt);
3413 
3414  if (is_gcm_mode &&
3415  !EVP_CIPHER_CTX_ctrl(&ctx_, EVP_CTRL_GCM_SET_IVLEN, iv_len, nullptr)) {
3416  EVP_CIPHER_CTX_cleanup(&ctx_);
3417  return env()->ThrowError("Invalid IV length");
3418  }
3419 
3420  if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
3421  EVP_CIPHER_CTX_cleanup(&ctx_);
3422  return env()->ThrowError("Invalid key length");
3423  }
3424 
3425  EVP_CipherInit_ex(&ctx_,
3426  nullptr,
3427  nullptr,
3428  reinterpret_cast<const unsigned char*>(key),
3429  reinterpret_cast<const unsigned char*>(iv),
3430  kind_ == kCipher);
3431  initialised_ = true;
3432 }
3433 
3434 
3435 void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
3436  CipherBase* cipher;
3437  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3438  Environment* env = cipher->env();
3439 
3440  if (args.Length() < 3) {
3441  return env->ThrowError("Cipher type, key, and IV arguments are mandatory");
3442  }
3443 
3444  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Cipher type");
3445  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3446  THROW_AND_RETURN_IF_NOT_BUFFER(args[2], "IV");
3447 
3448  const node::Utf8Value cipher_type(env->isolate(), args[0]);
3449  ssize_t key_len = Buffer::Length(args[1]);
3450  const char* key_buf = Buffer::Data(args[1]);
3451  ssize_t iv_len = Buffer::Length(args[2]);
3452  const char* iv_buf = Buffer::Data(args[2]);
3453  cipher->InitIv(*cipher_type, key_buf, key_len, iv_buf, iv_len);
3454 }
3455 
3456 
3457 bool CipherBase::IsAuthenticatedMode() const {
3458  // Check if this cipher operates in an AEAD mode that we support.
3459  CHECK_EQ(initialised_, true);
3460  const EVP_CIPHER* const cipher = EVP_CIPHER_CTX_cipher(&ctx_);
3461  int mode = EVP_CIPHER_mode(cipher);
3462  return mode == EVP_CIPH_GCM_MODE;
3463 }
3464 
3465 
3466 void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
3467  Environment* env = Environment::GetCurrent(args);
3468  CipherBase* cipher;
3469  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3470 
3471  // Only callable after Final and if encrypting.
3472  if (cipher->initialised_ ||
3473  cipher->kind_ != kCipher ||
3474  cipher->auth_tag_len_ == 0) {
3475  return env->ThrowError("Attempting to get auth tag in unsupported state");
3476  }
3477 
3478  Local<Object> buf =
3479  Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_)
3480  .ToLocalChecked();
3481  args.GetReturnValue().Set(buf);
3482 }
3483 
3484 
3485 void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
3486  Environment* env = Environment::GetCurrent(args);
3487 
3488  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Auth tag");
3489 
3490  CipherBase* cipher;
3491  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3492 
3493  if (!cipher->initialised_ ||
3494  !cipher->IsAuthenticatedMode() ||
3495  cipher->kind_ != kDecipher) {
3496  return env->ThrowError("Attempting to set auth tag in unsupported state");
3497  }
3498 
3499  // FIXME(bnoordhuis) Throw when buffer length is not a valid tag size.
3500  // Note: we don't use std::max() here to work around a header conflict.
3501  cipher->auth_tag_len_ = Buffer::Length(args[0]);
3502  if (cipher->auth_tag_len_ > sizeof(cipher->auth_tag_))
3503  cipher->auth_tag_len_ = sizeof(cipher->auth_tag_);
3504 
3505  memset(cipher->auth_tag_, 0, sizeof(cipher->auth_tag_));
3506  memcpy(cipher->auth_tag_, Buffer::Data(args[0]), cipher->auth_tag_len_);
3507 }
3508 
3509 
3510 bool CipherBase::SetAAD(const char* data, unsigned int len) {
3511  if (!initialised_ || !IsAuthenticatedMode())
3512  return false;
3513  int outlen;
3514  if (!EVP_CipherUpdate(&ctx_,
3515  nullptr,
3516  &outlen,
3517  reinterpret_cast<const unsigned char*>(data),
3518  len)) {
3519  return false;
3520  }
3521  return true;
3522 }
3523 
3524 
3525 void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
3526  Environment* env = Environment::GetCurrent(args);
3527 
3528  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "AAD");
3529 
3530  CipherBase* cipher;
3531  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3532 
3533  if (!cipher->SetAAD(Buffer::Data(args[0]), Buffer::Length(args[0])))
3534  env->ThrowError("Attempting to set AAD in unsupported state");
3535 }
3536 
3537 
3538 bool CipherBase::Update(const char* data,
3539  int len,
3540  unsigned char** out,
3541  int* out_len) {
3542  if (!initialised_)
3543  return 0;
3544 
3545  // on first update:
3546  if (kind_ == kDecipher && IsAuthenticatedMode() && auth_tag_len_ > 0) {
3547  EVP_CIPHER_CTX_ctrl(&ctx_,
3548  EVP_CTRL_GCM_SET_TAG,
3549  auth_tag_len_,
3550  reinterpret_cast<unsigned char*>(auth_tag_));
3551  auth_tag_len_ = 0;
3552  }
3553 
3554  *out_len = len + EVP_CIPHER_CTX_block_size(&ctx_);
3555  *out = Malloc<unsigned char>(static_cast<size_t>(*out_len));
3556  return EVP_CipherUpdate(&ctx_,
3557  *out,
3558  out_len,
3559  reinterpret_cast<const unsigned char*>(data),
3560  len);
3561 }
3562 
3563 
3564 void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
3565  Environment* env = Environment::GetCurrent(args);
3566 
3567  CipherBase* cipher;
3568  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3569 
3570  THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(args[0], "Cipher data");
3571 
3572  unsigned char* out = nullptr;
3573  bool r;
3574  int out_len = 0;
3575 
3576  // Only copy the data if we have to, because it's a string
3577  if (args[0]->IsString()) {
3578  StringBytes::InlineDecoder decoder;
3579  if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3580  return;
3581  r = cipher->Update(decoder.out(), decoder.size(), &out, &out_len);
3582  } else {
3583  char* buf = Buffer::Data(args[0]);
3584  size_t buflen = Buffer::Length(args[0]);
3585  r = cipher->Update(buf, buflen, &out, &out_len);
3586  }
3587 
3588  if (!r) {
3589  free(out);
3590  return ThrowCryptoError(env,
3591  ERR_get_error(),
3592  "Trying to add data in unsupported state");
3593  }
3594 
3595  CHECK(out != nullptr || out_len == 0);
3596  Local<Object> buf =
3597  Buffer::New(env, reinterpret_cast<char*>(out), out_len).ToLocalChecked();
3598 
3599  args.GetReturnValue().Set(buf);
3600 }
3601 
3602 
3603 bool CipherBase::SetAutoPadding(bool auto_padding) {
3604  if (!initialised_)
3605  return false;
3606  return EVP_CIPHER_CTX_set_padding(&ctx_, auto_padding);
3607 }
3608 
3609 
3610 void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
3611  Environment* env = Environment::GetCurrent(args);
3612 
3613  CipherBase* cipher;
3614  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3615 
3616  if (!cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue()))
3617  env->ThrowError("Attempting to set auto padding in unsupported state");
3618 }
3619 
3620 
3621 bool CipherBase::Final(unsigned char** out, int *out_len) {
3622  if (!initialised_)
3623  return false;
3624 
3625  *out = Malloc<unsigned char>(
3626  static_cast<size_t>(EVP_CIPHER_CTX_block_size(&ctx_)));
3627  int r = EVP_CipherFinal_ex(&ctx_, *out, out_len);
3628 
3629  if (r == 1 && kind_ == kCipher && IsAuthenticatedMode()) {
3630  auth_tag_len_ = sizeof(auth_tag_);
3631  r = EVP_CIPHER_CTX_ctrl(&ctx_, EVP_CTRL_GCM_GET_TAG, auth_tag_len_,
3632  reinterpret_cast<unsigned char*>(auth_tag_));
3633  CHECK_EQ(r, 1);
3634  }
3635 
3636  EVP_CIPHER_CTX_cleanup(&ctx_);
3637  initialised_ = false;
3638 
3639  return r == 1;
3640 }
3641 
3642 
3643 void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
3644  Environment* env = Environment::GetCurrent(args);
3645 
3646  CipherBase* cipher;
3647  ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder());
3648  if (!cipher->initialised_) return env->ThrowError("Unsupported state");
3649 
3650  unsigned char* out_value = nullptr;
3651  int out_len = -1;
3652 
3653  // Check IsAuthenticatedMode() first, Final() destroys the EVP_CIPHER_CTX.
3654  const bool is_auth_mode = cipher->IsAuthenticatedMode();
3655  bool r = cipher->Final(&out_value, &out_len);
3656 
3657  if (out_len <= 0 || !r) {
3658  free(out_value);
3659  out_value = nullptr;
3660  out_len = 0;
3661  if (!r) {
3662  const char* msg = is_auth_mode ?
3663  "Unsupported state or unable to authenticate data" :
3664  "Unsupported state";
3665 
3666  return ThrowCryptoError(env,
3667  ERR_get_error(),
3668  msg);
3669  }
3670  }
3671 
3672  Local<Object> buf = Buffer::New(
3673  env,
3674  reinterpret_cast<char*>(out_value),
3675  out_len).ToLocalChecked();
3676  args.GetReturnValue().Set(buf);
3677 }
3678 
3679 
3680 void Hmac::Initialize(Environment* env, v8::Local<v8::Object> target) {
3681  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3682 
3683  t->InstanceTemplate()->SetInternalFieldCount(1);
3684 
3685  env->SetProtoMethod(t, "init", HmacInit);
3686  env->SetProtoMethod(t, "update", HmacUpdate);
3687  env->SetProtoMethod(t, "digest", HmacDigest);
3688 
3689  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hmac"), t->GetFunction());
3690 }
3691 
3692 
3693 void Hmac::New(const FunctionCallbackInfo<Value>& args) {
3694  Environment* env = Environment::GetCurrent(args);
3695  new Hmac(env, args.This());
3696 }
3697 
3698 
3699 void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) {
3700  HandleScope scope(env()->isolate());
3701 
3702  CHECK_EQ(initialised_, false);
3703  const EVP_MD* md = EVP_get_digestbyname(hash_type);
3704  if (md == nullptr) {
3705  return env()->ThrowError("Unknown message digest");
3706  }
3707  HMAC_CTX_init(&ctx_);
3708  if (key_len == 0) {
3709  key = "";
3710  }
3711  if (!HMAC_Init_ex(&ctx_, key, key_len, md, nullptr)) {
3712  return ThrowCryptoError(env(), ERR_get_error());
3713  }
3714  initialised_ = true;
3715 }
3716 
3717 
3718 void Hmac::HmacInit(const FunctionCallbackInfo<Value>& args) {
3719  Hmac* hmac;
3720  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3721  Environment* env = hmac->env();
3722 
3723  if (args.Length() < 2) {
3724  return env->ThrowError("Hash type and key arguments are mandatory");
3725  }
3726 
3727  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Hash type");
3728  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Key");
3729 
3730  const node::Utf8Value hash_type(env->isolate(), args[0]);
3731  const char* buffer_data = Buffer::Data(args[1]);
3732  size_t buffer_length = Buffer::Length(args[1]);
3733  hmac->HmacInit(*hash_type, buffer_data, buffer_length);
3734 }
3735 
3736 
3737 bool Hmac::HmacUpdate(const char* data, int len) {
3738  if (!initialised_)
3739  return false;
3740  int r = HMAC_Update(&ctx_, reinterpret_cast<const unsigned char*>(data), len);
3741  return r == 1;
3742 }
3743 
3744 
3745 void Hmac::HmacUpdate(const FunctionCallbackInfo<Value>& args) {
3746  Environment* env = Environment::GetCurrent(args);
3747 
3748  Hmac* hmac;
3749  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3750 
3752 
3753  // Only copy the data if we have to, because it's a string
3754  bool r;
3755  if (args[0]->IsString()) {
3756  StringBytes::InlineDecoder decoder;
3757  if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3758  return;
3759  r = hmac->HmacUpdate(decoder.out(), decoder.size());
3760  } else {
3761  char* buf = Buffer::Data(args[0]);
3762  size_t buflen = Buffer::Length(args[0]);
3763  r = hmac->HmacUpdate(buf, buflen);
3764  }
3765 
3766  if (!r) {
3767  return env->ThrowTypeError("HmacUpdate fail");
3768  }
3769 }
3770 
3771 
3772 void Hmac::HmacDigest(const FunctionCallbackInfo<Value>& args) {
3773  Environment* env = Environment::GetCurrent(args);
3774 
3775  Hmac* hmac;
3776  ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder());
3777 
3778  enum encoding encoding = BUFFER;
3779  if (args.Length() >= 1) {
3780  CHECK(args[0]->IsString());
3781  encoding = ParseEncoding(env->isolate(), args[0], BUFFER);
3782  }
3783 
3784  if (encoding == UCS2) {
3785  return env->ThrowError("hmac.digest() does not support UTF-16");
3786  }
3787 
3788  unsigned char md_value[EVP_MAX_MD_SIZE];
3789  unsigned int md_len = 0;
3790 
3791  if (hmac->initialised_) {
3792  HMAC_Final(&hmac->ctx_, md_value, &md_len);
3793  HMAC_CTX_cleanup(&hmac->ctx_);
3794  hmac->initialised_ = false;
3795  }
3796 
3797  Local<Value> error;
3798  MaybeLocal<Value> rc =
3799  StringBytes::Encode(env->isolate(),
3800  reinterpret_cast<const char*>(md_value),
3801  md_len,
3802  encoding,
3803  &error);
3804  if (rc.IsEmpty()) {
3805  CHECK(!error.IsEmpty());
3806  env->isolate()->ThrowException(error);
3807  return;
3808  }
3809  args.GetReturnValue().Set(rc.ToLocalChecked());
3810 }
3811 
3812 
3813 void Hash::Initialize(Environment* env, v8::Local<v8::Object> target) {
3814  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3815 
3816  t->InstanceTemplate()->SetInternalFieldCount(1);
3817 
3818  env->SetProtoMethod(t, "update", HashUpdate);
3819  env->SetProtoMethod(t, "digest", HashDigest);
3820 
3821  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hash"), t->GetFunction());
3822 }
3823 
3824 
3825 void Hash::New(const FunctionCallbackInfo<Value>& args) {
3826  Environment* env = Environment::GetCurrent(args);
3827 
3828  if (args.Length() == 0 || !args[0]->IsString()) {
3829  return env->ThrowError("Must give hashtype string as argument");
3830  }
3831 
3832  const node::Utf8Value hash_type(env->isolate(), args[0]);
3833 
3834  Hash* hash = new Hash(env, args.This());
3835  if (!hash->HashInit(*hash_type)) {
3836  return ThrowCryptoError(env, ERR_get_error(),
3837  "Digest method not supported");
3838  }
3839 }
3840 
3841 
3842 bool Hash::HashInit(const char* hash_type) {
3843  CHECK_EQ(initialised_, false);
3844  const EVP_MD* md = EVP_get_digestbyname(hash_type);
3845  if (md == nullptr)
3846  return false;
3847  EVP_MD_CTX_init(&mdctx_);
3848  if (EVP_DigestInit_ex(&mdctx_, md, nullptr) <= 0) {
3849  return false;
3850  }
3851  initialised_ = true;
3852  finalized_ = false;
3853  return true;
3854 }
3855 
3856 
3857 bool Hash::HashUpdate(const char* data, int len) {
3858  if (!initialised_)
3859  return false;
3860  EVP_DigestUpdate(&mdctx_, data, len);
3861  return true;
3862 }
3863 
3864 
3865 void Hash::HashUpdate(const FunctionCallbackInfo<Value>& args) {
3866  Environment* env = Environment::GetCurrent(args);
3867 
3868  Hash* hash;
3869  ASSIGN_OR_RETURN_UNWRAP(&hash, args.Holder());
3870 
3872 
3873  if (!hash->initialised_) {
3874  return env->ThrowError("Not initialized");
3875  }
3876  if (hash->finalized_) {
3877  return env->ThrowError("Digest already called");
3878  }
3879 
3880  // Only copy the data if we have to, because it's a string
3881  bool r;
3882  if (args[0]->IsString()) {
3883  StringBytes::InlineDecoder decoder;
3884  if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
3885  return;
3886  r = hash->HashUpdate(decoder.out(), decoder.size());
3887  } else {
3888  char* buf = Buffer::Data(args[0]);
3889  size_t buflen = Buffer::Length(args[0]);
3890  r = hash->HashUpdate(buf, buflen);
3891  }
3892 
3893  if (!r) {
3894  return env->ThrowTypeError("HashUpdate fail");
3895  }
3896 }
3897 
3898 
3899 void Hash::HashDigest(const FunctionCallbackInfo<Value>& args) {
3900  Environment* env = Environment::GetCurrent(args);
3901 
3902  Hash* hash;
3903  ASSIGN_OR_RETURN_UNWRAP(&hash, args.Holder());
3904 
3905  if (!hash->initialised_) {
3906  return env->ThrowError("Not initialized");
3907  }
3908  if (hash->finalized_) {
3909  return env->ThrowError("Digest already called");
3910  }
3911 
3912  enum encoding encoding = BUFFER;
3913  if (args.Length() >= 1) {
3914  CHECK(args[0]->IsString());
3915  encoding = ParseEncoding(env->isolate(), args[0], BUFFER);
3916  }
3917 
3918  if (encoding == UCS2) {
3919  return env->ThrowError("hash.digest() does not support UTF-16");
3920  }
3921 
3922  unsigned char md_value[EVP_MAX_MD_SIZE];
3923  unsigned int md_len;
3924 
3925  EVP_DigestFinal_ex(&hash->mdctx_, md_value, &md_len);
3926  EVP_MD_CTX_cleanup(&hash->mdctx_);
3927  hash->finalized_ = true;
3928 
3929  Local<Value> error;
3930  MaybeLocal<Value> rc =
3931  StringBytes::Encode(env->isolate(),
3932  reinterpret_cast<const char*>(md_value),
3933  md_len,
3934  encoding,
3935  &error);
3936  if (rc.IsEmpty()) {
3937  CHECK(!error.IsEmpty());
3938  env->isolate()->ThrowException(error);
3939  return;
3940  }
3941  args.GetReturnValue().Set(rc.ToLocalChecked());
3942 }
3943 
3944 
3945 void SignBase::CheckThrow(SignBase::Error error) {
3946  HandleScope scope(env()->isolate());
3947 
3948  switch (error) {
3949  case kSignUnknownDigest:
3950  return env()->ThrowError("Unknown message digest");
3951 
3952  case kSignNotInitialised:
3953  return env()->ThrowError("Not initialised");
3954 
3955  case kSignInit:
3956  case kSignUpdate:
3957  case kSignPrivateKey:
3958  case kSignPublicKey:
3959  {
3960  unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
3961  if (err)
3962  return ThrowCryptoError(env(), err);
3963  switch (error) {
3964  case kSignInit:
3965  return env()->ThrowError("EVP_SignInit_ex failed");
3966  case kSignUpdate:
3967  return env()->ThrowError("EVP_SignUpdate failed");
3968  case kSignPrivateKey:
3969  return env()->ThrowError("PEM_read_bio_PrivateKey failed");
3970  case kSignPublicKey:
3971  return env()->ThrowError("PEM_read_bio_PUBKEY failed");
3972  default:
3973  ABORT();
3974  }
3975  }
3976 
3977  case kSignOk:
3978  return;
3979  }
3980 }
3981 
3982 static bool ApplyRSAOptions(EVP_PKEY* pkey, EVP_PKEY_CTX* pkctx, int padding,
3983  int salt_len) {
3984  if (pkey->type == EVP_PKEY_RSA || pkey->type == EVP_PKEY_RSA2) {
3985  if (EVP_PKEY_CTX_set_rsa_padding(pkctx, padding) <= 0)
3986  return false;
3987  if (padding == RSA_PKCS1_PSS_PADDING) {
3988  if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, salt_len) <= 0)
3989  return false;
3990  }
3991  }
3992 
3993  return true;
3994 }
3995 
3996 
3997 
3998 void Sign::Initialize(Environment* env, v8::Local<v8::Object> target) {
3999  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
4000 
4001  t->InstanceTemplate()->SetInternalFieldCount(1);
4002 
4003  env->SetProtoMethod(t, "init", SignInit);
4004  env->SetProtoMethod(t, "update", SignUpdate);
4005  env->SetProtoMethod(t, "sign", SignFinal);
4006 
4007  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Sign"), t->GetFunction());
4008 }
4009 
4010 
4011 void Sign::New(const FunctionCallbackInfo<Value>& args) {
4012  Environment* env = Environment::GetCurrent(args);
4013  new Sign(env, args.This());
4014 }
4015 
4016 
4017 SignBase::Error Sign::SignInit(const char* sign_type) {
4018  CHECK_EQ(initialised_, false);
4019  const EVP_MD* md = EVP_get_digestbyname(sign_type);
4020  if (md == nullptr)
4021  return kSignUnknownDigest;
4022 
4023  EVP_MD_CTX_init(&mdctx_);
4024  if (!EVP_DigestInit_ex(&mdctx_, md, nullptr))
4025  return kSignInit;
4026  initialised_ = true;
4027 
4028  return kSignOk;
4029 }
4030 
4031 
4032 void Sign::SignInit(const FunctionCallbackInfo<Value>& args) {
4033  Sign* sign;
4034  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
4035  Environment* env = sign->env();
4036 
4037  if (args.Length() == 0) {
4038  return env->ThrowError("Sign type argument is mandatory");
4039  }
4040 
4041  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Sign type");
4042 
4043  const node::Utf8Value sign_type(args.GetIsolate(), args[0]);
4044  sign->CheckThrow(sign->SignInit(*sign_type));
4045 }
4046 
4047 
4048 SignBase::Error Sign::SignUpdate(const char* data, int len) {
4049  if (!initialised_)
4050  return kSignNotInitialised;
4051  if (!EVP_DigestUpdate(&mdctx_, data, len))
4052  return kSignUpdate;
4053  return kSignOk;
4054 }
4055 
4056 
4057 void Sign::SignUpdate(const FunctionCallbackInfo<Value>& args) {
4058  Environment* env = Environment::GetCurrent(args);
4059 
4060  Sign* sign;
4061  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
4062 
4064 
4065  // Only copy the data if we have to, because it's a string
4066  Error err;
4067  if (args[0]->IsString()) {
4068  StringBytes::InlineDecoder decoder;
4069  if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
4070  return;
4071  err = sign->SignUpdate(decoder.out(), decoder.size());
4072  } else {
4073  char* buf = Buffer::Data(args[0]);
4074  size_t buflen = Buffer::Length(args[0]);
4075  err = sign->SignUpdate(buf, buflen);
4076  }
4077 
4078  sign->CheckThrow(err);
4079 }
4080 
4081 static int Node_SignFinal(EVP_MD_CTX* mdctx, unsigned char* md,
4082  unsigned int* sig_len, EVP_PKEY* pkey, int padding,
4083  int pss_salt_len) {
4084  unsigned char m[EVP_MAX_MD_SIZE];
4085  unsigned int m_len;
4086  int rv = 0;
4087  EVP_PKEY_CTX* pkctx = nullptr;
4088 
4089  *sig_len = 0;
4090  if (!EVP_DigestFinal_ex(mdctx, m, &m_len))
4091  return rv;
4092 
4093  if (mdctx->digest->flags & EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) {
4094  size_t sltmp = static_cast<size_t>(EVP_PKEY_size(pkey));
4095  pkctx = EVP_PKEY_CTX_new(pkey, nullptr);
4096  if (pkctx == nullptr)
4097  goto err;
4098  if (EVP_PKEY_sign_init(pkctx) <= 0)
4099  goto err;
4100  if (!ApplyRSAOptions(pkey, pkctx, padding, pss_salt_len))
4101  goto err;
4102  if (EVP_PKEY_CTX_set_signature_md(pkctx, mdctx->digest) <= 0)
4103  goto err;
4104  if (EVP_PKEY_sign(pkctx, md, &sltmp, m, m_len) <= 0)
4105  goto err;
4106  *sig_len = sltmp;
4107  rv = 1;
4108  err:
4109  EVP_PKEY_CTX_free(pkctx);
4110  return rv;
4111  }
4112 
4113  if (mdctx->digest->sign == nullptr) {
4114  EVPerr(EVP_F_EVP_SIGNFINAL, EVP_R_NO_SIGN_FUNCTION_CONFIGURED);
4115  return 0;
4116  }
4117 
4118  return mdctx->digest->sign(mdctx->digest->type, m, m_len, md, sig_len,
4119  pkey->pkey.ptr);
4120 }
4121 
4122 SignBase::Error Sign::SignFinal(const char* key_pem,
4123  int key_pem_len,
4124  const char* passphrase,
4125  unsigned char* sig,
4126  unsigned int* sig_len,
4127  int padding,
4128  int salt_len) {
4129  if (!initialised_)
4130  return kSignNotInitialised;
4131 
4132  BIO* bp = nullptr;
4133  EVP_PKEY* pkey = nullptr;
4134  bool fatal = true;
4135 
4136  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
4137  if (bp == nullptr)
4138  goto exit;
4139 
4140  pkey = PEM_read_bio_PrivateKey(bp,
4141  nullptr,
4142  PasswordCallback,
4143  const_cast<char*>(passphrase));
4144 
4145  // Errors might be injected into OpenSSL's error stack
4146  // without `pkey` being set to nullptr;
4147  // cf. the test of `test_bad_rsa_privkey.pem` for an example.
4148  if (pkey == nullptr || 0 != ERR_peek_error())
4149  goto exit;
4150 
4151 #ifdef NODE_FIPS_MODE
4152  /* Validate DSA2 parameters from FIPS 186-4 */
4153  if (FIPS_mode() && EVP_PKEY_DSA == pkey->type) {
4154  size_t L = BN_num_bits(pkey->pkey.dsa->p);
4155  size_t N = BN_num_bits(pkey->pkey.dsa->q);
4156  bool result = false;
4157 
4158  if (L == 1024 && N == 160)
4159  result = true;
4160  else if (L == 2048 && N == 224)
4161  result = true;
4162  else if (L == 2048 && N == 256)
4163  result = true;
4164  else if (L == 3072 && N == 256)
4165  result = true;
4166 
4167  if (!result) {
4168  fatal = true;
4169  goto exit;
4170  }
4171  }
4172 #endif // NODE_FIPS_MODE
4173 
4174  if (Node_SignFinal(&mdctx_, sig, sig_len, pkey, padding, salt_len))
4175  fatal = false;
4176 
4177  initialised_ = false;
4178 
4179  exit:
4180  if (pkey != nullptr)
4181  EVP_PKEY_free(pkey);
4182  if (bp != nullptr)
4183  BIO_free_all(bp);
4184 
4185  EVP_MD_CTX_cleanup(&mdctx_);
4186 
4187  if (fatal)
4188  return kSignPrivateKey;
4189 
4190  return kSignOk;
4191 }
4192 
4193 
4194 void Sign::SignFinal(const FunctionCallbackInfo<Value>& args) {
4195  Environment* env = Environment::GetCurrent(args);
4196 
4197  Sign* sign;
4198  ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder());
4199 
4200  unsigned int len = args.Length();
4201 
4202  node::Utf8Value passphrase(env->isolate(), args[1]);
4203 
4204  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
4205  size_t buf_len = Buffer::Length(args[0]);
4206  char* buf = Buffer::Data(args[0]);
4207 
4208  CHECK(args[2]->IsInt32());
4209  Maybe<int32_t> maybe_padding = args[2]->Int32Value(env->context());
4210  CHECK(maybe_padding.IsJust());
4211  int padding = maybe_padding.ToChecked();
4212 
4213  CHECK(args[3]->IsInt32());
4214  Maybe<int32_t> maybe_salt_len = args[3]->Int32Value(env->context());
4215  CHECK(maybe_salt_len.IsJust());
4216  int salt_len = maybe_salt_len.ToChecked();
4217 
4218  ClearErrorOnReturn clear_error_on_return;
4219  unsigned char md_value[8192];
4220  unsigned int md_len = sizeof(md_value);
4221 
4222  Error err = sign->SignFinal(
4223  buf,
4224  buf_len,
4225  len >= 2 && !args[1]->IsNull() ? *passphrase : nullptr,
4226  md_value,
4227  &md_len,
4228  padding,
4229  salt_len);
4230  if (err != kSignOk)
4231  return sign->CheckThrow(err);
4232 
4233  Local<Object> rc =
4234  Buffer::Copy(env, reinterpret_cast<char*>(md_value), md_len)
4235  .ToLocalChecked();
4236  args.GetReturnValue().Set(rc);
4237 }
4238 
4239 
4240 void Verify::Initialize(Environment* env, v8::Local<v8::Object> target) {
4241  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
4242 
4243  t->InstanceTemplate()->SetInternalFieldCount(1);
4244 
4245  env->SetProtoMethod(t, "init", VerifyInit);
4246  env->SetProtoMethod(t, "update", VerifyUpdate);
4247  env->SetProtoMethod(t, "verify", VerifyFinal);
4248 
4249  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Verify"),
4250  t->GetFunction());
4251 }
4252 
4253 
4254 void Verify::New(const FunctionCallbackInfo<Value>& args) {
4255  Environment* env = Environment::GetCurrent(args);
4256  new Verify(env, args.This());
4257 }
4258 
4259 
4260 SignBase::Error Verify::VerifyInit(const char* verify_type) {
4261  CHECK_EQ(initialised_, false);
4262  const EVP_MD* md = EVP_get_digestbyname(verify_type);
4263  if (md == nullptr)
4264  return kSignUnknownDigest;
4265 
4266  EVP_MD_CTX_init(&mdctx_);
4267  if (!EVP_DigestInit_ex(&mdctx_, md, nullptr))
4268  return kSignInit;
4269  initialised_ = true;
4270 
4271  return kSignOk;
4272 }
4273 
4274 
4275 void Verify::VerifyInit(const FunctionCallbackInfo<Value>& args) {
4276  Verify* verify;
4277  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4278  Environment* env = verify->env();
4279 
4280  if (args.Length() == 0) {
4281  return env->ThrowError("Verify type argument is mandatory");
4282  }
4283 
4284  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Verify type");
4285 
4286  const node::Utf8Value verify_type(args.GetIsolate(), args[0]);
4287  verify->CheckThrow(verify->VerifyInit(*verify_type));
4288 }
4289 
4290 
4291 SignBase::Error Verify::VerifyUpdate(const char* data, int len) {
4292  if (!initialised_)
4293  return kSignNotInitialised;
4294 
4295  if (!EVP_DigestUpdate(&mdctx_, data, len))
4296  return kSignUpdate;
4297 
4298  return kSignOk;
4299 }
4300 
4301 
4302 void Verify::VerifyUpdate(const FunctionCallbackInfo<Value>& args) {
4303  Environment* env = Environment::GetCurrent(args);
4304 
4305  Verify* verify;
4306  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4307 
4309 
4310  // Only copy the data if we have to, because it's a string
4311  Error err;
4312  if (args[0]->IsString()) {
4313  StringBytes::InlineDecoder decoder;
4314  if (!decoder.Decode(env, args[0].As<String>(), args[1], UTF8))
4315  return;
4316  err = verify->VerifyUpdate(decoder.out(), decoder.size());
4317  } else {
4318  char* buf = Buffer::Data(args[0]);
4319  size_t buflen = Buffer::Length(args[0]);
4320  err = verify->VerifyUpdate(buf, buflen);
4321  }
4322 
4323  verify->CheckThrow(err);
4324 }
4325 
4326 
4327 SignBase::Error Verify::VerifyFinal(const char* key_pem,
4328  int key_pem_len,
4329  const char* sig,
4330  int siglen,
4331  int padding,
4332  int saltlen,
4333  bool* verify_result) {
4334  if (!initialised_)
4335  return kSignNotInitialised;
4336 
4337  ClearErrorOnReturn clear_error_on_return;
4338 
4339  EVP_PKEY* pkey = nullptr;
4340  BIO* bp = nullptr;
4341  X509* x509 = nullptr;
4342  bool fatal = true;
4343  unsigned char m[EVP_MAX_MD_SIZE];
4344  unsigned int m_len;
4345  int r = 0;
4346  EVP_PKEY_CTX* pkctx = nullptr;
4347 
4348  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
4349  if (bp == nullptr)
4350  goto exit;
4351 
4352  // Check if this is a PKCS#8 or RSA public key before trying as X.509.
4353  // Split this out into a separate function once we have more than one
4354  // consumer of public keys.
4355  if (strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
4356  pkey = PEM_read_bio_PUBKEY(bp, nullptr, NoPasswordCallback, nullptr);
4357  if (pkey == nullptr)
4358  goto exit;
4359  } else if (strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
4360  RSA* rsa =
4361  PEM_read_bio_RSAPublicKey(bp, nullptr, PasswordCallback, nullptr);
4362  if (rsa) {
4363  pkey = EVP_PKEY_new();
4364  if (pkey)
4365  EVP_PKEY_set1_RSA(pkey, rsa);
4366  RSA_free(rsa);
4367  }
4368  if (pkey == nullptr)
4369  goto exit;
4370  } else {
4371  // X.509 fallback
4372  x509 = PEM_read_bio_X509(bp, nullptr, NoPasswordCallback, nullptr);
4373  if (x509 == nullptr)
4374  goto exit;
4375 
4376  pkey = X509_get_pubkey(x509);
4377  if (pkey == nullptr)
4378  goto exit;
4379  }
4380 
4381  if (!EVP_DigestFinal_ex(&mdctx_, m, &m_len)) {
4382  goto exit;
4383  }
4384 
4385  fatal = false;
4386 
4387  pkctx = EVP_PKEY_CTX_new(pkey, nullptr);
4388  if (pkctx == nullptr)
4389  goto err;
4390  if (EVP_PKEY_verify_init(pkctx) <= 0)
4391  goto err;
4392  if (!ApplyRSAOptions(pkey, pkctx, padding, saltlen))
4393  goto err;
4394  if (EVP_PKEY_CTX_set_signature_md(pkctx, mdctx_.digest) <= 0)
4395  goto err;
4396  r = EVP_PKEY_verify(pkctx,
4397  reinterpret_cast<const unsigned char*>(sig),
4398  siglen,
4399  m,
4400  m_len);
4401 
4402  err:
4403  EVP_PKEY_CTX_free(pkctx);
4404 
4405  exit:
4406  if (pkey != nullptr)
4407  EVP_PKEY_free(pkey);
4408  if (bp != nullptr)
4409  BIO_free_all(bp);
4410  if (x509 != nullptr)
4411  X509_free(x509);
4412 
4413  EVP_MD_CTX_cleanup(&mdctx_);
4414  initialised_ = false;
4415 
4416  if (fatal)
4417  return kSignPublicKey;
4418 
4419  *verify_result = r == 1;
4420  return kSignOk;
4421 }
4422 
4423 
4424 void Verify::VerifyFinal(const FunctionCallbackInfo<Value>& args) {
4425  Environment* env = Environment::GetCurrent(args);
4426 
4427  Verify* verify;
4428  ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder());
4429 
4430  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Key");
4431  char* kbuf = Buffer::Data(args[0]);
4432  ssize_t klen = Buffer::Length(args[0]);
4433 
4435 
4436  char* hbuf = Buffer::Data(args[1]);
4437  ssize_t hlen = Buffer::Length(args[1]);
4438 
4439  CHECK(args[2]->IsInt32());
4440  Maybe<int32_t> maybe_padding = args[2]->Int32Value(env->context());
4441  CHECK(maybe_padding.IsJust());
4442  int padding = maybe_padding.ToChecked();
4443 
4444  CHECK(args[3]->IsInt32());
4445  Maybe<int32_t> maybe_salt_len = args[3]->Int32Value(env->context());
4446  CHECK(maybe_salt_len.IsJust());
4447  int salt_len = maybe_salt_len.ToChecked();
4448 
4449  bool verify_result;
4450  Error err = verify->VerifyFinal(kbuf, klen, hbuf, hlen, padding, salt_len,
4451  &verify_result);
4452  if (err != kSignOk)
4453  return verify->CheckThrow(err);
4454  args.GetReturnValue().Set(verify_result);
4455 }
4456 
4457 
4458 template <PublicKeyCipher::Operation operation,
4459  PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
4460  PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
4461 bool PublicKeyCipher::Cipher(const char* key_pem,
4462  int key_pem_len,
4463  const char* passphrase,
4464  int padding,
4465  const unsigned char* data,
4466  int len,
4467  unsigned char** out,
4468  size_t* out_len) {
4469  EVP_PKEY* pkey = nullptr;
4470  EVP_PKEY_CTX* ctx = nullptr;
4471  BIO* bp = nullptr;
4472  X509* x509 = nullptr;
4473  bool fatal = true;
4474 
4475  bp = BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len);
4476  if (bp == nullptr)
4477  goto exit;
4478 
4479  // Check if this is a PKCS#8 or RSA public key before trying as X.509 and
4480  // private key.
4481  if (operation == kPublic &&
4482  strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
4483  pkey = PEM_read_bio_PUBKEY(bp, nullptr, nullptr, nullptr);
4484  if (pkey == nullptr)
4485  goto exit;
4486  } else if (operation == kPublic &&
4487  strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
4488  RSA* rsa = PEM_read_bio_RSAPublicKey(bp, nullptr, nullptr, nullptr);
4489  if (rsa) {
4490  pkey = EVP_PKEY_new();
4491  if (pkey)
4492  EVP_PKEY_set1_RSA(pkey, rsa);
4493  RSA_free(rsa);
4494  }
4495  if (pkey == nullptr)
4496  goto exit;
4497  } else if (operation == kPublic &&
4498  strncmp(key_pem, CERTIFICATE_PFX, CERTIFICATE_PFX_LEN) == 0) {
4499  x509 = PEM_read_bio_X509(bp, nullptr, NoPasswordCallback, nullptr);
4500  if (x509 == nullptr)
4501  goto exit;
4502 
4503  pkey = X509_get_pubkey(x509);
4504  if (pkey == nullptr)
4505  goto exit;
4506  } else {
4507  pkey = PEM_read_bio_PrivateKey(bp,
4508  nullptr,
4509  PasswordCallback,
4510  const_cast<char*>(passphrase));
4511  if (pkey == nullptr)
4512  goto exit;
4513  }
4514 
4515  ctx = EVP_PKEY_CTX_new(pkey, nullptr);
4516  if (!ctx)
4517  goto exit;
4518  if (EVP_PKEY_cipher_init(ctx) <= 0)
4519  goto exit;
4520  if (EVP_PKEY_CTX_set_rsa_padding(ctx, padding) <= 0)
4521  goto exit;
4522 
4523  if (EVP_PKEY_cipher(ctx, nullptr, out_len, data, len) <= 0)
4524  goto exit;
4525 
4526  *out = Malloc<unsigned char>(*out_len);
4527 
4528  if (EVP_PKEY_cipher(ctx, *out, out_len, data, len) <= 0)
4529  goto exit;
4530 
4531  fatal = false;
4532 
4533  exit:
4534  if (x509 != nullptr)
4535  X509_free(x509);
4536  if (pkey != nullptr)
4537  EVP_PKEY_free(pkey);
4538  if (bp != nullptr)
4539  BIO_free_all(bp);
4540  if (ctx != nullptr)
4541  EVP_PKEY_CTX_free(ctx);
4542 
4543  return !fatal;
4544 }
4545 
4546 
4547 template <PublicKeyCipher::Operation operation,
4548  PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
4549  PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
4550 void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
4551  Environment* env = Environment::GetCurrent(args);
4552 
4553  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Key");
4554  char* kbuf = Buffer::Data(args[0]);
4555  ssize_t klen = Buffer::Length(args[0]);
4556 
4557  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Data");
4558  char* buf = Buffer::Data(args[1]);
4559  ssize_t len = Buffer::Length(args[1]);
4560 
4561  int padding = args[2]->Uint32Value();
4562 
4563  String::Utf8Value passphrase(args[3]);
4564 
4565  unsigned char* out_value = nullptr;
4566  size_t out_len = 0;
4567 
4568  ClearErrorOnReturn clear_error_on_return;
4569 
4570  bool r = Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
4571  kbuf,
4572  klen,
4573  args.Length() >= 3 && !args[2]->IsNull() ? *passphrase : nullptr,
4574  padding,
4575  reinterpret_cast<const unsigned char*>(buf),
4576  len,
4577  &out_value,
4578  &out_len);
4579 
4580  if (out_len == 0 || !r) {
4581  free(out_value);
4582  out_value = nullptr;
4583  out_len = 0;
4584  if (!r) {
4585  return ThrowCryptoError(env,
4586  ERR_get_error());
4587  }
4588  }
4589 
4590  Local<Object> vbuf =
4591  Buffer::New(env, reinterpret_cast<char*>(out_value), out_len)
4592  .ToLocalChecked();
4593  args.GetReturnValue().Set(vbuf);
4594 }
4595 
4596 
4597 void DiffieHellman::Initialize(Environment* env, Local<Object> target) {
4598  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
4599 
4600  const PropertyAttribute attributes =
4601  static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
4602 
4603  t->InstanceTemplate()->SetInternalFieldCount(1);
4604 
4605  env->SetProtoMethod(t, "generateKeys", GenerateKeys);
4606  env->SetProtoMethod(t, "computeSecret", ComputeSecret);
4607  env->SetProtoMethod(t, "getPrime", GetPrime);
4608  env->SetProtoMethod(t, "getGenerator", GetGenerator);
4609  env->SetProtoMethod(t, "getPublicKey", GetPublicKey);
4610  env->SetProtoMethod(t, "getPrivateKey", GetPrivateKey);
4611  env->SetProtoMethod(t, "setPublicKey", SetPublicKey);
4612  env->SetProtoMethod(t, "setPrivateKey", SetPrivateKey);
4613 
4614  t->InstanceTemplate()->SetAccessor(
4615  env->verify_error_string(),
4616  DiffieHellman::VerifyErrorGetter,
4617  nullptr,
4618  env->as_external(),
4619  DEFAULT,
4620  attributes,
4621  AccessorSignature::New(env->isolate(), t));
4622 
4623  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellman"),
4624  t->GetFunction());
4625 
4626  Local<FunctionTemplate> t2 = env->NewFunctionTemplate(DiffieHellmanGroup);
4627  t2->InstanceTemplate()->SetInternalFieldCount(1);
4628 
4629  env->SetProtoMethod(t2, "generateKeys", GenerateKeys);
4630  env->SetProtoMethod(t2, "computeSecret", ComputeSecret);
4631  env->SetProtoMethod(t2, "getPrime", GetPrime);
4632  env->SetProtoMethod(t2, "getGenerator", GetGenerator);
4633  env->SetProtoMethod(t2, "getPublicKey", GetPublicKey);
4634  env->SetProtoMethod(t2, "getPrivateKey", GetPrivateKey);
4635 
4636  t2->InstanceTemplate()->SetAccessor(
4637  env->verify_error_string(),
4638  DiffieHellman::VerifyErrorGetter,
4639  nullptr,
4640  env->as_external(),
4641  DEFAULT,
4642  attributes,
4643  AccessorSignature::New(env->isolate(), t2));
4644 
4645  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellmanGroup"),
4646  t2->GetFunction());
4647 }
4648 
4649 
4650 bool DiffieHellman::Init(int primeLength, int g) {
4651  dh = DH_new();
4652  if (!DH_generate_parameters_ex(dh, primeLength, g, 0))
4653  return false;
4654  bool result = VerifyContext();
4655  if (!result)
4656  return false;
4657  initialised_ = true;
4658  return true;
4659 }
4660 
4661 
4662 bool DiffieHellman::Init(const char* p, int p_len, int g) {
4663  dh = DH_new();
4664  dh->p = BN_bin2bn(reinterpret_cast<const unsigned char*>(p), p_len, 0);
4665  dh->g = BN_new();
4666  if (!BN_set_word(dh->g, g))
4667  return false;
4668  bool result = VerifyContext();
4669  if (!result)
4670  return false;
4671  initialised_ = true;
4672  return true;
4673 }
4674 
4675 
4676 bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) {
4677  dh = DH_new();
4678  dh->p = BN_bin2bn(reinterpret_cast<const unsigned char*>(p), p_len, 0);
4679  dh->g = BN_bin2bn(reinterpret_cast<const unsigned char*>(g), g_len, 0);
4680  bool result = VerifyContext();
4681  if (!result)
4682  return false;
4683  initialised_ = true;
4684  return true;
4685 }
4686 
4687 
4688 void DiffieHellman::DiffieHellmanGroup(
4689  const FunctionCallbackInfo<Value>& args) {
4690  Environment* env = Environment::GetCurrent(args);
4691  DiffieHellman* diffieHellman = new DiffieHellman(env, args.This());
4692 
4693  if (args.Length() != 1) {
4694  return env->ThrowError("Group name argument is mandatory");
4695  }
4696 
4697  THROW_AND_RETURN_IF_NOT_STRING(args[0], "Group name");
4698 
4699  bool initialized = false;
4700 
4701  const node::Utf8Value group_name(env->isolate(), args[0]);
4702  for (size_t i = 0; i < arraysize(modp_groups); ++i) {
4703  const modp_group* it = modp_groups + i;
4704 
4705  if (!StringEqualNoCase(*group_name, it->name))
4706  continue;
4707 
4708  initialized = diffieHellman->Init(it->prime,
4709  it->prime_size,
4710  it->gen,
4711  it->gen_size);
4712  if (!initialized)
4713  env->ThrowError("Initialization failed");
4714  return;
4715  }
4716 
4717  env->ThrowError("Unknown group");
4718 }
4719 
4720 
4721 void DiffieHellman::New(const FunctionCallbackInfo<Value>& args) {
4722  Environment* env = Environment::GetCurrent(args);
4723  DiffieHellman* diffieHellman =
4724  new DiffieHellman(env, args.This());
4725  bool initialized = false;
4726 
4727  if (args.Length() == 2) {
4728  if (args[0]->IsInt32()) {
4729  if (args[1]->IsInt32()) {
4730  initialized = diffieHellman->Init(args[0]->Int32Value(),
4731  args[1]->Int32Value());
4732  }
4733  } else {
4734  if (args[1]->IsInt32()) {
4735  initialized = diffieHellman->Init(Buffer::Data(args[0]),
4736  Buffer::Length(args[0]),
4737  args[1]->Int32Value());
4738  } else {
4739  initialized = diffieHellman->Init(Buffer::Data(args[0]),
4740  Buffer::Length(args[0]),
4741  Buffer::Data(args[1]),
4742  Buffer::Length(args[1]));
4743  }
4744  }
4745  }
4746 
4747  if (!initialized) {
4748  return ThrowCryptoError(env, ERR_get_error(), "Initialization failed");
4749  }
4750 }
4751 
4752 
4753 void DiffieHellman::GenerateKeys(const FunctionCallbackInfo<Value>& args) {
4754  Environment* env = Environment::GetCurrent(args);
4755 
4756  DiffieHellman* diffieHellman;
4757  ASSIGN_OR_RETURN_UNWRAP(&diffieHellman, args.Holder());
4758 
4759  if (!diffieHellman->initialised_) {
4760  return ThrowCryptoError(env, ERR_get_error(), "Not initialized");
4761  }
4762 
4763  if (!DH_generate_key(diffieHellman->dh)) {
4764  return ThrowCryptoError(env, ERR_get_error(), "Key generation failed");
4765  }
4766 
4767  size_t size = BN_num_bytes(diffieHellman->dh->pub_key);
4768  char* data = Malloc(size);
4769  BN_bn2bin(diffieHellman->dh->pub_key, reinterpret_cast<unsigned char*>(data));
4770  args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
4771 }
4772 
4773 
4774 void DiffieHellman::GetField(const FunctionCallbackInfo<Value>& args,
4775  BIGNUM* (DH::*field), const char* err_if_null) {
4776  Environment* env = Environment::GetCurrent(args);
4777 
4778  DiffieHellman* dh;
4779  ASSIGN_OR_RETURN_UNWRAP(&dh, args.Holder());
4780  if (!dh->initialised_) return env->ThrowError("Not initialized");
4781 
4782  const BIGNUM* num = (dh->dh)->*field;
4783  if (num == nullptr) return env->ThrowError(err_if_null);
4784 
4785  size_t size = BN_num_bytes(num);
4786  char* data = Malloc(size);
4787  BN_bn2bin(num, reinterpret_cast<unsigned char*>(data));
4788  args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
4789 }
4790 
4791 void DiffieHellman::GetPrime(const FunctionCallbackInfo<Value>& args) {
4792  GetField(args, &DH::p, "p is null");
4793 }
4794 
4795 
4796 void DiffieHellman::GetGenerator(const FunctionCallbackInfo<Value>& args) {
4797  GetField(args, &DH::g, "g is null");
4798 }
4799 
4800 
4801 void DiffieHellman::GetPublicKey(const FunctionCallbackInfo<Value>& args) {
4802  GetField(args, &DH::pub_key,
4803  "No public key - did you forget to generate one?");
4804 }
4805 
4806 
4807 void DiffieHellman::GetPrivateKey(const FunctionCallbackInfo<Value>& args) {
4808  GetField(args, &DH::priv_key,
4809  "No private key - did you forget to generate one?");
4810 }
4811 
4812 
4813 void DiffieHellman::ComputeSecret(const FunctionCallbackInfo<Value>& args) {
4814  Environment* env = Environment::GetCurrent(args);
4815 
4816  DiffieHellman* diffieHellman;
4817  ASSIGN_OR_RETURN_UNWRAP(&diffieHellman, args.Holder());
4818 
4819  if (!diffieHellman->initialised_) {
4820  return ThrowCryptoError(env, ERR_get_error(), "Not initialized");
4821  }
4822 
4823  ClearErrorOnReturn clear_error_on_return;
4824  BIGNUM* key = nullptr;
4825 
4826  if (args.Length() == 0) {
4827  return env->ThrowError("Other party's public key argument is mandatory");
4828  } else {
4829  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Other party's public key");
4830  key = BN_bin2bn(
4831  reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
4832  Buffer::Length(args[0]),
4833  0);
4834  }
4835 
4836  int dataSize = DH_size(diffieHellman->dh);
4837  char* data = Malloc(dataSize);
4838 
4839  int size = DH_compute_key(reinterpret_cast<unsigned char*>(data),
4840  key,
4841  diffieHellman->dh);
4842 
4843  if (size == -1) {
4844  int checkResult;
4845  int checked;
4846 
4847  checked = DH_check_pub_key(diffieHellman->dh, key, &checkResult);
4848  BN_free(key);
4849  free(data);
4850 
4851  if (!checked) {
4852  return ThrowCryptoError(env, ERR_get_error(), "Invalid Key");
4853  } else if (checkResult) {
4854  if (checkResult & DH_CHECK_PUBKEY_TOO_SMALL) {
4855  return env->ThrowError("Supplied key is too small");
4856  } else if (checkResult & DH_CHECK_PUBKEY_TOO_LARGE) {
4857  return env->ThrowError("Supplied key is too large");
4858  } else {
4859  return env->ThrowError("Invalid key");
4860  }
4861  } else {
4862  return env->ThrowError("Invalid key");
4863  }
4864 
4865  UNREACHABLE();
4866  }
4867 
4868  BN_free(key);
4869  CHECK_GE(size, 0);
4870 
4871  // DH_size returns number of bytes in a prime number
4872  // DH_compute_key returns number of bytes in a remainder of exponent, which
4873  // may have less bytes than a prime number. Therefore add 0-padding to the
4874  // allocated buffer.
4875  if (size != dataSize) {
4876  CHECK(dataSize > size);
4877  memmove(data + dataSize - size, data, size);
4878  memset(data, 0, dataSize - size);
4879  }
4880 
4881  auto rc = Buffer::New(env->isolate(), data, dataSize).ToLocalChecked();
4882  args.GetReturnValue().Set(rc);
4883 }
4884 
4885 
4886 void DiffieHellman::SetKey(const v8::FunctionCallbackInfo<v8::Value>& args,
4887  BIGNUM* (DH::*field), const char* what) {
4888  Environment* env = Environment::GetCurrent(args);
4889 
4890  DiffieHellman* dh;
4891  ASSIGN_OR_RETURN_UNWRAP(&dh, args.Holder());
4892  if (!dh->initialised_) return env->ThrowError("Not initialized");
4893 
4894  BIGNUM** num = &((dh->dh)->*field);
4895  char errmsg[64];
4896 
4897  if (args.Length() == 0) {
4898  snprintf(errmsg, sizeof(errmsg), "%s argument is mandatory", what);
4899  return env->ThrowError(errmsg);
4900  }
4901 
4902  if (!Buffer::HasInstance(args[0])) {
4903  snprintf(errmsg, sizeof(errmsg), "%s must be a buffer", what);
4904  return env->ThrowTypeError(errmsg);
4905  }
4906 
4907  *num = BN_bin2bn(reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
4908  Buffer::Length(args[0]), *num);
4909  CHECK_NE(*num, nullptr);
4910 }
4911 
4912 
4913 void DiffieHellman::SetPublicKey(const FunctionCallbackInfo<Value>& args) {
4914  SetKey(args, &DH::pub_key, "Public key");
4915 }
4916 
4917 
4918 void DiffieHellman::SetPrivateKey(const FunctionCallbackInfo<Value>& args) {
4919  SetKey(args, &DH::priv_key, "Private key");
4920 }
4921 
4922 
4923 void DiffieHellman::VerifyErrorGetter(Local<String> property,
4924  const PropertyCallbackInfo<Value>& args) {
4925  HandleScope scope(args.GetIsolate());
4926 
4927  DiffieHellman* diffieHellman;
4928  ASSIGN_OR_RETURN_UNWRAP(&diffieHellman, args.Holder());
4929 
4930  if (!diffieHellman->initialised_)
4931  return ThrowCryptoError(diffieHellman->env(), ERR_get_error(),
4932  "Not initialized");
4933 
4934  args.GetReturnValue().Set(diffieHellman->verifyError_);
4935 }
4936 
4937 
4938 bool DiffieHellman::VerifyContext() {
4939  int codes;
4940  if (!DH_check(dh, &codes))
4941  return false;
4942  verifyError_ = codes;
4943  return true;
4944 }
4945 
4946 
4947 void ECDH::Initialize(Environment* env, Local<Object> target) {
4948  HandleScope scope(env->isolate());
4949 
4950  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
4951 
4952  t->InstanceTemplate()->SetInternalFieldCount(1);
4953 
4954  env->SetProtoMethod(t, "generateKeys", GenerateKeys);
4955  env->SetProtoMethod(t, "computeSecret", ComputeSecret);
4956  env->SetProtoMethod(t, "getPublicKey", GetPublicKey);
4957  env->SetProtoMethod(t, "getPrivateKey", GetPrivateKey);
4958  env->SetProtoMethod(t, "setPublicKey", SetPublicKey);
4959  env->SetProtoMethod(t, "setPrivateKey", SetPrivateKey);
4960 
4961  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"),
4962  t->GetFunction());
4963 }
4964 
4965 
4966 void ECDH::New(const FunctionCallbackInfo<Value>& args) {
4967  Environment* env = Environment::GetCurrent(args);
4968 
4969  MarkPopErrorOnReturn mark_pop_error_on_return;
4970 
4971  // TODO(indutny): Support raw curves?
4972  THROW_AND_RETURN_IF_NOT_STRING(args[0], "ECDH curve name");
4973  node::Utf8Value curve(env->isolate(), args[0]);
4974 
4975  int nid = OBJ_sn2nid(*curve);
4976  if (nid == NID_undef)
4977  return env->ThrowTypeError("First argument should be a valid curve name");
4978 
4979  EC_KEY* key = EC_KEY_new_by_curve_name(nid);
4980  if (key == nullptr)
4981  return env->ThrowError("Failed to create EC_KEY using curve name");
4982 
4983  new ECDH(env, args.This(), key);
4984 }
4985 
4986 
4987 void ECDH::GenerateKeys(const FunctionCallbackInfo<Value>& args) {
4988  Environment* env = Environment::GetCurrent(args);
4989 
4990  ECDH* ecdh;
4991  ASSIGN_OR_RETURN_UNWRAP(&ecdh, args.Holder());
4992 
4993  if (!EC_KEY_generate_key(ecdh->key_))
4994  return env->ThrowError("Failed to generate EC_KEY");
4995 }
4996 
4997 
4998 EC_POINT* ECDH::BufferToPoint(char* data, size_t len) {
4999  EC_POINT* pub;
5000  int r;
5001 
5002  pub = EC_POINT_new(group_);
5003  if (pub == nullptr) {
5004  env()->ThrowError("Failed to allocate EC_POINT for a public key");
5005  return nullptr;
5006  }
5007 
5008  r = EC_POINT_oct2point(
5009  group_,
5010  pub,
5011  reinterpret_cast<unsigned char*>(data),
5012  len,
5013  nullptr);
5014  if (!r) {
5015  env()->ThrowError("Failed to translate Buffer to a EC_POINT");
5016  goto fatal;
5017  }
5018 
5019  return pub;
5020 
5021  fatal:
5022  EC_POINT_free(pub);
5023  return nullptr;
5024 }
5025 
5026 
5027 void ECDH::ComputeSecret(const FunctionCallbackInfo<Value>& args) {
5028  Environment* env = Environment::GetCurrent(args);
5029 
5030  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
5031 
5032  ECDH* ecdh;
5033  ASSIGN_OR_RETURN_UNWRAP(&ecdh, args.Holder());
5034 
5035  MarkPopErrorOnReturn mark_pop_error_on_return;
5036 
5037  if (!ecdh->IsKeyPairValid())
5038  return env->ThrowError("Invalid key pair");
5039 
5040  EC_POINT* pub = ecdh->BufferToPoint(Buffer::Data(args[0]),
5041  Buffer::Length(args[0]));
5042  if (pub == nullptr)
5043  return;
5044 
5045  // NOTE: field_size is in bits
5046  int field_size = EC_GROUP_get_degree(ecdh->group_);
5047  size_t out_len = (field_size + 7) / 8;
5048  char* out = node::Malloc(out_len);
5049 
5050  int r = ECDH_compute_key(out, out_len, pub, ecdh->key_, nullptr);
5051  EC_POINT_free(pub);
5052  if (!r) {
5053  free(out);
5054  return env->ThrowError("Failed to compute ECDH key");
5055  }
5056 
5057  Local<Object> buf = Buffer::New(env, out, out_len).ToLocalChecked();
5058  args.GetReturnValue().Set(buf);
5059 }
5060 
5061 
5062 void ECDH::GetPublicKey(const FunctionCallbackInfo<Value>& args) {
5063  Environment* env = Environment::GetCurrent(args);
5064 
5065  // Conversion form
5066  CHECK_EQ(args.Length(), 1);
5067 
5068  ECDH* ecdh;
5069  ASSIGN_OR_RETURN_UNWRAP(&ecdh, args.Holder());
5070 
5071  const EC_POINT* pub = EC_KEY_get0_public_key(ecdh->key_);
5072  if (pub == nullptr)
5073  return env->ThrowError("Failed to get ECDH public key");
5074 
5075  int size;
5076  point_conversion_form_t form =
5077  static_cast<point_conversion_form_t>(args[0]->Uint32Value());
5078 
5079  size = EC_POINT_point2oct(ecdh->group_, pub, form, nullptr, 0, nullptr);
5080  if (size == 0)
5081  return env->ThrowError("Failed to get public key length");
5082 
5083  unsigned char* out = node::Malloc<unsigned char>(size);
5084 
5085  int r = EC_POINT_point2oct(ecdh->group_, pub, form, out, size, nullptr);
5086  if (r != size) {
5087  free(out);
5088  return env->ThrowError("Failed to get public key");
5089  }
5090 
5091  Local<Object> buf =
5092  Buffer::New(env, reinterpret_cast<char*>(out), size).ToLocalChecked();
5093  args.GetReturnValue().Set(buf);
5094 }
5095 
5096 
5097 void ECDH::GetPrivateKey(const FunctionCallbackInfo<Value>& args) {
5098  Environment* env = Environment::GetCurrent(args);
5099 
5100  ECDH* ecdh;
5101  ASSIGN_OR_RETURN_UNWRAP(&ecdh, args.Holder());
5102 
5103  const BIGNUM* b = EC_KEY_get0_private_key(ecdh->key_);
5104  if (b == nullptr)
5105  return env->ThrowError("Failed to get ECDH private key");
5106 
5107  int size = BN_num_bytes(b);
5108  unsigned char* out = node::Malloc<unsigned char>(size);
5109 
5110  if (size != BN_bn2bin(b, out)) {
5111  free(out);
5112  return env->ThrowError("Failed to convert ECDH private key to Buffer");
5113  }
5114 
5115  Local<Object> buf =
5116  Buffer::New(env, reinterpret_cast<char*>(out), size).ToLocalChecked();
5117  args.GetReturnValue().Set(buf);
5118 }
5119 
5120 
5121 void ECDH::SetPrivateKey(const FunctionCallbackInfo<Value>& args) {
5122  Environment* env = Environment::GetCurrent(args);
5123 
5124  ECDH* ecdh;
5125  ASSIGN_OR_RETURN_UNWRAP(&ecdh, args.Holder());
5126 
5127  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Private key");
5128 
5129  BIGNUM* priv = BN_bin2bn(
5130  reinterpret_cast<unsigned char*>(Buffer::Data(args[0].As<Object>())),
5131  Buffer::Length(args[0].As<Object>()),
5132  nullptr);
5133  if (priv == nullptr)
5134  return env->ThrowError("Failed to convert Buffer to BN");
5135 
5136  if (!ecdh->IsKeyValidForCurve(priv)) {
5137  BN_free(priv);
5138  return env->ThrowError("Private key is not valid for specified curve.");
5139  }
5140 
5141  int result = EC_KEY_set_private_key(ecdh->key_, priv);
5142  BN_free(priv);
5143 
5144  if (!result) {
5145  return env->ThrowError("Failed to convert BN to a private key");
5146  }
5147 
5148  // To avoid inconsistency, clear the current public key in-case computing
5149  // the new one fails for some reason.
5150  EC_KEY_set_public_key(ecdh->key_, nullptr);
5151 
5152  MarkPopErrorOnReturn mark_pop_error_on_return;
5153  (void) &mark_pop_error_on_return; // Silence compiler warning.
5154 
5155  const BIGNUM* priv_key = EC_KEY_get0_private_key(ecdh->key_);
5156  CHECK_NE(priv_key, nullptr);
5157 
5158  EC_POINT* pub = EC_POINT_new(ecdh->group_);
5159  CHECK_NE(pub, nullptr);
5160 
5161  if (!EC_POINT_mul(ecdh->group_, pub, priv_key, nullptr, nullptr, nullptr)) {
5162  EC_POINT_free(pub);
5163  return env->ThrowError("Failed to generate ECDH public key");
5164  }
5165 
5166  if (!EC_KEY_set_public_key(ecdh->key_, pub)) {
5167  EC_POINT_free(pub);
5168  return env->ThrowError("Failed to set generated public key");
5169  }
5170 
5171  EC_POINT_free(pub);
5172 }
5173 
5174 
5175 void ECDH::SetPublicKey(const FunctionCallbackInfo<Value>& args) {
5176  Environment* env = Environment::GetCurrent(args);
5177 
5178  ECDH* ecdh;
5179  ASSIGN_OR_RETURN_UNWRAP(&ecdh, args.Holder());
5180 
5181  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Public key");
5182 
5183  MarkPopErrorOnReturn mark_pop_error_on_return;
5184 
5185  EC_POINT* pub = ecdh->BufferToPoint(Buffer::Data(args[0].As<Object>()),
5186  Buffer::Length(args[0].As<Object>()));
5187  if (pub == nullptr)
5188  return env->ThrowError("Failed to convert Buffer to EC_POINT");
5189 
5190  int r = EC_KEY_set_public_key(ecdh->key_, pub);
5191  EC_POINT_free(pub);
5192  if (!r)
5193  return env->ThrowError("Failed to set EC_POINT as the public key");
5194 }
5195 
5196 
5197 bool ECDH::IsKeyValidForCurve(const BIGNUM* private_key) {
5198  CHECK_NE(group_, nullptr);
5199  CHECK_NE(private_key, nullptr);
5200  // Private keys must be in the range [1, n-1].
5201  // Ref: Section 3.2.1 - http://www.secg.org/sec1-v2.pdf
5202  if (BN_cmp(private_key, BN_value_one()) < 0) {
5203  return false;
5204  }
5205  BIGNUM* order = BN_new();
5206  CHECK_NE(order, nullptr);
5207  bool result = EC_GROUP_get_order(group_, order, nullptr) &&
5208  BN_cmp(private_key, order) < 0;
5209  BN_free(order);
5210  return result;
5211 }
5212 
5213 
5214 bool ECDH::IsKeyPairValid() {
5215  MarkPopErrorOnReturn mark_pop_error_on_return;
5216  (void) &mark_pop_error_on_return; // Silence compiler warning.
5217  return 1 == EC_KEY_check_key(key_);
5218 }
5219 
5220 
5221 class PBKDF2Request : public AsyncWrap {
5222  public:
5223  PBKDF2Request(Environment* env,
5224  Local<Object> object,
5225  const EVP_MD* digest,
5226  int passlen,
5227  char* pass,
5228  int saltlen,
5229  char* salt,
5230  int iter,
5231  int keylen)
5232  : AsyncWrap(env, object, AsyncWrap::PROVIDER_PBKDF2REQUEST),
5233  digest_(digest),
5234  success_(false),
5235  passlen_(passlen),
5236  pass_(pass),
5237  saltlen_(saltlen),
5238  salt_(salt),
5239  keylen_(keylen),
5240  key_(node::Malloc(keylen)),
5241  iter_(iter) {
5242  Wrap(object, this);
5243  }
5244 
5245  ~PBKDF2Request() override {
5246  free(pass_);
5247  pass_ = nullptr;
5248  passlen_ = 0;
5249 
5250  free(salt_);
5251  salt_ = nullptr;
5252  saltlen_ = 0;
5253 
5254  free(key_);
5255  key_ = nullptr;
5256  keylen_ = 0;
5257 
5258  ClearWrap(object());
5259  persistent().Reset();
5260  }
5261 
5262  uv_work_t* work_req() {
5263  return &work_req_;
5264  }
5265 
5266  size_t self_size() const override { return sizeof(*this); }
5267 
5268  static void Work(uv_work_t* work_req);
5269  void Work();
5270 
5271  static void After(uv_work_t* work_req, int status);
5272  void After(Local<Value> (*argv)[2]);
5273  void After();
5274 
5275  private:
5276  uv_work_t work_req_;
5277  const EVP_MD* digest_;
5278  bool success_;
5279  int passlen_;
5280  char* pass_;
5281  int saltlen_;
5282  char* salt_;
5283  int keylen_;
5284  char* key_;
5285  int iter_;
5286 };
5287 
5288 
5290  success_ =
5291  PKCS5_PBKDF2_HMAC(
5292  pass_, passlen_, reinterpret_cast<unsigned char*>(salt_), saltlen_,
5293  iter_, digest_, keylen_, reinterpret_cast<unsigned char*>(key_));
5294  OPENSSL_cleanse(pass_, passlen_);
5295  OPENSSL_cleanse(salt_, saltlen_);
5296 }
5297 
5298 
5299 void PBKDF2Request::Work(uv_work_t* work_req) {
5300  PBKDF2Request* req = ContainerOf(&PBKDF2Request::work_req_, work_req);
5301  req->Work();
5302 }
5303 
5304 
5305 void PBKDF2Request::After(Local<Value> (*argv)[2]) {
5306  if (success_) {
5307  (*argv)[0] = Undefined(env()->isolate());
5308  (*argv)[1] = Buffer::New(env(), key_, keylen_).ToLocalChecked();
5309  key_ = nullptr;
5310  keylen_ = 0;
5311  } else {
5312  (*argv)[0] = Exception::Error(env()->pbkdf2_error_string());
5313  (*argv)[1] = Undefined(env()->isolate());
5314  }
5315 }
5316 
5317 
5319  HandleScope handle_scope(env()->isolate());
5320  Context::Scope context_scope(env()->context());
5321  Local<Value> argv[2];
5322  After(&argv);
5323  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
5324 }
5325 
5326 
5327 void PBKDF2Request::After(uv_work_t* work_req, int status) {
5328  CHECK_EQ(status, 0);
5329  PBKDF2Request* req = ContainerOf(&PBKDF2Request::work_req_, work_req);
5330  req->After();
5331  delete req;
5332 }
5333 
5334 
5335 void PBKDF2(const FunctionCallbackInfo<Value>& args) {
5336  Environment* env = Environment::GetCurrent(args);
5337 
5338  const EVP_MD* digest = nullptr;
5339  const char* type_error = nullptr;
5340  char* pass = nullptr;
5341  char* salt = nullptr;
5342  int passlen = -1;
5343  int saltlen = -1;
5344  double raw_keylen = -1;
5345  int keylen = -1;
5346  int iter = -1;
5347  PBKDF2Request* req = nullptr;
5348  Local<Object> obj;
5349 
5350  if (args.Length() != 5 && args.Length() != 6) {
5351  type_error = "Bad parameter";
5352  goto err;
5353  }
5354 
5355  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Pass phrase");
5356  passlen = Buffer::Length(args[0]);
5357  if (passlen < 0) {
5358  type_error = "Bad password";
5359  goto err;
5360  }
5361 
5362  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Salt");
5363 
5364  pass = node::Malloc(passlen);
5365  memcpy(pass, Buffer::Data(args[0]), passlen);
5366 
5367  saltlen = Buffer::Length(args[1]);
5368  if (saltlen < 0) {
5369  type_error = "Bad salt";
5370  goto err;
5371  }
5372 
5373  salt = node::Malloc(saltlen);
5374  memcpy(salt, Buffer::Data(args[1]), saltlen);
5375 
5376  if (!args[2]->IsNumber()) {
5377  type_error = "Iterations not a number";
5378  goto err;
5379  }
5380 
5381  iter = args[2]->Int32Value();
5382  if (iter < 0) {
5383  type_error = "Bad iterations";
5384  goto err;
5385  }
5386 
5387  if (!args[3]->IsNumber()) {
5388  type_error = "Key length not a number";
5389  goto err;
5390  }
5391 
5392  raw_keylen = args[3]->NumberValue();
5393  if (raw_keylen < 0.0 || isnan(raw_keylen) || isinf(raw_keylen) ||
5394  raw_keylen > INT_MAX) {
5395  type_error = "Bad key length";
5396  goto err;
5397  }
5398 
5399  keylen = static_cast<int>(raw_keylen);
5400 
5401  if (args[4]->IsString()) {
5402  node::Utf8Value digest_name(env->isolate(), args[4]);
5403  digest = EVP_get_digestbyname(*digest_name);
5404  if (digest == nullptr) {
5405  type_error = "Bad digest name";
5406  goto err;
5407  }
5408  }
5409 
5410  if (digest == nullptr) {
5411  digest = EVP_sha1();
5412  }
5413 
5414  obj = env->pbkdf2_constructor_template()->
5415  NewInstance(env->context()).ToLocalChecked();
5416  req = new PBKDF2Request(env,
5417  obj,
5418  digest,
5419  passlen,
5420  pass,
5421  saltlen,
5422  salt,
5423  iter,
5424  keylen);
5425 
5426  if (args[5]->IsFunction()) {
5427  obj->Set(env->ondone_string(), args[5]);
5428 
5429  if (env->in_domain()) {
5430  obj->Set(env->context(),
5431  env->domain_string(),
5432  env->domain_array()->Get(env->context(), 0).ToLocalChecked())
5433  .FromJust();
5434  }
5435 
5436  uv_queue_work(env->event_loop(),
5437  req->work_req(),
5440  } else {
5441  env->PrintSyncTrace();
5442  req->Work();
5443  Local<Value> argv[2];
5444  req->After(&argv);
5445  delete req;
5446 
5447  if (argv[0]->IsObject())
5448  env->isolate()->ThrowException(argv[0]);
5449  else
5450  args.GetReturnValue().Set(argv[1]);
5451  }
5452  return;
5453 
5454  err:
5455  free(salt);
5456  free(pass);
5457  return env->ThrowTypeError(type_error);
5458 }
5459 
5460 
5461 // Only instantiate within a valid HandleScope.
5462 class RandomBytesRequest : public AsyncWrap {
5463  public:
5464  enum FreeMode { FREE_DATA, DONT_FREE_DATA };
5465 
5466  RandomBytesRequest(Environment* env,
5467  Local<Object> object,
5468  size_t size,
5469  char* data,
5470  FreeMode free_mode)
5471  : AsyncWrap(env, object, AsyncWrap::PROVIDER_RANDOMBYTESREQUEST),
5472  error_(0),
5473  size_(size),
5474  data_(data),
5475  free_mode_(free_mode) {
5476  Wrap(object, this);
5477  }
5478 
5479  ~RandomBytesRequest() override {
5480  ClearWrap(object());
5481  persistent().Reset();
5482  }
5483 
5484  uv_work_t* work_req() {
5485  return &work_req_;
5486  }
5487 
5488  inline size_t size() const {
5489  return size_;
5490  }
5491 
5492  inline char* data() const {
5493  return data_;
5494  }
5495 
5496  inline void set_data(char* data) {
5497  data_ = data;
5498  }
5499 
5500  inline void release() {
5501  size_ = 0;
5502  if (free_mode_ == FREE_DATA) {
5503  free(data_);
5504  data_ = nullptr;
5505  }
5506  }
5507 
5508  inline void return_memory(char** d, size_t* len) {
5509  *d = data_;
5510  data_ = nullptr;
5511  *len = size_;
5512  size_ = 0;
5513  }
5514 
5515  inline unsigned long error() const { // NOLINT(runtime/int)
5516  return error_;
5517  }
5518 
5519  inline void set_error(unsigned long err) { // NOLINT(runtime/int)
5520  error_ = err;
5521  }
5522 
5523  size_t self_size() const override { return sizeof(*this); }
5524 
5525  uv_work_t work_req_;
5526 
5527  private:
5528  unsigned long error_; // NOLINT(runtime/int)
5529  size_t size_;
5530  char* data_;
5531  const FreeMode free_mode_;
5532 };
5533 
5534 
5535 void RandomBytesWork(uv_work_t* work_req) {
5537  ContainerOf(&RandomBytesRequest::work_req_, work_req);
5538 
5539  // Ensure that OpenSSL's PRNG is properly seeded.
5540  CheckEntropy();
5541 
5542  const int r = RAND_bytes(reinterpret_cast<unsigned char*>(req->data()),
5543  req->size());
5544 
5545  // RAND_bytes() returns 0 on error.
5546  if (r == 0) {
5547  req->set_error(ERR_get_error()); // NOLINT(runtime/int)
5548  } else if (r == -1) {
5549  req->set_error(static_cast<unsigned long>(-1)); // NOLINT(runtime/int)
5550  }
5551 }
5552 
5553 
5554 // don't call this function without a valid HandleScope
5555 void RandomBytesCheck(RandomBytesRequest* req, Local<Value> (*argv)[2]) {
5556  if (req->error()) {
5557  char errmsg[256] = "Operation not supported";
5558 
5559  if (req->error() != static_cast<unsigned long>(-1)) // NOLINT(runtime/int)
5560  ERR_error_string_n(req->error(), errmsg, sizeof errmsg);
5561 
5562  (*argv)[0] = Exception::Error(OneByteString(req->env()->isolate(), errmsg));
5563  (*argv)[1] = Null(req->env()->isolate());
5564  req->release();
5565  } else {
5566  char* data = nullptr;
5567  size_t size;
5568  req->return_memory(&data, &size);
5569  (*argv)[0] = Null(req->env()->isolate());
5570  Local<Value> buffer =
5571  req->object()->Get(req->env()->context(),
5572  req->env()->buffer_string()).ToLocalChecked();
5573 
5574  if (buffer->IsUint8Array()) {
5575  CHECK_LE(req->size(), Buffer::Length(buffer));
5576  char* buf = Buffer::Data(buffer);
5577  memcpy(buf, data, req->size());
5578  (*argv)[1] = buffer;
5579  } else {
5580  (*argv)[1] = Buffer::New(req->env(), data, size).ToLocalChecked();
5581  }
5582  }
5583 }
5584 
5585 
5586 void RandomBytesAfter(uv_work_t* work_req, int status) {
5587  CHECK_EQ(status, 0);
5588  RandomBytesRequest* req =
5589  ContainerOf(&RandomBytesRequest::work_req_, work_req);
5590  Environment* env = req->env();
5591  HandleScope handle_scope(env->isolate());
5592  Context::Scope context_scope(env->context());
5593  Local<Value> argv[2];
5594  RandomBytesCheck(req, &argv);
5595  req->MakeCallback(env->ondone_string(), arraysize(argv), argv);
5596  delete req;
5597 }
5598 
5599 
5600 void RandomBytesProcessSync(Environment* env,
5601  RandomBytesRequest* req,
5602  Local<Value> (*argv)[2]) {
5603  env->PrintSyncTrace();
5604  RandomBytesWork(req->work_req());
5605  RandomBytesCheck(req, argv);
5606  delete req;
5607 
5608  if (!(*argv)[0]->IsNull())
5609  env->isolate()->ThrowException((*argv)[0]);
5610 }
5611 
5612 
5613 void RandomBytes(const FunctionCallbackInfo<Value>& args) {
5614  Environment* env = Environment::GetCurrent(args);
5615 
5616  if (!args[0]->IsUint32()) {
5617  return env->ThrowTypeError("size must be a number >= 0");
5618  }
5619 
5620  const int64_t size = args[0]->IntegerValue();
5621  if (size < 0 || size > Buffer::kMaxLength)
5622  return env->ThrowRangeError("size is not a valid Smi");
5623 
5624  Local<Object> obj = env->randombytes_constructor_template()->
5625  NewInstance(env->context()).ToLocalChecked();
5626  char* data = node::Malloc(size);
5627  RandomBytesRequest* req =
5628  new RandomBytesRequest(env,
5629  obj,
5630  size,
5631  data,
5633 
5634  if (args[1]->IsFunction()) {
5635  obj->Set(env->ondone_string(), args[1]);
5636 
5637  if (env->in_domain()) {
5638  obj->Set(env->context(),
5639  env->domain_string(),
5640  env->domain_array()->Get(env->context(), 0).ToLocalChecked())
5641  .FromJust();
5642  }
5643 
5644  uv_queue_work(env->event_loop(),
5645  req->work_req(),
5648  args.GetReturnValue().Set(obj);
5649  } else {
5650  Local<Value> argv[2];
5651  RandomBytesProcessSync(env, req, &argv);
5652  if (argv[0]->IsNull())
5653  args.GetReturnValue().Set(argv[1]);
5654  }
5655 }
5656 
5657 
5658 void RandomBytesBuffer(const FunctionCallbackInfo<Value>& args) {
5659  Environment* env = Environment::GetCurrent(args);
5660 
5661  CHECK(args[0]->IsUint8Array());
5662  CHECK(args[1]->IsUint32());
5663  CHECK(args[2]->IsUint32());
5664 
5665  int64_t offset = args[1]->IntegerValue();
5666  int64_t size = args[2]->IntegerValue();
5667 
5668  Local<Object> obj = env->randombytes_constructor_template()->
5669  NewInstance(env->context()).ToLocalChecked();
5670  obj->Set(env->context(), env->buffer_string(), args[0]).FromJust();
5671  char* data = Buffer::Data(args[0]);
5672  data += offset;
5673 
5674  RandomBytesRequest* req =
5675  new RandomBytesRequest(env,
5676  obj,
5677  size,
5678  data,
5680  if (args[3]->IsFunction()) {
5681  obj->Set(env->context(), env->ondone_string(), args[3]).FromJust();
5682 
5683  if (env->in_domain()) {
5684  obj->Set(env->context(),
5685  env->domain_string(),
5686  env->domain_array()->Get(env->context(), 0).ToLocalChecked())
5687  .FromJust();
5688  }
5689 
5690  uv_queue_work(env->event_loop(),
5691  req->work_req(),
5694  args.GetReturnValue().Set(obj);
5695  } else {
5696  Local<Value> argv[2];
5697  RandomBytesProcessSync(env, req, &argv);
5698  if (argv[0]->IsNull())
5699  args.GetReturnValue().Set(argv[1]);
5700  }
5701 }
5702 
5703 
5704 void GetSSLCiphers(const FunctionCallbackInfo<Value>& args) {
5705  Environment* env = Environment::GetCurrent(args);
5706 
5707  SSL_CTX* ctx = SSL_CTX_new(TLSv1_server_method());
5708  if (ctx == nullptr) {
5709  return env->ThrowError("SSL_CTX_new() failed.");
5710  }
5711 
5712  SSL* ssl = SSL_new(ctx);
5713  if (ssl == nullptr) {
5714  SSL_CTX_free(ctx);
5715  return env->ThrowError("SSL_new() failed.");
5716  }
5717 
5718  Local<Array> arr = Array::New(env->isolate());
5719  STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl);
5720 
5721  for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
5722  const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
5723  arr->Set(i, OneByteString(args.GetIsolate(), SSL_CIPHER_get_name(cipher)));
5724  }
5725 
5726  SSL_free(ssl);
5727  SSL_CTX_free(ctx);
5728 
5729  args.GetReturnValue().Set(arr);
5730 }
5731 
5732 
5734  public:
5735  explicit CipherPushContext(Environment* env)
5736  : arr(Array::New(env->isolate())),
5737  env_(env) {
5738  }
5739 
5740  inline Environment* env() const { return env_; }
5741 
5742  Local<Array> arr;
5743 
5744  private:
5745  Environment* env_;
5746 };
5747 
5748 
5749 template <class TypeName>
5750 static void array_push_back(const TypeName* md,
5751  const char* from,
5752  const char* to,
5753  void* arg) {
5754  CipherPushContext* ctx = static_cast<CipherPushContext*>(arg);
5755  ctx->arr->Set(ctx->arr->Length(), OneByteString(ctx->env()->isolate(), from));
5756 }
5757 
5758 
5759 void GetCiphers(const FunctionCallbackInfo<Value>& args) {
5760  Environment* env = Environment::GetCurrent(args);
5761  CipherPushContext ctx(env);
5762  EVP_CIPHER_do_all_sorted(array_push_back<EVP_CIPHER>, &ctx);
5763  args.GetReturnValue().Set(ctx.arr);
5764 }
5765 
5766 
5767 void GetHashes(const FunctionCallbackInfo<Value>& args) {
5768  Environment* env = Environment::GetCurrent(args);
5769  CipherPushContext ctx(env);
5770  EVP_MD_do_all_sorted(array_push_back<EVP_MD>, &ctx);
5771  args.GetReturnValue().Set(ctx.arr);
5772 }
5773 
5774 
5775 void GetCurves(const FunctionCallbackInfo<Value>& args) {
5776  Environment* env = Environment::GetCurrent(args);
5777  const size_t num_curves = EC_get_builtin_curves(nullptr, 0);
5778  Local<Array> arr = Array::New(env->isolate(), num_curves);
5779  EC_builtin_curve* curves;
5780 
5781  if (num_curves) {
5782  curves = node::Malloc<EC_builtin_curve>(num_curves);
5783 
5784  if (EC_get_builtin_curves(curves, num_curves)) {
5785  for (size_t i = 0; i < num_curves; i++) {
5786  arr->Set(i, OneByteString(env->isolate(), OBJ_nid2sn(curves[i].nid)));
5787  }
5788  }
5789 
5790  free(curves);
5791  }
5792 
5793  args.GetReturnValue().Set(arr);
5794 }
5795 
5796 
5797 bool VerifySpkac(const char* data, unsigned int len) {
5798  bool i = 0;
5799  EVP_PKEY* pkey = nullptr;
5800  NETSCAPE_SPKI* spki = nullptr;
5801 
5802  spki = NETSCAPE_SPKI_b64_decode(data, len);
5803  if (spki == nullptr)
5804  goto exit;
5805 
5806  pkey = X509_PUBKEY_get(spki->spkac->pubkey);
5807  if (pkey == nullptr)
5808  goto exit;
5809 
5810  i = NETSCAPE_SPKI_verify(spki, pkey) > 0;
5811 
5812  exit:
5813  if (pkey != nullptr)
5814  EVP_PKEY_free(pkey);
5815 
5816  if (spki != nullptr)
5817  NETSCAPE_SPKI_free(spki);
5818 
5819  return i;
5820 }
5821 
5822 
5823 void VerifySpkac(const FunctionCallbackInfo<Value>& args) {
5824  Environment* env = Environment::GetCurrent(args);
5825  bool i = false;
5826 
5827  if (args.Length() < 1)
5828  return env->ThrowTypeError("Data argument is mandatory");
5829 
5830  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Data");
5831 
5832  size_t length = Buffer::Length(args[0]);
5833  if (length == 0)
5834  return args.GetReturnValue().Set(i);
5835 
5836  char* data = Buffer::Data(args[0]);
5837  CHECK_NE(data, nullptr);
5838 
5839  i = VerifySpkac(data, length);
5840 
5841  args.GetReturnValue().Set(i);
5842 }
5843 
5844 
5845 char* ExportPublicKey(const char* data, int len, size_t* size) {
5846  char* buf = nullptr;
5847  EVP_PKEY* pkey = nullptr;
5848  NETSCAPE_SPKI* spki = nullptr;
5849 
5850  BIO* bio = BIO_new(BIO_s_mem());
5851  if (bio == nullptr)
5852  goto exit;
5853 
5854  spki = NETSCAPE_SPKI_b64_decode(data, len);
5855  if (spki == nullptr)
5856  goto exit;
5857 
5858  pkey = NETSCAPE_SPKI_get_pubkey(spki);
5859  if (pkey == nullptr)
5860  goto exit;
5861 
5862  if (PEM_write_bio_PUBKEY(bio, pkey) <= 0)
5863  goto exit;
5864 
5865  BUF_MEM* ptr;
5866  BIO_get_mem_ptr(bio, &ptr);
5867 
5868  *size = ptr->length;
5869  buf = Malloc(*size);
5870  memcpy(buf, ptr->data, *size);
5871 
5872  exit:
5873  if (pkey != nullptr)
5874  EVP_PKEY_free(pkey);
5875 
5876  if (spki != nullptr)
5877  NETSCAPE_SPKI_free(spki);
5878 
5879  if (bio != nullptr)
5880  BIO_free_all(bio);
5881 
5882  return buf;
5883 }
5884 
5885 
5886 void ExportPublicKey(const FunctionCallbackInfo<Value>& args) {
5887  Environment* env = Environment::GetCurrent(args);
5888 
5889  if (args.Length() < 1)
5890  return env->ThrowTypeError("Public key argument is mandatory");
5891 
5892  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Public key");
5893 
5894  size_t length = Buffer::Length(args[0]);
5895  if (length == 0)
5896  return args.GetReturnValue().SetEmptyString();
5897 
5898  char* data = Buffer::Data(args[0]);
5899  CHECK_NE(data, nullptr);
5900 
5901  size_t pkey_size;
5902  char* pkey = ExportPublicKey(data, length, &pkey_size);
5903  if (pkey == nullptr)
5904  return args.GetReturnValue().SetEmptyString();
5905 
5906  Local<Value> out = Buffer::New(env, pkey, pkey_size).ToLocalChecked();
5907  args.GetReturnValue().Set(out);
5908 }
5909 
5910 
5911 const char* ExportChallenge(const char* data, int len) {
5912  NETSCAPE_SPKI* sp = nullptr;
5913 
5914  sp = NETSCAPE_SPKI_b64_decode(data, len);
5915  if (sp == nullptr)
5916  return nullptr;
5917 
5918  unsigned char* buf = nullptr;
5919  ASN1_STRING_to_UTF8(&buf, sp->spkac->challenge);
5920 
5921  NETSCAPE_SPKI_free(sp);
5922 
5923  return reinterpret_cast<const char*>(buf);
5924 }
5925 
5926 
5927 void ExportChallenge(const FunctionCallbackInfo<Value>& args) {
5928  Environment* env = Environment::GetCurrent(args);
5929 
5930  if (args.Length() < 1)
5931  return env->ThrowTypeError("Challenge argument is mandatory");
5932 
5933  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Challenge");
5934 
5935  size_t len = Buffer::Length(args[0]);
5936  if (len == 0)
5937  return args.GetReturnValue().SetEmptyString();
5938 
5939  char* data = Buffer::Data(args[0]);
5940  CHECK_NE(data, nullptr);
5941 
5942  const char* cert = ExportChallenge(data, len);
5943  if (cert == nullptr)
5944  return args.GetReturnValue().SetEmptyString();
5945 
5946  Local<Value> outString = Encode(env->isolate(), cert, strlen(cert), BUFFER);
5947 
5948  OPENSSL_free(const_cast<char*>(cert));
5949 
5950  args.GetReturnValue().Set(outString);
5951 }
5952 
5953 void TimingSafeEqual(const FunctionCallbackInfo<Value>& args) {
5954  Environment* env = Environment::GetCurrent(args);
5955 
5956  THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "First argument");
5957  THROW_AND_RETURN_IF_NOT_BUFFER(args[1], "Second argument");
5958 
5959  size_t buf_length = Buffer::Length(args[0]);
5960  if (buf_length != Buffer::Length(args[1])) {
5961  return env->ThrowTypeError("Input buffers must have the same length");
5962  }
5963 
5964  const char* buf1 = Buffer::Data(args[0]);
5965  const char* buf2 = Buffer::Data(args[1]);
5966 
5967  return args.GetReturnValue().Set(CRYPTO_memcmp(buf1, buf2, buf_length) == 0);
5968 }
5969 
5971  SSL_load_error_strings();
5972  OPENSSL_no_config();
5973 
5974  // --openssl-config=...
5975  if (!openssl_config.empty()) {
5976  OPENSSL_load_builtin_modules();
5977 #ifndef OPENSSL_NO_ENGINE
5978  ENGINE_load_builtin_engines();
5979 #endif
5980  ERR_clear_error();
5981  CONF_modules_load_file(
5982  openssl_config.c_str(),
5983  nullptr,
5984  CONF_MFLAGS_DEFAULT_SECTION);
5985  int err = ERR_get_error();
5986  if (0 != err) {
5987  fprintf(stderr,
5988  "openssl config failed: %s\n",
5989  ERR_error_string(err, NULL));
5990  CHECK_NE(err, 0);
5991  }
5992  }
5993 
5994  SSL_library_init();
5995  OpenSSL_add_all_algorithms();
5996 
5997  crypto_lock_init();
5998  CRYPTO_set_locking_callback(crypto_lock_cb);
5999  CRYPTO_THREADID_set_callback(crypto_threadid_cb);
6000 
6001 #ifdef NODE_FIPS_MODE
6002  /* Override FIPS settings in cnf file, if needed. */
6003  unsigned long err = 0; // NOLINT(runtime/int)
6004  if (enable_fips_crypto || force_fips_crypto) {
6005  if (0 == FIPS_mode() && !FIPS_mode_set(1)) {
6006  err = ERR_get_error();
6007  }
6008  }
6009  if (0 != err) {
6010  fprintf(stderr, "openssl fips failed: %s\n", ERR_error_string(err, NULL));
6011  UNREACHABLE();
6012  }
6013 #endif // NODE_FIPS_MODE
6014 
6015 
6016  // Turn off compression. Saves memory and protects against CRIME attacks.
6017  // No-op with OPENSSL_NO_COMP builds of OpenSSL.
6018  sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
6019 
6020 #ifndef OPENSSL_NO_ENGINE
6021  ERR_load_ENGINE_strings();
6022  ENGINE_load_builtin_engines();
6023 #endif // !OPENSSL_NO_ENGINE
6024 }
6025 
6026 
6027 #ifndef OPENSSL_NO_ENGINE
6028 void SetEngine(const FunctionCallbackInfo<Value>& args) {
6029  Environment* env = Environment::GetCurrent(args);
6030  CHECK(args.Length() >= 2 && args[0]->IsString());
6031  unsigned int flags = args[1]->Uint32Value();
6032 
6033  ClearErrorOnReturn clear_error_on_return;
6034 
6035  const node::Utf8Value engine_id(env->isolate(), args[0]);
6036  ENGINE* engine = ENGINE_by_id(*engine_id);
6037 
6038  // Engine not found, try loading dynamically
6039  if (engine == nullptr) {
6040  engine = ENGINE_by_id("dynamic");
6041  if (engine != nullptr) {
6042  if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", *engine_id, 0) ||
6043  !ENGINE_ctrl_cmd_string(engine, "LOAD", nullptr, 0)) {
6044  ENGINE_free(engine);
6045  engine = nullptr;
6046  }
6047  }
6048  }
6049 
6050  if (engine == nullptr) {
6051  int err = ERR_get_error();
6052  if (err == 0) {
6053  char tmp[1024];
6054  snprintf(tmp, sizeof(tmp), "Engine \"%s\" was not found", *engine_id);
6055  return env->ThrowError(tmp);
6056  } else {
6057  return ThrowCryptoError(env, err);
6058  }
6059  }
6060 
6061  int r = ENGINE_set_default(engine, flags);
6062  ENGINE_free(engine);
6063  if (r == 0)
6064  return ThrowCryptoError(env, ERR_get_error());
6065 }
6066 #endif // !OPENSSL_NO_ENGINE
6067 
6068 void GetFipsCrypto(const FunctionCallbackInfo<Value>& args) {
6069  if (FIPS_mode()) {
6070  args.GetReturnValue().Set(1);
6071  } else {
6072  args.GetReturnValue().Set(0);
6073  }
6074 }
6075 
6076 void SetFipsCrypto(const FunctionCallbackInfo<Value>& args) {
6077  Environment* env = Environment::GetCurrent(args);
6078 #ifdef NODE_FIPS_MODE
6079  bool mode = args[0]->BooleanValue();
6080  if (force_fips_crypto) {
6081  return env->ThrowError(
6082  "Cannot set FIPS mode, it was forced with --force-fips at startup.");
6083  } else if (!FIPS_mode_set(mode)) {
6084  unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
6085  return ThrowCryptoError(env, err);
6086  }
6087 #else
6088  return env->ThrowError("Cannot set FIPS mode in a non-FIPS build.");
6089 #endif /* NODE_FIPS_MODE */
6090 }
6091 
6092 void InitCrypto(Local<Object> target,
6093  Local<Value> unused,
6094  Local<Context> context,
6095  void* priv) {
6096  static uv_once_t init_once = UV_ONCE_INIT;
6097  uv_once(&init_once, InitCryptoOnce);
6098 
6099  Environment* env = Environment::GetCurrent(context);
6100  SecureContext::Initialize(env, target);
6101  Connection::Initialize(env, target);
6102  CipherBase::Initialize(env, target);
6103  DiffieHellman::Initialize(env, target);
6104  ECDH::Initialize(env, target);
6105  Hmac::Initialize(env, target);
6106  Hash::Initialize(env, target);
6107  Sign::Initialize(env, target);
6108  Verify::Initialize(env, target);
6109 
6110  env->SetMethod(target, "certVerifySpkac", VerifySpkac);
6111  env->SetMethod(target, "certExportPublicKey", ExportPublicKey);
6112  env->SetMethod(target, "certExportChallenge", ExportChallenge);
6113 #ifndef OPENSSL_NO_ENGINE
6114  env->SetMethod(target, "setEngine", SetEngine);
6115 #endif // !OPENSSL_NO_ENGINE
6116  env->SetMethod(target, "getFipsCrypto", GetFipsCrypto);
6117  env->SetMethod(target, "setFipsCrypto", SetFipsCrypto);
6118  env->SetMethod(target, "PBKDF2", PBKDF2);
6119  env->SetMethod(target, "randomBytes", RandomBytes);
6120  env->SetMethod(target, "randomFill", RandomBytesBuffer);
6121  env->SetMethod(target, "timingSafeEqual", TimingSafeEqual);
6122  env->SetMethod(target, "getSSLCiphers", GetSSLCiphers);
6123  env->SetMethod(target, "getCiphers", GetCiphers);
6124  env->SetMethod(target, "getHashes", GetHashes);
6125  env->SetMethod(target, "getCurves", GetCurves);
6126  env->SetMethod(target, "publicEncrypt",
6127  PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
6128  EVP_PKEY_encrypt_init,
6129  EVP_PKEY_encrypt>);
6130  env->SetMethod(target, "privateDecrypt",
6131  PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
6132  EVP_PKEY_decrypt_init,
6133  EVP_PKEY_decrypt>);
6134  env->SetMethod(target, "privateEncrypt",
6135  PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate,
6136  EVP_PKEY_sign_init,
6137  EVP_PKEY_sign>);
6138  env->SetMethod(target, "publicDecrypt",
6139  PublicKeyCipher::Cipher<PublicKeyCipher::kPublic,
6140  EVP_PKEY_verify_recover_init,
6141  EVP_PKEY_verify_recover>);
6142 
6143  Local<FunctionTemplate> pb = FunctionTemplate::New(env->isolate());
6144  pb->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "PBKDF2"));
6145  AsyncWrap::AddWrapMethods(env, pb);
6146  Local<ObjectTemplate> pbt = pb->InstanceTemplate();
6147  pbt->SetInternalFieldCount(1);
6148  env->set_pbkdf2_constructor_template(pbt);
6149 
6150  Local<FunctionTemplate> rb = FunctionTemplate::New(env->isolate());
6151  rb->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "RandomBytes"));
6152  AsyncWrap::AddWrapMethods(env, rb);
6153  Local<ObjectTemplate> rbt = rb->InstanceTemplate();
6154  rbt->SetInternalFieldCount(1);
6155  env->set_randombytes_constructor_template(rbt);
6156 }
6157 
6158 } // namespace crypto
6159 } // namespace node
6160 
this func
Definition: v8ustack.d:371
uv_file file
Definition: module_wrap.cc:328
void set_error(unsigned long err)
PBKDF2Request(Environment *env, Local< Object > object, const EVP_MD *digest, int passlen, char *pass, int saltlen, char *salt, int iter, int keylen)
void GetSSLCiphers(const FunctionCallbackInfo< Value > &args)
void PBKDF2(const FunctionCallbackInfo< Value > &args)
CheckResult CheckWhitelistedServerCert(X509_STORE_CTX *ctx)
void InitCryptoOnce()
void GetFipsCrypto(const FunctionCallbackInfo< Value > &args)
size_t self_size() const override
bool HasInstance(Local< Value > val)
Definition: node_buffer.cc:201
unsigned char * buf
Definition: cares_wrap.cc:483
void GetHashes(const FunctionCallbackInfo< Value > &args)
bool CheckStartComOrWoSign(X509_NAME *root_name, X509 *cert)
NODE_MODULE_CONTEXT_AWARE_BUILTIN(inspector, node::inspector::Agent::InitInspector)
void RandomBytesAfter(uv_work_t *work_req, int status)
void RandomBytesBuffer(const FunctionCallbackInfo< Value > &args)
void SetEngine(const FunctionCallbackInfo< Value > &args)
char * ExportPublicKey(const char *data, int len, size_t *size)
int len
Definition: cares_wrap.cc:485
void ProcessEmitWarning(Environment *env, const char *fmt,...)
Definition: node.cc:2707
RandomBytesRequest(Environment *env, Local< Object > object, size_t size, char *data, FreeMode free_mode)
QueryWrap * wrap
Definition: cares_wrap.cc:478
Environment *const env_
bool CertIsStartComOrWoSign(X509_NAME *name)
int status
Definition: cares_wrap.cc:479
union node::cares_wrap::@8::CaresAsyncData::@0 data
#define THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(val, prefix)
Definition: node_crypto.cc:54
const char * ExportChallenge(const char *data, int len)
void InitCrypto(Local< Object > target, Local< Value > unused, Local< Context > context, void *priv)
int SSL_CTX_get_issuer(SSL_CTX *ctx, X509 *cert, X509 **issuer)
Definition: node_crypto.cc:523
void RandomBytesProcessSync(Environment *env, RandomBytesRequest *req, Local< Value >(*argv)[2])
void return_memory(char **d, size_t *len)
#define THROW_AND_RETURN_IF_NOT_BUFFER(val, prefix)
Definition: node_crypto.cc:61
void UseExtraCaCerts(const std::string &file)
Definition: node_crypto.cc:837
size_t Length(Local< Value > val)
Definition: node_buffer.cc:227
CipherPushContext(Environment *env)
this done
Definition: v8ustack.d:366
dtrace a
Definition: v8ustack.d:531
void Initialize(Local< Object > target, Local< Value > unused, Local< Context > context, void *priv)
Definition: node_http2.cc:1172
#define THROW_AND_RETURN_IF_NOT_STRING(val, prefix)
Definition: node_crypto.cc:68
encoding
Definition: node.h:322
void GetCiphers(const FunctionCallbackInfo< Value > &args)
char * Data(Local< Value > val)
Definition: node_buffer.cc:211
int SSL_CTX_use_certificate_chain(SSL_CTX *ctx, X509 *x, STACK_OF(X509) *extra_certs, X509 **cert, X509 **issuer)
Definition: node_crypto.cc:541
dtrace p
Definition: v8ustack.d:615
size_t self_size() const override
dtrace s
Definition: v8ustack.d:615
void ThrowCryptoError(Environment *env, unsigned long err, const char *default_message=nullptr)
Definition: node_crypto.cc:254
dtrace t
Definition: v8ustack.d:582
void TimingSafeEqual(const FunctionCallbackInfo< Value > &args)
#define DEBUG_PRINT(...)
int VerifyCallback(int preverify_ok, X509_STORE_CTX *ctx)
enum encoding ParseEncoding(const char *encoding, enum encoding default_encoding)
Definition: node.cc:1485
static void After(uv_work_t *work_req, int status)
uv_fs_t req
Definition: node_file.cc:374
X509 * FindRoot(STACK_OF(X509) *sk)
size_t size_
Environment * env() const
MaybeLocal< Object > New(Isolate *isolate, Local< String > string, enum encoding enc)
Definition: node_buffer.cc:241
method
Definition: node.d:195
MaybeLocal< Value > MakeCallback(Isolate *isolate, Local< Object > recv, Local< Function > callback, int argc, Local< Value > *argv, async_id asyncId, async_id triggerAsyncId)
Definition: async-wrap.cc:802
#define CASE_X509_ERR(CODE)
void CheckEntropy()
Definition: node_crypto.cc:288
void SetFipsCrypto(const FunctionCallbackInfo< Value > &args)
void GetCurves(const FunctionCallbackInfo< Value > &args)
static void Work(uv_work_t *work_req)
dtrace n
Definition: v8ustack.d:531
void RandomBytesWork(uv_work_t *work_req)
int IsSelfSigned(X509 *cert)
void RandomBytes(const FunctionCallbackInfo< Value > &args)
unsigned long error() const
this ctx
Definition: v8ustack.d:369
void RandomBytesCheck(RandomBytesRequest *req, Local< Value >(*argv)[2])
bool EntropySource(unsigned char *buffer, size_t length)
Definition: node_crypto.cc:302
bool VerifySpkac(const char *data, unsigned int len)
int Start(Isolate *isolate, IsolateData *isolate_data, int argc, const char *const *argv, int exec_argc, const char *const *exec_argv)
Definition: node.cc:4536
void Init(int *argc, const char **argv, int *exec_argc, const char ***exec_argv)
Definition: node.cc:4351
NODE_DEPRECATED("Use ParseEncoding(isolate, ...)", inline enum encoding ParseEncoding(v8::Local< v8::Value > encoding_v, enum encoding default_encoding=LATIN1) { return ParseEncoding(v8::Isolate::GetCurrent(), encoding_v, default_encoding);}) NODE_EXTERN void FatalException(v8 NODE_DEPRECATED("Use FatalException(isolate, ...)", inline void FatalException(const v8::TryCatch &try_catch) { return FatalException(v8::Isolate::GetCurrent(), try_catch);}) NODE_EXTERN v8 NODE_EXTERN v8::Local< v8::Value > Encode(v8::Isolate *isolate, const uint16_t *buf, size_t len)
Definition: node.h:350
MaybeLocal< Object > Copy(Isolate *isolate, const char *data, size_t length)
Definition: node_buffer.cc:320
int compar(const void *a, const void *b)
this off
Definition: v8ustack.d:365