]> git.kaiwu.me - njs.git/commitdiff
WebCrypto: free AES-GCM context on errors
authorDmitry Volyntsev <xeioex@nginx.com>
Mon, 16 Nov 2026 23:32:07 +0000 (15:32 -0800)
committerDmitry Volyntsev <xeioexception@gmail.com>
Tue, 17 Nov 2026 22:09:33 +0000 (14:09 -0800)
Previously, additionalData conversion and output allocation failures
returned without freeing the OpenSSL cipher context.  Repeated failed
operations leaked contexts and their associated allocations.

Route these failures through the existing cleanup.  The issue was
introduced in 7b2b7612 (0.7.0).

external/njs_webcrypto_module.c
test/webcrypto/aes_errors.t.mjs [new file with mode: 0644]

index f12244ead3556ba4138599905708d72700929639..dbccf2e9941093eb0f9101f30f8fdb12761d7bf8 100644 (file)
@@ -1065,7 +1065,8 @@ njs_cipher_aes_gcm(njs_vm_t *vm, njs_str_t *data, njs_webcrypto_key_t *key,
     if (value != NULL && !njs_value_is_undefined(value)) {
         ret = njs_vm_value_to_bytes(vm, &aad, value);
         if (njs_slow_path(ret != NJS_OK)) {
-            return NJS_ERROR;
+            ret = NJS_ERROR;
+            goto fail;
         }
     }
 
@@ -1083,7 +1084,8 @@ njs_cipher_aes_gcm(njs_vm_t *vm, njs_str_t *data, njs_webcrypto_key_t *key,
     dst = njs_mp_alloc(njs_vm_memory_pool(vm), dstlen);
     if (njs_slow_path(dst == NULL)) {
         njs_vm_memory_error(vm);
-        return NJS_ERROR;
+        ret = NJS_ERROR;
+        goto fail;
     }
 
     ret = EVP_CipherUpdate(ctx, dst, &outlen, data->start,
diff --git a/test/webcrypto/aes_errors.t.mjs b/test/webcrypto/aes_errors.t.mjs
new file mode 100644 (file)
index 0000000..8c0d510
--- /dev/null
@@ -0,0 +1,40 @@
+/*---
+includes: [compatBuffer.js, compatWebcrypto.js, runTsuite.js]
+flags: [async]
+---*/
+
+async function test(params) {
+    let key = await crypto.subtle.importKey('raw', new Uint8Array(16),
+                                            'AES-GCM', false,
+                                            ['encrypt', 'decrypt']);
+    let algorithm = {name: 'AES-GCM', iv: new Uint8Array(12)};
+    let data = new Uint8Array(16);
+
+    if (params.op == 'decrypt') {
+        data = await crypto.subtle.encrypt(algorithm, key, data);
+    }
+
+    algorithm.additionalData = Symbol.toStringTag;
+
+    try {
+        await crypto.subtle[params.op](algorithm, key, data);
+
+    } catch (e) {
+        return 'SUCCESS';
+    }
+
+    throw Error('AES-GCM accepted invalid additionalData');
+}
+
+let aes_errors_tsuite = {
+    name: 'AES-GCM additionalData conversion failure',
+    skip: () => (!has_buffer() || !has_webcrypto()),
+    T: test,
+    tests: [
+        {op: 'encrypt'},
+        {op: 'decrypt'},
+    ],
+};
+
+run([aes_errors_tsuite])
+.then($DONE, $DONE);