Repository: nodejs/node
Pull request: crypto: forward auth tag to OpenSSL immediately

This change simplifies the C++ AEAD implementation. Instead of storing the authentication tag when the user calls `setAuthTag()` and passing it to OpenSSL later in `MaybePassAuthTagToOpenSSL()`, the modified code forwards it to OpenSSL from within `setAuthTag()` already, removing the need to store it.

For clarity, I have also renamed the possible `AuthTagState` values to better reflect the actual state of the authentication tag.

I assume that we did not originally do this due to issues with some old versions of OpenSSL when reordering certain function calls, but even with the recent additions I made to the relevant test (namely, 1ef99237f566c89247660b935667fbf4efa606ce and 53944c44629b651425f8d18c4d33f9bc99657d37), it seems to pass in both OpenSSL 3 and OpenSSL 1.1.1 with this simplification.

<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: src/crypto/crypto_cipher.cc
patch: @@ -514,9 +514,9 @@ void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
   ASSIGN_OR_RETURN_UNWRAP(&cipher, args.This());
 
   // Only callable after Final and if encrypting.
-  if (cipher->ctx_ ||
-      cipher->kind_ != kCipher ||
-      cipher->auth_tag_len_ == kNoAuthTagLength) {
+  if (cipher->ctx_ || cipher->kind_ != kCipher ||
+      cipher->auth_tag_len_ == kNoAuthTagLength ||
+      cipher->auth_tag_state_ != kAuthTagComputed) {
     return;
   }
 
@@ -577,29 +577,16 @@ void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
   }
 
   cipher->auth_tag_len_ = tag_len;
-  cipher->auth_tag_state_ = kAuthTagKnown;
-  CHECK_LE(cipher->auth_tag_len_, sizeof(cipher->auth_tag_));
+  CHECK_LE(cipher->auth_tag_len_, ncrypto::Cipher::MAX_AUTH_TAG_LENGTH);
 
-  memset(cipher->auth_tag_, 0, sizeof(cipher->auth_tag_));
-  auth_tag.CopyTo(cipher->auth_tag_, cipher->auth_tag_len_);
+  if (!cipher->ctx_.setAeadTag({auth_tag.data(), cipher->auth_tag_len_})) {
+    return args.GetReturnValue().Set(false);
+  }
+  cipher->auth_tag_state_ = kAuthTagSetByUser;
 
   args.GetReturnValue().Set(true);
 }
 
-bool CipherBase::MaybePassAuthTagToOpenSSL() {
-  if (auth_tag_state_ == kAuthTagKnown) {
-    ncrypto::Buffer<const char> buffer{
-        .data = auth_tag_,
-        .len = auth_tag_len_,
-    };
-    if (!ctx_.setAeadTag(buffer)) {
-      return false;
-    }
-    auth_tag_state_ = kAuthTagPassedToOpenSSL;
-  }
-  return true;
-}
-
 bool CipherBase::SetAAD(
     const ArrayBufferOrViewContents<unsigned char>& data,
     int plaintext_len) {
@@ -622,10 +609,6 @@ bool CipherBase::SetAAD(
       return false;
     }
 
-    if (kind_ == kDecipher && !MaybePassAuthTagToOpenSSL()) {
-      return false;
-    }
-
     ncrypto::Buffer<const unsigned char> buffer{
         .data = nullptr,
         .len = static_cast<size_t>(plaintext_len),
@@ -670,12 +653,6 @@ CipherBase::UpdateResult CipherBase::Update(
     return kErrorMessageSize;
   }
 
-  // Pass the authentication tag to OpenSSL if possible. This will only happen
-  // once, usually on the first update.
-  if (kind_ == kDecipher && IsAuthenticatedMode()) {
-    CHECK(MaybePassAuthTagToOpenSSL());
-  }
-
   const int block_size = ctx_.getBlockSize();
   CHECK_GT(block_size, 0);
   if (len + block_size > INT_MAX) return kErrorState;
@@ -777,16 +754,11 @@ bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
       static_cast<size_t>(ctx_.getBlockSize()),
       BackingStoreInitializationMode::kUninitialized);
 
-  if (kind_ == kDecipher &&
-      Cipher::FromCtx(ctx_).isSupportedAuthenticatedMode()) {
-    MaybePassAuthTagToOpenSSL();
-  }
-
 #if (OPENSSL_VERSION_NUMBER < 0x30000000L)
   // OpenSSL v1.x doesn't verify the presence of the auth tag so do
   // it ourselves, see https://github.com/nodejs/node/issues/45874.
   if (kind_ == kDecipher && ctx_.isChaCha20Poly1305() &&
-      auth_tag_state_ != kAuthTagPassedToOpenSSL) {
+      auth_tag_state_ != kAuthTagSetByUser) {
     return false;
   }
 #endif
@@ -824,6 +796,9 @@ bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
       }
       ok = ctx_.getAeadTag(auth_tag_len_,
                            reinterpret_cast<unsigned char*>(auth_tag_));
+      if (ok) {
+        auth_tag_state_ = kAuthTagComputed;
+      }
     }
   }
 

filename: src/crypto/crypto_cipher.h
patch: @@ -38,8 +38,8 @@ class CipherBase : public BaseObject {
   };
   enum AuthTagState {
     kAuthTagUnknown,
-    kAuthTagKnown,
-    kAuthTagPassedToOpenSSL
+    kAuthTagSetByUser,
+    kAuthTagComputed,
   };
   static const unsigned kNoAuthTagLength = static_cast<unsigned>(-1);
 
@@ -64,10 +64,8 @@ class CipherBase : public BaseObject {
   bool SetAutoPadding(bool auto_padding);
 
   bool IsAuthenticatedMode() const;
-  bool SetAAD(
-      const ArrayBufferOrViewContents<unsigned char>& data,
-      int plaintext_len);
-  bool MaybePassAuthTagToOpenSSL();
+  bool SetAAD(const ArrayBufferOrViewContents<unsigned char>& data,
+              int plaintext_len);
 
   static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
   static void Update(const v8::FunctionCallbackInfo<v8::Value>& args);