]> git.kaiwu.me - njs.git/commitdiff
WebCrypto: validate derived key length consistently
authorDmitry Volyntsev <xeioex@nginx.com>
Thu, 19 Nov 2026 01:13:26 +0000 (17:13 -0800)
committerDmitry Volyntsev <xeioexception@gmail.com>
Thu, 19 Nov 2026 06:07:22 +0000 (22:07 -0800)
Previously, deriveKey() divided the requested length by 8 before
checking it, so AES lengths such as 129 were accepted as 128. HMAC
lengths below 8 bits produced an empty key, which importKey() rejects.
ECDH and X25519 did not check AES lengths at all, and njs reported an
unsupported HKDF or PBKDF2 derived key type as InternalError.

Now both deriveKey() paths check the length in bits before converting
it to bytes, reject HMAC keys shorter than one byte, and report invalid
derived key parameters as TypeError.

The AES length issue was introduced in 7b2b7612 (0.7.0) and inherited
by ECDH in 1b69415d (0.9.1).

external/njs_webcrypto_module.c
external/qjs_webcrypto_module.c
test/webcrypto/derive_ecdh.t.mjs

index 7b9e85a703787f0ee19de510d387a2a293e701f5..f6932832c29972d84baaf63c673ce4d944a8d3b9 100644 (file)
@@ -118,6 +118,8 @@ static njs_int_t njs_cipher_aes_cbc(njs_vm_t *vm, njs_str_t *data,
 static njs_int_t njs_cipher_aes_kw(njs_vm_t *vm, njs_str_t *data,
     njs_webcrypto_key_t *key, njs_bool_t encrypt, njs_value_t *retval);
 #endif
+static njs_int_t njs_derive_key_length(njs_vm_t *vm,
+    njs_webcrypto_algorithm_t *dalg, int64_t length);
 static njs_int_t njs_ext_derive(njs_vm_t *vm, njs_value_t *args,
     njs_uint_t nargs, njs_index_t derive_key, njs_value_t *retval);
 static njs_int_t njs_ext_digest(njs_vm_t *vm, njs_value_t *args,
@@ -1648,6 +1650,41 @@ fail:
 #endif
 
 
+static njs_int_t
+njs_derive_key_length(njs_vm_t *vm, njs_webcrypto_algorithm_t *dalg,
+    int64_t length)
+{
+    switch (dalg->type) {
+    case NJS_ALGORITHM_AES_GCM:
+    case NJS_ALGORITHM_AES_CTR:
+    case NJS_ALGORITHM_AES_CBC:
+    case NJS_ALGORITHM_AES_KW:
+        if (length != 128 && length != 192 && length != 256) {
+            njs_vm_type_error(vm, "deriveKey \"%V\" length must be "
+                              "128, 192, or 256",
+                              njs_algorithm_string(dalg));
+            return NJS_ERROR;
+        }
+
+        break;
+
+    case NJS_ALGORITHM_HMAC:
+        if (length < 8) {
+            njs_vm_type_error(vm, "deriveKey \"HMAC\" length must be "
+                              "at least 8");
+            return NJS_ERROR;
+        }
+
+        break;
+
+    default:
+        break;
+    }
+
+    return NJS_OK;
+}
+
+
 static njs_int_t
 njs_ext_derive_ecdh(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
     njs_index_t derive_key, njs_webcrypto_key_t *key, njs_value_t *retval)
@@ -1696,6 +1733,13 @@ njs_ext_derive_ecdh(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
         goto fail;
     }
 
+    if (derive_key) {
+        ret = njs_derive_key_length(vm, dalg, length);
+        if (njs_slow_path(ret != NJS_OK)) {
+            goto fail;
+        }
+    }
+
     dkey = NULL;
     length /= 8;
 
@@ -1918,34 +1962,31 @@ njs_ext_derive(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
         goto fail;
     }
 
-    dkey = NULL;
-    length /= 8;
-
     if (derive_key) {
         switch (dalg->type) {
         case NJS_ALGORITHM_AES_GCM:
         case NJS_ALGORITHM_AES_CTR:
         case NJS_ALGORITHM_AES_CBC:
         case NJS_ALGORITHM_AES_KW:
-
-            if (length != 16 && length != 24 && length != 32) {
-                njs_vm_type_error(vm, "deriveKey \"%V\" length must be "
-                                  "128, 192, or 256",
-                                  njs_algorithm_string(dalg));
-                goto fail;
-            }
-
-            break;
-
         case NJS_ALGORITHM_HMAC:
             break;
 
         default:
-            njs_vm_internal_error(vm, "not implemented deriveKey: \"%V\"",
-                                  njs_algorithm_string(dalg));
+            njs_vm_type_error(vm, "not implemented deriveKey: \"%V\"",
+                              njs_algorithm_string(dalg));
             goto fail;
         }
 
+        ret = njs_derive_key_length(vm, dalg, length);
+        if (njs_slow_path(ret != NJS_OK)) {
+            goto fail;
+        }
+    }
+
+    dkey = NULL;
+    length /= 8;
+
+    if (derive_key) {
         ret = njs_key_usage(vm, njs_arg(args, nargs, 5), &usage);
         if (njs_slow_path(ret != NJS_OK)) {
             goto fail;
index 483e84c29d0cc7557000fb827fc921739e0ebf69..23de3d71d3cfd98516c5dc2300ebbf50aa52c4d9 100644 (file)
@@ -141,6 +141,8 @@ static JSValue qjs_cipher_aes_cbc(JSContext *cx, njs_str_t *data,
 static JSValue qjs_cipher_aes_kw(JSContext *cx, njs_str_t *data,
     qjs_webcrypto_key_t *key, int encrypt);
 #endif
+static int qjs_derive_key_length(JSContext *cx,
+    qjs_webcrypto_algorithm_t *dalg, int64_t length);
 static JSValue qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc,
     int derive_key, qjs_webcrypto_key_t *key);
 static JSValue qjs_webcrypto_derive(JSContext *cx, JSValueConst this_val,
@@ -2069,6 +2071,41 @@ qjs_export_raw_ec(JSContext *cx, qjs_webcrypto_key_t *key)
 }
 
 
+static int
+qjs_derive_key_length(JSContext *cx, qjs_webcrypto_algorithm_t *dalg,
+    int64_t length)
+{
+    switch (dalg->type) {
+    case QJS_ALGORITHM_AES_GCM:
+    case QJS_ALGORITHM_AES_CTR:
+    case QJS_ALGORITHM_AES_CBC:
+    case QJS_ALGORITHM_AES_KW:
+        if (length != 128 && length != 192 && length != 256) {
+            JS_ThrowTypeError(cx, "deriveKey \"%s\" length must be "
+                              "128, 192, or 256",
+                              qjs_algorithm_string(dalg));
+            return -1;
+        }
+
+        break;
+
+    case QJS_ALGORITHM_HMAC:
+        if (length < 8) {
+            JS_ThrowTypeError(cx, "deriveKey \"HMAC\" length must be "
+                              "at least 8");
+            return -1;
+        }
+
+        break;
+
+    default:
+        break;
+    }
+
+    return 0;
+}
+
+
 static JSValue
 qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key,
     qjs_webcrypto_key_t *key)
@@ -2122,6 +2159,10 @@ qjs_derive_ecdh(JSContext *cx, JSValueConst *argv, int argc, int derive_key,
 
     JS_FreeValue(cx, value);
 
+    if (derive_key && qjs_derive_key_length(cx, dalg, length) < 0) {
+        goto fail;
+    }
+
     dkey = NULL;
     length /= 8;
 
@@ -2351,26 +2392,12 @@ qjs_webcrypto_derive(JSContext *cx, JSValueConst this_val, int argc,
 
     JS_FreeValue(cx, ret);
 
-    dkey = NULL;
-    length /= 8;
-    dkey_value = JS_UNDEFINED;
-
     if (derive_key) {
         switch (dalg->type) {
         case QJS_ALGORITHM_AES_GCM:
         case QJS_ALGORITHM_AES_CTR:
         case QJS_ALGORITHM_AES_CBC:
         case QJS_ALGORITHM_AES_KW:
-
-            if (length != 16 && length != 24 && length != 32) {
-                JS_ThrowTypeError(cx, "deriveKey \"%s\" length must be "
-                                  "128, 192, or 256",
-                                  qjs_algorithm_string(dalg));
-                return JS_EXCEPTION;
-            }
-
-            break;
-
         case QJS_ALGORITHM_HMAC:
             break;
 
@@ -2380,6 +2407,16 @@ qjs_webcrypto_derive(JSContext *cx, JSValueConst this_val, int argc,
             return JS_EXCEPTION;
         }
 
+        if (qjs_derive_key_length(cx, dalg, length) < 0) {
+            return JS_EXCEPTION;
+        }
+    }
+
+    dkey = NULL;
+    length /= 8;
+    dkey_value = JS_UNDEFINED;
+
+    if (derive_key) {
         ret = qjs_key_usage(cx, argv[4], &usage);
         if (JS_IsException(ret)) {
             return JS_EXCEPTION;
index 7e0a07713c4ec81f2c555f98a46483824e7d1f59..c2dfa80427954f8466837808c9b7845e70c74ca3 100644 (file)
@@ -228,6 +228,90 @@ async function testDerivedKeyType(params) {
     return "SUCCESS";
 }
 
+/* Error names other engines use for invalid derived key parameters. */
+const invalid = ["TypeError", "OperationError", "NotSupportedError",
+                 "DataError", "SyntaxError"];
+
+async function testDerivedKeyLength(params) {
+    let ecdh_pair = await load_key_pair('ec');
+    let peer = await load_key_pair('ec2');
+    let base;
+
+    if (params.base === "ECDH") {
+        base = { algorithm: { name: "ECDH", public: peer.publicKey },
+                 key: ecdh_pair.privateKey };
+
+    } else {
+        base = {
+            algorithm: { name: params.base, hash: "SHA-256",
+                         salt: new Uint8Array(16), info: new Uint8Array(0),
+                         iterations: 1 },
+            key: await crypto.subtle.importKey("raw", new Uint8Array(32),
+                                               params.base, false,
+                                               ["deriveKey"]),
+        };
+    }
+
+    let key;
+
+    try {
+        key = await crypto.subtle.deriveKey(base.algorithm, base.key,
+                                            params.derived, true,
+                                            params.usage);
+
+    } catch (e) {
+        if (params.error && params.error.indexOf(e.name) !== -1) {
+            return "SUCCESS";
+        }
+
+        throw e;
+    }
+
+    if (params.error) {
+        throw Error(`deriveKey accepted ${JSON.stringify(params.derived)}`);
+    }
+
+    let raw = await crypto.subtle.exportKey("raw", key);
+
+    if (raw.byteLength !== params.bytes) {
+        throw Error(`unexpected key length: ${raw.byteLength}`);
+    }
+
+    return "SUCCESS";
+}
+
+let derived_key_length_tsuite = {
+    name: "deriveKey length",
+    skip: () => (!has_buffer() || !has_webcrypto()),
+    T: testDerivedKeyLength,
+    opts: {
+        usage: ["sign"]
+    },
+    tests: [
+        { base: "ECDH", derived: { name: "AES-GCM", length: 129 },
+          usage: ["encrypt"],
+          error: invalid },
+        { base: "HKDF", derived: { name: "AES-GCM", length: 129 },
+          usage: ["encrypt"],
+          error: invalid },
+        { base: "PBKDF2", derived: { name: "AES-GCM", length: 129 },
+          usage: ["encrypt"],
+          error: invalid },
+        { base: "ECDH",
+          derived: { name: "HMAC", hash: "SHA-256", length: 7 },
+          error: invalid },
+        { base: "HKDF",
+          derived: { name: "HMAC", hash: "SHA-256", length: 0 },
+          error: invalid },
+        { base: "ECDH",
+          derived: { name: "HMAC", hash: "SHA-256", length: 8 },
+          bytes: 1 },
+        { base: "HKDF",
+          derived: { name: "ECDSA", namedCurve: "P-256", length: 256 },
+          error: invalid },
+    ]
+};
+
 let ecdh_key_type_tsuite = {
     name: "ECDH-DeriveKey type",
     skip: () => (!has_buffer() || !has_webcrypto()),
@@ -246,5 +330,6 @@ run([
     ecdh_bits_tsuite,
     ecdh_key_tsuite,
     ecdh_key_type_tsuite,
+    derived_key_length_tsuite,
 ])
 .then($DONE, $DONE);