Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: X25519 deriveBits checks its peer key

orezraey10f96a5eee64
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 09124def6..e665dbaa1 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -2165,6 +2165,43 @@
});
</script>
+<script id=x25519-peer-check 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 x25519 = await subtle.generateKey("X25519", false, ["deriveBits"]);
+ const aes = await subtle.generateKey({ name: "AES-GCM", length: 128 }, false, ["encrypt"]);
+ const hmac = await subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ const ecdh = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
+ const derive = (peer) => subtle.deriveBits({ name: "X25519", public: peer }, x25519.privateKey, 256);
+
+ // The peer must be an X25519 public key. An AES or HMAC key, which holds
+ // no EVP_PKEY, used to crash here.
+ const results = {
+ aes: await errorName(() => derive(aes)),
+ hmac: await errorName(() => derive(hmac)),
+ ecdh: await errorName(() => derive(ecdh.publicKey)),
+ privateKey: await errorName(() => derive(x25519.privateKey)),
+ publicKey: (await derive(x25519.publicKey)).byteLength,
+ };
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("InvalidAccessError", results.aes);
+ testing.expectEqual("InvalidAccessError", results.hmac);
+ testing.expectEqual("InvalidAccessError", results.ecdh);
+ testing.expectEqual("InvalidAccessError", results.privateKey);
+ testing.expectEqual(32, results.publicKey);
+ });
+</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.zig
index 0ae11f1a4..f48892184 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -515,6 +515,11 @@ 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,