Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: HMAC length and hash names

orezraey872f4fb103d6
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 41970f776..df6f83444 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -1346,6 +1346,132 @@
});
</script>
+<script id=hmac-length-and-hash 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 hex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
+ const raw = new Uint8Array(32).map((_, i) => i + 1);
+ const gen = (params) => subtle.generateKey({ name: "HMAC", hash: "SHA-256", ...params }, true, ["sign"]);
+ const imp = (params) => subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256", ...params }, true, ["sign"]);
+
+ // The hash matches case-insensitively and is reported in canonical form.
+ const lowerHash = await gen({ hash: "sha-256" });
+ const objectHash = await gen({ hash: { name: "sHa-384" } });
+ const lowerImport = await imp({ hash: "sha-512" });
+ const lowerJwk = await subtle.exportKey("jwk", lowerImport);
+
+ // A generated length needn't be whole bytes: the bits past it are zero.
+ let lowBits = 0;
+ const sizes = new Set();
+ for (let i = 0; i < 32; i++) {
+ const seven = new Uint8Array(await subtle.exportKey("raw", await gen({ length: 7 })));
+ const odd = new Uint8Array(await subtle.exportKey("raw", await gen({ length: 257 })));
+ sizes.add(`${seven.length},${odd.length}`);
+ lowBits |= (seven[0] & 0x01) | (odd[32] & 0x7f);
+ }
+ const k7 = await gen({ length: 7 });
+ const k257 = await gen({ length: 257 });
+ // A JWK has no length: re-imported, the key is whole bytes again.
+ const k257Jwk = await subtle.exportKey("jwk", k257);
+ const reimported = await subtle.importKey("jwk", k257Jwk, { name: "HMAC", hash: "SHA-256" }, true, ["sign"]);
+
+ // Importing, a length must end in the key's last byte; the key isn't cut.
+ const whole = await imp({});
+ const k255 = await imp({ length: 255 });
+ const sameMac = hex(await subtle.sign("HMAC", whole, raw)) === hex(await subtle.sign("HMAC", k255, raw));
+ const k255Raw = await subtle.exportKey("raw", k255);
+ const b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
+ const jwk = { kty: "oct", k: b64url(raw), alg: "HS256" };
+ const jwk250 = await subtle.importKey("jwk", jwk, { name: "HMAC", hash: "SHA-256", length: 250 }, true, ["sign"]);
+
+ // deriveKey takes the same length, and a lowercase hash.
+ const pbkdf2 = await subtle.importKey("raw", raw, "PBKDF2", false, ["deriveKey"]);
+ const derived = await subtle.deriveKey(
+ { name: "PBKDF2", hash: "SHA-256", salt: new Uint8Array(8), iterations: 2 },
+ pbkdf2,
+ { name: "HMAC", hash: "sha-256", length: 128 },
+ true,
+ ["sign"],
+ );
+
+ const results = {
+ // [EnforceRange] unsigned long: out of range is a TypeError, before the usages.
+ genHuge: await errorName(() => gen({ length: 2 ** 32 + 128 })),
+ genHugeNoUsages: await errorName(() => subtle.generateKey({ name: "HMAC", hash: "SHA-256", length: 2 ** 32 + 128 }, true, [])),
+ genNegative: await errorName(() => gen({ length: -1 })),
+ genNaN: await errorName(() => gen({ length: NaN })),
+ genZero: await errorName(() => gen({ length: 0 })),
+ importHuge: await errorName(() => imp({ length: 2 ** 32 + 8 })),
+ deriveHuge: await errorName(() => subtle.deriveKey(
+ { name: "PBKDF2", hash: "SHA-256", salt: new Uint8Array(8), iterations: 2 }, pbkdf2,
+ { name: "HMAC", hash: "SHA-256", length: -8 }, true, ["sign"])),
+ import256: await errorName(() => imp({ length: 256 })),
+ import249: await errorName(() => imp({ length: 249 })),
+ import248: await errorName(() => imp({ length: 248 })),
+ import257: await errorName(() => imp({ length: 257 })),
+ import0: await errorName(() => imp({ length: 0 })),
+ jwk200: await errorName(() => subtle.importKey("jwk", jwk, { name: "HMAC", hash: "SHA-256", length: 200 }, true, ["sign"])),
+ // RSA imports share HMAC's dictionary shape, and ignore a stray length.
+ rsaWithLength: await errorName(() => subtle.importKey("spki", rsaTestKey.spki, { name: "RSA-OAEP", hash: "SHA-256", length: -1 }, true, ["encrypt"])),
+ // null converts to 0, as for any unsigned long.
+ genNull: await errorName(() => gen({ length: null })),
+ importNull: await errorName(() => imp({ length: null })),
+ // deriveKey goes by the name: not an HMAC key for another algorithm with a hash.
+ deriveUnknown: await errorName(() => subtle.deriveKey(
+ { name: "PBKDF2", hash: "SHA-256", salt: new Uint8Array(8), iterations: 2 }, pbkdf2,
+ { name: "Foo", hash: "SHA-256" }, true, ["sign"])),
+ };
+ const aesWithHash = await subtle.deriveKey(
+ { name: "PBKDF2", hash: "SHA-256", salt: new Uint8Array(8), iterations: 2 }, pbkdf2,
+ { name: "AES-GCM", length: 128, hash: "SHA-256" }, true, ["encrypt"],
+ );
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("SHA-256 512", `${lowerHash.algorithm.hash.name} ${lowerHash.algorithm.length}`);
+ testing.expectEqual("SHA-384 1024", `${objectHash.algorithm.hash.name} ${objectHash.algorithm.length}`);
+ testing.expectEqual("SHA-512 HS512", `${lowerImport.algorithm.hash.name} ${lowerJwk.alg}`);
+ testing.expectEqual("1,33", [...sizes].join("|"));
+ testing.expectEqual(0, lowBits);
+ testing.expectEqual(7, k7.algorithm.length);
+ testing.expectEqual(257, k257.algorithm.length);
+ testing.expectEqual("HS256", k257Jwk.alg);
+ testing.expectEqual(264, reimported.algorithm.length);
+ testing.expectEqual(256, whole.algorithm.length);
+ testing.expectEqual(255, k255.algorithm.length);
+ testing.expectEqual(32, k255Raw.byteLength);
+ testing.expectEqual(true, sameMac);
+ testing.expectEqual(250, jwk250.algorithm.length);
+ testing.expectEqual("SHA-256 128", `${derived.algorithm.hash.name} ${derived.algorithm.length}`);
+ testing.expectEqual("TypeError", results.genHuge);
+ testing.expectEqual("TypeError", results.genHugeNoUsages);
+ testing.expectEqual("TypeError", results.genNegative);
+ testing.expectEqual("TypeError", results.genNaN);
+ testing.expectEqual("OperationError", results.genZero);
+ testing.expectEqual("TypeError", results.importHuge);
+ testing.expectEqual("TypeError", results.deriveHuge);
+ testing.expectEqual(null, results.import256);
+ testing.expectEqual(null, results.import249);
+ testing.expectEqual("DataError", results.import248);
+ testing.expectEqual("DataError", results.import257);
+ testing.expectEqual("DataError", results.import0);
+ testing.expectEqual("DataError", results.jwk200);
+ testing.expectEqual(null, results.rsaWithLength);
+ testing.expectEqual("OperationError", results.genNull);
+ testing.expectEqual("DataError", results.importNull);
+ testing.expectEqual("NotSupportedError", results.deriveUnknown);
+ testing.expectEqual("AES-GCM 128", `${aesWithHash.algorithm.name} ${aesWithHash.algorithm.length}`);
+ });
+</script>
+
<script id=generateKey-edxxx-validation type=module>
const state = await testing.async();
// Ed25519 / Ed448 only allow sign/verify; X448 only allows deriveKey/deriveBits.
diff --git a/src/browser/webapi/CryptoKey.zig b/src/browser/webapi/CryptoKey.zig
index ebea79386..df6860e01 100644
--- a/src/browser/webapi/CryptoKey.zig
+++ b/src/browser/webapi/CryptoKey.zig
@@ -62,6 +62,8 @@ pub const Algorithm = struct {
hash: ?[]const u8 = null,
named_curve: ?[]const u8 = null,
modulus_length: ?u32 = null,
+ /// HMAC: the key's length in bits, which needn't fill its last byte.
+ length: ?u32 = null,
/// RSA: big-endian, duped into the key's arena by init.
public_exponent: ?[]const u8 = null,
};
@@ -168,8 +170,9 @@ pub fn getExtractable(self: *const CryptoKey) bool {
}
/// The shape of the `.algorithm` dictionary depends on the algorithm. AES and
-/// HMAC expose a `length` (in bits, derived from the key material); HMAC also
-/// exposes a nested `hash`.
+/// HMAC expose a `length` in bits (AES's from the key material, HMAC's as
+/// stored, since it needn't fill the last byte); HMAC also exposes a nested
+/// `hash`.
const AlgorithmReport = union(enum) {
keyed: struct { name: []const u8, length: u32 },
hmac: struct { name: []const u8, length: u32, hash: struct { name: []const u8 } },
@@ -184,12 +187,12 @@ const AlgorithmReport = union(enum) {
};
pub fn getAlgorithm(self: *const CryptoKey) AlgorithmReport {
- const length: u32 = @intCast(self._key.len * 8);
return switch (self._type) {
- .aes => .{ .keyed = .{ .name = self._algorithm.name, .length = length } },
+ // AES keys are 16, 24 or 32 bytes.
+ .aes => .{ .keyed = .{ .name = self._algorithm.name, .length = @intCast(self._key.len * 8) } },
.hmac => .{ .hmac = .{
.name = self._algorithm.name,
- .length = length,
+ .length = self._algorithm.length orelse 0,
.hash = .{ .name = self._algorithm.hash orelse "" },
} },
.ec => .{ .ec = .{
diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zig
index 15441109d..807b018d4 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -169,8 +169,9 @@ pub fn importKey(
return AES.importJwk(name, jwk, extractable, key_usages, exec);
}
if (eqlIgnoreCase(name, "HMAC")) {
+ const length = try HMAC.lengthParam(importLength(algo), local);
const hash_name = importHash(algo) orelse return local.typeError("HMAC import requires a hash");
- return HMAC.importJwk(hash_name, jwk, extractable, key_usages, exec);
+ return HMAC.importJwk(hash_name, jwk, length, extractable, key_usages, exec);
}
// HKDF and PBKDF2 keys only come in "raw".
log.debug(.not_implemented, "SubtleCrypto.importKey", .{ .name = name, .format = format });
@@ -210,8 +211,9 @@ pub fn importKey(
}
}
if (eqlIgnoreCase(name, "HMAC")) {
+ const length = try HMAC.lengthParam(importLength(algo), local);
const hash_name = importHash(algo) orelse return local.typeError("HMAC import requires a hash");
- return HMAC.import(hash_name, raw, extractable, key_usages, exec);
+ return HMAC.import(hash_name, raw, length, extractable, key_usages, exec);
}
log.debug(.not_implemented, "SubtleCrypto.importKey", .{ .name = name });
@@ -231,6 +233,15 @@ fn importHash(algo: algorithm.Import) ?[]const u8 {
};
}
+/// The `length` member of an HMAC importKey algorithm, unconverted (see
+/// HMAC.lengthParam). Null when absent, or for the other variants.
+fn importLength(algo: algorithm.Import) ?js.Value {
+ return switch (algo) {
+ .hmac => |h| h.length,
+ 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 {
@@ -426,12 +437,24 @@ pub fn deriveKey(
return AES.import(k.name, bits, extractable, key_usages, exec);
},
.hmac => |h| {
- const hash_name = h.hash.name();
+ const local = exec.js.local.?;
+ // This shape ({name, hash, length?}) also matches an AES algorithm
+ // carrying a stray `hash`, or another algorithm's: go by the name.
+ if (AES.canonicalName(h.name) != null) {
+ const length = try HMAC.lengthParam(h.length, local) orelse return local.typeError("AES requires a length");
+ const bits = try deriveRaw(algo, base_key, length, usage_ok, exec);
+ return AES.import(h.name, bits, extractable, key_usages, exec);
+ }
+ if (!eqlIgnoreCase(h.name, "HMAC")) {
+ return error.NotSupported;
+ }
+ const requested = try HMAC.lengthParam(h.length, local);
+ const hash_name = common.canonicalHash(h.hash.name()) orelse return error.NotSupported;
const hash_md = crypto.findDigest(hash_name) catch return error.NotSupported;
// Default length, per spec, is the hash's block size (in bits).
- const length: u32 = h.length orelse @intCast(crypto.EVP_MD_block_size(hash_md) * 8);
+ const length: u32 = requested orelse @intCast(crypto.EVP_MD_block_size(hash_md) * 8);
const bits = try deriveRaw(algo, base_key, length, usage_ok, exec);
- return HMAC.import(hash_name, bits, extractable, key_usages, exec);
+ return HMAC.import(hash_name, bits, length, extractable, key_usages, exec);
},
.object, .name => {
log.debug(.not_implemented, "SubtleCrypto.deriveKey", .{});
diff --git a/src/browser/webapi/crypto/HMAC.zig b/src/browser/webapi/crypto/HMAC.zig
index afd24d6c7..551bb1522 100644
--- a/src/browser/webapi/crypto/HMAC.zig
+++ b/src/browser/webapi/crypto/HMAC.zig
@@ -42,12 +42,13 @@ pub fn init(
if (!std.ascii.eqlIgnoreCase(params.name, "HMAC")) {
return error.NotSupported;
}
- const hash_name = switch (params.hash) {
+ // Normalization converts the dictionary's members, then the hash: an
+ // unrecognized one surfaces as NotSupportedError, before the usages.
+ const length = try lengthParam(params.length, local);
+ const hash_name = common.canonicalHash(switch (params.hash) {
.string => |str| str,
.object => |obj| obj.name,
- };
- // Per spec, an unrecognized hash is caught during algorithm normalization
- // and surfaces as NotSupportedError.
+ }) orelse return error.NotSupported;
const digest = crypto.findDigest(hash_name) catch return error.NotSupported;
// HMAC only accepts sign / verify; any other usage is a SyntaxError per
@@ -66,60 +67,66 @@ pub fn init(
return error.SyntaxError;
}
- const block_size: usize = blk: {
- // Caller provides this in bits, not bytes.
- if (params.length) |length| {
- break :blk length >> 3;
- }
- // Prefer block size of the hash function instead.
- break :blk crypto.EVP_MD_block_size(digest);
- };
- // `block_size` cannot be 0.
- if (block_size == 0) {
+ // In bits; by default, the block size of the hash function.
+ const bits: u32 = length orelse @intCast(crypto.EVP_MD_block_size(digest) * 8);
+ if (bits == 0) {
return error.OperationError;
}
- // Should we reject this in promise too?
- const key = try exec.local_arena.alloc(u8, block_size);
+ // Enough bytes for `bits`, the ones past it in the last byte left zero.
+ const key = try exec.local_arena.alloc(u8, (@as(usize, bits) + 7) / 8);
// HMAC is simply CSPRNG.
const res = crypto.RAND_bytes(key.ptr, key.len);
lp.assert(res == 1, "HMAC.init", .{ .res = res });
+ const remainder_bits: u3 = @intCast(bits % 8);
+ if (remainder_bits != 0) {
+ key[key.len - 1] &= ~(@as(u8, 0xFF) >> remainder_bits);
+ }
const crypto_key = try CryptoKey.init(exec, .{
._type = .hmac,
._extractable = extractable,
._usages = mask,
._key = key,
- ._algorithm = .{ .name = "HMAC", .hash = hash_name },
+ ._algorithm = .{ .name = "HMAC", .hash = hash_name, .length = bits },
._vary = .{ .digest = digest },
});
return local.resolvePromise(crypto_key);
}
+/// HmacKeyGenParams' and HmacImportParams' optional `length`, in bits: an
+/// [EnforceRange] unsigned long, so a value outside u32 (NaN, the infinities)
+/// is a TypeError. Undefined is no length; null converts to 0.
+pub fn lengthParam(value: ?js.Value, local: *const js.Local) !?u32 {
+ const v = value orelse return null;
+ return js.enforceRange(u32, try v.toF64()) catch local.typeError("length is out of range");
+}
+
/// 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).
+/// checks (DataError). `length` is as for `import`.
pub fn importJwk(
hash_name: []const u8,
jwk: algorithm.KeyData.Jwk,
+ length: ?u32,
extractable: bool,
key_usages: []const []const u8,
exec: *const Execution,
) !js.Promise {
- _ = crypto.findDigest(hash_name) catch return error.NotSupported;
+ const hash = common.canonicalHash(hash_name) orelse 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;
+ if (!std.mem.eql(u8, alg, try jwkAlg(hash, 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);
+ // import() rejects an empty key, or a length that doesn't fit it (DataError).
+ return import(hash, raw, length, extractable, key_usages, exec);
}
/// The JWK `alg` of an HMAC key with the given hash ("SHA-256" → "HS256").
@@ -127,24 +134,33 @@ 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).
+/// Imports raw HMAC key material (from the `raw` format, the `k` of a JWK
+/// that `importJwk` checked, or deriveKey's bits). `length`, in bits, is
+/// HmacImportParams': when given, it must end in the key's last byte (it can
+/// leave some of its bits out), else DataError. The key bytes are kept whole.
pub fn import(
hash_name: []const u8,
raw: []const u8,
+ length: ?u32,
extractable: bool,
key_usages: []const []const u8,
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const digest = crypto.findDigest(hash_name) catch return error.NotSupported;
+ const hash = common.canonicalHash(hash_name) orelse return error.NotSupported;
+ const digest = crypto.findDigest(hash) catch return error.NotSupported;
const mask = try common.usageMask(&.{ "sign", "verify" }, key_usages);
if (raw.len == 0) {
return error.DataError;
}
+ const data_bits = raw.len * 8;
+ const bits: usize = length orelse data_bits;
+ if (bits > data_bits or bits + 8 <= data_bits) {
+ return error.DataError;
+ }
const crypto_key = try CryptoKey.init(exec, .{
._type = .hmac,
@@ -152,7 +168,7 @@ pub fn import(
._extractable = extractable,
._usages = mask,
._key = raw,
- ._algorithm = .{ .name = "HMAC", .hash = hash_name },
+ ._algorithm = .{ .name = "HMAC", .hash = hash, .length = std.math.cast(u32, bits) orelse return error.DataError },
._vary = .{ .digest = digest },
});
diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zig
index 131965766..f89f4e890 100644
--- a/src/browser/webapi/crypto/RSA.zig
+++ b/src/browser/webapi/crypto/RSA.zig
@@ -131,17 +131,8 @@ pub fn scheme(name: []const u8) ?*const Scheme {
return null;
}
-const hashes = [_][]const u8{ "SHA-1", "SHA-256", "SHA-384", "SHA-512" };
-
-/// The registered hash name (case-insensitive), or null if not a supported
-/// hash. Stored on the key, so `.algorithm.hash.name` reports it and
-/// `findDigest` (which is case-sensitive) can look it up.
-pub fn canonicalHash(name: []const u8) ?[]const u8 {
- for (hashes) |canonical| {
- if (eql(name, canonical)) return canonical;
- }
- return null;
-}
+const hashes = common.hashes;
+const canonicalHash = common.canonicalHash;
/// The JWK `alg` of `s` for a canonical hash name.
fn jwkAlgOfHash(s: *const Scheme, hash: []const u8) ?[]const u8 {
diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zig
index 96e0064bc..050250308 100644
--- a/src/browser/webapi/crypto/algorithm.zig
+++ b/src/browser/webapi/crypto/algorithm.zig
@@ -76,7 +76,10 @@ pub const Init = union(enum) {
object: struct { name: []const u8 },
},
/// If omitted, default is the block size of the chosen hash function.
- length: ?usize,
+ /// An [EnforceRange] unsigned long, kept as a value: HMAC.init converts
+ /// it (HMAC.lengthParam) once the name is known to be HMAC's, since
+ /// another algorithm's object can be probed into this dictionary.
+ length: ?js.Value = null,
/// Always HMAC.
name: []const u8,
};
@@ -127,7 +130,8 @@ pub const Derive = union(enum) {
/// produce. HMAC carries a hash; AES carries a length. Probed in that order so
/// the more specific shapes win.
pub const DerivedKey = union(enum) {
- hmac: struct { hash: Derive.Hash, length: ?u32 = null, name: []const u8 },
+ /// `length` as in Import.hmac.
+ hmac: struct { hash: Derive.Hash, length: ?js.Value = null, name: []const u8 },
keyed: struct { length: u32, name: []const u8 },
object: struct { name: []const u8 },
name: []const u8,
@@ -142,7 +146,9 @@ pub const Import = union(enum) {
string: []const u8,
object: struct { name: []const u8 },
},
- length: ?u32 = null,
+ /// HMAC's [EnforceRange] unsigned long, kept as a value: RSA imports
+ /// share this variant and ignore it. HMAC.lengthParam converts it.
+ length: ?js.Value = null,
name: []const u8,
},
ec: struct { name: []const u8, namedCurve: []const u8 },
diff --git a/src/browser/webapi/crypto/common.zig b/src/browser/webapi/crypto/common.zig
index ad86a7012..e1d28669e 100644
--- a/src/browser/webapi/crypto/common.zig
+++ b/src/browser/webapi/crypto/common.zig
@@ -26,6 +26,19 @@ const Allocator = std.mem.Allocator;
const CryptoKey = @import("../CryptoKey.zig");
const algorithm = @import("algorithm.zig");
+/// The hashes the algorithms take (their `hash` member).
+pub const hashes = [_][]const u8{ "SHA-1", "SHA-256", "SHA-384", "SHA-512" };
+
+/// The registered hash name (case-insensitive), or null if not a supported
+/// hash. Stored on the key, so `.algorithm.hash.name` reports it and
+/// `findDigest` (which is case-sensitive) can look it up.
+pub fn canonicalHash(name: []const u8) ?[]const u8 {
+ for (hashes) |canonical| {
+ if (std.ascii.eqlIgnoreCase(name, canonical)) return canonical;
+ }
+ return null;
+}
+
/// Maps a usage string to its `CryptoKey.Usages` bit, or null if unknown.
pub fn usageBit(name: []const u8) ?u8 {
const U = CryptoKey.Usages;