Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: check AES and HMAC JWKs on import (kty, alg, use, key_ops, ext)

orezraey82da9422c4a0
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 819e14a23..7623c6142 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -556,6 +556,84 @@
});
</script>
+<script id=jwk-symmetric type=module>
+ const state = await testing.async();
+ const subtle = crypto.subtle;
+ const errorName = async (fn) => {
+ try {
+ await fn();
+ return null;
+ } catch (err) {
+ return err.name;
+ }
+ };
+ const k16 = "AAAAAAAAAAAAAAAAAAAAAA"; // 16 bytes
+ const k24 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; // 24 bytes
+ const k32 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; // 32 bytes
+ const aes = { kty: "oct", k: k16, alg: "A128GCM" };
+ const hmac = { kty: "oct", k: k16, alg: "HS256" };
+ const importAes =(jwk, usages = ["encrypt"], extractable = true, name = "AES-GCM") =>
+ errorName(() => subtle.importKey("jwk", jwk, name, extractable, usages));
+ const importHmac = (jwk, usages = ["sign"], hash = "SHA-256") =>
+ errorName(() => subtle.importKey("jwk", jwk, { name: "HMAC", hash }, true, usages));
+
+ // A non-extractable JWK, wrapped as JSON, must not come back extractable.
+ const wrapper = await subtle.generateKey({ name: "AES-GCM", length: 128 }, true, ["encrypt", "unwrapKey"]);
+ const gcm = { name: "AES-GCM", iv: new Uint8Array(12) };
+ const lockedJson = new TextEncoder().encode(JSON.stringify({ ...aes, ext: false }));
+ const wrappedLocked = await subtle.encrypt(gcm, wrapper, lockedJson);
+
+ const results = {
+ // Accepted: matching alg, use and key_ops, ext:false imported as non-extractable.
+ aes: await importAes(aes),
+ aesWithoutAlg: await importAes({ kty: "oct", k: k16 }),
+ kw: await importAes({ kty: "oct", k: k16, alg: "A128KW" }, ["wrapKey"], true, "AES-KW"),
+ cbc192: await importAes({ kty: "oct", k: k24, alg: "A192CBC" }, ["encrypt"], true, "AES-CBC"),
+ ctr256: await importAes({ kty: "oct", k: k32, alg: "A256CTR" }, ["encrypt"], true, "AES-CTR"),
+ hmac: await importHmac(hmac),
+ hmacSha1: await importHmac({ kty: "oct", k: k16, alg: "HS1" }, ["sign"], "SHA-1"),
+ useMatches: await importAes({ ...aes, use: "enc" }),
+ extFalseLocked: await importAes({ ...aes, ext: false }, ["encrypt"], false),
+ keyOpsWider: await importAes({ ...aes, key_ops: ["encrypt", "decrypt"] }),
+ // kty, k and alg (case-sensitive, and naming this algorithm at this length / hash).
+ ktyMissing: await importAes({ k: k16 }),
+ ktyRsa: await importAes({ ...aes, kty: "RSA" }),
+ kMissing: await importAes({ kty: "oct", alg: "A128GCM" }),
+ algLength: await importAes({ ...aes, alg: "A256GCM" }),
+ algMode: await importAes({ ...aes, alg: "A128CBC" }),
+ algLowercase: await importAes({ ...aes, alg: "a128gcm" }),
+ hmacAlgHash: await importHmac({ ...hmac, alg: "HS512" }),
+ // use, key_ops and ext.
+ aesUseSig: await importAes({ ...aes, use: "sig" }),
+ hmacUseEnc: await importHmac({ ...hmac, use: "enc" }),
+ keyOpsMissing: await importAes({ ...aes, key_ops: ["decrypt"] }),
+ keyOpsDuplicate: await importAes({ ...aes, key_ops: ["encrypt", "encrypt"] }),
+ aesExtFalse: await importAes({ ...aes, ext: false }),
+ hmacExtFalse: await importHmac({ ...hmac, ext: false }),
+ unwrapExtFalse: await errorName(() => subtle.unwrapKey("jwk", wrappedLocked, wrapper, gcm, "AES-GCM", true, ["encrypt"])),
+ // The usages are checked before the JWK.
+ badUsageBadKty: await importAes({ ...aes, kty: "RSA" }, ["sign"]),
+ // HKDF and PBKDF2 keys only come in raw.
+ hkdf: await errorName(() => subtle.importKey("jwk", { kty: "oct", k: k16 }, "HKDF", false, ["deriveBits"])),
+ pbkdf2: await errorName(() => subtle.importKey("jwk", { kty: "oct", k: k16 }, "PBKDF2", false, ["deriveBits"])),
+ };
+
+ state.resolve();
+ await state.done(() => {
+ // Compared with the case name, so a failure says which one.
+ for (const ok of ["aes", "aesWithoutAlg", "kw", "cbc192", "ctr256", "hmac", "hmacSha1", "useMatches", "extFalseLocked", "keyOpsWider"]) {
+ testing.expectEqual(`${ok}: null`, `${ok}: ${results[ok]}`);
+ }
+ for (const bad of ["ktyMissing", "ktyRsa", "kMissing", "algLength", "algMode", "algLowercase", "hmacAlgHash",
+ "aesUseSig", "hmacUseEnc", "keyOpsMissing", "keyOpsDuplicate", "aesExtFalse", "hmacExtFalse", "unwrapExtFalse"]) {
+ testing.expectEqual(`${bad}: DataError`, `${bad}: ${results[bad]}`);
+ }
+ testing.expectEqual("SyntaxError", results.badUsageBadKty);
+ testing.expectEqual("NotSupportedError", results.hkdf);
+ testing.expectEqual("NotSupportedError", results.pbkdf2);
+ });
+</script>
+
<script id=aes-ctr-counter-wrap type=module>
const state = await testing.async();
// AES-CTR must increment only the rightmost `length` bits of the counter
diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zig
index 46014f3cf..73aac52e2 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -141,15 +141,7 @@ pub fn importKey(
return EC.import(name, algo.namedCurve(), format, der, is_private, extractable, mask, exec);
}
if (RSA.canonicalName(name) != null) {
- // RSA-OAEP import params {name, hash} match the `.hmac` variant of the
- // Import union (same shape: a name plus a hash), so the hash is read there.
- const hash_name = switch (algo) {
- .hmac => |h| switch (h.hash) {
- .string => |s| s,
- .object => |o| o.name,
- },
- else => return local.typeError("RSA-OAEP import requires a hash"),
- };
+ const hash_name = importHash(algo) orelse return local.typeError("RSA-OAEP import requires a hash");
const is_jwk = std.mem.eql(u8, format, "jwk");
switch (key_data) {
.bytes => |b| {
@@ -166,8 +158,25 @@ pub fn importKey(
return error.NotSupported;
}
- // Resolve the raw key bytes from the requested format. Symmetric keys
- // support "raw" (a BufferSource) and "jwk" (an "oct" JSON Web Key).
+ // Symmetric keys come in "raw" (a BufferSource) or, for AES and HMAC, "jwk"
+ // (an "oct" JSON Web Key, which each checks against the key it imports).
+ if (std.mem.eql(u8, format, "jwk")) {
+ const jwk = switch (key_data) {
+ .jwk => |j| j,
+ .bytes => return local.typeError("jwk format expects an object"),
+ };
+ if (AES.canonicalName(name) != null) {
+ return AES.importJwk(name, jwk, extractable, key_usages, exec);
+ }
+ if (eqlIgnoreCase(name, "HMAC")) {
+ const hash_name = importHash(algo) orelse return local.typeError("HMAC import requires a hash");
+ return HMAC.importJwk(hash_name, jwk, extractable, key_usages, exec);
+ }
+ // HKDF and PBKDF2 keys only come in "raw".
+ log.debug(.not_implemented, "SubtleCrypto.importKey", .{ .name = name, .format = format });
+ return error.NotSupported;
+ }
+
const raw: []const u8 = blk: {
if (std.mem.eql(u8, format, "raw")) {
break :blk switch (key_data) {
@@ -176,21 +185,6 @@ pub fn importKey(
.jwk => return local.typeError("raw format expects a BufferSource"),
};
}
- if (std.mem.eql(u8, format, "jwk")) {
- const jwk = switch (key_data) {
- .jwk => |j| j,
- .bytes => return local.typeError("jwk format expects an object"),
- };
- if (!std.mem.eql(u8, jwk.kty orelse "", "oct")) {
- return error.DataError;
- }
- // A JWK marked non-extractable can't be imported as extractable.
- if (extractable and jwk.ext == false) {
- return error.DataError;
- }
- const k = jwk.k orelse return error.DataError;
- break :blk try common.base64Decode(exec.local_arena, k);
- }
// spki / pkcs8 (asymmetric formats) are not supported for these algorithms.
return error.NotSupported;
};
@@ -216,13 +210,7 @@ pub fn importKey(
}
}
if (eqlIgnoreCase(name, "HMAC")) {
- const hash_name = switch (algo) {
- .hmac => |h| switch (h.hash) {
- .string => |s| s,
- .object => |o| o.name,
- },
- else => return local.typeError("HMAC import requires a hash"),
- };
+ const hash_name = importHash(algo) orelse return local.typeError("HMAC import requires a hash");
return HMAC.import(hash_name, raw, extractable, key_usages, exec);
}
@@ -230,6 +218,19 @@ pub fn importKey(
return error.NotSupported;
}
+/// The hash of an importKey algorithm that carries one (HMAC, RSA-OAEP): those
+/// params {name, hash} match the `.hmac` variant of the Import union (same
+/// shape), so the hash is read there. Null for the other variants.
+fn importHash(algo: algorithm.Import) ?[]const u8 {
+ return switch (algo) {
+ .hmac => |h| switch (h.hash) {
+ .string => |s| s,
+ .object => |o| o.name,
+ },
+ else => null,
+ };
+}
+
/// Whether the requested format/key-data describe a private key. The format
/// alone decides for DER/raw variants; for JWK the presence of `d` marks it.
fn importKind(format: []const u8, key_data: algorithm.KeyData) bool {
@@ -370,14 +371,8 @@ const JwkSecret = struct {
fn exportJwk(key: *CryptoKey, exec: *const Execution) !Jwk {
// The `alg` registry value depends on the algorithm and key length.
const alg: []const u8 = switch (key._type) {
- .aes => try exec.local_arena.print("A{d}{s}", .{
- key._key.len * 8,
- key._algorithm.name[4..], // strip "AES-"
- }),
- .hmac => blk: {
- const hash: []const u8 = key._algorithm.hash orelse "SHA-";
- break :blk try exec.local_arena.print("HS{s}", .{hash[4..]}); // strip "SHA-"
- },
+ .aes => try AES.jwkAlg(key._algorithm.name, key._key.len, exec),
+ .hmac => try HMAC.jwkAlg(key._algorithm.hash orelse "SHA-", exec),
.rsa => return .{ .rsa = try RSA.exportJwk(key, exec) },
else => {
log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = "jwk", .type = key._type });
diff --git a/src/browser/webapi/crypto/AES.zig b/src/browser/webapi/crypto/AES.zig
index daa1a8cd4..cbee981f5 100644
--- a/src/browser/webapi/crypto/AES.zig
+++ b/src/browser/webapi/crypto/AES.zig
@@ -107,8 +107,8 @@ pub fn generate(
return local.resolvePromise(crypto_key);
}
-/// Imports raw AES key material (from the `raw` or `jwk` formats; the caller has
-/// already turned both into the underlying bytes).
+/// Imports raw AES key material (from the `raw` format, or the `k` of a JWK
+/// that `importJwk` checked).
pub fn import(
name: []const u8,
raw: []const u8,
@@ -140,6 +140,36 @@ pub fn import(
return local.resolvePromise(crypto_key);
}
+/// Imports an AES key from a JWK, following the "jwk" steps of AES's "import
+/// key": the usages first (SyntaxError), then kty "oct", the key in `k`, an
+/// `alg` that names this algorithm at the key's length, and the common
+/// use/key_ops/ext checks (DataError).
+pub fn importJwk(
+ name: []const u8,
+ jwk: algorithm.KeyData.Jwk,
+ extractable: bool,
+ key_usages: []const []const u8,
+ exec: *const Execution,
+) !js.Promise {
+ const canonical = canonicalName(name) orelse return error.NotSupported;
+ const mask = try common.usageMask(allowedUsages(canonical).?, key_usages);
+
+ const raw = try common.octKey(jwk, exec.local_arena);
+ if (jwk.alg) |alg| {
+ if (!std.mem.eql(u8, alg, try jwkAlg(canonical, raw.len, exec))) return error.DataError;
+ }
+ try common.checkJwk(jwk, "enc", mask, extractable);
+
+ // import() rejects a key that isn't 128, 192 or 256 bits (DataError).
+ return import(canonical, raw, extractable, key_usages, exec);
+}
+
+/// The JWK `alg` of an AES key: "A", its length in bits and the mode
+/// ("A128GCM", "A256KW", ...). `name` is the canonical algorithm name.
+pub fn jwkAlg(name: []const u8, key_len: usize, exec: *const Execution) ![]const u8 {
+ return exec.local_arena.print("A{d}{s}", .{ key_len * 8, name[4..] }); // strip "AES-"
+}
+
const CipherError = error{ InvalidAccessError, OperationError, NotSupported, OutOfMemory };
const Mode = enum { cbc, ctr, gcm };
diff --git a/src/browser/webapi/crypto/HMAC.zig b/src/browser/webapi/crypto/HMAC.zig
index 882a977ad..dd0a25dbc 100644
--- a/src/browser/webapi/crypto/HMAC.zig
+++ b/src/browser/webapi/crypto/HMAC.zig
@@ -98,8 +98,37 @@ pub fn init(
return local.resolvePromise(crypto_key);
}
-/// Imports raw HMAC key material (from the `raw` or `jwk` formats; the caller
-/// has already turned both into the underlying bytes).
+/// Imports an HMAC key from a JWK, following the "jwk" steps of HMAC's "import
+/// key": the usages first (SyntaxError), then kty "oct", the key in `k`, an
+/// `alg` that names the hash ("HS256", ...), and the common use/key_ops/ext
+/// checks (DataError).
+pub fn importJwk(
+ hash_name: []const u8,
+ jwk: algorithm.KeyData.Jwk,
+ extractable: bool,
+ key_usages: []const []const u8,
+ exec: *const Execution,
+) !js.Promise {
+ _ = crypto.findDigest(hash_name) catch return error.NotSupported;
+ const mask = try common.usageMask(&.{ "sign", "verify" }, key_usages);
+
+ const raw = try common.octKey(jwk, exec.local_arena);
+ if (jwk.alg) |alg| {
+ if (!std.mem.eql(u8, alg, try jwkAlg(hash_name, exec))) return error.DataError;
+ }
+ try common.checkJwk(jwk, "sig", mask, extractable);
+
+ // import() rejects an empty key (DataError).
+ return import(hash_name, raw, extractable, key_usages, exec);
+}
+
+/// The JWK `alg` of an HMAC key with the given hash ("SHA-256" → "HS256").
+pub fn jwkAlg(hash_name: []const u8, exec: *const Execution) ![]const u8 {
+ return exec.local_arena.print("HS{s}", .{hash_name[4..]}); // strip "SHA-"
+}
+
+/// Imports raw HMAC key material (from the `raw` format, or the `k` of a JWK
+/// that `importJwk` checked).
pub fn import(
hash_name: []const u8,
raw: []const u8,
diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zig
index 83e3e64ff..bdecd51ae 100644
--- a/src/browser/webapi/crypto/RSA.zig
+++ b/src/browser/webapi/crypto/RSA.zig
@@ -264,13 +264,7 @@ pub fn importJwk(
const hash = canonicalHash(hash_name) orelse return error.NotSupported;
if (!std.mem.eql(u8, jwk.kty orelse "", "RSA")) return error.DataError;
- if (jwk.use) |use| {
- if (usages_mask != 0 and !std.mem.eql(u8, use, "enc")) return error.DataError;
- }
- if (jwk.key_ops) |key_ops| try checkKeyOps(key_ops, usages_mask);
- if (jwk.ext) |ext| {
- if (!ext and extractable) return error.DataError;
- }
+ try common.checkJwk(jwk, "enc", usages_mask, extractable);
// `alg` is optional; when present, it must name the requested hash.
if (jwk.alg) |alg| {
const alg_hash = hashOfJwkAlg(alg) orelse return error.DataError;
@@ -286,19 +280,6 @@ pub fn importJwk(
return local.resolvePromise(try newKey(pkey, hash, jwk.d != null, extractable, usages_mask, exec));
}
-/// A JWK `key_ops` must hold every requested usage, and no value twice
-/// (RFC 7517, section 4.3). Values that aren't usages are allowed.
-fn checkKeyOps(key_ops: []const []const u8, usages_mask: u8) !void {
- var listed: u8 = 0;
- for (key_ops, 0..) |op, i| {
- for (key_ops[0..i]) |earlier| {
- if (std.mem.eql(u8, earlier, op)) return error.DataError;
- }
- if (common.usageBit(op)) |bit| listed |= bit;
- }
- if (usages_mask & ~listed != 0) return error.DataError;
-}
-
/// The RSA key described by a JWK (JWA, section 6.3). A private key needs all
/// of the CRT members; libcrypto rejects members that don't make a valid key,
/// such as the extra primes of `oth`, which this two-prime import ignores.
diff --git a/src/browser/webapi/crypto/common.zig b/src/browser/webapi/crypto/common.zig
index d25758c4b..ad86a7012 100644
--- a/src/browser/webapi/crypto/common.zig
+++ b/src/browser/webapi/crypto/common.zig
@@ -16,13 +16,15 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-//! Shared helpers for the symmetric SubtleCrypto algorithms (AES, HMAC):
-//! usage-mask validation and the base64url codec used by the JWK format.
+//! Shared helpers for the SubtleCrypto algorithms: usage-mask validation, the
+//! base64url codec used by the JWK format, and the JWK checks every
+//! algorithm's import makes.
const std = @import("std");
const Allocator = std.mem.Allocator;
const CryptoKey = @import("../CryptoKey.zig");
+const algorithm = @import("algorithm.zig");
/// Maps a usage string to its `CryptoKey.Usages` bit, or null if unknown.
pub fn usageBit(name: []const u8) ?u8 {
@@ -67,6 +69,43 @@ pub fn usageMaskInner(allowed: []const []const u8, usages: []const []const u8, r
return mask;
}
+/// The key bytes of a symmetric ("oct") JWK: its `kty` must be "oct" and its
+/// `k` present and decodable (JWA, section 6.4). Anything else is DataError.
+pub fn octKey(jwk: algorithm.KeyData.Jwk, allocator: Allocator) error{ OutOfMemory, DataError }![]u8 {
+ if (!std.mem.eql(u8, jwk.kty orelse "", "oct")) return error.DataError;
+ return base64Decode(allocator, jwk.k orelse return error.DataError);
+}
+
+/// The JWK checks shared by every algorithm's "import key": `use` must be
+/// `expected_use` ("enc" or "sig") when usages are requested, `key_ops` must
+/// hold every requested usage and no value twice (RFC 7517, section 4.3;
+/// values that aren't usages are allowed), and a JWK with `ext: false` can't be
+/// imported as extractable. `kty`, the key members and `alg` are each
+/// algorithm's own.
+pub fn checkJwk(
+ jwk: algorithm.KeyData.Jwk,
+ expected_use: []const u8,
+ usages_mask: u8,
+ extractable: bool,
+) error{DataError}!void {
+ if (jwk.use) |use| {
+ if (usages_mask != 0 and !std.mem.eql(u8, use, expected_use)) return error.DataError;
+ }
+ if (jwk.key_ops) |key_ops| {
+ var listed: u8 = 0;
+ for (key_ops, 0..) |op, i| {
+ for (key_ops[0..i]) |earlier| {
+ if (std.mem.eql(u8, earlier, op)) return error.DataError;
+ }
+ if (usageBit(op)) |bit| listed |= bit;
+ }
+ if (usages_mask & ~listed != 0) return error.DataError;
+ }
+ if (jwk.ext) |ext| {
+ if (!ext and extractable) return error.DataError;
+ }
+}
+
/// Decodes a base64url (or base64) string, tolerating either alphabet and
/// optional padding. Returns DataError on malformed input, per the JWK import
/// rules.