Lightpanda: the headless browser designed for AI and automation
webapi: small crypto fixes
Karl Seguincb58c518d158
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.htmlindex 5ff05893f..93abac9a4 100644--- a/src/browser/tests/crypto.html+++ b/src/browser/tests/crypto.html@@ -165,6 +165,48 @@});</script>+<script id=derive-key-import 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 secret = new Uint8Array(16);+ const imp = (name, extractable) => errorName(() => subtle.importKey("raw", secret, name, extractable, ["deriveBits"]));++ // HKDF and PBKDF2 keys are never extractable: asking is a SyntaxError.+ const results = {+ hkdf: await imp("HKDF", false),+ pbkdf2: await imp("PBKDF2", false),+ hkdfExtractable: await imp("HKDF", true),+ pbkdf2Extractable: await imp("PBKDF2", true),+ };++ // HKDF yields at most 255 blocks of its hash (RFC 5869): 8160 bytes for+ // SHA-256. One more is an OperationError, before any buffer is allocated.+ const hkdfKey = await subtle.importKey("raw", secret, "HKDF", false, ["deriveBits"]);+ const hkdf = { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(16), info: new Uint8Array(0) };+ results.hkdfMax = await errorName(() => subtle.deriveBits(hkdf, hkdfKey, 255 * 32 * 8));+ results.hkdfOverMax = await errorName(() => subtle.deriveBits(hkdf, hkdfKey, 255 * 32 * 8 + 8));+ results.hkdfHuge = await errorName(() => subtle.deriveBits(hkdf, hkdfKey, 2 ** 32 - 8));++ state.resolve();+ await state.done(() => {+ testing.expectEqual(null, results.hkdf);+ testing.expectEqual(null, results.pbkdf2);+ testing.expectEqual("SyntaxError", results.hkdfExtractable);+ testing.expectEqual("SyntaxError", results.pbkdf2Extractable);+ testing.expectEqual(null, results.hkdfMax);+ testing.expectEqual("OperationError", results.hkdfOverMax);+ testing.expectEqual("OperationError", results.hkdfHuge);+ });+</script>+<script id=rsa-oaep-roundtrip type=module>const state = await testing.async();const { privateKey, publicKey } = await crypto.subtle.generateKey(@@ -697,6 +739,83 @@});</script>+<script id=der-import-strict 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 rsa = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };+ const ec = { name: "ECDSA", namedCurve: "P-256" };+ const ecPair = await subtle.generateKey(ec, true, ["sign", "verify"]);+ const ecSpki = new Uint8Array(await subtle.exportKey("spki", ecPair.publicKey));+ const ecPkcs8 = new Uint8Array(await subtle.exportKey("pkcs8", ecPair.privateKey));+ const edPair = await subtle.generateKey("Ed25519", true, ["sign", "verify"]);+ const edSpki = new Uint8Array(await subtle.exportKey("spki", edPair.publicKey));+ const edPkcs8 = new Uint8Array(await subtle.exportKey("pkcs8", edPair.privateKey));++ // Three zero bytes after the structure. d2i_* used to stop at its end.+ const withTrailing = (der) => {+ const out = new Uint8Array(der.length + 3);+ out.set(der);+ return out;+ };+ // The DER length of the TLV at `i`, and the offset of its contents.+ const tlv = (der, i) => {+ let len = der[i + 1];+ let at = i + 2;+ if (len & 0x80) {+ const n = len & 0x7f;+ len = 0;+ for (let j = 0; j < n; j++) len = (len << 8) | der[at++];+ }+ return { len, at };+ };+ // The privateKey OCTET STRING inside a PrivateKeyInfo: the legacy+ // RSAPrivateKey (PKCS #1) or ECPrivateKey (SEC 1) encoding, which+ // d2i_AutoPrivateKey used to accept as "pkcs8".+ const innerKey = (pkcs8) => {+ let { at } = tlv(pkcs8, 0); // PrivateKeyInfo+ at = tlv(pkcs8, at).at + tlv(pkcs8, at).len; // version+ at = tlv(pkcs8, at).at + tlv(pkcs8, at).len; // AlgorithmIdentifier+ const { len, at: start } = tlv(pkcs8, at); // privateKey+ return pkcs8.slice(start, start + len);+ };++ const results = {+ rsaSpki: await errorName(() => subtle.importKey("spki", rsaTestKey.spki, rsa, true, ["verify"])),+ rsaPkcs8: await errorName(() => subtle.importKey("pkcs8", rsaTestKey.pkcs8, rsa, true, ["sign"])),+ rsaSpkiTrailing: await errorName(() => subtle.importKey("spki", withTrailing(rsaTestKey.spki), rsa, true, ["verify"])),+ rsaPkcs8Trailing: await errorName(() => subtle.importKey("pkcs8", withTrailing(rsaTestKey.pkcs8), rsa, true, ["sign"])),+ rsaPkcs1: await errorName(() => subtle.importKey("pkcs8", innerKey(rsaTestKey.pkcs8), rsa, true, ["sign"])),+ ecSpki: await errorName(() => subtle.importKey("spki", ecSpki, ec, true, ["verify"])),+ ecPkcs8: await errorName(() => subtle.importKey("pkcs8", ecPkcs8, ec, true, ["sign"])),+ ecSpkiTrailing: await errorName(() => subtle.importKey("spki", withTrailing(ecSpki), ec, true, ["verify"])),+ ecPkcs8Trailing: await errorName(() => subtle.importKey("pkcs8", withTrailing(ecPkcs8), ec, true, ["sign"])),+ ecSec1: await errorName(() => subtle.importKey("pkcs8", innerKey(ecPkcs8), ec, true, ["sign"])),+ edSpki: await errorName(() => subtle.importKey("spki", edSpki, "Ed25519", true, ["verify"])),+ edPkcs8: await errorName(() => subtle.importKey("pkcs8", edPkcs8, "Ed25519", true, ["sign"])),+ edSpkiTrailing: await errorName(() => subtle.importKey("spki", withTrailing(edSpki), "Ed25519", true, ["verify"])),+ edPkcs8Trailing: await errorName(() => subtle.importKey("pkcs8", withTrailing(edPkcs8), "Ed25519", true, ["sign"])),+ empty: await errorName(() => subtle.importKey("spki", new Uint8Array(0), rsa, true, ["verify"])),+ };++ state.resolve();+ await state.done(() => {+ for (const ok of ["rsaSpki", "rsaPkcs8", "ecSpki", "ecPkcs8", "edSpki", "edPkcs8"]) {+ testing.expectEqual(`${ok}: null`, `${ok}: ${results[ok]}`);+ }+ for (const bad of ["rsaSpkiTrailing", "rsaPkcs8Trailing", "rsaPkcs1", "ecSpkiTrailing", "ecPkcs8Trailing", "ecSec1", "edSpkiTrailing", "edPkcs8Trailing", "empty"]) {+ testing.expectEqual(`${bad}: DataError`, `${bad}: ${results[bad]}`);+ }+ });+</script>+<script id=rsa-pss type=module>const state = await testing.async();const subtle = crypto.subtle;@@ -1337,6 +1456,18 @@pbkdf2: await errorName(() => subtle.importKey("jwk", { kty: "oct", k: k16 }, "PBKDF2", false, ["deriveBits"])),};+ // An exported JWK lists its members in lexicographic order, the WebIDL+ // dictionary order Chrome returns, and wrapKey serializes the same order.+ const aesKey = await subtle.generateKey({ name: "AES-GCM", length: 128 }, true, ["encrypt"]);+ const hmacKey = await subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, true, ["sign"]);+ const order = {+ aes: Object.keys(await subtle.exportKey("jwk", aesKey)).join(),+ hmac: Object.keys(await subtle.exportKey("jwk", hmacKey)).join(),+ };+ const decrypter = await subtle.generateKey({ name: "AES-GCM", length: 128 }, false, ["wrapKey", "decrypt"]);+ const wrapped = await subtle.wrapKey("jwk", aesKey, decrypter, gcm);+ const wrappedText = new TextDecoder().decode(await subtle.decrypt(gcm, decrypter, wrapped));+state.resolve();await state.done(() => {// Compared with the case name, so a failure says which one.@@ -1350,6 +1481,10 @@testing.expectEqual("SyntaxError", results.badUsageBadKty);testing.expectEqual("NotSupportedError", results.hkdf);testing.expectEqual("NotSupportedError", results.pbkdf2);+ testing.expectEqual("alg,ext,k,key_ops,kty", order.aes);+ testing.expectEqual("alg,ext,k,key_ops,kty", order.hmac);+ testing.expectEqual(JSON.stringify(JSON.parse(wrappedText)), wrappedText);+ testing.expectEqual(true, wrappedText.startsWith('{"alg":"A128GCM","ext":true,"k":"'));});</script>@@ -1739,6 +1874,11 @@// null converts to 0, as for any unsigned long.genNull: await errorName(() => gen({ length: null })),importNull: await errorName(() => imp({ length: null })),+ // Generation is capped at 2^16 bits: any longer key is hashed down to the+ // block size anyway, and an unsigned long could ask for 512MB.+ genMax: await errorName(() => gen({ length: 2 ** 16 })),+ genOverMax: await errorName(() => gen({ length: 2 ** 16 + 8 })),+ genGigantic: await errorName(() => gen({ length: 2 ** 31 })),// 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,@@ -1782,6 +1922,9 @@testing.expectEqual(null, results.rsaWithLength);testing.expectEqual("OperationError", results.genNull);testing.expectEqual("DataError", results.importNull);+ testing.expectEqual(null, results.genMax);+ testing.expectEqual("OperationError", results.genOverMax);+ testing.expectEqual("OperationError", results.genGigantic);testing.expectEqual("NotSupportedError", results.deriveUnknown);testing.expectEqual("AES-GCM 128", `${aesWithHash.algorithm.name} ${aesWithHash.algorithm.length}`);});diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zigindex b16ac9db7..99ac92365 100644--- a/src/browser/webapi/SubtleCrypto.zig+++ b/src/browser/webapi/SubtleCrypto.zig@@ -216,10 +216,11 @@ pub fn importKey(}// HKDF / PBKDF2: key-derivation inputs. The raw bytes are the key; there's- // no length constraint and these keys are non-extractable.+ // no length constraint and these keys are never extractable.inline for ([_][]const u8{ "HKDF", "PBKDF2" }) |derive_name| {if (eqlIgnoreCase(name, derive_name)) {const mask = try common.usageMask(&.{ "deriveKey", "deriveBits" }, key_usages);+ if (extractable) return error.SyntaxError;const crypto_key = try CryptoKey.init(exec, .{._type = .derive,._kind = .secret,@@ -393,13 +394,15 @@ fn exportAs(format: []const u8, key: *CryptoKey, exec: *const Execution) !Exportreturn local.typeError("invalid format");}-/// The JSON Web Key returned for symmetric ("oct") keys.+/// The JSON Web Key returned for symmetric ("oct") keys. Members are listed+/// in lexicographic order, the order browsers return a JsonWebKey in, which is+/// also the order wrapKey serializes them in.const JwkSecret = struct {- kty: []const u8 = "oct",- k: []const u8,alg: []const u8,ext: bool,+ k: []const u8,key_ops: []const []const u8,+ kty: []const u8 = "oct",};fn exportJwk(key: *CryptoKey, exec: *const Execution) !Jwk {@@ -417,9 +420,9 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !Jwk {};return .{ .secret = .{- .k = try common.base64Encode(exec.local_arena, key._key),.alg = alg,.ext = key._extractable,+ .k = try common.base64Encode(exec.local_arena, key._key),.key_ops = try key.getUsages(exec),} };}diff --git a/src/browser/webapi/crypto/EC.zig b/src/browser/webapi/crypto/EC.zigindex f2fb265f2..c93300f96 100644--- a/src/browser/webapi/crypto/EC.zig+++ b/src/browser/webapi/crypto/EC.zig@@ -144,9 +144,9 @@ pub fn generate(}/// Imports an EC key from `spki` (public) or `pkcs8` (private) DER, or from a-/// `raw` public point (SEC 1: uncompressed or compressed). libcrypto parses-/// the data, so a malformed structure, a point that isn't on the curve, or a-/// key on another curve than `named_curve` is DataError. JWK goes through+/// `raw` public point (SEC 1: uncompressed or compressed). A malformed+/// structure (common.parseDer), a point that isn't on the curve, or a key on+/// another curve than `named_curve` is DataError. JWK goes through/// `importJwk`.pub fn import(name: []const u8,@@ -165,25 +165,10 @@ pub fn import(return error.NotSupported;};- var ptr: [*c]const u8 = data.ptr;- const pkey: *crypto.EVP_PKEY = blk: {- if (std.mem.eql(u8, format, "spki")) {- break :blk crypto.d2i_PUBKEY(null, &ptr, @intCast(data.len)) orelse {- crypto.ERR_clear_error();- return error.DataError;- };- }- if (std.mem.eql(u8, format, "pkcs8")) {- break :blk crypto.d2i_AutoPrivateKey(null, &ptr, @intCast(data.len)) orelse {- crypto.ERR_clear_error();- return error.DataError;- };- }- if (std.mem.eql(u8, format, "raw")) {- break :blk try keyFromPoint(curve, data, null);- }- return error.NotSupported;- };+ const pkey = if (std.mem.eql(u8, format, "raw"))+ try keyFromPoint(curve, data, null)+ else+ try common.parseDer(format, data);errdefer crypto.EVP_PKEY_free(pkey);if (crypto.EVP_PKEY_id(pkey) != crypto.EVP_PKEY_EC) {diff --git a/src/browser/webapi/crypto/HMAC.zig b/src/browser/webapi/crypto/HMAC.zigindex 12176a2be..c5c635346 100644--- a/src/browser/webapi/crypto/HMAC.zig+++ b/src/browser/webapi/crypto/HMAC.zig@@ -30,6 +30,12 @@ const CryptoKey = @import("../CryptoKey.zig");const Execution = js.Execution;+/// The longest key generateKey makes, in bits. The length is an unsigned+/// long, so a page could ask for 512MB of key material (allocated twice); HMAC+/// hashes any key longer than the block size (1024 bits at most) down to it,+/// so nothing legitimate asks for more than this.+const max_generated_length = 1 << 16;+pub fn init(params: algorithm.Init.HmacKeyGen,extractable: bool,@@ -66,7 +72,7 @@ pub fn init(// 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) {+ if (bits == 0 or bits > max_generated_length) {return error.OperationError;}diff --git a/src/browser/webapi/crypto/KDF.zig b/src/browser/webapi/crypto/KDF.zigindex 32186bedf..74ae89633 100644--- a/src/browser/webapi/crypto/KDF.zig+++ b/src/browser/webapi/crypto/KDF.zig@@ -113,12 +113,18 @@ pub fn hkdf(// Normalizing the params (the hash) comes before the key checks.const digest = crypto.findDigest(try params.hash.canonical(exec.js.local.?)) catch return error.NotSupported;try checkBaseKey(base_key, "HKDF", usage_ok);- const out = try exec.local_arena.alloc(u8, try outputLen(length));+ const out_len = try outputLen(length);// A zero-length derivation is valid and yields an empty buffer; the C// routines reject a zero output length, so short-circuit here.- if (out.len == 0) {- return out;+ if (out_len == 0) {+ return &.{};}+ // RFC 5869 caps the output at 255 blocks of the hash. libcrypto rejects+ // more too, but only once the buffer (up to 512MB) has been allocated.+ if (out_len > 255 * crypto.EVP_MD_size(digest)) {+ return error.OperationError;+ }+ const out = try exec.local_arena.alloc(u8, out_len);const salt = params.salt.values;const info = params.info.values;diff --git a/src/browser/webapi/crypto/OKP.zig b/src/browser/webapi/crypto/OKP.zigindex 1cc720d3c..a6d40a408 100644--- a/src/browser/webapi/crypto/OKP.zig+++ b/src/browser/webapi/crypto/OKP.zig@@ -119,8 +119,8 @@ pub fn generate(curve: *const Curve, extractable: bool, key_usages: []const []co}/// Imports a key from `spki` or `pkcs8` DER, or a `raw` public key. A-/// malformed structure, a key of another algorithm, or a raw key of the wrong-/// size is DataError. JWK goes through `importJwk`. The usages were already+/// malformed structure (common.parseDer), a key of another algorithm, or a+/// raw key of the wrong size is DataError. JWK goes through `importJwk`. The usages were already/// checked against the key's kind (SubtleCrypto.importKey).pub fn import(curve: *const Curve,@@ -133,20 +133,7 @@ pub fn import() !js.Promise {const local = exec.js.local.?;- var ptr: [*c]const u8 = data.ptr;- const pkey: *crypto.EVP_PKEY = blk: {- if (std.mem.eql(u8, format, "spki")) {- break :blk crypto.d2i_PUBKEY(null, &ptr, @intCast(data.len)) orelse {- crypto.ERR_clear_error();- return error.DataError;- };- }- if (std.mem.eql(u8, format, "pkcs8")) {- break :blk crypto.d2i_AutoPrivateKey(null, &ptr, @intCast(data.len)) orelse {- crypto.ERR_clear_error();- return error.DataError;- };- }+ const pkey = blk: {if (std.mem.eql(u8, format, "raw")) {if (data.len != curve.size) return error.DataError;break :blk crypto.EVP_PKEY_new_raw_public_key(curve.pkey_type, null, data.ptr, data.len) orelse {@@ -154,14 +141,12 @@ pub fn import(return error.DataError;};}- return error.NotSupported;+ break :blk try common.parseDer(format, data);};errdefer crypto.EVP_PKEY_free(pkey);- // The DER's own algorithm identifier must be this curve's, and nothing- // may follow its structure (`raw` doesn't move `ptr`).+ // The DER's own algorithm identifier must be this curve's.if (crypto.EVP_PKEY_id(pkey) != curve.pkey_type) return error.DataError;- if (!std.mem.eql(u8, format, "raw") and ptr != data.ptr + data.len) return error.DataError;return local.resolvePromise(try newKey(curve, pkey, is_private, extractable, usages_mask, exec));}diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zigindex a127551e5..9aa19475b 100644--- a/src/browser/webapi/crypto/RSA.zig+++ b/src/browser/webapi/crypto/RSA.zig@@ -237,7 +237,7 @@ pub fn generate(}/// Imports an RSA key of scheme `s` from DER: `spki` (public) or `pkcs8`-/// (private). libcrypto parses the DER, so a malformed structure is DataError.+/// (private). A malformed structure is DataError (common.parseDer)./// `hash_name` is the digest of the OAEP padding or of the signature, kept on/// the key. JWK goes through `importJwk`.pub fn import(@@ -256,17 +256,8 @@ pub fn import(// surface only on the first operation.const hash = canonicalHash(hash_name) orelse return error.NotSupported;- var ptr: [*c]const u8 = der.ptr;- const pkey: *crypto.EVP_PKEY = blk: {- if (std.mem.eql(u8, format, "spki")) {- break :blk crypto.d2i_PUBKEY(null, &ptr, @intCast(der.len)) orelse return error.DataError;- }- if (std.mem.eql(u8, format, "pkcs8")) {- break :blk crypto.d2i_AutoPrivateKey(null, &ptr, @intCast(der.len)) orelse return error.DataError;- }- // "raw" isn't a format RSA keys have.- return error.NotSupported;- };+ // "raw" isn't a format RSA keys have: NotSupported from parseDer.+ const pkey = try common.parseDer(format, der);errdefer crypto.EVP_PKEY_free(pkey);if (crypto.EVP_PKEY_id(pkey) != crypto.EVP_PKEY_RSA) return error.DataError;diff --git a/src/browser/webapi/crypto/common.zig b/src/browser/webapi/crypto/common.zigindex 0398b8748..234f5517e 100644--- a/src/browser/webapi/crypto/common.zig+++ b/src/browser/webapi/crypto/common.zig@@ -197,6 +197,27 @@ pub fn base64Encode(allocator: Allocator, bytes: []const u8) error{OutOfMemory}!return encoder.encode(out, bytes);}+/// Parses the DER of an asymmetric key (RSA, EC, OKP): a SubjectPublicKeyInfo for+/// `spki`, a PrivateKeyInfo for `pkcs8`. Anything libcrypto can't parse as+/// exactly that structure, trailing bytes included, is DataError, as in+/// Chrome. The caller checks the key's type and frees it.+pub fn parseDer(format: []const u8, der: []const u8) error{ DataError, NotSupported }!*crypto.EVP_PKEY {+ var cbs: crypto.CBS = .{ .data = der.ptr, .len = der.len };+ const pkey = blk: {+ if (std.mem.eql(u8, format, "spki")) break :blk crypto.EVP_parse_public_key(&cbs);+ if (std.mem.eql(u8, format, "pkcs8")) break :blk crypto.EVP_parse_private_key(&cbs);+ return error.NotSupported;+ } orelse {+ crypto.ERR_clear_error();+ return error.DataError;+ };+ if (cbs.len != 0) {+ crypto.EVP_PKEY_free(pkey);+ return error.DataError;+ }+ return pkey;+}+/// Exports an asymmetric key (RSA, EC) as DER: `spki` for a public key,/// `pkcs8` for a private one. Asking for the other half's format is/// InvalidAccessError.diff --git a/src/sys/libcrypto.zig b/src/sys/libcrypto.zigindex 3ce9e0610..61e5714a1 100644--- a/src/sys/libcrypto.zig+++ b/src/sys/libcrypto.zig@@ -182,9 +182,15 @@ pub extern fn ECDSA_SIG_get0(sig: *const ECDSA_SIG, out_r: *?*const BIGNUM, out_/// Takes ownership of `r` and `s` on success only.pub extern fn ECDSA_SIG_set0(sig: *ECDSA_SIG, r: *BIGNUM, s: *BIGNUM) c_int;-// DER decoders (advance `inp` past the parsed structure).-pub extern fn d2i_PUBKEY(out: ?*?*EVP_PKEY, inp: *[*c]const u8, len: c_long) ?*EVP_PKEY;-pub extern fn d2i_AutoPrivateKey(out: ?*?*EVP_PKEY, inp: *[*c]const u8, len: c_long) ?*EVP_PKEY;+// DER decoders over a CBS (a byte string cursor, advanced past the parsed+// structure). Unlike the d2i_* family, these parse exactly one SubjectPublicKeyInfo+// or PrivateKeyInfo: no legacy RSAPrivateKey / ECPrivateKey fallback.+pub const CBS = extern struct {+ data: [*]const u8,+ len: usize,+};+pub extern fn EVP_parse_public_key(cbs: *CBS) ?*EVP_PKEY;+pub extern fn EVP_parse_private_key(cbs: *CBS) ?*EVP_PKEY;// RSA: key generation, import, and the encrypt/decrypt and sign/verify operations.pub const EVP_PKEY_RSA = 6; // NID_rsaEncryption