Skip to content

The headless browser for AI agents and web scraping

fix(js): wrap keys with AES-KW and serialize wrapped JWKs natively

orezraeyd57489cdf81c
diff --git a/Cargo.lock b/Cargo.lock
index bca5da4a..9a3c5002 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -59,6 +59,15 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "aes-kw"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69fa2b352dcefb5f7f3a5fb840e02665d311d878955380515e4fd50095dd3d8c"
+dependencies = [
+ "aes",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -2070,6 +2079,7 @@ version = "0.1.0"
dependencies = [
"aes",
"aes-gcm",
+ "aes-kw",
"anyhow",
"base64",
"cbc",
diff --git a/crates/obscura-js/Cargo.toml b/crates/obscura-js/Cargo.toml
index c9350fb2..936d1f74 100644
--- a/crates/obscura-js/Cargo.toml
+++ b/crates/obscura-js/Cargo.toml
@@ -44,6 +44,7 @@ sha2 = "0.10"
# and they unify on the digest 0.10 / cipher 0.4 stack already in the tree.
hmac = "0.12"
aes = "0.8"
+aes-kw = { version = "0.2", features = ["alloc"] }
aes-gcm = "0.10"
cbc = { version = "0.1", features = ["alloc"] }
ctr = "0.9"
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 9d45822f..69b20645 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -16936,6 +16936,15 @@ 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);
+ }
+ if (key.algorithm.name === "HMAC") return "HS" + key.algorithm.hash.name.slice(4);
+ return undefined;
+ }
+
function keyAlgorithmFor(alg, bytes) {
switch (alg.name) {
case "HMAC":
@@ -16983,12 +16992,14 @@ if (!globalThis.crypto.subtle) {
if (!key.extractable) throw new DOMException("Key is not extractable", "InvalidAccessError");
if (format === "raw") return bufferOf(bytes);
if (format === "jwk") {
- const jwk = { kty: "oct", k: bytesToB64url(bytes), ext: key.extractable, key_ops: key.usages.slice() };
- if (key.algorithm.name && key.algorithm.name.indexOf("AES-") === 0) {
- jwk.alg = "A" + (bytes.length * 8) + key.algorithm.name.slice(4);
- } else if (key.algorithm.name === "HMAC") {
- jwk.alg = "HS" + key.algorithm.hash.name.slice(4);
- }
+ // Members in lexicographic order, as browsers return a JsonWebKey and
+ // as wrapKey serializes it.
+ const alg = jwkAlg(key, bytes);
+ const jwk = alg ? { alg } : {};
+ jwk.ext = key.extractable;
+ jwk.k = bytesToB64url(bytes);
+ jwk.key_ops = key.usages.slice();
+ jwk.kty = "oct";
return jwk;
}
throw new DOMException("Only 'raw' and 'jwk' export is supported", "NotSupportedError");
@@ -17077,18 +17088,41 @@ if (!globalThis.crypto.subtle) {
},
async wrapKey(format, key, wrappingKey, wrapAlgorithm) {
+ const alg = normalizeAlgo(wrapAlgorithm);
const exported = await this.exportKey(format, key);
- const bytes = format === "jwk"
- ? new TextEncoder().encode(JSON.stringify(exported))
- : new Uint8Array(exported);
+ // 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.
+ let bytes;
+ if (format === "jwk") {
+ const material = keyBytes(key);
+ bytes = __obscuraCore.ops.op_subtle_jwk_json(
+ jwkAlg(key, material) || "", key.extractable, bytesToB64url(material), key.usages.map(String));
+ } else {
+ bytes = new Uint8Array(exported);
+ }
+ // 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 this.encrypt(wrapAlgorithm, wrappingKey, bytes);
},
async unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) {
- const decrypted = await this.decrypt(unwrapAlgorithm, unwrappingKey, wrappedKey);
- const keyData = format === "jwk"
- ? JSON.parse(new TextDecoder().decode(new Uint8Array(decrypted)))
- : decrypted;
+ const alg = normalizeAlgo(unwrapAlgorithm);
+ const decrypted = alg.name === "AES-KW"
+ ? runOp(() => __obscuraCore.ops.op_subtle_aes_kw(false, keyBytes(unwrappingKey), toBytes(wrappedKey)))
+ : new Uint8Array(await this.decrypt(unwrapAlgorithm, unwrappingKey, wrappedKey));
+ let keyData;
+ if (format === "jwk") {
+ // Parsed natively too, not with the page's JSON.parse.
+ try {
+ keyData = __obscuraCore.ops.op_subtle_jwk_parse(decrypted);
+ } catch (e) {
+ throw new DOMException("The unwrapped key is not a JSON Web Key", "DataError");
+ }
+ } else {
+ keyData = bufferOf(decrypted);
+ }
return this.importKey(format, keyData, unwrappedKeyAlgorithm, extractable, keyUsages);
},
};
diff --git a/crates/obscura-js/src/lib.rs b/crates/obscura-js/src/lib.rs
index 2a7e7324..ae47e5c1 100644
--- a/crates/obscura-js/src/lib.rs
+++ b/crates/obscura-js/src/lib.rs
@@ -11,6 +11,8 @@ mod write_stream;
#[cfg(test)]
mod indexed_db_tests;
+#[cfg(test)]
+mod webcrypto_tests;
pub use markdown::HTML_TO_MARKDOWN_JS;
pub use v8_flags::set_v8_flags;
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 0152ad82..63581ef2 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -5413,7 +5413,7 @@ mod tests {
// buffer straight from an untrusted u32 length. Each must reject a length
// above its fixed maximum before allocating, and still work for ordinary
// inputs. See #910.
- use super::{HKDF_MAX_OUTPUT_BYTES, RANDOM_BYTES_MAX, hkdf_derive, random_bytes};
+ use super::{HKDF_MAX_OUTPUT_BYTES, RANDOM_BYTES_MAX, aes_kw, hkdf_derive, oct_jwk_json, parse_jwk, random_bytes};
#[test]
fn hkdf_rejects_excessive_output_length() {
@@ -5438,6 +5438,57 @@ mod tests {
assert_eq!(okm.len(), 32, "derived key must have the requested length");
}
+ // RFC 3394, section 4.1: 128 bits of key data with a 128-bit KEK.
+ #[test]
+ fn aes_kw_matches_rfc_3394() {
+ let kek: Vec<u8> = (0u8..16).collect();
+ let data: Vec<u8> = (0u8..16).map(|i| i * 0x11).collect();
+ let wrapped = aes_kw(true, &kek, &data).expect("a 128-bit key wraps");
+ assert_eq!(
+ wrapped,
+ [
+ 0x1f, 0xa6, 0x8b, 0x0a, 0x81, 0x12, 0xb4, 0x47, 0xae, 0xf3, 0x4b, 0xd8, 0xfb, 0x5a,
+ 0x7b, 0x82, 0x9d, 0x3e, 0x86, 0x23, 0x71, 0xd2, 0xcf, 0xe5
+ ]
+ );
+ assert_eq!(aes_kw(false, &kek, &wrapped).expect("the wrap unwraps"), data);
+ }
+
+ #[test]
+ fn aes_kw_rejects_tampering_and_bad_sizes() {
+ let kek = [7u8; 32];
+ let mut wrapped = aes_kw(true, &kek, &[1u8; 24]).expect("a 192-bit key wraps");
+ wrapped[3] ^= 1;
+ assert!(aes_kw(false, &kek, &wrapped).is_err(), "a tampered wrap must not unwrap");
+ assert!(aes_kw(false, &[8u8; 32], &aes_kw(true, &kek, &[1u8; 16]).unwrap()).is_err(), "another key must not unwrap");
+ assert!(aes_kw(true, &kek, &[1u8; 20]).is_err(), "data not a multiple of 8 bytes must not wrap");
+ assert!(aes_kw(true, &kek, &[1u8; 8]).is_err(), "a single block must not wrap");
+ assert!(aes_kw(false, &kek, &[1u8; 16]).is_err(), "a single wrapped block must not unwrap");
+ assert!(aes_kw(false, &kek, &[]).is_err(), "nothing must not unwrap");
+ assert!(aes_kw(true, &[7u8; 20], &[1u8; 16]).is_err(), "a 160-bit KEK is not an AES key");
+ }
+
+ #[test]
+ fn oct_jwk_json_is_in_lexicographic_order() {
+ let ops = vec!["sign".to_string(), "verify".to_string()];
+ assert_eq!(
+ String::from_utf8(oct_jwk_json("HS256", true, "AQID", &ops)).unwrap(),
+ r#"{"alg":"HS256","ext":true,"k":"AQID","key_ops":["sign","verify"],"kty":"oct"}"#
+ );
+ assert_eq!(
+ String::from_utf8(oct_jwk_json("", false, "AQID", &[])).unwrap(),
+ r#"{"ext":false,"k":"AQID","key_ops":[],"kty":"oct"}"#
+ );
+ }
+
+ #[test]
+ fn parse_jwk_wants_a_json_object() {
+ assert!(parse_jwk(br#"{"kty":"oct","k":"AQID"}"#).unwrap().is_object());
+ assert!(parse_jwk(b"not json").is_err());
+ assert!(parse_jwk(b"[1, 2]").is_err());
+ assert!(parse_jwk(b"\"oct\"").is_err());
+ }
+
#[test]
fn random_bytes_rejects_excessive_length() {
let err =
@@ -7008,6 +7059,97 @@ fn op_subtle_aes_ctr(
Ok(buf)
}
+/// AES-KW (RFC 3394) key wrap and unwrap, for `wrapKey` / `unwrapKey`. RFC 3394
+/// wraps at least two 64-bit blocks, so the data to wrap must be a multiple of
+/// 8 bytes and at least 16 (a wrap, at least 24); unwrapping checks the
+/// integrity value, so a wrong key or a tampered wrap is an error too (the
+/// shim's OperationError). Split out from the op so it is unit-testable.
+fn aes_kw(wrap: bool, key: &[u8], data: &[u8]) -> Result<Vec<u8>, deno_error::JsErrorBox> {
+ use aes_kw::{KekAes128, KekAes192, KekAes256};
+ // aes-kw itself accepts a single block.
+ if data.len() < if wrap { 16 } else { 24 } {
+ return Err(crypto_err("AES-KW wraps at least two 64-bit blocks"));
+ }
+ macro_rules! run {
+ ($kek:ty) => {{
+ let kek = <$kek>::try_from(key).map_err(crypto_err)?;
+ if wrap { kek.wrap_vec(data) } else { kek.unwrap_vec(data) }.map_err(crypto_err)?
+ }};
+ }
+ Ok(match key.len() {
+ 16 => run!(KekAes128),
+ 24 => run!(KekAes192),
+ 32 => run!(KekAes256),
+ _ => return Err(crypto_err("AES-KW keys are 128, 192 or 256 bits")),
+ })
+}
+
+#[op2]
+#[buffer]
+fn op_subtle_aes_kw(
+ wrap: bool,
+ #[buffer] key: &[u8],
+ #[buffer] data: &[u8],
+) -> Result<Vec<u8>, deno_error::JsErrorBox> {
+ aes_kw(wrap, key, data)
+}
+
+/// A symmetric ("oct") JWK as `wrapKey` serializes it. Members are declared in
+/// lexicographic order, the order `JSON.stringify` gives a JsonWebKey
+/// dictionary.
+#[derive(serde::Serialize)]
+struct OctJwk<'a> {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ alg: Option<&'a str>,
+ ext: bool,
+ k: &'a str,
+ key_ops: &'a [String],
+ kty: &'static str,
+}
+
+/// The UTF-8 JSON text of an "oct" JWK, for `wrapKey`. Built here rather than
+/// with the page's `JSON.stringify`, so a `toJSON` or another override on the
+/// page's prototypes can't change the wrapped bytes: the spec serializes it in
+/// the context of a new global object. An empty `alg` is left out.
+fn oct_jwk_json(alg: &str, ext: bool, k: &str, key_ops: &[String]) -> Vec<u8> {
+ let jwk = OctJwk {
+ alg: (!alg.is_empty()).then_some(alg),
+ ext,
+ k,
+ key_ops,
+ kty: "oct",
+ };
+ serde_json::to_vec(&jwk).unwrap_or_default()
+}
+
+#[op2]
+#[buffer]
+fn op_subtle_jwk_json(
+ #[string] alg: &str,
+ ext: bool,
+ #[string] k: &str,
+ #[serde] key_ops: Vec<String>,
+) -> Vec<u8> {
+ oct_jwk_json(alg, ext, k, &key_ops)
+}
+
+/// Parses the JSON text `unwrapKey` decrypted for a "jwk" import, for the same
+/// reason as `oct_jwk_json`: not with the page's `JSON.parse`. Text that isn't
+/// JSON, or isn't an object, is an error (the shim's DataError).
+fn parse_jwk(bytes: &[u8]) -> Result<serde_json::Value, deno_error::JsErrorBox> {
+ let value: serde_json::Value = serde_json::from_slice(bytes).map_err(crypto_err)?;
+ if !value.is_object() {
+ return Err(crypto_err("the unwrapped key is not a JSON object"));
+ }
+ Ok(value)
+}
+
+#[op2]
+#[serde]
+fn op_subtle_jwk_parse(#[buffer] bytes: &[u8]) -> Result<serde_json::Value, deno_error::JsErrorBox> {
+ parse_jwk(bytes)
+}
+
/// Generous upper bounds on PBKDF2 parameters. WebCrypto imposes no limit, but
/// page JS drives this op on the single-threaded runtime: an unbounded
/// iteration count pins the V8 isolate (blocking every other CDP command on the
@@ -7625,6 +7767,9 @@ pub fn build_extension() -> Extension {
op_subtle_aes_gcm(),
op_subtle_aes_cbc(),
op_subtle_aes_ctr(),
+ op_subtle_aes_kw(),
+ op_subtle_jwk_json(),
+ op_subtle_jwk_parse(),
op_subtle_pbkdf2(),
op_subtle_hkdf(),
op_random_bytes(),
diff --git a/crates/obscura-js/src/webcrypto_tests.rs b/crates/obscura-js/src/webcrypto_tests.rs
new file mode 100644
index 00000000..1e3223f9
--- /dev/null
+++ b/crates/obscura-js/src/webcrypto_tests.rs
@@ -0,0 +1,100 @@
+use crate::runtime::ObscuraJsRuntime;
+use serde_json::{json, Value};
+
+async fn probe(script: &str) -> Value {
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_dom(obscura_dom::parse_html("<!doctype html><body></body>"));
+ rt.set_url("https://webcrypto.test/");
+ rt.run_page_init();
+ rt.execute_script("webcrypto-regression", &format!(r#"
+ globalThis.cryptoResult = null;
+ const s = crypto.subtle;
+ const hex = buf => Array.from(new Uint8Array(buf), b => b.toString(16).padStart(2, '0')).join('');
+ const fromHex = h => new Uint8Array(h.match(/../g).map(b => parseInt(b, 16)));
+ const errorName = async fn => {{ try {{ await fn(); return null; }} catch (e) {{ return e.name; }} }};
+ (async () => {{ {script} }})().then(
+ value => cryptoResult = value,
+ error => cryptoResult = {{error:error.name, message:error.message}}
+ );
+ "#)).unwrap();
+ rt.run_event_loop_bounded(1000).await.unwrap();
+ rt.evaluate("cryptoResult").unwrap()
+}
+
+#[tokio::test]
+async fn aes_kw_wraps_and_unwraps_raw_keys() {
+ // RFC 3394, section 4.1, through wrapKey / unwrapKey.
+ let out = probe(r#"
+ const kek = await s.importKey('raw', fromHex('000102030405060708090a0b0c0d0e0f'), 'AES-KW', false, ['wrapKey', 'unwrapKey']);
+ const key = await s.importKey('raw', fromHex('00112233445566778899aabbccddeeff'), 'AES-CBC', true, ['encrypt']);
+ const wrapped = await s.wrapKey('raw', key, kek, 'AES-KW');
+ const back = await s.unwrapKey('raw', wrapped, kek, {name: 'AES-KW'}, 'AES-GCM', true, ['encrypt']);
+ const tampered = new Uint8Array(wrapped.slice(0)); tampered[0] ^= 1;
+ const generated = await s.generateKey({name: 'AES-KW', length: 256}, false, ['wrapKey', 'unwrapKey']);
+ const roundTrip = await s.unwrapKey('raw', await s.wrapKey('raw', key, generated, 'AES-KW'), generated, 'AES-KW', 'AES-CBC', true, ['decrypt']);
+ // RFC 3394 wraps at least two blocks, of 8 bytes each.
+ const hmac8 = await s.importKey('raw', new Uint8Array(8).fill(1), {name: 'HMAC', hash: 'SHA-256'}, true, ['sign']);
+ const hmac3 = await s.importKey('raw', new Uint8Array([1, 2, 3]), {name: 'HMAC', hash: 'SHA-256'}, true, ['sign', 'verify']);
+ const hmac16 = await s.importKey('raw', new Uint8Array(16).fill(2), {name: 'HMAC', hash: 'SHA-256'}, true, ['sign']);
+ const hmac16Back = await s.unwrapKey('raw', await s.wrapKey('raw', hmac16, kek, 'AES-KW'), kek, 'AES-KW', {name: 'HMAC', hash: 'SHA-256'}, true, ['sign']);
+ return [
+ hex(wrapped),
+ back.algorithm.name, hex(await s.exportKey('raw', back)),
+ hex(await s.exportKey('raw', roundTrip)),
+ await errorName(() => s.unwrapKey('raw', tampered, kek, 'AES-KW', 'AES-GCM', true, ['encrypt'])),
+ await errorName(() => s.encrypt('AES-KW', kek, new Uint8Array(16))),
+ await errorName(() => s.wrapKey('raw', hmac8, kek, 'AES-KW')),
+ // This JWK's JSON text is 77 bytes, not a multiple of 8.
+ await errorName(() => s.wrapKey('jwk', hmac3, kek, 'AES-KW')),
+ await errorName(() => s.unwrapKey('raw', new Uint8Array(16), kek, 'AES-KW', 'AES-GCM', true, ['encrypt'])),
+ hmac16Back.algorithm.length,
+ ];
+ "#).await;
+ assert_eq!(out, json!([
+ "1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5",
+ "AES-GCM", "00112233445566778899aabbccddeeff",
+ "00112233445566778899aabbccddeeff",
+ "OperationError",
+ "NotSupportedError",
+ "OperationError",
+ "OperationError",
+ "OperationError",
+ 128,
+ ]));
+}
+
+#[tokio::test]
+async fn wrapped_jwks_ignore_the_pages_json() {
+ let out = probe(r#"
+ const gcm = {name: 'AES-GCM', iv: new Uint8Array(12)};
+ const wrapper = await s.generateKey({name: 'AES-GCM', length: 128}, true, ['wrapKey', 'unwrapKey', 'decrypt', 'encrypt']);
+ const hmac = await s.importKey('raw', new Uint8Array([1, 2, 3]), {name: 'HMAC', hash: 'SHA-256'}, true, ['sign', 'verify']);
+ Object.prototype.toJSON = () => ({injected: true});
+ Array.prototype.toJSON = () => 'injected';
+ const realParse = JSON.parse;
+ JSON.parse = () => ({kty: 'oct', k: 'AAAA'});
+ let text, unwrapped, sig;
+ try {
+ const wrapped = await s.wrapKey('jwk', hmac, wrapper, gcm);
+ text = new TextDecoder().decode(await s.decrypt(gcm, wrapper, wrapped));
+ unwrapped = await s.unwrapKey('jwk', wrapped, wrapper, gcm, {name: 'HMAC', hash: 'SHA-256'}, true, ['sign']);
+ } finally {
+ delete Object.prototype.toJSON;
+ delete Array.prototype.toJSON;
+ JSON.parse = realParse;
+ }
+ const notJson = await s.encrypt(gcm, wrapper, new TextEncoder().encode('not json'));
+ return [
+ text,
+ JSON.stringify(await s.exportKey('jwk', hmac)) === text,
+ hex(await s.exportKey('raw', unwrapped)),
+ await errorName(() => s.unwrapKey('jwk', notJson, wrapper, gcm, {name: 'HMAC', hash: 'SHA-256'}, true, ['sign'])),
+ ];
+ "#).await;
+ assert_eq!(out, json!([
+ r#"{"alg":"HS256","ext":true,"k":"AQID","key_ops":["sign","verify"],"kty":"oct"}"#,
+ true,
+ "010203",
+ "DataError",
+ ]));
+}