From c62e00a9c3aed3a65c48692b2e963f2f4c92fc0a Mon Sep 17 00:00:00 2001 From: devgianlu Date: Mon, 2 Dec 2024 19:42:51 +0100 Subject: [PATCH] LibCrypto+LibWeb: Implement ECDSA.sign Gained ~20 tests, failing only on P-521. --- Libraries/LibCrypto/Curves/SECPxxxr1.h | 63 +++++++++++ Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp | 100 ++++++++++++++---- .../sign_verify/ecdsa.https.any.txt | 38 +++---- 3 files changed, 159 insertions(+), 42 deletions(-) diff --git a/Libraries/LibCrypto/Curves/SECPxxxr1.h b/Libraries/LibCrypto/Curves/SECPxxxr1.h index 809892202ec12..47dad30d5705b 100644 --- a/Libraries/LibCrypto/Curves/SECPxxxr1.h +++ b/Libraries/LibCrypto/Curves/SECPxxxr1.h @@ -315,6 +315,69 @@ class SECPxxxr1 : public EllipticCurve { SECPxxxr1Signature { r_bigint, s_bigint }); } + ErrorOr sign_scalar(ReadonlyBytes hash, UnsignedBigInteger private_key) + { + auto d = unsigned_big_integer_to_storage_type(private_key); + + auto k_int = TRY(generate_private_key_scalar()); + auto k = unsigned_big_integer_to_storage_type(k_int); + auto k_mo = to_montgomery_order(k); + + auto kG = TRY(generate_public_key_internal(k)); + auto r = kG.x; + + if (r.is_zero_constant_time()) { + // Retry with a new k + return sign_scalar(hash, private_key); + } + + // Compute z from the hash + StorageType z = 0u; + for (size_t i = 0; i < KEY_BYTE_SIZE && i < hash.size(); i++) { + z <<= 8; + z |= hash[i]; + } + + // Compute s = k^-1 * (z + r * d) mod n + auto r_mo = to_montgomery_order(r); + auto z_mo = to_montgomery_order(z); + auto d_mo = to_montgomery_order(d); + + // r * d mod n + auto rd_mo = modular_multiply_order(r_mo, d_mo); + + // z + (r * d) mod n + auto z_plus_rd_mo = modular_add_order(z_mo, rd_mo); + + // k^-1 mod n + auto k_inv_mo = modular_inverse_order(k_mo); + + // s = k^-1 * (z + r * d) mod n + auto s_mo = modular_multiply_order(z_plus_rd_mo, k_inv_mo); + auto s = from_montgomery_order(s_mo); + + if (s.is_zero_constant_time()) { + // Retry with a new k + return sign_scalar(hash, private_key); + } + + return SECPxxxr1Signature { storage_type_to_unsigned_big_integer(r), storage_type_to_unsigned_big_integer(s) }; + } + + ErrorOr sign(ReadonlyBytes hash, ReadonlyBytes private_key_bytes) + { + auto signature = TRY(sign_scalar(hash, UnsignedBigInteger::import_data(private_key_bytes.data(), private_key_bytes.size()))); + + Crypto::ASN1::Encoder asn1_encoder; + TRY(asn1_encoder.write_constructed(ASN1::Class::Universal, ASN1::Kind::Sequence, [&]() -> ErrorOr { + TRY(asn1_encoder.write(signature.r)); + TRY(asn1_encoder.write(signature.s)); + return {}; + })); + + return asn1_encoder.finish(); + } + private: StorageType unsigned_big_integer_to_storage_type(UnsignedBigInteger big) { diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp index 150bc8136b927..0d0bd41f49ace 100644 --- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp +++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp @@ -2359,35 +2359,93 @@ WebIDL::ExceptionOr> ECDSA::sign(AlgorithmParams const& auto& vm = realm.vm(); auto const& normalized_algorithm = static_cast(params); - (void)vm; - (void)message; - // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError. if (key->type() != Bindings::KeyType::Private) return WebIDL::InvalidAccessError::create(realm, "Key is not a private key"_string); // 2. Let hashAlgorithm be the hash member of normalizedAlgorithm. - [[maybe_unused]] auto const& hash_algorithm = normalized_algorithm.hash; + auto const& hash_algorithm = TRY(normalized_algorithm.hash.name(vm)); + + // 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message. + ::Crypto::Hash::HashKind hash_kind; + if (hash_algorithm == "SHA-1") { + hash_kind = ::Crypto::Hash::HashKind::SHA1; + } else if (hash_algorithm == "SHA-256") { + hash_kind = ::Crypto::Hash::HashKind::SHA256; + } else if (hash_algorithm == "SHA-384") { + hash_kind = ::Crypto::Hash::HashKind::SHA384; + } else if (hash_algorithm == "SHA-512") { + hash_kind = ::Crypto::Hash::HashKind::SHA512; + } else { + return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", hash_algorithm))); + } + ::Crypto::Hash::Manager hash { hash_kind }; + hash.update(message); + auto digest = hash.digest(); + + auto M = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(digest.immutable_data(), hash.digest_size())); + + // 4. Let d be the ECDSA private key associated with key. + auto d = key->handle().get<::Crypto::PK::ECPrivateKey<>>(); - // NOTE: We dont have sign() on the SECPxxxr1 curves, so we can't implement this yet - // FIXME: 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message. - // FIXME: 4. Let d be the ECDSA private key associated with key. // FIXME: 5. Let params be the EC domain parameters associated with key. - // FIXME: 6. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521": - // FIXME: 1. Perform the ECDSA signing process, as specified in [RFC6090], Section 5.4, with M as the message, using params as the EC domain parameters, and with d as the private key. - // FIXME: 2. Let r and s be the pair of integers resulting from performing the ECDSA signing process. - // FIXME: 3. Let result be an empty byte sequence. - // FIXME: 4. Let n be the smallest integer such that n * 8 is greater than the logarithm to base 2 of the order of the base point of the elliptic curve identified by params. - // FIXME: 5. Convert r to an octet string of length n and append this sequence of bytes to result. - // FIXME: 6. Convert s to an octet string of length n and append this sequence of bytes to result. + auto const& internal_algorithm = static_cast(*key->algorithm()); + auto const& named_curve = internal_algorithm.named_curve(); + + ByteBuffer result; - // FIXME: Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification: - // FIXME: Perform the ECDSA signature steps specified in that specification, passing in M, params and d and resulting in result. + // 6. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521": + if (named_curve.is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) { + size_t coord_size; + Variant curve; + if (named_curve == "P-256") { + coord_size = 32; + curve = ::Crypto::Curves::SECP256r1 {}; + } else if (named_curve == "P-384") { + coord_size = 48; + curve = ::Crypto::Curves::SECP384r1 {}; + } else if (named_curve == "P-521") { + // FIXME: Support P-521 + coord_size = 66; + return WebIDL::NotSupportedError::create(m_realm, "'P-521' is not supported yet"_string); + } else { + VERIFY_NOT_REACHED(); + } + + // 1. Perform the ECDSA signing process, as specified in [RFC6090], Section 5.4, with M as the message, + // 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. + auto maybe_signature = curve.visit( + [](Empty const&) -> ErrorOr<::Crypto::Curves::SECPxxxr1Signature> { return Error::from_string_literal("Failed to create valid crypto instance"); }, + [&](auto instance) { return instance.sign_scalar(M, d.d()); }); + + if (maybe_signature.is_error()) { + auto error_message = MUST(String::from_utf8(maybe_signature.error().string_literal())); + return WebIDL::OperationError::create(m_realm, error_message); + } + + auto signature = maybe_signature.release_value(); + + // 3. Let result be an empty byte sequence. + result = TRY_OR_THROW_OOM(vm, ByteBuffer::create_zeroed(coord_size * 2)); + + // 4. Let n be the smallest integer such that n * 8 is greater than the logarithm to base 2 of the order of the base point of the elliptic curve identified by params. + // 5. Convert r to an octet string of length n and append this sequence of bytes to result. + VERIFY(signature.r.byte_length() <= coord_size); + (void)signature.r.export_data(result.span()); + + // 6. Convert s to an octet string of length n and append this sequence of bytes to result. + VERIFY(signature.s.byte_length() <= coord_size); + (void)signature.s.export_data(result.span().slice(coord_size)); + } else { + // FIXME: Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification: + // FIXME: Perform the ECDSA signature steps specified in that specification, passing in M, params and d and resulting in result. + } // NOTE: The spec jumps to 9 here for some reason - // FIXME: 9. Return the result of creating an ArrayBuffer containing result. - return WebIDL::NotSupportedError::create(realm, "ECDSA signing is not supported yet"_string); + // 9. Return the result of creating an ArrayBuffer containing result. + return JS::ArrayBuffer::create(m_realm, result); } // https://w3c.github.io/webcrypto/#ecdsa-operations @@ -2420,11 +2478,7 @@ WebIDL::ExceptionOr ECDSA::verify(AlgorithmParams const& params, GC:: hash.update(message); auto digest = hash.digest(); - auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size()); - if (result_buffer.is_error()) - return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_string); - - auto M = result_buffer.release_value(); + auto M = TRY_OR_THROW_OOM(realm.vm(), ByteBuffer::copy(digest.immutable_data(), hash.digest_size())); // 4. Let Q be the ECDSA public key associated with key. auto Q = key->handle().get<::Crypto::PK::ECPublicKey<>>(); diff --git a/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/ecdsa.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/ecdsa.https.any.txt index eef80604f9111..2aeb94f213775 100644 --- a/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/ecdsa.https.any.txt +++ b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/ecdsa.https.any.txt @@ -6,42 +6,42 @@ Rerun Found 253 tests -176 Pass -77 Fail +193 Pass +60 Fail Details Result Test Name MessagePass setup Pass ECDSA P-256 with SHA-1 verification Pass ECDSA P-256 with SHA-256 verification -Fail ECDSA P-256 with SHA-384 verification -Fail ECDSA P-256 with SHA-512 verification +Pass ECDSA P-256 with SHA-384 verification +Pass ECDSA P-256 with SHA-512 verification Pass ECDSA P-384 with SHA-1 verification Pass ECDSA P-384 with SHA-256 verification Pass ECDSA P-384 with SHA-384 verification -Fail ECDSA P-384 with SHA-512 verification +Pass ECDSA P-384 with SHA-512 verification Fail ECDSA P-521 with SHA-1 verification Fail ECDSA P-521 with SHA-256 verification Fail ECDSA P-521 with SHA-384 verification Fail ECDSA P-521 with SHA-512 verification Pass ECDSA P-256 with SHA-1 verification with altered signature after call Pass ECDSA P-256 with SHA-256 verification with altered signature after call -Fail ECDSA P-256 with SHA-384 verification with altered signature after call -Fail ECDSA P-256 with SHA-512 verification with altered signature after call +Pass ECDSA P-256 with SHA-384 verification with altered signature after call +Pass ECDSA P-256 with SHA-512 verification with altered signature after call Pass ECDSA P-384 with SHA-1 verification with altered signature after call Pass ECDSA P-384 with SHA-256 verification with altered signature after call Pass ECDSA P-384 with SHA-384 verification with altered signature after call -Fail ECDSA P-384 with SHA-512 verification with altered signature after call +Pass ECDSA P-384 with SHA-512 verification with altered signature after call Fail ECDSA P-521 with SHA-1 verification with altered signature after call Fail ECDSA P-521 with SHA-256 verification with altered signature after call Fail ECDSA P-521 with SHA-384 verification with altered signature after call Fail ECDSA P-521 with SHA-512 verification with altered signature after call Pass ECDSA P-256 with SHA-1 with altered plaintext after call Pass ECDSA P-256 with SHA-256 with altered plaintext after call -Fail ECDSA P-256 with SHA-384 with altered plaintext after call -Fail ECDSA P-256 with SHA-512 with altered plaintext after call +Pass ECDSA P-256 with SHA-384 with altered plaintext after call +Pass ECDSA P-256 with SHA-512 with altered plaintext after call Pass ECDSA P-384 with SHA-1 with altered plaintext after call Pass ECDSA P-384 with SHA-256 with altered plaintext after call Pass ECDSA P-384 with SHA-384 with altered plaintext after call -Fail ECDSA P-384 with SHA-512 with altered plaintext after call +Pass ECDSA P-384 with SHA-512 with altered plaintext after call Fail ECDSA P-521 with SHA-1 with altered plaintext after call Fail ECDSA P-521 with SHA-256 with altered plaintext after call Fail ECDSA P-521 with SHA-384 with altered plaintext after call @@ -82,14 +82,14 @@ Pass ECDSA P-521 with SHA-1 no verify usage Pass ECDSA P-521 with SHA-256 no verify usage Pass ECDSA P-521 with SHA-384 no verify usage Pass ECDSA P-521 with SHA-512 no verify usage -Fail ECDSA P-256 with SHA-1 round trip -Fail ECDSA P-256 with SHA-256 round trip -Fail ECDSA P-256 with SHA-384 round trip -Fail ECDSA P-256 with SHA-512 round trip -Fail ECDSA P-384 with SHA-1 round trip -Fail ECDSA P-384 with SHA-256 round trip -Fail ECDSA P-384 with SHA-384 round trip -Fail ECDSA P-384 with SHA-512 round trip +Pass ECDSA P-256 with SHA-1 round trip +Pass ECDSA P-256 with SHA-256 round trip +Pass ECDSA P-256 with SHA-384 round trip +Pass ECDSA P-256 with SHA-512 round trip +Pass ECDSA P-384 with SHA-1 round trip +Pass ECDSA P-384 with SHA-256 round trip +Pass ECDSA P-384 with SHA-384 round trip +Pass ECDSA P-384 with SHA-512 round trip Fail ECDSA P-521 with SHA-1 round trip Fail ECDSA P-521 with SHA-256 round trip Fail ECDSA P-521 with SHA-384 round trip