The headless browser for AI agents and web scraping
fix(js): validate key wrapping permissions
SGavrld853a7313f33
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 69b20645..e6399853 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -16849,22 +16849,31 @@ if (!globalThis.crypto.subtle) {}function makeKey(type, extractable, algorithm, usages, bytes) {const k = Object.create(CryptoKey.prototype);+ const publicAlgorithm = Object.assign({}, algorithm);+ if (algorithm.hash) publicAlgorithm.hash = Object.assign({}, algorithm.hash);Object.defineProperty(k, "type", { value: type, enumerable: true });Object.defineProperty(k, "extractable", { value: !!extractable, enumerable: true });- Object.defineProperty(k, "algorithm", { value: algorithm, enumerable: true });+ Object.defineProperty(k, "algorithm", { value: publicAlgorithm, enumerable: true });Object.defineProperty(k, "usages", { value: Object.freeze((usages || []).slice()), enumerable: true });- keyMaterial.set(k, bytes);+ keyMaterial.set(k, {bytes, algorithm, usages: k.usages});return k;}- function keyBytes(key) {+ function keyBytes(key, algorithm, usage) {if (!(key instanceof CryptoKey) || !keyMaterial.has(key)) {throw new DOMException("Argument is not a valid CryptoKey", "InvalidAccessError");}- return keyMaterial.get(key);+ const material = keyMaterial.get(key);+ if (usage && algorithm !== "AES-KW" && algorithm !== "AES-GCM" && algorithm !== "AES-CBC" && algorithm !== "AES-CTR") {+ throw new DOMException("Unsupported key wrapping algorithm: " + algorithm, "NotSupportedError");+ }+ if (usage && (material.algorithm.name !== algorithm || !material.usages.includes(usage))) {+ throw new DOMException("Key does not allow " + usage + " with " + algorithm, "InvalidAccessError");+ }+ return material.bytes;}_idbPlatformCodecs.push({name:"CryptoKey", test:key => keyMaterial.has(key),- encode:key => ({type:key.type,extractable:key.extractable,algorithm:key.algorithm,usages:key.usages,bytes:keyBytes(key)}),+ encode:key => ({type:key.type,extractable:key.extractable,...keyMaterial.get(key)}),decode:data => makeKey(data.type,data.extractable,data.algorithm,data.usages,data.bytes),});// A CryptoKey cloned via structuredClone or postMessage is a different@@ -16879,7 +16888,9 @@ if (!globalThis.crypto.subtle) {// material is registered once), matching structuredClone's identity rules.globalThis.__obscura_clone_hooks["CryptoKey"] = function (src, seen) {if (seen && seen.has(src)) return seen.get(src);- const copy = makeKey(src.type, src.extractable, src.algorithm, src.usages, keyBytes(src));+ const bytes = keyBytes(src);+ const material = keyMaterial.get(src);+ const copy = makeKey(src.type, src.extractable, material.algorithm, material.usages, bytes);if (seen) seen.set(src, copy);return copy;};@@ -16938,10 +16949,11 @@ if (!globalThis.crypto.subtle) {// The JWK `alg` of an AES or HMAC key, or undefined for the others.function jwkAlg(key, bytes) {- if (key.algorithm.name && key.algorithm.name.indexOf("AES-") === 0) {- return "A" + (bytes.length * 8) + key.algorithm.name.slice(4);+ const algorithm = keyMaterial.get(key).algorithm;+ if (algorithm.name && algorithm.name.indexOf("AES-") === 0) {+ return "A" + (bytes.length * 8) + algorithm.name.slice(4);}- if (key.algorithm.name === "HMAC") return "HS" + key.algorithm.hash.name.slice(4);+ if (algorithm.name === "HMAC") return "HS" + algorithm.hash.name.slice(4);return undefined;}@@ -17089,6 +17101,7 @@ if (!globalThis.crypto.subtle) {async wrapKey(format, key, wrappingKey, wrapAlgorithm) {const alg = normalizeAlgo(wrapAlgorithm);+ const wrappingBytes = keyBytes(wrappingKey, alg.name, "wrapKey");const exported = await this.exportKey(format, key);// A JWK is serialized natively rather than with the page's JSON.stringify,// so a toJSON or another prototype override can't change the wrapped bytes.@@ -17102,15 +17115,16 @@ if (!globalThis.crypto.subtle) {}// AES-KW has no encrypt, only its key wrap.if (alg.name === "AES-KW") {- return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_aes_kw(true, keyBytes(wrappingKey), bytes)));+ return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_aes_kw(true, wrappingBytes, bytes)));}return this.encrypt(wrapAlgorithm, wrappingKey, bytes);},async unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) {const alg = normalizeAlgo(unwrapAlgorithm);+ const unwrappingBytes = keyBytes(unwrappingKey, alg.name, "unwrapKey");const decrypted = alg.name === "AES-KW"- ? runOp(() => __obscuraCore.ops.op_subtle_aes_kw(false, keyBytes(unwrappingKey), toBytes(wrappedKey)))+ ? runOp(() => __obscuraCore.ops.op_subtle_aes_kw(false, unwrappingBytes, toBytes(wrappedKey))): new Uint8Array(await this.decrypt(unwrapAlgorithm, unwrappingKey, wrappedKey));let keyData;if (format === "jwk") {diff --git a/crates/obscura-js/src/webcrypto_tests.rs b/crates/obscura-js/src/webcrypto_tests.rsindex 1e3223f9..b82dd9b1 100644--- a/crates/obscura-js/src/webcrypto_tests.rs+++ b/crates/obscura-js/src/webcrypto_tests.rs@@ -98,3 +98,92 @@ async fn wrapped_jwks_ignore_the_pages_json() {"DataError",]));}++#[tokio::test]+async fn key_wrapping_checks_the_wrapping_keys_algorithm_and_usage() {+ let out = probe(r#"+ const bytes = new Uint8Array(16);+ const payload = await s.importKey('raw', bytes, 'AES-GCM', true, ['encrypt']);+ const results = [];+ for (const name of ['AES-KW', 'AES-GCM', 'AES-CBC', 'AES-CTR']) {+ const alg = name === 'AES-GCM' ? {name, iv: new Uint8Array(12)}+ : name === 'AES-CBC' ? {name, iv: new Uint8Array(16)}+ : name === 'AES-CTR' ? {name, counter: new Uint8Array(16), length: 64} : name;+ const unwrapOnly = await s.importKey('raw', bytes, name, false, ['unwrapKey']);+ const wrongAlgorithm = await s.importKey('raw', bytes, {name:'HMAC', hash:'SHA-256'}, false, ['sign']);+ results.push(await errorName(() => s.wrapKey('raw', payload, unwrapOnly, alg)));+ results.push(await errorName(() => s.wrapKey('raw', payload, wrongAlgorithm, alg)));+ wrongAlgorithm.algorithm.name = name;+ results.push(await errorName(() => s.wrapKey('raw', payload, wrongAlgorithm, alg)));+ const wrapOnly = await s.importKey('raw', bytes, name, false, ['wrapKey']);+ wrapOnly.algorithm.name = 'HMAC';+ results.push((await s.wrapKey('raw', payload, wrapOnly, alg)).byteLength > 0);+ }+ return results;+ "#).await;+ assert_eq!(out, json!([+ "InvalidAccessError", "InvalidAccessError", "InvalidAccessError", true,+ "InvalidAccessError", "InvalidAccessError", "InvalidAccessError", true,+ "InvalidAccessError", "InvalidAccessError", "InvalidAccessError", true,+ "InvalidAccessError", "InvalidAccessError", "InvalidAccessError", true,+ ]));+}++#[tokio::test]+async fn key_unwrapping_checks_the_unwrapping_keys_algorithm_and_usage() {+ let out = probe(r#"+ const bytes = new Uint8Array(16);+ const payload = await s.importKey('raw', bytes, 'AES-GCM', true, ['encrypt']);+ const results = [];+ for (const name of ['AES-KW', 'AES-GCM', 'AES-CBC', 'AES-CTR']) {+ const alg = name === 'AES-GCM' ? {name, iv: new Uint8Array(12)}+ : name === 'AES-CBC' ? {name, iv: new Uint8Array(16)}+ : name === 'AES-CTR' ? {name, counter: new Uint8Array(16), length: 64} : name;+ const wrapOnly = await s.importKey('raw', bytes, name, false, ['wrapKey']);+ const wrapped = await s.wrapKey('raw', payload, wrapOnly, alg);+ const wrongAlgorithm = await s.importKey('raw', bytes, {name:'HMAC', hash:'SHA-256'}, false, ['sign']);+ const unwrap = key => s.unwrapKey('raw', wrapped, key, alg, 'AES-GCM', true, ['encrypt']);+ results.push(await errorName(() => unwrap(wrapOnly)));+ results.push(await errorName(() => unwrap(wrongAlgorithm)));+ wrongAlgorithm.algorithm.name = name;+ results.push(await errorName(() => unwrap(wrongAlgorithm)));+ const unwrapOnly = await s.importKey('raw', bytes, name, false, ['unwrapKey']);+ unwrapOnly.algorithm.name = 'HMAC';+ const restored = await unwrap(unwrapOnly);+ results.push(hex(await s.exportKey('raw', restored)));+ }+ return results;+ "#).await;+ assert_eq!(out, json!([+ "InvalidAccessError", "InvalidAccessError", "InvalidAccessError", "00000000000000000000000000000000",+ "InvalidAccessError", "InvalidAccessError", "InvalidAccessError", "00000000000000000000000000000000",+ "InvalidAccessError", "InvalidAccessError", "InvalidAccessError", "00000000000000000000000000000000",+ "InvalidAccessError", "InvalidAccessError", "InvalidAccessError", "00000000000000000000000000000000",+ ]));+}++#[tokio::test]+async fn unsupported_wrapping_algorithms_still_report_not_supported() {+ let out = probe(r#"+ const key = await s.importKey('raw', new Uint8Array(16), {name:'HMAC', hash:'SHA-256'}, true, ['sign']);+ return [+ await errorName(() => s.wrapKey('raw', key, key, 'HMAC')),+ await errorName(() => s.unwrapKey('raw', new Uint8Array(24), key, 'HMAC', 'AES-GCM', false, ['encrypt'])),+ ];+ "#).await;+ assert_eq!(out, json!(["NotSupportedError", "NotSupportedError"]));+}++#[tokio::test]+async fn cloned_wrapping_keys_keep_their_internal_algorithm() {+ let out = probe(r#"+ const key = await s.importKey('raw', new Uint8Array(16), 'AES-KW', false, ['wrapKey', 'unwrapKey']);+ key.algorithm.name = 'HMAC';+ const copy = structuredClone({first:key, second:key});+ const payload = await s.importKey('raw', new Uint8Array(16), 'AES-GCM', true, ['encrypt']);+ const wrapped = await s.wrapKey('raw', payload, copy.first, 'AES-KW');+ const restored = await s.unwrapKey('raw', wrapped, copy.first, 'AES-KW', 'AES-GCM', true, ['encrypt']);+ return [copy.first.algorithm.name, copy.first === copy.second, hex(await s.exportKey('raw', restored))];+ "#).await;+ assert_eq!(out, json!(["AES-KW", true, "00000000000000000000000000000000"]));+}