From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Shelley Vohr <shelley.vohr@gmail.com>
Date: Wed, 12 Feb 2020 15:08:04 -0800
Subject: fix: handle BoringSSL and OpenSSL incompatibilities

This patch corrects for imcompatibilities between OpenSSL, which Node.js uses,
and BoringSSL which Electron uses via Chromium. Each incompatibility typically has
~2 paths forward:
* Upstream a shim or adapted implementation to BoringSSL
* Alter Node.js functionality to something which both libraries can handle.

Where possible, we should seek to make this patch as minimal as possible.

Upstreams:
- https://github.com/nodejs/node/pull/39054
- https://github.com/nodejs/node/pull/39138
- https://github.com/nodejs/node/pull/39136

diff --git a/src/crypto/crypto_cipher.cc b/src/crypto/crypto_cipher.cc
index 2685f5ea0bea998094453a5a29d23b1aaae55667..0ad4ba47b50a87bcf9e31a73c20a3a51be4ab96e 100644
--- a/src/crypto/crypto_cipher.cc
+++ b/src/crypto/crypto_cipher.cc
@@ -27,7 +27,8 @@ using v8::Value;
 namespace crypto {
 namespace {
 bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
-  switch (EVP_CIPHER_mode(cipher)) {
+  const int mode = EVP_CIPHER_mode(cipher);
+  switch (mode) {
   case EVP_CIPH_CCM_MODE:
   case EVP_CIPH_GCM_MODE:
 #ifndef OPENSSL_NO_OCB
diff --git a/src/crypto/crypto_common.cc b/src/crypto/crypto_common.cc
index a1d0dfc16ce23503b0985ec6e185fb54758c8893..85daa8c8c12c28571f0ee739868549335cb1f730 100644
--- a/src/crypto/crypto_common.cc
+++ b/src/crypto/crypto_common.cc
@@ -159,7 +159,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) {
   const unsigned char* buf;
   size_t len;
   size_t rem;
-
+#ifndef OPENSSL_IS_BORINGSSL
   if (!SSL_client_hello_get0_ext(
           ssl.get(),
           TLSEXT_TYPE_application_layer_protocol_negotiation,
@@ -172,13 +172,15 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) {
   len = (buf[0] << 8) | buf[1];
   if (len + 2 != rem) return nullptr;
   return reinterpret_cast<const char*>(buf + 3);
+#endif
+  return nullptr;
 }
 
 const char* GetClientHelloServerName(const SSLPointer& ssl) {
   const unsigned char* buf;
   size_t len;
   size_t rem;
-
+#ifndef OPENSSL_IS_BORINGSSL
   if (!SSL_client_hello_get0_ext(
           ssl.get(),
           TLSEXT_TYPE_server_name,
@@ -200,15 +202,20 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) {
   if (len + 2 > rem)
     return nullptr;
   return reinterpret_cast<const char*>(buf + 5);
+#endif
+  return nullptr;
 }
 
 const char* GetServerName(SSL* ssl) {
   return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
 }
 
-bool SetGroups(SecureContext* sc, const char* groups) {
-  return SSL_CTX_set1_groups_list(sc->ctx().get(), groups) == 1;
-}
+ bool SetGroups(SecureContext* sc, const char* groups) {
+#ifndef OPENSSL_IS_BORINGSSL
+   return SSL_CTX_set1_groups_list(sc->ctx().get(), groups) == 1;
+#endif
+  return SSL_CTX_set1_curves_list(sc->ctx().get(), groups) == 1;
+ }
 
 const char* X509ErrorCode(long err) {  // NOLINT(runtime/int)
   const char* code = "UNSPECIFIED";
@@ -1039,14 +1046,14 @@ MaybeLocal<Array> GetClientHelloCiphers(
     Environment* env,
     const SSLPointer& ssl) {
   EscapableHandleScope scope(env->isolate());
-  const unsigned char* buf;
-  size_t len = SSL_client_hello_get0_ciphers(ssl.get(), &buf);
+  // const unsigned char* buf = nullptr;
+  size_t len = 0; // SSL_client_hello_get0_ciphers(ssl.get(), &buf);
   size_t count = len / 2;
   MaybeStackBuffer<Local<Value>, 16> ciphers(count);
   int j = 0;
   for (size_t n = 0; n < len; n += 2) {
-    const SSL_CIPHER* cipher = SSL_CIPHER_find(ssl.get(), buf);
-    buf += 2;
+    const SSL_CIPHER* cipher = nullptr; // SSL_CIPHER_find(ssl.get(), buf);
+    // buf += 2;
     Local<Object> obj = Object::New(env->isolate());
     if (!Set(env->context(),
              obj,
diff --git a/src/crypto/crypto_dh.cc b/src/crypto/crypto_dh.cc
index dd69323b80076d7333b80453c9cc9ef5b680ce27..6431b768c83fa27b2287588e936f93ae00169ad5 100644
--- a/src/crypto/crypto_dh.cc
+++ b/src/crypto/crypto_dh.cc
@@ -154,13 +154,11 @@ bool DiffieHellman::Init(BignumPointer&& bn_p, int g) {
 bool DiffieHellman::Init(const char* p, int p_len, int g) {
   dh_.reset(DH_new());
   if (p_len <= 0) {
-    ERR_put_error(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX,
-      BN_R_BITS_TOO_SMALL, __FILE__, __LINE__);
+    OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL);
     return false;
   }
   if (g <= 1) {
-    ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS,
-      DH_R_BAD_GENERATOR, __FILE__, __LINE__);
+    OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
     return false;
   }
   BIGNUM* bn_p =
@@ -178,21 +176,18 @@ bool DiffieHellman::Init(const char* p, int p_len, int g) {
 bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) {
   dh_.reset(DH_new());
   if (p_len <= 0) {
-    ERR_put_error(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX,
-      BN_R_BITS_TOO_SMALL, __FILE__, __LINE__);
+    OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL);
     return false;
   }
   if (g_len <= 0) {
-    ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS,
-      DH_R_BAD_GENERATOR, __FILE__, __LINE__);
+    OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
     return false;
   }
   BIGNUM* bn_g =
       BN_bin2bn(reinterpret_cast<const unsigned char*>(g), g_len, nullptr);
   if (BN_is_zero(bn_g) || BN_is_one(bn_g)) {
     BN_free(bn_g);
-    ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS,
-      DH_R_BAD_GENERATOR, __FILE__, __LINE__);
+    OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
     return false;
   }
   BIGNUM* bn_p =
@@ -219,8 +214,10 @@ typedef BignumPointer (*StandardizedGroupInstantiator)();
 inline StandardizedGroupInstantiator FindDiffieHellmanGroup(const char* name) {
 #define V(n, p)                                                                \
   if (StringEqualNoCase(name, n)) return InstantiateStandardizedGroup<p>
+#ifndef OPENSSL_IS_BORINGSSL
   V("modp1", BN_get_rfc2409_prime_768);
   V("modp2", BN_get_rfc2409_prime_1024);
+#endif
   V("modp5", BN_get_rfc3526_prime_1536);
   V("modp14", BN_get_rfc3526_prime_2048);
   V("modp15", BN_get_rfc3526_prime_3072);
@@ -559,15 +556,20 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) {
       return EVPKeyCtxPointer();
     }
 
+#ifndef OPENSSL_IS_BORINGSSL
     prime_fixed_value->release();
     bn_g.release();
 
     key_params = EVPKeyPointer(EVP_PKEY_new());
     CHECK(key_params);
     CHECK_EQ(EVP_PKEY_assign_DH(key_params.get(), dh.release()), 1);
+#else
+    return EVPKeyCtxPointer();
+#endif
   } else if (int* prime_size = std::get_if<int>(&params->params.prime)) {
     EVPKeyCtxPointer param_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DH, nullptr));
     EVP_PKEY* raw_params = nullptr;
+#ifndef OPENSSL_IS_BORINGSSL
     if (!param_ctx ||
         EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 ||
         EVP_PKEY_CTX_set_dh_paramgen_prime_len(
@@ -581,6 +583,9 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) {
     }
 
     key_params = EVPKeyPointer(raw_params);
+#else
+    return EVPKeyCtxPointer();
+#endif
   } else {
     UNREACHABLE();
   }
diff --git a/src/crypto/crypto_dsa.cc b/src/crypto/crypto_dsa.cc
index 6839283fbf4ca7ee7dd586e749c80671ad965658..4e186abdf13613cbe576da5b7d547408c0ee9f93 100644
--- a/src/crypto/crypto_dsa.cc
+++ b/src/crypto/crypto_dsa.cc
@@ -40,7 +40,7 @@ namespace crypto {
 EVPKeyCtxPointer DsaKeyGenTraits::Setup(DsaKeyPairGenConfig* params) {
   EVPKeyCtxPointer param_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, nullptr));
   EVP_PKEY* raw_params = nullptr;
-
+#ifndef OPENSSL_IS_BORINGSSL
   if (!param_ctx ||
       EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 ||
       EVP_PKEY_CTX_set_dsa_paramgen_bits(
@@ -55,7 +55,9 @@ EVPKeyCtxPointer DsaKeyGenTraits::Setup(DsaKeyPairGenConfig* params) {
       return EVPKeyCtxPointer();
     }
   }
-
+#else
+  return EVPKeyCtxPointer();
+#endif
   if (EVP_PKEY_paramgen(param_ctx.get(), &raw_params) <= 0)
     return EVPKeyCtxPointer();
 
diff --git a/src/crypto/crypto_random.cc b/src/crypto/crypto_random.cc
index 2f9e9aacb1e652202d72c69b46f8e76d6c5405a8..5f19c38a78e37d3e8d92bcc20ae1357f20349ad4 100644
--- a/src/crypto/crypto_random.cc
+++ b/src/crypto/crypto_random.cc
@@ -146,7 +146,7 @@ Maybe<bool> RandomPrimeTraits::AdditionalConfig(
 
   params->bits = bits;
   params->safe = safe;
-  params->prime.reset(BN_secure_new());
+  params->prime.reset(BN_new());
   if (!params->prime) {
     THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
     return Nothing<bool>();
diff --git a/src/crypto/crypto_rsa.cc b/src/crypto/crypto_rsa.cc
index 47a42246eddfc795b735f5efd08edf2832bbf6c1..7e6afaa1d3a4612fd567924b40438a318ac93bac 100644
--- a/src/crypto/crypto_rsa.cc
+++ b/src/crypto/crypto_rsa.cc
@@ -610,10 +610,11 @@ Maybe<bool> GetRsaKeyDetail(
       }
 
       if (params->saltLength != nullptr) {
-        if (ASN1_INTEGER_get_int64(&salt_length, params->saltLength) != 1) {
-          ThrowCryptoError(env, ERR_get_error(), "ASN1_INTEGER_get_in64 error");
-          return Nothing<bool>();
-        }
+        // TODO(codebytere): Upstream a shim to BoringSSL?
+        // if (ASN1_INTEGER_get_int64(&salt_length, params->saltLength) != 1) {
+        //   ThrowCryptoError(env, ERR_get_error(), "ASN1_INTEGER_get_in64 error");
+        //   return Nothing<bool>();
+        // }
       }
 
       if (target
diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc
index 28eb1bd6b7dc839fa6aefebe5813343c8e9444bb..1fe573cd7b6894743a0986e87802960ad09e2dd9 100644
--- a/src/crypto/crypto_util.cc
+++ b/src/crypto/crypto_util.cc
@@ -493,24 +493,15 @@ Maybe<bool> Decorate(Environment* env, Local<Object> obj,
     V(BIO)                                                                    \
     V(PKCS7)                                                                  \
     V(X509V3)                                                                 \
-    V(PKCS12)                                                                 \
     V(RAND)                                                                   \
-    V(DSO)                                                                    \
     V(ENGINE)                                                                 \
     V(OCSP)                                                                   \
     V(UI)                                                                     \
     V(COMP)                                                                   \
     V(ECDSA)                                                                  \
     V(ECDH)                                                                   \
-    V(OSSL_STORE)                                                             \
-    V(FIPS)                                                                   \
-    V(CMS)                                                                    \
-    V(TS)                                                                     \
     V(HMAC)                                                                   \
-    V(CT)                                                                     \
-    V(ASYNC)                                                                  \
-    V(KDF)                                                                    \
-    V(SM2)                                                                    \
+    V(HKDF)                                                                    \
     V(USER)                                                                   \
 
 #define V(name) case ERR_LIB_##name: lib = #name "_"; break;
@@ -684,7 +675,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
   CHECK(args[0]->IsUint32());
   Environment* env = Environment::GetCurrent(args);
   uint32_t len = args[0].As<Uint32>()->Value();
-  void* data = OPENSSL_secure_zalloc(len);
+  void* data = OPENSSL_malloc(len);
   if (data == nullptr) {
     // There's no memory available for the allocation.
     // Return nothing.
@@ -695,7 +686,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
           data,
           len,
           [](void* data, size_t len, void* deleter_data) {
-            OPENSSL_secure_clear_free(data, len);
+            OPENSSL_clear_free(data, len);
           },
           data);
   Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store);
@@ -703,10 +694,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
 }
 
 void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) {
+#ifndef OPENSSL_IS_BORINGSSL
   Environment* env = Environment::GetCurrent(args);
   if (CRYPTO_secure_malloc_initialized())
     args.GetReturnValue().Set(
         BigInt::New(env->isolate(), CRYPTO_secure_used()));
+#endif
 }
 }  // namespace
 
diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h
index fd014e703454dd1988e9b5a013b937881c1f514a..0adbe57d582eff906476330083258716e5bcae99 100644
--- a/src/crypto/crypto_util.h
+++ b/src/crypto/crypto_util.h
@@ -15,6 +15,7 @@
 #include <openssl/err.h>
 #include <openssl/evp.h>
 #include <openssl/ec.h>
+#include <openssl/hmac.h>
 #include <openssl/kdf.h>
 #include <openssl/rsa.h>
 #include <openssl/dsa.h>
diff --git a/src/node_metadata.cc b/src/node_metadata.cc
index ed28871c385532b13e102200ba549bb7d7e901e6..c69d3f1867cd1b86194b109351643d9520c661e7 100644
--- a/src/node_metadata.cc
+++ b/src/node_metadata.cc
@@ -13,7 +13,7 @@
 #include "v8.h"
 #include "zlib.h"
 
-#if HAVE_OPENSSL
+#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
 #include <openssl/opensslv.h>
 #if NODE_OPENSSL_HAS_QUIC
 #include <openssl/quic.h>
diff --git a/src/node_metadata.h b/src/node_metadata.h
index 2a924141d6edbaade371dd29d553eb1107ff5f75..be37169bb1d5e70e11601ccf00db0552ee3511ed 100644
--- a/src/node_metadata.h
+++ b/src/node_metadata.h
@@ -6,7 +6,7 @@
 #include <string>
 #include "node_version.h"
 
-#if HAVE_OPENSSL
+#if 0
 #include <openssl/crypto.h>
 #if NODE_OPENSSL_HAS_QUIC
 #include <openssl/quic.h>
diff --git a/src/node_options.cc b/src/node_options.cc
index def333cfddef800fefb4244d7fad6e489a5dafed..99f5274aec7512956a5e13a5ca9c0b593a57cc7a 100644
--- a/src/node_options.cc
+++ b/src/node_options.cc
@@ -5,7 +5,7 @@
 #include "node_binding.h"
 #include "node_external_reference.h"
 #include "node_internals.h"
-#if HAVE_OPENSSL
+#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
 #include "openssl/opensslv.h"
 #endif
 
diff --git a/src/node_options.h b/src/node_options.h
index 2e4da9decf3b4b05b89a586cda194a475e0cd41d..8fabd68975721ed27fd99ff50dbbfcb3158336e7 100644
--- a/src/node_options.h
+++ b/src/node_options.h
@@ -11,7 +11,7 @@
 #include "node_mutex.h"
 #include "util.h"
 
-#if HAVE_OPENSSL
+#if 0
 #include "openssl/opensslv.h"
 #endif
 
