crypto: harden WebCrypto against prototype pollution

Avoid re-wrapping native WebCrypto promises with PromiseResolve(),
since resolving a promise can read its user-mutated constructor.

Add a helper for chaining internal WebCrypto job promises without
consulting Promise species state, and use it for intermediate job
results.

Also align JWK wrapping and unwrapping with the spec's fresh-global
JSON handling by detaching internal JWK values from user prototypes.
Use the internal UTF-8 encoder/decoder bindings instead of shared
TextEncoder/TextDecoder prototype methods.

Expand the WebCrypto prototype pollution regression test to cover
SubtleCrypto methods, export formats, zero-length KDF results, JWK
toJSON/kty pollution, and encoder/decoder prototype poisoning.

Signed-off-by: Filip Skokan <panva.ip@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/63363
Backport-PR-URL: https://github.com/nodejs/node/pull/63563
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: René <contact.9a5d6388@renegade334.me.uk>
This commit is contained in:
Filip Skokan authored and Stewart X Addison committed 2026-06-23 01:06:45 +01:00
1 parent 3d05a1d396
commit ae61cd68f3
13 files changed
+978 -148

No files matched your search

+2 -2
View File
@@ -5,7 +5,6 @@ const {
FunctionPrototypeCall,
MathCeil,
ObjectDefineProperty,
PromisePrototypeThen,
SafeSet,
TypedArrayPrototypeGetBuffer,
Uint8Array,
@@ -65,6 +64,7 @@ const {
const {
getArrayBufferOrView,
jobPromise,
jobPromiseThen,
toBuf,
kHandle,
} = require('internal/crypto/util');
@@ -405,7 +405,7 @@ function ecdhDeriveBits(algorithm, baseKey, length) {
if (length === null)
return bits;
return PromisePrototypeThen(bits, (bits) => {
return jobPromiseThen(bits, (bits) => {
// If the length is not a multiple of 8 the nearest ceiled
// multiple of 8 is sliced.
const sliceLength = MathCeil(length / 8);
+70
View File
@@ -14,7 +14,9 @@ const {
ObjectEntries,
ObjectKeys,
ObjectPrototypeHasOwnProperty,
PromisePrototypeThen,
PromiseReject,
PromiseWithResolvers,
SafeSet,
StringPrototypeToUpperCase,
Symbol,
@@ -76,6 +78,7 @@ const {
emitExperimentalWarning,
filterDuplicateStrings,
lazyDOMException,
setOwnProperty,
} = require('internal/util');
const {
@@ -89,6 +92,7 @@ const {
isDataView,
isArrayBufferView,
isAnyArrayBuffer,
isPromise,
} = require('internal/util/types');
const kHandle = Symbol('kHandle');
@@ -669,6 +673,69 @@ function jobPromise(getJob) {
}
}
// Temporarily shadow inherited then accessors on WebCrypto result objects.
// Promise resolution reads "then" synchronously for thenable assimilation.
// Returning an own undefined data property keeps that lookup from reaching
// user-mutated prototypes.
function prepareWebCryptoResult(value) {
if ((value === null || typeof value !== 'object') &&
typeof value !== 'function') {
return false;
}
if (isPromise(value) || ObjectPrototypeHasOwnProperty(value, 'then'))
return false;
setOwnProperty(value, 'then', undefined);
return true;
}
// Remove the temporary then property installed by prepareWebCryptoResult().
function cleanupWebCryptoResult(value) {
delete value.then;
}
// Resolve a WebCrypto promise while inherited then accessors are shadowed.
function resolveWebCryptoResult(resolve, value) {
const shouldCleanupResult = prepareWebCryptoResult(value);
try {
resolve(value);
} finally {
if (shouldCleanupResult)
cleanupWebCryptoResult(value);
}
}
// Run a WebCrypto promise reaction and settle the outer promise.
function settleJobPromise(handler, resolve, reject, value, isRejected) {
try {
if (typeof handler === 'function') {
resolveWebCryptoResult(resolve, handler(value));
} else if (isRejected) {
reject(value);
} else {
resolveWebCryptoResult(resolve, value);
}
} catch (err) {
reject(err);
}
}
// Promise.prototype.then gets promise.constructor to determine the result
// promise's species. These promises are internal WebCrypto intermediates, so
// make that lookup stay on the promise itself instead of user-mutated state.
function jobPromiseThen(promise, onFulfilled, onRejected) {
const {
promise: resultPromise,
resolve,
reject,
} = PromiseWithResolvers();
setOwnProperty(promise, 'constructor', undefined);
PromisePrototypeThen(
promise,
(value) => settleJobPromise(onFulfilled, resolve, reject, value, false),
(value) => settleJobPromise(onRejected, resolve, reject, value, true));
return resultPromise;
}
// In WebCrypto, the publicExponent option in RSA is represented as a
// WebIDL "BigInteger"... that is, a Uint8Array that allows an arbitrary
// number of leading zero bits. Our conventional APIs for reading
@@ -891,6 +958,9 @@ module.exports = {
validateByteSource,
validateKeyOps,
jobPromise,
jobPromiseThen,
cleanupWebCryptoResult,
prepareWebCryptoResult,
validateMaxBufferLength,
bigIntArrayToUnsignedBigInt,
bigIntArrayToUnsignedInt,
+120 -38
View File
@@ -1,19 +1,24 @@
'use strict';
const {
ArrayIsArray,
ArrayPrototypeSlice,
FunctionPrototypeCall,
JSONParse,
JSONStringify,
ObjectDefineProperties,
PromisePrototypeThen,
ObjectKeys,
ObjectPrototypeHasOwnProperty,
ObjectSetPrototypeOf,
PromiseReject,
PromiseResolve,
ReflectApply,
ReflectConstruct,
SafeArrayIterator,
StringPrototypeRepeat,
StringPrototypeSlice,
StringPrototypeStartsWith,
SymbolIterator,
SymbolToStringTag,
TypedArrayPrototypeGetBuffer,
} = primordials;
@@ -26,7 +31,10 @@ const {
kWebCryptoCipherDecrypt,
} = internalBinding('crypto');
const { TextDecoder, TextEncoder } = require('internal/encoding');
const {
decodeUTF8,
encodeUtf8String,
} = internalBinding('encoding_binding');
const {
codes: {
@@ -54,9 +62,12 @@ const {
} = require('internal/crypto/hash');
const {
cleanupWebCryptoResult,
getBlockSize,
jobPromiseThen,
normalizeAlgorithm,
normalizeHashName,
prepareWebCryptoResult,
validateMaxBufferLength,
} = require('internal/crypto/util');
@@ -64,6 +75,7 @@ const {
emitExperimentalWarning,
kEnumerableProperty,
lazyDOMException,
setOwnProperty,
} = require('internal/util');
const {
@@ -71,13 +83,28 @@ const {
randomUUID: _randomUUID,
} = require('internal/crypto/random');
const {
isPromise,
} = require('internal/util/types');
let webidl;
// WebCrypto methods return promises, including for synchronous validation
// failures. Keep that conversion in one place so method bodies stay readable.
function callSubtleCryptoMethod(fn, receiver, args) {
try {
return PromiseResolve(ReflectApply(fn, receiver, args));
const result = ReflectApply(fn, receiver, args);
if (isPromise(result))
return result;
// PromiseResolve() performs thenable assimilation for object results.
// Shadow inherited then accessors while it resolves synchronous results.
const shouldCleanupResult = prepareWebCryptoResult(result);
try {
return PromiseResolve(result);
} finally {
if (shouldCleanupResult)
cleanupWebCryptoResult(result);
}
} catch (err) {
return PromiseReject(err);
}
@@ -384,7 +411,7 @@ function deriveKeyImpl(
throw lazyDOMException('Unrecognized algorithm name', 'NotSupportedError');
}
return PromisePrototypeThen(bits, (bits) => FunctionPrototypeCall(
return jobPromiseThen(bits, (bits) => FunctionPrototypeCall(
importKeySync,
this,
'raw-secret', bits, derivedKeyAlgorithm, extractable, keyUsages,
@@ -571,30 +598,24 @@ function exportKeyRawSecret(key, format) {
function exportKeyJWK(key) {
const algorithm = getCryptoKeyAlgorithm(key);
const parameters = {
key_ops: ArrayPrototypeSlice(getCryptoKeyUsages(key), 0),
ext: getCryptoKeyExtractable(key),
};
let alg;
switch (algorithm.name) {
case 'RSASSA-PKCS1-v1_5': {
const alg = normalizeHashName(
alg = normalizeHashName(
algorithm.hash.name,
normalizeHashName.kContextJwkRsa);
if (alg) parameters.alg = alg;
break;
}
case 'RSA-PSS': {
const alg = normalizeHashName(
alg = normalizeHashName(
algorithm.hash.name,
normalizeHashName.kContextJwkRsaPss);
if (alg) parameters.alg = alg;
break;
}
case 'RSA-OAEP': {
const alg = normalizeHashName(
alg = normalizeHashName(
algorithm.hash.name,
normalizeHashName.kContextJwkRsaOaep);
if (alg) parameters.alg = alg;
break;
}
case 'ECDSA':
@@ -620,7 +641,7 @@ function exportKeyJWK(key) {
case 'Ed25519':
// Fall through
case 'Ed448':
parameters.alg = algorithm.name;
alg = algorithm.name;
break;
case 'AES-CTR':
// Fall through
@@ -631,30 +652,39 @@ function exportKeyJWK(key) {
case 'AES-OCB':
// Fall through
case 'AES-KW':
parameters.alg = require('internal/crypto/aes')
alg = require('internal/crypto/aes')
.getAlgorithmName(algorithm.name, algorithm.length);
break;
case 'ChaCha20-Poly1305':
parameters.alg = 'C20P';
alg = 'C20P';
break;
case 'HMAC': {
const alg = normalizeHashName(
alg = normalizeHashName(
algorithm.hash.name,
normalizeHashName.kContextJwkHmac);
if (alg) parameters.alg = alg;
break;
}
case 'KMAC128':
parameters.alg = 'K128';
alg = 'K128';
break;
case 'KMAC256': {
parameters.alg = 'K256';
alg = 'K256';
break;
}
default:
return undefined;
}
// Keep `alg` in the object literal so an inherited setter cannot capture
// `parameters` before native export populates key material. Delete it for
// algorithms without a JWK alg value to keep the expected shape.
const parameters = {
key_ops: ArrayPrototypeSlice(getCryptoKeyUsages(key), 0),
ext: getCryptoKeyExtractable(key),
alg,
};
if (alg === undefined) delete parameters.alg;
return getCryptoKeyHandle(key).exportJwk(parameters, true);
}
@@ -748,6 +778,60 @@ function exportKeyImpl(format, key) {
return exportKeySync(format, key);
}
// Parsed JWK arrays are detached from Array.prototype but still need to pass
// WebIDL sequence conversion, which reads @@iterator from the value.
function safeArrayIterator() {
return new SafeArrayIterator(this);
}
// The WebCrypto spec parses and stringifies JWKs in a fresh global object.
// Detach internal JSON values from the current global's mutable prototypes to
// approximate those fresh-realm semantics without creating a new realm.
function detachFromUserPrototypes(value) {
if (value === null || typeof value !== 'object')
return;
ObjectSetPrototypeOf(value, null);
if (ArrayIsArray(value)) {
setOwnProperty(value, SymbolIterator, safeArrayIterator);
for (let n = 0; n < value.length; n++)
detachFromUserPrototypes(value[n]);
return;
}
const keys = ObjectKeys(value);
for (let n = 0; n < keys.length; n++)
detachFromUserPrototypes(value[keys[n]]);
}
// Parse wrapped JWK bytes according to WebCrypto's "parse a JWK" procedure.
function parseJwk(keyData) {
let key;
try {
// WebCrypto parses JWKs in a fresh global. Detach parsed JSON values
// from user-mutated prototypes before WebIDL dictionary conversion.
// Wrapped JWKs may be produced outside WebCrypto, so parse using the
// spec-required UTF-8.
const json = decodeUTF8(keyData, false, true);
const result = JSONParse(json);
detachFromUserPrototypes(result);
key = webidl.converters.JsonWebKey(result);
} catch (err) {
throw lazyDOMException(
'Invalid wrapped JWK key',
{ name: 'DataError', cause: err });
}
if (!ObjectPrototypeHasOwnProperty(key, 'kty')) {
throw lazyDOMException(
'Invalid wrapped JWK key',
'DataError');
}
return key;
}
function aliasKeyFormat(format) {
switch (format) {
case 'raw-public':
@@ -967,15 +1051,21 @@ function wrapKeyImpl(format, key, wrappingKey, algorithm) {
let keyData = exportKeySync(format, key);
if (format === 'jwk') {
const ec = new TextEncoder();
const raw = JSONStringify(keyData);
// The WebCrypto spec stringifies JWKs in a new global object. Rather
// than create a new realm here, detach this internally generated JWK from
// user-mutated prototypes so JSON.stringify cannot read inherited toJSON
// hooks from the current global.
detachFromUserPrototypes(keyData);
const json = JSONStringify(keyData);
// As per the NOTE in step 13 https://w3c.github.io/webcrypto/#SubtleCrypto-method-wrapKey
// we're padding AES-KW wrapped JWK to make sure it is always a multiple of 8 bytes
// in length
if (algorithm.name === 'AES-KW' && raw.length % 8 !== 0) {
keyData = ec.encode(raw + StringPrototypeRepeat(' ', 8 - (raw.length % 8)));
// The spec then UTF-8 encodes json.
if (algorithm.name === 'AES-KW' && json.length % 8 !== 0) {
keyData = encodeUtf8String(
json + StringPrototypeRepeat(' ', 8 - (json.length % 8)));
} else {
keyData = ec.encode(raw);
keyData = encodeUtf8String(json);
}
}
@@ -1067,17 +1157,9 @@ function unwrapKeyImpl(
wrappedKey,
'unwrapKey');
return PromisePrototypeThen(keyData, (keyData) => {
return jobPromiseThen(keyData, (keyData) => {
if (format === 'jwk') {
// The fatal: true option is only supported in builds that have ICU.
const options = process.versions.icu !== undefined ?
{ fatal: true } : undefined;
const dec = new TextDecoder('utf-8', options);
try {
keyData = JSONParse(dec.decode(keyData));
} catch {
throw lazyDOMException('Invalid wrapped JWK key', 'DataError');
}
keyData = parseJwk(keyData);
}
return FunctionPrototypeCall(
@@ -1453,7 +1535,7 @@ function encapsulateKeyImpl(
throw lazyDOMException('Unrecognized algorithm name', 'NotSupportedError');
}
return PromisePrototypeThen(encapsulateBits, (encapsulateBits) => {
return jobPromiseThen(encapsulateBits, (encapsulateBits) => {
const sharedKey = FunctionPrototypeCall(
importKeySync,
this,
@@ -1593,7 +1675,7 @@ function decapsulateKeyImpl(
throw lazyDOMException('Unrecognized algorithm name', 'NotSupportedError');
}
return PromisePrototypeThen(decapsulatedBits, (decapsulatedBits) => FunctionPrototypeCall(
return jobPromiseThen(decapsulatedBits, (decapsulatedBits) => FunctionPrototypeCall(
importKeySync,
this,
'raw-secret', decapsulatedBits, normalizedSharedKeyAlgorithm, extractable,
+18 -16
View File
@@ -621,10 +621,10 @@ bool ExportJWKEcKey(Environment* env,
return false;
}
if (target->Set(
env->context(),
env->jwk_kty_string(),
env->jwk_ec_string()).IsNothing()) {
if (!target
->DefineOwnProperty(
env->context(), env->jwk_kty_string(), env->jwk_ec_string())
.FromMaybe(false)) {
return false;
}
@@ -664,10 +664,9 @@ bool ExportJWKEcKey(Environment* env,
return false;
}
}
if (target->Set(
env->context(),
env->jwk_crv_string(),
crv_name).IsNothing()) {
if (!target
->DefineOwnProperty(env->context(), env->jwk_crv_string(), crv_name)
.FromMaybe(false)) {
return false;
}
@@ -710,20 +709,23 @@ bool ExportJWKEdKey(Environment* env,
const ncrypto::Buffer<const char> out = data;
return StringBytes::Encode(env->isolate(), out.data, out.len, BASE64URL)
.ToLocal(&encoded) &&
target->Set(env->context(), key, encoded).IsJust();
target->DefineOwnProperty(env->context(), key, encoded)
.FromMaybe(false);
};
return !(
target
->Set(env->context(),
env->jwk_crv_string(),
OneByteString(env->isolate(), curve))
.IsNothing() ||
!target
->DefineOwnProperty(env->context(),
env->jwk_crv_string(),
OneByteString(env->isolate(), curve))
.FromMaybe(false) ||
(key.GetKeyType() == kKeyTypePrivate &&
!trySetKey(env, pkey.rawPrivateKey(), target, env->jwk_d_string())) ||
!trySetKey(env, pkey.rawPublicKey(), target, env->jwk_x_string()) ||
target->Set(env->context(), env->jwk_kty_string(), env->jwk_okp_string())
.IsNothing());
!target
->DefineOwnProperty(
env->context(), env->jwk_kty_string(), env->jwk_okp_string())
.FromMaybe(false));
}
KeyObjectData ImportJWKEdKey(Environment* env, Local<Object> jwk) {
Local<Value> crv_value;
+10 -10
View File
@@ -177,16 +177,16 @@ MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
if (params.job_mode == kCryptoJobWebCrypto) {
Local<Object> result = Object::New(env->isolate());
if (result
->Set(env->context(),
OneByteString(env->isolate(), "sharedKey"),
shared_key_obj.As<ArrayBufferView>()->Buffer())
.IsNothing() ||
result
->Set(env->context(),
OneByteString(env->isolate(), "ciphertext"),
ciphertext_obj.As<ArrayBufferView>()->Buffer())
.IsNothing()) {
if (!result
->DefineOwnProperty(env->context(),
OneByteString(env->isolate(), "sharedKey"),
shared_key_obj.As<ArrayBufferView>()->Buffer())
.FromMaybe(false) ||
!result
->DefineOwnProperty(env->context(),
OneByteString(env->isolate(), "ciphertext"),
ciphertext_obj.As<ArrayBufferView>()->Buffer())
.FromMaybe(false)) {
return MaybeLocal<Value>();
}
return result;
+8 -8
View File
@@ -184,14 +184,14 @@ class KeyGenJob final : public CryptoJob<KeyGenTraits> {
}
v8::Local<v8::Object> ret = v8::Object::New(isolate);
if (ret->Set(env->context(),
OneByteString(isolate, "publicKey"),
public_key)
.IsNothing() ||
ret->Set(env->context(),
OneByteString(isolate, "privateKey"),
private_key)
.IsNothing()) {
if (!ret->DefineOwnProperty(env->context(),
OneByteString(isolate, "publicKey"),
public_key)
.FromMaybe(false) ||
!ret->DefineOwnProperty(env->context(),
OneByteString(isolate, "privateKey"),
private_key)
.FromMaybe(false)) {
return {};
}
return ret;
+5 -3
View File
@@ -157,9 +157,11 @@ bool ExportJWKSecretKey(Environment* env,
BASE64URL)
.ToLocal(&raw) &&
target
->Set(env->context(), env->jwk_kty_string(), env->jwk_oct_string())
.IsJust() &&
target->Set(env->context(), env->jwk_k_string(), raw).IsJust();
->DefineOwnProperty(
env->context(), env->jwk_kty_string(), env->jwk_oct_string())
.FromMaybe(false) &&
target->DefineOwnProperty(env->context(), env->jwk_k_string(), raw)
.FromMaybe(false);
}
KeyObjectData ImportJWKSecretKey(Environment* env, Local<Object> jwk) {
+14 -11
View File
@@ -145,7 +145,8 @@ bool TrySetEncodedKey(Environment* env,
const ncrypto::Buffer<const char> out = data;
return StringBytes::Encode(env->isolate(), out.data, out.len, BASE64URL)
.ToLocal(&encoded) &&
target->Set(env->context(), key, encoded).IsJust();
target->DefineOwnProperty(env->context(), key, encoded)
.FromMaybe(false);
}
} // namespace
@@ -172,16 +173,18 @@ bool ExportJwkPqcKey(Environment* env,
}
}
return !(
target->Set(env->context(), env->jwk_kty_string(), env->jwk_akp_string())
.IsNothing() ||
target
->Set(env->context(),
env->jwk_alg_string(),
OneByteString(env->isolate(), alg->name))
.IsNothing() ||
!TrySetEncodedKey(
env, pkey.rawPublicKey(), target, env->jwk_pub_string()));
return !(!target
->DefineOwnProperty(env->context(),
env->jwk_kty_string(),
env->jwk_akp_string())
.FromMaybe(false) ||
!target
->DefineOwnProperty(env->context(),
env->jwk_alg_string(),
OneByteString(env->isolate(), alg->name))
.FromMaybe(false) ||
!TrySetEncodedKey(
env, pkey.rawPublicKey(), target, env->jwk_pub_string()));
}
KeyObjectData ImportJWKPqcKey(Environment* env, Local<Object> jwk) {
+4 -2
View File
@@ -337,8 +337,10 @@ bool ExportJWKRsaKey(Environment* env,
const ncrypto::Rsa rsa = m_pkey;
if (!rsa ||
target->Set(env->context(), env->jwk_kty_string(), env->jwk_rsa_string())
.IsNothing()) {
!target
->DefineOwnProperty(
env->context(), env->jwk_kty_string(), env->jwk_rsa_string())
.FromMaybe(false)) {
return false;
}
+3 -2
View File
@@ -666,8 +666,9 @@ Maybe<void> SetEncodedValue(Environment* env,
if (!EncodeBignum(env, bn, size).ToLocal(&value)) {
return Nothing<void>();
}
return target->Set(env->context(), name, value).IsJust() ? JustVoid()
: Nothing<void>();
return target->DefineOwnProperty(env->context(), name, value).FromMaybe(false)
? JustVoid()
: Nothing<void>();
}
CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args) {
+37 -2
View File
@@ -425,13 +425,45 @@ class CryptoJob : public AsyncWrap, public ThreadPoolWork {
private:
void ResolveWebCrypto(v8::Local<v8::Value> value) {
Environment* env = AsyncWrap::env();
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Promise::Resolver> resolver =
v8::Local<v8::Promise::Resolver>::New(env->isolate(), resolver_);
bool should_delete_then = false;
v8::Local<v8::String> then_key;
v8::Local<v8::Value> exception;
{
node::errors::TryCatchScope try_catch(env);
if (resolver->Resolve(env->context(), value).IsJust()) {
if (value->IsObject()) {
then_key = FIXED_ONE_BYTE_STRING(env->isolate(), "then");
v8::Local<v8::Object> object = value.As<v8::Object>();
v8::Maybe<bool> has_own_then =
object->HasOwnProperty(context, then_key);
if (has_own_then.IsNothing()) {
if (try_catch.HasCaught() && try_catch.CanContinue()) {
exception = try_catch.Exception();
}
} else if (!has_own_then.FromJust()) {
if (object
->DefineOwnProperty(context,
then_key,
v8::Undefined(env->isolate()),
v8::DontEnum)
.FromMaybe(false)) {
should_delete_then = true;
} else if (try_catch.HasCaught() && try_catch.CanContinue()) {
exception = try_catch.Exception();
} else {
exception = v8::Exception::Error(OneByteString(
env->isolate(), "Failed to prepare WebCrypto job result"));
}
}
}
if (exception.IsEmpty() && resolver->Resolve(context, value).IsJust()) {
if (should_delete_then) {
USE(value.As<v8::Object>()->Delete(context, then_key));
}
resolver_.Reset();
return;
}
@@ -440,8 +472,11 @@ class CryptoJob : public AsyncWrap, public ThreadPoolWork {
}
}
if (should_delete_then) {
USE(value.As<v8::Object>()->Delete(context, then_key));
}
if (!exception.IsEmpty()) {
USE(resolver->Reject(env->context(), exception));
USE(resolver->Reject(context, exception));
}
resolver_.Reset();
}
+63 -15
View File
@@ -7,6 +7,7 @@ if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const { hasOpenSSL } = require('../common/crypto');
const { types: { isCryptoKey } } = require('util');
const { internalBinding } = require('internal/test/binding');
const {
@@ -31,6 +32,34 @@ const {
const { subtle } = globalThis.crypto;
// Defines Object.prototype setters that fail the test if native result objects
// carrying key or shared secret material use [[Set]].
async function withObjectPrototypeSetters(names, fn) {
const descriptors = new Map();
for (const name of names) {
descriptors.set(name, Object.getOwnPropertyDescriptor(Object.prototype, name));
Object.defineProperty(Object.prototype, name, {
__proto__: null,
configurable: true,
get: common.mustNotCall(`Object.prototype.${name} getter`),
set: common.mustNotCall(`Object.prototype.${name} setter`),
});
}
try {
return await fn();
} finally {
for (const name of names) {
const descriptor = descriptors.get(name);
if (descriptor === undefined) {
delete Object.prototype[name];
} else {
Object.defineProperty(Object.prototype, name, descriptor);
}
}
}
}
(async function() {
{
const promise = new HashJob(
@@ -49,6 +78,7 @@ const { subtle } = globalThis.crypto;
const digest = await promise;
assert(digest instanceof ArrayBuffer);
assert.strictEqual(digest.byteLength, 32);
assert.strictEqual(Object.hasOwn(digest, 'then'), false);
}
{
@@ -67,16 +97,19 @@ const { subtle } = globalThis.crypto;
}
{
const pair = await new EcKeyPairGenJob(
kCryptoJobWebCrypto,
'P-256',
undefined,
{ name: 'ECDSA', namedCurve: 'P-256' },
getUsagesMask(new Set(['verify'])),
getUsagesMask(new Set(['sign'])),
true).run();
const pair = await withObjectPrototypeSetters(
['publicKey', 'privateKey'],
() => new EcKeyPairGenJob(
kCryptoJobWebCrypto,
'P-256',
undefined,
{ name: 'ECDSA', namedCurve: 'P-256' },
getUsagesMask(new Set(['verify'])),
getUsagesMask(new Set(['sign'])),
true).run());
assert.strictEqual(Object.getPrototypeOf(pair), Object.prototype);
assert.strictEqual(Object.hasOwn(pair, 'then'), false);
assert(isCryptoKey(pair.publicKey));
assert(isCryptoKey(pair.privateKey));
assert(pair.publicKey instanceof CryptoKey);
@@ -163,18 +196,33 @@ const { subtle } = globalThis.crypto;
Object.defineProperty(CryptoKey.prototype, 'then', {
__proto__: null,
configurable: true,
get() { throw new Error('resolve then getter'); },
get: common.mustNotCall('CryptoKey.prototype.then getter'),
});
try {
await assert.rejects(
subtle.generateKey(
{ name: 'AES-CBC', length: 128 },
true,
['encrypt']),
/resolve then getter/);
const key = await subtle.generateKey(
{ name: 'AES-CBC', length: 128 },
true,
['encrypt']);
assert(isCryptoKey(key));
assert.strictEqual(Object.hasOwn(key, 'then'), false);
} finally {
delete CryptoKey.prototype.then;
}
}
if (hasOpenSSL(3, 5) || process.features.openssl_is_boringssl) {
const pair = await subtle.generateKey(
{ name: 'ML-KEM-768' },
true,
['encapsulateBits', 'decapsulateBits']);
const result = await withObjectPrototypeSetters(
['sharedKey', 'ciphertext'],
() => subtle.encapsulateBits({ name: 'ML-KEM-768' }, pair.publicKey));
assert.strictEqual(Object.getPrototypeOf(result), Object.prototype);
assert.strictEqual(Object.hasOwn(result, 'then'), false);
assert(result.sharedKey instanceof ArrayBuffer);
assert(result.ciphertext instanceof ArrayBuffer);
}
})().then(common.mustCall());
@@ -1,9 +1,10 @@
import * as common from '../common/index.mjs';
import assert from 'node:assert';
if (!common.hasCrypto) common.skip('missing crypto');
// WebCrypto subtle methods must not leak intermediate values
// through Promise.prototype.then pollution.
// through Promise.prototype.then or constructor pollution.
// Regression test for https://github.com/nodejs/node/pull/61492
// and https://github.com/nodejs/node/issues/59699.
@@ -13,51 +14,442 @@ const { subtle } = globalThis.crypto;
Promise.prototype.then = common.mustNotCall('Promise.prototype.then');
await subtle.digest('SHA-256', new Uint8Array([1, 2, 3]));
// WebCrypto methods return native promises. Re-wrapping a promise with
// PromiseResolve() or chaining it with Promise.prototype.then can read
// user-mutated constructor/species accessors.
async function assertNoPromiseConstructorAccess(name, fn) {
const constructorDescriptor =
Object.getOwnPropertyDescriptor(Promise.prototype, 'constructor');
const speciesDescriptor =
Object.getOwnPropertyDescriptor(Promise, Symbol.species);
let promise;
Object.defineProperty(Promise.prototype, 'constructor', {
__proto__: null,
configurable: true,
get: common.mustNotCall(
`${name} Promise.prototype.constructor getter`),
});
Object.defineProperty(Promise, Symbol.species, {
__proto__: null,
configurable: true,
get: common.mustNotCall(`${name} Promise[Symbol.species] getter`),
});
try {
promise = fn();
} finally {
Object.defineProperty(
Promise.prototype,
'constructor',
constructorDescriptor);
Object.defineProperty(Promise, Symbol.species, speciesDescriptor);
}
return await promise;
}
await subtle.generateKey({ name: 'AES-CBC', length: 256 }, true, ['encrypt', 'decrypt']);
// Exercise each export format through the same promise-constructor guard.
function assertExportKeyNoPromiseConstructorAccess(name, format, key) {
return assertNoPromiseConstructorAccess(`exportKey ${name}`, () =>
subtle.exportKey(format, key));
}
await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']);
// Non-promise object results must be fulfilled without thenable assimilation
// observing inherited then accessors on the returned object.
async function assertNoInheritedThenAccess(name, prototype, prototypeName, fn) {
const descriptor = Object.getOwnPropertyDescriptor(prototype, 'then');
Object.defineProperty(prototype, 'then', {
__proto__: null,
configurable: true,
get: common.mustNotCall(`${name} ${prototypeName}.prototype.then`),
});
try {
return await fn();
} finally {
if (descriptor === undefined) {
delete prototype.then;
} else {
Object.defineProperty(prototype, 'then', descriptor);
}
}
}
function assertNoInheritedArrayBufferThenAccess(name, fn) {
return assertNoInheritedThenAccess(
name,
ArrayBuffer.prototype,
'ArrayBuffer',
fn);
}
function assertNoInheritedCryptoKeyThenAccess(name, fn) {
return assertNoInheritedThenAccess(
name,
CryptoKey.prototype,
'CryptoKey',
fn);
}
function assertNoInheritedObjectThenAccess(name, fn) {
return assertNoInheritedThenAccess(
name,
Object.prototype,
'Object',
fn);
}
// wrapKey('jwk') stringifies an internally exported JWK. The spec does this
// in a fresh global, so inherited toJSON hooks from the current global must
// not observe or replace key material.
async function assertNoInheritedToJSONAccess(name, fn) {
const objectDescriptor =
Object.getOwnPropertyDescriptor(Object.prototype, 'toJSON');
const arrayDescriptor =
Object.getOwnPropertyDescriptor(Array.prototype, 'toJSON');
Object.defineProperty(Object.prototype, 'toJSON', {
__proto__: null,
configurable: true,
value: common.mustNotCall(`${name} Object.prototype.toJSON`),
});
Object.defineProperty(Array.prototype, 'toJSON', {
__proto__: null,
configurable: true,
value: common.mustNotCall(`${name} Array.prototype.toJSON`),
});
try {
return await fn();
} finally {
if (objectDescriptor === undefined) {
delete Object.prototype.toJSON;
} else {
Object.defineProperty(Object.prototype, 'toJSON', objectDescriptor);
}
if (arrayDescriptor === undefined) {
delete Array.prototype.toJSON;
} else {
Object.defineProperty(Array.prototype, 'toJSON', arrayDescriptor);
}
}
}
// JWK export creates and fills a result object. The exported members must be
// own data properties, not writes that can observe inherited accessors.
async function assertNoInheritedJwkPropertyAccess(name, fn) {
const properties = [
'alg',
'crv',
'd',
'dp',
'dq',
'e',
'ext',
'k',
'key_ops',
'kty',
'n',
'p',
'priv',
'pub',
'q',
'qi',
'x',
'y',
];
const descriptors = new Map();
for (const property of properties) {
descriptors.set(
property,
Object.getOwnPropertyDescriptor(Object.prototype, property));
Object.defineProperty(Object.prototype, property, {
__proto__: null,
configurable: true,
get: common.mustNotCall(`${name} Object.prototype.${property} getter`),
set: common.mustNotCall(`${name} Object.prototype.${property} setter`),
});
}
try {
return await fn();
} finally {
for (const property of properties) {
const descriptor = descriptors.get(property);
if (descriptor === undefined) {
delete Object.prototype[property];
} else {
Object.defineProperty(Object.prototype, property, descriptor);
}
}
}
}
// unwrapKey('jwk') parses a JWK and then converts it to the JsonWebKey IDL
// dictionary. The parsed JWK must provide its own kty member; an inherited
// Object.prototype.kty must not satisfy that required WebCrypto step.
async function assertMissingJwkKtyIgnoresPrototype(fn) {
const descriptor = Object.getOwnPropertyDescriptor(Object.prototype, 'kty');
Object.defineProperty(Object.prototype, 'kty', {
__proto__: null,
configurable: true,
value: 'oct',
});
try {
await assert.rejects(fn(), { name: 'DataError' });
} finally {
if (descriptor === undefined) {
delete Object.prototype.kty;
} else {
Object.defineProperty(Object.prototype, 'kty', descriptor);
}
}
}
// wrapKey('jwk') UTF-8 encodes the JSON string. That step must not rely on
// user-mutable encoding APIs such as TextEncoder or Buffer.
async function assertNoUserMutableEncodeAccess(name, fn) {
const textEncoderDescriptor =
Object.getOwnPropertyDescriptor(TextEncoder.prototype, 'encode');
const bufferFromDescriptor = Object.getOwnPropertyDescriptor(Buffer, 'from');
Object.defineProperty(TextEncoder.prototype, 'encode', {
__proto__: null,
configurable: true,
value: common.mustNotCall(`${name} TextEncoder.prototype.encode`),
});
Object.defineProperty(Buffer, 'from', {
__proto__: null,
configurable: true,
value: common.mustNotCall(`${name} Buffer.from`),
});
try {
return await fn();
} finally {
Object.defineProperty(
TextEncoder.prototype,
'encode',
textEncoderDescriptor);
Object.defineProperty(Buffer, 'from', bufferFromDescriptor);
}
}
// unwrapKey('jwk') decodes the wrapped bytes as UTF-8. That step must not
// rely on user-mutable encoding APIs such as TextDecoder or Buffer.
async function assertNoUserMutableDecodeAccess(name, fn) {
const textDecoderDescriptor =
Object.getOwnPropertyDescriptor(TextDecoder.prototype, 'decode');
const bufferFromDescriptor = Object.getOwnPropertyDescriptor(Buffer, 'from');
const bufferToStringDescriptor =
Object.getOwnPropertyDescriptor(Buffer.prototype, 'toString');
Object.defineProperty(TextDecoder.prototype, 'decode', {
__proto__: null,
configurable: true,
value: common.mustNotCall(`${name} TextDecoder.prototype.decode`),
});
Object.defineProperty(Buffer, 'from', {
__proto__: null,
configurable: true,
value: common.mustNotCall(`${name} Buffer.from`),
});
Object.defineProperty(Buffer.prototype, 'toString', {
__proto__: null,
configurable: true,
value: common.mustNotCall(`${name} Buffer.prototype.toString`),
});
try {
return await fn();
} finally {
Object.defineProperty(
TextDecoder.prototype,
'decode',
textDecoderDescriptor);
Object.defineProperty(Buffer, 'from', bufferFromDescriptor);
Object.defineProperty(
Buffer.prototype,
'toString',
bufferToStringDescriptor);
}
}
// encapsulateKey() first resolves an internal encapsulateBits job whose result
// object contains a raw sharedKey. The final method result is also an object,
// but its sharedKey is a CryptoKey and is intentionally returned to the caller.
async function assertNoRawSharedKeyObjectThenAccess(name, fn) {
const descriptor = Object.getOwnPropertyDescriptor(Object.prototype, 'then');
Object.defineProperty(Object.prototype, 'then', {
__proto__: null,
configurable: true,
get() {
if (Object.hasOwn(this, 'sharedKey') &&
this.sharedKey instanceof ArrayBuffer) {
assert.fail(`${name} Object.prototype.then observed raw sharedKey`);
}
return undefined;
},
});
try {
return await fn();
} finally {
if (descriptor === undefined) {
delete Object.prototype.then;
} else {
Object.defineProperty(Object.prototype, 'then', descriptor);
}
}
}
await assertNoPromiseConstructorAccess('digest', () =>
subtle.digest('SHA-256', new Uint8Array([1, 2, 3])));
const secretKey = await assertNoPromiseConstructorAccess(
'generateKey secret',
() => subtle.generateKey(
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
const extractableKeyPair = await assertNoPromiseConstructorAccess('generateKey pair', () =>
subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-256' },
true,
['sign', 'verify']));
const rawKey = globalThis.crypto.getRandomValues(new Uint8Array(32));
const importedKey = await subtle.importKey(
'raw', rawKey, { name: 'AES-CBC', length: 256 }, false, ['encrypt', 'decrypt']);
const importedKey = await assertNoPromiseConstructorAccess('importKey', () =>
subtle.importKey(
'raw',
rawKey,
{ name: 'AES-CBC', length: 256 },
false,
['encrypt', 'decrypt']));
const exportableKey = await subtle.importKey(
'raw', rawKey, { name: 'AES-CBC', length: 256 }, true, ['encrypt', 'decrypt']);
await assertNoInheritedCryptoKeyThenAccess('importKey', () =>
subtle.importKey(
'raw',
rawKey,
{ name: 'AES-CBC', length: 256 },
false,
['encrypt', 'decrypt']));
await subtle.exportKey('raw', exportableKey);
await assertNoInheritedJwkPropertyAccess('exportKey jwk secret', () =>
assertExportKeyNoPromiseConstructorAccess(
'jwk secret',
'jwk',
secretKey));
await assertNoInheritedObjectThenAccess('exportKey jwk secret', () =>
subtle.exportKey('jwk', secretKey));
await assertNoInheritedJwkPropertyAccess('exportKey jwk public', () =>
assertExportKeyNoPromiseConstructorAccess(
'jwk public',
'jwk',
extractableKeyPair.publicKey));
await assertNoInheritedObjectThenAccess('exportKey jwk public', () =>
subtle.exportKey('jwk', extractableKeyPair.publicKey));
await assertNoInheritedJwkPropertyAccess('exportKey jwk private', () =>
assertExportKeyNoPromiseConstructorAccess(
'jwk private',
'jwk',
extractableKeyPair.privateKey));
await assertNoInheritedObjectThenAccess('exportKey jwk private', () =>
subtle.exportKey('jwk', extractableKeyPair.privateKey));
await assertNoInheritedArrayBufferThenAccess('exportKey raw secret', () =>
subtle.exportKey('raw', secretKey));
await assertExportKeyNoPromiseConstructorAccess(
'raw secret',
'raw',
secretKey);
await assertNoInheritedArrayBufferThenAccess('exportKey spki', () =>
subtle.exportKey('spki', extractableKeyPair.publicKey));
await assertExportKeyNoPromiseConstructorAccess(
'spki',
'spki',
extractableKeyPair.publicKey);
await assertNoInheritedArrayBufferThenAccess('exportKey pkcs8', () =>
subtle.exportKey('pkcs8', extractableKeyPair.privateKey));
await assertExportKeyNoPromiseConstructorAccess(
'pkcs8',
'pkcs8',
extractableKeyPair.privateKey);
await assertNoInheritedArrayBufferThenAccess('exportKey raw-public', () =>
subtle.exportKey('raw-public', extractableKeyPair.publicKey));
await assertExportKeyNoPromiseConstructorAccess(
'raw-public',
'raw-public',
extractableKeyPair.publicKey);
const iv = globalThis.crypto.getRandomValues(new Uint8Array(16));
const plaintext = new TextEncoder().encode('Hello, world!');
const ciphertext = await subtle.encrypt({ name: 'AES-CBC', iv }, importedKey, plaintext);
const ciphertext = await assertNoPromiseConstructorAccess('encrypt', () =>
subtle.encrypt({ name: 'AES-CBC', iv }, importedKey, plaintext));
await subtle.decrypt({ name: 'AES-CBC', iv }, importedKey, ciphertext);
await assertNoPromiseConstructorAccess('decrypt', () =>
subtle.decrypt({ name: 'AES-CBC', iv }, importedKey, ciphertext));
const signingKey = await subtle.generateKey(
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign', 'verify']);
const data = new TextEncoder().encode('test data');
const signature = await subtle.sign('HMAC', signingKey, data);
const signature = await assertNoPromiseConstructorAccess('sign', () =>
subtle.sign('HMAC', signingKey, data));
await subtle.verify('HMAC', signingKey, signature, data);
await assertNoPromiseConstructorAccess('verify', () =>
subtle.verify('HMAC', signingKey, signature, data));
const pbkdf2Key = await subtle.importKey(
'raw', rawKey, 'PBKDF2', false, ['deriveBits', 'deriveKey']);
await subtle.deriveBits(
{ name: 'PBKDF2', salt: rawKey, iterations: 1000, hash: 'SHA-256' },
pbkdf2Key, 256);
await assertNoPromiseConstructorAccess('deriveBits', () =>
subtle.deriveBits(
{ name: 'PBKDF2', salt: rawKey, iterations: 1000, hash: 'SHA-256' },
pbkdf2Key,
256));
await subtle.deriveKey(
{ name: 'PBKDF2', salt: rawKey, iterations: 1000, hash: 'SHA-256' },
pbkdf2Key,
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']);
await assertNoPromiseConstructorAccess('deriveBits PBKDF2 zero-length', () =>
subtle.deriveBits(
{ name: 'PBKDF2', salt: rawKey, iterations: 1000, hash: 'SHA-256' },
pbkdf2Key,
0));
const hkdfKey = await subtle.importKey(
'raw', rawKey, 'HKDF', false, ['deriveBits']);
await assertNoPromiseConstructorAccess('deriveBits HKDF zero-length', () =>
subtle.deriveBits(
{ name: 'HKDF', hash: 'SHA-256', salt: rawKey, info: rawKey },
hkdfKey,
0));
const ecdhKeyPair = await subtle.generateKey(
{ name: 'ECDH', namedCurve: 'P-256' },
false,
['deriveBits']);
await assertNoPromiseConstructorAccess('deriveBits ECDH', () =>
subtle.deriveBits(
{ name: 'ECDH', public: ecdhKeyPair.publicKey },
ecdhKeyPair.privateKey,
256));
await assertNoPromiseConstructorAccess('deriveKey', () =>
subtle.deriveKey(
{ name: 'PBKDF2', salt: rawKey, iterations: 1000, hash: 'SHA-256' },
pbkdf2Key,
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
await assertNoInheritedArrayBufferThenAccess('deriveKey', () =>
subtle.deriveKey(
{ name: 'PBKDF2', salt: rawKey, iterations: 1000, hash: 'SHA-256' },
pbkdf2Key,
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
await assertNoInheritedCryptoKeyThenAccess('deriveKey result', () =>
subtle.deriveKey(
{ name: 'PBKDF2', salt: rawKey, iterations: 1000, hash: 'SHA-256' },
pbkdf2Key,
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
const wrappingKey = await subtle.generateKey(
{ name: 'AES-KW', length: 256 }, true, ['wrapKey', 'unwrapKey']);
@@ -65,31 +457,224 @@ const wrappingKey = await subtle.generateKey(
const keyToWrap = await subtle.generateKey(
{ name: 'AES-CBC', length: 256 }, true, ['encrypt', 'decrypt']);
const wrapped = await subtle.wrapKey('raw', keyToWrap, wrappingKey, 'AES-KW');
const wrapped = await assertNoPromiseConstructorAccess('wrapKey', () =>
subtle.wrapKey('raw', keyToWrap, wrappingKey, 'AES-KW'));
await subtle.unwrapKey(
'raw', wrapped, wrappingKey, 'AES-KW',
{ name: 'AES-CBC', length: 256 }, true, ['encrypt', 'decrypt']);
const wrappedJwk = await assertNoInheritedJwkPropertyAccess('wrapKey jwk', () =>
assertNoInheritedToJSONAccess('wrapKey jwk', () =>
assertNoUserMutableEncodeAccess('wrapKey jwk', () =>
assertNoPromiseConstructorAccess('wrapKey jwk', () =>
subtle.wrapKey('jwk', keyToWrap, wrappingKey, 'AES-KW')))));
const { privateKey } = await subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']);
await assertNoPromiseConstructorAccess('unwrapKey', () =>
subtle.unwrapKey(
'raw',
wrapped,
wrappingKey,
'AES-KW',
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
await assertNoInheritedArrayBufferThenAccess('unwrapKey', () =>
subtle.unwrapKey(
'raw',
wrapped,
wrappingKey,
'AES-KW',
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
await assertNoInheritedCryptoKeyThenAccess('unwrapKey result', () =>
subtle.unwrapKey(
'raw',
wrapped,
wrappingKey,
'AES-KW',
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
await subtle.getPublicKey(privateKey, ['verify']);
await assertNoUserMutableDecodeAccess('unwrapKey jwk', () =>
assertNoPromiseConstructorAccess('unwrapKey jwk', () =>
subtle.unwrapKey(
'jwk',
wrappedJwk,
wrappingKey,
'AES-KW',
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt'])));
await assertNoInheritedArrayBufferThenAccess('unwrapKey jwk', () =>
subtle.unwrapKey(
'jwk',
wrappedJwk,
wrappingKey,
'AES-KW',
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
await assertNoInheritedCryptoKeyThenAccess('unwrapKey jwk result', () =>
subtle.unwrapKey(
'jwk',
wrappedJwk,
wrappingKey,
'AES-KW',
{ name: 'AES-CBC', length: 256 },
true,
['encrypt', 'decrypt']));
{
const jwkUnwrappingKey = await subtle.generateKey(
{ name: 'AES-CBC', length: 128 },
true,
['encrypt', 'unwrapKey']);
{
const iv = globalThis.crypto.getRandomValues(new Uint8Array(16));
const validWrappedJwk = await subtle.encrypt(
{ name: 'AES-CBC', iv },
jwkUnwrappingKey,
Buffer.from('{"kty":"oct","k":"AAAAAAAAAAAAAAAAAAAAAA"}'));
await assertNoUserMutableDecodeAccess('unwrapKey jwk AES-CBC', () =>
assertNoPromiseConstructorAccess('unwrapKey jwk AES-CBC', () =>
subtle.unwrapKey(
'jwk',
validWrappedJwk,
jwkUnwrappingKey,
{ name: 'AES-CBC', iv },
{ name: 'AES-CBC', length: 128 },
true,
['encrypt'])));
await assertNoInheritedCryptoKeyThenAccess(
'unwrapKey jwk AES-CBC result',
() => subtle.unwrapKey(
'jwk',
validWrappedJwk,
jwkUnwrappingKey,
{ name: 'AES-CBC', iv },
{ name: 'AES-CBC', length: 128 },
true,
['encrypt']));
}
{
const iv = globalThis.crypto.getRandomValues(new Uint8Array(16));
const wrappedRawKey = await subtle.encrypt(
{ name: 'AES-CBC', iv },
jwkUnwrappingKey,
rawKey);
await assertNoPromiseConstructorAccess('unwrapKey raw AES-CBC', () =>
subtle.unwrapKey(
'raw',
wrappedRawKey,
jwkUnwrappingKey,
{ name: 'AES-CBC', iv },
{ name: 'AES-CBC', length: 256 },
true,
['encrypt']));
await assertNoInheritedArrayBufferThenAccess('unwrapKey raw AES-CBC', () =>
subtle.unwrapKey(
'raw',
wrappedRawKey,
jwkUnwrappingKey,
{ name: 'AES-CBC', iv },
{ name: 'AES-CBC', length: 256 },
true,
['encrypt']));
await assertNoInheritedCryptoKeyThenAccess(
'unwrapKey raw AES-CBC result',
() => subtle.unwrapKey(
'raw',
wrappedRawKey,
jwkUnwrappingKey,
{ name: 'AES-CBC', iv },
{ name: 'AES-CBC', length: 256 },
true,
['encrypt']));
}
{
const iv = globalThis.crypto.getRandomValues(new Uint8Array(16));
const missingKtyWrappedJwk = await subtle.encrypt(
{ name: 'AES-CBC', iv },
jwkUnwrappingKey,
Buffer.from('{"k":"AAAAAAAAAAAAAAAAAAAAAA"}'));
await assertMissingJwkKtyIgnoresPrototype(() =>
subtle.unwrapKey(
'jwk',
missingKtyWrappedJwk,
jwkUnwrappingKey,
{ name: 'AES-CBC', iv },
{ name: 'AES-CBC', length: 128 },
true,
['encrypt']));
}
}
await assertNoPromiseConstructorAccess('getPublicKey', () =>
subtle.getPublicKey(extractableKeyPair.privateKey, ['verify']));
await assertNoInheritedCryptoKeyThenAccess('getPublicKey', () =>
subtle.getPublicKey(extractableKeyPair.privateKey, ['verify']));
if (hasOpenSSL(3, 5) || process.features.openssl_is_boringssl) {
const kemPair = await subtle.generateKey(
{ name: 'ML-KEM-768' }, false,
{ name: 'ML-KEM-768' }, true,
['encapsulateKey', 'encapsulateBits', 'decapsulateKey', 'decapsulateBits']);
const { ciphertext: ct1 } = await subtle.encapsulateKey(
{ name: 'ML-KEM-768' }, kemPair.publicKey, 'HKDF', false, ['deriveBits']);
await assertNoInheritedArrayBufferThenAccess('exportKey raw-seed', () =>
subtle.exportKey('raw-seed', kemPair.privateKey));
await assertExportKeyNoPromiseConstructorAccess(
'raw-seed',
'raw-seed',
kemPair.privateKey);
await subtle.decapsulateKey(
{ name: 'ML-KEM-768' }, kemPair.privateKey, ct1, 'HKDF', false, ['deriveBits']);
const { ciphertext: ct1 } =
await assertNoRawSharedKeyObjectThenAccess('encapsulateKey', () =>
assertNoPromiseConstructorAccess('encapsulateKey', () =>
subtle.encapsulateKey(
{ name: 'ML-KEM-768' },
kemPair.publicKey,
'HKDF',
false,
['deriveBits'])));
const { ciphertext: ct2 } = await subtle.encapsulateBits(
{ name: 'ML-KEM-768' }, kemPair.publicKey);
await assertNoPromiseConstructorAccess('decapsulateKey', () =>
subtle.decapsulateKey(
{ name: 'ML-KEM-768' },
kemPair.privateKey,
ct1,
'HKDF',
false,
['deriveBits']));
await assertNoInheritedArrayBufferThenAccess('decapsulateKey', () =>
subtle.decapsulateKey(
{ name: 'ML-KEM-768' },
kemPair.privateKey,
ct1,
'HKDF',
false,
['deriveBits']));
await assertNoInheritedCryptoKeyThenAccess('decapsulateKey result', () =>
subtle.decapsulateKey(
{ name: 'ML-KEM-768' },
kemPair.privateKey,
ct1,
'HKDF',
false,
['deriveBits']));
await subtle.decapsulateBits(
{ name: 'ML-KEM-768' }, kemPair.privateKey, ct2);
const { ciphertext: ct2 } =
await assertNoPromiseConstructorAccess('encapsulateBits', () =>
subtle.encapsulateBits(
{ name: 'ML-KEM-768' },
kemPair.publicKey));
await assertNoPromiseConstructorAccess('decapsulateBits', () =>
subtle.decapsulateBits(
{ name: 'ML-KEM-768' },
kemPair.privateKey,
ct2));
}