Truly independent web browser
LibCrypto: Hold EC keys as OpenSSL keys
Shannon Boothb5f823191c40
diff --git a/Libraries/LibCrypto/ASN1/DER.h b/Libraries/LibCrypto/ASN1/DER.hindex c82db1f498e..ee30d5ced5a 100644--- a/Libraries/LibCrypto/ASN1/DER.h+++ b/Libraries/LibCrypto/ASN1/DER.h@@ -6,11 +6,35 @@#pragma once+#include <AK/Array.h>+#include <AK/String.h>#include <AK/Types.h>#include <AK/Vector.h>#include <LibCrypto/ASN1/ASN1.h>#include <LibCrypto/BigInt/UnsignedBigInteger.h>+namespace {++// Used by ASN1 macros, whose errors are views of it. It keeps the text of the last error of a thread, cut to fit.+// NB: Not a String, so that it needs no destructor and a thread that ends leaves nothing behind.+struct ASN1ErrorString {+ ASN1ErrorString& operator=(String const& text)+ {+ m_length = min(text.bytes().size(), m_buffer.size());+ text.bytes().trim(m_length).copy_to(m_buffer);+ return *this;+ }++ StringView bytes_as_string_view() const { return StringView { m_buffer.span().trim(m_length) }; }++ Array<u8, 512> m_buffer {};+ size_t m_length { 0 };+};++static thread_local ASN1ErrorString s_error_string;++}+namespace Crypto::ASN1 {using ObjectIdentifier = Vector<u32, 12>;diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txtindex b1c969bea93..32dc6c4d025 100644--- a/Libraries/LibCrypto/CMakeLists.txt+++ b/Libraries/LibCrypto/CMakeLists.txt@@ -13,7 +13,6 @@ set(SOURCESCipher/AES.cppCipher/ChaCha.cppCurves/EdwardsCurve.cpp- Curves/SECPxxxr1.cppHash/Argon2.cppHash/Hash.cppHash/SHAKE.cppdiff --git a/Libraries/LibCrypto/Certificate/Certificate.cpp b/Libraries/LibCrypto/Certificate/Certificate.cppindex 4e462c01c32..0e6510f428b 100644--- a/Libraries/LibCrypto/Certificate/Certificate.cpp+++ b/Libraries/LibCrypto/Certificate/Certificate.cpp@@ -7,6 +7,7 @@#include <AK/ByteBuffer.h>#include <LibCrypto/ASN1/ASN1.h>+#include <LibCrypto/ASN1/Constants.h>#include <LibCrypto/ASN1/DER.h>#include <LibCrypto/Certificate/Certificate.h>#include <LibCrypto/PK/EC.h>diff --git a/Libraries/LibCrypto/Curves/SECPxxxr1.cpp b/Libraries/LibCrypto/Curves/SECPxxxr1.cppdeleted file mode 100644index a37962ee341..00000000000--- a/Libraries/LibCrypto/Curves/SECPxxxr1.cpp+++ /dev/null@@ -1,265 +0,0 @@-/*- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Curves/SECPxxxr1.h>-#include <LibCrypto/OpenSSL.h>--#include <openssl/core_names.h>-#include <openssl/ec.h>-#include <openssl/evp.h>-#include <openssl/param_build.h>--namespace Crypto::Curves {--static char const* curve_name_for_scalar_size(size_t scalar_size)-{- switch (scalar_size) {- case 32:- return "P-256";- case 48:- return "P-384";- case 66:- return "P-521";- default:- return nullptr;- }-}--ErrorOr<SECPxxxr1Point> SECPxxxr1Point::from_compressed(ReadonlyBytes data)-{- if (data.size() < 2 || (data[0] != 0x02 && data[0] != 0x03))- return Error::from_string_literal("Invalid compressed EC point");-- auto scalar_size = data.size() - 1;- auto const* curve = curve_name_for_scalar_size(scalar_size);- if (!curve)- return Error::from_string_literal("Unsupported curve for compressed EC point");-- auto* group = OPENSSL_TRY_PTR(EC_GROUP_new_by_curve_name(EC_curve_nist2nid(curve)));- ScopeGuard const free_group = [&] { EC_GROUP_free(group); };-- auto* point = OPENSSL_TRY_PTR(EC_POINT_new(group));- ScopeGuard const free_point = [&] { EC_POINT_free(point); };-- OPENSSL_TRY(EC_POINT_oct2point(group, point, data.data(), data.size(), nullptr));-- auto x = TRY(OpenSSL_BN::create());- auto y = TRY(OpenSSL_BN::create());- OPENSSL_TRY(EC_POINT_get_affine_coordinates(group, point, x.ptr(), y.ptr(), nullptr));-- return SECPxxxr1Point {- TRY(openssl_bignum_to_unsigned_big_integer(x)),- TRY(openssl_bignum_to_unsigned_big_integer(y)),- scalar_size,- };-}--ErrorOr<UnsignedBigInteger> SECPxxxr1::generate_private_key()-{- auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_Q_keygen(nullptr, nullptr, "EC", m_curve_name)));-- auto priv_bn = TRY(OpenSSL_BN::create());- auto* priv_bn_ptr = priv_bn.ptr();- OPENSSL_TRY(EVP_PKEY_get_bn_param(key.ptr(), OSSL_PKEY_PARAM_PRIV_KEY, &priv_bn_ptr));-- return TRY(openssl_bignum_to_unsigned_big_integer(priv_bn));-}--ErrorOr<SECPxxxr1Point> SECPxxxr1::generate_public_key(UnsignedBigInteger scalar)-{- auto* group = EC_GROUP_new_by_curve_name(EC_curve_nist2nid(m_curve_name));- ScopeGuard const free_group = [&] { EC_GROUP_free(group); };-- auto scalar_int = TRY(unsigned_big_integer_to_openssl_bignum(scalar));-- auto* r = EC_POINT_new(group);- ScopeGuard const free_r = [&] { EC_POINT_free(r); };-- OPENSSL_TRY(EC_POINT_mul(group, r, scalar_int.ptr(), nullptr, nullptr, nullptr));-- auto x = TRY(OpenSSL_BN::create());- auto y = TRY(OpenSSL_BN::create());-- OPENSSL_TRY(EC_POINT_get_affine_coordinates(group, r, x.ptr(), y.ptr(), nullptr));-- return SECPxxxr1Point {- TRY(openssl_bignum_to_unsigned_big_integer(x)),- TRY(openssl_bignum_to_unsigned_big_integer(y)),- m_scalar_size,- };-}--ErrorOr<SECPxxxr1Point> SECPxxxr1::compute_coordinate(UnsignedBigInteger scalar, SECPxxxr1Point point)-{- if (point.size != m_scalar_size)- return Error::from_string_literal("Invalid point size for curve");-- auto* group = EC_GROUP_new_by_curve_name(EC_curve_nist2nid(m_curve_name));- ScopeGuard const free_group = [&] { EC_GROUP_free(group); };-- auto scalar_int = TRY(unsigned_big_integer_to_openssl_bignum(scalar));-- auto qx = TRY(unsigned_big_integer_to_openssl_bignum(point.x));- auto qy = TRY(unsigned_big_integer_to_openssl_bignum(point.y));-- auto* q = EC_POINT_new(group);- ScopeGuard const free_q = [&] { EC_POINT_free(q); };-- OPENSSL_TRY(EC_POINT_set_affine_coordinates(group, q, qx.ptr(), qy.ptr(), nullptr));-- auto* r = EC_POINT_new(group);- ScopeGuard const free_r = [&] { EC_POINT_free(r); };-- OPENSSL_TRY(EC_POINT_mul(group, r, nullptr, q, scalar_int.ptr(), nullptr));-- auto rx = TRY(OpenSSL_BN::create());- auto ry = TRY(OpenSSL_BN::create());-- OPENSSL_TRY(EC_POINT_get_affine_coordinates(group, r, rx.ptr(), ry.ptr(), nullptr));-- return SECPxxxr1Point {- TRY(openssl_bignum_to_unsigned_big_integer(rx)),- TRY(openssl_bignum_to_unsigned_big_integer(ry)),- m_scalar_size,- };-}--ErrorOr<bool> SECPxxxr1::verify(ReadonlyBytes hash, SECPxxxr1Point pubkey, SECPxxxr1Signature signature)-{- if (signature.size != m_scalar_size)- return false;-- auto ctx_import = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr)));-- OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx_import.ptr()));-- auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());- ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); };-- OPENSSL_TRY(OSSL_PARAM_BLD_push_utf8_string(params_bld, OSSL_PKEY_PARAM_GROUP_NAME, m_curve_name, strlen(m_curve_name)));-- auto pubkey_bytes = TRY(pubkey.to_uncompressed());- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_PUB_KEY, pubkey_bytes.data(), pubkey_bytes.size()));-- auto* params = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_to_param(params_bld));- ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };-- auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new()));- auto* key_ptr = key.ptr();- OPENSSL_TRY(EVP_PKEY_fromdata(ctx_import.ptr(), &key_ptr, EVP_PKEY_PUBLIC_KEY, params));-- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.ptr(), nullptr)));-- OPENSSL_TRY(EVP_PKEY_verify_init(ctx.ptr()));-- auto* sig_obj = OPENSSL_TRY_PTR(ECDSA_SIG_new());- ScopeGuard const free_sig_obj = [&] { ECDSA_SIG_free(sig_obj); };-- auto r = TRY(unsigned_big_integer_to_openssl_bignum(signature.r));- auto s = TRY(unsigned_big_integer_to_openssl_bignum(signature.s));-- // Let sig_obj own a copy of r and s- OPENSSL_TRY(ECDSA_SIG_set0(sig_obj, BN_dup(r.ptr()), BN_dup(s.ptr())));-- u8* sig = nullptr;- ScopeGuard const free_sig = [&] { OPENSSL_free(sig); };-- auto sig_len = TRY([&] -> ErrorOr<int> {- auto ret = i2d_ECDSA_SIG(sig_obj, &sig);- if (ret <= 0) {- OPENSSL_TRY(ret);- VERIFY_NOT_REACHED();- }- return ret;- }());-- auto ret = EVP_PKEY_verify(ctx.ptr(), sig, sig_len, hash.data(), hash.size());- if (ret == 1)- return true;- if (ret == 0)- return false;- OPENSSL_TRY(ret);- VERIFY_NOT_REACHED();-}--ErrorOr<SECPxxxr1Signature> SECPxxxr1::sign(ReadonlyBytes hash, UnsignedBigInteger private_key)-{- auto ctx_import = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr)));-- OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx_import.ptr()));-- auto d = TRY(unsigned_big_integer_to_openssl_bignum(private_key));-- auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());- ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); };-- OPENSSL_TRY(OSSL_PARAM_BLD_push_utf8_string(params_bld, OSSL_PKEY_PARAM_GROUP_NAME, m_curve_name, strlen(m_curve_name)));- OPENSSL_TRY(OSSL_PARAM_BLD_push_BN(params_bld, OSSL_PKEY_PARAM_PRIV_KEY, d.ptr()));-- auto* params = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_to_param(params_bld));- ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };-- auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new()));- auto* key_ptr = key.ptr();- OPENSSL_TRY(EVP_PKEY_fromdata(ctx_import.ptr(), &key_ptr, EVP_PKEY_KEYPAIR, params));-- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.ptr(), nullptr)));-- OPENSSL_TRY(EVP_PKEY_sign_init(ctx.ptr()));-- size_t sig_len = 0;- OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), nullptr, &sig_len, hash.data(), hash.size()));-- auto sig = TRY(ByteBuffer::create_uninitialized(sig_len));- OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), sig.data(), &sig_len, hash.data(), hash.size()));-- auto const* sig_data = sig.data();- auto* sig_obj = OPENSSL_TRY_PTR(d2i_ECDSA_SIG(nullptr, &sig_data, sig.size()));- ScopeGuard const free_sig_obj = [&] { ECDSA_SIG_free(sig_obj); };-- // Duplicate r and s so that sig_obj can own them- auto r = TRY(OpenSSL_BN::wrap(BN_dup(OPENSSL_TRY_PTR(ECDSA_SIG_get0_r(sig_obj)))));- auto s = TRY(OpenSSL_BN::wrap(BN_dup(OPENSSL_TRY_PTR(ECDSA_SIG_get0_s(sig_obj)))));-- return SECPxxxr1Signature {- TRY(openssl_bignum_to_unsigned_big_integer(r)),- TRY(openssl_bignum_to_unsigned_big_integer(s)),- m_scalar_size,- };-}--ErrorOr<bool> SECPxxxr1::is_valid_point(SECPxxxr1Point pubkey, Optional<UnsignedBigInteger> private_key)-{- if (pubkey.size != m_scalar_size)- return false;-- auto* group = OPENSSL_TRY_PTR(EC_GROUP_new_by_curve_name(EC_curve_nist2nid(m_curve_name)));- ScopeGuard const free_group = [&] { EC_GROUP_free(group); };-- auto x = TRY(unsigned_big_integer_to_openssl_bignum(pubkey.x));- auto y = TRY(unsigned_big_integer_to_openssl_bignum(pubkey.y));-- auto* point = OPENSSL_TRY_PTR(EC_POINT_new(group));- ScopeGuard const free_point = [&] { EC_POINT_free(point); };-- // Check public point is on the curve, EC_POINT_set_affine_coordinates calls EC_POINT_is_on_curve internally- if (EC_POINT_set_affine_coordinates(group, point, x.ptr(), y.ptr(), nullptr) != 1)- return false;-- if (!private_key.has_value())- return true;-- // Check that the public key is a valid point for the given private key- auto private_key_int = TRY(unsigned_big_integer_to_openssl_bignum(*private_key));-- auto* expected_point = EC_POINT_new(group);- ScopeGuard const free_expected_point = [&] { EC_POINT_free(expected_point); };-- OPENSSL_TRY(EC_POINT_mul(group, expected_point, private_key_int.ptr(), nullptr, nullptr, nullptr));- return EC_POINT_cmp(group, expected_point, point, nullptr) == 0;-}--}diff --git a/Libraries/LibCrypto/Curves/SECPxxxr1.h b/Libraries/LibCrypto/Curves/SECPxxxr1.hdeleted file mode 100644index 4ed1d54a7d2..00000000000--- a/Libraries/LibCrypto/Curves/SECPxxxr1.h+++ /dev/null@@ -1,164 +0,0 @@-/*- * Copyright (c) 2023, Michiel Visser <[email protected]>- * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Array.h>-#include <AK/ByteBuffer.h>-#include <AK/String.h>-#include <AK/StringView.h>-#include <LibCrypto/ASN1/Constants.h>-#include <LibCrypto/ASN1/DER.h>--namespace {--// Used by ASN1 macros, whose errors are views of it. It keeps the text of the last error of a thread, cut to fit.-// NB: Not a String, so that it needs no destructor and a thread that ends leaves nothing behind.-struct ASN1ErrorString {- ASN1ErrorString& operator=(String const& text)- {- m_length = min(text.bytes().size(), m_buffer.size());- text.bytes().trim(m_length).copy_to(m_buffer);- return *this;- }-- StringView bytes_as_string_view() const { return StringView { m_buffer.span().trim(m_length) }; }-- Array<u8, 512> m_buffer {};- size_t m_length { 0 };-};--static thread_local ASN1ErrorString s_error_string;--}--namespace Crypto::Curves {--struct SECPxxxr1Point {- UnsignedBigInteger x;- UnsignedBigInteger y;- size_t size;-- static ErrorOr<ByteBuffer> scalar_to_bytes(UnsignedBigInteger const& a, size_t size)- {- auto a_bytes = TRY(ByteBuffer::create_uninitialized(a.byte_length()));- auto a_result = a.export_data(a_bytes.span());-- if (a_result.size() > size)- return Error::from_string_literal("Scalar is too large for the given size");-- if (a_result.size() == size)- return a_bytes;-- auto a_extended_bytes = TRY(ByteBuffer::create_zeroed(size));- a_extended_bytes.overwrite(size - a_result.size(), a_result.data(), a_result.size());- return a_extended_bytes;- }-- static ErrorOr<SECPxxxr1Point> from_uncompressed(ReadonlyBytes data)- {- if (data.size() < 3 || data[0] != 0x04)- return Error::from_string_literal("Invalid length or not an uncompressed SECPxxxr1 point");-- auto half_size = (data.size() - 1) / 2;- if (1 + half_size * 2 != data.size())- return Error::from_string_literal("Invalid uncompressed SECPxxxr1 point length");-- return SECPxxxr1Point {- UnsignedBigInteger::import_data(data.slice(1, half_size)),- UnsignedBigInteger::import_data(data.slice(1 + half_size, half_size)),- half_size,- };- }-- static ErrorOr<SECPxxxr1Point> from_compressed(ReadonlyBytes data);-- ErrorOr<ByteBuffer> x_bytes() const- {- return scalar_to_bytes(x, size);- }-- ErrorOr<ByteBuffer> y_bytes() const- {- return scalar_to_bytes(y, size);- }-- ErrorOr<ByteBuffer> to_uncompressed() const- {- auto x = TRY(x_bytes());- auto y = TRY(y_bytes());-- auto bytes = TRY(ByteBuffer::create_uninitialized(1 + (size * 2)));- bytes[0] = 0x04; // uncompressed- bytes.overwrite(1, x.data(), size);- bytes.overwrite(1 + size, y.data(), size);- return bytes;- }-};--struct SECPxxxr1Signature {- UnsignedBigInteger r;- UnsignedBigInteger s;- size_t size;-- ErrorOr<ByteBuffer> r_bytes() const- {- return SECPxxxr1Point::scalar_to_bytes(r, size);- }-- ErrorOr<ByteBuffer> s_bytes() const- {- return SECPxxxr1Point::scalar_to_bytes(s, size);- }-};--class SECPxxxr1 {-public:- ErrorOr<UnsignedBigInteger> generate_private_key();- ErrorOr<SECPxxxr1Point> generate_public_key(UnsignedBigInteger scalar);- ErrorOr<SECPxxxr1Point> compute_coordinate(UnsignedBigInteger scalar, SECPxxxr1Point point);- ErrorOr<bool> verify(ReadonlyBytes hash, SECPxxxr1Point pubkey, SECPxxxr1Signature signature);- ErrorOr<SECPxxxr1Signature> sign(ReadonlyBytes hash, UnsignedBigInteger private_key);- ErrorOr<bool> is_valid_point(SECPxxxr1Point pubkey, Optional<UnsignedBigInteger> private_key = {});--protected:- SECPxxxr1(char const* curve_name, size_t scalar_size)- : m_curve_name(curve_name)- , m_scalar_size(scalar_size)- {- }--private:- char const* m_curve_name;- size_t m_scalar_size;-};--class SECP256r1 : public SECPxxxr1 {-public:- SECP256r1()- : SECPxxxr1("P-256", 32)- {- }-};--class SECP384r1 : public SECPxxxr1 {-public:- SECP384r1()- : SECPxxxr1("P-384", 48)- {- }-};--class SECP521r1 : public SECPxxxr1 {-public:- SECP521r1()- : SECPxxxr1("P-521", 66)- {- }-};--}diff --git a/Libraries/LibCrypto/KeyHandle.cpp b/Libraries/LibCrypto/KeyHandle.cppindex c1d5e038a38..6cde161809b 100644--- a/Libraries/LibCrypto/KeyHandle.cpp+++ b/Libraries/LibCrypto/KeyHandle.cpp@@ -21,6 +21,13 @@ struct CryptoKeyHandleFields {bool has_ec_public_key { false };};+// NB: libcrypto_rust passes these values across the FFI.+enum class KeyDecodeResult : u8 {+ Decoded,+ InvalidComponents,+ OutOfMemory,+};+extern "C" {void crypto_key_destroy_handle(KeyHandle*);KeyHandle* crypto_key_create_byte_handle(ReadonlyBytes);@@ -28,7 +35,7 @@ KeyHandle* crypto_key_create_okp_handle(bool, ReadonlyBytes);void crypto_key_okp_handle_bytes(KeyHandle const*, ReadonlyBytes*);void crypto_key_byte_handle_bytes(KeyHandle const*, ReadonlyBytes*);void crypto_key_encode_handle(KeyHandle const*, void*, void (*)(void*, CryptoKeyHandleFields const*));-bool crypto_key_decode_handle(CryptoKeyHandleFields const*, KeyHandle**);+KeyDecodeResult crypto_key_decode_handle(CryptoKeyHandleFields const*, KeyHandle**);}void crypto_key_destroy_handle(KeyHandle* handle)@@ -38,7 +45,6 @@ void crypto_key_destroy_handle(KeyHandle* handle)[](OKPPublicKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },[](OKPPrivateKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },[](::Crypto::PK::RSAPrivateKey& data) { data.clear_sensitive_data(); },- [](::Crypto::PK::ECPrivateKey& data) { data.clear_sensitive_data(); },[](::Crypto::PK::MLDSAPrivateKey& data) { data.clear_sensitive_data(); },[](::Crypto::PK::MLKEMPrivateKey& data) { data.clear_sensitive_data(); },[](auto&) { });@@ -184,7 +190,7 @@ static ErrorOr<KeyHandle> handle_from_fields(CryptoKeyHandleFields const& fieldscase HandleTag::RSAPrivateKey:return ::Crypto::PK::RSAPrivateKey { big_integer(0), big_integer(1), big_integer(2), big_integer(3), big_integer(4), big_integer(5), big_integer(6), big_integer(7) };case HandleTag::ECPublicKey:- return ::Crypto::PK::ECPublicKey { big_integer(0), big_integer(1), buffer(0).size() };+ return TRY(::Crypto::PK::ECPublicKey::from_coordinates(buffer(0), buffer(1)));case HandleTag::ECPrivateKey: {Optional<::Crypto::ASN1::ObjectIdentifier> parameters;if (fields.has_ec_parameters) {@@ -194,8 +200,8 @@ static ErrorOr<KeyHandle> handle_from_fields(CryptoKeyHandleFields const& fields}Optional<::Crypto::PK::ECPublicKey> public_key;if (fields.has_ec_public_key)- public_key = ::Crypto::PK::ECPublicKey { big_integer(1), big_integer(2), buffer(1).size() };- return ::Crypto::PK::ECPrivateKey { big_integer(0), buffer(0).size(), move(parameters), move(public_key) };+ public_key = TRY(::Crypto::PK::ECPublicKey::from_coordinates(buffer(1), buffer(2)));+ return TRY(::Crypto::PK::ECPrivateKey::from_scalar(buffer(0), move(parameters), move(public_key)));}case HandleTag::MLDSAPublicKey:return ::Crypto::PK::MLDSAPublicKey { TRY(copy(0)) };@@ -213,13 +219,17 @@ static ErrorOr<KeyHandle> handle_from_fields(CryptoKeyHandleFields const& fieldsVERIFY_NOT_REACHED();}-bool crypto_key_decode_handle(CryptoKeyHandleFields const* fields, KeyHandle** out_handle)+KeyDecodeResult crypto_key_decode_handle(CryptoKeyHandleFields const* fields, KeyHandle** out_handle){auto handle = handle_from_fields(*fields);- if (handle.is_error())- return false;+ if (handle.is_error()) {+ // NB: An allocation fails with ENOMEM. Any other error is a component that does not make a valid key.+ if (handle.error().is_errno() && handle.error().code() == ENOMEM)+ return KeyDecodeResult::OutOfMemory;+ return KeyDecodeResult::InvalidComponents;+ }*out_handle = new KeyHandle(handle.release_value());- return true;+ return KeyDecodeResult::Decoded;}}diff --git a/Libraries/LibCrypto/OpenSSL.cpp b/Libraries/LibCrypto/OpenSSL.cppindex dd3ff05e3fe..632d592f7d9 100644--- a/Libraries/LibCrypto/OpenSSL.cpp+++ b/Libraries/LibCrypto/OpenSSL.cpp@@ -22,6 +22,42 @@ ErrorOr<OpenSSL_PKEY> OpenSSL_PKEY::create()return OpenSSL_PKEY(OPENSSL_TRY_PTR(EVP_PKEY_new()));}+OpenSSL_SharedPKEY::OpenSSL_SharedPKEY(OpenSSL_PKEY&& key)+ : m_ptr(key.leak_ptr())+{+}++OpenSSL_SharedPKEY::OpenSSL_SharedPKEY(OpenSSL_SharedPKEY const& other)+ : m_ptr(other.m_ptr)+{+ if (m_ptr)+ VERIFY(EVP_PKEY_up_ref(m_ptr) == 1);+}++OpenSSL_SharedPKEY::OpenSSL_SharedPKEY(OpenSSL_SharedPKEY&& other)+ : m_ptr(exchange(other.m_ptr, nullptr))+{+}++OpenSSL_SharedPKEY& OpenSSL_SharedPKEY::operator=(OpenSSL_SharedPKEY const& other)+{+ OpenSSL_SharedPKEY copy(other);+ swap(m_ptr, copy.m_ptr);+ return *this;+}++OpenSSL_SharedPKEY& OpenSSL_SharedPKEY::operator=(OpenSSL_SharedPKEY&& other)+{+ OpenSSL_SharedPKEY moved(move(other));+ swap(m_ptr, moved.m_ptr);+ return *this;+}++OpenSSL_SharedPKEY::~OpenSSL_SharedPKEY()+{+ EVP_PKEY_free(m_ptr);+}+ErrorOr<OpenSSL_MD_CTX> OpenSSL_MD_CTX::create(){return OpenSSL_MD_CTX(OPENSSL_TRY_PTR(EVP_MD_CTX_new()));diff --git a/Libraries/LibCrypto/OpenSSL.h b/Libraries/LibCrypto/OpenSSL.hindex 1e52ea83fda..e36d1bab82c 100644--- a/Libraries/LibCrypto/OpenSSL.h+++ b/Libraries/LibCrypto/OpenSSL.h@@ -98,6 +98,27 @@ class OpenSSL_PKEY {public:static ErrorOr<OpenSSL_PKEY> create();++ friend class OpenSSL_SharedPKEY;+};++// OpenSSL never changes a key once it is built, so copies share one key.+class OpenSSL_SharedPKEY {+public:+ OpenSSL_SharedPKEY() = default;+ explicit OpenSSL_SharedPKEY(OpenSSL_PKEY&&);++ OpenSSL_SharedPKEY(OpenSSL_SharedPKEY const&);+ OpenSSL_SharedPKEY(OpenSSL_SharedPKEY&&);+ OpenSSL_SharedPKEY& operator=(OpenSSL_SharedPKEY const&);+ OpenSSL_SharedPKEY& operator=(OpenSSL_SharedPKEY&&);+ ~OpenSSL_SharedPKEY();++ // NB: OpenSSL takes a non-const key even to read from it.+ EVP_PKEY* ptr() const { return m_ptr; }++private:+ EVP_PKEY* m_ptr { nullptr };};class OpenSSL_PKEY_CTX {diff --git a/Libraries/LibCrypto/PK/EC.cpp b/Libraries/LibCrypto/PK/EC.cppindex fb0b8d74da2..df9bf20fafc 100644--- a/Libraries/LibCrypto/PK/EC.cpp+++ b/Libraries/LibCrypto/PK/EC.cpp@@ -5,18 +5,178 @@*/#include <AK/ByteBuffer.h>+#include <AK/Memory.h>+#include <AK/ScopeGuard.h>#include <AK/StringView.h>#include <LibCrypto/ASN1/DER.h>#include <LibCrypto/Certificate/Certificate.h>#include <LibCrypto/OpenSSL.h>+#include <LibCrypto/PK/EC.h>+#include <openssl/core_names.h>#include <openssl/ec.h>+#include <openssl/evp.h>+#include <openssl/param_build.h>namespace Crypto::PK {-void ECPrivateKey::clear_sensitive_data()+static ErrorOr<char const*> curve_name(size_t scalar_size){- m_d.clear_sensitive_data();+ switch (scalar_size) {+ case 32:+ return "P-256";+ case 48:+ return "P-384";+ case 66:+ return "P-521";+ default:+ return Error::from_string_literal("Unsupported EC curve");+ }+}++static ErrorOr<OpenSSL_SharedPKEY> key_from_parameters(int selection, OSSL_PARAM_BLD* builder)+{+ auto* params = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_to_param(builder));+ ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };++ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr)));+ OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));++ EVP_PKEY* key = nullptr;+ OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key, selection, params));+ return OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(key)) };+}++static ErrorOr<ByteBuffer> integer_parameter(EVP_PKEY* key, char const* name, size_t size)+{+ BIGNUM* value = nullptr;+ OPENSSL_TRY(EVP_PKEY_get_bn_param(key, name, &value));+ ScopeGuard const free_value = [&] { BN_clear_free(value); };++ auto bytes = TRY(ByteBuffer::create_uninitialized(size));+ if (BN_bn2binpad(value, bytes.data(), size) < 0)+ return Error::from_string_literal("EC key component is too large");+ return bytes;+}++ErrorOr<ECPublicKey> ECPublicKey::from_octets(ReadonlyBytes data)+{+ if (data.is_empty())+ return Error::from_string_literal("Empty EC point");++ size_t scalar_size = 0;+ if (data[0] == 0x04 && data.size() % 2 == 1)+ scalar_size = (data.size() - 1) / 2;+ else if (data[0] == 0x02 || data[0] == 0x03)+ scalar_size = data.size() - 1;+ else+ return Error::from_string_literal("Unsupported EC point format");++ auto const* group = TRY(curve_name(scalar_size));++ auto* builder = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());+ ScopeGuard const free_builder = [&] { OSSL_PARAM_BLD_free(builder); };+ OPENSSL_TRY(OSSL_PARAM_BLD_push_utf8_string(builder, OSSL_PKEY_PARAM_GROUP_NAME, group, 0));+ OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(builder, OSSL_PKEY_PARAM_PUB_KEY, data.data(), data.size()));+ auto key = key_from_parameters(EVP_PKEY_PUBLIC_KEY, builder);+ if (key.is_error())+ return Error::from_string_literal("Invalid EC public key");++ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.value().ptr(), nullptr)));+ if (EVP_PKEY_public_check(ctx.ptr()) != 1)+ return Error::from_string_literal("Invalid EC public key");++ return ECPublicKey { key.release_value(), scalar_size };+}++ErrorOr<ECPublicKey> ECPublicKey::from_coordinates(ReadonlyBytes x, ReadonlyBytes y)+{+ if (x.size() != y.size())+ return Error::from_string_literal("EC coordinates have different sizes");++ auto octets = TRY(ByteBuffer::create_uninitialized(1 + x.size() + y.size()));+ octets[0] = 0x04;+ octets.overwrite(1, x.data(), x.size());+ octets.overwrite(1 + x.size(), y.data(), y.size());+ return from_octets(octets);+}++ErrorOr<ByteBuffer> ECPublicKey::x_bytes() const+{+ return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_EC_PUB_X, m_scalar_size);+}++ErrorOr<ByteBuffer> ECPublicKey::y_bytes() const+{+ return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_EC_PUB_Y, m_scalar_size);+}++ErrorOr<ByteBuffer> ECPublicKey::to_uncompressed() const+{+ auto x = TRY(x_bytes());+ auto y = TRY(y_bytes());++ auto bytes = TRY(ByteBuffer::create_uninitialized(1 + x.size() + y.size()));+ bytes[0] = 0x04;+ bytes.overwrite(1, x.data(), x.size());+ bytes.overwrite(1 + x.size(), y.data(), y.size());+ return bytes;+}++ErrorOr<ECPrivateKey> ECPrivateKey::generate(size_t scalar_size)+{+ auto key = OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(EVP_PKEY_Q_keygen(nullptr, nullptr, "EC", TRY(curve_name(scalar_size))))) };+ ECPrivateKey private_key { move(key), scalar_size, {}, {} };+ private_key.m_public_key = TRY(private_key.derive_public_key());+ return private_key;+}++ErrorOr<ECPrivateKey> ECPrivateKey::from_scalar(ReadonlyBytes d_bytes, Optional<ASN1::ObjectIdentifier> parameters, Optional<ECPublicKey> public_key)+{+ auto const* group_name = TRY(curve_name(d_bytes.size()));++ auto* group = OPENSSL_TRY_PTR(EC_GROUP_new_by_curve_name(EC_curve_nist2nid(group_name)));+ ScopeGuard const free_group = [&] { EC_GROUP_free(group); };++ auto* d = OPENSSL_TRY_PTR(BN_secure_new());+ ScopeGuard const free_d = [&] { BN_clear_free(d); };+ OPENSSL_TRY_PTR(BN_bin2bn(d_bytes.data(), d_bytes.size(), d));++ // NB: SEC 1 requires d to be in [1, n − 1].+ if (BN_is_zero(d) || BN_cmp(d, EC_GROUP_get0_order(group)) >= 0)+ return Error::from_string_literal("EC private key is out of range");++ auto* point = OPENSSL_TRY_PTR(EC_POINT_new(group));+ ScopeGuard const free_point = [&] { EC_POINT_free(point); };+ OPENSSL_TRY(EC_POINT_mul(group, point, d, nullptr, nullptr, nullptr));++ auto public_octets = TRY(ByteBuffer::create_uninitialized(1 + 2 * d_bytes.size()));+ if (EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, public_octets.data(), public_octets.size(), nullptr) != public_octets.size())+ return Error::from_string_literal("Failed to encode EC public key");++ if (public_key.has_value() && TRY(public_key->to_uncompressed()) != public_octets)+ return Error::from_string_literal("EC public key does not match the private key");++ auto* builder = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());+ ScopeGuard const free_builder = [&] { OSSL_PARAM_BLD_free(builder); };+ OPENSSL_TRY(OSSL_PARAM_BLD_push_utf8_string(builder, OSSL_PKEY_PARAM_GROUP_NAME, group_name, 0));+ OPENSSL_TRY(OSSL_PARAM_BLD_push_BN(builder, OSSL_PKEY_PARAM_PRIV_KEY, d));+ OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(builder, OSSL_PKEY_PARAM_PUB_KEY, public_octets.data(), public_octets.size()));+ auto key = TRY(key_from_parameters(EVP_PKEY_KEYPAIR, builder));++ return ECPrivateKey { move(key), d_bytes.size(), move(parameters), move(public_key) };+}++ErrorOr<ByteBuffer> ECPrivateKey::d_bytes() const+{+ return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_PRIV_KEY, m_scalar_size);+}++ErrorOr<ECPublicKey> ECPrivateKey::derive_public_key() const+{+ auto x = TRY(integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_EC_PUB_X, m_scalar_size));+ auto y = TRY(integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_EC_PUB_Y, m_scalar_size));+ return ECPublicKey::from_coordinates(x, y);}ErrorOr<ByteBuffer> ECPrivateKey::export_as_der() const@@ -26,6 +186,7 @@ ErrorOr<ByteBuffer> ECPrivateKey::export_as_der() constTRY(encoder.write(1u)); // versionauto d = TRY(d_bytes());+ ScopeGuard const clear_d = [&] { secure_zero(d.data(), d.size()); };TRY(encoder.write<ReadonlyBytes>(d));if (m_parameters.has_value()) {@@ -50,116 +211,162 @@ ErrorOr<ByteBuffer> ECPrivateKey::export_as_der() constreturn encoder.finish();}-static ErrorOr<ECPublicKey> read_ec_public_key(ReadonlyBytes bytes, Vector<StringView> current_scope)-{- // NOTE: Public keys do not have an ASN1 structure- if (bytes.size() < 1) {- ERROR_WITH_SCOPE("Invalid public key length");- }-- if (bytes[0] == 0x04) {- auto point = TRY(Curves::SECPxxxr1Point::from_uncompressed(bytes));- return ECPublicKey { move(point) };- }-- // Compressed point format: 0x02 (y even) or 0x03 (y odd)- if (bytes[0] == 0x02 || bytes[0] == 0x03) {- auto point = TRY(Curves::SECPxxxr1Point::from_compressed(bytes));- return ECPublicKey { move(point) };- }-- if (bytes.size() % 2 == 0) {- // Raw public key, without the 0x04 prefix- auto half_size = bytes.size() / 2;- return ::Crypto::PK::ECPublicKey {- UnsignedBigInteger::import_data(bytes.slice(0, half_size)),- UnsignedBigInteger::import_data(bytes.slice(half_size, half_size)),- half_size,- };- }-- ERROR_WITH_SCOPE("Unsupported public key format");-}-// https://www.rfc-editor.org/rfc/rfc5915#section-3ErrorOr<EC::KeyPairType> EC::parse_ec_key(ReadonlyBytes der, bool is_private, Vector<StringView> current_scope){KeyPairType keypair;- ASN1::Decoder decoder(der);+ if (!is_private) {+ // NB: A raw public key is the SEC 1 point itself.+ auto maybe_key = ECPublicKey::from_octets(der);+ if (maybe_key.is_error()) {+ ERROR_WITH_SCOPE(maybe_key.release_error());+ }- if (is_private) {- // ECPrivateKey ::= SEQUENCE {- // version INTEGER { ecPrivkeyVer1(1) }(ecPrivkeyVer1),- // privateKey OCTET STRING,- // parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,- // publicKey [1] BIT STRING OPTIONAL- // }+ keypair.public_key = maybe_key.release_value();+ return keypair;+ }- ENTER_TYPED_SCOPE(Sequence, "ECPrivateKey");+ ASN1::Decoder decoder(der);- PUSH_SCOPE("version");- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, version);- POP_SCOPE();+ // ECPrivateKey ::= SEQUENCE {+ // version INTEGER { ecPrivkeyVer1(1) }(ecPrivkeyVer1),+ // privateKey OCTET STRING,+ // parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,+ // publicKey [1] BIT STRING OPTIONAL+ // }- if (version != 1) {- ERROR_WITH_SCOPE("Invalid version");- }+ ENTER_TYPED_SCOPE(Sequence, "ECPrivateKey");- PUSH_SCOPE("privateKey");- READ_OBJECT(OctetString, StringView, private_key_bytes);- POP_SCOPE();+ PUSH_SCOPE("version");+ READ_OBJECT(Integer, Crypto::UnsignedBigInteger, version);+ POP_SCOPE();- auto private_key = UnsignedBigInteger::import_data(private_key_bytes.bytes());+ if (version != 1) {+ ERROR_WITH_SCOPE("Invalid version");+ }- Optional<ASN1::ObjectIdentifier> parameters;- if (!decoder.eof()) {- auto tag = TRY(decoder.peek());- if (static_cast<u8>(tag.kind) == 0) {- REWRITE_TAG(Sequence);- ENTER_TYPED_SCOPE(Sequence, "parameters");- parameters = TRY(Crypto::Certificate::parse_ec_parameters(decoder, {}));- EXIT_SCOPE();- }+ PUSH_SCOPE("privateKey");+ READ_OBJECT(OctetString, StringView, private_key_bytes);+ POP_SCOPE();++ Optional<ASN1::ObjectIdentifier> parameters;+ if (!decoder.eof()) {+ auto tag = TRY(decoder.peek());+ if (static_cast<u8>(tag.kind) == 0) {+ REWRITE_TAG(Sequence);+ ENTER_TYPED_SCOPE(Sequence, "parameters");+ parameters = TRY(Crypto::Certificate::parse_ec_parameters(decoder, {}));+ EXIT_SCOPE();}+ }- Optional<ECPublicKey> public_key;- if (!decoder.eof()) {- auto tag = TRY(decoder.peek());- if (static_cast<u8>(tag.kind) == 1) {- REWRITE_TAG(Sequence);- ENTER_TYPED_SCOPE(Sequence, "publicKey");- READ_OBJECT(BitString, Crypto::ASN1::BitStringView, public_key_bits);-- auto public_key_bytes = TRY(public_key_bits.raw_bytes());- auto maybe_public_key = read_ec_public_key(public_key_bytes, current_scope);- if (maybe_public_key.is_error()) {- ERROR_WITH_SCOPE(maybe_public_key.release_error());- }-- keypair.public_key = maybe_public_key.release_value();- public_key = keypair.public_key;- if (keypair.public_key.scalar_size() != private_key_bytes.length()) {- ERROR_WITH_SCOPE("Invalid public key length");- }-- EXIT_SCOPE();+ Optional<ECPublicKey> public_key;+ if (!decoder.eof()) {+ auto tag = TRY(decoder.peek());+ if (static_cast<u8>(tag.kind) == 1) {+ REWRITE_TAG(Sequence);+ ENTER_TYPED_SCOPE(Sequence, "publicKey");+ READ_OBJECT(BitString, Crypto::ASN1::BitStringView, public_key_bits);++ auto public_key_bytes = TRY(public_key_bits.raw_bytes());+ auto maybe_public_key = ECPublicKey::from_octets(public_key_bytes);+ if (maybe_public_key.is_error()) {+ ERROR_WITH_SCOPE(maybe_public_key.release_error());}- }- keypair.private_key = ECPrivateKey { private_key, private_key_bytes.length(), parameters, public_key };+ keypair.public_key = maybe_public_key.release_value();+ public_key = keypair.public_key;- EXIT_SCOPE();- return keypair;- } else {- auto maybe_key = read_ec_public_key(der, current_scope);- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());+ EXIT_SCOPE();}+ }- keypair.public_key = maybe_key.release_value();- return keypair;+ auto private_key = ECPrivateKey::from_scalar(private_key_bytes.bytes(), move(parameters), move(public_key));+ if (private_key.is_error()) {+ ERROR_WITH_SCOPE(private_key.release_error());+ }+ keypair.private_key = private_key.release_value();++ EXIT_SCOPE();+ return keypair;+}++ErrorOr<ECDSASignature> ecdsa_sign(ECPrivateKey const& private_key, ReadonlyBytes digest)+{+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, private_key.openssl_key(), nullptr)));+ OPENSSL_TRY(EVP_PKEY_sign_init(ctx.ptr()));++ size_t signature_size = 0;+ OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), nullptr, &signature_size, digest.data(), digest.size()));++ auto signature = TRY(ByteBuffer::create_uninitialized(signature_size));+ OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), signature.data(), &signature_size, digest.data(), digest.size()));++ auto const* signature_data = signature.data();+ auto* signature_object = OPENSSL_TRY_PTR(d2i_ECDSA_SIG(nullptr, &signature_data, signature_size));+ ScopeGuard const free_signature_object = [&] { ECDSA_SIG_free(signature_object); };++ auto size = private_key.scalar_size();+ ECDSASignature result {+ TRY(ByteBuffer::create_uninitialized(size)),+ TRY(ByteBuffer::create_uninitialized(size)),+ };+ if (BN_bn2binpad(ECDSA_SIG_get0_r(signature_object), result.r.data(), size) < 0 || BN_bn2binpad(ECDSA_SIG_get0_s(signature_object), result.s.data(), size) < 0)+ return Error::from_string_literal("ECDSA signature is too large");+ return result;+}++ErrorOr<bool> ecdsa_verify(ECPublicKey const& public_key, ReadonlyBytes digest, ReadonlyBytes r, ReadonlyBytes s)+{+ if (r.size() != public_key.scalar_size() || s.size() != public_key.scalar_size())+ return false;++ auto* signature_object = OPENSSL_TRY_PTR(ECDSA_SIG_new());+ ScopeGuard const free_signature_object = [&] { ECDSA_SIG_free(signature_object); };++ auto* r_value = OPENSSL_TRY_PTR(BN_bin2bn(r.data(), r.size(), nullptr));+ auto* s_value = BN_bin2bn(s.data(), s.size(), nullptr);+ if (!s_value || ECDSA_SIG_set0(signature_object, r_value, s_value) != 1) {+ BN_free(r_value);+ BN_free(s_value);+ return Error::from_string_literal("Failed to build the ECDSA signature");}++ u8* signature = nullptr;+ ScopeGuard const free_signature = [&] { OPENSSL_free(signature); };+ auto signature_size = i2d_ECDSA_SIG(signature_object, &signature);+ if (signature_size <= 0)+ return Error::from_string_literal("Failed to encode the ECDSA signature");++ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, public_key.openssl_key(), nullptr)));+ OPENSSL_TRY(EVP_PKEY_verify_init(ctx.ptr()));++ auto result = EVP_PKEY_verify(ctx.ptr(), signature, signature_size, digest.data(), digest.size());+ if (result == 1)+ return true;+ if (result == 0)+ return false;+ OPENSSL_TRY(result);+ VERIFY_NOT_REACHED();+}++ErrorOr<ByteBuffer> ecdh_derive(ECPrivateKey const& private_key, ECPublicKey const& peer)+{+ if (private_key.scalar_size() != peer.scalar_size())+ return Error::from_string_literal("EC keys are on different curves");++ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, private_key.openssl_key(), nullptr)));+ OPENSSL_TRY(EVP_PKEY_derive_init(ctx.ptr()));+ OPENSSL_TRY(EVP_PKEY_derive_set_peer_ex(ctx.ptr(), peer.openssl_key(), 1));++ size_t secret_size = 0;+ OPENSSL_TRY(EVP_PKEY_derive(ctx.ptr(), nullptr, &secret_size));++ auto secret = TRY(ByteBuffer::create_uninitialized(secret_size));+ OPENSSL_TRY(EVP_PKEY_derive(ctx.ptr(), secret.data(), &secret_size));+ secret.resize(secret_size);+ return secret;}}diff --git a/Libraries/LibCrypto/PK/EC.h b/Libraries/LibCrypto/PK/EC.hindex 929148939f9..fbab5e171df 100644--- a/Libraries/LibCrypto/PK/EC.h+++ b/Libraries/LibCrypto/PK/EC.h@@ -7,108 +7,96 @@#pragma once#include <AK/ByteBuffer.h>+#include <AK/Optional.h>#include <AK/StringView.h>-#include <LibCrypto/Curves/SECPxxxr1.h>-#include <LibCrypto/PK/PK.h>+#include <LibCrypto/ASN1/DER.h>+#include <LibCrypto/OpenSSL.h>+// NB: Each key's curve is the NIST prime curve whose coordinates have the key's scalar size: 32 bytes for P-256, 48 for+// P-384 and 66 for P-521.namespace Crypto::PK {class ECPublicKey {public:- ECPublicKey(UnsignedBigInteger x, UnsignedBigInteger y, size_t scalar_size)- : m_x(move(x))- , m_y(move(y))- , m_scalar_size(scalar_size)- {- }+ ECPublicKey() = default;- ECPublicKey(Curves::SECPxxxr1Point point)- : m_x(move(point.x))- , m_y(move(point.y))- , m_scalar_size(point.size)- {- }-- ECPublicKey()- : m_x(0)- , m_y(0)- , m_scalar_size(0)- {- }+ static ErrorOr<ECPublicKey> from_octets(ReadonlyBytes);+ static ErrorOr<ECPublicKey> from_coordinates(ReadonlyBytes x, ReadonlyBytes y);size_t scalar_size() const { return m_scalar_size; }- ErrorOr<ByteBuffer> x_bytes() const- {- return Curves::SECPxxxr1Point::scalar_to_bytes(m_x, m_scalar_size);- }-- ErrorOr<ByteBuffer> y_bytes() const- {- return Curves::SECPxxxr1Point::scalar_to_bytes(m_y, m_scalar_size);- }+ ErrorOr<ByteBuffer> x_bytes() const;+ ErrorOr<ByteBuffer> y_bytes() const;+ ErrorOr<ByteBuffer> to_uncompressed() const;- Curves::SECPxxxr1Point to_secpxxxr1_point() const- {- return Curves::SECPxxxr1Point { m_x, m_y, m_scalar_size };- }+ EVP_PKEY* openssl_key() const { return m_key.ptr(); }- ErrorOr<ByteBuffer> to_uncompressed() const+private:+ ECPublicKey(OpenSSL_SharedPKEY key, size_t scalar_size)+ : m_key(move(key))+ , m_scalar_size(scalar_size){- return to_secpxxxr1_point().to_uncompressed();}-private:- UnsignedBigInteger m_x;- UnsignedBigInteger m_y;- size_t m_scalar_size;+ OpenSSL_SharedPKEY m_key;+ size_t m_scalar_size { 0 };};// https://www.rfc-editor.org/rfc/rfc5915#section-3class ECPrivateKey {public:- ECPrivateKey(UnsignedBigInteger d, size_t scalar_size, Optional<ASN1::ObjectIdentifier> parameters, Optional<ECPublicKey> public_key)- : m_d(move(d))- , m_scalar_size(scalar_size)- , m_parameters(parameters)- , m_public_key(public_key)- {- }-ECPrivateKey() = default;- void clear_sensitive_data();+ static ErrorOr<ECPrivateKey> generate(size_t scalar_size);+ static ErrorOr<ECPrivateKey> from_scalar(ReadonlyBytes d, Optional<ASN1::ObjectIdentifier> parameters, Optional<ECPublicKey> public_key);- UnsignedBigInteger const& d() const { return m_d; }- ErrorOr<ByteBuffer> d_bytes() const- {- return Curves::SECPxxxr1Point::scalar_to_bytes(m_d, m_scalar_size);- }+ size_t scalar_size() const { return m_scalar_size; }++ ErrorOr<ByteBuffer> d_bytes() const;+ ErrorOr<ECPublicKey> derive_public_key() const;Optional<ASN1::ObjectIdentifier> const& parameters() const { return m_parameters; }Optional<ECPublicKey> const& public_key() const { return m_public_key; }ErrorOr<ByteBuffer> export_as_der() const;+ EVP_PKEY* openssl_key() const { return m_key.ptr(); }+private:- UnsignedBigInteger m_d;- size_t m_scalar_size;+ ECPrivateKey(OpenSSL_SharedPKEY key, size_t scalar_size, Optional<ASN1::ObjectIdentifier> parameters, Optional<ECPublicKey> public_key)+ : m_key(move(key))+ , m_scalar_size(scalar_size)+ , m_parameters(move(parameters))+ , m_public_key(move(public_key))+ {+ }+ OpenSSL_SharedPKEY m_key;+ size_t m_scalar_size { 0 };Optional<ASN1::ObjectIdentifier> m_parameters;Optional<ECPublicKey> m_public_key;};-template<typename PubKey, typename PrivKey>struct ECKeyPair {- PubKey public_key;- PrivKey private_key;+ ECPublicKey public_key;+ ECPrivateKey private_key;};class EC {public:- using KeyPairType = ECKeyPair<ECPublicKey, ECPrivateKey>;+ using KeyPairType = ECKeyPair;static ErrorOr<KeyPairType> parse_ec_key(ReadonlyBytes der, bool is_private, Vector<StringView> current_scope);};+struct ECDSASignature {+ ByteBuffer r;+ ByteBuffer s;+};++ErrorOr<ECDSASignature> ecdsa_sign(ECPrivateKey const&, ReadonlyBytes digest);+ErrorOr<bool> ecdsa_verify(ECPublicKey const&, ReadonlyBytes digest, ReadonlyBytes r, ReadonlyBytes s);++ErrorOr<ByteBuffer> ecdh_derive(ECPrivateKey const&, ECPublicKey const& peer);+}diff --git a/Libraries/LibCrypto/PK/MLDSA.cpp b/Libraries/LibCrypto/PK/MLDSA.cppindex f94c9f48ac1..846b7ac9e5b 100644--- a/Libraries/LibCrypto/PK/MLDSA.cpp+++ b/Libraries/LibCrypto/PK/MLDSA.cpp@@ -7,7 +7,7 @@#include <AK/Memory.h>#include <LibCrypto/PK/MLDSA.h>-#include <LibCrypto/Curves/SECPxxxr1.h>+#include <LibCrypto/ASN1/DER.h>#include <LibCrypto/OpenSSL.h>#include <LibCrypto/PK/ModuleLatticePrivateKey.h>diff --git a/Libraries/LibCrypto/PK/MLKEM.cpp b/Libraries/LibCrypto/PK/MLKEM.cppindex aa248fbe4a1..699bc32e9dd 100644--- a/Libraries/LibCrypto/PK/MLKEM.cpp+++ b/Libraries/LibCrypto/PK/MLKEM.cpp@@ -8,7 +8,6 @@#include <LibCrypto/PK/MLKEM.h>#include <LibCrypto/ASN1/DER.h>-#include <LibCrypto/Curves/SECPxxxr1.h>#include <LibCrypto/OpenSSL.h>#include <LibCrypto/PK/ModuleLatticePrivateKey.h>diff --git a/Libraries/LibCrypto/Rust/src/ffi.rs b/Libraries/LibCrypto/Rust/src/ffi.rsindex b12b12df3b6..89a6e56786b 100644--- a/Libraries/LibCrypto/Rust/src/ffi.rs+++ b/Libraries/LibCrypto/Rust/src/ffi.rs@@ -42,8 +42,7 @@ unsafe extern "C" {out: *mut c_void,all_consumed: &mut bool,) -> usize;- pub(super) fn crypto_public_key_for_private_key(key: *const c_void, name: usize, named_curve: usize)- -> *mut c_void;+ pub(super) fn crypto_public_key_for_private_key(key: *const c_void, name: usize) -> *mut c_void;pub(super) fn crypto_sha_digest(kind: ShaHashKind,data: Span<'_, u8>,@@ -253,11 +252,10 @@ unsafe extern "C" {curve: EcCurve,key: *const c_void,digest: Span<'_, u8>,- error: &mut usize,r: *mut c_void,s: *mut c_void,receive: ReceiveBytes,- ) -> u8;+ ) -> usize;pub(super) fn crypto_ec_verify(curve: EcCurve,key: *const c_void,@@ -271,10 +269,9 @@ unsafe extern "C" {curve: EcCurve,key: *const c_void,public_key: *const c_void,- error: &mut usize,state: *mut c_void,receive: ReceiveBytes,- ) -> u8;+ ) -> usize;pub(super) fn crypto_ec_key_info_has_public_key_oid(structure: Asn1Structure, key_info: *const c_void) -> bool;pub(super) fn crypto_ec_key_info_parameters(structure: Asn1Structure,@@ -283,12 +280,8 @@ unsafe extern "C" {) -> bool;pub(super) fn crypto_ec_private_key_info_parameters_match(key_info: *const c_void) -> bool;pub(super) fn crypto_ec_key_info_read_key(structure: Asn1Structure, key_info: *const c_void) -> *mut c_void;- pub(super) fn crypto_ec_key_from_coordinates(- x: Span<'_, u8>,- y: Span<'_, u8>,- coord_size: usize,- d: OptionalBytes<'_>,- ) -> *mut c_void;+ pub(super) fn crypto_ec_key_from_coordinates(x: Span<'_, u8>, y: Span<'_, u8>, d: OptionalBytes<'_>)+ -> *mut c_void;pub(super) fn crypto_ec_parse_raw_public_key(bytes: Span<'_, u8>) -> *mut c_void;pub(super) fn crypto_ec_key_is_valid(curve: EcCurve, key: *const c_void, valid: &mut bool) -> bool;pub(super) fn crypto_ec_export_der(@@ -300,7 +293,6 @@ unsafe extern "C" {) -> bool;pub(super) fn crypto_ec_export_uncompressed(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> bool;pub(super) fn crypto_ec_export_public_coordinates(- curve: EcCurve,key: *const c_void,x: *mut c_void,y: *mut c_void,diff --git a/Libraries/LibCrypto/Rust/src/key.rs b/Libraries/LibCrypto/Rust/src/key.rsindex 8afa2d4e331..4e39ee44ea3 100644--- a/Libraries/LibCrypto/Rust/src/key.rs+++ b/Libraries/LibCrypto/Rust/src/key.rs@@ -50,6 +50,15 @@ impl<'a> KeyComponents<'a> {}}+/// The result of decoding a key handle, Crypto's KeyDecodeResult.+#[repr(u8)]+#[allow(dead_code, reason = "LibCrypto constructs the variants")]+enum RawKeyDecodeResult {+ Decoded,+ InvalidComponents,+ OutOfMemory,+}+#[repr(C)]struct RawKeyComponents<'a> {tag: u8,@@ -71,7 +80,7 @@ unsafe extern "C" {state: *mut c_void,steps: unsafe extern "C" fn(*mut c_void, *const RawKeyComponents<'_>),);- fn crypto_key_decode_handle(fields: &RawKeyComponents<'_>, key: &mut *mut c_void) -> bool;+ fn crypto_key_decode_handle(fields: &RawKeyComponents<'_>, key: &mut *mut c_void) -> RawKeyDecodeResult;}impl KeyHandle {@@ -171,8 +180,10 @@ impl KeyHandle {};let mut key = core::ptr::null_mut();// SAFETY: The validated fields and output slot are live for the call.- if !unsafe { crypto_key_decode_handle(&fields, &mut key) } {- return Err(KeyDecodeError::OutOfMemory);+ match unsafe { crypto_key_decode_handle(&fields, &mut key) } {+ RawKeyDecodeResult::Decoded => {}+ RawKeyDecodeResult::InvalidComponents => return Err(KeyDecodeError::InvalidComponents),+ RawKeyDecodeResult::OutOfMemory => return Err(KeyDecodeError::OutOfMemory),}// SAFETY: Success transfers ownership of the native key.Ok(unsafe { Self::from_raw(key) }.expect("LibCrypto returns the decoded key"))diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rsindex f52a6941d9d..65579abd0ed 100644--- a/Libraries/LibCrypto/Rust/src/lib.rs+++ b/Libraries/LibCrypto/Rust/src/lib.rs@@ -656,11 +656,11 @@ pub fn ec_public_key_scalar_size(key: &KeyHandle) -> usize {unsafe { ffi::crypto_ec_public_key_scalar_size(key.as_raw()) }}-pub fn ec_key_from_coordinates(x: &[u8], y: &[u8], coord_size: usize, d: Option<&[u8]>) -> KeyHandle {+pub fn ec_key_from_coordinates(x: &[u8], y: &[u8], d: Option<&[u8]>) -> Option<KeyHandle> {// SAFETY: The input is borrowed for the call.- let raw = unsafe { ffi::crypto_ec_key_from_coordinates(Span::new(x), Span::new(y), coord_size, d.into()) };+ let raw = unsafe { ffi::crypto_ec_key_from_coordinates(Span::new(x), Span::new(y), d.into()) };// SAFETY: The native operation transfers ownership of the key.- unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns a key")+ unsafe { KeyHandle::from_raw(raw) }}pub fn ec_parse_raw_public_key(bytes: &[u8]) -> Option<KeyHandle> {@@ -696,13 +696,12 @@ pub fn ec_export_uncompressed(key: &KeyHandle) -> Result<Vec<u8>, BackendError>Ok(bytes)}-pub fn ec_export_public_coordinates(curve: EcCurve, key: &KeyHandle) -> Result<(Vec<u8>, Vec<u8>), BackendError> {+pub fn ec_export_public_coordinates(key: &KeyHandle) -> Result<(Vec<u8>, Vec<u8>), BackendError> {let mut first = Vec::new();let mut second = Vec::new();// SAFETY: Inputs and both output slots are borrowed for the call.let status = unsafe {ffi::crypto_ec_export_public_coordinates(- curve,key.as_raw(),core::ptr::from_mut(&mut first).cast(),core::ptr::from_mut(&mut second).cast(),@@ -943,14 +942,9 @@ pub fn mlkem_decapsulate(size: MlKemSize, key: &KeyHandle, ciphertext: &[u8]) ->Ok(bytes)}-pub fn public_key_for_private_key(- key: &KeyHandle,- name: &Utf16String,- named_curve: Option<&Utf16String>,-) -> Option<KeyHandle> {- let named_curve = named_curve.map_or(0, Utf16String::raw_identity);+pub fn public_key_for_private_key(key: &KeyHandle, name: &Utf16String) -> Option<KeyHandle> {// SAFETY: The inputs are borrowed for the call.- let raw = unsafe { ffi::crypto_public_key_for_private_key(key.as_raw(), name.raw_identity(), named_curve) };+ let raw = unsafe { ffi::crypto_public_key_for_private_key(key.as_raw(), name.raw_identity()) };// SAFETY: A non-null result transfers ownership of the key.unsafe { KeyHandle::from_raw(raw) }}@@ -978,22 +972,7 @@ pub fn rsa_key_from_components(is_private: bool, components: &[&[u8]]) -> Optionunsafe { KeyHandle::from_raw(raw) }}-#[derive(Debug)]-pub enum EcError {- Operation(Utf16String),- CoordinateEncoding,-}--fn ec_result(status: u8, error: usize) -> Result<(), EcError> {- match status {- 0 => Ok(()),- 1 => result_from_error(error).map_err(EcError::Operation),- _ => Err(EcError::CoordinateEncoding),- }-}--pub fn ec_sign(curve: EcCurve, key: &KeyHandle, digest: &[u8]) -> Result<(Vec<u8>, Vec<u8>), EcError> {- let mut error = 0;+pub fn ec_sign(curve: EcCurve, key: &KeyHandle, digest: &[u8]) -> Result<(Vec<u8>, Vec<u8>), Utf16String> {let mut r = Vec::new();let mut s = Vec::new();// SAFETY: Inputs and both output slots are live for the synchronous call.@@ -1002,22 +981,20 @@ pub fn ec_sign(curve: EcCurve, key: &KeyHandle, digest: &[u8]) -> Result<(Vec<u8curve,key.as_raw(),Span::new(digest),- &mut error,core::ptr::from_mut(&mut r).cast(),core::ptr::from_mut(&mut s).cast(),receive_bytes,)};- ec_result(status, error)?;+ result_from_error(status)?;Ok((r, s))}-pub fn ec_compute_coordinate(curve: EcCurve, key: &KeyHandle, public_key: &KeyHandle) -> Result<Vec<u8>, EcError> {- let mut error = 0;- // SAFETY: The key handles and output slots are live for the synchronous call.+pub fn ec_compute_coordinate(curve: EcCurve, key: &KeyHandle, public_key: &KeyHandle) -> Result<Vec<u8>, Utf16String> {+ // SAFETY: The key handles and output slot are live for the synchronous call.let (status, bytes) = receive_native_bytes(|state, receive| unsafe {- ffi::crypto_ec_compute_coordinate(curve, key.as_raw(), public_key.as_raw(), &mut error, state, receive)+ ffi::crypto_ec_compute_coordinate(curve, key.as_raw(), public_key.as_raw(), state, receive)});- ec_result(status, error)?;+ result_from_error(status)?;Ok(bytes)}diff --git a/Libraries/LibCrypto/RustBindings.cpp b/Libraries/LibCrypto/RustBindings.cppindex 75dacf2650d..74dda707834 100644--- a/Libraries/LibCrypto/RustBindings.cpp+++ b/Libraries/LibCrypto/RustBindings.cpp@@ -19,13 +19,13 @@#include <LibCrypto/Cipher/AES.h>#include <LibCrypto/Cipher/ChaCha.h>#include <LibCrypto/Curves/EdwardsCurve.h>-#include <LibCrypto/Curves/SECPxxxr1.h>#include <LibCrypto/Hash/Argon2.h>#include <LibCrypto/Hash/HKDF.h>#include <LibCrypto/Hash/Hash.h>#include <LibCrypto/Hash/PBKDF2.h>#include <LibCrypto/Hash/SHAKE.h>#include <LibCrypto/KeyHandle.h>+#include <LibCrypto/PK/EC.h>#include <LibCrypto/PK/MLDSA.h>#include <LibCrypto/PK/MLKEM.h>#include <LibCrypto/PK/RSA.h>@@ -135,7 +135,6 @@ void crypto_asn1_delete_key_info(Asn1Structure structure, void* key_info)VERIFY(structure == Asn1Structure::PrivateKeyInfo);auto* storage = static_cast<PrivateKeyStorage*>(key_info);storage->value.rsa.clear_sensitive_data();- storage->value.ec.clear_sensitive_data();storage->value.mldsa.clear_sensitive_data();storage->value.mlkem.clear_sensitive_data();secure_zero(storage->value.raw_key.data(), storage->value.raw_key.size());@@ -418,15 +417,15 @@ enum class EcCurve : u8 {P521,};-static ::Crypto::Curves::SECPxxxr1 ec_curve(EcCurve curve)+static size_t ec_scalar_size(EcCurve curve){switch (curve) {case EcCurve::P256:- return ::Crypto::Curves::SECP256r1 {};+ return 32;case EcCurve::P384:- return ::Crypto::Curves::SECP384r1 {};+ return 48;case EcCurve::P521:- return ::Crypto::Curves::SECP521r1 {};+ return 66;}VERIFY_NOT_REACHED();}@@ -446,65 +445,54 @@ static ReadonlySpan<u32> ec_curve_oid(EcCurve curve)extern "C" {bool crypto_ec_generate_key_pair(EcCurve, KeyHandle**, KeyHandle**);-u8 crypto_ec_sign(EcCurve, KeyHandle const*, ReadonlyBytes, FlatPtr*, void*, void*, ReceiveEncodedBytes);+FlatPtr crypto_ec_sign(EcCurve, KeyHandle const*, ReadonlyBytes, void*, void*, ReceiveEncodedBytes);FlatPtr crypto_ec_verify(EcCurve, KeyHandle const*, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, bool*);size_t crypto_ec_public_key_scalar_size(KeyHandle const*);-u8 crypto_ec_compute_coordinate(EcCurve, KeyHandle const*, KeyHandle const*, FlatPtr*, void*, ReceiveEncodedBytes);+FlatPtr crypto_ec_compute_coordinate(EcCurve, KeyHandle const*, KeyHandle const*, void*, ReceiveEncodedBytes);bool crypto_ec_key_info_has_public_key_oid(Asn1Structure, void const*);bool crypto_ec_key_info_parameters(Asn1Structure, void const*, ReadonlySpan<u32>*);bool crypto_ec_private_key_info_parameters_match(void const*);KeyHandle* crypto_ec_key_info_read_key(Asn1Structure, void const*);-KeyHandle* crypto_ec_key_from_coordinates(ReadonlyBytes, ReadonlyBytes, size_t, OptionalBytes);+KeyHandle* crypto_ec_key_from_coordinates(ReadonlyBytes, ReadonlyBytes, OptionalBytes);KeyHandle* crypto_ec_parse_raw_public_key(ReadonlyBytes);bool crypto_ec_key_is_valid(EcCurve, KeyHandle const*, bool*);bool crypto_ec_export_der(EcCurve, KeyHandle const*, bool, void*, ReceiveEncodedBytes);bool crypto_ec_export_uncompressed(KeyHandle const*, void*, ReceiveEncodedBytes);-bool crypto_ec_export_public_coordinates(EcCurve, KeyHandle const*, void*, void*, ReceiveEncodedBytes);+bool crypto_ec_export_public_coordinates(KeyHandle const*, void*, void*, ReceiveEncodedBytes);bool crypto_ec_export_private_scalar(KeyHandle const*, void*, ReceiveEncodedBytes);}-bool crypto_ec_generate_key_pair(EcCurve curve_id, KeyHandle** out_public_key, KeyHandle** out_private_key)+bool crypto_ec_generate_key_pair(EcCurve curve, KeyHandle** out_public_key, KeyHandle** out_private_key){- auto curve = ec_curve(curve_id);- auto maybe_private_key_data = curve.generate_private_key();- if (maybe_private_key_data.is_error())+ auto private_key = ::Crypto::PK::ECPrivateKey::generate(ec_scalar_size(curve));+ if (private_key.is_error())return false;- auto private_key_data = maybe_private_key_data.release_value();- auto maybe_public_key_data = curve.generate_public_key(private_key_data);- if (maybe_public_key_data.is_error())- return false;- auto public_key_data = maybe_public_key_data.release_value();- auto public_key = ::Crypto::PK::ECPublicKey { public_key_data };- auto private_key = ::Crypto::PK::ECPrivateKey { move(private_key_data), public_key_data.size, {}, public_key };- *out_public_key = new KeyHandle(move(public_key));- *out_private_key = new KeyHandle(move(private_key));+ *out_public_key = new KeyHandle(*private_key.value().public_key());+ *out_private_key = new KeyHandle(private_key.release_value());return true;}-u8 crypto_ec_sign(EcCurve curve_id, KeyHandle const* key, ReadonlyBytes digest, FlatPtr* error, void* r, void* s, ReceiveEncodedBytes receive)+FlatPtr crypto_ec_sign(EcCurve curve, KeyHandle const* key, ReadonlyBytes digest, void* r, void* s, ReceiveEncodedBytes receive){- auto signature = ec_curve(curve_id).sign(digest, key->get<::Crypto::PK::ECPrivateKey>().d());- if (signature.is_error()) {- *error = Utf16String::from_utf8(signature.error().string_literal()).into_raw();- return 1;- }- auto r_bytes = signature.value().r_bytes();- if (r_bytes.is_error())- return 2;- receive(r, r_bytes.value());- auto s_bytes = signature.value().s_bytes();- if (s_bytes.is_error())- return 2;- receive(s, s_bytes.value());+ auto const& private_key = key->get<::Crypto::PK::ECPrivateKey>();+ if (private_key.scalar_size() != ec_scalar_size(curve))+ return Utf16String::from_utf8("The key is on a different curve"sv).into_raw();+ auto signature = ::Crypto::PK::ecdsa_sign(private_key, digest);+ if (signature.is_error())+ return Utf16String::formatted("{}", signature.error()).into_raw();+ receive(r, signature.value().r);+ receive(s, signature.value().s);return 0;}-FlatPtr crypto_ec_verify(EcCurve curve_id, KeyHandle const* key, ReadonlyBytes digest, ReadonlyBytes r_bytes, ReadonlyBytes s_bytes, bool* verified)+FlatPtr crypto_ec_verify(EcCurve curve, KeyHandle const* key, ReadonlyBytes digest, ReadonlyBytes r, ReadonlyBytes s, bool* verified){auto const& public_key = key->get<::Crypto::PK::ECPublicKey>();- auto r = ::Crypto::UnsignedBigInteger::import_data(r_bytes);- auto s = ::Crypto::UnsignedBigInteger::import_data(s_bytes);- auto result = ec_curve(curve_id).verify(digest, public_key.to_secpxxxr1_point(), { move(r), move(s), public_key.scalar_size() });+ if (public_key.scalar_size() != ec_scalar_size(curve)) {+ *verified = false;+ return 0;+ }+ auto result = ::Crypto::PK::ecdsa_verify(public_key, digest, r, s);if (result.is_error())return Utf16String::from_utf8(result.error().string_literal()).into_raw();*verified = result.value();@@ -516,19 +504,16 @@ size_t crypto_ec_public_key_scalar_size(KeyHandle const* key)return key->get<::Crypto::PK::ECPublicKey>().scalar_size();}-u8 crypto_ec_compute_coordinate(EcCurve curve_id, KeyHandle const* key, KeyHandle const* public_key, FlatPtr* error, void* state, ReceiveEncodedBytes receive)+FlatPtr crypto_ec_compute_coordinate(EcCurve curve, KeyHandle const* key, KeyHandle const* public_key, void* state, ReceiveEncodedBytes receive){- auto const& private_key_data = key->get<::Crypto::PK::ECPrivateKey>();- auto const& public_key_data = public_key->get<::Crypto::PK::ECPublicKey>();- auto secret = ec_curve(curve_id).compute_coordinate(private_key_data.d(), public_key_data.to_secpxxxr1_point());- if (secret.is_error()) {- *error = Utf16String::formatted("{}", secret.error()).into_raw();- return 1;- }- auto secret_data = secret.value().to_uncompressed();- if (secret_data.is_error())- return 2;- receive(state, secret_data.value());+ auto const& private_key = key->get<::Crypto::PK::ECPrivateKey>();+ if (private_key.scalar_size() != ec_scalar_size(curve))+ return Utf16String::from_utf8("The key is on a different curve"sv).into_raw();+ auto secret = ::Crypto::PK::ecdh_derive(private_key, public_key->get<::Crypto::PK::ECPublicKey>());+ if (secret.is_error())+ return Utf16String::formatted("{}", secret.error()).into_raw();+ receive(state, secret.value());+ secure_zero(secret.value().data(), secret.value().size());return 0;}@@ -569,38 +554,35 @@ KeyHandle* crypto_ec_key_info_read_key(Asn1Structure structure, void const* key_return new KeyHandle(static_cast<PrivateKeyStorage const*>(key_info)->value.ec);}-KeyHandle* crypto_ec_key_from_coordinates(ReadonlyBytes x, ReadonlyBytes y, size_t coord_size, OptionalBytes d)+KeyHandle* crypto_ec_key_from_coordinates(ReadonlyBytes x, ReadonlyBytes y, OptionalBytes d){- auto public_key = ::Crypto::PK::ECPublicKey { ::Crypto::UnsignedBigInteger::import_data(x), ::Crypto::UnsignedBigInteger::import_data(y), coord_size };+ auto public_key = ::Crypto::PK::ECPublicKey::from_coordinates(x, y);+ if (public_key.is_error())+ return nullptr;if (!d.has_value)- return new KeyHandle(move(public_key));- return new KeyHandle(::Crypto::PK::ECPrivateKey { ::Crypto::UnsignedBigInteger::import_data(d.bytes), coord_size, {}, move(public_key) });+ return new KeyHandle(public_key.release_value());+ auto private_key = ::Crypto::PK::ECPrivateKey::from_scalar(d.bytes, {}, public_key.release_value());+ if (private_key.is_error())+ return nullptr;+ return new KeyHandle(private_key.release_value());}KeyHandle* crypto_ec_parse_raw_public_key(ReadonlyBytes data){- auto result = ::Crypto::PK::EC::parse_ec_key(data, false, {});- if (result.is_error())+ auto public_key = ::Crypto::PK::ECPublicKey::from_octets(data);+ if (public_key.is_error())return nullptr;- return new KeyHandle(move(result.value().public_key));+ return new KeyHandle(public_key.release_value());}-bool crypto_ec_key_is_valid(EcCurve curve_id, KeyHandle const* key, bool* valid)+// NB: Every EC key is a valid key for its own curve, since building it checks that.+bool crypto_ec_key_is_valid(EcCurve curve, KeyHandle const* key, bool* valid){- auto curve = ec_curve(curve_id);- auto result = key->visit(- [&](::Crypto::PK::ECPublicKey const& public_key) {- return curve.is_valid_point(public_key.to_secpxxxr1_point());- },- [&](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<bool> {- if (!private_key.public_key().has_value())- return true;- return curve.is_valid_point(private_key.public_key()->to_secpxxxr1_point(), private_key.d());- },- [](auto const&) -> ErrorOr<bool> { VERIFY_NOT_REACHED(); });- if (result.is_error())- return false;- *valid = result.value();+ auto scalar_size = key->visit(+ [](::Crypto::PK::ECPublicKey const& public_key) { return public_key.scalar_size(); },+ [](::Crypto::PK::ECPrivateKey const& private_key) { return private_key.scalar_size(); },+ [](auto const&) -> size_t { VERIFY_NOT_REACHED(); });+ *valid = scalar_size == ec_scalar_size(curve);return true;}@@ -625,32 +607,30 @@ bool crypto_ec_export_uncompressed(KeyHandle const* key, void* state, ReceiveEncreturn receive_byte_result(result, state, receive);}-bool crypto_ec_export_public_coordinates(EcCurve curve_id, KeyHandle const* key, void* x, void* y, ReceiveEncodedBytes receive)+bool crypto_ec_export_public_coordinates(KeyHandle const* key, void* x, void* y, ReceiveEncodedBytes receive){- auto result = key->visit(- [&](::Crypto::PK::ECPublicKey const& public_key) -> ErrorOr<void> {- auto x_bytes = TRY(public_key.x_bytes());- receive(x, x_bytes);- auto y_bytes = TRY(public_key.y_bytes());- receive(y, y_bytes);- return {};- },- [&](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<void> {- auto public_key = TRY(ec_curve(curve_id).generate_public_key(private_key.d()));- auto x_bytes = TRY(public_key.x_bytes());- auto y_bytes = TRY(public_key.y_bytes());- receive(x, x_bytes);- receive(y, y_bytes);- return {};- },- [](auto const&) -> ErrorOr<void> { VERIFY_NOT_REACHED(); });+ auto result = [&]() -> ErrorOr<void> {+ auto public_key = TRY(key->visit(+ [](::Crypto::PK::ECPublicKey const& public_key) -> ErrorOr<::Crypto::PK::ECPublicKey> { return public_key; },+ [](::Crypto::PK::ECPrivateKey const& private_key) { return private_key.derive_public_key(); },+ [](auto const&) -> ErrorOr<::Crypto::PK::ECPublicKey> { VERIFY_NOT_REACHED(); }));+ auto x_bytes = TRY(public_key.x_bytes());+ auto y_bytes = TRY(public_key.y_bytes());+ receive(x, x_bytes);+ receive(y, y_bytes);+ return {};+ }();return !result.is_error();}bool crypto_ec_export_private_scalar(KeyHandle const* key, void* state, ReceiveEncodedBytes receive){auto result = key->get<::Crypto::PK::ECPrivateKey>().d_bytes();- return receive_byte_result(result, state, receive);+ if (result.is_error())+ return false;+ receive(state, result.value());+ secure_zero(result.value().data(), result.value().size());+ return true;}enum class OkpCurve : u8 {@@ -1074,30 +1054,18 @@ bool crypto_kmac_sign(::Crypto::Authentication::KMACKind kind, ReadonlyBytes keyreturn receive_byte_result(result, state, receive);}-extern "C" KeyHandle* crypto_public_key_for_private_key(KeyHandle const*, FlatPtr name, FlatPtr named_curve);+extern "C" KeyHandle* crypto_public_key_for_private_key(KeyHandle const*, FlatPtr name);-KeyHandle* crypto_public_key_for_private_key(KeyHandle const* key, FlatPtr raw_name, FlatPtr raw_named_curve)+KeyHandle* crypto_public_key_for_private_key(KeyHandle const* key, FlatPtr raw_name){auto result = key->visit([](::Crypto::PK::RSAPrivateKey const& private_key) -> ErrorOr<KeyHandle> {return ::Crypto::PK::RSAPublicKey { private_key.modulus(), private_key.public_exponent() };},- [&](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<KeyHandle> {+ [](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<KeyHandle> {if (private_key.public_key().has_value())return *private_key.public_key();-- VERIFY(raw_named_curve);- auto named_curve = Utf16String::from_raw(raw_named_curve);- auto point = TRY([&] -> ErrorOr<::Crypto::Curves::SECPxxxr1Point> {- if (named_curve == "P-256"_utf16)- return ::Crypto::Curves::SECP256r1 {}.generate_public_key(private_key.d());- if (named_curve == "P-384"_utf16)- return ::Crypto::Curves::SECP384r1 {}.generate_public_key(private_key.d());- if (named_curve == "P-521"_utf16)- return ::Crypto::Curves::SECP521r1 {}.generate_public_key(private_key.d());- return Error::from_string_literal("Unsupported named curve");- }());- return ::Crypto::PK::ECPublicKey { move(point) };+ return TRY(private_key.derive_public_key());},[](::Crypto::PK::MLDSAPrivateKey const& private_key) -> ErrorOr<KeyHandle> {return ::Crypto::PK::MLDSAPublicKey { private_key.public_key() };diff --git a/Libraries/LibDNS/Validator.cpp b/Libraries/LibDNS/Validator.cppindex ae84f9bf2ba..773b2c0bda7 100644--- a/Libraries/LibDNS/Validator.cpp+++ b/Libraries/LibDNS/Validator.cpp@@ -10,8 +10,8 @@#include <AK/NeverDestroyed.h>#include <AK/QuickSort.h>#include <LibCrypto/Curves/EdwardsCurve.h>-#include <LibCrypto/Curves/SECPxxxr1.h>#include <LibCrypto/Hash/Hash.h>+#include <LibCrypto/PK/EC.h>#include <LibCrypto/PK/RSA.h>#include <LibDNS/Validator.h>@@ -139,24 +139,9 @@ static ErrorOr<bool> verify_signature(Records::DNSKEY const& key, ReadonlyBytessize_t scalar_size = is_p256 ? 32 : 48;if (key.public_key.size() != scalar_size * 2 || signature.size() != scalar_size * 2)return false;- Crypto::Curves::SECPxxxr1Point point {- Crypto::UnsignedBigInteger::import_data(key.public_key.bytes().slice(0, scalar_size)),- Crypto::UnsignedBigInteger::import_data(key.public_key.bytes().slice(scalar_size, scalar_size)),- scalar_size,- };- Crypto::Curves::SECPxxxr1Signature ecdsa_signature {- Crypto::UnsignedBigInteger::import_data(signature.slice(0, scalar_size)),- Crypto::UnsignedBigInteger::import_data(signature.slice(scalar_size, scalar_size)),- scalar_size,- };- if (is_p256) {- auto digest = Crypto::Hash::digest(Crypto::Hash::HashKind::SHA256, signed_data);- Crypto::Curves::SECP256r1 curve;- return curve.verify(digest.bytes(), point, ecdsa_signature);- }- auto digest = Crypto::Hash::digest(Crypto::Hash::HashKind::SHA384, signed_data);- Crypto::Curves::SECP384r1 curve;- return curve.verify(digest.bytes(), point, ecdsa_signature);+ auto public_key = TRY(Crypto::PK::ECPublicKey::from_coordinates(key.public_key.bytes().slice(0, scalar_size), key.public_key.bytes().slice(scalar_size, scalar_size)));+ auto digest = Crypto::Hash::digest(is_p256 ? Crypto::Hash::HashKind::SHA256 : Crypto::Hash::HashKind::SHA384, signed_data);+ return Crypto::PK::ecdsa_verify(public_key, digest.bytes(), signature.slice(0, scalar_size), signature.slice(scalar_size, scalar_size));}case Algorithm::ED25519: {Crypto::Curves::Ed25519 ed25519;diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rsindex a186ff002c4..2c70929e7c6 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs@@ -14,8 +14,8 @@ use std::rc::Rc;use ak::{Utf16String, Utf16StringUnits};use libcrypto_rust::{- Argon2Inputs, Argon2Type, Asn1Structure, Asn1Value, BackendError, CShakeKind, EcCurve, EcError, KeyHandle, KeyInfo,- KeyPair, KmacKind, MlDsaSize, MlKemSize, OkpCurve, RsaJwkInteger, ShaHashKind,+ Argon2Inputs, Argon2Type, Asn1Structure, Asn1Value, BackendError, CShakeKind, EcCurve, KeyHandle, KeyInfo, KeyPair,+ KmacKind, MlDsaSize, MlKemSize, OkpCurve, RsaJwkInteger, ShaHashKind,};use libjs_rust::api::{ErrorKind, ErrorType, Gc, Object, PropertyKey, Realm, Trace, TypedArrayBase, TypedArrayKind, Value, Vm,@@ -7841,11 +7841,11 @@ const SECP256R1_OID: [u32; 7] = [1, 2, 840, 10045, 3, 1, 7];const SECP384R1_OID: [u32; 5] = [1, 3, 132, 0, 34];const SECP521R1_OID: [u32; 5] = [1, 3, 132, 0, 35];-fn ec_key_from_coordinates(vm: &Vm, x: &Bytes, y: &Bytes, coord_size: usize, d: Option<&Bytes>) -> Ref<CryptoKey> {- CryptoKey::create(- vm,- libcrypto_rust::ec_key_from_coordinates(x.as_slice(), y.as_slice(), coord_size, d.map(Bytes::as_slice)),- )+fn ec_key_from_coordinates(vm: &Vm, x: &Bytes, y: &Bytes, d: Option<&Bytes>) -> WebIdlResult<Ref<CryptoKey>> {+ let Some(key) = libcrypto_rust::ec_key_from_coordinates(x.as_slice(), y.as_slice(), d.map(Bytes::as_slice)) else {+ return Err(dom_error("DataError", b"Invalid key"));+ };+ Ok(CryptoKey::create(vm, key))}fn ec_parse_raw_public_key(vm: &Vm, curve: EcCurve, key_bytes: &Bytes) -> WebIdlResult<Ref<CryptoKey>> {@@ -7874,8 +7874,8 @@ fn ec_export_uncompressed(key: Ref<CryptoKey>) -> Result<Bytes, BackendError> {libcrypto_rust::ec_export_uncompressed(key.handle()).map(Bytes::new)}-fn ec_export_public_coordinates(curve: EcCurve, key: Ref<CryptoKey>) -> Result<(Bytes, Bytes), BackendError> {- let (x, y) = libcrypto_rust::ec_export_public_coordinates(curve, key.handle())?;+fn ec_export_public_coordinates(key: Ref<CryptoKey>) -> Result<(Bytes, Bytes), BackendError> {+ let (x, y) = libcrypto_rust::ec_export_public_coordinates(key.handle())?;Ok((Bytes::new(x), Bytes::new(y)))}@@ -8082,16 +8082,10 @@ impl AlgorithmMethods for Ecdsa {// using params as the EC domain parameters, and with d as the private key.// 2. Let r and s be the pair of integers resulting from performing the ECDSA signing process.let signature = libcrypto_rust::ec_sign(curve, d, m.as_slice());- if let Err(EcError::Operation(message)) = signature {- return Err(Exception::Dom("OperationError", message));- }- if matches!(signature, Err(EcError::CoordinateEncoding)) {- return cx- .vm()- .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])- .map_err(Into::into);- }- let (r_bytes, s_bytes) = signature.expect("LibCrypto returns the signature");+ let (r_bytes, s_bytes) = match signature {+ Ok(signature) => signature,+ Err(message) => return Err(Exception::Dom("OperationError", message)),+ };// 3. Let result be an empty byte sequence.let mut result_bytes = Vec::new();@@ -8612,7 +8606,7 @@ impl AlgorithmMethods for Ecdsa {// 2. Let key be a new CryptoKey object that represents the Elliptic Curve private key identified// by interpreting jwk according to Section 6.2.2 of JSON Web Algorithms [JWA].- key = ec_key_from_coordinates(cx.vm(), &x_bytes, &y_bytes, coord_size, Some(&d_bytes));+ key = ec_key_from_coordinates(cx.vm(), &x_bytes, &y_bytes, Some(&d_bytes))?;// 3. Set the [[type]] internal slot of Key to "private".key.set_type(KeyType::Private);@@ -8621,7 +8615,7 @@ impl AlgorithmMethods for Ecdsa {// 1. If jwk does not meet the requirements of Section 6.2.1 of JSON Web Algorithms [JWA], then throw a DataError.// 2. Let key be a new CryptoKey object that represents the Elliptic Curve public key identified by interpreting// jwk according to Section 6.2.1 of JSON Web Algorithms [JWA].- key = ec_key_from_coordinates(cx.vm(), &x_bytes, &y_bytes, coord_size, None);+ key = ec_key_from_coordinates(cx.vm(), &x_bytes, &y_bytes, None)?;// 3. Set the [[type]] internal slot of Key to "public".key.set_type(KeyType::Public);@@ -8852,7 +8846,7 @@ impl AlgorithmMethods for Ecdsa {let InternalAlgorithmData::Ec { named_curve, .. } = &*algorithm else {unreachable!("the key has an EC algorithm")};- if let Some(curve) = ec_curve_from_name(named_curve) {+ if ec_curve_from_name(named_curve).is_some() {// 1. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256":if *named_curve == Utf16String::from_ascii(b"P-256") {// Set the crv attribute of jwk to "P-256"@@ -8873,7 +8867,7 @@ impl AlgorithmMethods for Ecdsa {// 3. Set the y attribute of jwk according to the definition in Section 6.2.1.3 of JSON Web Algorithms [JWA].// 2. Set the x attribute of jwk according to the definition in Section 6.2.1.2 of JSON Web Algorithms [JWA].// 3. Set the y attribute of jwk according to the definition in Section 6.2.1.3 of JSON Web Algorithms [JWA].- let (x_bytes, y_bytes) = ec_export_public_coordinates(curve, key)+ let (x_bytes, y_bytes) = ec_export_public_coordinates(key).map_err(|_| dom_error("DataError", b"Failed to encode public key"))?;jwk.x = Some(base64_url_bytes_encode(x_bytes.as_slice()));jwk.y = Some(base64_url_bytes_encode(y_bytes.as_slice()));@@ -9179,24 +9173,17 @@ impl AlgorithmMethods for Ecdh {// by the [[handle]] internal slot of publicKey as the EC public key.// 2. Let secret be a byte sequence containing the result of applying the field element to octet string// conversion defined in Section 6.2 of [RFC6090] to the output of the ECDH primitive.- // NOTE: Remove the prefix from the uncompressed pointlet secret_data = libcrypto_rust::ec_compute_coordinate(curve, key.handle(), public_key.handle());- if let Err(EcError::Operation(detail)) = secret_data {- return Err(Exception::Dom(- "OperationError",- libjs_rust::api::utf16_formatted("Failed to compute secret: {}", &[&detail]),- ));- }- if matches!(secret_data, Err(EcError::CoordinateEncoding)) {- return Err(dom_error("OperationError", b"Failed to convert secret"));- }- let secret_data = secret_data.expect("LibCrypto returns the uncompressed point");- assert_eq!(secret_data[0], 0x04);-- // NOTE: Use the x-coordinate as shared secret. RFC6090 section 4.2:- // In the ECDH key exchange protocol, after the element g^(j*k) has been- // computed, the x-coordinate of that value can be used as the shared secret.- secret = copy_bytes(cx.vm(), &secret_data[1..=secret_data.len() / 2])?;+ let secret_data = match secret_data {+ Ok(secret_data) => secret_data,+ Err(detail) => {+ return Err(Exception::Dom(+ "OperationError",+ libjs_rust::api::utf16_formatted("Failed to compute secret: {}", &[&detail]),+ ));+ }+ };+ secret = copy_bytes(cx.vm(), &secret_data)?;} else {// If the namedCurve property of the [[algorithm]] internal slot of key is a value specified// in an applicable specification that specifies the use of that value with ECDH:@@ -9587,7 +9574,7 @@ impl AlgorithmMethods for Ecdh {// 2. Let key be a new CryptoKey object that represents the Elliptic Curve private key identified// by interpreting jwk according to Section 6.2.2 of JSON Web Algorithms [JWA].- key = ec_key_from_coordinates(cx.vm(), &x_bytes, &y_bytes, coord_size, Some(&d_bytes));+ key = ec_key_from_coordinates(cx.vm(), &x_bytes, &y_bytes, Some(&d_bytes))?;// 3. Set the [[type]] internal slot of Key to "private".key.set_type(KeyType::Private);@@ -9596,7 +9583,7 @@ impl AlgorithmMethods for Ecdh {// 1. If jwk does not meet the requirements of Section 6.2.1 of JSON Web Algorithms [JWA], then throw a DataError.// 2. Let key be a new CryptoKey object that represents the Elliptic Curve public key identified by interpreting// jwk according to Section 6.2.1 of JSON Web Algorithms [JWA].- key = ec_key_from_coordinates(cx.vm(), &x_bytes, &y_bytes, coord_size, None);+ key = ec_key_from_coordinates(cx.vm(), &x_bytes, &y_bytes, None)?;// 3. Set the [[type]] internal slot of Key to "public".key.set_type(KeyType::Public);@@ -9821,7 +9808,7 @@ impl AlgorithmMethods for Ecdh {let InternalAlgorithmData::Ec { named_curve, .. } = &*algorithm else {unreachable!("the key has an EC algorithm")};- if let Some(curve) = ec_curve_from_name(named_curve) {+ if ec_curve_from_name(named_curve).is_some() {// 1. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256":if *named_curve == Utf16String::from_ascii(b"P-256") {// Set the crv attribute of jwk to "P-256"@@ -9842,7 +9829,7 @@ impl AlgorithmMethods for Ecdh {// 3. Set the y attribute of jwk according to the definition in Section 6.2.1.3 of JSON Web Algorithms [JWA].// 2. Set the x attribute of jwk according to the definition in Section 6.2.1.2 of JSON Web Algorithms [JWA].// 3. Set the y attribute of jwk according to the definition in Section 6.2.1.3 of JSON Web Algorithms [JWA].- let (x_bytes, y_bytes) = ec_export_public_coordinates(curve, key)+ let (x_bytes, y_bytes) = ec_export_public_coordinates(key).map_err(|_| dom_error("DataError", b"Failed to encode public key"))?;jwk.x = Some(base64_url_bytes_encode(x_bytes.as_slice()));jwk.y = Some(base64_url_bytes_encode(y_bytes.as_slice()));@@ -13926,12 +13913,5 @@ impl AlgorithmMethods for MlKem {pub(crate) fn public_key_for_private_key(vm: &Vm, key: Ref<CryptoKey>) -> Option<Ref<CryptoKey>> {let name = key.algorithm_name();- let algorithm = key.internal_algorithm();- let named_curve = if let InternalAlgorithmData::Ec { named_curve, .. } = &*algorithm {- Some(named_curve)- } else {- None- };- libcrypto_rust::public_key_for_private_key(key.handle(), &name, named_curve)- .map(|handle| CryptoKey::create(vm, handle))+ libcrypto_rust::public_key_for_private_key(key.handle(), &name).map(|handle| CryptoKey::create(vm, handle))}diff --git a/Tests/LibCrypto/TestCurves.cpp b/Tests/LibCrypto/TestCurves.cppindex 2b32f15539e..65288cd2a1c 100644--- a/Tests/LibCrypto/TestCurves.cpp+++ b/Tests/LibCrypto/TestCurves.cpp@@ -6,21 +6,23 @@#include <AK/ByteBuffer.h>#include <LibCrypto/Curves/EdwardsCurve.h>-#include <LibCrypto/Curves/SECPxxxr1.h>+#include <LibCrypto/PK/EC.h>#include <LibTest/TestCase.h>TEST_CASE(test_secp256r1_rejects_wrong_signature_width){- Crypto::Curves::SECP256r1 curve;Array<u8, 32> hash {};- Crypto::UnsignedBigInteger const private_key { 1 };+ Array<u8, 32> d {};+ d[31] = 1;- auto public_key = TRY_OR_FAIL(curve.generate_public_key(private_key));- auto signature = TRY_OR_FAIL(curve.sign(hash, private_key));- EXPECT(TRY_OR_FAIL(curve.verify(hash, public_key, signature)));+ auto private_key = TRY_OR_FAIL(Crypto::PK::ECPrivateKey::from_scalar(d, {}, {}));+ auto public_key = TRY_OR_FAIL(private_key.derive_public_key());+ auto signature = TRY_OR_FAIL(Crypto::PK::ecdsa_sign(private_key, hash));+ EXPECT(TRY_OR_FAIL(Crypto::PK::ecdsa_verify(public_key, hash, signature.r, signature.s)));- ++signature.size;- EXPECT(!TRY_OR_FAIL(curve.verify(hash, public_key, signature)));+ auto wide_r = TRY_OR_FAIL(ByteBuffer::create_zeroed(1));+ TRY_OR_FAIL(wide_r.try_append(signature.r));+ EXPECT(!TRY_OR_FAIL(Crypto::PK::ecdsa_verify(public_key, hash, wide_r, signature.s)));}TEST_CASE(test_x25519)@@ -211,38 +213,44 @@ TEST_CASE(test_secp256r1)};// clang-format on- auto alice_private_key = Crypto::UnsignedBigInteger::import_data(alice_private_key_data);- auto alice_public_key = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_uncompressed({ alice_public_key_data, 65 }));- auto bob_private_key = Crypto::UnsignedBigInteger::import_data(bob_private_key_data);- auto bob_public_key = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_uncompressed({ bob_public_key_data, 65 }));- auto shared_secret = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_uncompressed({ shared_secret_data, 65 }));- auto private_key = Crypto::UnsignedBigInteger::import_data(private_key_data);- auto expected_public_key = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_uncompressed({ expected_public_key_data, 65 }));+ auto alice_private_key = TRY_OR_FAIL(Crypto::PK::ECPrivateKey::from_scalar(alice_private_key_data, {}, {}));+ auto alice_public_key = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(alice_public_key_data));+ auto bob_private_key = TRY_OR_FAIL(Crypto::PK::ECPrivateKey::from_scalar(bob_private_key_data, {}, {}));+ auto bob_public_key = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(bob_public_key_data));+ auto private_key = TRY_OR_FAIL(Crypto::PK::ECPrivateKey::from_scalar(private_key_data, {}, {}));- Crypto::Curves::SECP256r1 curve;-- auto generated_alice_public = MUST(curve.generate_public_key(alice_private_key));- EXPECT_EQ(alice_public_key.x, generated_alice_public.x);- EXPECT_EQ(alice_public_key.y, generated_alice_public.y);-- auto generated_bob_public = MUST(curve.generate_public_key(bob_private_key));- EXPECT_EQ(bob_public_key.x, generated_bob_public.x);- EXPECT_EQ(bob_public_key.y, generated_bob_public.y);-- auto shared_alice = MUST(curve.compute_coordinate(alice_private_key, bob_public_key));- EXPECT_EQ(shared_alice.x, shared_secret.x);- EXPECT_EQ(shared_alice.y, shared_secret.y);+ auto expect_public_key = [](Crypto::PK::ECPrivateKey const& private_key, ReadonlyBytes expected) {+ auto public_key = TRY_OR_FAIL(TRY_OR_FAIL(private_key.derive_public_key()).to_uncompressed());+ EXPECT_EQ(public_key.bytes(), expected);+ };+ expect_public_key(alice_private_key, alice_public_key_data);+ expect_public_key(bob_private_key, bob_public_key_data);+ expect_public_key(private_key, expected_public_key_data);++ // ECDH gives the x-coordinate of the shared point.+ auto shared_secret_x = ReadonlyBytes { shared_secret_data }.slice(1, 32);+ auto shared_alice = TRY_OR_FAIL(Crypto::PK::ecdh_derive(alice_private_key, bob_public_key));+ EXPECT_EQ(shared_alice.bytes(), shared_secret_x);+ auto shared_bob = TRY_OR_FAIL(Crypto::PK::ecdh_derive(bob_private_key, alice_public_key));+ EXPECT_EQ(shared_bob.bytes(), shared_secret_x);+}- auto shared_bob = MUST(curve.compute_coordinate(bob_private_key, alice_public_key));- EXPECT_EQ(shared_bob.x, shared_secret.x);- EXPECT_EQ(shared_bob.y, shared_secret.y);+TEST_CASE(test_secp256r1_rejects_out_of_range_private_keys)+{+ Array<u8, 32> zero {};+ EXPECT(Crypto::PK::ECPrivateKey::from_scalar(zero, {}, {}).is_error());- EXPECT_EQ(shared_alice.x, shared_bob.x);- EXPECT_EQ(shared_alice.y, shared_bob.y);+ // n, the order of P-256's base point.+ u8 const order[32] {+ 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,+ 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51+ };+ EXPECT(Crypto::PK::ECPrivateKey::from_scalar(order, {}, {}).is_error());- auto generated_public = MUST(curve.generate_public_key(private_key));- EXPECT_EQ(expected_public_key.x, generated_public.x);- EXPECT_EQ(expected_public_key.y, generated_public.y);+ // A scalar that is not as wide as P-256's coordinates.+ Array<u8, 31> narrow {};+ narrow[30] = 1;+ EXPECT(Crypto::PK::ECPrivateKey::from_scalar(narrow, {}, {}).is_error());}// Test vectors from WebCryptoAPI WPT ec_importKey.https.any.js@@ -262,11 +270,10 @@ TEST_CASE(test_ec_compressed_point_p256)0x01, 0x85, 0x43, 0xBB, 0xA0, 0x0C, 0x92, 0x50, 0xDF, 0x92, 0x57, 0xC2, 0xAC, 0xAE, 0x5D, 0xD1,};- auto uncompressed = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_uncompressed({ raw_data, sizeof(raw_data) }));- auto compressed = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_compressed({ compressed_data, sizeof(compressed_data) }));+ auto uncompressed = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(raw_data));+ auto compressed = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(compressed_data));- EXPECT_EQ(uncompressed.x, compressed.x);- EXPECT_EQ(uncompressed.y, compressed.y);+ EXPECT_EQ(TRY_OR_FAIL(compressed.to_uncompressed()), TRY_OR_FAIL(uncompressed.to_uncompressed()));}TEST_CASE(test_ec_compressed_point_p384)@@ -288,11 +295,10 @@ TEST_CASE(test_ec_compressed_point_p384)0x5F, 0xBD, 0xEB, 0xD1, 0xD0, 0x8D, 0xD6, 0x9E, 0x2D, 0x7D, 0xC1, 0xDC, 0x21, 0x8C, 0xB4, 0x35,};- auto uncompressed = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_uncompressed({ raw_data, sizeof(raw_data) }));- auto compressed = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_compressed({ compressed_data, sizeof(compressed_data) }));+ auto uncompressed = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(raw_data));+ auto compressed = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(compressed_data));- EXPECT_EQ(uncompressed.x, compressed.x);- EXPECT_EQ(uncompressed.y, compressed.y);+ EXPECT_EQ(TRY_OR_FAIL(compressed.to_uncompressed()), TRY_OR_FAIL(uncompressed.to_uncompressed()));}TEST_CASE(test_ec_compressed_point_p521)@@ -320,9 +326,8 @@ TEST_CASE(test_ec_compressed_point_p521)0x75, 0x3F,};- auto uncompressed = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_uncompressed({ raw_data, sizeof(raw_data) }));- auto compressed = TRY_OR_FAIL(Crypto::Curves::SECPxxxr1Point::from_compressed({ compressed_data, sizeof(compressed_data) }));+ auto uncompressed = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(raw_data));+ auto compressed = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(compressed_data));- EXPECT_EQ(uncompressed.x, compressed.x);- EXPECT_EQ(uncompressed.y, compressed.y);+ EXPECT_EQ(TRY_OR_FAIL(compressed.to_uncompressed()), TRY_OR_FAIL(uncompressed.to_uncompressed()));}diff --git a/Tests/LibTLS/TestTLSCertificateParser.cpp b/Tests/LibTLS/TestTLSCertificateParser.cppindex 5da16575581..ff0a28ed215 100644--- a/Tests/LibTLS/TestTLSCertificateParser.cpp+++ b/Tests/LibTLS/TestTLSCertificateParser.cpp@@ -5,6 +5,7 @@*/#include <AK/Base64.h>+#include <LibCrypto/ASN1/Constants.h>#include <LibCrypto/Certificate/Certificate.h>#include <LibTest/TestCase.h>diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.hindex 223f99bee3b..2bf4ee0788a 100644--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h@@ -640,12 +640,23 @@ inline Vector<u8> ec_coordinate(u8 fill)return bytes;}+// The base point of P-256, which EC key handles must hold a point on.+inline Vector<u8> p256_base_point_x()+{+ return { 0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96 };+}++inline Vector<u8> p256_base_point_y()+{+ return { 0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5 };+}+inline Vector<CryptoAlgorithmGolden> crypto_algorithm_goldens(){using Web::Crypto::KeyAlgorithmTag;auto secret_handle = handle_byte_buffer("0123456789abcdef"sv.bytes());- auto x = ec_coordinate(0x11);- auto y = ec_coordinate(0x22);+ auto x = p256_base_point_x();+ auto y = p256_base_point_y();Array<u8, 3> exponent { 0x01, 0x00, 0x01 }; // 65537Array<u8, 4> modulus { 0xC0, 0x00, 0x00, 0x01 };@@ -666,8 +677,8 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()auto buffer = "0123456789abcdef"sv.bytes();Array<u8, 3> exponent { 0x01, 0x00, 0x01 };Array<u8, 4> modulus { 0xC0, 0x00, 0x00, 0x01 };- auto x = ec_coordinate(0x11);- auto y = ec_coordinate(0x22);+ auto x = p256_base_point_x();+ auto y = p256_base_point_y();auto d = ec_coordinate(0x33);auto seed = "seedseedseedseed"sv.bytes();auto pub = "publicpublicpubl"sv.bytes();diff --git a/Tests/LibWeb/TestStructuredSerializeDurability.cpp b/Tests/LibWeb/TestStructuredSerializeDurability.cppindex 86d9a3ec87d..f1555bb9c7d 100644--- a/Tests/LibWeb/TestStructuredSerializeDurability.cpp+++ b/Tests/LibWeb/TestStructuredSerializeDurability.cpp@@ -33,6 +33,7 @@#include <LibWeb/HTML/ImageBitmap.h>#include <LibWeb/HTML/ImageData.h>#include <LibWeb/WebIDL/DOMException.h>+#include <LibWeb/WebIDL/ExceptionOrUtils.h>#include <LibWeb/WebIDL/QuotaExceededError.h>using Web::Crypto::HandleTag;@@ -600,6 +601,19 @@ TEST_CASE(crypto_key_algorithm_variants_decode_from_frozen_bytes)}}+TEST_CASE(crypto_key_with_an_invalid_ec_point_is_a_data_clone_error)+{+ Array<u8, 32> zero {};+ auto record = crypto_key_full_record("public"sv, "verify"sv, alg_ec_key_algorithm("ECDSA"sv, "P-256"sv), handle_ec_public_key(zero, zero));+ auto& realm = principal_test_realm();+ auto result = Web::WebIDL::throw_dom_exception_if_needed(realm.vm(), realm, [&] {+ return principal_storage_deserialize(record);+ });+ EXPECT(result.is_error());+ if (result.is_error())+ EXPECT_EQ(unwrap_wrappable<Web::WebIDL::DOMException>(result.error_value()).name(), "DataCloneError"_utf16);+}+TEST_CASE(crypto_key_handle_variants_decode_from_frozen_bytes){for (auto const& golden : crypto_handle_goldens()) {diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-ec-bad-import-key.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-ec-bad-import-key.txtindex 24089564c2a..5d0c6646885 100644--- a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-ec-bad-import-key.txt+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-ec-bad-import-key.txt@@ -1,30 +1,30 @@ECDSA P-256 PUB - jwk OK: DataError: Invalid key-ECDSA P-256 PUB - spki OK: DataError: Invalid key+ECDSA P-256 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public keyECDSA P-256 PRIV - jwk OK: DataError: Invalid key-ECDSA P-256 PRIV - pkcs8 OK: DataError: Invalid key-ECDSA P-256 PRIV - pkcs8 OK: DataError: Invalid key+ECDSA P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key+ECDSA P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public keyECDSA P-384 PUB - jwk OK: DataError: Invalid key-ECDSA P-384 PUB - spki OK: DataError: Invalid key+ECDSA P-384 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public keyECDSA P-384 PRIV - jwk OK: DataError: Invalid key-ECDSA P-384 PRIV - pkcs8 OK: DataError: Invalid key-ECDSA P-384 PRIV - pkcs8 OK: DataError: Invalid key+ECDSA P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key+ECDSA P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public keyECDSA P-521 PUB - jwk OK: DataError: Invalid key-ECDSA P-521 PUB - spki OK: DataError: Invalid key+ECDSA P-521 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public keyECDSA P-521 PRIV - jwk OK: DataError: Invalid key-ECDSA P-521 PRIV - pkcs8 OK: DataError: Invalid key-ECDSA P-521 PRIV - pkcs8 OK: DataError: Invalid key+ECDSA P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key+ECDSA P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public keyECDH P-256 PUB - jwk OK: DataError: Invalid key-ECDH P-256 PUB - spki OK: DataError: Invalid key+ECDH P-256 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public keyECDH P-256 PRIV - jwk OK: DataError: Invalid key-ECDH P-256 PRIV - pkcs8 OK: DataError: Invalid key-ECDH P-256 PRIV - pkcs8 OK: DataError: Invalid key+ECDH P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key+ECDH P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public keyECDH P-384 PUB - jwk OK: DataError: Invalid key-ECDH P-384 PUB - spki OK: DataError: Invalid key+ECDH P-384 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public keyECDH P-384 PRIV - jwk OK: DataError: Invalid key-ECDH P-384 PRIV - pkcs8 OK: DataError: Invalid key-ECDH P-384 PRIV - pkcs8 OK: DataError: Invalid key+ECDH P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key+ECDH P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public keyECDH P-521 PUB - jwk OK: DataError: Invalid key-ECDH P-521 PUB - spki OK: DataError: Invalid key+ECDH P-521 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public keyECDH P-521 PRIV - jwk OK: DataError: Invalid key-ECDH P-521 PRIV - pkcs8 OK: DataError: Invalid key-ECDH P-521 PRIV - pkcs8 OK: DataError: Invalid key+ECDH P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key+ECDH P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public keydiff --git a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-algorithm-3.bin b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-algorithm-3.binindex aa7ddfa7ec8..1c818651cd7 100644Binary files a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-algorithm-3.bin and b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-algorithm-3.bin differdiff --git a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-3.bin b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-3.binindex aa7ddfa7ec8..1c818651cd7 100644Binary files a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-3.bin and b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-3.bin differ