]> git.kaiwu.me - njs.git/commitdiff
WebCrypto: fix ECDH public key use after free
authorDmitry Volyntsev <xeioex@nginx.com>
Fri, 13 Nov 2026 00:48:45 +0000 (16:48 -0800)
committerDmitry Volyntsev <xeioexception@gmail.com>
Mon, 16 Nov 2026 18:13:27 +0000 (10:13 -0800)
Previously, the QuickJS deriveBits() and deriveKey() implementation
for ECDH released the "public" algorithm member right after taking
the key from it.  When the member was returned by a getter and no
other reference was held, the CryptoKey and its EVP_PKEY were freed
before EVP_PKEY_derive() used them.

Now the member value is kept until the derivation is done.

The issue was introduced in 1b69415d (0.9.1).

external/qjs_webcrypto_module.c

index e1626cb04cab5c987ce51e849cb456336ccbcc8a..adfe35355f1f3c390cf92678d4733fe243b7e7e8 100644 (file)
@@ -1956,7 +1956,7 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key,
     u_char                     *k;
     size_t                     olen;
     int64_t                    length;
-    JSValue                    ret, result, value, dobject;
+    JSValue                    ret, result, value, dobject, public_value;
     unsigned                   usage;
     EVP_PKEY                   *priv_pkey, *pub_pkey;
     EVP_PKEY_CTX               *pctx;
@@ -1964,6 +1964,7 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key,
     qjs_webcrypto_algorithm_t  *dalg;
 
     result = JS_UNDEFINED;
+    public_value = JS_UNDEFINED;
     dobject = argv[2];
 
     if (derive_key) {
@@ -2029,8 +2030,9 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key,
         goto fail;
     }
 
-    pkey = JS_GetOpaque(value, QJS_CORE_CLASS_ID_WEBCRYPTO_KEY);
-    JS_FreeValue(cx, value);
+    public_value = value;
+
+    pkey = JS_GetOpaque(public_value, QJS_CORE_CLASS_ID_WEBCRYPTO_KEY);
     if (pkey == NULL) {
         JS_ThrowTypeError(cx, "algorithm.public is not a CryptoKey object");
         goto fail;
@@ -2108,6 +2110,9 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key,
 
     EVP_PKEY_CTX_free(pctx);
 
+    JS_FreeValue(cx, public_value);
+    public_value = JS_UNDEFINED;
+
     if (derive_key) {
         if (dalg->type == QJS_ALGORITHM_HMAC) {
             ret = qjs_algorithm_hash(cx, dobject, &dkey->hash);
@@ -2129,6 +2134,7 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key,
     return qjs_promise_result(cx, result);
 
 fail:
+    JS_FreeValue(cx, public_value);
     JS_FreeValue(cx, result);
 
     return qjs_promise_result(cx, JS_EXCEPTION);