Lightpanda: the headless browser designed for AI and automation
webapi: X25519 key import and export, and a peer check in deriveBits
orezraey4eb99ef3c35d
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.htmlindex e665dbaa1..5ff05893f 100644--- a/src/browser/tests/crypto.html+++ b/src/browser/tests/crypto.html@@ -2202,6 +2202,99 @@});</script>+<script id=x25519-keys 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 unhex = (h) => new Uint8Array(h.match(/../g).map((x) => parseInt(x, 16)));+ const b64u = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+ const describe = (key) => `${key.type}:${key.algorithm.name}:${key.extractable}:${key.usages.join("+")}`;++ // RFC 7748, section 6.1.+ const alicePrivate = unhex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");+ const alicePublic = unhex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a");+ const bobPublic = unhex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f");+ const shared = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742";+ const pkcs8 = unhex("302e020100300506032b656e04220420" + hex(alicePrivate));+ const jwkPrivate = { kty: "OKP", crv: "X25519", x: b64u(alicePublic), d: b64u(alicePrivate) };++ const alice = await subtle.importKey("pkcs8", pkcs8, "X25519", true, ["deriveBits", "deriveKey"]);+ const bob = await subtle.importKey("raw", bobPublic, { name: "x25519" }, true, []);+ const generated = await subtle.generateKey("X25519", true, ["deriveBits"]);+ const ed25519 = await subtle.generateKey("Ed25519", true, ["sign", "verify"]);+ const aes = await subtle.generateKey({ name: "AES-GCM", length: 128 }, true, ["encrypt"]);+ const derive = (publicKey, length) => subtle.deriveBits({ name: "X25519", public: publicKey }, alice, length);++ const results = {+ shared: hex(await derive(bob, 256)),+ sharedNull: hex(await derive(bob, null)),+ shared12: hex(await derive(bob, 12)),+ tooLong: await errorName(() => derive(bob, 264)),+ // The peer must be an X25519 public key: not a key of another algorithm+ // (which used to crash here) nor a private key.+ aesPeer: await errorName(() => derive(aes, 256)),+ ed25519Peer: await errorName(() => derive(ed25519.publicKey, 256)),+ privatePeer: await errorName(() => derive(alice, 256)),+ // A peer of small order gives an all-zero secret.+ smallOrderPeer: await errorName(async () => derive(await subtle.importKey("raw", new Uint8Array(32), "X25519", false, []), 256)),+ raw: hex(await subtle.exportKey("raw", bob)),+ spki: hex(await subtle.exportKey("spki", bob)),+ pkcs8: hex(await subtle.exportKey("pkcs8", alice)),+ // X25519's JWK has no alg.+ jwkPublic: JSON.stringify(await subtle.exportKey("jwk", bob)),+ jwkPrivate: JSON.stringify(await subtle.exportKey("jwk", alice)),+ importJwk: describe(await subtle.importKey("jwk", jwkPrivate, "X25519", false, ["deriveBits"])),+ importJwkAlg: describe(await subtle.importKey("jwk", { ...jwkPrivate, alg: "ignored" }, "X25519", false, ["deriveBits"])),+ importSpki: describe(await subtle.importKey("spki", unhex("302a300506032b656e032100" + hex(bobPublic)), "X25519", true, [])),+ useSig: await errorName(() => subtle.importKey("jwk", { ...jwkPrivate, use: "sig" }, "X25519", false, ["deriveBits"])),+ crvEd25519: await errorName(() => subtle.importKey("jwk", { ...jwkPrivate, crv: "Ed25519" }, "X25519", false, ["deriveBits"])),+ otherX: await errorName(() => subtle.importKey("jwk", { ...jwkPrivate, x: b64u(bobPublic) }, "X25519", false, ["deriveBits"])),+ rawWithUsage: await errorName(() => subtle.importKey("raw", bobPublic, "X25519", true, ["deriveBits"])),+ ed25519Spki: await errorName(async () => subtle.importKey("spki", await subtle.exportKey("spki", ed25519.publicKey), "X25519", true, [])),+ generatedPrivate: describe(generated.privateKey),+ generatedPublic: describe(generated.publicKey),+ generatedSelf: (await subtle.deriveBits({ name: "X25519", public: generated.publicKey }, generated.privateKey, 256)).byteLength,+ generateSign: await errorName(() => subtle.generateKey("X25519", true, ["sign"])),+ };++ state.resolve();+ await state.done(() => {+ testing.expectEqual(shared, results.shared);+ testing.expectEqual(shared, results.sharedNull);+ testing.expectEqual("4a50", results.shared12);+ testing.expectEqual("OperationError", results.tooLong);+ testing.expectEqual("InvalidAccessError", results.aesPeer);+ testing.expectEqual("InvalidAccessError", results.ed25519Peer);+ testing.expectEqual("InvalidAccessError", results.privatePeer);+ testing.expectEqual("OperationError", results.smallOrderPeer);+ testing.expectEqual(hex(bobPublic), results.raw);+ testing.expectEqual("302a300506032b656e032100" + hex(bobPublic), results.spki);+ testing.expectEqual(hex(pkcs8), results.pkcs8);+ testing.expectEqual(`{"crv":"X25519","ext":true,"key_ops":[],"kty":"OKP","x":"${b64u(bobPublic)}"}`, results.jwkPublic);+ testing.expectEqual(`{"crv":"X25519","d":"${b64u(alicePrivate)}","ext":true,"key_ops":["deriveKey","deriveBits"],"kty":"OKP","x":"${b64u(alicePublic)}"}`, results.jwkPrivate);+ testing.expectEqual("private:X25519:false:deriveBits", results.importJwk);+ testing.expectEqual("private:X25519:false:deriveBits", results.importJwkAlg);+ testing.expectEqual("public:X25519:true:", results.importSpki);+ testing.expectEqual("DataError", results.useSig);+ testing.expectEqual("DataError", results.crvEd25519);+ testing.expectEqual("DataError", results.otherX);+ testing.expectEqual("SyntaxError", results.rawWithUsage);+ testing.expectEqual("DataError", results.ed25519Spki);+ testing.expectEqual("private:X25519:true:deriveBits", results.generatedPrivate);+ testing.expectEqual("public:X25519:true:", results.generatedPublic);+ testing.expectEqual(32, results.generatedSelf);+ testing.expectEqual("SyntaxError", results.generateSign);+ });+</script>+<script id="digest" type=module>const state = await testing.async();async function hash(algo, data) {diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zigindex f48892184..b16ac9db7 100644--- a/src/browser/webapi/SubtleCrypto.zig+++ b/src/browser/webapi/SubtleCrypto.zig@@ -73,9 +73,6 @@ fn generateKeyFromName(key_usages: []const []const u8,exec: *const Execution,) !js.Promise {- if (name.eql(comptime .wrap("X25519"))) {- return X25519.init(extractable, key_usages, exec);- }if (OKP.curveOf(name.str())) |curve| {return OKP.generate(curve, extractable, key_usages, exec);}@@ -281,8 +278,8 @@ fn importKind(format: []const u8, key_data: algorithm.KeyData) bool {/// The usages permitted for an EC/OKP/RSA key of the given privacy, or null if/// the algorithm isn't one of the asymmetric algorithms handled here. Only EC,-/// RSA and Ed25519 import their keys; for the others this only drives usage-/// validation.+/// RSA, Ed25519 and X25519 import their keys; for the others this only drives+/// usage validation.fn asymmetricAllowedUsages(name: []const u8, is_private: bool) ?[]const []const u8 {if (eqlIgnoreCase(name, "ECDSA") or eqlIgnoreCase(name, "Ed25519") or eqlIgnoreCase(name, "Ed448")) {return if (is_private) &.{"sign"} else &.{"verify"};@@ -374,7 +371,7 @@ fn exportAs(format: []const u8, key: *CryptoKey, exec: *const Execution) !Exportif (key._type == .ec) {return .{ .bytes = try EC.exportRaw(key, exec) };}- if (key._type == .ed25519) {+ if (key._type == .ed25519 or key._type == .x25519) {return .{ .bytes = try OKP.exportRaw(key, exec) };}return .{ .bytes = key._key };@@ -386,7 +383,7 @@ fn exportAs(format: []const u8, key: *CryptoKey, exec: *const Execution) !Exportconst is_der = std.mem.eql(u8, format, "pkcs8") or std.mem.eql(u8, format, "spki");if (is_der) {- if (key._type == .rsa or key._type == .ec or key._type == .ed25519) {+ if (key._type == .rsa or key._type == .ec or key._type == .ed25519 or key._type == .x25519) {return .{ .bytes = try common.exportDer(format, key, exec) };}log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = format });@@ -412,7 +409,7 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !Jwk {.hmac => try HMAC.jwkAlg(key._algorithm.hash orelse "SHA-", exec),.rsa => return .{ .rsa = try RSA.exportJwk(key, exec) },.ec => return .{ .ec = try EC.exportJwk(key, exec) },- .ed25519 => return .{ .okp = try OKP.exportJwk(key, exec) },+ .ed25519, .x25519 => return .{ .okp = try OKP.exportJwk(key, exec) },else => {log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = "jwk", .type = key._type });return error.NotSupported;@@ -515,17 +512,7 @@ fn deriveRaw(return error.InvalidAccessError;}if (eqlIgnoreCase(params.name, "X25519")) {- // The peer must be an X25519 public key: another key may hold- // no EVP_PKEY at all for X25519.deriveBits to read.- if (params.public._type != .x25519 or params.public._kind != .public) {- return error.InvalidAccessError;- }- // null length means "derive the full shared secret" (256 bits).- const result = X25519.deriveBits(base_key, params.public, length orelse 256, exec) catch |err| switch (err) {- error.OutOfMemory => return error.OutOfMemory,- else => return error.OperationError,- };- return result.values;+ return X25519.deriveBits(base_key, params.public, length, exec);}if (eqlIgnoreCase(params.name, "ECDH")) {return EC.deriveBits(base_key, params.public, length, exec);diff --git a/src/browser/webapi/crypto/EC.zig b/src/browser/webapi/crypto/EC.zigindex 128fc7ad6..f2fb265f2 100644--- a/src/browser/webapi/crypto/EC.zig+++ b/src/browser/webapi/crypto/EC.zig@@ -377,7 +377,7 @@ pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !Jwk {}/// ECDH key agreement: derive `length_in_bits` from `private` + the peer-/// `public`. Mirrors X25519's truncation rules.+/// `public` (common.leadingBits, as X25519).pub fn deriveBits(private: *const CryptoKey,public: *const CryptoKey,@@ -413,19 +413,7 @@ pub fn deriveBits(}// null length means "the full shared secret".- const bits = length_in_bits orelse @as(u32, @intCast(secret_len * 8));- const byte_len = (bits + 7) / 8;- if (byte_len > secret_len) {- return error.OperationError;- }- const out = secret[0..byte_len];-- // Zero the unused trailing bits of the final byte.- const remainder_bits: u3 = @intCast(bits % 8);- if (remainder_bits != 0 and out.len > 0) {- out[out.len - 1] &= ~(@as(u8, 0xFF) >> remainder_bits);- }- return out;+ return common.leadingBits(secret[0..secret_len], length_in_bits);}/// The size in bytes of each of r and s in an ECDSA signature with `ec`: thatdiff --git a/src/browser/webapi/crypto/OKP.zig b/src/browser/webapi/crypto/OKP.zigindex ca5a5eba9..1cc720d3c 100644--- a/src/browser/webapi/crypto/OKP.zig+++ b/src/browser/webapi/crypto/OKP.zig@@ -16,9 +16,11 @@// 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/>.-//! Ed25519 keys (RFC 8032): generate, import and export (raw, spki and pkcs8-//! per RFC 8410, jwk per RFC 8037), and sign / verify. The key material lives-//! as a libcrypto EVP_PKEY in `CryptoKey._vary.pkey`, as for EC and RSA.+//! Octet Key Pair keys, Ed25519 (RFC 8032) and X25519 (RFC 7748): generate,+//! import and export (raw, spki and pkcs8 per RFC 8410, jwk per RFC 8037), and+//! Ed25519's sign / verify (X25519's deriveBits is in X25519.zig). The key+//! material lives as a libcrypto EVP_PKEY in `CryptoKey._vary.pkey`, as for EC+//! and RSA.const std = @import("std");const crypto = @import("../../../sys/libcrypto.zig");@@ -30,18 +32,44 @@ const common = @import("common.zig");const CryptoKey = @import("../CryptoKey.zig");const Execution = js.Execution;-/// An Octet Key Pair algorithm: its name, which is also its JWK `crv`, and-/// how libcrypto knows it.+/// An Octet Key Pair algorithm: its name, which is also its JWK `crv`, how+/// libcrypto knows it, and the usages of each half.pub const Curve = struct {name: []const u8,key_type: CryptoKey.Type,pkey_type: c_int,- /// The size of the public key and of the private seed.+ /// The size of the public key and of the private key.size: usize,+ private_usages: []const []const u8,+ public_usages: []const []const u8,+ /// The JWK `use` its keys are for.+ jwk_use: []const u8,+ /// Whether its JWK carries an `alg`: the algorithm's name on export, that+ /// or "EdDSA" on import. X25519's has none, and ignores one on import.+ jwk_alg: bool,};const curves = [_]Curve{- .{ .name = "Ed25519", .key_type = .ed25519, .pkey_type = crypto.EVP_PKEY_ED25519, .size = 32 },+ .{+ .name = "Ed25519",+ .key_type = .ed25519,+ .pkey_type = crypto.EVP_PKEY_ED25519,+ .size = 32,+ .private_usages = &.{"sign"},+ .public_usages = &.{"verify"},+ .jwk_use = "sig",+ .jwk_alg = true,+ },+ .{+ .name = "X25519",+ .key_type = .x25519,+ .pkey_type = crypto.EVP_PKEY_X25519,+ .size = 32,+ .private_usages = &.{ "deriveKey", "deriveBits" },+ .public_usages = &.{},+ .jwk_use = "enc",+ .jwk_alg = false,+ },};/// The curve an algorithm name refers to, case-insensitively, or null.@@ -52,30 +80,33 @@ pub fn curveOf(name: []const u8) ?*const Curve {return null;}-const private_usages: []const []const u8 = &.{"sign"};-const public_usages: []const []const u8 = &.{"verify"};--/// Generates an Ed25519 key pair: the private key gets the "sign" usage, the-/// public key "verify". Any other usage, or none for the private key, is-/// SyntaxError.+/// Generates a key pair, splitting the usages between its halves (Ed25519's+/// "sign" and "verify"; X25519's "deriveKey" and "deriveBits" go to the+/// private key). Any other usage, or none for the private key, is SyntaxError.pub fn generate(curve: *const Curve, extractable: bool, key_usages: []const []const u8, exec: *const Execution) !js.Promise {const local = exec.js.local.?;for (key_usages) |usage| {- if (!common.usageIn(private_usages, usage) and !common.usageIn(public_usages, usage)) {+ if (!common.usageIn(curve.private_usages, usage) and !common.usageIn(curve.public_usages, usage)) {return error.SyntaxError;}}- const private_mask = common.usageIntersection(private_usages, key_usages);- const public_mask = common.usageIntersection(public_usages, key_usages);+ const private_mask = common.usageIntersection(curve.private_usages, key_usages);+ const public_mask = common.usageIntersection(curve.public_usages, key_usages);if (private_mask == 0) return error.SyntaxError;- var public_key: [crypto.ED25519_PUBLIC_KEY_LEN]u8 = undefined;+ // libcrypto takes an Ed25519 private key as its 32-byte seed, the first+ // half of what ED25519_keypair returns.+ var public_key: [32]u8 = undefined;var private_key: [crypto.ED25519_PRIVATE_KEY_LEN]u8 = undefined;defer std.crypto.secureZero(u8, &private_key);- crypto.ED25519_keypair(&public_key, &private_key);+ switch (curve.key_type) {+ .ed25519 => crypto.ED25519_keypair(&public_key, &private_key),+ .x25519 => crypto.X25519_keypair(&public_key, private_key[0..32]),+ // A curve added to the table without its key pair generation.+ else => return error.NotSupported,+ }- // libcrypto takes the private key as its 32-byte seed.const private_pkey = crypto.EVP_PKEY_new_raw_private_key(curve.pkey_type, null, &private_key, curve.size) orelse return error.OutOfMemory;errdefer crypto.EVP_PKEY_free(private_pkey);const public_pkey = crypto.EVP_PKEY_new_raw_public_key(curve.pkey_type, null, &public_key, public_key.len) orelse return error.OutOfMemory;@@ -136,9 +167,10 @@ pub fn import(}/// Imports a key from a JSON Web Key (RFC 8037): kty "OKP", the common `use`-/// ("sig") / key_ops / ext checks, `crv` naming the curve, an `alg`, if any,-/// of the curve's name or "EdDSA", and `x` (plus `d` for a private key) of the-/// curve's size, `x` being `d`'s public key. Anything else is DataError.+/// ("sig" for Ed25519, "enc" for X25519) / key_ops / ext checks, `crv` naming+/// the curve, for Ed25519 an `alg`, if any, of its name or "EdDSA", and `x`+/// (plus `d` for a private key) of the curve's size, `x` being `d`'s public+/// key. Anything else is DataError.pub fn importJwk(curve: *const Curve,jwk: algorithm.KeyData.Jwk,@@ -149,10 +181,12 @@ pub fn importJwk(const local = exec.js.local.?;if (!std.mem.eql(u8, jwk.kty orelse "", "OKP")) return error.DataError;- try common.checkJwk(jwk, "sig", usages_mask, extractable);+ try common.checkJwk(jwk, curve.jwk_use, usages_mask, extractable);if (!std.mem.eql(u8, jwk.crv orelse "", curve.name)) return error.DataError;- if (jwk.alg) |alg| {- if (!std.mem.eql(u8, alg, curve.name) and !std.mem.eql(u8, alg, "EdDSA")) return error.DataError;+ if (curve.jwk_alg) {+ if (jwk.alg) |alg| {+ if (!std.mem.eql(u8, alg, curve.name) and !std.mem.eql(u8, alg, "EdDSA")) return error.DataError;+ }}const x = try common.jwkBytes(exec.local_arena, jwk.x, curve.size);@@ -216,9 +250,9 @@ pub fn exportRaw(key: *const CryptoKey, exec: *const Execution) ![]const u8 {}/// The JWK of an OKP key (RFC 8037). Members are listed in lexicographic-/// order, the order browsers return a JsonWebKey in; `alg` is the algorithm's-/// name.-const JwkPublic = struct {+/// order, the order browsers return a JsonWebKey in. Ed25519's carries an+/// `alg`, its name; X25519's doesn't.+const SigningPublic = struct {alg: []const u8,crv: []const u8,ext: bool,@@ -227,7 +261,7 @@ const JwkPublic = struct {x: []const u8,};-const JwkPrivate = struct {+const SigningPrivate = struct {alg: []const u8,crv: []const u8,d: []const u8,@@ -237,35 +271,55 @@ const JwkPrivate = struct {x: []const u8,};-/// The JWK of either half of an OKP key.+const AgreementPublic = struct {+ crv: []const u8,+ ext: bool,+ key_ops: []const []const u8,+ kty: []const u8 = "OKP",+ x: []const u8,+};++const AgreementPrivate = struct {+ crv: []const u8,+ d: []const u8,+ ext: bool,+ key_ops: []const []const u8,+ kty: []const u8 = "OKP",+ x: []const u8,+};++/// The JWK of either half of an Ed25519 or X25519 key.pub const Jwk = union(enum) {- public: JwkPublic,- private: JwkPrivate,+ signing_public: SigningPublic,+ signing_private: SigningPrivate,+ agreement_public: AgreementPublic,+ agreement_private: AgreementPrivate,};/// Exports a key as a JWK: `x` for either half, plus `d` for the private key.pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !Jwk {- const name = key._algorithm.name;+ const curve = curveOf(key._algorithm.name) orelse return error.OperationError;const pkey = key.getKeyObject();const x = try common.base64Encode(exec.local_arena, try rawPublic(pkey, exec));const key_ops = try key.getUsages(exec);+ const ext = key._extractable;if (key._kind == .public) {- return .{ .public = .{ .alg = name, .crv = name, .ext = key._extractable, .key_ops = key_ops, .x = x } };+ if (curve.jwk_alg) {+ return .{ .signing_public = .{ .alg = curve.name, .crv = curve.name, .ext = ext, .key_ops = key_ops, .x = x } };+ }+ return .{ .agreement_public = .{ .crv = curve.name, .ext = ext, .key_ops = key_ops, .x = x } };}var len: usize = 0;if (crypto.EVP_PKEY_get_raw_private_key(pkey, null, &len) != 1) return error.OperationError;- const seed = try exec.local_arena.alloc(u8, len);- defer std.crypto.secureZero(u8, seed);- if (crypto.EVP_PKEY_get_raw_private_key(pkey, seed.ptr, &len) != 1) return error.OperationError;- return .{ .private = .{- .alg = name,- .crv = name,- .d = try common.base64Encode(exec.local_arena, seed[0..len]),- .ext = key._extractable,- .key_ops = key_ops,- .x = x,- } };+ const private = try exec.local_arena.alloc(u8, len);+ defer std.crypto.secureZero(u8, private);+ if (crypto.EVP_PKEY_get_raw_private_key(pkey, private.ptr, &len) != 1) return error.OperationError;+ const d = try common.base64Encode(exec.local_arena, private[0..len]);+ if (curve.jwk_alg) {+ return .{ .signing_private = .{ .alg = curve.name, .crv = curve.name, .d = d, .ext = ext, .key_ops = key_ops, .x = x } };+ }+ return .{ .agreement_private = .{ .crv = curve.name, .d = d, .ext = ext, .key_ops = key_ops, .x = x } };}/// Signs `data` with a private key (pure Ed25519, no prehash).diff --git a/src/browser/webapi/crypto/X25519.zig b/src/browser/webapi/crypto/X25519.zigindex 8ada52939..ee19d437a 100644--- a/src/browser/webapi/crypto/X25519.zig+++ b/src/browser/webapi/crypto/X25519.zig@@ -16,148 +16,45 @@// 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/>.-//! Interprets `CryptoKey` for X25519.+//! X25519's deriveBits. Its keys are generated, imported and exported in+//! OKP.zig.-const std = @import("std");-const lp = @import("lightpanda");const crypto = @import("../../../sys/libcrypto.zig");const js = @import("../../js/js.zig");const CryptoKey = @import("../CryptoKey.zig");+const common = @import("common.zig");const Execution = js.Execution;-pub fn init(- extractable: bool,- key_usages: []const []const u8,- exec: *const Execution,-) !js.Promise {- // This code has too many allocations here and there, might be nice to- // gather them together with a single alloc call. Not sure if factory- // pattern is suitable for it though.-- const local = exec.js.local.?;-- // Calculate usages; only matters for private key.- // Only deriveKey() and deriveBits() be used for X25519.- if (key_usages.len == 0) {- return error.SyntaxError;- }- var mask: u8 = 0;- iter_usages: for (key_usages) |usage| {- inline for ([_][]const u8{ "deriveKey", "deriveBits" }) |name| {- if (std.mem.eql(u8, name, usage)) {- mask |= @field(CryptoKey.Usages, name);- continue :iter_usages;- }- }- // Unknown usage if got here.- return error.SyntaxError;- }-- const public_value = try exec.local_arena.alloc(u8, crypto.X25519_PUBLIC_VALUE_LEN);- const private_key = try exec.local_arena.alloc(u8, crypto.X25519_PRIVATE_KEY_LEN);-- // There's no info about whether this can fail; so I assume it cannot.- crypto.X25519_keypair(@ptrCast(public_value), @ptrCast(private_key));-- // Create EVP_PKEY for public key.- // Seems we can use `EVP_PKEY_from_raw_private_key` for this, Chrome- // prefer not to, yet BoringSSL added it and recommends instead of what- // we're doing currently.- const public_pkey = crypto.EVP_PKEY_new_raw_public_key(- crypto.EVP_PKEY_X25519,- null,- public_value.ptr,- public_value.len,- ) orelse return error.OutOfMemory;-- // Create EVP_PKEY for private key.- // Seems we can use `EVP_PKEY_from_raw_private_key` for this, Chrome- // prefer not to, yet BoringSSL added it and recommends instead of what- // we're doing currently.- const private_pkey = crypto.EVP_PKEY_new_raw_private_key(- crypto.EVP_PKEY_X25519,- null,- private_key.ptr,- private_key.len,- ) orelse return error.OutOfMemory;-- const private = try CryptoKey.init(exec, .{- ._type = .x25519,- ._kind = .private,- ._extractable = extractable,- ._usages = mask,- ._key = private_key,- ._algorithm = .{ .name = "X25519" },- ._vary = .{ .pkey = private_pkey },- });-- const public = try CryptoKey.init(exec, .{- ._type = .x25519,- ._kind = .public,- // Public keys are always extractable.- ._extractable = true,- // Always empty for public key.- ._usages = 0,- ._key = public_value,- ._algorithm = .{ .name = "X25519" },- ._vary = .{ .pkey = public_pkey },- });-- return local.resolvePromise(CryptoKey.Pair{ .privateKey = private, .publicKey = public });-}-+/// X25519 key agreement (RFC 7748): the shared secret of `private` and the+/// peer `public`, cut to `length_in_bits` (all 256 bits when null). The peer+/// must be an X25519 public key, else InvalidAccessError. An all-zero secret+/// (a peer of small order, which libcrypto refuses) or a length beyond the+/// secret is OperationError.pub fn deriveBits(private: *const CryptoKey,public: *const CryptoKey,- length_in_bits: usize,+ length_in_bits: ?u32,exec: *const Execution,-) !js.ArrayBuffer {- const ctx = crypto.EVP_PKEY_CTX_new(private.getKeyObject(), null) orelse {- // Failed on our end.- return error.Internal;- };- // Context is valid, free it on failure.- errdefer crypto.EVP_PKEY_CTX_free(ctx);-- // Init derive operation and set public key as peer.- if (crypto.EVP_PKEY_derive_init(ctx) != 1 or- crypto.EVP_PKEY_derive_set_peer(ctx, public.getKeyObject()) != 1)- {- // Failed on our end.- return error.Internal;+) error{ InvalidAccessError, OperationError, OutOfMemory }![]const u8 {+ if (public._type != .x25519 or public._kind != .public) {+ return error.InvalidAccessError;}- const derived_key = try exec.local_arena.alloc(u8, 32);- errdefer exec.local_arena.free(derived_key);-- var out_key_len: usize = derived_key.len;- const result = crypto.EVP_PKEY_derive(ctx, derived_key.ptr, &out_key_len);- if (result != 1) {- // Failed on our end.- return error.Internal;+ const ctx = crypto.EVP_PKEY_CTX_new(private.getKeyObject(), null) orelse return error.OutOfMemory;+ defer crypto.EVP_PKEY_CTX_free(ctx);+ if (crypto.EVP_PKEY_derive_init(ctx) != 1 or crypto.EVP_PKEY_derive_set_peer(ctx, public.getKeyObject()) != 1) {+ crypto.ERR_clear_error();+ return error.OperationError;}- // Sanity check.- lp.assert(derived_key.len == out_key_len, "X25519.deriveBits", .{});- // Length is in bits, convert to byte length.- const length = (length_in_bits / 8) + (7 + (length_in_bits % 8)) / 8;- // Truncate the slice to specified length.- // Same as `derived_key`.- const tailored = blk: {- if (length > derived_key.len) {- return error.LengthTooLong;- }- break :blk derived_key[0..length];- };-- // Zero any "unused bits" in the final byte.- const remainder_bits: u3 = @intCast(length_in_bits % 8);- if (remainder_bits != 0) {- tailored[tailored.len - 1] &= ~(@as(u8, 0xFF) >> remainder_bits);+ const secret = try exec.local_arena.alloc(u8, 32);+ var secret_len: usize = secret.len;+ if (crypto.EVP_PKEY_derive(ctx, secret.ptr, &secret_len) != 1 or secret_len != secret.len) {+ crypto.ERR_clear_error();+ return error.OperationError;}-- return js.ArrayBuffer{ .values = tailored };+ return common.leadingBits(secret, length_in_bits);}diff --git a/src/browser/webapi/crypto/common.zig b/src/browser/webapi/crypto/common.zigindex 286a2dfb9..0398b8748 100644--- a/src/browser/webapi/crypto/common.zig+++ b/src/browser/webapi/crypto/common.zig@@ -140,6 +140,23 @@ pub fn checkJwk(}}+/// The first `length_in_bits` bits of a derived `secret`, all of it when null:+/// whole bytes, with the unused low bits of a partial last byte zeroed. A+/// length beyond the secret is OperationError.+pub fn leadingBits(secret: []u8, length_in_bits: ?u32) error{OperationError}![]u8 {+ const bits = length_in_bits orelse return secret;+ const byte_len = (@as(usize, bits) + 7) / 8;+ if (byte_len > secret.len) {+ return error.OperationError;+ }+ const out = secret[0..byte_len];+ const remainder_bits: u3 = @intCast(bits % 8);+ if (remainder_bits != 0) {+ out[out.len - 1] &= ~(@as(u8, 0xFF) >> remainder_bits);+ }+ return out;+}+/// A JWK key member (a coordinate, `x`, `d`, ...): base64url of exactly `n`/// bytes. A missing member or one of another size is DataError.pub fn jwkBytes(allocator: Allocator, member: ?[]const u8, n: usize) error{ OutOfMemory, DataError }![]u8 {